This is a Rock Paper Scissors game I built in R! This project was actually an exercise from a data analysis course I enrolled. It was a fun way to practice the logic of coding
How to play
To play this game, you will need to run the code in an R environment. You can use any platform you are comfortable with, e.g. Posit Cloud, Google Colab, or RStudio Desktop.
Follow these steps
- Copy the code below, or from GitHub.
- Paste and run the script in your R console.
- Start the game by typing
play_rps()and hitting Enter. - Follow the on-screen instructions to make your move.
play_rps <- function() {
hands <- c("rock", "paper", "scissors")
player_score <- 0
valid_choices <- c(hands, "exit")
while(TRUE) {
player_choice <- tolower(readline("Choose your hand(rock, paper, scissors) or exit: "))
# Check for invalid inputs
if (!(player_choice %in% valid_choices)) {
print("Invalid choice. Please enter 'rock', 'paper', 'scissors', or 'exit'.")
next # Skips the rest of the loop and starts the next iteration
}
if (player_choice == "exit") {
cat("\n--- GAME OVER ---\n")
print(paste("Total score: ",player_score))
break
}
com_choice <- sample(hands, 1)
print(paste("Computer chose:", com_choice))
if((player_choice == "rock" & com_choice == "scissors")|
(player_choice == "paper" & com_choice == "rock")|
(player_choice == "scissors" & com_choice == "paper")) {
player_score <- player_score+1
cat("you win this round!")
}
else if((player_choice == "rock" & com_choice == "paper")|
(player_choice == "paper" & com_choice == "scissors")|
(player_choice == "scissors" & com_choice == "rock")) {
cat("you lose this round!")
}
else {
cat("It's a draw")
}
print(paste("Current Score:", player_score))
}
}
I hope you enjoy!

Leave a comment