By: Phichaya W.

Explanation

Define rules

rules <- c("Welcome to Rock Paper Scissors Game",
           "Rules:",
           "1. Please enter one option: paper, rock, or scissor.",
           "2. You can play up to 10 rounds",
           "3. If you are done, just type 'quit' to exit the game.")

Function to get player choice

# Choices for player
player_choices <- c("paper", "scissor", "rock", "quit")

# function
player_hand <- function() {
  player_answer <- tolower(readline("Insert your choice here: "))
  
  if (!(player_answer %in% player_choices)) {
    cat("Invalid input! Please enter rock, paper, or scissor.\\n")
    return(player_hand())  # Call again if input is invalid
  }
  
  return(player_answer)
}

Function to get computer choice

# Choices for computer
com_choices <- c("paper", "scissor", "rock")

# Function for computer choice
com_hand <- function() {
  return(sample(com_choices, 1))
}

Function to determine the winner and store scores

# Score tracking
scores <- list(player = 0, computer = 0, draw = 0)

# Function to determine the winner
find_winner <- function(player, computer) {
  cat("Computer chose:", computer, "\\n")
  
  if (player == computer) {
    scores$draw <<- scores$draw + 1
    cat("It's a draw!\\n")
  } else if ((player == "paper" & computer == "scissor") ||
             (player == "rock" & computer == "paper") ||
             (player == "scissor" & computer == "rock")) {
    scores$computer <<- scores$computer + 1
    cat("You Lose! Try again!\\n")
  } else {
    scores$player <<- scores$player + 1
    cat("Lucky! You Win!\\n")
  }
}

Main game function

# Main game function using for-loop
play <- function(max_rounds = 10) {
  # Print game introduction
  cat(rules, sep = "\\n")
  cat("\\n!!! GAME START!!!\\n")
	
	# start for-loop
  for (i in 1:max_rounds) {
    cat("\\nRound", i, "of", max_rounds, ":\\n")
    
    # Get player input
    player <- player_hand()
    
    # Exit game if player chooses quit
    if (player == "quit") {
      cat("\\nGame Over!\\n")
      break  
    }
    
    # Get computer input
    computer <- com_hand()
    
    # Find and display winner
    find_winner(player, computer)
  }
  # ending for-loop
  
  # Final score summary
  cat("\\nFinal Scores:\\n")
  cat("Player Scores:", scores$player, "\\n")
  cat("Computer Scores:", scores$computer, "\\n")
  cat("Draws:", scores$draw, "\\n")
  cat("\\nThanks for playing!\\n")
}

GAME START!

# Start the game
play()