# Rock Paper Scissors

The learning algorithm for this simple game AI determines its strategy based on the cumulative frequency distribution of its [human] opponent's choices. As an added bonus, a bar chart pops up at the end of the game indicating the total number of wins, losses and ties.

I went for the minimum viable algorithm here, so I should clarify that the integer choices are meant to represent

1: Rock

2: Paper

3: Scissors

The following code is written in R:

rockPaperScissors <- function (nRounds = 5, nChoices = 3) { choices <- 1:nChoices learningVector <- rep(NA, nRounds) outcomes <- rep(NA, nRounds) AIstrategy <- rep((1/nChoices), nChoices) total <- NA for (k in 1:nRounds) { playerChoice <- as.numeric(readline(prompt = "Choose an integer from 1 to 3: ")) learningVector[k] <- playerChoice playerHistory <- rep(0, nChoices) if (k == 1) { # Simulate Round 1 (AI strategy has uniform probabilities for Round 1) for (i in 1:nChoices) { total <- length(na.omit(learningVector)) choiceFreq <- length(which(learningVector == i)) playerHistory[i] <- choiceFreq / total } } else { # Calculate playerHistory and AIstrategy via freq counts from learningVector for (i in 1:nChoices) { total <- length(na.omit(learningVector)) choiceFreq <- length(which(learningVector == i)) playerHistory[i] <- choiceFreq / total if (i + 1 <= nChoices) AIstrategy[i+1] <- playerHistory[i] else AIstrategy[1] <- playerHistory[i] } } AIchoice <- sample(choices, size = 1, prob = AIstrategy) # The match-up print(paste0(playerChoice, " vs. ", AIchoice)) # Outcomes: Player vs AI outcomes[k] <- playerChoice - AIchoice if (outcomes[k] == -2 | outcomes[k] == 1) { outcomes[k] <- "win" } else if (outcomes[k] == 0) { outcomes[k] <- "tie" } else outcomes[k] <- "lose" # Print the outcome after each round print(outcomes[k]) } print("Final Score: ") print(table(outcomes)) plot(factor(outcomes), col = "darkblue", main = "Player Outcomes") return() }