Task

Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player.

Rock Paper Scissors is a two player game.

Each player chooses one of rock, paper or scissors, without knowing the other player's choice.

The winner is decided by a set of rules:

   Rock beats scissors
   Scissors beat paper
   Paper beats rock


If both players choose the same thing, there is no winner for that round.

For this task, the computer will be one of the players.

The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.



Extra credit

Support additional choices   additional weapons.




link printf
 
procedure main()
 
printf("Welcome to Rock, Paper, Scissors.\n_
        Rock beats scissors, Scissors beat paper, and Paper beats rock.\n\n")
 
historyP := ["rock","paper","scissors"]      # seed player history  
winP := winC := draws := 0                   # totals
 
beats := ["rock","scissors","paper","rock"]  # what beats what 1 apart
 
repeat {
   printf("Enter your choice or rock(r), paper(p), scissors(s) or quit(q):")
   turnP := case map(read()) of {
      "q"|"quit": break
      "r"|"rock": "rock"
      "p"|"paper": "paper"
      "s"|"scissors": "scissors"
      default:  printf(" - invalid choice.\n") & next
      }
 
   turnC := beats[(?historyP == beats[i := 2 to *beats],i-1)]  # choose move
 
   put(historyP,turnP)                       # record history
   printf("You chose %s, computer chose %s",turnP,turnC)   
 
   (beats[p := 1 to *beats] == turnP) & 
      (beats[c := 1 to *beats] == turnC) & (abs(p-c) <= 1)  # rank play
 
   if p = c then
      printf(" - draw (#%d)\n",draws +:= 1 )
   else if p > c then   
      printf(" - player win(#%d)\n",winP +:= 1)        
   else 
      printf(" - computer win(#%d)\n",winC +:= 1)    
   }
 
printf("\nResults:\n %d rounds\n %d Draws\n %d Computer wins\n %d Player wins\n",
   winP+winC+draws,draws,winC,winP)   
end