Rock-paper-scissors: Difference between revisions
Content added Content deleted
Childishbeat (talk | contribs) m (→{{header|Wee Basic}}: The code has been revised to be a little shorter in data size.) |
(Add Factor example) |
||
Line 1,813: | Line 1,813: | ||
game(1.0, 1.0, 1.0) |
game(1.0, 1.0, 1.0) |
||
</lang> |
</lang> |
||
=={{header|Factor}}== |
|||
<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</lang> |
|||
{{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|Fortran}}== |
=={{header|Fortran}}== |