Skip to content

Commit

Permalink
refactor: [#383] centralize random number generation
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyckahn committed Mar 7, 2023
1 parent c666650 commit 19226ba
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 20 deletions.
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
7 changes: 6 additions & 1 deletion src/common/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
/** @typedef {import("../index").farmhand.priceEvent} farmhand.priceEvent */
import { itemsMap } from '../data/maps'

export const random = () => {
return Math.random()
}

/**
* @param {farmhand.priceEvent} [priceCrashes]
* @param {farmhand.priceEvent} [priceSurges]
Expand All @@ -13,7 +18,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
6 changes: 3 additions & 3 deletions src/game-logic/reducers/applyCrows.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { random } from '../../common/utils'
import { doesPlotContainCrop, isRandomNumberLessThan } from '../../utils'
import { CROW_CHANCE, MAX_CROWS } from '../../constants'
import { CROWS_DESTROYED } from '../../templates'

import { modifyFieldPlotAt } from './modifyFieldPlotAt'

import { fieldHasScarecrow } from './helpers'

/**
Expand Down Expand Up @@ -47,12 +47,12 @@ export const applyCrows = state => {

const numCrows = Math.min(
plotsWithCrops.length,
Math.floor(Math.random() * (purchasedField + 1) * MAX_CROWS)
Math.floor(random() * (purchasedField + 1) * MAX_CROWS)
)
let numCropsDestroyed = 0

for (let i = 0; i < numCrows; i++) {
const attackPlotId = Math.floor(Math.random() * plotsWithCrops.length)
const attackPlotId = Math.floor(random() * plotsWithCrops.length)
const target = plotsWithCrops.splice(attackPlotId, 1)[0]

state = modifyFieldPlotAt(state, target.x, target.y, () => null)
Expand Down
5 changes: 3 additions & 2 deletions src/game-logic/reducers/generatePriceEvents.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from '../../utils'
import { PRICE_EVENT_CHANCE } from '../../constants'
import { PRICE_CRASH, PRICE_SURGE } from '../../templates'
import { random } from '../../common/utils'

import { createPriceEvent } from './createPriceEvent'

Expand All @@ -26,7 +27,7 @@ export const generatePriceEvents = state => {

// TODO: Use isRandomNumberLessThan here once it supports an exclusive
// less-than check.
if (Math.random() < PRICE_EVENT_CHANCE) {
if (random() < PRICE_EVENT_CHANCE) {
const { items: unlockedItems } = getLevelEntitlements(
levelAchieved(farmProductsSold(state.itemsSold))
)
Expand All @@ -41,7 +42,7 @@ export const generatePriceEvents = state => {
)

if (!doesPriceEventAlreadyExist) {
const priceEventType = Math.random() < 0.5 ? TYPE_CRASH : TYPE_SURGE
const priceEventType = random() < 0.5 ? TYPE_CRASH : TYPE_SURGE

priceEvent = createPriceEvent(
state,
Expand Down
5 changes: 2 additions & 3 deletions src/game-logic/reducers/minePlot.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { toolType } from '../../enums'
import { chooseRandom, doesInventorySpaceRemain } from '../../utils'
import { INVENTORY_FULL_NOTIFICATION } from '../../strings'
import { ResourceFactory } from '../../factories'
import { random } from '../../common/utils'

import { addItemToInventory } from './addItemToInventory'
import { showNotification } from './showNotification'
Expand Down Expand Up @@ -41,9 +42,7 @@ export const minePlot = (state, x, y) => {
// if ore was spawned, add up to 10 days to the time to clear
// at random, based loosely on the spawnChance meant to make
// rarer ores take longer to cooldown
daysUntilClear += Math.round(
Math.random() * (1 - spawnedOre.spawnChance) * 10
)
daysUntilClear += Math.round(random() * (1 - spawnedOre.spawnChance) * 10)

for (let resource of spawnedResources) {
state = addItemToInventory(state, resource)
Expand Down
11 changes: 6 additions & 5 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
STORM_CHANCE,
STORAGE_EXPANSION_SCALE_PREMIUM,
} from './constants'
import { random } from './common/utils'

const Jimp = configureJimp({
types: [jimpPng],
Expand All @@ -96,7 +97,7 @@ const purchasableItemMap = [...cowShopInventory, ...shopInventory].reduce(
* @return {number}
*/
export const chooseRandomIndex = list =>
Math.round(Math.random() * (list.length - 1))
Math.round(random() * (list.length - 1))

/**
* @param {Array.<*>} list
Expand Down Expand Up @@ -499,7 +500,7 @@ export const generateCow = (options = {}) => {
COW_STARTING_WEIGHT_BASE *
(gender === genders.MALE ? MALE_COW_WEIGHT_MULTIPLIER : 1) -
COW_STARTING_WEIGHT_VARIANCE +
Math.random() * (COW_STARTING_WEIGHT_VARIANCE * 2)
random() * (COW_STARTING_WEIGHT_VARIANCE * 2)
)

const cow = {
Expand Down Expand Up @@ -1191,7 +1192,7 @@ export function randomChoice(weightedOptions) {

sortedOptions.sort(o => o.weight)

let diceRoll = Math.random() * totalWeight
let diceRoll = random() * totalWeight
let option
let runningTotal = 0

Expand Down Expand Up @@ -1309,8 +1310,8 @@ export const isInViewport = element => {
)
}

export const shouldPrecipitateToday = () => Math.random() < PRECIPITATION_CHANCE
export const shouldStormToday = () => Math.random() < STORM_CHANCE
export const shouldPrecipitateToday = () => random() < PRECIPITATION_CHANCE
export const shouldStormToday = () => random() < STORM_CHANCE

/**
* @param {farmhand.cow} cow
Expand Down
4 changes: 3 additions & 1 deletion src/utils/isRandomNumberLessThan.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { random } from '../common/utils'

/**
* Compares given number against a randomly generated number
* @param {number} chance float between 0-1 to compare dice roll against
* @returns {bool} true if the dice roll was equal to or lower than the given chance, false otherwise
*/
export default function isRandomNumberLessThan(chance) {
return Math.random() <= chance
return random() <= chance
}

0 comments on commit 19226ba

Please sign in to comment.