Rock-paper-scissors: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(152 intermediate revisions by 59 users not shown)
Line 1:
{{task|Games}}
{{task|Games}}The task is to implement the classic children's game [[wp:Rock-paper-scissors|Rock-paper-scissors]], as well as a simple predictive AI player.
 
;Task:
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:
Implement the classic children's game [[wp:Rock-paper-scissors|Rock-paper-scissors]], as well as a simple predictive &nbsp; '''AI''' &nbsp; (<u>a</u>rtificial <u>i</u>ntelligence) &nbsp; player.
 
Rock Paper Scissors is a two player game.
* Rock beats scissors
* Scissors beat paper
* Paper beats rock.
 
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:
 
:::* &nbsp; Rock beats scissors
:::* &nbsp; Scissors beat paper
:::* &nbsp; Paper beats rock
 
<br>
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.
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 [[Probabilistic choice|weighted random choice]] in an attempt to defeat its opponent.
 
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 [[Probabilistic choice|weighted random choice]] in an attempt to defeat its opponent.
 
 
;Extra credit:
Support additional choices &nbsp; [[wp:Rock-paper-scissors#Additional_weapons|additional weapons]].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V rules = [‘rock’ = ‘paper’, ‘scissors’ = ‘rock’, ‘paper’ = ‘scissors’]
V previous = [‘rock’, ‘paper’, ‘scissors’]
 
L
V human = input("\nchoose your weapon: ")
V computer = rules[random:choice(previous)]
 
I human C (‘quit’, ‘exit’)
L.break
 
E I human C rules
previous.append(human)
print(‘the computer played ’computer, end' ‘; ’)
 
I rules[computer] == human
print(‘yay you win!’)
E I rules[human] == computer
print(‘the computer beat you... :(’)
E
print(‘it's a tie!’)
 
E
print(‘that's not a valid choice’)</syntaxhighlight>
 
{{out}}
<pre>
 
choose your weapon: rock
the computer played paper; the computer beat you... :(
 
choose your weapon: rock
the computer played scissors; yay you win!
 
choose your weapon: rock
the computer played paper; the computer beat you... :(
 
choose your weapon: rock
the computer played paper; the computer beat you... :(
 
choose your weapon: rock
the computer played rock; it's a tie!
</pre>
 
'''Extra credit:''' easy support for [[wp:Rock-paper-scissors#Additional_weapons|additional weapons]].
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; with Ada.Numerics.Float_Random;
 
procedure Rock_Paper_Scissors is
Line 120 ⟶ 180:
Ada.Text_IO.Put_Line(Result'Image(R) & Natural'Image(Score(R)));
end loop;
end Rock_Paper_Scissors;</langsyntaxhighlight>
 
First and last few lines of the output of a game, where the human did permanently choose Rock:
Line 168 ⟶ 228:
 
=={{header|Aime}}==
<syntaxhighlight lang ="aime"></lang>text
computer_play(record plays, record beats)
{
integer a, c, total;
text s;
 
total = plays["rock"] + plays["paper"] + plays["scissors"];
a = drand(total - 1);
for (s, c in plays) {
if (a < c) {
break;
}
a -= c;
}
 
beats[s];
}
 
integer
main(void)
{
integer computer, human;
record beats, plays;
file f;
text s;
 
computer = human = 0;
 
f.stdin;
 
beats["rock"] = "paper";
beats["paper"] = "scissors";
beats["scissors"] = "rock";
 
plays["rock"] = 1;
plays["paper"] = 1;
plays["scissors"] = 1;
 
while (1) {
o_text("Your choice [rock/paper/scissors]:\n");
if (f.line(s) == -1) {
break;
}
 
if (!plays.key(s)) {
o_text("Invalid choice, try again\n");
} else {
text c;
 
c = computer_play(plays, beats);
 
o_form("Human: ~, Computer: ~\n", s, c);
 
if (s == c) {
o_text("Draw\n");
} elif (c == beats[s]) {
computer += 1;
o_text("Computer wins\n");
} else {
human += 1;
o_text("Human wins\n");
}
 
plays.up(s);
 
o_form("Score: Human: ~, Computer: ~\n", human, computer);
}
}
 
return 0;
}</syntaxhighlight>
 
=={{header|ALGOL 68}}==
<syntaxhighlight lang="algol68">BEGIN
# rock/paper/scissors game #
# counts of the number of times the player has chosen each move #
# we initialise each to 1 so that the total isn't zero when we are #
# choosing the computer's first move (as in the Ada version) #
INT r count := 1;
INT p count := 1;
INT s count := 1;
# counts of how many games the player and computer have won #
INT player count := 0;
INT computer count := 0;
print( ( "rock/paper/scissors", newline, newline ) );
WHILE
CHAR player move;
# get the players move - r => rock, p => paper, s => scissors #
# q => quit #
WHILE
print( ( "Please enter your move (r/p/s) or q to quit: " ) );
read( ( player move, newline ) );
( player move /= "r"
AND player move /= "p"
AND player move /= "s"
AND player move /= "q"
)
DO
print( ( "Unrecognised move", newline ) )
OD;
# continue playing until the player chooses quit #
player move /= "q"
DO
# decide the computer's move based on the player's history #
CHAR computer move;
INT move count = r count + p count + s count;
# predict player will play rock if the random number #
# is in the range 0 .. rock / total #
# predict player will play paper if the random number #
# is in the range rock / total .. ( rock + paper ) / total #
# predict player will play scissors otherwise #
REAL r limit = r count / move count;
REAL p limit = r limit + ( p count / move count );
REAL random move = next random;
IF random move < r limit THEN
# we predict the player will choose rock - we choose paper #
computer move := "p"
ELIF random move < p limit THEN
# we predict the player will choose paper - we choose scissors #
computer move := "s"
ELSE
# we predict the player will choose scissors - we choose rock #
computer move := "r"
FI;
print( ( "You chose: " + player move, newline ) );
print( ( "I chose: " + computer move, newline ) );
IF player move = computer move THEN
# both players chose the same - draw #
print( ( "We draw", newline ) )
ELSE
# players chose different moves - there is a winner #
IF ( player move = "r" AND computer move = "s" )
OR ( player move = "p" AND computer move = "r" )
OR ( player move = "s" AND computer move = "p" )
THEN
player count +:= 1;
print( ( "You win", newline ) )
ELSE
computer count +:= 1;
print( ( "I win", newline ) )
FI;
print( ( "You won: "
, whole( player count , 0 )
, ", I won: "
, whole( computer count, 0 )
, newline
)
)
FI;
IF player move = "r" THEN
# player chose rock #
r count +:= 1
ELIF player move = "p" THEN
# player chose paper #
p count +:= 1
ELSE
# player chose scissors #
s count +:= 1
FI
OD;
print( ( "Thanks for a most enjoyable game", newline ) )
END</syntaxhighlight>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="ahk">DllCall("AllocConsole")
<lang AHK>#Warn
DllCall("AllocConsole")
Write("Welcome to Rock-Paper-Scissors`nMake a choice: ")
 
Line 216 ⟶ 436:
Write(txt){
FileAppend, % txt, CONOUT$
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
I´ve created a GUI to play and show results, no Console Input
 
<langsyntaxhighlight lang="autoit">
RPS()
 
Line 315 ⟶ 536:
EndFunc ;==>_RPS_Eval
 
</syntaxhighlight>
</lang>
 
=={{header|Bash}}==
<syntaxhighlight lang="bash">#!/bin/bash
echo "What will you choose? [rock/paper/scissors]"
read response
aiThought=$(echo $[ 1 + $[ RANDOM % 3 ]])
case $aiThought in
1) aiResponse="rock" ;;
2) aiResponse="paper" ;;
3) aiResponse="scissors" ;;
esac
echo "AI - $aiResponse"
responses="$response$aiResponse"
case $responses in
rockrock) isTie=1 ;;
rockpaper) playerWon=0 ;;
rockscissors) playerWon=1 ;;
paperrock) playerWon=1 ;;
paperpaper) isTie=1 ;;
paperscissors) playerWon=0 ;;
scissorsrock) playerWon=0 ;;
scissorspaper) playerWon=1 ;;
scissorsscissors) isTie=1 ;;
esac
if [[ $isTie == 1 ]] ; then echo "It's a tie!" && exit 1 ; fi
if [[ $playerWon == 0 ]] ; then echo "Sorry, $aiResponse beats $response , try again.." && exit 1 ; fi
if [[ $playerWon == 1 ]] ; then echo "Good job, $response beats $aiResponse!" && exit 1 ; fi</syntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QBasic}}
 
<langsyntaxhighlight lang="qbasic">DIM pPLchoice(1 TO 3) AS INTEGER, pCMchoice(1 TO 3) AS INTEGER
DIM choices(1 TO 3) AS STRING
DIM playerwins(1 TO 3) AS INTEGER
Line 381 ⟶ 629:
PRINT , choices(1), choices(2), choices(3)
PRINT "You chose:", pPLchoice(1), pPLchoice(2), pPLchoice(3)
PRINT " I chose:", pCMchoice(1), pCMchoice(2), pCMchoice(3)</langsyntaxhighlight>
 
A sample game:
Line 405 ⟶ 653:
I chose: 2 55 4
 
=={{header|Batch File}}==
{{works with|uBasic}}
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
set choice1=rock
This works with a tiny, integer BASIC interpreter. The expression:
set choice2=paper
set choice3=scissors
set freq1=0
set freq2=0
set freq3=0
set games=0
set won=0
set lost=0
set tie=0
 
:start
CHOOSE X=3
cls
echo Games - %games% : Won - %won% : Lost - %lost% : Ties - %tie%
choice /c RPS /n /m "[R]ock, [P]aper or [S]cissors? "
 
set choice=%errorlevel%
Is equivalent to:
rem used [1,1000] as interval for random
if %games% equ 0 (
rem at the beginning, there's no bias for each choice
set /a "rocklimit=1000 / 3"
set /a "scissorslimit=1000 * 2 / 3"
) else (
set /a "rocklimit=1000 * %freq3% / %games%"
set /a "scissorslimit=1000 * (%freq1% + %freq3%) / %games%"
)
set /a "randchoice=%random% %% 1000 + 1"
set compchoice=2
if %randchoice% geq %scissorslimit% set compchoice=3
if %randchoice% leq %rocklimit% set compchoice=1
 
cls
LET X=INT(RND(1)*3)
echo Player: !choice%choice%! ^|vs^| Computer: !choice%compchoice%!
goto %compchoice%
 
:1
This implementation uses a 6-bits binary scheme, where the lower three bits represent the choice of the user and the higher three bits the choice of the computer:
if %choice%==1 goto tie
if %choice%==2 goto win
if %choice%==3 goto loss
 
:2
<lang ubasic> 20 LET P=0: LET Q=0: LET Z=0
if %choice%==1 goto loss
30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
if %choice%==2 goto tie
40 IF A>3 THEN GOTO 400
if %choice%==3 goto win
50 IF A=3 THEN LET A=4
60 IF A<1 THEN GOTO 400
70 CHOOSE C=3 : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10
90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO 30
100 P=P+1 : PRINT "You chose 'paper', I chose 'rock'. You win.." : GOTO 30
120 Q=Q+1 : PRINT "You chose 'scissors', I chose 'rock'. I win!" : GOTO 30
170 Q=Q+1 : PRINT "You chose 'rock', I chose 'paper'. I win!" : GOTO 30
180 Z=Z+1 : PRINT "We both chose 'paper'. It's a draw." : GOTO 30
200 P=P+1 : PRINT "You chose 'scissors', I chose 'paper'. You win.." : GOTO 30
330 P=P+1 : PRINT "You chose 'rock', I chose 'scissors'. You win.." : GOTO 30
340 Q=Q+1 : PRINT "You chose 'paper', I chose 'scissors'. I win!" : GOTO 30
360 Z=Z+1 : PRINT "We both chose 'scissors'. It's a draw." : GOTO 30
400 PRINT "There were ";Z;" draws. I lost ";P;" times, you lost ";Q;" times." : END</lang>
 
:3
A sample game:
if %choice%==1 goto win
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 1
if %choice%==2 goto loss
You chose 'rock', I chose 'paper'. I win!
if %choice%==3 goto tie
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 2
 
You chose 'paper', I chose 'scissors'. I win!
:win
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 3
set /a "won+=1"
You chose 'scissors', I chose 'paper'. You win..
echo Player wins^!
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 1
goto end
You chose 'rock', I chose 'paper'. I win!
 
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 2
:loss
We both chose 'paper'. It's a draw.
set /a "lost+=1"
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 3
echo Computer Wins^!
You chose 'scissors', I chose 'rock'. I win!
goto end
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 4
 
There were 1 draws. I lost 1 times, you lost 4 times.
:tie
set /a "tie+=1"
echo Tie^!
goto end
 
:end
set /a "games+=1"
set /a "freq%choice%+=1"
pause
goto start</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic">PRINT"Welcome to the game of rock-paper-scissors"
PRINT "Each player guesses one of these three, and reveals it at the same time."
PRINT "Rock blunts scissors, which cut paper, which wraps stone."
Line 496 ⟶ 774:
IF r%<=p%(0) THEN =1
IF r%<=p%(0)+p%(1) THEN =2
=0</langsyntaxhighlight>
 
Sample output:
Line 526 ⟶ 804:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#define LEN 3
 
/* pick a random index from 0 to n-1, according to probablities listed
int rand_i(int n)
in p[] which is assumed to have a sum of 1. The values in the probablity
list matters up to the point where the sum goes over 1 */
int rand_idx(double *p, int n)
{
intdouble rand_maxs = RAND_MAXrand() -/ (RAND_MAX %+ n1.0);
int reti;
whilefor ((reti = rand0; i < n - 1 && ()s -= p[i]) >= rand_max0; i++);
return ret/(rand_max / n);
}
 
int weighed_rand(int *tbl, int len)
{
int i, sum, r;
for (i = 0, sum = 0; i < len; sum += tbl[i++]);
if (!sum) return rand_i(len);
 
r = rand_i(sum) + 1;
for (i = 0; i < len && (r -= tbl[i]) > 0; i++);
return i;
}
Line 555 ⟶ 827:
char str[2];
const char *winner[] = { "We tied.", "Meself winned.", "You win." };
double p[LEN] = { 1./3, 1./3, 1./3 };
 
while (1) {
my_action = rand_idx(weighed_rand(user_recp, 3) + 1LEN) % 3;
 
printf("\nYour choice [1-3]:\n"
" 1. Rock\n 2. Paper\n 3. Scissors\n> ");
 
/* scanf is a terrible way to do input. should use stty and keystrokes */
if (!scanf("%d", &user_action)) {
scanf("%1s", str);
if (*str == 'q') return 0;{
printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]);
return 0;
}
continue;
}
Line 576 ⟶ 852:
names[user_action], names[my_action],
winner[(my_action - user_action + 3) % 3]);
 
user_rec[user_action]++;
}
}
}</lang>
</syntaxhighlight>
{{incorrect|C|This example does not seem to use the weighted average AI from the task description.}}
 
Here's another code: (Does it using a while loop and is much shorter then the above)
Here's another code: (Does it using a while loop)
<lang C>
<syntaxhighlight lang="c">
#include <stdio.h> // Standard IO
#include <stdlib.h> // other stuff
#include <time.h>
#include <string.h>
 
int main(int argc, const char *argv[]){
//This should add weighted random function to "The Elite Noob"'s code, stolen from above code because it does calculation so well
//closest I could make it to original but without pointless attempt to make code look smaller than above code by putting code on the same lines
int rand_i(int n)
{
int rand_max = RAND_MAX - (RAND_MAX % n);
int ret;
while ((ret = rand()) >= rand_max);
return ret/(rand_max / n);
}
int weighed_rand(int *tbl, int len)
{
int i, sum, r;
for (i = 0, sum = 0; i < len; sum += tbl[i++]);
if (!sum) return rand_i(len);
r = rand_i(sum) + 1;
for (i = 0; i < len && (r -= tbl[i]) > 0; i++);
return i;
}
 
 
 
int main(int argc, const char *argv[])
{
char umove[10], cmove[10], line[255];
int user, comp;
int tbl[]={0,0,0};
int tbllen=3;
printf("Hello, Welcome to rock-paper-scissors\nBy The Elite Noob\n");
mainloop:
while(1){ // infinite loop :)
while(1)
{ // infinite loop :)
printf("\n\nPlease type in 1 for Rock, 2 For Paper, 3 for Scissors, 4 to quit\n");
srand(time(NULL));
int user, comp = (randweighed_rand(tbl, tbllen)%3) + 1) % 3;
char line[255];
fgets(line, sizeof(line), stdin);
while(sscanf(line, "%d", &user) != 1) { //1 match of defined specifier on input line
{
printf("You have not entered an integer.\n");
fgets(line, sizeof(line), stdin);
}
if(user != 1 && (user !=> 24) &&|| (user !=< 3 && user != 41){printf("Please enter a valid number!\n");continue;}
{
char umove[10], cmove[10];
printf("Please enter a valid number!\n");
if(comp == 1){strcpy(cmove, "Rock");}else if(comp == 2){strcpy(cmove, "Paper");}else{strcpy(cmove, "Scissors");}
continue;
if(user == 1){strcpy(umove, "Rock");}else if(user == 2){strcpy(umove, "Paper");}else{strcpy(umove, "Scissors");}
}
if(user == 4){printf("Goodbye! Thanks for playing!\n");break;}
switch (comp)
if((comp == 1 && user == 3)||(comp == 2 && user == 1)||(comp == 3 && user == 2)){
{
case 1 :
strcpy(cmove, "Rock");
break;
case 2 :
strcpy(cmove, "Paper");
break;
case 3 :
strcpy(cmove, "Scissors");
break;
default :
printf("Computer Error, set comp=1\n");
comp=1;
strcpy(cmove, "Rock");
break;
}
switch (user)
{
case 1 :
strcpy(umove, "Rock");
break;
case 2 :
strcpy(umove, "Paper");
break;
case 3 :
strcpy(umove, "Scissors");
break;
case 4 :
printf("Goodbye! Thanks for playing!\n");
return 0;
default :
printf("Error, user number not between 1-4 exiting...");
goto mainloop;
}
if( (user+1)%3 == comp )
{
printf("Comp Played: %s\nYou Played: %s\nSorry, You Lost!\n", cmove, umove);
}
}else if(comp == user){
else if(comp == user)
printf("Comp Played: %s\nYou Played: %s\nYou Tied :p\n", cmove, umove);}
else{
printf("Comp Played: %s\nYou Played: %s\nYou Tied :p\n", cmove, umove);
}
else
{
printf("Comp Played: %s\nYou Played: %s\nYay, You Won!\n", cmove, umove);
}
}}return 1;}
tbl[user-1]++;
</lang>
}
}
</syntaxhighlight>
 
=={{header|C sharp}}==
<syntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
using System.Linq;
 
namespace RockPaperScissors
{
class Program
{
static void Main(string[] args)
{
// There is no limit on the amount of weapons supported by RPSGame. Matchups are calculated depending on the order.
var rps = new RPSGame("scissors", "paper", "rock", "lizard", "spock");
 
int wins = 0, losses = 0, draws = 0;
 
while (true)
{
Console.WriteLine("Make your move: " + string.Join(", ", rps.Weapons) + ", quit");
 
string weapon = Console.ReadLine().Trim().ToLower();
 
if (weapon == "quit")
break;
 
if (!rps.Weapons.Contains(weapon))
{
Console.WriteLine("Invalid weapon!");
continue;
}
 
int result = rps.Next(weapon);
 
Console.WriteLine("You chose {0} and your opponent chose {1}!", weapon, rps.LastAIWeapon);
 
switch (result)
{
case 1: Console.WriteLine("{0} pwns {1}. You're a winner!", weapon, rps.LastAIWeapon);
wins++;
break;
case 0: Console.WriteLine("Draw!");
draws++;
break;
case -1: Console.WriteLine("{0} pwns {1}. You're a loser!", rps.LastAIWeapon, weapon);
losses++;
break;
}
 
Console.WriteLine();
}
 
Console.WriteLine("\nPlayer Statistics\nWins: {0}\nLosses: {1}\nDraws: {2}", wins, losses, draws);
}
 
class RPSGame
{
public RPSGame(params string[] weapons)
{
Weapons = weapons;
 
// Creates a new AI opponent, and gives it the list of weapons.
_rpsAI = new RPSAI(weapons);
}
 
// Play next turn.
public int Next(string weapon)
{
string aiWeapon = _rpsAI.NextMove(); // Gets the AI opponent's next move.
LastAIWeapon = aiWeapon; // Saves the AI opponent's move in a property so the player can see it.
 
_rpsAI.AddPlayerMove(weapon); // Let the AI know which weapon the player chose, for future predictions.
return GetWinner(Weapons, weapon, aiWeapon); // Returns -1 if AI win, 0 if draw, and 1 if player win.
}
 
// Returns matchup winner.
public static int GetWinner(string[] weapons, string weapon1, string weapon2)
{
if (weapon1 == weapon2)
return 0; // If weapons are the same, return 0 for draw.
 
if (GetVictories(weapons, weapon1).Contains(weapon2))
return 1; // Returns 1 for weapon1 win.
else if (GetVictories(weapons, weapon2).Contains(weapon1))
return -1; // Returns -1 for weapon2 win.
 
throw new Exception("No winner found.");
}
 
/*
* Return weapons that the provided weapon beats.
* The are calculated in the following way:
* If the index of the weapon is even, then all even indices less than it,
* and all odd indices greater than it, are victories.
* One exception is if it is an odd index, and also the last index in the set,
* then the first index in the set is a victory.
*/
public static IEnumerable<string> GetVictories(string[] weapons, string weapon)
{
// Gets index of weapon.
int index = Array.IndexOf(weapons, weapon);
 
// If weapon is odd and the final index in the set, then return the first item in the set as a victory.
if (index % 2 != 0 && index == weapons.Length - 1)
yield return weapons[0];
for (int i = index - 2; i >= 0; i -= 2)
yield return weapons[i];
 
for (int i = index + 1; i < weapons.Length; i += 2)
yield return weapons[i];
}
 
public string LastAIWeapon
{
private set;
get;
}
 
public readonly string[] Weapons;
private RPSAI _rpsAI;
 
class RPSAI
{
public RPSAI(params string[] weapons)
{
_weapons = weapons;
_weaponProbability = new Dictionary<string, int>();
 
// The AI sets the probability for each weapon to be chosen as 1.
foreach (string weapon in weapons)
_weaponProbability.Add(weapon, 1);
 
_random = new Random();
}
 
// Increases probability of selecting each weapon that beats the provided move.
public void AddPlayerMove(string weapon)
{
int index = Array.IndexOf(_weapons, weapon);
 
foreach (string winWeapon in _weapons.Except(GetVictories(_weapons, weapon)))
if (winWeapon != weapon)
_weaponProbability[winWeapon]++;
}
 
// Gets the AI's next move.
public string NextMove()
{
double r = _random.NextDouble();
 
double divisor = _weaponProbability.Values.Sum();
 
var weightedWeaponRanges = new Dictionary<double, string>();
 
double currentPos = 0.0;
 
// Maps probabilities to ranges between 0.0 and 1.0. Returns weighted random weapon.
foreach (var weapon in _weaponProbability)
{
double weightedRange = weapon.Value / divisor;
if (r <= currentPos + (weapon.Value / divisor))
return weapon.Key;
currentPos += weightedRange;
}
 
throw new Exception("Error calculating move.");
}
 
Random _random;
private readonly string[] _weapons;
private Dictionary<string, int> _weaponProbability;
}
}
}
}</syntaxhighlight>
 
Sample output of first 2 and last 2 rounds when player chooses rock every turn:
 
<pre>Make your move: scissors, paper, rock, lizard, spock, quit
rock
You chose rock and your opponent chose lizard!
rock pwns lizard. You're a winner!
 
Make your move: scissors, paper, rock, lizard, spock, quit
rock
You chose rock and your opponent chose lizard!
rock pwns lizard. You're a winner!
 
...
 
Make your move: scissors, paper, rock, lizard, spock, quit
rock
You chose rock and your opponent chose paper!
paper pwns rock. You're a loser!
 
Make your move: scissors, paper, rock, lizard, spock, quit
rock
You chose rock and your opponent chose spock!
spock pwns rock. You're a loser!
 
Make your move: scissors, paper, rock, lizard, spock, quit
quit
 
Player Statistics
Wins: 5
Losses: 60
Draws: 1
</pre>
 
=={{header|C++}}==
Version using Additional Weapons
 
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 776 ⟶ 1,337:
}
//-------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
Sample output:
Line 813 ⟶ 1,374:
</pre>
 
=={{header|DClojure}}==
{{translibheader|Pythonjline}}
{{libheader|clojure.data.generators}}
<lang d>import std.stdio, std.random, std.string, std.array,
std.typecons, std.traits, std.conv, std.algorithm;
 
Note: If you run it with Leiningen, use the special trampoline run to prevent issues:
enum Choice { rock, paper, scissors }
immutable order = [EnumMembers!Choice];
 
<pre>$ lein trampoline run</pre>
uint[order.length] choiceFrequency;
 
Code:
Choice whatBeats(in Choice ch) pure /*nothrow*/ {
return order[(order.countUntil(ch) + 1) % $];
}
 
<syntaxhighlight lang="clojure">(ns rps.core
Nullable!Choice checkWinner(in Choice a, in Choice b)
(:require [clojure.data.generators :refer [weighted]])
pure /*nothrow*/ {
(:import jline.Terminal)
alias TResult = typeof(return);
(:gen-class))
 
(def what-beats {:rock :paper, :paper :scissors, :scissors :rock})
if (b == whatBeats(a))
return TResult(b);
else if (a == whatBeats(b))
return TResult(a);
return TResult();
}
 
(defn battle [human comp]
Choice getRandomChoice() /*nothrow*/ {
(let [h (name human)
if (choiceFrequency[].reduce!q{a + b} == 0)
returnc uniform!Choice;(name comp)]
(cond
return order[choiceFrequency.dice].whatBeats;
(= human comp) (println (format "We both picked %s. DRAW!" c))
(= human (what-beats comp))
(println (format "Your %s defeats computer's %s. YOU WIN!" h c))
(= comp (what-beats human))
(println (format "Computer's %s defeats your %s. YOU LOSE!" c h))
:else (println (format "Wat? %s and %s ?" h c)))))
 
(defn key->rps [k]
(cond
(or (= k 82) (= k 114)) :rock
(or (= k 80) (= k 112)) :paper
(or (= k 83) (= k 115)) :scissors
:else nil))
 
(defn play-game [freqs]
(println "\n(R)ock, (P)aper, (S)cissors?")
(let [term (Terminal/getTerminal)
rps (key->rps (.readCharacter term System/in))]
(if-not (nil? rps)
(do
(battle rps (what-beats (weighted freqs)))
(recur (assoc freqs rps (inc (rps freqs)))))
(println "Game Over Man! Game Over!"))))
 
(defn -main
"Rock, Paper, Scissors!"
[& args]
(play-game {:rock 1, :paper 1, :scissors 1}))</syntaxhighlight>
 
{{out}}
<pre>(R)ock, (P)aper, (S)cissors?
Your paper defeats computer's rock. YOU WIN!
 
(R)ock, (P)aper, (S)cissors?
Computer's paper defeats your rock. YOU LOSE!
 
(R)ock, (P)aper, (S)cissors?
We both picked scissors. DRAW!</pre>
 
=={{header|Crystal}}==
Inspired by [[#Ruby]] solution, but improved to allow additional weapons
<syntaxhighlight lang="ruby">
# conventional weapons
enum Choice
Rock
Paper
Scissors
end
 
BEATS = {
Choice::Rock => [Choice::Paper],
Choice::Paper => [Choice::Scissors],
Choice::Scissors => [Choice::Rock],
}
 
# uncomment to use additional weapons
void main() {
# enum Choice
writeln("Rock-Paper-Scissors Game");
# Rock
# Paper
# Scissors
# Lizard
# Spock
# end
 
# BEATS = {
while (true) {
# Choice::Rock => [Choice::Paper, Choice::Spock],
write("Your choice (empty to end game): ");
# Choice::Paper => [Choice::Scissors, Choice::Lizard],
immutable humanChoiceStr = readln.strip.toLower;
# Choice::Scissors => [Choice::Rock, Choice::Spock],
if (humanChoiceStr.empty)
# Choice::Lizard => [Choice::Rock, Choice::Scissors],
break;
# Choice::Spock => [Choice::Paper, Choice::Lizard],
# }
 
class RPSAI
Choice humanChoice;
@stats = {} of Choice => try {Int32
humanChoice = humanChoiceStr.to!Choice;
} catch (ConvException e) {
writeln("Wrong input: ", humanChoiceStr);
continue;
}
 
def initialize
immutable compChoice = getRandomChoice;
Choice.values.each do |c|
write("Computer picked ", compChoice, ", ");
@stats[c] = 1
end
end
 
def choose
// Don't register the player choice until after
v = rand(@stats.values.sum)
// the computer has made its choice.
@stats.each do |choice, rate|
choiceFrequency[humanChoice]++;
v -= rate
return choice if v < 0
end
raise ""
end
 
def train(selected)
immutable winner = checkWinner(humanChoice, compChoice);
BEATS[selected].each do |c|
if (winner.isNull)
@stats[c] += 1
writeln("Nobody wins!");
elseend
end
writeln(winner.get, " wins!");
end
}
 
}</lang>
enum GameResult
{{out|Output example}}
HumanWin
<pre>Rock-Paper-Scissors Game
ComputerWin
Your choice (empty to end game): rock
Draw
Computer picked scissors, rock wins!
 
Your choice (empty to end game): scissors
def to_s
Computer picked paper, scissors wins!
case self
Your choice (empty to end game):</pre>
when .draw?
===Alternative Version===
"Draw"
This version is more similar to the functional solutions.
when .human_win?
<lang d>import std.stdio, std.random, std.string, std.conv, std.array,
"You std.typecons;win!"
when .computer_win?
"I win!"
end
end
end
 
class RPSGame
@score = Hash(GameResult, Int32).new(0)
@ai = RPSAI.new
 
def check(player, computer)
return GameResult::ComputerWin if BEATS[player].includes? computer
return GameResult::HumanWin if BEATS[computer].includes? player
return GameResult::Draw
end
 
def round
puts ""
print "Your choice (#{Choice.values.join(", ")}):"
s = gets.not_nil!.strip.downcase
return false if "quit".starts_with? s
player_turn = Choice.values.find { |choice| choice.to_s.downcase.starts_with? s }
unless player_turn
puts "Invalid choice"
return true
end
ai_turn = @ai.choose
result = check(player_turn, ai_turn)
puts "H: #{player_turn}, C: #{ai_turn} => #{result}"
@score[result] += 1
puts "score: human=%d, computer=%d, draw=%d" % GameResult.values.map { |r| @score[r] }
@ai.train player_turn
true
end
end
 
game = RPSGame.new
loop do
break unless game.round
end</syntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<syntaxhighlight lang="d">import std.stdio, std.random, std.string, std.conv, std.array, std.typecons;
 
enum Choice { rock, paper, scissors }
 
bool beats(in Choice c1, in Choice c2) pure nothrow @safe @nogc {
with (Choice) return (c1 == Choice.paper && c2 == Choice.rock) ||
(c1 == Choice.scissors && c2 == Choice.paper) ||
(c1 == Choice.rock && c2 == Choice.scissors);
}
 
Choice genMove(in int r, in int p, in int s) @safe /*@nogc*/ {
immutable x = uniform!"[]"(1, r + p + s);
if (x < s) return Choice.rock;
Line 902 ⟶ 1,563:
}
 
Nullable!To maybeTo(To, From)(From x) pure nothrow @safe {
try {
return typeof(return)(x.to!To);
} catch (ConvException e) {
return typeof(return)();
} catch (Exception e) {
static immutable err = new Error("std.conv.to failure");
throw err;
}
}
 
void main() /*@safe*/ {
int r = 1, p = 1, s = 1;
 
Line 926 ⟶ 1,590:
 
immutable c = genMove(r, p, s);
writeln("Player: ", h.get, " Computer: ", c);
 
if (beats(h, c)) writeln("Player wins\n");
Line 938 ⟶ 1,602:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>rock, paper or scissors? paper
Line 957 ⟶ 1,621:
 
rock, paper or scissors?
</pre>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule Rock_paper_scissors do
def play, do: loop([1,1,1])
defp loop([r,p,s]=odds) do
IO.gets("What is your move? (R,P,S,Q) ") |> String.upcase |> String.first
|> case do
"Q" -> IO.puts "Good bye!"
human when human in ["R","P","S"] ->
IO.puts "Your move is #{play_to_string(human)}."
computer = select_play(odds)
IO.puts "My move is #{play_to_string(computer)}"
case beats(human,computer) do
true -> IO.puts "You win!"
false -> IO.puts "I win!"
_ -> IO.puts "Draw"
end
case human do
"R" -> loop([r+1,p,s])
"P" -> loop([r,p+1,s])
"S" -> loop([r,p,s+1])
end
_ ->
IO.puts "Invalid play"
loop(odds)
end
end
defp beats("R","S"), do: true
defp beats("P","R"), do: true
defp beats("S","P"), do: true
defp beats(x,x), do: :draw
defp beats(_,_), do: false
defp play_to_string("R"), do: "Rock"
defp play_to_string("P"), do: "Paper"
defp play_to_string("S"), do: "Scissors"
defp select_play([r,p,s]) do
n = :rand.uniform(r+p+s)
cond do
n <= r -> "P"
n <= r+p -> "S"
true -> "R"
end
end
end
 
Rock_paper_scissors.play</syntaxhighlight>
 
'''Sample output:'''
<pre>
What is your move? (R,P,S,Q) r
Your move is Rock.
My move is Scissors
You win!
What is your move? (R,P,S,Q) p
Your move is Paper.
My move is Paper
Draw
What is your move? (R,P,S,Q) s
Your move is Scissors.
My move is Scissors
Draw
What is your move? (R,P,S,Q) q
Good bye!
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(rps).
-compile(export_all).
Line 1,007 ⟶ 1,740:
true -> $R
end.
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{trans|C}}
<langsyntaxhighlight lang="euphoria">function weighted_rand(sequence table)
integer sum,r
sum = 0
Line 1,060 ⟶ 1,793:
printf(1,"\nScore %d:%d\n",score)
user_rec[user_action] += 1
end while</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight FSharplang="fsharp">open System
 
let random = Random ()
Line 1,124 ⟶ 1,857:
 
game(1.0, 1.0, 1.0)
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: combinators formatting io kernel math math.ranges qw
random sequences ;
IN: rosetta-code.rock-paper-scissors
 
CONSTANT: thing qw{ rock paper scissors }
CONSTANT: msg { "I win." "Tie!" "You win." }
 
: ai-choice ( r p s -- n )
3dup + + nip [1,b] random {
{ [ 3dup nip >= ] [ 3drop 1 ] }
{ [ 3dup [ + ] dip >= ] [ 3drop 2 ] }
[ 3drop 0 ]
} cond ;
 
: player-choice ( -- n )
"r/p/s/q? " write readln qw{ r p s q } index dup
[ drop player-choice ] unless ;
 
! return:
! -1 for n1 loses to n2.
! 0 for n1 ties n2.
! 1 for n1 beats n2.
: outcome ( n1 n2 -- n3 ) - dup abs 1 > [ neg ] when sgn ;
 
: status. ( seq -- )
"My wins: %d Ties: %d Your wins: %d\n" vprintf ;
 
: choices. ( n1 n2 -- )
[ thing nth ] bi@ "You chose: %s\nI chose: %s\n" printf ;
 
: tally ( seq n -- seq' ) over [ 1 + ] change-nth ;
 
: game ( seq -- seq' )
dup status. player-choice dup 3 = [ drop ] [
[ 3 + tally ] keep over 3 tail* first3 ai-choice 2dup
choices. outcome 1 + dup [ tally ] dip msg nth print nl
game
] if ;
 
! The game state is a sequence where the members are:
! losses, ties, wins, #rock, #paper, #scissors
: main ( -- ) { 0 0 0 1 1 1 } clone game drop ;
 
MAIN: main</syntaxhighlight>
{{out}}
<pre>
My wins: 0 Ties: 0 Your wins: 0
r/p/s/q? r
You chose: rock
I chose: paper
I win.
 
My wins: 1 Ties: 0 Your wins: 0
r/p/s/q? r
You chose: rock
I chose: scissors
You win.
 
My wins: 1 Ties: 0 Your wins: 1
r/p/s/q? r
You chose: rock
I chose: paper
I win.
 
My wins: 2 Ties: 0 Your wins: 1
r/p/s/q? r
You chose: rock
I chose: rock
Tie!
 
My wins: 2 Ties: 1 Your wins: 1
r/p/s/q? r
You chose: rock
I chose: rock
Tie!
 
My wins: 2 Ties: 2 Your wins: 1
r/p/s/q? r
You chose: rock
I chose: paper
I win.
 
My wins: 3 Ties: 2 Your wins: 1
r/p/s/q? r
You chose: rock
I chose: paper
I win.
 
My wins: 4 Ties: 2 Your wins: 1
r/p/s/q? q
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
include random.fs
 
0 value aiwins
0 value plwins
 
10 constant inlim
0 constant rock
1 constant paper
2 constant scissors
 
create rpshistory 0 , 0 , 0 ,
create inversemove 1 , 2 , 0 ,
3 constant historylen
 
: @a ( n array -- )
swap cells + @ ;
 
: sum-history ( -- n )
0 historylen 0 ?do
i rpshistory @a 1+ + loop ;
 
: probable-choice ( -- n ) \ Simple linear search
sum-history random
historylen 0 ?do
i rpshistory @a -
dup 0< if drop i leave then
loop inversemove @a ;
 
: rps-print ( addr u -- )
cr type ;
 
: rpslog. ( -- )
s" ROCK PAPER SCISSORS AI/W PL/W" rps-print cr
3 0 do i cells rpshistory + @ 9 u.r loop aiwins 7 u.r plwins 6 u.r cr ;
 
create rpswords ' rock , ' paper , ' scissors , ' quit ,
 
: update-history! ( n -- )
cells rpshistory + 1 swap +! ;
 
: thrown. ( n -- addr u )
cells rpswords + @ name>string ;
 
: throws. ( n n -- )
thrown. s" AI threw: " 2swap s+ rps-print
thrown. s" You threw: " 2swap s+ rps-print ;
 
: print-throws ( n n -- )
rpslog. throws. ;
 
: tie. ( n n -- )
s" Tie. " rps-print ;
 
: plwin ( n n -- )
1 +to plwins s" You win. " rps-print ;
 
: aiwin ( n n -- )
1 +to aiwins s" AI wins. " rps-print ;
 
create rpsstates ' tie. , ' plwin , ' aiwin ,
 
: determine-winner ( n n -- )
>r abs r> abs - 3 + 3 mod
cells rpsstates + @ execute ;
 
: rps-validate ( name -- ) ( Rude way of checking for only valid commands )
4 0 do i cells rpswords + @ over = swap loop drop or or or ;
 
: rps-prompt. ( -- )
s" Enter choice (rock, paper, scissors or quit): " rps-print ;
 
: player-choice ( -- n ) recursive
pad inlim accept pad swap find-name
dup rps-validate if execute
else drop rps-prompt. player-choice then ;
 
: update-log ( n n -- )
update-history! update-history! ;
 
: rps ( -- ) recursive
rps-prompt. player-choice probable-choice
2dup update-log 2dup print-throws
determine-winner rps ;
</syntaxhighlight>
<pre>
 
Enter choice (rock, paper, scissors): rock
rock
ROCK PAPER SCISSORS AI/W PL/W
34 12 8 12 8
 
AI threw: rock
You threw: rock
Tie.
 
</pre>
=={{header|Fortran}}==
Please find an example run in a GNU/linux system along with compilation instructions at the beginning of the FORTRAN 2008 source code. Following the source are examples demonstrating the effectiveness of the built in simple predictive artificial intelligence. It uses the yes utility for a constant data source.
<syntaxhighlight lang="fortran">
! compilation
! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
! EXAMPLE
!
!$ ./f
!rock, paper, scissors? papier
!scoring computer choice (r) and your choice (p)
!rock, paper, scissors? sizzerz
!scoring computer choice (s) and your choice (s)
!rock, paper, scissors? quit
!scoring computer choice (r) and your choice (q)
! Who's keeping score anyway???
! 0.5 1.5
! you won!
!$
 
 
 
program rpsgame
 
integer, parameter :: COMPUTER=1, HAPLESSUSER=2
integer, dimension(3) :: rps = (/1,1,1/)
real, dimension(3) :: p
character :: answer, cc ! computer choice
integer :: exhaustion, i
real, dimension(2) :: score = (/0, 0/)
character(len=8), dimension(3) :: choices = (/'rock ','paper ','scissors'/)
real :: harvest
do exhaustion = 1, 30
p = rps/real(sum(rps))
p(2) = p(2) + p(1)
p(3) = p(3) + p(2)
call random_number(harvest)
i = sum(merge(1,0,harvest.le.p)) ! In memory of Ken Iverson, logical is more useful as integer.
cc = 'rsp'(i:i)
write(6, "(2(A,', '),A,'? ')", advance='no')(trim(choices(i)),i=1,size(choices))
read(5, *) answer
write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer
if (answer.eq.cc) then
score = score + 0.5
else
i = HAPLESSUSER
if (answer.eq.'r') then
if (cc.eq.'p') i = COMPUTER
else if (answer.eq.'p') then
if (cc.eq.'s') i = COMPUTER
else if (answer.eq.'s') then
if (cc.eq.'r') i = COMPUTER
else
exit
endif
score(i) = score(i) + 1
end if
i = scan('rps',answer)
rps(i) = rps(i) + 1
end do
if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull"
write(6, *)"Who's keeping score anyway???"
write(6, '(2f5.1)') score
if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won!'
end program rpsgame
</syntaxhighlight>
rpsgame won't play more than 30 games at a time.
<syntaxhighlight lang="bash">
$ yes r | ./f # rock
rock, paper, scissors? scoring computer choice (r) and your choice (r)
rock, paper, scissors? scoring computer choice (s) and your choice (r)
rock, paper, scissors? scoring computer choice (r) and your choice (r)
...
rock, paper, scissors? scoring computer choice (p) and your choice (r)
I'm bored out of my skull
Who's keeping score anyway???
25.5 4.5
yes: standard output: Broken pipe
yes: write error
$ yes p 2>/dev/null | ./f # paper
rock, paper, scissors? scoring computer choice (r) and your choice (p)
rock, paper, scissors? scoring computer choice (s) and your choice (p)
rock, paper, scissors? scoring computer choice (r) and your choice (p)
rock, paper, scissors? scoring computer choice (s) and your choice (p)
...
rock, paper, scissors? scoring computer choice (s) and your choice (p)
I'm bored out of my skull
Who's keeping score anyway???
25.5 4.5
$ yes scissors 2>/dev/null | ./f # scissors
rock, paper, scissors? scoring computer choice (r) and your choice (s)
rock, paper, scissors? scoring computer choice (r) and your choice (s)
...
rock, paper, scissors? scoring computer choice (r) and your choice (s)
I'm bored out of my skull
Who's keeping score anyway???
26.5 3.5
$
</syntaxhighlight>
 
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<syntaxhighlight lang="freebasic">Dim Shared As Byte ganador = 1, accion = 2, perdedor = 3, wp, wc
Dim Shared As String word(10, 3)
For n As Byte = 0 To 9
Read word(n, ganador), word(n, accion), word(n, perdedor)
Next n
 
Sub SimonSay(n As Byte)
Print Using "\ \ \ \ "; word(n, ganador); word(n, accion); word(n, perdedor)
End Sub
 
Sub Puntuacion()
Print !"\nPlayer = "; wp; !"\tComputer = "; wc; !"\n"
End Sub
 
Dim As Byte n
Dim As String*1 k
Dim As String eleccionCPU, eleccionJUG
Randomize Timer
Do
Cls
eleccionCPU = word(Rnd *10, ganador)
 
Print !"'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
For n = 0 To 9
SimonSay(n)
Next n
 
Print !"\nType your choice letter:"
Input !"(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit ", k
k = Ucase(k)
Select Case k
Case "Q"
Exit Do
Case "R"
eleccionJUG = "Rock"
Case "P"
eleccionJUG = "Paper"
Case "S"
eleccionJUG = "Scissors"
Case "L"
eleccionJUG = "Lizard"
Case "K"
eleccionJUG = "Spock"
End Select
Print !"\nPlayer chose "; eleccionJUG; " and Computer chose "; eleccionCPU
For n = 0 To 9
If word(n, ganador) = eleccionJUG And word(n, perdedor) = eleccionCPU Then
SimonSay(n)
Print !"\nWinner was Player"
wp += 1
Exit For
Elseif word(n, ganador) = eleccionCPU And word(n, perdedor) = eleccionJUG Then
SimonSay(n)
Print !"\nWinner was Computer"
wc += 1
Exit For
End If
Next n
If n = 10 Then Print !"\nOuch!"
Puntuacion()
Print "Press <SPACE> to continue"
Sleep
Loop Until(k = "Q")
 
Cls
Puntuacion()
If wp > wc Then
Print "Player win"
Elseif wc > wp Then
Print "Computer win"
Else
Print "Tie"
End If
Sleep
End
 
Data "Scissors","cuts","Paper"
Data "Paper","covers","Rock"
Data "Rock","crushes","Lizard"
Data "Lizard","poisons","Spock"
Data "Spock","smashes","Scissors"
Data "Scissors","decapites","Lizard"
Data "Lizard","eats","Paper"
Data "Paper","disproves","Spock"
Data "Spock","vaporizes","Rock"
Data "Rock","blunts","Scissors"</syntaxhighlight>
 
 
=={{header|GlovePIE}}==
You can only press the R, P or S key to advance.
<syntaxhighlight lang="glovepie">if var.end=0 then
var.end=0
var.computerchoice=random(3) // 1 is rock, 2 is paper, and 3 is scissors.
debug="Press the R key for rock, the P key for paper, or the S key for scissors:"
endif
if pressed(Key.R)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="You chose rock, which the computer also chose, so it's a tie!"
else
if var.computerchoice=2 then
debug="The computer chose paper, covering your choice of rock, so you lose!"
else
debug="You chose rock, smashing the computer's choice of scissors, so you win!"
endif
endif
endif
if pressed(Key.P)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="You chose paper, covering the computer's choice of rock, so you win!"
else
if var.computerchoice=2 then
debug="You chose paper, which the computer also chose, so it's a tie!"
else
debug="The computer chose scissors, cutting your choice of paper, so you lose!"
endif
endif
endif
if pressed(Key.S)and var.end=0 then
var.end=1
if var.computerchoice=1 then
debug="The computer chose rock, smashing your choice of scissors, so you lose!"
else
if var.computerchoice=2 then
debug="You chose scissors, cutting the computer's choice of paper, so you win!"
else
debug="You chose scissors, which the computer also chose, so it's a tie!"
endif
endif
endif</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,195 ⟶ 2,357:
}
}
}</langsyntaxhighlight>
{{out|Sample output:}}
<pre>
Rock Paper Scissors
Line 1,215 ⟶ 2,377:
1:2 Play:
</pre>
Additional weapons:
<syntaxhighlight lang="go">package main
 
import (
=={{header|Haskell}}==
"flag"
"fmt"
"log"
"math/rand"
"regexp"
"strings"
"time"
 
"github.com/BurntSushi/toml"
<lang haskell>import System.Random
)
 
var help = `rps plays rock-paper-scissors with optional addition weapons.
 
Usage: rps [-h] [game]
-h display help.
game is a game description file in TOML (https://github.com/mojombo/toml).
 
The traditional game can be described as
 
title = "Rock Paper Scissors"
win = [
"rock breaks scissors",
"paper covers rock",
"scissors cut paper",
]
 
The title is optional, it just prints out at the beginning of a game.
 
The "win" list is statments where the first word wins over the last word.
 
It's case sensitive so make things easy by using consistent case.
Don't use punctuation, at least not next to a first or last word.
 
Additionally, you can have a "lose" key where the first word loses to the
the last, for example
 
lose = ["rock falls into well"]
 
To organize things with additional weapons, you can just use the winning
weapon with a list of clauses, for example
 
lizard = ["poisons Spock", "eats paper"]
 
The progam ignores anything in parentheses when identifying first or last
words. Examples (from RPS-101) with weapons gun, fire, and sword,
 
win = [
"gun fire(s)"
"(flaming) sword has fire"
]
 
Finally, TOML is a hash, so don't duplicate keys. That means no multiple
win or lose keys. You must combine all the win statements and all the lose
statements.`
 
var rps = `
title = "Rock Paper Scissors"
win = [
"rock breaks scissors",
"paper covers rock",
"scissors cut paper",
]`
 
func main() {
h := flag.Bool("h", false, "show help")
flag.Parse()
if *h {
fmt.Println(help)
return
}
m := map[string]interface{}{}
var err error
switch flag.NArg() {
case 0:
_, err = toml.Decode(rps, &m)
case 1:
_, err = toml.DecodeFile(flag.Arg(0), &m)
default:
flag.Usage()
return
}
if err != nil {
log.Fatal(err)
}
play(parse(m))
}
 
type decision map[string]map[string]string
 
type fIndex map[string]int
 
func parse(m map[string]interface{}) (title string, f fIndex, d decision) {
d = decision{}
for k, v := range m {
switch t := v.(type) {
case []interface{}:
d.parseList(k, t)
case string:
if k == "title" {
title = t
} else {
log.Println("Unknown key:", k)
}
}
}
i := 0
f = fIndex{}
for w, wl := range d {
if _, ok := f[w]; !ok {
f[w] = i
i++
}
for l := range wl {
if _, ok := f[l]; !ok {
f[l] = i
i++
}
}
}
for fm := range f {
if _, ok := d[fm]; !ok {
log.Println("note,", fm, "always loses!")
}
}
balanced := len(f)&1 == 1
for _, l := range d {
if !balanced {
break
}
balanced = len(l)*2+1 == len(f)
}
if !balanced {
log.Print("note, game is unbalanced")
}
return title, f, d
}
var r = regexp.MustCompile(`[(].*[)]`)
func (d decision) parseList(kw string, l []interface{}) {
var ww string
for _, e := range l {
st, ok := e.(string)
if !ok {
log.Fatal("invalid", e)
}
w := strings.Fields(r.ReplaceAllLiteralString(st, ""))
if len(w) == 0 {
log.Fatalln("invalid:", kw, st)
}
lw := w[len(w)-1]
switch kw {
case "win":
ww = w[0]
case "lose":
ww, lw = lw, w[0]
default:
ww = kw
for i := 0; ; i++ {
if i == len(w) {
st = ww + " " + st
break
}
if w[i] == ww {
break
}
}
}
if lw == ww {
log.Fatalln("invalid:", st)
}
if cs, ok := d[lw][ww]; ok {
log.Fatalln("conflict:", cs, "and", st)
}
d1, ok := d[ww]
if !ok {
d1 = map[string]string{}
}
d1[lw] = st
d[ww] = d1
}
}
 
func play(title string, fx fIndex, d decision) {
rand.Seed(time.Now().Unix())
if len(fx) == 0 {
return
}
form := make([]string, len(fx))
for w, i := range fx {
form[i] = w
}
fmt.Println()
fmt.Println(title)
fmt.Print("Choices are ", form[0])
for _, w := range form[1:] {
fmt.Printf(", %s", w)
}
fmt.Println(".")
fmt.Println("Enter one of these choices as your play. " +
"Anything else ends the game.")
fmt.Println("Running score shown as <your wins>:<my wins>")
var pw string
var aScore, pScore int
sl := 3
wcf := make([]int, len(form))
wct := 0
ax := rand.Intn(len(form))
aw := form[ax]
for {
fmt.Print("Play: ")
_, err := fmt.Scanln(&pw)
if err != nil {
break
}
px, ok := fx[pw]
if !ok {
fmt.Println(pw, "invalid.")
break
}
for f, l := range d {
if _, ok := l[pw]; ok {
wcf[fx[f]]++
wct++
}
}
 
fmt.Printf("My play:%s%s.\n", strings.Repeat(" ", sl-2), aw)
ast := d[aw][pw]
pst := d[pw][aw]
switch {
case ax == px:
fmt.Println("Tie.")
case ast > "" && pst > "":
log.Fatalln("conflict: ", ast, "and", pst)
case ast > "":
fmt.Printf("%s. My point.\n", ast)
aScore++
default:
fmt.Printf("%s. Your point.\n", pst)
pScore++
}
sl, _ = fmt.Printf("%d:%d ", pScore, aScore)
ax = 0
for rn := rand.Intn(wct); ; ax++ {
if f := wcf[ax]; rn < f {
break
} else {
rn -= f
}
}
aw = form[ax]
}
}</syntaxhighlight>
Example game files:
<pre>
# example unbalanced game described with both win and lose statements
 
title = "Rock Paper Scissors Well"
win = [
"rock breaks scissors",
"paper covers rock",
"paper covers well",
"scissors cut paper",
]
lose = [
"rock falls into well",
"scissors fall into well",
]
</pre>
<pre>
# example with implied wins, parenthetical word.
 
title = "RPS-7"
rock = [
"pounds out fire",
"crushes scissors",
"crushes sponge",
]
fire = [
"melts scissors",
"burns paper",
"burns sponge",
]
scissors = [
"swish through air",
"cut paper",
"cut sponge",
]
sponge = [
"soaks paper",
"uses air (pockets)",
"absorbs water",
]
paper = [
"fans air",
"covers rock",
"floats on water",
]
air = [
"blows out fire",
"erodes rock",
"evaporates water",
]
water = [
"erodes rock",
"puts out fire",
"rusts scissors",
]
</pre>
{{out|Example output}}
<pre>
> rps rpsw
2014/05/20 20:42:03 note, game is unbalanced
 
Rock Paper Scissors Well
Choices are rock, scissors, paper, well.
Enter one of these choices as your play. Anything else ends the game.
Running score shown as <your wins>:<my wins>
Play: rock
My play: rock.
Tie.
0:0 Play: well
My play: paper.
paper covers well. My point.
0:1 Play: scissors
My play: paper.
scissors cut paper. Your point.
1:1 Play: well
My play: paper.
paper covers well. My point.
1:2 Play:
 
> rps rps7
 
RPS-7
Choices are rock, scissors, sponge, fire, paper, air, water.
Enter one of these choices as your play. Anything else ends the game.
Running score shown as <your wins>:<my wins>
Play: air
My play: water.
air evaporates water. Your point.
1:0 Play:
</pre>
 
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">import System.Random (randomRIO)
data Choice = Rock | Paper | Scissors
deriving (Show, Eq)
 
data Choice
= Rock
| Paper
| Scissors
deriving (Show, Eq)
 
beats :: Choice -> Choice -> Bool
beats Paper Rock = True
beats Scissors Paper = True
Line 1,229 ⟶ 2,742:
beats _ _ = False
 
genrps :: (rInt,p Int,s) = fmapInt) rps-> randIO Choice
genrps (r, p, s) = rps <$> rand
where rps x | x <= s = Rock
where
| x <= s+r = Paper
rps x
| otherwise = Scissors
| x rand <= randomRIO (1,r+p+s) :: IO= IntRock
| x <= s + r = Paper
| otherwise = Scissors
rand = randomRIO (1, r + p + s) :: IO Int
 
getrps =:: fmap rps getLineIO Choice
getrps = rps <$> getLine
where rps "scissors" = Scissors
where
rps "rock" = Rock
rps "paperscissors" = PaperScissors
rps _"rock" = error "invalid input"Rock
rps "paper" = Paper
rps _ = error "invalid input"
 
game :: (Int, Int, Int) -> IO a
game (r,p,s) = do putStrLn "rock, paper or scissors?"
game (r, p, s) = do
h <- getrps
putStrLn "rock, paper or scissors?"
c <- genrps (r,p,s)
h <- getrps
putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c)
c <- genrps (r, p, s)
putStrLn (if beats h c then "player wins\n"
putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c)
else if beats c h then "player loses\n"
putStrLn
else "draw\n")
(if beats h c
let rr = if h == Rock then r+1 else r
pp = if h == Paper then p+1 else"player pwins\n"
else if beats c h
ss = if h == Scissors then s+1 else s
then "player game (rr,pp,ss)loses\n"
else "draw\n")
let rr =
if h == Rock
then r + 1
else r
pp =
if h == Paper
then p + 1
else p
ss =
if h == Scissors
then s + 1
else s
game (rr, pp, ss)
 
main =:: gameIO (1,1,1)</lang>a
main = game (1, 1, 1)</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The key to this comes down to two structures and two lines of code. The player history ''historyP'' is just an ordered list of every player turn and provides the weight for the random selection. The ''beats'' list is used to rank moves and to choose the move that would beat the randomly selected move.
<langsyntaxhighlight Iconlang="icon">link printf
 
procedure main()
Line 1,297 ⟶ 2,830:
printf("\nResults:\n %d rounds\n %d Draws\n %d Computer wins\n %d Player wins\n",
winP+winC+draws,draws,winC,winP)
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
Line 1,328 ⟶ 2,861:
1 Computer wins
1 Player wins</pre>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "Rock.bas"
110 RANDOMIZE
120 STRING CH$(1 TO 3)*8,K$*1
130 NUMERIC PLWINS(1 TO 3),SCORE(1 TO 3),PLSTAT(1 TO 3),CMSTAT(1 TO 3),PLCHOICE,CMCHOICE
140 CALL INIC
150 DO
160 CALL GUESS
170 PRINT :PRINT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors, ESC = quit)"
180 DO
190 LET K$=INKEY$
200 LOOP UNTIL K$>="1" AND K$<="3" OR K$=CHR$(27)
210 IF K$=CHR$(27) THEN EXIT DO
220 LET PLCHOICE=VAL(K$)
230 LET CMSTAT(CMCHOICE)=CMSTAT(CMCHOICE)+1:LET PLSTAT(PLCHOICE)=PLSTAT(PLCHOICE)+1
240 PRINT "You chose ";CH$(PLCHOICE);" and I chose ";CH$(CMCHOICE);"."
250 SET #102:INK 3
260 IF PLCHOICE=CMCHOICE THEN
270 PRINT "Tie!"
280 LET SCORE(3)=SCORE(3)+1
290 ELSE IF CMCHOICE=PLWINS(PLCHOICE) THEN
300 PRINT "You won!"
310 LET SCORE(1)=SCORE(1)+1
320 ELSE
330 PRINT "I won!"
340 LET SCORE(2)=SCORE(2)+1
350 END IF
360 SET #102:INK 1
370 LOOP
380 PRINT :PRINT "Some useless statistics:"
390 PRINT "You won";SCORE(1);"times, and I won";SCORE(2);"times;";SCORE(3);"ties."
400 PRINT :PRINT ,,CH$(1),CH$(2),CH$(3)
410 PRINT "You chose:",PLSTAT(1),PLSTAT(2),PLSTAT(3)
420 PRINT " I chose:",CMSTAT(1),CMSTAT(2),CMSTAT(3)
430 END
440 DEF INIC
450 LET CH$(1)="rock":LET CH$(2)="paper":LET CH$(3)="scissors"
460 LET PLWINS(1)=3:LET PLWINS(2)=1:LET PLWINS(3)=2
470 FOR I=1 TO 3
480 LET PLSTAT(I),CMSTAT(I),SCORE(I)=0
490 NEXT
500 TEXT 80
510 END DEF
520 DEF GUESS
530 LET CMCHOICE=INT(RND*(PLSTAT(1)+PLSTAT(2)+PLSTAT(3)+3))
540 SELECT CASE CMCHOICE
550 CASE 0 TO PLSTAT(1)
560 LET CMCHOICE=2
570 CASE PLSTAT(1)+1 TO PLSTAT(1)+PLSTAT(2)+1
580 LET CMCHOICE=3
590 CASE ELSE
600 LET CMCHOICE=1
610 END SELECT
620 END DEF</syntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j">require'general/misc/prompt strings' NB. was 'misc strings' in older versions of J
game=:3 :0
outcomes=. rps=. 0 0 0
Line 1,349 ⟶ 2,937:
end.
('Draws:','My wins:',:'Your wins: '),.":,.outcomes
)</langsyntaxhighlight>
 
Example use (playing to give the computer implementation the advantage):
 
<langsyntaxhighlight lang="j"> game''
Choose Rock, Paper or Scissors: rock
I choose Scissors
Line 1,372 ⟶ 2,960:
Draws: 0
My wins: 4
Your wins: 1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
This could probably be made simpler, but some more complexity is necessary so that other items besides rock, paper, and scissors can be added (as school children and nerds like to do [setup for rock-paper-scissors-lizard-spock is in multi-line comments]). The method <code>getAIChoice()</code> borrows from [[#Ada|the Ada example]] in spirit, but is more generic to additional items.
<langsyntaxhighlight lang="java5">import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
Line 1,455 ⟶ 3,043:
return null;
}
}</langsyntaxhighlight>
Sample output:
<pre>Make your choice: rock
Line 1,494 ⟶ 3,082:
You chose...wisely. You win!
...</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
const logic = {
rock: { w: 'scissor', l: 'paper'},
paper: {w:'rock', l:'scissor'},
scissor: {w:'paper', l:'rock'},
}
 
class Player {
constructor(name){
this.name = name;
}
setChoice(choice){
this.choice = choice;
}
challengeOther(PlayerTwo){
return logic[this.choice].w === PlayerTwo.choice;
}
}
 
const p1 = new Player('Chris');
const p2 = new Player('John');
 
p1.setChoice('rock');
p2.setChoice('scissor');
 
p1.challengeOther(p2); //true (Win)
</syntaxhighlight>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
<syntaxhighlight lang=jq>
# To quit, enter a blank line or type "q" or "quit"
def choices: ["r", "p", "s", "q"];
 
# The main source of entropy for this pseudo pseudo random number generator is the player :-)
# PRN in range(0;3)
def rand: now * 100 | floor | tostring[-2:] | tonumber % 3;
 
def tallies:
{pWins: 0, # player wins
cWins: 0, # computer wins
draws: 0, # neither wins
games: 0, # games played
pFreqs: [0, 0, 0] # player frequencies for each choice (rps)
};
 
# Update the tallies and populate .emit
def update($pChoice; $cChoice):
if $pChoice == "r" and $cChoice == "s"
then .emit += "Rock breaks scissors - You win!"
| .pWins += 1
elif $pChoice == "p" and $cChoice == "r"
then .emit += "Paper covers rock - You win!"
| .pWins += 1
elif $pChoice == "s" and $cChoice == "p"
then .emit += "Scissors cut paper - You win!"
| .pWins += 1
elif $pChoice == "s" and $cChoice == "r"
then .emit += "Rock breaks scissors - Computer wins!"
| .cWins += 1
elif $pChoice == "r" and $cChoice == "p"
then .emit += "Paper covers rock - Computer wins!"
| .cWins += 1
elif $pChoice == "p" and $cChoice == "s"
then .emit += "Scissors cut paper - Computer wins!"
| .cWins += 1
else .emit += "It's a draw!"
| .draws += 1
end
| .pFreqs[choices|index($pChoice)] += 1
| .games += 1 ;
 
def printScore:
"Wins: You \(.pWins), Computer \(.cWins), Neither \(.draws)\n";
 
 
def getComputerChoice:
# make a completely random choice until 3 games have been played
if .games < 3 then choices[rand]
else .games as $games
| (.pFreqs | map(3 * . / $games)) as $pFreqs
| rand as $num
| if $num < $pFreqs[0] then "p"
elif $num < $pFreqs[0] + $pFreqs[1] then "s"
else "r"
end
end ;
 
# Get player's choice (empty line or q or quit to quit).
# Return false if the choice is not recognized.
def pChoice:
(first(inputs) // null) as $in
| if $in == null or $in == "q" or $in == "quit" then null
else ($in|ascii_downcase) as $in
| if any(choices[]; . == $in) then $in
else false
end
end;
 
# Solicit input
def prompt:
if .games == 0
then "Enter: (r)ock, (p)aper, (s)cissors or (q)uit"
else printScore + "---\n\nYour choice r/p/s/q : "
end;
 
def play:
label $out
| foreach range(1; infinite) as $i (tallies ;
# if .prompt then it is time to get input:
if .prompt
then pChoice as $pChoice
| if $pChoice == null
then .prompt = false
| .emit = "OK, quitting", break $out
elif $pChoice == false
then .emit = "Valid responses are one of r p s q\nPlease try again."
else getComputerChoice as $cChoice
| .prompt = false
| .emit = "Computer's choice : \($cChoice)\n"
| update($pChoice; $cChoice)
end
else .prompt = prompt
| .emit = null
end )
 
| select(.emit).emit,
select(.prompt).prompt ;
 
play
</syntaxhighlight>
 
'''Invocation:''' jq -nrR -f rock-paper-scissors.jq
 
'''Sample game'''
<pre>
Enter: (r)ock, (p)aper, (s)cissors or (q)uit
?
Valid responses are one of r p s q
Please try again.
Enter: (r)ock, (p)aper, (s)cissors or (q)uit
r
Computer's choice : r
It's a draw!
Wins: You 0, Computer 0, Neither 1
---
 
Your choice r/p/s/q :
p
Computer's choice : s
Scissors cut paper - Computer wins!
Wins: You 0, Computer 1, Neither 1
---
 
Your choice r/p/s/q :
s
Computer's choice : s
It's a draw!
Wins: You 0, Computer 1, Neither 2
---
 
Your choice r/p/s/q :
OK, quitting
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function rps()
print("Welcome to Rock, paper, scissors! Go ahead and type your pick.\n
r(ock), p(aper), or s(cissors)\n
Line 1,518 ⟶ 3,272:
end
end
end</langsyntaxhighlight>
<pre>julia> rps()
Welcome to Rock, paper, scissors! Go ahead and type your pick.
Line 1,541 ⟶ 3,295:
you 2
me 1</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.2.10
 
import java.util.Random
 
const val choices = "rpsq"
val rand = Random()
 
var pWins = 0 // player wins
var cWins = 0 // computer wins
var draws = 0 // neither wins
var games = 0 // games played
val pFreqs = arrayOf(0, 0, 0) // player frequencies for each choice (rps)
 
fun printScore() = println("Wins: You $pWins, Computer $cWins, Neither $draws\n")
 
fun getComputerChoice(): Char {
// make a completely random choice until 3 games have been played
if (games < 3) return choices[rand.nextInt(3)]
val num = rand.nextInt(games)
return when {
num < pFreqs[0] -> 'p'
num < pFreqs[0] + pFreqs[1] -> 's'
else -> 'r'
}
}
 
fun main(args: Array<String>) {
println("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n")
while (true) {
printScore()
var pChoice: Char
while (true) {
print("Your choice r/p/s/q : ")
val input = readLine()!!.toLowerCase()
if (input.length == 1) {
pChoice = input[0]
if (pChoice in choices) break
}
println("Invalid choice, try again")
}
if (pChoice == 'q') {
println("OK, quitting")
return
}
val cChoice = getComputerChoice()
println("Computer's choice : $cChoice")
if (pChoice == 'r' && cChoice == 's') {
println("Rock breaks scissors - You win!")
pWins++
}
else if (pChoice == 'p' && cChoice == 'r') {
println("Paper covers rock - You win!")
pWins++
}
else if (pChoice == 's' && cChoice == 'p') {
println("Scissors cut paper - You win!")
pWins++
}
else if (pChoice == 's' && cChoice == 'r') {
println("Rock breaks scissors - Computer wins!")
cWins++
}
else if (pChoice == 'r' && cChoice == 'p') {
println("Paper covers rock - Computer wins!")
cWins++
}
else if (pChoice == 'p' && cChoice == 's') {
println("Scissors cut paper - Computer wins!")
cWins++
}
else {
println("It's a draw!")
draws++
}
pFreqs[choices.indexOf(pChoice)]++
games++
println()
}
}</syntaxhighlight>
 
Sample session:
<pre>
Enter: (r)ock, (p)aper, (s)cissors or (q)uit
 
Wins: You 0, Computer 0, Neither 0
 
Your choice r/p/s/q : r
Computer's choice : r
It's a draw!
 
Wins: You 0, Computer 0, Neither 1
 
Your choice r/p/s/q : p
Computer's choice : s
Scissors cut paper - Computer wins!
 
Wins: You 0, Computer 1, Neither 1
 
Your choice r/p/s/q : p
Computer's choice : r
Paper covers rock - You win!
 
Wins: You 1, Computer 1, Neither 1
 
Your choice r/p/s/q : s
Computer's choice : s
It's a draw!
 
Wins: You 1, Computer 1, Neither 2
 
Your choice r/p/s/q : p
Computer's choice : p
It's a draw!
 
Wins: You 1, Computer 1, Neither 3
 
Your choice r/p/s/q : q
OK, quitting
</pre>
 
=={{header|Lasso}}==
Notes: This implementation uses the default session handling in Lasso, and assumes it's running on a web server. User choices are passed in via HTTP as GET query parameters.
<syntaxhighlight lang="lasso">session_start('user')
session_addvar('user', 'historic_choices')
session_addvar('user', 'win_record')
session_addvar('user', 'plays')
var(historic_choices)->isNotA(::map) ? var(historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0))
var(plays)->isNotA(::integer) ? var(plays = 0)
var(win_record)->isNotA(::array) ? var(win_record = array)
 
define br => '<br>'
define winner(c::string,p::string) => {
if(#c == $superior->find(#p)) => {
$win_record->insert('lasso')
return 'Lasso'
else(#p == $superior->find(#c))
$win_record->insert('user')
return 'User'
else
$win_record->insert('tie')
return 'Nobody'
}
}
var(
choice = web_request->param('choice')->asString,
lookup = array('rock', 'paper', 'scissors'),
computer_choice = $lookup->get(math_random(3,1)),
superior = map('rock'='paper', 'paper'='scissors', 'scissors'='rock'),
controls = '<a href=?choice=rock>Rock</a> <a href=?choice=paper>Paper</a> <a href=?choice=scissors>Scissors</a> <a href=?choice=quit>Quit</a><br/>'
)
if($choice == 'quit') => {^
'See ya. <a href=?>Start over</a>'
session_end('user')
$historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0)
$plays = 0
$win_record = array
else(array('rock','paper','scissors') >> $choice)
$controls
if($plays != 0) => {
local('possibilities') = array
with i in $lookup do => {
loop($historic_choices->find(#i)) => { #possibilities->insert(#i) }
}
$computer_choice = $superior->find(#possibilities->get(math_random($plays,1)))
}
'User chose ' + $choice + br
'Lasso chose ' + $computer_choice + br
winner($computer_choice->asString, $choice) + ' wins!'
$historic_choices->find($choice) = $historic_choices->find($choice)+1
$plays += 1
else($choice->size == 0)
$controls
else
'Invalid Choice.'+ br + $controls
^}
if($win_record->size) => {^
br
br
'Win record: '+br
'Lasso: '+($win_record->find('lasso')->size)+br
'User: '+($win_record->find('user')->size)+br
'Tie: '+($win_record->find('tie')->size)+br
^}</syntaxhighlight>
{{out}}
<pre>Rock Paper Scissors Quit (<- as links)
User chose paper
Lasso chose rock
User wins!
 
Win record:
Lasso: 2
User: 1
Tie: 3</pre>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim rps( 2), g$( 3)
 
Line 1,632 ⟶ 3,589:
print " Thanks for playing!"
end
</syntaxhighlight>
</lang>
You won 3204, and I won 3669. There were 3128 draws.
I AM THE CHAMPION!!
Line 1,656 ⟶ 3,613:
Can you see what will happen if, say, the 'human' is set to give 'Rock' EVERY time?
Try different %ages by altering the marked code lines.
 
 
=={{header|Locomotive Basic}}==
Line 1,662 ⟶ 3,618:
{{trans|Go}}
 
<langsyntaxhighlight lang="locobasic">10 mode 1:defint a-z:randomize time
20 rps$="rps"
30 msg$(1)="Rock breaks scissors"
Line 1,684 ⟶ 3,640:
210 rn=rnd*plays
220 if rn<pcf(1) then achoice=2 else if rn<pcf(1)+pcf(2) then achoice=3 else achoice=1
230 goto 110</langsyntaxhighlight>
 
=={{header|MathematicaLua}}==
<syntaxhighlight lang="lua">function cpuMove()
<lang mathematica>DynamicModule[{record, play, text = "\nRock-paper-scissors\n",
local totalChance = record.R + record.P + record.S
if totalChance == 0 then -- First game, unweighted random
local choice = math.random(1, 3)
if choice == 1 then return "R" end
if choice == 2 then return "P" end
if choice == 3 then return "S" end
end
local choice = math.random(1, totalChance) -- Weighted random bit
if choice <= record.R then return "P" end
if choice <= record.R + record.P then return "S" end
return "R"
end
function playerMove() -- Get user input for choice of 'weapon'
local choice
repeat
os.execute("cls") -- Windows specific command, change per OS
print("\nRock, Paper, Scissors")
print("=====================\n")
print("Scores -\tPlayer:", score.player)
print("\t\tCPU:", score.cpu .. "\n\t\tDraws:", score.draws)
io.write("\nChoose [R]ock [P]aper or [S]cissors: ")
choice = io.read():upper():sub(1, 1)
until choice == "R" or choice == "P" or choice == "S"
return choice
end
-- Decide who won, increment scores
function checkWinner (c, p)
io.write("I chose ")
if c == "R" then print("rock...") end
if c == "P" then print("paper...") end
if c == "S" then print("scissors...") end
if c == p then
print("\nDraw!")
score.draws = score.draws + 1
elseif (c == "R" and p == "P") or
(c == "P" and p == "S") or
(c == "S" and p == "R") then
print("\nYou win!")
score.player = score.player + 1
else
print("\nYou lose!")
score.cpu = score.cpu + 1
end
end
-- Main procedure
math.randomseed(os.time())
score = {player = 0, cpu = 0, draws = 0}
record = {R = 0, P = 0, S = 0}
local playerChoice, cpuChoice
repeat
cpuChoice = cpuMove()
playerChoice = playerMove()
record[playerChoice] = record[playerChoice] + 1
checkWinner(cpuChoice, playerChoice)
io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ")
until io.read():upper():sub(1, 1) == "Q"</syntaxhighlight>
Session in which I chose nothing but rock:
<pre>
Rock, Paper, Scissors
=====================
 
Scores - Player: 1
CPU: 25
Draws: 0
 
Choose [R]ock [P]aper or [S]cissors: r
I chose paper...
 
You lose!
 
Press ENTER to continue or enter 'Q' to quit . . .
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">DynamicModule[{record, play, text = "\nRock-paper-scissors\n",
choices = {"Rock", "Paper", "Scissors"}},
Evaluate[record /@ choices] = {1, 1, 1};
Line 1,698 ⟶ 3,732:
Alternatives @@ Reverse /@ Partition[choices, 2, 1, 1],
"You win.", _, "Draw."]];
Column@{Dynamic[text], ButtonBar[# :> play[#] & /@ choices]}]</langsyntaxhighlight>
 
=={{header|Mercury}}==
{{trans|Prolog}}
<syntaxhighlight lang="mercury">:- module rps.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- use_module random, exception.
:- import_module list, string.
 
:- type play
---> rock
; paper
; scissors.
 
:- pred beats(play, play).
:- mode beats(in, in) is semidet.
beats(rock, scissors).
beats(paper, rock).
beats(scissors, paper).
 
:- pred random(play::out, random.supply::mdi, random.supply::muo) is det.
random(Play, !RS) :-
random.random(1, 3, N, !RS),
( if N = 1 then
Play = rock
else if N = 2 then
Play = paper
else
Play = scissors
).
 
main(!IO) :-
seed(Seed, !IO),
random.init(Seed, RS),
play(RS, !IO).
 
:- pred play(random.supply::mdi, io::di, io::uo) is det.
play(!.RS, !IO) :-
io.write_string("Your choice? ", !IO),
io.read(Res, !IO),
(
Res = ok(Play),
random(Counter, !RS),
io.format("The computer chose %s\n", [s(string(Counter))], !IO),
( if beats(Counter, Play) then
io.write_string("Computer wins.\n", !IO)
else if beats(Play, Counter) then
io.write_string("You win!\n", !IO)
else
io.write_string("It is a draw\n", !IO)
),
play(!.RS, !IO)
;
Res = eof
;
Res = error(_, _),
exception.throw(Res)
).
 
:- pragma foreign_decl("C", "#include <time.h>").
:- pred seed(int::out, io::di, io::uo) is det.
:- pragma foreign_proc("C",
seed(Seed::out, _IO0::di, _IO::uo),
[promise_pure, will_not_call_mercury],
"
Seed = time(NULL);
").</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import random, strutils, tables
 
type
Choice {.pure.} = enum Rock, Paper, Scissors
History = tuple[total: int; counts: CountTable[Choice]]
 
const Successor: array[Choice, Choice] = [Paper, Scissors, Rock]
 
func `>`(a, b: Choice): bool =
## By construction, only the successor is greater than the choice.
a == Successor[b]
 
proc choose(history: History): Choice =
## Make a weighted random choice using the player counts
## then select the choice likely to beat it.
var value = rand(1..history.total)
for choice, count in history.counts.pairs:
if value <= count:
return Successor[choice]
dec value, count
 
 
randomize()
 
# Initialize history with one for each choice in order to avoid special case.
var history: History = (3, [Rock, Paper, Scissors].toCountTable)
 
echo "To quit game, type 'q' when asked for your choice."
 
var myChoice, yourChoice: Choice
var myWins, yourWins = 0
 
while true:
 
# Get player choice.
try:
stdout.write "Rock(1), paper(2), scissors(3). Your choice? "
let answer = stdin.readLine().strip()
if answer == "q":
quit "Quitting game.", QuitSuccess
if answer notin ["1", "2", "3"]:
echo "Invalid choice."
continue
yourChoice = Choice(ord(answer[0]) - ord('1'))
except EOFError:
quit "Quitting game.", QuitFailure
 
# Make my choice.
myChoice = history.choose()
echo "I choosed ", myChoice, '.'
history.counts.inc yourChoice
inc history.total
 
# Display result of round.
if myChoice == yourChoice:
echo "It’s a tie."
elif myChoice > yourChoice:
echo "I win."
inc myWins
else:
echo "You win."
inc yourWins
echo "Total wins. You: ", yourWins, " Me: ", myWins</syntaxhighlight>
 
{{out}}
<pre>To quit game, type 'q' when asked for your choice.
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Rock.
It’s a tie.
Total wins. You: 0 Me: 0
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Rock.
It’s a tie.
Total wins. You: 0 Me: 0
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 1
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Rock.
It’s a tie.
Total wins. You: 0 Me: 1
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 2
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 3
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 4
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 5
Rock(1), paper(2), scissors(3). Your choice? 1
I choosed Paper.
I win.
Total wins. You: 0 Me: 6
Rock(1), paper(2), scissors(3). Your choice? q
Quitting game.</pre>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 COMPUTER=RND(3)+1
20 COMPUTER$="ROCK"
30 IF COMPUTER=2 THEN COMPUTER$="PAPER"
40 IF COMPUTER=3 THEN COMPUTER$="SCISSORS"
50 INPUT "ROCK, PAPER OR SCISSORS? ",HUMAN$
60 IF HUMAN$="ROCK" THEN GOTO 100
70 IF HUMAN$="PAPER" THEN GOTO 100
80 IF HUMAN$="SCISSORS" THEN GOTO 100
90 PRINT "INVALID GUESS. TRY AGAIN.": GOTO 50
100 PRINT "YOU CHOSE "HUMAN$" AND THE COMPUTER CHOSE "COMPUTER$"."
110 IF HUMAN$=COMPUTER$ THEN PRINT "THOSE ARE THE SAME CHOICES";", SO YOU TIED."
120 IF HUMAN$="ROCK" AND COMPUTER=2 THEN PRINT "PAPER COVERS ROCK, SO YOU LOSE."
130 IF HUMAN$="ROCK" AND COMPUTER=3 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU WIN."
140 IF HUMAN$="PAPER" AND COMPUTER=1 THEN PRINT "PAPER COVERS ROCK, SO YOU WIN."
150 IF HUMAN$="PAPER" AND COMPUTER=3 THEN PRINT "SCISSORS CUT PAPER";", SO YOU LOSE."
160 IF HUMAN$="SCISSORS" AND COMPUTER=1 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU LOSE."
170 IF HUMAN$="SCISSORS" AND COMPUTER=2 THEN PRINT "SCISSORS CUT PAPER, SO YOU WIN."10 COMPUTER=RND(3)+1</syntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang OCaml>
let pf = Printf.printf ;;
 
Line 1,755 ⟶ 3,983:
make_moves 1. 1. 1. ;;
 
</syntaxhighlight>
</lang>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">contest(rounds)={
my(v=[1,1,1],wins,losses); \\ Laplace rule
for(i=1,rounds,
Line 1,792 ⟶ 4,020:
[wins,losses]
};
contest(10)</langsyntaxhighlight>
 
=={{header|Perl 6}}==
The program supports "--quiet" option, which makes it suppress all in-game output (useful for batch testing). At the end of a game it displays detailed statistics.
This is slightly more complicated than it could be; it is a general case framework with input filtering. It weights the computers choices based on your previous choices. Type in at least the first two characters of your choice, or just hit enter to quit. Customize it by supplying your own <tt>%vs</tt> options/outcomes.
<syntaxhighlight lang="perl">
use 5.012;
use warnings;
use utf8;
use open qw(:encoding(utf-8) :std);
use Getopt::Long;
 
package Game {
Here is standard Rock-Paper-Scissors.
use List::Util qw(shuffle first);
 
<lang perl6> my %vs$turns = (0;
my %human_choice = ( rock => 0, paper => 0, scissors => 0, );
options => [<Rock Paper Scissors>],
my %comp_choice = ( rock => 0, paper => 0, scissors => 0, );
ro => {
my %what_beats =
ro => [ 2, '' ],
( parock => [ 1'paper', 'Paperpaper covers Rock:=> 'scissors', scissors => ]'rock', );
my $comp_wins = 0;
sc => [ 0, 'Rock smashes Scissors: ' ]
my $human_wins = 0;
},
pamy $draws => {0;
 
ro => [ 0, 'Paper covers Rock: ' ],
sub save_human_choice {
pa => [ 2, '' ],
scmy $ch => [ 1, 'Scissors cut Paper: ' lc ]pop;
if ( exists $human_choice{ $ch } ) {
},
++$human_choice{ $ch };
sc => {
}
ro => [ 1, 'Rock smashes Scissors: '],
else {
pa => [ 0, 'Scissors cut Paper: ' ],
sc => [ 2, ''die __PACKAGE__ . ":: wrong choice: ]'$ch'";
}
}
);
 
sub get_comp_choice {
my %choices = %vs<options>.map({; $_.substr(0,2).lc => $_ });
my $keys my @keys = %choices.shuffle keys.join('|') %human_choice;
my $ch;
my $prompt = %vs<options>.map({$_.subst(/(\w\w)/,->$/{"[$0]"})}).join(' ')~"? ";
my ( $prob, $rand ) = ( 0, rand );
my %weight = %choices.keys »=>» 1;
$ch = ( first { $rand <= ( $prob += ( $human_choice{ $_ } / $turns ) ) } @keys )
if $turns > 0;
$ch //= $keys[0];
$ch = $what_beats{ $ch };
++$comp_choice{ $ch };
return $ch;
}
 
sub make_turn {
my @stats = 0,0,0;
my ( $comp_ch, $human_ch ) = ( pop(), pop() );
my $round;
++$turns;
if ( $what_beats{ $human_ch } eq $comp_ch ) {
++$comp_wins;
return 'I win!';
}
elsif ( $what_beats{ $comp_ch } eq $human_ch ) {
++$human_wins;
return 'You win!';
}
else {
++$draws;
return 'Draw!';
}
}
 
sub get_final_report {
while my $player = (prompt "Round {++$round}: " ~ $prompt).lc {
my $report =
$player.=substr(0,2);
"You chose:\n"
say 'Invalid choice, try again.' and $round-- and next
. " rock = $human_choice{rock} times,\n"
unless $player.chars == 2 and $player ~~ /<$keys>/;
. " paper = $human_choice{paper} times,\n"
my $computer = %weight.keys.map( { $_ xx %weight{$_} } ).pick;
. " scissors = $human_choice{scissors} times,\n"
%weight{$_.key}++ for %vs{$player}.grep( { $_.value[0] == 1 } );
. "I chose:\n"
my $result = %vs{$player}{$computer}[0];
. " rock = $comp_choice{rock} times,\n"
@stats[$result]++;
. " paper = $comp_choice{paper} times,\n"
say "You chose %choices{$player}, Computer chose %choices{$computer}.";
. " scissors = $comp_choice{scissors} times,\n"
print %vs{$player}{$computer}[1];
. "Turns: $turns\n"
print ( 'You win!', 'You Lose!','Tie.' )[$result];
. "I won: $comp_wins, you won: $human_wins, draws: $draws\n";
say " - (W:{@stats[0]} L:{@stats[1]} T:{@stats[2]})\n",
return $report;
};</lang>Example output:
}
<pre>Round 1: [Ro]ck [Pa]per [Sc]issors? ro
}
You chose Rock, Computer chose Paper.
Paper covers Rock: You Lose! - (W:0 L:1 T:0)
 
sub main {
Round 2: [Ro]ck [Pa]per [Sc]issors? pa
GetOptions( 'quiet' => \my $quiet );
You chose Paper, Computer chose Scissors.
greet() if !$quiet;
Scissors cut Paper: You Lose! - (W:0 L:2 T:0)
while (1) {
print_next_line() if !$quiet;
my $input = get_input();
last unless $input;
if ( $input eq 'error' ) {
print "I don't understand!\n" if !$quiet;
redo;
}
my $comp_choice = Game::get_comp_choice();
Game::save_human_choice($input);
my $result = Game::make_turn( $input, $comp_choice );
describe_turn_result( $input, $comp_choice, $result )
if !$quiet;
}
print Game::get_final_report();
}
 
sub greet {
Round 3: [Ro]ck [Pa]per [Sc]issors? pa
print "Welcome to the Rock-Paper-Scissors game!\n"
You chose Paper, Computer chose Scissors.
. "Choose 'rock', 'paper' or 'scissors'\n"
Scissors cut Paper: You Lose! - (W:0 L:3 T:0)
. "Enter empty line or 'quit' to quit\n";
}
 
sub print_next_line {
Round 4: [Ro]ck [Pa]per [Sc]issors? ro
print 'Your choice: ';
You chose Rock, Computer chose Rock.
}
Tie. - (W:0 L:3 T:1)
 
sub get_input {
Round 5: [Ro]ck [Pa]per [Sc]issors? sc
my $input = <>;
You chose Scissors, Computer chose Scissors.
print "\n" and return if !$input; # EOF
Tie. - (W:0 L:3 T:2)
chomp $input;
...</pre>
return if !$input or $input =~ m/\A \s* q/xi;
return
( $input =~ m/\A \s* r/xi ) ? 'rock'
: ( $input =~ m/\A \s* p/xi ) ? 'paper'
: ( $input =~ m/\A \s* s/xi ) ? 'scissors'
: 'error';
}
 
sub describe_turn_result {
Here is example output from the same code only with a different %vs data structure implementing [http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock Rock-Paper-Scissors-Lizard-Spock].
my ( $human_ch, $comp_ch, $result ) = @_;
print "You chose \u$human_ch, I chose \u$comp_ch. $result\n";
}
 
main();
<lang perl6>my %vs = (
</syntaxhighlight>
options => [<Rock Paper Scissors Lizard Spock>],
Example input can be generated as follows:
ro => {
<syntaxhighlight lang="bash">
ro => [ 2, '' ],
perl -e '@c=qw(r p s); for(1..10000){ print $c[ rand() < 0.75 ? 0 : int rand(2) + 1 ], "\n" }' | perl rps.pl --quiet
pa => [ 1, 'Paper covers Rock: ' ],
</syntaxhighlight>
sc => [ 0, 'Rock smashes Scissors: ' ],
Output:
li => [ 0, 'Rock crushes Lizard: ' ],
<pre>
sp => [ 1, 'Spock vaporizes Rock: ' ]
You chose:
},
rock pa => {7542 times,
paper = 1204 times,
ro => [ 0, 'Paper covers Rock: ' ],
scissors = 1254 times,
pa => [ 2, '' ],
I chose:
sc => [ 1, 'Scissors cut Paper: ' ],
rock = 1275 times,
li => [ 1, 'Lizard eats Paper: ' ],
paper = 7460 times,
sp => [ 0, 'Paper disproves Spock: ' ]
scissors = }1265 times,
Turns: 10000
sc => {
I won: 5920, you won: 2012, draws: 2068
ro => [ 1, 'Rock smashes Scissors: ' ],
pa => [ 0, 'Scissors cut Paper: ' ],
sc => [ 2, '' ],
li => [ 0, 'Scissors decapitate Lizard: '],
sp => [ 1, 'Spock smashes Scissors: ' ]
},
li => {
ro => [ 1, 'Rock crushes Lizard: ' ],
pa => [ 0, 'Lizard eats Paper: ' ],
sc => [ 1, 'Scissors decapitate Lizard: '],
li => [ 2, '' ],
sp => [ 0, 'Lizard poisons Spock: ' ]
},
sp => {
ro => [ 0, 'Spock vaporizes Rock: ' ],
pa => [ 1, 'Paper disproves Spock: ' ],
sc => [ 0, 'Spock smashes Scissors: ' ],
li => [ 1, 'Lizard poisons Spock: ' ],
sp => [ 2, '' ]
}
);</lang>
 
</pre>
<pre>Round 1: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? li
Example of an interactive session:
You chose Lizard, Computer chose Scissors.
<pre>
Scissors decapitate Lizard: You Lose! - (W:0 L:1 T:0)
Welcome to the Rock-Paper-Scissors game!
Choose 'rock', 'paper' or 'scissors'
Enter empty line or 'quit' to quit
Your choice: s
You chose Scissors, I chose Paper. You win!
Your choice: s
You chose Scissors, I chose Rock. I win!
Your choice: s
You chose Scissors, I chose Rock. I win!
Your choice: s
You chose Scissors, I chose Rock. I win!
Your choice: s
You chose Scissors, I chose Rock. I win!
Your choice: p
You chose Paper, I chose Rock. You win!
Your choice: s
You chose Scissors, I chose Rock. I win!
Your choice: q
You chose:
rock = 0 times,
paper = 1 times,
scissors = 6 times,
I chose:
rock = 6 times,
paper = 1 times,
scissors = 0 times,
Turns: 7
I won: 5, you won: 2, draws: 0
</pre>
 
=={{header|Phix}}==
Round 2: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? sp
<syntaxhighlight lang="phix">--standard game
You chose Spock, Computer chose Paper.
constant rule3 = {"rock blunts scissors",
Paper disproves Spock: You Lose! - (W:0 L:2 T:0)
"paper wraps rock",
"scissors cut paper"}
--extended version
constant rule5 = {"rock blunts scissors",
"rock crushes lizard",
"paper wraps rock",
"paper disproves spock",
"scissors cut paper",
"scissors decapitate lizard",
"lizard eats paper",
"lizard poisons spock",
"spock smashes scissors",
"spock vaporizes rock"}
 
constant rules = iff(rand(2)=1?rule3:rule5)
Round 3: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? ro
 
You chose Rock, Computer chose Lizard.
sequence what = {}
Rock crushes Lizard: You Win! - (W:1 L:2 T:0)
sequence beats = {}
string wkeys = ""
string question = "What is your move "
integer choices, hsum
sequence history, cplays, pplays
 
object x, verb, y
 
for i=1 to length(rules) do
{x} = split(rules[i])
if not find(x,what) then
what = append(what,x)
if find(x[1],wkeys) then
wkeys = append(wkeys,x[$])
question &= x[1..-2]&"("&x[$]&"), "
else
wkeys = append(wkeys,x[1])
question &= "("&x[1]&")"&x[2..$]&", "
end if
end if
end for
choices = length(wkeys)
history = repeat(1,choices)
hsum = 3
cplays = repeat(0,choices)
pplays = repeat(0,choices)
beats = repeat(repeat(0,choices),choices)
question[-2] = '?'
for i=1 to length(rules) do
{x,verb,y} = split(rules[i])
beats[find(x,what)][find(y,what)] = verb
end for
 
integer cmove, pmove, draws = 0, pwins = 0, cwins = 0
while 1 do
cmove = rand(hsum)
for i=1 to choices do
cmove -= history[i]
if cmove<=0 then
-- predicted user choice of i, find whatever beats it
for j=1 to choices do
if string(beats[j][i]) then
cmove = j
exit
end if
end for
exit
end if
end for
puts(1,question)
while 1 do
pmove = lower(wait_key())
if pmove='q' then exit end if
pmove = find(pmove,wkeys)
if pmove!=0 then exit end if
end while
if pmove='q' then exit end if
 
printf(1,"you: %s, me: %s, ",{what[pmove],what[cmove]})
cplays[cmove] += 1
pplays[pmove] += 1
if cmove=pmove then
printf(1,"a draw.\n")
draws += 1
else
if string(beats[cmove][pmove]) then
printf(1,"%s %s %s. I win.\n",{what[cmove],beats[cmove][pmove],what[pmove]})
cwins += 1
elsif string(beats[pmove][cmove]) then
printf(1,"%s %s %s. You win.\n",{what[pmove],beats[pmove][cmove],what[cmove]})
pwins += 1
else
?9/0 -- sanity check
end if
end if
history[pmove] += 1
hsum += 1
end while
printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws})
printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws})
printf(1," ") for i=1 to choices do printf(1,"%9s",what[i]) end for
printf(1,"\nyou: ") for i=1 to choices do printf(1,"%9d",pplays[i]) end for
printf(1,"\n me: ") for i=1 to choices do printf(1,"%9d",cplays[i]) end for</syntaxhighlight>
{{out}}
<pre style="font-size: 8px">
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: scissors, rock blunts scissors. You win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: rock, a draw.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: rock, a draw.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors? you: rock, me: paper, paper wraps rock. I win.
What is your move (r)ock, (p)aper, (s)cissors?
 
Your wins:1, My wins:7, Draws:2
rock paper scissors
you: 10 0 0
me: 2 7 1
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
0 var wh
0 var wc
( "Scissors cuts Paper"
"Paper covers Rock"
"Rock crushes Lizard"
"Lizard poisons Spock"
"Spock smashes Scissors"
"Scissors decapites Lizard"
"Lizard eats Paper"
"Paper disproves Spock"
"Spock vaporizes Rock"
"Rock blunts Scissors" )
"'Rock, Paper, Scissors, Lizard, Spock!' rules are: " ? nl
len for
get ?
endfor
nl
( ( "S" "Scissors" ) ( "P" "Paper" ) ( "R" "Rock" ) ( "L" "Lizard" ) ( "K" "Spock" ) )
 
true while
"Choose (S)cissors, (P)paper, (R)ock, (L)izard, Spoc(K) or (Q)uit: " input nl upper
dup "Q" == if
nl drop false
else
getd if
dup "You choose " print ? var he
rand 5 * int 1 + 2 2 tolist sget
dup "I choose " print ? var ce
he ce == if
"Draw" ?
else
swap len for
get dup
split 2 del
he ce 2 tolist
over over == rot rot reverse == or if exitfor else drop endif
endfor
dup ?
he find 1 == if wh 1 + var wh "You win!" else wc 1 + var wc "I win!" endif ? drop
swap
endif
else
print " is a invalid input!" ?
endif
true
endif
endwhile
drop drop
"Your punctuation: " print wh ?
"Mi punctuation: " print wc ?
wh wc > if "You win!" else wh wc < if "I win!" else "Draw!" endif endif ?</syntaxhighlight>
{{out}}
<pre>'Rock, Paper, Scissors, Lizard, Spock!' rules are:
 
Scissors cuts Paper
Paper covers Rock
Rock crushes Lizard
Lizard poisons Spock
Spock smashes Scissors
Scissors decapites Lizard
Lizard eats Paper
Paper disproves Spock
Spock vaporizes Rock
Rock blunts Scissors
 
Choose (S)cissors, (P)paper, (R)ock, (L)izard, Spoc(K) or (Q)uit: k
You choose Spock
I choose Rock
Spock vaporizes Rock
You win!
Choose (S)cissors, (P)paper, (R)ock, (L)izard, Spoc(K) or (Q)uit: q
 
Your punctuation: 1
Mi punctuation: 0
You win!
 
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
'''Use the url bar to play'''
 
e.g: www.example.com/rockpaper.php?moves=paper
<br>
www.example.com/rockpaper.php?moves=rock
 
----
 
 
<syntaxhighlight lang="php">
 
<?php
echo "<h1>" . "Choose: ROCK - PAPER - SCISSORS" . "</h1>";
echo "<h2>";
echo "";
 
$player = strtoupper( $_GET["moves"] );
$wins = [
'ROCK' => 'SCISSORS',
'PAPER' => 'ROCK',
'SCISSORS' => 'PAPER'
];
$a_i = array_rand($wins);
echo "<br>";
echo "Player chooses " . "<i style=\"color:blue\">" . $player . "</i>";
echo "<br>";
echo "<br>" . "A.I chooses " . "<i style=\"color:red\">" . $a_i . "</i>";
 
$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
$results = "A.I wins";
} else {
$results = "Player wins";
}
 
echo "<br>" . $results;
?>
</syntaxhighlight>
 
=={{header|Picat}}==
{{trans|Prolog}}
 
(Some part is from the Prolog version.)
 
<syntaxhighlight lang="picat">go ?=>
println("\nEnd terms with '.'.\n'quit.' ends the session.\n"),
Prev = findall(P,beats(P,_)),
ChoiceMap = new_map([P=0 : P in Prev]),
ResultMap = new_map([computer_wins=0,user_wins=0,draw=0]),
play(Prev,ChoiceMap,ResultMap),
nl,
println("Summary:"),
println(choiceMap=ChoiceMap),
println(resultMap=ResultMap),
nl.
go => true.
 
%
% Play an interactive game.
%
play(Prev,ChoiceMap,ResultMap) =>
print("Your choice? "),
P = read_term(),
if P == quit then
nl,
print_result(ResultMap)
else
C = choice(ChoiceMap),
printf("The computer chose %w%n", C),
result(C,P,Prev,Next,Result),
ChoiceMap.put(P,ChoiceMap.get(P)+1),
ResultMap.put(Result,ResultMap.get(Result,0)+1),
play(Next,ChoiceMap,ResultMap)
end.
 
%
% Do a weighted random choice based on the user's previous choices.
%
weighted_choice(Map) = Choice =>
Map2 = [(V+1)=K : K=V in Map].sort, % ensure that all choices can be made
% Prepare the probability matrix M
Total = sum([P : P=_ in Map2]),
Len = Map2.len,
M = new_array(Len,2),
T = new_list(Len),
foreach({I,P=C} in zip(1..Len,Map2))
if I == 1 then
M[I,1] := 1,
M[I,2] := P
else
M[I,1] := M[I-1,2]+1,
M[I,2] := M[I,1]+P-1
end,
T[I] := C
end,
M[Len,2] := Total,
 
% Pick a random number in 1..Total
R = random(1,Total),
Choice = _,
% Check were R match
foreach(I in 1..Len, var(Choice))
if M[I,1] <= R, M[I,2] >= R then
Choice := T[I]
end
end.
 
%
% Check probably best counter choice.
%
choice(Map) = Choice =>
% what is the Player's probably choice
PlayersProbablyMove = weighted_choice(Map),
% select the choice that beats it
beats(Choice,PlayersProbablyMove).
 
 
print_result(ResultMap) =>
foreach(C in ResultMap.keys)
println(C=ResultMap.get(C))
end,
nl.
 
% This part is from the Prolog version.
result(C,P,R,[C|R],Result) :-
beats(C,P),
Result = computer_wins,
printf("Computer wins.\n").
result(C,P,R,[B|R],Result) :-
beats(P,C),
beats(B,P),
Result=user_wins,
printf("You win!%n").
result(C,C,R,[B|R],Result) :-
beats(B,C),
Result=draw,
printf("It is a draw\n").
 
beats(paper, rock).
beats(rock, scissors).
beats(scissors, paper).</syntaxhighlight>
 
 
Sample result when user only plays rock.
{{out}}
<pre>End terms with '.'.
'quit.' ends the session.
 
Your choice? rock.
The computer chose paper
Computer wins.
Your choice? rock.
The computer chose paper
Computer wins.
Your choice? rock.
The computer chose paper
Computer wins.
Your choice? rock.
The computer chose rock
It is a draw
Your choice? rock.
The computer chose rock
It is a draw
Your choice? quit.
 
computer_wins = 3
user_wins = 0
draw = 2
 
Summary:
choiceMap = (map)[rock = 5,paper = 0,scissors = 0]
resultMap = (map)[computer_wins = 3,user_wins = 0,draw = 2]</pre>
 
Round 4: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? ro
You chose Rock, Computer chose Scissors.
Rock smashes Scissors: You win! - (W:2 L:2 T:0)
 
Round 5: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? li
You chose Lizard, Computer chose Paper.
Lizard eats Paper: You win! - (W:3 L:2 T:0)
...</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(use (C Mine Your)
(let (Rock 0 Paper 0 Scissors 0)
(loop
Line 1,942 ⟶ 4,603:
((== Your (car Mine)) "I win")
(T "You win") ) )
(inc Your) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
rock: procedure options (main); /* 30 October 2013 */
declare move character (1), cm fixed binary;
 
put ('The Rock-Paper-Scissors game');
put skip list ("please type 'r' for rock, 'p' for paper, 's' for scissors.");
put skip list ("Anything else finishes:");
do forever;
get edit (move) (a(1));
move = lowercase(move);
if index('rpsq', move) = 0 then iterate;
if move = 'q' then stop;
cm = random()*3; /* computer moves: 0 = rock, 1 = paper, 2 = scissors */
select (cm);
when (0) select (move);
when ('r') put list ('rock and rock: A draw');
when ('p') put list ('paper beats rock: You win');
when ('s') put list ('rock breaks scissors: I win');
end;
when (1) select (move);
when ('r') put list ('paper beats rock: I win');
when ('p') put list ('paper and paper: A draw');
when ('s') put list ('scissors cut paper: You win');
end;
when (2) select (move);
when ('r') put list ('rock breaks scissors: You win');
when ('p') put list ('scissors cuts paper: I win');
when ('s') put list ('Scissors and Scissors: A draw');
end;
end;
end;
end rock;
</syntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">play :-
findall(P,beats(P,_),Prev),
play(Prev).
 
play(Prev) :-
write('your choice? '),
read(P),
random_member(C, Prev),
format('The computer chose ~p~n', C),
result(C,P,Prev,Next),
!,
play(Next).
 
result(C,P,R,[C|R]) :-
beats(C,P),
format('Computer wins.~n').
result(C,P,R,[B|R]) :-
beats(P,C),
beats(B,P),
format('You win!~n').
result(C,C,R,[B|R]) :-
beats(B,C),
format('It is a draw~n').
 
beats(paper, rock).
beats(rock, scissors).
beats(scissors, paper).</syntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Enumeration
;choices are in listed according to their cycle, weaker followed by stronger
#rock
Line 2,027 ⟶ 4,753:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre style="height:40ex;overflow:scroll">Welcome to the game of rock-paper-scissors
Line 2,075 ⟶ 4,801:
 
=={{header|Python}}==
A light version with limited support for additional rules. New weapons can be introduced, but each can only be beaten by one other weapon.
<lang python>#!/usr/bin/python
from random import choice, randrange
from bisect import bisect
from collections import defaultdict
 
The <code>rules</code> dictionary is of the form <code>'this': beaten by 'that', etc</code> as opposed to <code>'this': beats 'that'</code>.
WHATBEATS = { 'paper' : 'scissors',
'scissors' : 'rock',
'rock' : 'paper' }
 
<syntaxhighlight lang="python">from random import choice
ORDER = ('rock', 'paper', 'scissors')
 
rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
CHOICEFREQUENCY = defaultdict(int)
previous = ['rock', 'paper', 'scissors']
 
while True:
def probChoice(choices, probabilities):
totalhuman = suminput(probabilities'\nchoose your weapon: ')
computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous"
prob_accumulator = 0
accumulator = []
for p in probabilities:
prob_accumulator += p
accumulator.append(prob_accumulator)
r = randrange(total)
bsct = bisect(accumulator, r)
chc = choices[bsct]
return chc
 
if human in ('quit', 'exit'): break
def checkWinner(a, b):
if b == WHATBEATS[a]:
return b
elif a == WHATBEATS[b]:
return a
 
elif human in rules:
return None
previous.append(human)
print('the computer played', computer, end='; ')
 
if rules[computer] == human: # if what beats the computer's choice is the human's choice...
def sanitizeChoice(a):
print('yay you win!')
# Drop it to lower-case
elif rules[human] == computer: # if what beats the human's choice is the computer's choice...
return a.lower()
print('the computer beat you... :(')
else: print("it's a tie!")
 
else: print("that's not a valid choice")</syntaxhighlight>
def registerPlayerChoice(choice):
CHOICEFREQUENCY[choice] += 1
 
Output, where player always chooses Rock:
def getRandomChoice():
if len(CHOICEFREQUENCY) == 0:
return choice(ORDER)
choices = CHOICEFREQUENCY.keys()
probabilities = CHOICEFREQUENCY.values()
return WHATBEATS[probChoice(choices, probabilities)]
 
<pre>choose your weapon: rock
the computer played rock; it's a tie!
 
choose your weapon: rock
the computer played scissors; yay you win!
 
choose your weapon: rock
the computer played paper; the computer beat you... :(
 
choose your weapon: rock
the computer played paper; the computer beat you... :(
 
choose your weapon: rock
the computer played paper; the computer beat you... :(</pre>
 
This is another code. Output is as same as the above output.
<syntaxhighlight lang="python">from random import randint
 
hands = ['rock', 'scissors', 'paper']; judge = ['its a tie!', 'the computer beat you... :(', 'yay you win!']
while True:
try:
humanChoice = raw_input()
YOU = hands.index(input('Choose your weapon: ')) # YOU = hands.index(raw_input('Choose your weapon: ')) If you use Python2.7
humanChoice = sanitizeChoice(humanChoice)
except ValueError:
if humanChoice not in ORDER:
continuebreak
NPC = randint(0, 2)
print('The computer played ' + hands[NPC] + '; ' + judge[YOU-NPC])</syntaxhighlight>
 
=={{header|Quackery}}==
compChoice = getRandomChoice()
print "Computer picked", compChoice+",",
 
<syntaxhighlight lang="Quackery">
# Don't register the player choice until after the computer has made
[ 0 ] is rock ( --> n )
# its choice.
[ 1 ] is paper ( --> n )
registerPlayerChoice(humanChoice)
[ 2 ] is scissor ( --> n )
 
[ $ "Choose rock, paper or scissors: "
winner = checkWinner(humanChoice, compChoice)
input cr
trim reverse trim reverse
$ "" swap witheach [ lower join ]
dup $ "rock" = iff
[ drop rock ] done
dup $ "paper" = iff
[ drop paper ] done
$ "scissors" = iff
scissor done
again ] is player ( --> n )
 
[ stack 1 ] is rocks ( --> s )
if winner == None:
[ stack 1 ] is papers ( --> s )
winner = "nobody"
[ stack 1 ] is scissors ( --> s )
 
[ 1 swap
print winner, "wins!"</lang>
[ table rocks papers scissors ]
do tally ] is notechoice ( n --> )
 
[ 0 ' [ rocks papers scissors ]
Output, where player always chooses Rock:
witheach [ share + ]
random
dup rocks share < iff
[ drop paper ] done
rocks share -
papers share < iff
scissor done
rock ] is computer ( --> n )
 
[ say "Computer chose "
<pre>!504 #5 j0 ?0 $ ./rps.py
[ table rock paper scissors ]
rock
echo say "." cr ] is echomove ( n --> )
Computer picked scissors, rock wins!
 
rock
[ [ table
Computer picked paper, paper wins!
[ table 0 1 2 ]
rock
[ table 2 0 1 ]
Computer picked paper, paper wins!
[ table 1 2 0 ] ] do ] is result ( n n --> n )
rock
 
Computer picked paper, paper wins!
[ [ table
rock
$ "It's a draw."
Computer picked paper, paper wins!</pre>
$ "Computer wins."
$ "Player wins." ]
do echo$ cr cr ] is announce ( n --> )
 
[ stack 0 ] is draws ( --> s )
[ stack 0 ] is cwins ( --> s )
[ stack 0 ] is pwins ( --> s )
 
[ [ table draws cwins pwins ]
1 swap tally ] is keepscore ( n --> )
 
[ say "Computer: " cwins share echo
say " Player: " pwins share echo
say " Draws: " draws share echo
cr cr ] is scoreboard ( --> )
 
[ ' [ rocks papers scissors ]
witheach [ 1 swap replace ]
' [ draws cwins pwins ]
witheach [ 0 swap replace ] ] is initialise ( --> )
 
[ 0
[ drop
$ "How many games? " input
trim reverse trim reverse
$->n until ]
cr ] is games ( --> n )
 
[ initialise
games times
[ computer
player dup notechoice
over echomove
result dup announce
keepscore
scoreboard ] ] is play ( --> )</syntaxhighlight>
 
{{out}}
 
As a dialogue in the Quackery shell.
 
<pre>/O> play
...
How many games? 3
 
Choose rock, paper or scissors: rock
 
Computer chose rock.
It's a draw.
 
Computer: 0 Player: 0 Draws: 1
 
Choose rock, paper or scissors: paper
 
Computer chose scissors.
Computer wins.
 
Computer: 1 Player: 0 Draws: 1
 
Choose rock, paper or scissors: scissors
 
Computer chose paper.
Player wins.
 
Computer: 1 Player: 1 Draws: 1
 
 
Stack empty.
 
/O></pre>
 
=={{header|R}}==
This milks R's vectorisation quite heavily. However, this approach doesn't generalise well to the extra credit task. In particular, the last two lines of the loop would need a lot of work to be both non-ugly and working.
<syntaxhighlight lang="rsplus">play <- function()
{
bias <- c(r = 1, p = 1, s = 1)
repeat
{
playerChoice <- readline(prompt = "Rock (r), Paper (p), Scissors (s), or Quit (q)? ")
if(playerChoice == "q") break
rps <- c(Rock = "r", Paper = "p", Scissors = "s")
if(!playerChoice %in% rps) next
compChoice <- sample(rps, 1, prob = bias / sum(bias))
cat("I choose", names(compChoice), "\n",
c("We draw!", "I win!", "I lose!")[1 + (which(compChoice == rps) - which(playerChoice == rps)) %% 3], "\n")
bias <- bias + (playerChoice == c("s", "r", "p"))
}
}
play()</syntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(require math)
 
(define history (make-hash '((paper . 1) (scissors . 1) (rock . 1))))
(define total 3)
 
(define (update-history! human-choice)
(set! total (+ total 1))
(hash-update! history human-choice add1 0))
 
(define (pick-one)
(sample
(discrete-dist '(paper scissors rock)
(map (λ (x) (hash-ref history x))
'(scissors paper rock)))))
 
(define (find-winner computer human)
(define order '(scissors paper rock scissors))
(cond
[(eq? computer human) 'none]
[(eq? (second (member computer order)) human) 'computer]
[ 'human]))
 
(define (game-loop)
(define computer-choice (pick-one))
(define human-choice (read))
(define winner (find-winner computer-choice human-choice))
(update-history! human-choice)
(displayln (~a "Computer picked " computer-choice ", "
"human picked " human-choice ", "
winner " wins."))
(game-loop))
 
(game-loop)
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
This is slightly more complicated than it could be; it is a general case framework with input filtering. It weights the computers choices based on your previous choices. Type in at least the first two characters of your choice, or just hit enter to quit. Customize it by supplying your own <tt>%vs</tt> options/outcomes.
 
Here is standard Rock-Paper-Scissors.
 
<syntaxhighlight lang="raku" line>my %vs = (
options => [<Rock Paper Scissors>],
ro => {
ro => [ 2, '' ],
pa => [ 1, 'Paper covers Rock: ' ],
sc => [ 0, 'Rock smashes Scissors: ' ]
},
pa => {
ro => [ 0, 'Paper covers Rock: ' ],
pa => [ 2, '' ],
sc => [ 1, 'Scissors cut Paper: ' ]
},
sc => {
ro => [ 1, 'Rock smashes Scissors: '],
pa => [ 0, 'Scissors cut Paper: ' ],
sc => [ 2, '' ]
}
);
 
my %choices = %vs<options>.map({; $_.substr(0,2).lc => $_ });
my $keys = %choices.keys.join('|');
my $prompt = %vs<options>.map({$_.subst(/(\w\w)/, -> $/ {"[$0]"})}).join(' ')~"? ";
my %weight = %choices.keys »=>» 1;
 
my @stats = 0,0,0;
my $round;
 
while my $player = (prompt "Round {++$round}: " ~ $prompt).lc {
$player.=substr(0,2);
say 'Invalid choice, try again.' and $round-- and next
unless $player.chars == 2 and $player ~~ /<$keys>/;
my $computer = (flat %weight.keys.map( { $_ xx %weight{$_} } )).pick;
%weight{$_.key}++ for %vs{$player}.grep( { $_.value[0] == 1 } );
my $result = %vs{$player}{$computer}[0];
@stats[$result]++;
say "You chose %choices{$player}, Computer chose %choices{$computer}.";
print %vs{$player}{$computer}[1];
print ( 'You win!', 'You Lose!','Tie.' )[$result];
say " - (W:{@stats[0]} L:{@stats[1]} T:{@stats[2]})\n",
};</syntaxhighlight>Example output:
<pre>Round 1: [Ro]ck [Pa]per [Sc]issors? ro
You chose Rock, Computer chose Paper.
Paper covers Rock: You Lose! - (W:0 L:1 T:0)
 
Round 2: [Ro]ck [Pa]per [Sc]issors? pa
You chose Paper, Computer chose Scissors.
Scissors cut Paper: You Lose! - (W:0 L:2 T:0)
 
Round 3: [Ro]ck [Pa]per [Sc]issors? pa
You chose Paper, Computer chose Scissors.
Scissors cut Paper: You Lose! - (W:0 L:3 T:0)
 
Round 4: [Ro]ck [Pa]per [Sc]issors? ro
You chose Rock, Computer chose Rock.
Tie. - (W:0 L:3 T:1)
 
Round 5: [Ro]ck [Pa]per [Sc]issors? sc
You chose Scissors, Computer chose Scissors.
Tie. - (W:0 L:3 T:2)
...</pre>
 
Here is example output from the same code only with a different %vs data structure implementing [http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock Rock-Paper-Scissors-Lizard-Spock].
 
<syntaxhighlight lang="raku" line>my %vs = (
options => [<Rock Paper Scissors Lizard Spock>],
ro => {
ro => [ 2, '' ],
pa => [ 1, 'Paper covers Rock: ' ],
sc => [ 0, 'Rock smashes Scissors: ' ],
li => [ 0, 'Rock crushes Lizard: ' ],
sp => [ 1, 'Spock vaporizes Rock: ' ]
},
pa => {
ro => [ 0, 'Paper covers Rock: ' ],
pa => [ 2, '' ],
sc => [ 1, 'Scissors cut Paper: ' ],
li => [ 1, 'Lizard eats Paper: ' ],
sp => [ 0, 'Paper disproves Spock: ' ]
},
sc => {
ro => [ 1, 'Rock smashes Scissors: ' ],
pa => [ 0, 'Scissors cut Paper: ' ],
sc => [ 2, '' ],
li => [ 0, 'Scissors decapitate Lizard: '],
sp => [ 1, 'Spock smashes Scissors: ' ]
},
li => {
ro => [ 1, 'Rock crushes Lizard: ' ],
pa => [ 0, 'Lizard eats Paper: ' ],
sc => [ 1, 'Scissors decapitate Lizard: '],
li => [ 2, '' ],
sp => [ 0, 'Lizard poisons Spock: ' ]
},
sp => {
ro => [ 0, 'Spock vaporizes Rock: ' ],
pa => [ 1, 'Paper disproves Spock: ' ],
sc => [ 0, 'Spock smashes Scissors: ' ],
li => [ 1, 'Lizard poisons Spock: ' ],
sp => [ 2, '' ]
}
);</syntaxhighlight>
 
<pre>Round 1: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? li
You chose Lizard, Computer chose Scissors.
Scissors decapitate Lizard: You Lose! - (W:0 L:1 T:0)
 
Round 2: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? sp
You chose Spock, Computer chose Paper.
Paper disproves Spock: You Lose! - (W:0 L:2 T:0)
 
Round 3: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? ro
You chose Rock, Computer chose Lizard.
Rock crushes Lizard: You Win! - (W:1 L:2 T:0)
 
Round 4: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? ro
You chose Rock, Computer chose Scissors.
Rock smashes Scissors: You win! - (W:2 L:2 T:0)
 
Round 5: [Ro]ck [Pa]per [Sc]issors [Li]zard [Sp]ock? li
You chose Lizard, Computer chose Paper.
Lizard eats Paper: You win! - (W:3 L:2 T:0)
...</pre>
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">import Prelude;
 
rel[str, str] whatbeats = {<"Rock", "Scissors">, <"Scissors", "Paper">, <"Paper", "Rock">};
Line 2,176 ⟶ 5,182:
ComputerChoices += x;
return "Computer played <computer>. <CheckWinner(human, computer)> wins!";
}</langsyntaxhighlight>
Sample output:
<langsyntaxhighlight lang="rascal">rascal>RPS("Rock")
str: "Computer played Rock. Nobody wins!"
 
Line 2,206 ⟶ 5,212:
 
rascal>RPS("Rock")
str: "Computer played Paper. Paper wins!"</langsyntaxhighlight>
 
=={{header|RacketRed}}==
<syntaxhighlight lang="rebol">
<lang racket>
Red [Purpose: "Implement a rock-paper-scissors game with weighted probability"]
#lang racket
(require math)
 
prior: rejoin choices: ["r" "p" "s"]
(define history (make-hash '((paper . 1) (scissors . 1) (rock . 1))))
(define total 3)
 
while [
(define (update-history! human-choice)
find choices pchoice: ask "choose rock: r, paper: p, or scissors: s^/"
(set! total (+ total 1))
] [
(hash-update! history human-choice add1 0))
print ["AI Draws:" cchoice: random/only prior]
 
cwin: select "rpsr" pchoice
(define (pick-one)
close: select "rspr" pchoice
(sample
(discrete-dist '(paper scissors rock)
print case [
(map (λ (x) (hash-ref history x))
pchoice = cchoice ["tie"]
'(scissors paper rock)))))
cchoice = cwin ["you lose"]
 
'else ["you win"]
(define (find-winner computer human)
]
(define order '(scissors paper rock scissors))
(cond
append prior cwin ;adds what would have beaten player
[(eq? computer human) 'none]
remove find prior close ;removes what would have lost to player
[(eq? (second (member computer order)) human) 'computer]
]
[ 'human]))
</syntaxhighlight>
 
(define (game-loop)
(define computer-choice (pick-one))
(define human-choice (read))
(define winner (find-winner computer-choice human-choice))
(update-history! human-choice)
(displayln (~a "Computer picked " computer-choice ", "
"human picked " human-choice ", "
winner " wins."))
(game-loop))
 
(game-loop)
</lang>
 
=={{header|REXX}}==
===traditional, 3 choices===
This version of the REXX program:
This REXX program version:
* allows the human player to abbreviate their choice
::* &nbsp; allows the human player to &nbsp; QUIT &nbsp; atabbreviate anytheir timechoice
::* &nbsp; issues appropriate error messages for an incorrect (or no) choice(s)
* keeps track of the human player's responses &nbsp; (to make a hopefully winning choice)
::* &nbsp; allows the human player to &nbsp; QUIT &nbsp; at any time
* uses proper "English" &nbsp; ''rock breaks scissors''
::* &nbsp; keeps track of the human player's responses &nbsp; (to hopefully make future computer winning choices)
<lang rexx>/*REXX pgm plays rock-paper-scissors with a CBLF (carbon-based life form*/
::* &nbsp; uses better "English"/grammer, &nbsp; &nbsp; i.e.: &nbsp; &nbsp; &nbsp; ''rock breaks scissors'', &nbsp; &nbsp; &nbsp; and &nbsp; &nbsp; &nbsp; ''paper covers rock''.
!='────────'; er='***error!***'; @.=0 /*some constants for pgm*/
<syntaxhighlight lang="rexx">/*REXX program plays rock─paper─scissors with a human; tracks what human tends to use. */
z=! 'Please enter one of: Rock Paper Scissors (or Quit)'
$.p!= 'paper────────'; $.serr='scissors'! "***error***"; $@.r='rock'0 /*computer'ssome choicesconstants for this program. */
prompt= ! 'Please enter one of: Rock Paper Scissors (or Quit)'
b.p=' covers '; b.s=' cuts '; b.r=' breaks ' /*how the choice wins.*/
$.p= 'paper' ; $.s= "scissors"; $.r= 'rock' /*list of the choices in this program. */
t.p= $.r ; t.s= $.p ; t.r= $.s /*thingys that beats stuff. */
w.p= $.s ; w.s= $.r ; w.r= $.p /*stuff " " thingys. */
b.p= 'covers'; b.s= "cuts" ; b.r= 'breaks' /*verbs: how the choice wins. */
 
do forever; say; say zprompt; say /*prompt the CBLF; &then get a response.*/
c= word('rock$.p paper$.s scissors'$.r, random(1, 3) ) /*choose the computer's 1stfirst pick. */
m= max(@.r, @.p, @.s); f c='paper' w.r /*prepare to examine the choice history.*/
if @.p==m then fc='scissors' w.p /*emulate JC's: The Amazing Karnac. */
if @.s==m then fc='rock' w.s /* " " " " " */
if m\c1==0 left(c, 1) then c=f /*chooseC1 based onis CBLF'sused historyfor faster comparing. */
c1=left(c,1)parse pull u; upper c1 a= strip(u) /*C1 is used for fast comparing /*get the CBLF's choice/pick (answer). */
parseupper a c1 pull u; a a1=strip left(ua, 1); /*getuppercase thechoices, CBLF'sget choice1st (answer)character.*/
upperok= 0 a; a1=left(a,1) /*uppercaseindicate answer, getisn't 1stOK char (so far). */
ok=0 select /*indicateprocess/verify answerthe isn CBLF'ts OKchoice. so far*/
selectwhen words(u)==0 then say err /*process the CBLF'snothing choice. */entered'
when words(u)==0>1 then say ererr 'nothingtoo many choices: entered' u
when wordsabbrev(u)>1'QUIT', a) then do; say ! "quitting."; then say er 'tooexit; many choices: ' uend
when abbrev('QUITROCK',a) a) then do; say ! 'quitting.'; exit; end|,
when abbrev('ROCKPAPER', a) |,
abbrev('PAPERSCISSORS',a) |, then ok=1 /*Yes? This is a valid answer by CBLF.*/
otherwise abbrev('SCISSORS',a) then ok=1 /* say err 'you entered a validbad choice: ' answer by CBLF.*/u
otherwise say er 'you entered a bad choice:' u
end /*select*/
 
if \ok then iterate /*answer ¬ OK? Then get another choice.*/
@.a1 = @.a1 + 1 /*keep tracka history of the CBLF's answerschoices. */
say ! 'computer chose: ' c
if a1==c1 c1 then do; say ! 'draw.'; iterate; end
if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1
if a1=='R' & c1=='S' |,
else say ! 'you win! ' ! $.a1 b.a1 $.c1
a1=='S' & c1=='P' |,
end a1=='P'/*forever*/ & c1=='R' then say ! 'you win! ' ! $.a1 b.a1 $ /*stick a fork in it, we're all done.c1 */</syntaxhighlight>
{{out|output|text=&nbsp; with various responses from the user &nbsp; (output shown is a screen scraping):}}
else say ! 'the computer wins. ' ! $.c1 b.c1 $.a1
<pre>
end /*forever*/
/*stick a fork in it, we're done.*/</lang>
'''output''' with various responses from the user &nbsp; (output shown is a screen scraping):
<pre style="overflow:scroll">
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
s ◄■■■■■■■■■■■■■■■ human input.
s
──────── computer chose: rock
──────── the computer wins. ──────── rock breaks scissors
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
s ◄■■■■■■■■■■■■■■■ human input.
s
──────── computer chose: rock
──────── the computer wins. ──────── rock breaks scissors
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
s ◄■■■■■■■■■■■■■■■ human input.
s
──────── computer chose: rock
──────── the computer wins. ──────── rock breaks scissors
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
s ◄■■■■■■■■■■■■■■■ human input.
s
──────── computer chose: rock
──────── the computer wins. ──────── rock breaks scissors
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
s ◄■■■■■■■■■■■■■■■ human input.
s
──────── computer chose: rock
──────── the computer wins. ──────── rock breaks scissors
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
p ◄■■■■■■■■■■■■■■■ human input.
p
──────── computer chose: rock
──────── you win! ──────── paper covers rock
 
──────── Please enter one of: Rock Paper Scissors (or Quit)
 
q ◄■■■■■■■■■■■■■■■ human input.
q
──────── quitting.
</pre>
 
===extended, 5 choices===
This REXX version supports more choices: &nbsp; <big> rock &nbsp; paper &nbsp; scissors &nbsp; lizard &nbsp; Spock </big>
<syntaxhighlight lang="rexx">/*REXX pgm plays rock─paper─scissors─lizard─Spock with human; tracks human usage trend. */
!= '────────'; err=! "***error***"; @.=0 /*some constants for this REXX program.*/
prompt=! 'Please enter one of: Rock Paper SCissors Lizard SPock (Vulcan) (or Quit)'
$.p='paper' ; $.s="scissors" ; $.r='rock' ; $.L="lizard" ; $.v='Spock' /*names of the thingys*/
t.p= $.r $.v ; t.s= $.p $.L ; t.r= $.s $.L ; t.L= $.p $.v ; t.v= $.r $.s /*thingys beats stuff.*/
w.p= $.L $.s ; w.s= $.v $.r ; w.r= $.v $.p ; w.L= $.r $.s ; w.v= $.L $.p /*stuff beats thingys.*/
b.p='covers disproves'; b.s="cuts decapitates"; b.r='breaks crushes'; b.L="eats poisons"; b.v='vaporizes smashes' /*how the choice wins.*/
whom.1= ! 'the computer wins. ' !; whom.2= ! "you win! " !; win= words(t. p)
 
do forever; say; say prompt; say /*prompt CBLF; then get a response. */
c= word($.p $.s $.r $.L $.v, random(1, 5) ) /*the computer's first choice/pick. */
m= max(@.r, @.p, @.s, @.L, @.v) /*used in examining CBLF's history. */
if @.p==m then c= word(w.p, random(1, 2) ) /*emulate JC's The Amazing Karnac. */
if @.s==m then c= word(w.s, random(1, 2) ) /* " " " " " */
if @.r==m then c= word(w.r, random(1, 2) ) /* " " " " " */
if @.L==m then c= word(w.L, random(1, 2) ) /* " " " " " */
if @.v==m then c= word(w.v, random(1, 2) ) /* " " " " " */
c1= left(c, 1) /*C1 is used for faster comparing. */
parse pull u; a= strip(u) /*obtain the CBLF's choice/pick. */
upper a c1 ; a1= left(a, 1) /*uppercase the choices, get 1st char. */
ok=0 /*indicate answer isn't OK (so far). */
select /* [↓] process the CBLF's choice/pick.*/
when words(u)==0 then say err 'nothing entered.'
when words(u)>1 then say err 'too many choices: ' u
when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end
when abbrev('LIZARD', a) |,
abbrev('ROCK', a) |,
abbrev('PAPER', a) |,
abbrev('VULCAN', a) |,
abbrev('SPOCK', a,2) |,
abbrev('SCISSORS',a,2) then ok=1 /*it's a valid choice for the human. */
otherwise say err 'you entered a bad choice: ' u
end /*select*/
 
if \ok then iterate /*answer ¬OK? Then get another choice.*/
@.a1= @.a1 + 1 /*keep a history of the CBLF's choices.*/
say ! 'computer chose: ' c
if a1==c1 then say ! 'draw.' /*Oh rats! The contest ended up a draw*/
else do who=1 for 2 /*either the computer or the CBLF won. */
if who==2 then parse value a1 c1 with c1 a1
do j=1 for win /*see who won. */
if $.a1 \== word(t.c1, j) then iterate /*not this 'un. */
say whom.who $.c1 word(b.c1, j) $.a1 /*notify winner.*/
leave /*leave J loop.*/
end /*j*/
end /*who*/
end /*forever*/ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; is similar to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Rock-paper-scissors
 
load "stdlib.ring"
load "guilib.ring"
 
width = 200
height = 200
 
myChose = 1
compChose = 1
nextPlayer = 1
myScore = 0
compScore = 0
C_FONTSIZE = 15
 
C_ROCK = "images/rock.jpg"
C_PAPER = "images/paper.jpg"
C_SCISSORS = "images/scissors.jpg"
 
ChoseList = [C_ROCK,C_PAPER,C_SCISSORS]
 
Button = list(len(ChoseList))
 
app = new QApp
{
 
StyleFusion()
 
win = new QWidget() {
 
setWindowTitle('Stone Paper Scissors Game')
setWinIcon(self,C_ROCK)
setStyleSheet("background-color:cyan;")
setWindowFlags(Qt_Window | Qt_WindowTitleHint | Qt_WindowCloseButtonHint | Qt_CustomizeWindowHint)
reSize(900,600)
winheight = height()
fontSize = 8 + (winheight / 100)
 
for Col = 1 to len(ChoseList)
Button[Col] = new QPushButton(win) {
x = 150+(Col-1)*height
setgeometry(x,35,width,height)
setStyleSheet("background-color:white;")
seticon(new qicon(new qpixmap(ChoseList[Col])))
setIconSize(new qSize(200,200))
setclickevent("ButtonPress(" + string(Col) + ")")
setSizePolicy(1,1)
}
next
 
labelMyChose = new QLabel(win) {
setgeometry(200,250,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("My Chose:")
}
 
labelCompChose = new QLabel(win) {
setgeometry(580,250,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Comp Chose:")
}
 
labelScoreEnd = new QLabel(win) {
setgeometry(0,510,win.width(),30)
setAlignment(Qt_AlignHCenter | Qt_AlignVCenter)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
 
btnMyChose = new QPushButton(win) {
setgeometry(150,300,width,height)
setStyleSheet("background-color:white;")
}
 
btnCompChose = new QPushButton(win) {
setgeometry(550,300,width,height)
setStyleSheet("background-color:white;")
}
 
btnNewGame = new QPushButton(win) {
setgeometry(170,550,150,40)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
setclickevent("NewGame()")
settext("New Game")
}
 
btnExit = new QPushButton(win) {
setgeometry(580,550,150,40)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
setclickevent("Close()")
settext("Exit")
}
 
labelMyScore = new QLabel(win) {
setgeometry(170,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("My Score: ")
}
 
labelMyScoreSum = new QLabel(win) {
setgeometry(300,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
 
labelCompScore = new QLabel(win) {
setgeometry(580,0,130,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Comp Score: ")
}
 
labelCompScoreSum = new QLabel(win) {
setgeometry(730,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
 
show()
 
}
 
exec()
 
}
 
func ButtonPress Col
 
if nextPlayer = 1
myChose = Col
btnMyChose {
seticon(new qicon(new qpixmap(ChoseList[Col])))
setIconSize(new qSize(width,height))
}
nextPlayer = 2
compChose()
ok
 
func compChose
 
rndChose = random(len(ChoseList)-1) + 1
compChose = rndChose
btnCompChose {
seticon(new qicon(new qpixmap(ChoseList[compChose])))
setIconSize(new qSize(width,height))
}
nextPlayer = 1
Result()
 
func Result
 
if (myChose = compChose)
labelScoreEnd.settext("Draw!")
ok
if (myChose = 1) and (compChose = 2)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 1) and (compChose = 3)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
if (myChose = 2) and (compChose = 3)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 2) and (compChose = 1)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
if (myChose = 3) and (compChose = 1)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 3) and (compChose = 2)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
 
func NewGame
 
nextPlayer = 1
myScore = 0
compScore = 0
btnMyChose {
seticon(new qicon(new qpixmap("")))
setIconSize(new qSize(200,200))
}
 
btnCompChose {
seticon(new qicon(new qpixmap("")))
setIconSize(new qSize(200,200))
}
 
labelScoreEnd.settext("")
labelMyScoreSum.settext("0")
labelCompScoreSum.settext("0")
 
func Close
 
win.close()
app.quit()
 
</syntaxhighlight>
 
[https://github.com/ring-lang/ring/tree/master/applications/rockpaperscissors Rock Paper Scissors - image]
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class RockPaperScissorsGame
CHOICES = %w[rock paper scissors quit]
BEATS = {
'rock' => 'paper',
'paper' => 'scissors',
'scissors' => 'rock',
}
def initialize()
@pieces = %w[rock paper scissors]
@beats = {
'rock' => 'paper',
'paper' => 'scissors',
'scissors' => 'rock',
}
@plays = {
'rock' => 1,
'paper' => 1,
'scissors' => 1,
}
@score = [0, 0, 0] # [0]:Human wins, [1]:Computer wins, [2]:draw
 
play
end
 
def humanPlay()
answer = nil
loop do
print "\nYour choice: #@pieces{CHOICES}? "
answer = STDIN.gets.strip.downcase
next if answer.empty?
if idx = @piecesCHOICES.find_index {|piecechoice| piecechoice.match(/^#{answer}/)}
return answer = @piecesCHOICES[idx] if idx
puts "invalid breakanswer, try again"
else
puts "invalid answer, try again"
end
end
answer
end
 
def computerPlay()
total = @plays.values.reduce(:+)
r = rand(total) + 1
sum = 0
humans_choiceCHOICES.each =do nil|choice|
sum += @plays[choice]
@pieces.each do |piece|
sumreturn += @playsBEATS[piecechoice] if r <= sum
if r <= sum
humans_choice = piece
break
end
end
@beats[humans_choice]
end
 
def play
loop do
h = humanPlay
break if h == "quit"
c = computerPlay
print "H: #{h}, C: #{c} => "
 
# only update the human player's history after the computer has chosen
@plays[h] += 1
 
if h == c
puts "draw"
elsif h == @beatsscore[c2] += 1
elsif h == BEATS[c]
puts "Human wins"
@score[0] += 1
Line 2,400 ⟶ 5,653:
@score[1] += 1
end
puts "score: human=#{@score[0]}%d, computer=#{%d, draw=%d" % [*@score[1]}"
end
@plays.each_key{|k| @plays[k] -= 1}
puts "\nhumans chose #{@plays}"
end
end
 
game = RockPaperScissorsGame.new</langsyntaxhighlight>
 
sample game where human always chooses rock:
<pre style="height: 40ex; overflow: scroll">Your choice: ["rock", "paper", "scissors"]? r
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: rock => draw
score: human=0, computer=0, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paperscissors => ComputerHuman wins
score: human=01, computer=0, draw=1
 
Your choice: ["rock", "paper", "scissors"]? r
H: rock, C: rock => draw
score: human=0, computer=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=21, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=32, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=43, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=54, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=65, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=76, draw=1
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paperrock => Computer winsdraw
score: human=01, computer=86, draw=2
 
Your choice: ["rock", "paper", "scissors", "quit"]? r
H: rock, C: paper => Computer wins
score: human=01, computer=97, draw=2
 
Your choice: ["rock", "paper", "scissors", "quit"]? rq
 
H: rock, C: paper => Computer wins
humans chose {"rock"=>10, "paper"=>0, "scissors"=>0}
score: human=0, computer=10</pre>
</pre>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">pri$ = "RSPR"
rps$ = "Rock,Paper,Sissors"
[loop]
Line 2,486 ⟶ 5,740:
print "Good Bye! I enjoyed the game"
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">extern crate rand;
#[macro_use]
extern crate rand_derive;
 
use std::io;
use rand::Rng;
use Choice::*;
 
#[derive(PartialEq, Clone, Copy, Rand, Debug)]
enum Choice {
Rock,
Paper,
Scissors,
}
 
fn beats(c1: Choice, c2: Choice) -> bool {
(c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock)
}
 
fn ai_move<R: Rng>(rng: &mut R, v: [usize; 3]) -> Choice {
// weighted random choice, a dynamic version of `rand::distributions::WeightedChoice`
let rand = rng.gen_range(0, v[0] + v[1] + v[2]);
if rand < v[0] {
Paper
} else if rand < v[0] + v[1] {
Scissors
} else {
Rock
}
}
 
fn main() {
let mut rng = rand::thread_rng();
 
println!("Rock, paper, scissors!");
let mut ai_choice: Choice = rng.gen();
let mut ucf = [0, 0, 0]; // user choice frequency
let mut score = [0, 0];
 
loop {
println!("Please input your move: 'r', 'p' or 's'. Type 'q' to quit");
 
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
let u_choice = match input.to_lowercase().trim() {
s if s.starts_with('r') => {
ucf[0] += 1;
Rock
}
s if s.starts_with('p') => {
ucf[1] += 1;
Paper
}
s if s.starts_with('s') => {
ucf[2] += 1;
Scissors
}
s if s.starts_with('q') => break,
_ => {
println!("Please enter a correct choice!");
continue;
}
};
println!("You chose {:?}, I chose {:?}.", u_choice, ai_choice);
if beats(u_choice, ai_choice) {
score[0] += 1;
println!("You win!");
} else if u_choice == ai_choice {
println!("It's a tie!");
} else {
score[1] += 1;
println!("I win!");
}
println!("-Score: You {}, Me {}", score[0], score[1]);
 
// only after the 1st iteration the AI knows the stats and can make
// its weighted random move
ai_choice = ai_move(&mut rng, ucf);
}
println!("Thank you for the game!");
}</syntaxhighlight>
 
=={{header|Scala}}==
You can invoke this game with an arbitrary number of weapons:
<syntaxhighlight lang="scala">object RockPaperScissors extends App {
import scala.collection.mutable.LinkedHashMap
def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) {
val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match {
case null => println; return
case "" => return
case s => Symbol(s)
}
beats get h match {
case Some(losers) =>
def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match {
case (s, i) if rand <= (accum + i) => s
case (_, i) => weighted(todo, rand, accum + i)
}
val c = weighted(played.toIterator, 1 + scala.util.Random.nextInt(played.values.sum)) match {
// choose an opponent that would beat the player's anticipated move
case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1
}
print(s" My move: $c\n ")
c match {
case c if losers contains c => println("You won")
case c if beats(c) contains h => println("You lost")
case _ => println("We drew") // or underspecified
}
case x => println(" Unknown weapon, try again.")
}
play(beats, played get h match {
case None => played
case Some(count) => played.updated(h, count + 1)
})
}
 
def play(beats: LinkedHashMap[Symbol,Set[Symbol]]): Unit =
play(beats, beats.mapValues(_ => 1)) // init with uniform probabilities
 
play(LinkedHashMap(
'rock -> Set('lizard, 'scissors),
'paper -> Set('rock, 'spock),
'scissors -> Set('paper, 'lizard),
'lizard -> Set('spock, 'paper),
'spock -> Set('scissors, 'rock)
))
}</syntaxhighlight>
{{out}}
<pre>Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): paper
My move: 'paper
We drew
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): scissors
My move: 'paper
You won
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'scissors
You won
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'rock
We drew
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'paper
You lost
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'rock
We drew
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'paper
You lost
Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): rock
My move: 'paper
You lost</pre>
 
Here's another code: (I refactored the above code, it is more functional, more testable )
<syntaxhighlight lang="scala">object RockPaperScissors extends App {
def beats = Map(
'rock -> Set('lizard, 'scissors),
'paper -> Set('rock, 'spock),
'scissors -> Set('paper, 'lizard),
'lizard -> Set('spock, 'paper),
'spock -> Set('scissors, 'rock)
)
// init with uniform probabilities
def initPlayed = beats.mapValues(_ => 1)
def input = Symbol(readLine(s"""Your move (${beats.keys mkString ", "}): """))
def random(max: Int) = scala.util.Random.nextInt(max)
def display(text: String) = print(text)
 
def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match {
case (s, i) if rand <= (accum + i) => s
case (_, i) => weighted(todo, rand, accum + i)
}
 
def calcMyMove(random: Int => Int, played: Map[Symbol,Int]) = {
weighted(played.toIterator, 1 + random(played.values.sum)) match {
// choose an opponent that would beat the player's anticipated move
case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1
}
}
 
case class Result(text: String, won: Int, lost: Int, drew: Int) {
override def toString = s"$text. Won: $won, Lost: $lost, Drew: $drew"
}
 
def getResult(userWeapon: Symbol, myMove: Symbol, result: Result) = {
if (beats(userWeapon) contains myMove)
result.copy(text = "You won", won = result.won + 1)
else if (beats(myMove) contains userWeapon)
result.copy(text = "You lost", lost = result.lost + 1)
else result.copy(text = "We drew", drew = result.drew + 1)
}
 
def play(input: => Symbol, display: String => Unit, random: Int => Int)
(played: Map[Symbol,Int], result: Result): Result = {
val userWeapon = input
if (userWeapon != Symbol("")) {
val newResult = if (beats contains userWeapon) {
val myMove = calcMyMove(random, played)
display(s" My move: $myMove\n ")
getResult(userWeapon, myMove, result)
} else {
result.copy(text = " Unknown weapon, try again")
}
display(newResult + "\n")
play(input, display, random)(played get userWeapon match {
case None => played
case Some(count) => played.updated(userWeapon, count + 1)
}, newResult)
} else result
}
 
override def main(args: Array[String]): Unit =
play(input, display, random)(initPlayed, Result("Start", 0, 0, 0))
}</syntaxhighlight>
{{out}}
<pre>
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): rock
My move: 'rock
We drew. Won: 0, Lost: 0, Drew: 1
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): spock
My move: 'spock
We drew. Won: 0, Lost: 0, Drew: 2
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): lizard
My move: 'spock
You won. Won: 1, Lost: 0, Drew: 2
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): scissors
My move: 'spock
You lost. Won: 1, Lost: 1, Drew: 2
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): scissors
My move: 'spock
You lost. Won: 1, Lost: 2, Drew: 2
Your move ('spock, 'rock, 'lizard, 'paper, 'scissors): spock
My move: 'rock
You won. Won: 2, Lost: 2, Drew: 2</pre>
 
=={{header|Seed7}}==
Line 2,493 ⟶ 5,985:
[http://seed7.sourceforge.net/libraries/keybd.htm#getc%28in_console_keybd_file%29 getc].
It is also possible to quit the program with q.
 
<lang seed7>$ include "seed7_05.s7i";
{{incorrect|Seed7|This example does not seem to use the weighted average AI from the task description.}}
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
$ include "keybd.s7i";
 
Line 2,527 ⟶ 6,022:
until command = 'q';
writeln("Goodbye! Thanks for playing!");
end func;</langsyntaxhighlight>
 
Sample run:
Line 2,546 ⟶ 6,041:
Please type in 1 for Rock, 2 for Paper, 3 for Scissors, q to quit q
Goodbye! Thanks for playing!
</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">const rps = %w(r p s)
 
const msg = [
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
]
 
say <<"EOT"
\n>> Rock Paper Scissors <<\n
** Enter 'r', 'p', or 's' as your play.
** Enter 'q' to exit the game.
** Running score shown as <your wins>:<my wins>
EOT
 
var plays = 0
var aScore = 0
var pScore = 0
var pcf = [0,0,0] # pcf = player choice frequency
var aChoice = pick(0..2) # ai choice for first play is completely random
 
loop {
var pi = Sys.scanln("Play: ")
pi == 'q' && break
 
var pChoice = rps.index(pi)
 
if (pChoice == -1) {
STDERR.print("Invalid input!\n")
next
}
 
++pcf[pChoice]
++plays
 
# show result of play
">> My play: %-8s".printf(rps[aChoice])
 
given ((aChoice - pChoice + 3) % 3) {
when (0) { say "Tie." }
when (1) { "%-*s %s".printlnf(30, msg[aChoice], 'My point'); aScore++ }
when (2) { "%-*s %s".printlnf(30, msg[pChoice], 'Your point'); pScore++ }
}
 
# show score
"%-6s".printf("%d:%d" % (pScore, aScore))
 
# compute ai choice for next play
given (plays.rand.int) { |rn|
case (rn < pcf[0]) { aChoice = 1 }
case (pcf[0]+pcf[1] > rn) { aChoice = 2 }
default { aChoice = 0 }
}
}</syntaxhighlight>
 
'''Sample run:'''
<pre>
>> Rock Paper Scissors <<
 
** Enter 'r', 'p', or 's' as your play.
** Enter 'q' to exit the game.
** Running score shown as <your wins>:<my wins>
 
Play: r
>> My play: s Rock breaks scissors Your point
1:0 Play: p
>> My play: p Tie.
1:0 Play: r
>> My play: s Rock breaks scissors Your point
2:0 Play: s
>> My play: p Scissors cut paper Your point
3:0 Play: r
>> My play: p Paper covers rock My point
3:1 Play: p
>> My play: r Paper covers rock Your point
4:1 Play: q
</pre>
 
=={{header|SuperCollider}}==
 
<pre>
// play it in the REPL, evaluating line by line
 
a = RockPaperScissors.new;
a.next(Scissors);
a.next(Scissors);
a.next(Scissors);
a.next(Paper);
</pre>
 
An implementation using classes
 
<pre>
Rock {
 
*play { |other|
^other.rock + this + "against" + other
}
 
*rock {
^"tie"
}
 
*paper {
^"loses"
}
 
*scissors {
^"wins"
}
 
*losesAgainst {
^Paper
}
 
}
 
Paper {
 
*play { |other|
^other.paper + this + "against" + other
}
 
*paper {
^"tie"
}
 
*scissors {
^"loses"
}
 
*rock {
^"wins"
}
 
*losesAgainst {
^Scissors
}
 
}
 
Scissors {
 
*play { |other|
^other.scissors + this + "against" + other
}
 
*scissors {
^"tie"
}
 
*rock {
^"loses"
}
 
*paper {
^"wins"
}
 
*losesAgainst {
^Rock
}
 
}
 
RockPaperScissors {
var opponentMoves;
 
*new {
^super.new.init
}
 
init {
opponentMoves = Bag.new;
}
 
findBestMatch {
var typicalMove = opponentMoves.wchoose;
if(typicalMove.isNil) { ^[Rock, Paper, Scissors].choose };
^typicalMove.losesAgainst
}
 
next { |otherMove|
var myMove = this.findBestMatch;
opponentMoves.add(otherMove);
^play(otherMove, myMove)
}
 
}
</pre>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">enum Choice: CaseIterable {
case rock
case paper
case scissors
case lizard
case spock
}
 
extension Choice {
var weaknesses: Set<Choice> {
switch self {
case .rock:
return [.paper, .spock]
case .paper:
return [.scissors, .lizard]
case .scissors:
return [.rock, .spock]
case .lizard:
return [.rock, .scissors]
case .spock:
return [.paper, .lizard]
}
}
}
 
struct Game {
private(set) var history: [(Choice, Choice)] = []
private(set) var p1Score: Int = 0
private(set) var p2Score: Int = 0
 
mutating func play(_ p1Choice: Choice, against p2Choice: Choice) {
history.append((p1Choice, p2Choice))
if p2Choice.weaknesses.contains(p1Choice) {
p1Score += 1
} else if p1Choice.weaknesses.contains(p2Choice) {
p2Score += 1
}
}
}
 
func aiChoice(for game: Game) -> Choice {
if let weightedWeekness = game.history.flatMap({ $0.0.weaknesses }).randomElement() {
return weightedWeekness
} else {
// If history is empty, return random Choice
return Choice.allCases.randomElement()!
}
}
 
var game = Game()
print("Type your choice to play a round, or 'q' to quit")
loop: while true {
let choice: Choice
switch readLine().map({ $0.lowercased() }) {
case "r", "rock":
choice = .rock
case "p", "paper":
choice = .paper
case "scissors":
choice = .scissors
case "l", "lizard":
choice = .lizard
case "spock":
choice = .spock
case "q", "quit", "exit":
break loop
case "s":
print("Do you mean Spock, or scissors?")
continue
default:
print("Unknown choice. Type 'q' to quit")
continue
}
let p2Choice = aiChoice(for: game)
print("You played \(choice) against \(p2Choice)")
game.play(choice, against: p2Choice)
print("Current score: \(game.p1Score) : \(game.p2Score)")
}</syntaxhighlight>
'''Sample run:'''
<pre>
Type your choice to play a round, or 'q' to quit
r
You played rock against paper
Current score: 0 : 1
Paper
You played paper against paper
Current score: 0 : 1
spock
You played spock against lizard
Current score: 0 : 2
lizard
You played lizard against paper
Current score: 1 : 2
q
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
### Choices are represented by integers, which are indices into this list:
Line 2,612 ⟶ 6,396:
# Update the state of how the human has played in the past
lset states $humanMove [expr {[lindex $states $humanMove] + 1}]
}</langsyntaxhighlight>
Sample run:
<pre>
Line 2,644 ⟶ 6,428:
Bye!
</pre>
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">PROGRAM:RPS
:{0,0,0}→L1
:{0,0,0}→L2
:Lbl ST
:Disp "R/P/S"
:Disp "1/2/3"
:Lbl EC
:Input A
:If A>3 or A<1
:Then
:Goto NO
:End
:randInt(1,3+L1(1)+L1(2)+L1(3)→C
:If C≤1+L1(1)
:Then
:2→B
:Goto NS
:End
:If C>2+L1(2)
:Then
:1→B
:Else
:3→B
:End
:Lbl NS
:L1(A)+1→L1(A)
:If A=B
:Then
:Disp "TIE GAME"
:L2(3)+1→L2(3)
:Goto TG
:End
:If (A=1 and B=2) or (A=2 and B=3) or (A=3 and B=1)
:Then
:Disp "I WIN"
:L2(1)+1→L2(1)
:Else
:Disp "YOU WIN"
:L2(2)+1→L2(2)
:End
:Lbl TG
:Disp "PLAY AGAIN?"
:Input Str1
:If Str1="YES"
:Then
:ClrHome
:Goto ST
:Else
:Goto EN
:End
:Lbl NO
:ClrHome
:Pause "PICK 1,2, or 3"
:ClrHome
:Goto EC
:Lbl EN
:ClrHome
:Disp "I WON:"
:Disp L2(1)
:Disp "YOU WON:"
:Disp L2(2)
:Disp "WE TIED:"
:Disp L2(3)
:Disp "BYE"
</syntaxhighlight>
 
{{omit from|GUISS}}
 
=={{header|TorqueScript}}==
Line 2,649 ⟶ 6,502:
Rock Paper Scissors in TorqueScript:
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
while(isobject(RockPaperScissors))
RockPaperScissors.delete();
Line 2,790 ⟶ 6,643:
return %result;
}
</syntaxhighlight>
</lang>
 
To begin do:
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
RockPaperScissors.startGame();
</syntaxhighlight>
</lang>
 
Choose and play!
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
choose("Rock");
</syntaxhighlight>
</lang>
 
=> You chose rock computer chose paper, you lose!
 
=={{header|TI-83 BASICuBasic/4tH}}==
This implementation uses a 6-bits binary scheme, where the lower three bits represent the choice of the user and the higher three bits the choice of the computer:
<lang ti83b>PROGRAM:RPS
:{0,0,0}→L1
:{0,0,0}→L2
:Lbl ST
:Disp "R/P/S"
:Disp "1/2/3"
:Lbl EC
:Input A
:If A>3 or A<1
:Then
:Goto NO
:End
:randInt(1,3+L1(1)+L1(2)+L1(3)→C
:If C≤1+L1(1)
:Then
:2→B
:Goto NS
:End
:If C>2+L1(2)
:Then
:1→B
:Else
:3→B
:End
:Lbl NS
:L1(A)+1→L1(A)
:If A=B
:Then
:Disp "TIE GAME"
:L2(3)+1→L2(3)
:Goto TG
:End
:If (A=1 and B=2) or (A=2 and B=3) or (A=3 and B=1)
:Then
:Disp "I WIN"
:L2(1)+1→L2(1)
:Else
:Disp "YOU WIN"
:L2(2)+1→L2(2)
:End
:Lbl TG
:Disp "PLAY AGAIN?"
:Input Str1
:If Str1="YES"
:Then
:ClrHome
:Goto ST
:Else
:Goto EN
:End
:Lbl NO
:ClrHome
:Pause "PICK 1,2, or 3"
:ClrHome
:Goto EC
:Lbl EN
:ClrHome
:Disp "I WON:"
:Disp L2(1)
:Disp "YOU WON:"
:Disp L2(2)
:Disp "WE TIED:"
:Disp L2(3)
:Disp "BYE"
</lang>
 
{{incorrect|uBasic/4tH|This example does not seem to use the weighted average AI from the task description.}}
 
<syntaxhighlight lang="text"> 20 LET P=0: LET Q=0: LET Z=0
{{omit from|GUISS}}
30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
40 IF A>3 THEN GOTO 400
50 IF A=3 THEN LET A=4
60 IF A<1 THEN GOTO 400
70 C=RND(3) : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10
90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO 30
100 P=P+1 : PRINT "You chose 'paper', I chose 'rock'. You win.." : GOTO 30
120 Q=Q+1 : PRINT "You chose 'scissors', I chose 'rock'. I win!" : GOTO 30
170 Q=Q+1 : PRINT "You chose 'rock', I chose 'paper'. I win!" : GOTO 30
180 Z=Z+1 : PRINT "We both chose 'paper'. It's a draw." : GOTO 30
200 P=P+1 : PRINT "You chose 'scissors', I chose 'paper'. You win.." : GOTO 30
330 P=P+1 : PRINT "You chose 'rock', I chose 'scissors'. You win.." : GOTO 30
340 Q=Q+1 : PRINT "You chose 'paper', I chose 'scissors'. I win!" : GOTO 30
360 Z=Z+1 : PRINT "We both chose 'scissors'. It's a draw." : GOTO 30
400 PRINT "There were ";Z;" draws. I lost ";P;" times, you lost ";Q;" times." : END</syntaxhighlight>
 
A sample game:
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 1
You chose 'rock', I chose 'paper'. I win!
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 2
You chose 'paper', I chose 'scissors'. I win!
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 3
You chose 'scissors', I chose 'paper'. You win..
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 1
You chose 'rock', I chose 'paper'. I win!
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 2
We both chose 'paper'. It's a draw.
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 3
You chose 'scissors', I chose 'rock'. I win!
Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? 4
There were 1 draws. I lost 1 times, you lost 4 times.
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell|4}}
<syntaxhighlight lang="bash">#!/bin/bash
choices=(rock paper scissors)
 
# comparison function, works like Perl
# winner x y = 2 if y beats x, 1 if x beats 1, 0 if it's a tie
winner() {
local left="$1" right="$2"
echo $(( (3 + left - right) % 3 ))
}
 
 
human_counts=(1 1 1)
human_count=3
computer_counts=(0 0 0)
games=0 human=0 computer=0
 
PS3="What do you throw? "
while true; do
select choice in rock paper scissors quit; do
if [ -z "$choice" ]; then choice="$REPLY"; fi
if [ "$choice" = "quit" ]; then
break 2
fi
for (( h=0; h<${#choices[@]}; ++h )); do
if [ "${choices[h]}" = "$choice" ]; then
break
fi
done
if (( h < 3 )); then
break
fi
echo "Unrecognized choice. Try again!"
done
 
let n=RANDOM%human_count
for (( c=0; c<${#human_counts[@]}; ++c )); do
let n-=${human_counts[c]}
if (( n < 0 )); then
break
fi
done
let computer_counts[c]+=1
echo
echo "You chose ${choices[h]^^}"
echo "I chose ${choices[c]^^}"
w="$(winner "$c" "$h")"
case "$w" in
2) echo "YOU WIN!"; let human+=1;;
0) echo "TIE!";;
1) echo "I WIN!"; let computer+=1;;
*) echo "winner returned weird result '$w'";;
esac
echo
let games+=1
(( human_counts[(h+1)%3]+=1, human_count+=1 ))
done
 
echo
echo "We played $games games. You won $human, and I won $computer."
for (( i=0; i<3; ++i )); do
echo "You picked ${choices[i]} $(( human_counts[ (i+1)%3 ] - 1 )) times."
echo "I picked ${choices[i]} $(( computer_counts[i] )) times."
done</syntaxhighlight>
 
=={{header|V (Vlang)}}==
Semi-translation of Go version:
 
<syntaxhighlight lang="v (vlang)">
import rand
import os
 
const (
rps = 'rps'
msg = [
'Rock breaks scissors',s
'Paper covers rock',
'Scissors cut paper'
]
)
 
fn main() {
println("Rock Paper Scissors")
println("Enter r, p, or s as your play. Anything else ends the game.")
println("Running score shown as <your wins>:<my wins>")
mut pi :='' // player input
mut a_score, mut p_score := 0, 0
mut pcf := []int{len: 2, init: 0} // pcf = player choice frequency
mut a_choice := rand.intn(3) or {0} // ai choice for first play is completely random
for _ in 0..6 {
// get player choice
pi = os.input('Play: ').str()
if typeof(pi).name != 'string' || pi.len != 1 {break}
p_choice := rps.index_any(pi)
if p_choice < 0 {break}
pcf << p_choice
// show result of play
println('My play: ' + rps[a_choice].ascii_str())
match (a_choice - p_choice + 3) % 3 {
0 {println("Tie.")}
1 {println('My point.\n' + msg[a_choice]) a_score++}
2 {println('Your point.\n' + msg[p_choice]) p_score++}
else {break}
}
// show score
println('$p_score : $a_score')
// compute ai choice for next play
rn := rand.intn(3) or {0}
match true {
rn < pcf[0] {a_choice = 2}
rn < pcf[0] + pcf[1] {a_choice = 0}
else {a_choice = rand.intn(3) or {0}}
}
}
}
</syntaxhighlight>
 
{{out}}
Sample game:
<pre>
Rock Paper Scissors
Enter r, p, or s as your play. Anything else ends the game.
Running score shown as <your wins>:<my wins>
Play: p
My play: s
My point.
Scissors cut paper
0 : 1
Play: r
My play: r
Tie.
0 : 1
Play: s
My play: p
Your point.
Scissors cut paper
1 : 1
Play: p
My play: p
Tie.
1 : 1
Play: r
My play: p
My point.
Paper covers rock
1 : 2
Play: s
My play: r
My point.
Rock breaks scissors
1 : 3
</pre>
 
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered for the computer's choice to be generated.
<syntaxhighlight lang="wee basic">let entered=0
let keycode=0
let rcounter=1
print 1 "Enter R for rock, P for paper, or S for scissors. (not case sensitive)"
while entered=0
input human$
if human=$="r"
let human$="rock"
let entered=1
elseif human=$="R"
let human$="rock"
let entered=1
elseif human=$="p"
let human$="paper"
let entered=1
elseif human=$="P"
let human$="paper"
let entered=1
elseif human=$="s"
let human$="scissors"
let entered=1
elseif human=$="S"
let human$="scissors"
let entered=1
elseif entered=0
print 1 "That choice is invalid."
endif
wend
print 1 "Press any key so the computer can make its choice."
while keycode=0
let rcounter=rcounter+1
let keycode=key()
if rcounter=4
let rcounter=1
endif
wend
if rcounter=1
let cpu$="rock"
elseif rcounter=2
let cpu$="paper"
elseif rcounter=3
let cpu$="scissors"
endif
print 1 "You chose"+human$+"."
print 1 "The computer chose"+cpu$+"."
if human$=cpu$
print 1 "You tied."
endif
if human$="rock"
if cpu$="paper"
print 1 "Paper covers rock, so you lose."
endif
if cpu$="scissors"
print 1 "Rock blunts scissors, so you win."
endif
endif
if human$="paper"
if cpu$="rock"
print 1 "Paper covers rock, so you win."
endif
if cpu$="scissors"
print 1 "Scissors cut paper, so you lose."
endif
endif
if human$="scissors"
if cpu$="rock"
print 1 "Rock blunts scissors, so you lose."
endif
if cpu$="paper"
print 1 "Scissors cut paper, so you win."
endif
endif
end</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
{{libheader|Wren-ioutil}}
<syntaxhighlight lang="wren">import "random" for Random
import "./str" for Str
import "./ioutil" for Input
 
var choices = "rpsq"
var rand = Random.new()
 
var pWins = 0 // player wins
var cWins = 0 // computer wins
var draws = 0 // neither wins
var games = 0 // games played
var pFreqs = [0, 0, 0] // player frequencies for each choice (rps)
 
var printScore = Fn.new {
System.print("Wins: You %(pWins), Computer %(cWins), Neither %(draws)\n")
}
 
var getComputerChoice = Fn.new {
// make a completely random choice until 3 games have been played
if (games < 3) return choices[rand.int(3)]
var num = rand.int(games)
return (num < pFreqs[0]) ? "p" :
(num < pFreqs[0] + pFreqs[1]) ? "s" : "r"
}
 
System.print("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n")
while (true) {
printScore.call()
var pChoice = Str.lower(Input.option("Your choice r/p/s/q : ", "rpsqRPSQ"))
if (pChoice == "q") {
System.print("OK, quitting")
return
}
var cChoice = getComputerChoice.call()
System.print("Computer's choice : %(cChoice)")
if (pChoice == "r" && cChoice == "s") {
System.print("Rock breaks scissors - You win!")
pWins = pWins + 1
} else if (pChoice == "p" && cChoice == "r") {
System.print("Paper covers rock - You win!")
pWins = pWins + 1
} else if (pChoice == "s" && cChoice == "p") {
System.print("Scissors cut paper - You win!")
pWins = pWins + 1
} else if (pChoice == "s" && cChoice == "r") {
System.print("Rock breaks scissors - Computer wins!")
cWins = cWins + 1
} else if (pChoice == "r" && cChoice == "p") {
System.print("Paper covers rock - Computer wins!")
cWins = cWins + 1
} else if (pChoice == "p" && cChoice == "s") {
System.print("Scissors cut paper - Computer wins!")
cWins = cWins + 1
} else {
System.print("It's a draw!")
draws = draws + 1
}
var pf = pFreqs[choices.indexOf(pChoice)]
pFreqs[choices.indexOf(pChoice)] = pf + 1
games = games + 1
System.print()
}</syntaxhighlight>
 
{{out}}
Sample game:
<pre>
Enter: (r)ock, (p)aper, (s)cissors or (q)uit
 
Wins: You 0, Computer 0, Neither 0
 
Your choice r/p/s/q : r
Computer's choice : r
It's a draw!
 
Wins: You 0, Computer 0, Neither 1
 
Your choice r/p/s/q : p
Computer's choice : s
Scissors cut paper - Computer wins!
 
Wins: You 0, Computer 1, Neither 1
 
Your choice r/p/s/q : s
Computer's choice : p
Scissors cut paper - You win!
 
Wins: You 1, Computer 1, Neither 1
 
Your choice r/p/s/q : q
OK, quitting
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">REM Yabasic 2.763 version
 
WINNER = 1 : ACTION = 2 : LOSSER = 3
dim word$(10, 3)
 
for n = 0 to 9
read word$(n, WINNER), word$(n, ACTION), word$(n, LOSSER)
next n
 
repeat
clear screen
computerChoice$ = word$(ran(10), WINNER)
print "'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
for n = 0 to 9
SimonSay(n)
next n
print "\nType your choice letter:"
print "(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit\n"
k$ = upper$(inkey$)
if k$ = "Q" break
switch k$
case "R": humanChoice$ = "Rock" : break
case "P": humanChoice$ = "Paper" : break
case "S": humanChoice$ = "Scissors" : break
case "L": humanChoice$ = "Lizard" : break
case "K": humanChoice$ = "Spock" : break
end switch
print "Player chose ", humanChoice$, " and Computer chose ", computerChoice$
for n = 0 to 9
if word$(n, WINNER) = humanChoice$ and word$(n, LOSSER) = computerChoice$ then
SimonSay(n)
print "Winner was Player"
wp = wp + 1
break
elseif word$(n, WINNER) = computerChoice$ and word$(n, LOSSER) = humanChoice$ then
SimonSay(n)
print "Winner was Computer"
wc = wc + 1
break
end if
next n
if n = 10 then
print "Ouch!"
end if
punctuation()
print "\nPress any key to continue"
inkey$
until(k$ = "Q")
 
punctuation()
if wp > wc then
print "Player win"
elseif wc > wp then
print "Computer win"
else
print "Tie"
end if
 
end
 
sub SimonSay(n)
print word$(n, WINNER), " ", word$(n, ACTION), " ", word$(n, LOSSER)
end sub
 
sub punctuation()
print "\nPlayer = ", wp, "\tComputer = ", wc, "\n"
end sub
 
data "Scissors","cuts","Paper"
data "Paper","covers","Rock"
data "Rock","crushes","Lizard"
data "Lizard","poisons","Spock"
data "Spock","smashes","Scissors"
data "Scissors","decapites","Lizard"
data "Lizard","eats","Paper"
data "Paper","disproves","Spock"
data "Spock","vaporizes","Rock"
data "Rock","blunts","Scissors"</syntaxhighlight>
9,476

edits