21 game: Difference between revisions

1,851 bytes added ,  3 years ago
Line 2,748:
when (y == 1) $ do
putStrLn $ (snd names) ++ " has won the game"</lang>
=={{header|J}}==
The main definition <tt>g21</tt> starts the game. J doesn't support niladic verbs. Although the <tt>y<tt> argument has no effect, it must be given. The empty literal vector <tt>''</tt> types quickly, hence often used to trigger niladic verbs.
<lang J>
g21=: summary@play@setup NB. ::('21: error termination'"_)
 
 
read=: 1!:1@:1:
write=: 1!:2 4: NB. unused
 
format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ])
 
Until=: 2 :'u^:(0-:v)^:_'
 
 
t=: 'score turn choice'
(t)=: i. # ;: t
erase't'
 
Fetch=: &{
Alter=: }
 
done=: 21 <: score Fetch
 
 
setup=: ([ [: echo 'On your turn enter 1 2 or 3, other entries exit'"_)@((3 :'?2') turn Alter ])@0 0 0"_ NB. choose first player randomly
summary=: 'won' ,~ (];.2 'house you ') {~ turn Fetch
 
play=: move Until done
move=: [: update you`it@.(turn Fetch)
 
update=: swap@display@add
add=: score Alter~ (score Fetch + choice Fetch)
display=: [ ([: echo 'sum: {}' format~ score Fetch)
swap=: turn Alter~ ([: -. turn Fetch)
 
it=: ([ [: echo 'House chose {}.' format~ choice Fetch)@(choice Alter~ cb)
cb=: (1:`r`3:`2:)@.(4 | score Fetch) NB. computer brain
r=: 3 :'>:?3'
 
you=: qio1@check@acquire@prompt
prompt=: [ ([: echo 'your choice?'"_)
acquire=: choice Alter~ ('123' i. 0 { ' ' ,~ read)
check=: (choice Alter~ (665 - score Fetch))@([ ([: echo '21: early termination'"_))^:(3 = choice Fetch)
qio1=: choice Alter~ ([: >: choice Fetch)
</lang>
<pre>
g21''
On your turn enter 1 2 or 3, other entries exit
your choice?
3
sum: 3
House chose 2.
sum: 5
your choice?
2
sum: 7
House chose 2.
sum: 9
your choice?
1
sum: 10
House chose 3.
sum: 13
your choice?
3
sum: 16
House chose 1.
sum: 17
your choice?
1
sum: 18
House chose 3.
sum: 21
house won
g21''
On your turn enter 1 2 or 3, other entries exit
your choice?
x
21: early termination
sum: 666
you won
</pre>
=={{header|Java}}==
Options for creating a game:
Anonymous user