Rock-paper-scissors: Difference between revisions

m
(add Mercury)
m (→‎{{header|Wren}}: Minor tidy)
 
(40 intermediate revisions by 20 users not shown)
Line 25:
Support additional choices   [[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>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; with Ada.Numerics.Float_Random;
 
procedure Rock_Paper_Scissors is
Line 134 ⟶ 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 182 ⟶ 228:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">text
computer_play(record plays, record beats)
{
Line 252 ⟶ 298:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# rock/paper/scissors game #
# counts of the number of times the player has chosen each move #
Line 343 ⟶ 389:
OD;
print( ( "Thanks for a most enjoyable game", newline ) )
END</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AHKlang="ahk">DllCall("AllocConsole")
Write("Welcome to Rock-Paper-Scissors`nMake a choice: ")
 
Line 390 ⟶ 436:
Write(txt){
FileAppend, % txt, CONOUT$
}</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Line 396 ⟶ 442:
I´ve created a GUI to play and show results, no Console Input
 
<langsyntaxhighlight lang="autoit">
RPS()
 
Line 490 ⟶ 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 556 ⟶ 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 579 ⟶ 652:
You chose: 60 0 1
I chose: 2 55 4
 
=={{header|Bash}}==
<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</lang>
 
=={{header|Batch File}}==
<syntaxhighlight lang="dos">@echo off
<lang dos>
@echo off
setlocal enabledelayedexpansion
 
Line 624 ⟶ 669:
 
:start
 
cls
echo Games - %games% : Won - %won% : Lost - %lost% : Ties - %tie%
choice /c RPS /n /m "[R]ock, [P]aper or [S]cissors? "
 
set /a choicequant+=1
set choice=%errorlevel%
rem used [1,1000] as interval for random
set /a rocklimit=100 / %choicequant% * %freq3%
if %games% equ 0 (
set /a scissorslimit=100 - (100 / %choicequant% * %freq2%)
rem at the beginning, there's no bias for each choice
set /a randchoice=%random% %% 100 + 1
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
Line 642 ⟶ 692:
goto %compchoice%
 
:1
 
if %choice%==1 goto tie
if %choice%==2 goto win
Line 649 ⟶ 698:
 
:2
 
if %choice%==1 goto loss
if %choice%==2 goto tie
if %choice%==3 goto win
 
:3
 
if %choice%==1 goto win
if %choice%==2 goto loss
Line 661 ⟶ 708:
 
:win
set /a "won+=1"
echo Player wins^!
goto end
 
:loss
set /a "lost+=1"
echo Computer Wins^!
goto end
 
:tie
set /a "tie+=1"
echo Tie^!
goto end
 
:end
set /a "games+=1"
set /a "freq%choice%+=1"
pause
goto start</syntaxhighlight>
</lang>
 
=={{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 728 ⟶ 774:
IF r%<=p%(0) THEN =1
IF r%<=p%(0)+p%(1) THEN =2
=0</langsyntaxhighlight>
 
Sample output:
Line 758 ⟶ 804:
 
=={{header|C}}==
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 810 ⟶ 856:
}
}
</syntaxhighlight>
</lang>
 
Here's another code: (Does it using a while loop)
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h> // Standard IO
#include <stdlib.h> // other stuff
Line 917 ⟶ 963:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Version using Additional Weapons
 
<lang cpp>
#include <windows.h>
#include <iostream>
#include <string>
 
//-------------------------------------------------------------------------------
using namespace std;
 
//-------------------------------------------------------------------------------
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
 
//-------------------------------------------------------------------------------
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win ) );
}
void draw() { _draw++; }
void win( int p ) { _win[p]++; }
void move( int p, int m ) { _moves[p][m]++; }
int getMove( int p, int m ) { return _moves[p][m]; }
string format( int a )
{
char t[32];
wsprintf( t, "%.3d", a );
string d( t );
return d;
}
 
void print()
{
string d = format( _draw ),
pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ),
pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ),
pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ),
ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),
pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ),
pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] );
 
system( "cls" );
cout << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl;
cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl;
cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << endl << endl;
 
system( "pause" );
 
}
 
private:
int _moves[2][MX_C], _win[2], _draw;
};
//-------------------------------------------------------------------------------
class rps
{
private:
int makeMove()
{
int total = 0, r, s;
for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );
r = rand() % total;
 
for( int i = ROCK; i < SCISSORS; i++ )
{
s = statistics.getMove( PLAYER, i );
if( r < s ) return ( i + 1 );
r -= s;
}
 
return ROCK;
}
 
void printMove( int p, int m )
{
if( p == COMPUTER ) cout << "My move: ";
else cout << "Your move: ";
 
switch( m )
{
case ROCK: cout << "ROCK\n"; break;
case PAPER: cout << "PAPER\n"; break;
case SCISSORS: cout << "SCISSORS\n"; break;
case LIZARD: cout << "LIZARD\n"; break;
case SPOCK: cout << "SPOCK\n";
}
}
 
public:
rps()
{
checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;
checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;
checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;
checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;
checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;
}
void play()
{
int p, r, m;
while( true )
{
cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? ";
cin >> p;
if( !p || p < 0 ) break;
if( p > 0 && p < 6 )
{
p--;
cout << endl;
printMove( PLAYER, p );
statistics.move( PLAYER, p );
 
m = makeMove();
statistics.move( COMPUTER, m );
printMove( COMPUTER, m );
 
r = checker[p][m];
switch( r )
{
case DRAW:
cout << endl << "DRAW!" << endl << endl;
statistics.draw();
break;
case COMPUTER:
cout << endl << "I WIN!" << endl << endl;
statistics.win( COMPUTER );
break;
case PLAYER:
cout << endl << "YOU WIN!" << endl << endl;
statistics.win( PLAYER );
 
}
system( "pause" );
}
system( "cls" );
}
statistics.print();
}
 
private:
stats statistics;
int checker[MX_C][MX_C];
};
//-------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
rps game;
game.play();
return 0;
}
//-------------------------------------------------------------------------------
</lang>
 
Sample output:
<pre>
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 1
 
Your move: ROCK
My move: PAPER
 
I WIN!
 
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 3
 
Your move: PAPER
My move: SPOCK
 
YOU WIN!
 
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 1
 
Your move: SPOCK
My move: LIZARD
 
I WIN!
 
[...]
 
+----------+-------+--------+--------+---------+----------+--------+---------+
| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |
+----------+-------+--------+--------+---------+----------+--------+---------+
| PLAYER | 001 | | 003 | 002 | 000 | 000 | 009 |
+----------+-------+ 005 +--------+---------+----------+--------+---------+
| COMPUTER | 008 | | 000 | 005 | 000 | 001 | 008 |
+----------+-------+--------+--------+---------+----------+--------+---------+
 
</pre>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="c sharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,293 ⟶ 1,139:
}
}
}</langsyntaxhighlight>
 
Sample output of first 2 and last 2 rounds when player chooses rock every turn:
Line 1,326 ⟶ 1,172:
Losses: 60
Draws: 1
</pre>
 
=={{header|C++}}==
Version using Additional Weapons
 
<syntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
#include <string>
 
//-------------------------------------------------------------------------------
using namespace std;
 
//-------------------------------------------------------------------------------
enum choices { ROCK, SPOCK, PAPER, LIZARD, SCISSORS, MX_C };
enum indexes { PLAYER, COMPUTER, DRAW };
 
//-------------------------------------------------------------------------------
class stats
{
public:
stats() : _draw( 0 )
{
ZeroMemory( _moves, sizeof( _moves ) );
ZeroMemory( _win, sizeof( _win ) );
}
void draw() { _draw++; }
void win( int p ) { _win[p]++; }
void move( int p, int m ) { _moves[p][m]++; }
int getMove( int p, int m ) { return _moves[p][m]; }
string format( int a )
{
char t[32];
wsprintf( t, "%.3d", a );
string d( t );
return d;
}
 
void print()
{
string d = format( _draw ),
pw = format( _win[PLAYER] ), cw = format( _win[COMPUTER] ),
pr = format( _moves[PLAYER][ROCK] ), cr = format( _moves[COMPUTER][ROCK] ),
pp = format( _moves[PLAYER][PAPER] ), cp = format( _moves[COMPUTER][PAPER] ),
ps = format( _moves[PLAYER][SCISSORS] ), cs = format( _moves[COMPUTER][SCISSORS] ),
pl = format( _moves[PLAYER][LIZARD] ), cl = format( _moves[COMPUTER][LIZARD] ),
pk = format( _moves[PLAYER][SPOCK] ), ck = format( _moves[COMPUTER][SPOCK] );
 
system( "cls" );
cout << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << "| PLAYER | " << pw << " | | " << pr << " | " << pp << " | " << ps << " | " << pl << " | " << pk << " |" << endl;
cout << "+----------+-------+ " << d << " +--------+---------+----------+--------+---------+" << endl;
cout << "| COMPUTER | " << cw << " | | " << cr << " | " << cp << " | " << cs << " | " << cl << " | " << ck << " |" << endl;
cout << "+----------+-------+--------+--------+---------+----------+--------+---------+" << endl;
cout << endl << endl;
 
system( "pause" );
 
}
 
private:
int _moves[2][MX_C], _win[2], _draw;
};
//-------------------------------------------------------------------------------
class rps
{
private:
int makeMove()
{
int total = 0, r, s;
for( int i = 0; i < MX_C; total += statistics.getMove( PLAYER, i++ ) );
r = rand() % total;
 
for( int i = ROCK; i < SCISSORS; i++ )
{
s = statistics.getMove( PLAYER, i );
if( r < s ) return ( i + 1 );
r -= s;
}
 
return ROCK;
}
 
void printMove( int p, int m )
{
if( p == COMPUTER ) cout << "My move: ";
else cout << "Your move: ";
 
switch( m )
{
case ROCK: cout << "ROCK\n"; break;
case PAPER: cout << "PAPER\n"; break;
case SCISSORS: cout << "SCISSORS\n"; break;
case LIZARD: cout << "LIZARD\n"; break;
case SPOCK: cout << "SPOCK\n";
}
}
 
public:
rps()
{
checker[ROCK][ROCK] = 2; checker[ROCK][PAPER] = 1; checker[ROCK][SCISSORS] = 0; checker[ROCK][LIZARD] = 0; checker[ROCK][SPOCK] = 1;
checker[PAPER][ROCK] = 0; checker[PAPER][PAPER] = 2; checker[PAPER][SCISSORS] = 1; checker[PAPER][LIZARD] = 1; checker[PAPER][SPOCK] = 0;
checker[SCISSORS][ROCK] = 1; checker[SCISSORS][PAPER] = 0; checker[SCISSORS][SCISSORS] = 2; checker[SCISSORS][LIZARD] = 0; checker[SCISSORS][SPOCK] = 1;
checker[LIZARD][ROCK] = 1; checker[LIZARD][PAPER] = 0; checker[LIZARD][SCISSORS] = 1; checker[LIZARD][LIZARD] = 2; checker[LIZARD][SPOCK] = 0;
checker[SPOCK][ROCK] = 0; checker[SPOCK][PAPER] = 1; checker[SPOCK][SCISSORS] = 0; checker[SPOCK][LIZARD] = 1; checker[SPOCK][SPOCK] = 2;
}
void play()
{
int p, r, m;
while( true )
{
cout << "What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? ";
cin >> p;
if( !p || p < 0 ) break;
if( p > 0 && p < 6 )
{
p--;
cout << endl;
printMove( PLAYER, p );
statistics.move( PLAYER, p );
 
m = makeMove();
statistics.move( COMPUTER, m );
printMove( COMPUTER, m );
 
r = checker[p][m];
switch( r )
{
case DRAW:
cout << endl << "DRAW!" << endl << endl;
statistics.draw();
break;
case COMPUTER:
cout << endl << "I WIN!" << endl << endl;
statistics.win( COMPUTER );
break;
case PLAYER:
cout << endl << "YOU WIN!" << endl << endl;
statistics.win( PLAYER );
 
}
system( "pause" );
}
system( "cls" );
}
statistics.print();
}
 
private:
stats statistics;
int checker[MX_C][MX_C];
};
//-------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
rps game;
game.play();
return 0;
}
//-------------------------------------------------------------------------------
</syntaxhighlight>
 
Sample output:
<pre>
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 1
 
Your move: ROCK
My move: PAPER
 
I WIN!
 
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 3
 
Your move: PAPER
My move: SPOCK
 
YOU WIN!
 
What is your move (1)ROCK (2)SPOCK (3)PAPER (4)LIZARD (5)SCISSORS (0)Quit ? 1
 
Your move: SPOCK
My move: LIZARD
 
I WIN!
 
[...]
 
+----------+-------+--------+--------+---------+----------+--------+---------+
| | WON | DRAW | ROCK | PAPER | SCISSORS | LIZARD | SPOCK |
+----------+-------+--------+--------+---------+----------+--------+---------+
| PLAYER | 001 | | 003 | 002 | 000 | 000 | 009 |
+----------+-------+ 005 +--------+---------+----------+--------+---------+
| COMPUTER | 008 | | 000 | 005 | 000 | 001 | 008 |
+----------+-------+--------+--------+---------+----------+--------+---------+
 
</pre>
 
Line 1,338 ⟶ 1,384:
Code:
 
<langsyntaxhighlight lang="clojure">(ns rps.core
(:require [clojure.data.generators :refer [weighted]])
(:import jline.Terminal)
Line 1,376 ⟶ 1,422:
"Rock, Paper, Scissors!"
[& args]
(play-game {:rock 1, :paper 1, :scissors 1}))</langsyntaxhighlight>
 
{{out}}
Line 1,390 ⟶ 1,436:
=={{header|Crystal}}==
Inspired by [[#Ruby]] solution, but improved to allow additional weapons
<langsyntaxhighlight lang="ruby">
# conventional weapons
enum Choice
Line 1,496 ⟶ 1,542:
loop do
break unless game.round
end</langsyntaxhighlight>
 
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.string, std.conv, std.array, std.typecons;
 
enum Choice { rock, paper, scissors }
Line 1,557 ⟶ 1,602:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>rock, paper or scissors? paper
Line 1,580 ⟶ 1,625:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Rock_paper_scissors do
def play, do: loop([1,1,1])
Line 1,627 ⟶ 1,672:
end
 
Rock_paper_scissors.play</langsyntaxhighlight>
 
'''Sample output:'''
Line 1,648 ⟶ 1,693:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(rps).
-compile(export_all).
Line 1,695 ⟶ 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,748 ⟶ 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,812 ⟶ 1,857:
 
game(1.0, 1.0, 1.0)
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators formatting io kernel math math.ranges qw
random sequences ;
IN: rosetta-code.rock-paper-scissors
Line 1,858 ⟶ 1,903:
: main ( -- ) { 0 0 0 1 1 1 } clone game drop ;
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,907 ⟶ 1,952:
</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">
<lang FORTRAN>
! compilation
! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
Line 1,972 ⟶ 2,115:
if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won!'
end program rpsgame
</syntaxhighlight>
</lang>
rpsgame won't play more than 30 games at a time.
<langsyntaxhighlight lang="bash">
$ yes r | ./f # rock
rock, paper, scissors? scoring computer choice (r) and your choice (r)
Line 2,005 ⟶ 2,148:
26.5 3.5
$
</syntaxhighlight>
</lang>
 
 
=={{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.
<langsyntaxhighlight lang="glovepie">if var.end=0 then
var.end=0
var.computerchoice=random(3) // 1 is rock, 2 is paper, and 3 is scissors.
Line 2,049 ⟶ 2,286:
endif
endif
endif</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,120 ⟶ 2,357:
}
}
}</langsyntaxhighlight>
{{out|Sample output}}
<pre>
Line 2,141 ⟶ 2,378:
</pre>
Additional weapons:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,397 ⟶ 2,634:
aw = form[ax]
}
}</langsyntaxhighlight>
Example game files:
<pre>
Line 2,491 ⟶ 2,728:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import System.Random (randomRIO)
 
data Choice
Line 2,549 ⟶ 2,786:
 
main :: IO a
main = game (1, 1, 1)</langsyntaxhighlight>
 
=={{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 2,593 ⟶ 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 2,626 ⟶ 2,863:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Rock.bas"
110 RANDOMIZE
120 STRING CH$(1 TO 3)*8,K$*1
Line 2,678 ⟶ 2,915:
600 LET CMCHOICE=1
610 END SELECT
620 END DEF</langsyntaxhighlight>
 
=={{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 2,700 ⟶ 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 2,723 ⟶ 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 2,806 ⟶ 3,043:
return null;
}
}</langsyntaxhighlight>
Sample output:
<pre>Make your choice: rock
Line 2,845 ⟶ 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 2,869 ⟶ 3,272:
end
end
end</langsyntaxhighlight>
<pre>julia> rps()
Welcome to Rock, paper, scissors! Go ahead and type your pick.
Line 2,894 ⟶ 3,297:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.10
 
import java.util.Random
Line 2,972 ⟶ 3,375:
println()
}
}</langsyntaxhighlight>
 
Sample session:
Line 3,016 ⟶ 3,419:
=={{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.
<langsyntaxhighlight Lassolang="lasso">session_start('user')
session_addvar('user', 'historic_choices')
session_addvar('user', 'win_record')
Line 3,084 ⟶ 3,487:
'User: '+($win_record->find('user')->size)+br
'Tie: '+($win_record->find('tie')->size)+br
^}</langsyntaxhighlight>
{{out}}
<pre>Rock Paper Scissors Quit (<- as links)
Line 3,097 ⟶ 3,500:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
dim rps( 2), g$( 3)
 
Line 3,186 ⟶ 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 3,215 ⟶ 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 3,237 ⟶ 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|Lua}}==
<langsyntaxhighlight Lualang="lua">function cpuMove()
local totalChance = record.R + record.P + record.S
if totalChance == 0 then -- First game, unweighted random
Line 3,299 ⟶ 3,702:
checkWinner(cpuChoice, playerChoice)
io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ")
until io.read():upper():sub(1, 1) == "Q"</langsyntaxhighlight>
Session in which I chose nothing but rock:
<pre>
Line 3,317 ⟶ 3,720:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">DynamicModule[{record, play, text = "\nRock-paper-scissors\n",
choices = {"Rock", "Paper", "Scissors"}},
Evaluate[record /@ choices] = {1, 1, 1};
Line 3,329 ⟶ 3,732:
Alternatives @@ Reverse /@ Partition[choices, 2, 1, 1],
"You win.", _, "Draw."]];
Column@{Dynamic[text], ButtonBar[# :> play[#] & /@ choices]}]</langsyntaxhighlight>
 
=={{header|Mercury}}==
{{trans|Prolog}}
<langsyntaxhighlight Mercurylang="mercury">:- module rps.
:- interface.
:- import_module io.
Line 3,398 ⟶ 3,801:
"
Seed = time(NULL);
").</langsyntaxhighlight>
 
=={{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 3,455 ⟶ 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 3,492 ⟶ 4,020:
[wins,losses]
};
contest(10)</langsyntaxhighlight>
 
=={{header|Perl}}==
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.
<langsyntaxhighlight lang="perl">
use 5.012;
use warnings;
Line 3,618 ⟶ 4,146:
 
main();
</syntaxhighlight>
</lang>
Example input can be generated as follows:
<langsyntaxhighlight lang="bash">
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
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,668 ⟶ 4,196:
I won: 5, you won: 2, draws: 0
</pre>
 
=={{header|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.
 
<lang perl6>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",
};</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)
 
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].
 
<lang perl6>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, '' ]
}
);</lang>
 
<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|Phix}}==
<langsyntaxhighlight Phixlang="phix">--standard game
constant rule3 = {"rock blunts scissors",
"paper wraps rock",
Line 3,899 ⟶ 4,299:
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</langsyntaxhighlight>
{{out}}
<pre style="font-size: 8px">
Line 3,919 ⟶ 4,319:
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}}==
Line 3,930 ⟶ 4,414:
 
 
<syntaxhighlight lang="php">
<lang PHP>
 
<?php
Line 3,960 ⟶ 4,444:
echo "<br>" . $results;
?>
</syntaxhighlight>
</lang>
 
=={{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>
 
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(use (C Mine Your)
(let (Rock 0 Paper 0 Scissors 0)
(loop
Line 3,982 ⟶ 4,603:
((== Your (car Mine)) "I win")
(T "You win") ) )
(inc Your) ) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
rock: procedure options (main); /* 30 October 2013 */
declare move character (1), cm fixed binary;
Line 4,017 ⟶ 4,638:
end;
end rock;
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">play :-
findall(P,beats(P,_),Prev),
play(Prev).
Line 4,046 ⟶ 4,667:
beats(paper, rock).
beats(rock, scissors).
beats(scissors, paper).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">Enumeration
;choices are in listed according to their cycle, weaker followed by stronger
#rock
Line 4,132 ⟶ 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 4,184 ⟶ 4,805:
The <code>rules</code> dictionary is of the form <code>'this': beaten by 'that', etc</code> as opposed to <code>'this': beats 'that'</code>.
 
<langsyntaxhighlight lang="python">from random import choice
 
rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
Line 4,205 ⟶ 4,826:
else: print("it's a tie!")
 
else: print("that's not a valid choice")</langsyntaxhighlight>
 
Output, where player always chooses Rock:
Line 4,225 ⟶ 4,846:
 
This is another code. Output is as same as the above output.
<langsyntaxhighlight lang="python">from random import randint
 
hands = ['rock', 'scissors', 'paper']; judge = ['its a tie!', 'the computer beat you... :(', 'yay you win!']
Line 4,234 ⟶ 4,855:
break
NPC = randint(0, 2)
print('The computer played ' + hands[NPC] + '; ' + judge[YOU-NPC])</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery">
[ 0 ] is rock ( --> n )
[ 1 ] is paper ( --> n )
[ 2 ] is scissor ( --> n )
 
[ $ "Choose rock, paper or scissors: "
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 )
[ stack 1 ] is papers ( --> s )
[ stack 1 ] is scissors ( --> s )
 
[ 1 swap
[ table rocks papers scissors ]
do tally ] is notechoice ( n --> )
 
[ 0 ' [ rocks papers scissors ]
witheach [ share + ]
random
dup rocks share < iff
[ drop paper ] done
rocks share -
papers share < iff
scissor done
rock ] is computer ( --> n )
 
[ say "Computer chose "
[ table rock paper scissors ]
echo say "." cr ] is echomove ( n --> )
 
[ [ table
[ table 0 1 2 ]
[ table 2 0 1 ]
[ table 1 2 0 ] ] do ] is result ( n n --> n )
 
[ [ table
$ "It's a draw."
$ "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 4,256 ⟶ 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 4,286 ⟶ 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}}==
Line 4,334 ⟶ 5,246:
::* &nbsp; keeps track of the human player's responses &nbsp; (to hopefully make future computer winning choices)
::* &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''.
<langsyntaxhighlight lang="rexx">/*REXX program plays rock─paper─scissors with a human; tracks what human tends to use. */
!= '────────'; err=! '"***error***'"; @.=0 /*some constants for this program. */
prompt= ! 'Please enter one of: Rock Paper Scissors (or Quit)'
$.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 prompt; say prompt; say /*prompt the CBLF; then get a response.*/
c= word($.p $.s $.r, random(1, 3) ) /*choose the computer's first pick. */
m= max(@.r, @.p, @.s); c= w.r /*prepare to examine the choice history*/
if @.p==m then c= w.p /*emulate JC's: The Amazing Karnac. */
if @.s==m then c= w.s /* " " " " " */
c1= left(c, 1) /*C1 is used for faster comparing. */
parse pull u; a= strip(u) /*get the CBLF's choice/pick (answer). */
upper a c1 ; a1= left(a, 1) /*uppercase choices, get 1st character.*/
ok=0 0 /*indicate answer isn't OK (so far). */
select /*process/verify the CBLF's choice. */
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('ROCK', a) |,
abbrev('PAPER', a) |,
Line 4,362 ⟶ 5,274:
 
if \ok then iterate /*answer ¬OK? Then get another choice.*/
@.a1= @.a1 +1 1 /*keep a history of the CBLF's choices.*/
say ! 'computer chose: ' c
if a1== c1 then do; say ! 'draw.'; iterate; end
if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1
else say ! 'you win! ' ! $.a1 b.a1 $.c1
end /*forever*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; with various responses from the user &nbsp; (output shown is a screen scraping):}}
<pre>
Line 4,414 ⟶ 5,326:
===extended, 5 choices===
This REXX version supports more choices: &nbsp; <big> rock &nbsp; paper &nbsp; scissors &nbsp; lizard &nbsp; Spock </big>
<langsyntaxhighlight 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 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.*/
Line 4,460 ⟶ 5,372:
end /*j*/
end /*who*/
end /*forever*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is similar to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Rock-paper-scissors
 
load "stdlib.ring"
see "
load "guilib.ring"
welcome to the game of rock-paper-scissors.
each player guesses one of these three, and reveals it at the same time.
rock blunts scissors, which cut paper, which wraps stone.
if both players choose the same, it is a draw!
when you've had enough, choose q.
"
g = ["rock","paper","scissors"]
total=0 draw=0
pwin=0 cwin=0
see "what is your move (press r, p, or s)?"
while true
c=random(2)+1
give q
gs = floor((substr("rpsq",lower(q))))
if gs>3 or gs<1
summarise()
exit
ok
total = total + 1
see"you chose " + g[gs] + " and i chose " + g[c] + nl
temp = gs-c
if temp = 0
see ". it's a draw"
draw = draw + 1
ok
if temp = 1 or temp = -2
see ". you win!"
pwin = pwin + 1
ok
if temp = (-1) or temp = 2
see ". i win!"
cwin = cwin + 1
ok
end
</lang>
Output:
<pre>
welcome to the game of rock-paper-scissors.
each player guesses one of these three, and reveals it at the same time.
rock blunts scissors, which cut paper, which wraps stone.
if both players choose the same, it is a draw!
when you've had enough, choose q.
 
width = 200
what is your move (press r, p, or s)?
height = 200
r
 
you chose rock and i chose rock
myChose = 1
. it's a draw
compChose = 1
p
nextPlayer = 1
you chose paper and i chose paper
myScore = 0
. it's a draw
compScore = 0
s
C_FONTSIZE = 15
you chose scissors and i chose rock
 
. i win!
C_ROCK = "images/rock.jpg"
R
C_PAPER = "images/paper.jpg"
you chose rock and i chose paper
C_SCISSORS = "images/scissors.jpg"
. i win!
 
P
ChoseList = [C_ROCK,C_PAPER,C_SCISSORS]
you chose paper and i chose paper
 
. it's a draw
Button = list(len(ChoseList))
S
 
you chose scissors and i chose paper
app = new QApp
. you win!
{
q
 
you won 1, and i won 2. there were 3 draws
StyleFusion()
thanks for playing!
 
</pre>
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 = {
Line 4,603 ⟶ 5,660:
end
 
RockPaperScissorsGame.new</langsyntaxhighlight>
 
sample game where human always chooses rock:
Line 4,653 ⟶ 5,710:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">pri$ = "RSPR"
rps$ = "Rock,Paper,Sissors"
[loop]
Line 4,683 ⟶ 5,740:
print "Good Bye! I enjoyed the game"
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">extern crate rand;
#[macro_use]
extern crate rand_derive;
Line 4,768 ⟶ 5,825:
}
println!("Thank you for the game!");
}</langsyntaxhighlight>
 
=={{header|Scala}}==
You can invoke this game with an arbitrary number of weapons:
<langsyntaxhighlight Scalalang="scala">object RockPaperScissors extends App {
import scala.collection.mutable.LinkedHashMap
def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) {
Line 4,814 ⟶ 5,871:
'spock -> Set('scissors, 'rock)
))
}</langsyntaxhighlight>
{{out}}
<pre>Your move ('rock, 'paper, 'scissors, 'lizard, 'spock): paper
Line 4,842 ⟶ 5,899:
 
Here's another code: (I refactored the above code, it is more functional, more testable )
<langsyntaxhighlight Scalalang="scala">object RockPaperScissors extends App {
def beats = Map(
'rock -> Set('lizard, 'scissors),
Line 4,901 ⟶ 5,958:
override def main(args: Array[String]): Unit =
play(input, display, random)(initPlayed, Result("Start", 0, 0, 0))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,929 ⟶ 5,986:
It is also possible to quit the program with q.
 
{{incorrect|CSeed7|This example does not seem to use the weighted average AI from the task description.}}
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
$ include "keybd.s7i";
 
Line 4,965 ⟶ 6,022:
until command = 'q';
writeln("Goodbye! Thanks for playing!");
end func;</langsyntaxhighlight>
 
Sample run:
Line 4,987 ⟶ 6,044:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">const rps = %w(r p s)
 
const msg = [
Line 5,040 ⟶ 6,097:
default { aChoice = 0 }
}
}</langsyntaxhighlight>
 
'''Sample run:'''
Line 5,064 ⟶ 6,121:
4:1 Play: q
</pre>
 
 
=={{header|SuperCollider}}==
Line 5,178 ⟶ 6,234:
}
</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">enum Choice: CaseIterable {
case rock
case paper
Line 5,256 ⟶ 6,313:
game.play(choice, against: p2Choice)
print("Current score: \(game.p1Score) : \(game.p2Score)")
}</langsyntaxhighlight>
'''Sample run:'''
<pre>
Line 5,276 ⟶ 6,333:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
### Choices are represented by integers, which are indices into this list:
Line 5,339 ⟶ 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 5,371 ⟶ 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 5,376 ⟶ 6,502:
Rock Paper Scissors in TorqueScript:
 
<syntaxhighlight lang="torquescript">
<lang TorqueScript>
while(isobject(RockPaperScissors))
RockPaperScissors.delete();
Line 5,517 ⟶ 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 BASIC}}==
<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>
 
{{omit from|GUISS}}
 
=={{header|uBasic/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:
 
{{incorrect|CuBasic/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
30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
40 IF A>3 THEN GOTO 400
Line 5,622 ⟶ 6,679:
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</langsyntaxhighlight>
 
A sample game:
Line 5,642 ⟶ 6,699:
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell|4}}
<langsyntaxhighlight lang="bash">#!/bin/bash
choices=(rock paper scissors)
 
Line 5,704 ⟶ 6,761:
echo "You picked ${choices[i]} $(( human_counts[ (i+1)%3 ] - 1 )) times."
echo "I picked ${choices[i]} $(( computer_counts[i] )) times."
done</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight Weelang="wee Basicbasic">let entered=0
let keycode=0
let rcounter=1
Line 5,780 ⟶ 6,925:
endif
endif
end</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight Yabasiclang="yabasic">REM Yabasic 2.763 version
 
WINNER = 1 : ACTION = 2 : LOSSER = 3
Line 5,860 ⟶ 7,101:
data "Paper","disproves","Spock"
data "Spock","vaporizes","Rock"
data "Rock","blunts","Scissors"</langsyntaxhighlight>
9,476

edits