Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: [closes #383] Random number generator seeding #397

Merged
merged 15 commits into from
Mar 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions api/post-day-results.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const {
getRoomData,
getRoomName,
} = require('../api-etc/utils')
const { random } = require('../src/common/utils')

const client = getRedisClient()

Expand All @@ -30,7 +31,7 @@ const applyPositionsToMarket = (valueAdjustments, positions) => {
(acc, itemName) => {
const itemPositionChange = positions[itemName]

const variance = Math.random() * 0.2
const variance = random() * 0.2

const MAX = 1.5
const MIN = 0.5
Expand All @@ -43,7 +44,7 @@ const applyPositionsToMarket = (valueAdjustments, positions) => {
// If item value is at a range boundary but was not changed in this
// operation, randomize it to introduce some variability to the market.
if (acc[itemName] === MAX || acc[itemName] === MIN) {
acc[itemName] = Math.random() + MIN
acc[itemName] = random() + MIN
}
}

Expand Down
63 changes: 57 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^12.0.0",
"@testing-library/user-event": "^13.2.1",
"@types/react": "^17.0.2",
"@typescript-eslint/eslint-plugin": "^2.23.0",
"@typescript-eslint/parser": "^2.23.0",
"bittorrent-tracker": "^9.19.0",
Expand Down Expand Up @@ -122,6 +123,7 @@
"react-use": "^17.4.0",
"react-zoom-pan-pinch": "^1.6.1",
"redis": "^3.0.2",
"seedrandom": "^3.0.5",
"shifty": "^2.15.2",
"source-map-explorer": "^2.3.1",
"stream": "npm:stream-browserify@^3.0.0",
Expand Down
40 changes: 40 additions & 0 deletions src/common/services/randomNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import seedrandom from 'seedrandom'
import window from 'global/window'

export class RandomNumberService {
/**
* @type {Function?}
*/
seededRandom = null

constructor() {
// The availability of window.location needs to be checked before accessing
// its .search property. This code runs in both a browser and Node.js
// context, and window.location is not defined in Node.js environments.
const initialSeed = new URLSearchParams(window.location?.search).get('seed')
jeremyckahn marked this conversation as resolved.
Show resolved Hide resolved

if (initialSeed) {
this.seedRandomNumber(initialSeed)
}
}

/**
* @param {string} seed
*/
seedRandomNumber(seed) {
this.seededRandom = seedrandom(seed)
}

/**
* @returns {number}
*/
generateRandomNumber() {
return this.seededRandom ? this.seededRandom() : Math.random()
}

unseedRandomNumber() {
this.seededRandom = null
}
}

export const randomNumberService = new RandomNumberService()
9 changes: 8 additions & 1 deletion src/common/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
/** @typedef {import("../index").farmhand.priceEvent} farmhand.priceEvent */
import { itemsMap } from '../data/maps'

import { randomNumberService } from './services/randomNumber'

export const random = () => {
return randomNumberService.generateRandomNumber()
}

/**
* @param {farmhand.priceEvent} [priceCrashes]
* @param {farmhand.priceEvent} [priceSurges]
Expand All @@ -13,7 +20,7 @@ export const generateValueAdjustments = (priceCrashes = {}, priceSurges = {}) =>
} else if (priceSurges[key]) {
acc[key] = 1.5
} else {
acc[key] = Math.random() + 0.5
acc[key] = random() + 0.5
}
}

Expand Down
5 changes: 3 additions & 2 deletions src/components/CowPen/CowPen.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import { pixel } from '../../img'
import { getCowDisplayName, getCowImage } from '../../utils'

import './CowPen.sass'
import { random } from '../../common/utils'

// Only moves the cow within the middle 80% of the pen
const randomPosition = () => 10 + Math.random() * 80
const randomPosition = () => 10 + random() * 80

// TODO: Break this out into its own component file
export class Cow extends Component {
Expand Down Expand Up @@ -155,7 +156,7 @@ export class Cow extends Component {

this.repositionTimeoutId = setTimeout(
this.repositionTimeoutHandler,
Math.random() * this.waitVariance
random() * this.waitVariance
)
}

Expand Down
4 changes: 3 additions & 1 deletion src/components/Home/SnowBackground.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import React from 'react'
import useWindowSize from 'react-use/lib/useWindowSize'
import Confetti from 'react-confetti'

import { random } from '../../common/utils'

const randomInt = (min, max) => {
return Math.floor(min + Math.random() * (max - min + 1))
return Math.floor(min + random() * (max - min + 1))
}

// Taken from:
Expand Down
52 changes: 52 additions & 0 deletions src/components/SettingsView/RandomSeedInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React, { useContext, useState } from 'react'
import { string } from 'prop-types'
import window from 'global/window'
import TextField from '@material-ui/core/TextField'

import FarmhandContext from '../Farmhand/Farmhand.context'

import './RandomSeedInput.sass'

export const RandomSeedInput = ({ search = window.location.search }) => {
jeremyckahn marked this conversation as resolved.
Show resolved Hide resolved
const {
handlers: { handleRNGSeedChange },
} = useContext(FarmhandContext)

const [seed, setSeed] = useState(
new URLSearchParams(search).get('seed') ?? ''
)

/**
* @param {React.SyntheticEvent<HTMLInputElement>} e
*/
const handleChange = e => {
setSeed(e.target.value)
}

/**
* @param {React.SyntheticEvent<HTMLFormElement>} e
*/
const handleSubmit = e => {
e.preventDefault()

handleRNGSeedChange(seed)
}

return (
<form className="RandomSeedInput" onSubmit={handleSubmit}>
jeremyckahn marked this conversation as resolved.
Show resolved Hide resolved
<TextField
value={seed}
variant="outlined"
label="Random number seed"
onChange={handleChange}
inputProps={{
maxLength: 30,
}}
/>
</form>
)
}

RandomSeedInput.propTypes = {
search: string,
}
3 changes: 3 additions & 0 deletions src/components/SettingsView/RandomSeedInput.sass
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.RandomSeedInput
display: flex
justify-content: center
35 changes: 35 additions & 0 deletions src/components/SettingsView/RandomSeedInput.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

import FarmhandContext from '../Farmhand/Farmhand.context'

import { RandomSeedInput } from './RandomSeedInput'

const mockHandleRNGSeedChange = jest.fn()

const MockRandomSeedInput = props => (
<FarmhandContext.Provider
value={{ handlers: { handleRNGSeedChange: mockHandleRNGSeedChange } }}
>
<RandomSeedInput {...props} />
</FarmhandContext.Provider>
)

describe('RandomSeedInput', () => {
test('gets initial value from query param', () => {
render(<MockRandomSeedInput search="?seed=123" />)

expect(screen.getByDisplayValue('123')).toBeInTheDocument()
})

test('updates query param', () => {
render(<MockRandomSeedInput search="?seed=123" />)

const input = screen.getByDisplayValue('123')

userEvent.type(input, '[Backspace][Backspace][Backspace]456[Enter]')

expect(mockHandleRNGSeedChange).toHaveBeenCalledWith('456')
})
})
3 changes: 3 additions & 0 deletions src/components/SettingsView/SettingsView.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import FileReaderInput from 'react-file-reader-input'

import FarmhandContext from '../Farmhand/Farmhand.context'

import { RandomSeedInput } from './RandomSeedInput'
import './SettingsView.sass'

const SettingsView = ({
Expand Down Expand Up @@ -48,6 +49,8 @@ const SettingsView = ({
</Button>
</div>
<Divider />
<RandomSeedInput />
<Divider />

<FormControl component="fieldset">
<FormLabel component="legend">Options</FormLabel>
Expand Down
Loading