Skip to content

Instantly share code, notes, and snippets.

@lukasvermeer
Created January 28, 2018 10:06
Show Gist options
  • Save lukasvermeer/a489171042274562b5f47e17a0a2844f to your computer and use it in GitHub Desktop.
Save lukasvermeer/a489171042274562b5f47e17a0a2844f to your computer and use it in GitHub Desktop.
# Simulation to estimate emperical odds to win the Haba game "Boomgaard".
# Set number of games to play
NUM.SIM = 10000
# Simulate one turn. Roll die and pick fruit or move bird.
# Input: game state.
# Output: game state after this turn.
turn <- function(state) {
roll <- sample(1:6,1)
# Five represents "basket" side of die which allows picking from any tree.
if (roll == 5) {
# Optimal strategy is to pick tree with most remaining fruit.
roll <- which.max(state[1:4])
}
# Reduce state counter.
state[roll] <- max(0, state[roll] - 1)
return(state)
}
# Check if the game is over.
# Input: game state.
# Output: Boolean if game over (T=win, F=loss), NULL otherwise.
game.over <- function(state) {
if (state[6] == 0) { return (F) }
if (sum(state[1:4]) == 0) { return (T) }
return (NULL)
}
# Play a game.
# Input: index (ignored).
# Output: Boolean game outcome (T=win, F=loss).
play.game <- function(i) {
state <- c(4,4,4,4,0,5)
while (is.null(game.over(state))) { state <- turn(state) }
return(game.over(state))
}
# Simulate many games.
wins <- sapply(1:NUM.SIM, play.game)
# Compute win odds.
sum(wins) / NUM.SIM
@lukasvermeer
Copy link
Author

Should return approximately 0.6244 (e.g. 62% odds to win).

@lukasvermeer
Copy link
Author

To simulate increased difficulty by removing one bird path tile, set line 36 to state <- c(4,4,4,4,0,4).

Should return approximately 0.4608 (e.g. 46% odds to win).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment