Last active
January 13, 2020 16:05
-
-
Save alecklandgraf/8097ff66da18a0ce9d86a1ea870c43a2 to your computer and use it in GitHub Desktop.
first orchard game simulation https://www.habausa.com/my-very-first-games-first-orchard/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 100 million simulations reveal of 63.1% chance of winning First Orchard. | |
*/ | |
const GREEN_APPLES = "green apples"; | |
const RED_APPLES = "red apples"; | |
const PLUMBS = "plumbs"; | |
const PEARS = "pears"; | |
const BASKET = "basket"; | |
const RAVEN = "raven"; | |
const STRATEGY = "best"; | |
function generateState() { | |
return { | |
[RAVEN]: 5, | |
[GREEN_APPLES]: 4, | |
[RED_APPLES]: 4, | |
[PLUMBS]: 4, | |
[PEARS]: 4 | |
}; | |
} | |
const die = [GREEN_APPLES, RED_APPLES, PLUMBS, PEARS, BASKET, RAVEN]; | |
function rollDie() { | |
return die[Math.floor(Math.random() * 6)]; | |
} | |
function findMax(state) { | |
let max = state[RED_APPLES]; | |
let basket = RED_APPLES; | |
if (state[GREEN_APPLES] > max) { | |
basket = GREEN_APPLES; | |
max = state[GREEN_APPLES]; | |
} | |
if (state[PLUMBS] > max) { | |
basket = PLUMBS; | |
max = state[PLUMBS]; | |
} | |
if (state[PEARS] > max) { | |
basket = PEARS; | |
} | |
return basket; | |
} | |
function simulate() { | |
const state = generateState(); | |
while ( | |
state[RAVEN] !== 0 && | |
[state[GREEN_APPLES], state[RED_APPLES], state[PLUMBS], state[PEARS]].some( | |
Boolean | |
) | |
) { | |
let roll = rollDie(); | |
// worst strategy would be random or picking a tree with less fruit than another | |
if (roll === BASKET && STRATEGY === "best") { | |
roll = findMax(state); | |
} | |
if (state[roll] > 0) { | |
state[roll] -= 1; | |
} | |
} | |
return state[RAVEN] === 0 ? "lost" : "won"; | |
} | |
module.exports = simulate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for perf, an interesting data structure could be something like