21 game: Difference between revisions

53,165 bytes added ,  3 months ago
m
(Add F# version)
 
(32 intermediate revisions by 19 users not shown)
Line 29:
{{trans|Python: Original, with output}}
 
<langsyntaxhighlight lang="11l">F select_count(game_count)
‘selects a random number if the game_count is less than 18. otherwise chooses the winning number’
Int t
Line 90:
V t = input(‘Another game?(press y to continue):’)
I t != ‘y’
L.break</langsyntaxhighlight>
 
{{out}}
Line 97:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program game21_64.s */
Line 315:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
procedure Game_21 is
 
procedure Put (Item : String) is
begin
for Char of Item loop
Ada.Text_IO.Put (Char);
delay 0.010;
end loop;
end Put;
 
procedure New_Line is
begin
Ada.Text_IO.New_Line;
end New_Line;
 
procedure Put_Line (Item : String) is
begin
Put (Item);
New_Line;
end Put_LIne;
 
type Player_Kind is (Human, Computer);
type Score_Type is range 0 .. 21;
subtype Amount_Range is Score_Type range 1 .. 3;
 
package Amount_Generators is
new Ada.Numerics.Discrete_Random (Amount_Range);
 
Gen : Amount_Generators.Generator;
Total : Score_Type := 0;
Choice : Character;
Player : Player_Kind;
Amount : Amount_Range;
begin
Amount_Generators.Reset (Gen);
 
Put_Line ("--- The 21 Game ---"); New_Line;
 
Put ("Who is starting human or computer (h/c) ? ");
Ada.Text_IO.Get_Immediate (Choice);
New_Line;
 
case Choice is
when 'c' | 'C' => Player := Computer;
when 'h' | 'H' => Player := Human;
when others => return;
end case;
 
Play_Loop : loop
New_Line;
Put ("Runing total is "); Put (Total'Image); New_Line;
New_Line;
 
case Player is
 
when Human =>
Put_Line ("It is your turn !");
Input_Loop : loop
Put ("Enter choice 1 .. 3 (0 to end) : ");
Ada.Text_IO.Get_Immediate (Choice);
 
case Choice is
when '1' .. '3' =>
Amount := Amount_Range'Value ("" & Choice);
exit Input_Loop;
 
when '0' =>
exit Play_Loop;
 
when others =>
Put_Line ("Choice must be in 1 .. 3");
end case;
end loop Input_Loop;
New_Line;
 
when Computer =>
delay 1.500;
Amount := Amount_Generators.Random (Gen);
Put ("Computer chooses: "); Put (Amount'Image); New_Line;
delay 0.800;
 
end case;
 
New_Line;
Amount := Score_Type'Min (Amount, Score_Type'Last - Total);
Put (" "); Put (Total'Image); Put (" + "); Put (Amount'Image); Put (" = ");
Total := Total + Amount;
Put (Total'Image);
New_Line;
 
if Total = 21 then
New_Line;
Put ("... and we have a WINNER !!"); New_Line;
delay 0.500;
Put_Line (" ... and the winner is ...");
delay 1.000;
Put_Line (" " & Player'Image);
exit;
end if;
 
Player := (case Player is
when Computer => Human,
when Human => Computer);
end loop Play_Loop;
end Game_21;</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
{{trans|Commodore BASIC}}
Most comments are removed, see [[#Commodore_BASIC|Commodore BASIC]] for comments. The code is compacted, see the [[#Commodore_BASIC|Commodore BASIC]] listing for a line-by-line listing.
 
All text is upper case as only the the Apple IIe and later models have can display lower case on the text screen. Input is converted to upper case as the earlier models may not be able to enter lower case from the keyboard.
 
Commodore control codes are converted to the equivilent Applesoft BASIC command: ?CHR$(147); is HOME ?CHR$(18); is INVERSE and ?CHR$(146); is NORMAL. The code is adjusted when printing a numeric variables as Applesoft BASIC does not print any spaces. There are a few other changes: VAL function instead of ASC to convert number, FOR instead of GOTO or THEN, and
WAIT instead of GET in a loop.
 
<syntaxhighlight lang="gwbasic"> 5 DIM P$(2),HC(2),CA(4),CN$(6): READ CA(0),CA(1),CA(2),CA(3): FOR I = 1 TO 6: READ CN$(I): NEXT : DEF FN M(X) = (X - ( INT (X / 4)) * 4): DEF FN U(K) = K - (K > 95) * 32:L$ = " ":M$ = CHR$ (13): DATA 1,1,3,2
9 FOR PLAY = 0 TO 1
10 REM SET SCREEN COLORS HERE
11 LET C% = INT ( RND (1) * 16)
12 LET B% = INT ( RND (1) * 15 + C% + 1): IF B% > 15 THEN B% = B% - 16
13 POKE 49186,C% + B% * 16: REM FOREGROUND&BACKGROUND
14 POKE 49204, INT ( RND (1) * 16): REM BORDER
20 HOME : PRINT M$ SPC( 16);"21 GAME"M$M$" THE GOAL OF THIS GAME IS TO TAKE TURNS"M$" ADDING THE VALUE OF EITHER 1, 2, OR 3"M$" TO A RUNNING TOTAL. THE FIRST PLAYER"M$" TO BRING THE TOTAL TO 21..."M$M$ SPC( 10);"... WINS THE GAME!"M$
30 GOSUB 1000
40 FOR SETUP = 0 TO 1: HOME : PRINT
42 FOR P = 1 TO 2
44 PRINT M$"PLAYER";L$;P;", [H]UMAN OR [C]OMPUTER? ";
45 FOR K = 0 TO 1: GET K$:K$ = CHR$ ( FN U( ASC (K$))):K = K$ = "C" OR K$ = "H": NEXT K
46 PRINT K$M$M$"PLAYER";L$;P;",": PRINT "ENTER YOUR NAME";
50 LET HC(P) = (K$ = "C"): IF HC(P) THEN FOR PC = 0 TO 1:PN = INT ( RND (1) * 6) + 1:T$ = CN$(PN):PC = T$ < > P$(P - 1): NEXT PC:P$(P) = T$: PRINT "? ";P$(P)
52 IF NOT HC(P) THEN INPUT P$(P)
54 NEXT P
60 FOR P = 1 TO 2: PRINT M$L$;P;". ";P$(P);: NEXT P: PRINT M$M$"IS THIS CORRECT (Y/N)? ";: FOR K = 0 TO 1: GET K$:K$ = CHR$ ( FN U( ASC (K$))):K = K$ = "Y" OR K$ = "N": NEXT K: PRINT K$:SETUP = K$ < > "N"
70 NEXT SETUP
80 PRINT M$"WHO WILL PLAY FIRST (1 OR 2)? ";: FOR K = 0 TO 1: GET K$:K = K$ = "1" OR K$ = "2": NEXT K
90 FP = VAL (K$): PRINT K$M$M$"OKAY, ";P$(FP);" WILL PLAY FIRST."M$: GOSUB 1000
100 LET RT = 0:PI = FP - 1
110 FOR GAME = 0 TO 1
115 PI = PI * (PI < 2) + 1: HOME : PRINT "TOTAL SO FAR:";L$;RT;M$M$P$(PI);"'S TURN."
120 IF HC(PI) THEN PRINT M$"THINKING...";:TT = INT ( RND (1) * 10): FOR T = 1 TO TT: PRINT ".";: FOR I = 1 TO 250: NEXT I,T:RM = FN M(RT):AD = CA(RM): PRINT M$M$P$(PI);" ADDS";L$;CA(RM);".": FOR T = 1 TO 1000: NEXT T
125 IF NOT HC(PI) THEN FOR AMOUNT = 0 TO 1: PRINT MID$ (M$ + "ILLEGAL AMOUNT. TRY AGAIN." + M$,1,AMOUNT * 255)M$"HOW MUCH TO ADD,": INPUT "1, 2, OR 3 (0 TO QUIT) ?";AD:AMOUNT = AD > = 0 AND AD < = 3: NEXT AMOUNT
128 LET RT = RT + AD:GAME = RT > = 21 OR AD = 0
130 NEXT GAME
140 IF RT > 21 THEN PRINT M$P$(PI);" LOSES BY GOING OVER 21!!"
150 IF RT = 21 THEN PRINT M$"21! ";P$(PI);" WINS THE GAME!!!"
160 IF NOT AD THEN PRINT M$"GAME WAS ENDED BY ";P$(PI);".":PLAY = 1
210 IF AD THEN PRINT : PRINT "WOULD YOU LIKE TO PLAY AGAIN? ";: FOR K = 0 TO 1: GET K$:K$ = CHR$ ( FN U( ASC (K$))):K = K$ = "N" OR K$ = "Y": NEXT K: PRINT K$:PLAY = K$ = "N"
220 NEXT PLAY
230 IF AD THEN PRINT M$"OKAY, MAYBE ANOTHER TIME. BYE!"
240 END
1000 Z$ = " PRESS A KEY TO CONTINUE. ": PRINT SPC( 20 - INT ( LEN (Z$) / 2));: INVERSE : PRINT Z$;: NORMAL : WAIT 49152,128:K = PEEK (49168): RETURN
2010 DATA "APPLE IIE","APPLE II PLUS","APPLE IIC","APPLE II","APPLE IIGS","MACINTOSH LC"</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program game21.s */
Line 538 ⟶ 695:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
The first move is human move.
Line 567 ⟶ 724:
The first move is Raspberry pi.
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">print "-----------------------------"
print " Welcome to 21 Game"
print "-----------------------------"
 
players: ["A" "B"]
currentPlayer: sample players
nextPlayer: first players -- currentPlayer
runningTotal: new 0
num: 0
 
getNum: function [][
result: strip input "Enter a number (1,2,3) / x to exit: "
if result="x" -> exit
return result
]
 
loop.forever @[currentPlayer nextPlayer] 'plays [
print ["Running total:" runningTotal]
print ["Player" plays "turn"]
 
num: getNum
 
while [or? [not? numeric? num][not? contains? 1..3 to :integer num]][
num: getNum
]
 
runningTotal: runningTotal + to :integer num
 
print ""
 
if runningTotal=21 [
print ["Running total is 21. Player" plays "won!"]
exit
]
]
</syntaxhighlight>
 
{{out}}
 
<pre>-----------------------------
Welcome to 21 Game
-----------------------------
Running total: 0
Player B turn
Enter a number (1,2,3) / x to exit: 1
 
Running total: 1
Player A turn
Enter a number (1,2,3) / x to exit: 2
 
Running total: 3
Player B turn
Enter a number (1,2,3) / x to exit: 1
 
Running total: 4
Player A turn
Enter a number (1,2,3) / x to exit: 3
 
Running total: 7
Player B turn
Enter a number (1,2,3) / x to exit: 4
Enter a number (1,2,3) / x to exit: 2
 
Running total: 9
Player A turn
Enter a number (1,2,3) / x to exit: 3
 
Running total: 12
Player B turn
Enter a number (1,2,3) / x to exit: 1
 
Running total: 13
Player A turn
Enter a number (1,2,3) / x to exit: 2
 
Running total: 15
Player B turn
Enter a number (1,2,3) / x to exit: 3
 
Running total: 18
Player A turn
Enter a number (1,2,3) / x to exit: 3
 
Running total is 21. Player A won!</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Gui, font, S16
Gui, add, Radio, vRadioC , Cake
Gui, add, Radio, vRadioE x+0 Checked, Easy
Line 652 ⟶ 897:
Loop 3
GuiControl, Enable, % "Player1_" A_Index
return</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk"># Game 21 - an example in AWK language for Rosseta Code.
 
BEGIN {
Line 723 ⟶ 968:
newgame();
}
}</langsyntaxhighlight>
{{Output}}
<pre>
Line 803 ⟶ 1,048:
quit
goodbye</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="qbasic">PLAYER = 1
COMP = 0
 
sum = 0
total = 0
turn = int(rand + 0.5)
dim precomp = {1, 1, 3, 2}
 
while sum < 21
turn = 1 - turn
print "The sum is "; sum
if turn = PLAYER then
print "It is your turn."
while total < 1 or total > 3 or total + sum > 21
input "How many would you like to total? ", total
end while
else
print "It is the computer's turn."
total = precomp[sum mod 4]
print "The computer totals ", total, "."
end if
print
sum += total
total = 0
end while
 
if turn = PLAYER then
print "Congratulations. You win."
else
print "Bad luck. The computer wins."
end if</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{trans|Commodore BASIC}}
{{works with|Chipmunk Basic|3.6.4}}
{{works with|MSX BASIC}}
<syntaxhighlight lang="qbasic">100 rem 21 game
110 rem for rosetta code
120 '
130 rem initialization
140 l$ = chr$(157) : rem left cursor
150 dim p$(2),hc(2),ca(4) : hc(1) = 0 : hc(2) = 0 : rem players
160 ca(0) = 1 : ca(1) = 1 : ca(2) = 3 : ca(3) = 2 : rem computer answers
170 dim cn$(6) : for i = 1 to 6 : read cn$(i) : next i : rem computer names
180 def fnm(X)=(X-(INT(X/4))*4):REM modulo function
190 '
200 rem optionally set screen colors here
210 cls
220 print " 21 GAME"
230 print : print " The goal of this game is to take turns"
240 print " adding the value of either 1, 2, or 3"
250 print " to a running total. The first player"
260 print " to bring the total to 21..."
270 print : print " ... WINS THE GAME!"
280 print : gosub 1110
290 for p = 1 to 2
300 '
310 rem game setup and get players
320 for p = 1 to 2
330 print : print "Player ";p;l$;", [H]uman or [C]omputer? ";
340 k$ = inkey$ : if k$ <> "c" and k$ <> "h" then 340
350 print k$ : hc(p) = (k$ = "c")
360 print : print "Player";p;l$ "," : print "Enter your name"; : if hc(p) then goto 400
370 input p$(p)
380 next p
390 goto 420
400 gosub 1340 : print "? ";p$(p)
410 next p
420 print
430 for p = 1 to 2 : print p;l$;". ";p$(p) : next p
440 print : print "Is this correct (y/n)? ";
450 k$ = inkey$ : if k$ <> "y" and k$ <> "n" then 450
460 print k$ : if k$ = "n" then goto 290
470 print : print "Who will play first (1 or 2)? ";
480 k$ = inkey$ : if k$ < "1" or k$ > "2" then 480
490 fp = asc(k$)-48 : print k$ : print
500 print "Okay, ";p$(fp);" will play first." : print : gosub 1110
510 cls
520 '
530 rem start main game loop
540 pi = fp : rt = 0
550 print "Total so far:";rt
560 print : print p$(pi);"'s turn."
570 if hc(pi) then gosub 1240
580 if not hc(pi) then gosub 1170
590 rt = rt+ad
600 if rt = 21 then goto 680
610 if rt > 21 then print : print p$(pi);" loses by going over 21!!" : goto 700
620 pi = pi+1 : if pi > 2 then pi = 1
630 goto 550
640 print : print " ... WINS THE GAME!"
650 print : gosub 1110
660 '
670 for p = 1 to 2
680 rem winner winner chicken dinner
690 print : print "21! ";p$(pi);" wins the game!!!"
700 print : print "Would you like to play again? ";
710 k$ = inkey$ : if k$ <> "n" and k$ <> "y" then 710
720 print k$
730 if k$ = "n" then print : print "Okay, maybe another time. Bye!" : end
740 goto 200
750 print k$ : hc(p) = (k$ = "c")
760 print : print "Player";p;l$ "," : print "Enter your name"; : if hc(p) then goto 800
770 input p$(p)
780 next p
790 goto 820
800 gosub 1340 : print "? ";p$(p)
810 next p
820 print : for p = 1 to 2 : print p;l$;". ";p$(p) : next p
830 print : print "Is this correct (y/n)? ";
840 k$ = inkey$ : if k$ <> "y" and k$ <> "n" then 840
850 print k$ : if k$ = "n" then goto 660
860 print : print "Who will play first (1 or 2)? ";
870 k$ = inkey$ : if k$ < "1" or k$ > "2" then 870
880 fp = asc(k$)-48 : print k$ : print
890 print "Okay, ";p$(fp);" will play first." : print : gosub 1110
900 '
910 rem start main game loop
920 pi = fp : rt = 0
930 print chr$(147);"Total so far: ";rt
940 print : print p$(pi);"'s turn."
950 if hc(pi) then gosub 1240
960 if not hc(pi) then gosub 1170
970 rt = rt+ad
980 if rt = 21 then goto 1030
990 if rt > 21 then print : print p$(pi);" loses by going over 21!!" : goto 1050
1000 pi = pi+1 : if pi > 2 then pi = 1
1010 goto 930
1020 '
1030 rem winner winner chicken dinner
1040 print : print "21! ";p$(pi);" wins the game!!!"
1050 print : print "Would you like to play again? ";
1060 k$ = inkey$ : if k$ <> "n" and k$ <> "y" then 1060
1070 print k$
1080 if k$ = "n" then print : print "Okay, maybe another time. Bye!" : end
1090 goto 490
1100 '
1110 rem pause for keypress
1120 z$ = " Press a key to continue. "
1130 print z$
1140 k$ = inkey$ : if k$ = "" then 1140
1150 return
1160 '
1170 rem human player move
1180 print : print "How much to add,"
1190 print "1, 2, or 3 (0 to quit)"; : input ad
1200 if ad < 0 or ad > 3 then print : print "Illegal amount. Try again." : goto 1180
1210 if ad = 0 then print : print "Game was ended by ";p$(pi);"." : end
1220 return
1230 '
1240 rem computer player move
1250 print : print "Thinking...";
1260 tt = int(rnd(1)*10)
1270 for t = 1 to tt : print "."; : for i = 1 to 250 : next i : next t : print
1280 rm = fn m(rt)
1290 ad = ca(rm)
1300 print : print p$(pi);" adds ";ca(rm);l$;"."
1310 for t = 1 to 1000 : next t
1320 return
1330 '
1340 rem pick a computer name
1350 pn = int(rnd(1)*6)+1 : t$ = cn$(pn)
1360 if t$ = p$(p-1) then goto 1350
1370 p$(p) = t$
1380 return
1390 '
1400 rem some computer names to pick from
1410 data "Commodore 64","VIC-20","Commodore 128"
1420 data "PET","Plus/4","Commodore 16"</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "21Game.bas"
110 RANDOMIZE
120 LET SUM,ADD=0
130 LET TURN=RND(2)-1
140 CLEAR SCREEN
150 PRINT "21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly 21."
160 PRINT "The running total starts at zero. One player will be the computer.":PRINT
170 DO
180 LET TURN=NOT TURN
190 SET #102:INK 3:PRINT "The sum is";SUM:SET #102:INK 1
200 IF TURN THEN
210 PRINT "It is your turn.":PRINT "How many would you like to add? (1-3): ";
220 LET ADD=READKEY
230 IF ADD>21-SUM THEN PRINT "You can only add";21-SUM
240 ELSE
250 LET ADD=4-MOD(SUM-1,4)
260 IF ADD=4 THEN LET ADD=RND(3)+1
270 PRINT "It is the computer's turn.":PRINT "The computer adds";ADD
280 END IF
290 PRINT :LET SUM=SUM+ADD
300 LOOP WHILE SUM<21
310 IF TURN THEN
320 PRINT "Congratulations. You win."
330 ELSE
340 PRINT "Bad luck. The computer wins."
350 END IF
360 END
370 DEF READKEY
380 DO
390 LET T$=INKEY$
400 LOOP WHILE T$>"3" OR T$<"1"
410 PRINT T$:LET READKEY=VAL(T$)
420 END DEF </syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#Chipmunk Basic|Chipmunk Basic]] solution works without any changes.
 
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="purebasic">If OpenConsole()
PLAYER.i = 1
COMP.i = 0
sum.i = 0
total.i = 0
turn.i = Random(1) + 0.5
Dim precomp.i(3)
precomp(0) = 1
precomp(1) = 1
precomp(2) = 3
precomp(3) = 2
While sum < 21
turn = 1 - turn
PrintN("The sum is " + Str(sum))
If turn = PLAYER
PrintN("It is your turn.")
While total < 1 Or total > 3 Or total + sum > 21
Print("How many would you like to total? ")
total = Val(Input())
Wend
Else
PrintN("It is the computer's turn.")
total = precomp(sum % 4)
PrintN("The computer totals " + Str(total) + ".")
EndIf
PrintN("")
sum + total
total = 0
Wend
If turn = PLAYER
PrintN("Congratulations. You win.")
Else
PrintN("Bad luck. The computer wins.")
EndIf
Input()
EndIf</syntaxhighlight>
 
==={{header|QBasic}}===
{{trans|FreeBASIC}}
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">PLAYER = 1
COMP = 0
RANDOMIZE TIMER
 
sum = 0
total = 0
turn = INT(RND + 0.5)
DIM precomp(0 TO 3)
precomp(0) = 1 : precomp(1) = 1
precomp(2) = 3 : precomp(3) = 2
 
WHILE sum < 21
turn = 1 - turn
PRINT "The sum is "; sum
IF turn = PLAYER THEN
PRINT "It is your turn."
WHILE total < 1 OR total > 3 OR total + sum > 21
INPUT "How many would you like to total? ", total
WEND
ELSE
PRINT "It is the computer's turn."
total = precomp(sum MOD 4)
PRINT "The computer totals"; total; "."
END IF
PRINT
sum = sum + total
total = 0
WEND
 
IF turn = PLAYER THEN
PRINT "Congratulations. You win."
ELSE
PRINT "Bad luck. The computer wins."
END IF</syntaxhighlight>
 
==={{header|True BASIC}}===
{{trans|QBasic}}
<syntaxhighlight lang="qbasic">LET player = 1
LET comp = 0
RANDOMIZE
LET sum = 0
LET total = 0
LET turn = INT(RND+0.5)
DIM precomp(0 TO 3)
LET precomp(0) = 1
LET precomp(1) = 1
LET precomp(2) = 3
LET precomp(3) = 2
DO WHILE sum < 21
LET turn = 1-turn
PRINT "The sum is "; sum
IF turn = player THEN
PRINT "It is your turn."
DO WHILE total < 1 OR total > 3 OR total+sum > 21
INPUT prompt "How many would you like to total? ": total
LOOP
ELSE
PRINT "It is the computer's turn."
LET total = precomp(remainder(round(sum),4))
PRINT USING "The computer totals #.": total
END IF
PRINT
LET sum = sum+total
LET total = 0
LOOP
IF turn = player THEN PRINT "Congratulations. You win." ELSE PRINT "Bad luck. The computer wins."
END</syntaxhighlight>
 
==={{header|PureBasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">If OpenConsole()
PLAYER.i = 1
COMP.i = 0
sum.i = 0
total.i = 0
turn.i = Random(1) + 0.5
Dim precomp.i(3)
precomp(0) = 1
precomp(1) = 1
precomp(2) = 3
precomp(3) = 2
While sum < 21
turn = 1 - turn
PrintN("The sum is " + Str(sum))
If turn = PLAYER
PrintN("It is your turn.")
While total < 1 Or total > 3 Or total + sum > 21
Print("How many would you like to total? ")
total = Val(Input())
Wend
Else
PrintN("It is the computer's turn.")
total = precomp(sum % 4)
PrintN("The computer totals " + Str(total) + ".")
EndIf
PrintN("")
sum + total
total = 0
Wend
If turn = PLAYER
PrintN("Congratulations. You win.")
Else
PrintN("Bad luck. The computer wins.")
EndIf
Input()
EndIf</syntaxhighlight>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">PLAYER = 1
COMP = 0
 
sum = 0
total = 0
turn = int(ran() + 0.5)
dim precomp(3)
precomp(0) = 1 : precomp(1) = 1
precomp(2) = 3 : precomp(3) = 2
 
while sum < 21
turn = 1 - turn
print "The sum is ", sum
if turn = PLAYER then
print "It is your turn."
while total < 1 or total > 3 or total + sum > 21
input "How many would you like to total? " total
wend
else
print "It is the computer's turn."
total = precomp(mod(sum, 4))
print "The computer totals ", total, "."
fi
print
sum = sum + total
total = 0
wend
 
if turn = PLAYER then
print "Congratulations. You win."
else
print "Bad luck. The computer wins."
fi</syntaxhighlight>
 
=={{header|bash}}==
<langsyntaxhighlight lang="bash">shopt -s expand_aliases
alias bind_variables='
{
Line 940 ⟶ 1,591:
fi
21_Game
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">/**
* Game 21 - an example in C language for Rosseta Code.
*
Line 1,082 ⟶ 1,733:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>21 Game
Line 1,178 ⟶ 1,829:
=={{header|C++}}==
===Model View Controller===
<langsyntaxhighlight lang="cpp">/**
* Game 21 - an example in C++ language for Rosseta Code.
*
Line 1,378 ⟶ 2,029:
}
return EXIT_SUCCESS; // dead code
}</langsyntaxhighlight>
 
===Model View Presenter===
<langsyntaxhighlight lang="cpp">/**
* Game 21 - an example in C++ language for Rosseta Code.
*
Line 1,620 ⟶ 2,271:
return EXIT_SUCCESS; // dead code
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,695 ⟶ 2,346:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">// 21 Game
 
using System;
Line 1,848 ⟶ 2,499:
 
 
</syntaxhighlight>
</lang>
=={{header|Commodore BASIC}}==
 
Written for BASIC v2 on the Commodore 64, this should be mostly compatible with all Commodore machines running any version of BASIC v2 and above. This implementation allows for one or both players to be either human or computer players. Also note that the computer player's "Thinking..." routine is a purely random delay meant to allow any human user time to process the flow of the game.
 
<langsyntaxhighlight lang="gwbasic">1 rem 21 game
2 rem for rosetta code
 
Line 1,942 ⟶ 2,593:
2000 rem some computer names to pick from
2010 data "Commodore 64","VIC-20","Commodore 128","PET"
2020 data "Plus/4","Commodore 16"</langsyntaxhighlight>
 
{{output}}
Line 2,044 ⟶ 2,695:
=={{header|EasyLang}}==
The computer plays optimally
<syntaxhighlight>
<lang>print "Who reaches 21, wins"
print "Who reaches 21, wins"
print "Do you want to begin (y/n)"
who = 1
if input = "n"
who = 12
.
who$[] = [ "Human" "Computer" ]
repeat
if who = 01
repeat
print ""
Line 2,062 ⟶ 2,715:
sleep 1
if sum mod 4 = 1
n = randomrandint 3 + 1
else
n = 4 - (sum + 3) mod 4
Line 2,070 ⟶ 2,723:
print who$[who] & ": " & n & " --> " & sum
until sum >= 21 or a$ = "q"
who = (who + 1) mod 2 + 1
.
if a$ <> "q"
Line 2,079 ⟶ 2,732:
print "Sorry, you lost"
.
.
.</lang>
</syntaxhighlight>
 
=={{header|Factor}}==
A difficulty system has been implemented. The player chooses a difficulty from 1-10. There is a <code>difficulty in 10</code> chance that the computer opponent gets to move first. There is a <code>difficulty in 10</code> chance each turn that the computer opponent will make the optimal move (i.e. setting the total to a number of the form <code>4n+1</code>) as opposed to a random move. At difficulty level 10, it is impossible for the human player to win the game.
{{works with|Factor|0.99 2020-07-03}}
<langsyntaxhighlight lang="factor">USING: accessors combinators.random continuations formatting io
kernel math math.functions math.parser multiline qw random
sequences ;
Line 2,164 ⟶ 2,818:
.welcome nl [ <game> do-turns ] with-return ;
 
MAIN: play-21-game</langsyntaxhighlight>
{{out}}
<pre>
Line 2,205 ⟶ 2,859:
 
=={{header|F sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
type Player =
| Computer
Line 2,271 ⟶ 2,925:
let run () = looper Start
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,298 ⟶ 2,952:
 
</pre>
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">: READKEY
1+ BEGIN
KEY DUP 27 = ABORT" Bye!"
48 - 2DUP > OVER 0 > AND IF
DUP 48 + EMIT CR SWAP DROP EXIT
THEN DROP
REPEAT
;
: 21GAME CLS
0 2 RND 1-
." 21 is a two player game." CR
." The game is played by choosing a number (1, 2 or 3) to be added to the running total. "
." The game is won by the player whose chosen number causes the running total to reach exactly 21."
." The running total starts at zero. One player will be the computer."
BEGIN
NOT
CR ." The sum is " OVER . CR
SWAP OVER IF
." How many would you like add?"
." (1-3) " 3 READKEY
ELSE
." It is the computer's turn."
4 OVER 1- 4 MOD -
DUP 4 = IF 3 RND 1+ MIN THEN
DUP CR ." Computer adds " . CR
THEN + SWAP
OVER 21 < NOT UNTIL
CR
IF ." Congratulations. You win."
ELSE ." Bad Luck. Computer wins."
THEN CR DROP
;</syntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight Fortranlang="fortran">! game 21 - an example in modern fortran language for rosseta code.
 
subroutine ai
Line 2,384 ⟶ 3,072:
end do
end do
end program main</langsyntaxhighlight>
{{out}}
<pre>game 21 - an example in fortran language for rosseta code.
Line 2,446 ⟶ 3,134:
 
=={{Header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define PLAYER 1
#define COMP 0
randomize timer
Line 2,476 ⟶ 3,164:
else
print "Bad luck. The computer wins."
end if</langsyntaxhighlight>
 
=={{Header|FutureBasic}}==
A fairly simple game, but this FutureBasic code builds a full, stand-alone, interactive app for it in about 100 LOC. It includes three levels of play, selectable via a popup menu:
* Min level has the computer play at random, choosing the optimal play only 1/3 of the time. Good for learning, or for kids.
* Mid level gives the computer its optimal play 2/3 of the time, making for more varied and interesting play.
* Max level always chooses the optimal play, meaning when the computer starts, it can't lose, which seems less fun.
*
<syntaxhighlight lang="futurebasic">
 
begin globals
begin enum 1
_btn1
_btn2
_btn3
_sum
_msg
_popup
_skill
_human = 0
_robot
end enum
str15 cr : cr = chr$(13)
str255 string(1) : short who = _human
byte best(3), sum, num, skill = 1 //Medium skill
poke int @best(0), 33751297 //Initialize computer responses
end globals
 
local fn buildWindow
subclass window 1, @"21 Game in FutureBasic" , ( 0, 0,640,200 )
popupbutton _popup,, 1, @"Minimum;Medium;Maximum" , ( 80, 17,100, 32 )
textlabel _msg , @"Original code: J. Reeve", ( 20,160,600, 32 )
textlabel _skill , @"Skill level:", ( 20, 12, 75, 32 )
textfield _sum ,, @"0",( 530,85,90,60 )
button _btn1 ,, , @"1",( 245,20,50,50 ),,NSBezelStyleRegularSquare
button _btn2 ,, , @"2",( 295,20,50,50 ),,NSBezelStyleRegularSquare
button _btn3 ,, , @"3",( 345,20,50,50 ),,NSBezelStyleRegularSquare
ControlSetAlignment( _msg, NSTextAlignmentCenter )
ControlSetAlignment( _sum, NSTextAlignmentCenter )
TextFieldSetEditable( _sum, no )
ControlSetFontWithName( _msg, @"Menlo", 15.0 )
ControlSetFontWithName( _btn1, @"Menlo", 20.0 )
ControlSetFontWithName( _btn2, @"Menlo", 20.0 )
ControlSetFontWithName( _btn3, @"Menlo", 20.0 )
ControlSetFontWithName( _sum, @"Menlo", 32.0 )
text @"menlo", 15.0
end fn
 
local fn show( add as byte )
CFStringRef msg
if (sum + add) > 21 then beep : exit fn
button 1, who : button 2, who : button 3, who
sum += add : cls
ControlSetIntegerValue( _sum, sum )
string( who ) += "+" + chr$( add or 48 ) + " "
print cr;cr;cr;string( _human );cr;cr;string( _robot )
if sum < 21
if who == _robot then msg = @"Your turn..." else msg = @"My turn..."
else
if who == _robot
msg = @"Too bad. I win. Press any key to play again."
else
msg = @"Congratulations! YOU WIN! Press any key to play again."
end if
end if
if peek( @string( who ) ) > 20 then textlabel _msg, msg
who = who xor _robot
end fn
 
local fn play( add as byte )
if sum + add > 21 then beep : exit fn
fn show( add ) //Show human's play
if sum < 21
if (skill + maybe) > 0 then num = best(sum mod 4) else num = rnd(3)
if sum + num > 21 then num = 21 - sum
timerbegin 1.0, NO //wait a sec before playing
fn show( num ) //Show computer's play
timerend
end if
end fn
 
local fn start
sum = 0 : cls
string( _human ) = " You: " : string( _robot ) = " Computer: "
string( 1-who ) += " "
if who == _robot
if skill == 2 then num = 1 else num = rnd( 3 )
textlabel _msg, fn StringWithFormat( @"I'll start with %i.", num )
fn show( num )
else
ControlSetIntegerValue( _sum, sum )
textlabel _msg, @"You start. Type or click 1, 2, or 3."
end if
end fn
 
local fn DoDialog( evt as long, tag as long)
byte key
select ( evt )
case _windowKeyUp
if sum == 21 then fn start : exit fn
if who == _robot then exit fn
key = intval( fn EventCharacters )
if key > 0 && key < 4 then fn play( key )
case _btnClick
if tag < _popup then beep : fn play( tag ) : exit fn
skill = popupbutton( _popup )
case _windowWillClose : end
end select
end fn
 
fn buildWindow
fn start
on dialog fn doDialog
handleevents
</syntaxhighlight>
{{out}}
[[File:FutureBasic screenshot for 21 Game.png]]
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">
' Gambas module file
 
Line 2,580 ⟶ 3,384:
Endif
 
End</langsyntaxhighlight>
 
<pre>
Line 2,639 ⟶ 3,443:
Good Bye!
</pre>
 
=={{header|GDScript}}==
{{works with|Godot|4.0}}
 
<syntaxhighlight lang="gdscript">
extends MainLoop
 
 
enum Player {Human, Computer}
 
const target: int = 21
 
 
# -1 is returned to request quit
func get_player_choice(total: int) -> int:
while true:
printraw("Player's choice: ")
var input: String = OS.read_string_from_stdin().strip_edges()
 
if input == "quit":
return -1
 
if not input.is_valid_int():
print("Please input an integer.")
continue
 
var input_int := int(input)
if input_int < 1 or input_int > 3:
print("Please pick a number from 1 to 3")
continue
 
if input_int + total > target:
print("Please do not exceed a total of %d" % target)
continue
 
return input_int
 
# This is required since Godot does not detect the unreachable code path
OS.crash("unreachable")
return 0
 
 
func get_computer_choice(total: int) -> int:
# This can be shortened using max() if you do not have type checking OCD
var remaining: int = target - total
return randi_range(1, 3 if remaining > 3 else remaining)
 
 
func play() -> void:
print("""\
Welcome to the 21 game.
Type quit to exit.""")
var total: int = 0
var player: Player
match randi_range(1, 2):
1:
player = Player.Human
print("You will go first.")
2:
player = Player.Computer
print("The computer will go first.")
 
while true:
print("\nThe total is %d" % total)
 
var choice: int
match player:
Player.Human:
choice = get_player_choice(total)
if choice == -1:
return
Player.Computer:
choice = get_computer_choice(total)
print("The computer plays %d" % choice)
assert(1 <= choice and choice <= 3)
 
total += choice
if total == target:
match player:
Player.Human: print("You win!")
Player.Computer: print("The computer won, you lose.")
return
assert(total < target)
 
match player:
Player.Human: player = Player.Computer
Player.Computer: player = Player.Human
 
 
func _process(_delta: float) -> bool:
randomize()
play()
return true
 
</syntaxhighlight>
 
=={{header|Go}}==
 
To give the human player a reasonable chance whoever goes first, the computer always chooses randomly when the running total is below 18 but otherwise chooses the exact number needed to win the game.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,742 ⟶ 3,641:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,848 ⟶ 3,747:
=={{header|Haskell}}==
The computer chooses values randomly.
<langsyntaxhighlight lang="haskell">import System.Random
import System.IO
import System.Exit
Line 2,911 ⟶ 3,810:
putStrLn $ (fst names) ++ " has won the game"
when (y == 1) $ do
putStrLn $ (snd names) ++ " has won the game"</langsyntaxhighlight>
 
=={{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 <nowiki>''</nowiki> types quickly, hence often used to trigger niladic verbs. g21 does not superfluously penalize final sums exceeding 21.
<syntaxhighlight lang="j">
<lang J>
g21=: summarize@play@setup ::('g21: error termination'"_)
 
Line 2,952 ⟶ 3,852:
write=: 1!:2 4: NB. unused
format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ])
</syntaxhighlight>
</lang>
<pre>
g21''
Line 3,012 ⟶ 3,912:
The computer strategy is to see if a valid value will win the game. If so, that value is selected. Otherwise, a random value among the valid values is selected.
 
<langsyntaxhighlight lang="java">
import java.util.Random;
import java.util.Scanner;
Line 3,148 ⟶ 4,048:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,293 ⟶ 4,193:
=={{header|Javascript}}==
The solution as a Javascript script inside a page written in HTML5. It should work with all modern browsers.
<langsyntaxhighlight lang="javascript"><!DOCTYPE html><html lang="en">
 
<head>
Line 3,451 ⟶ 4,351:
 
</body>
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
The computer or player can always win if they go first and choose a number that brings the total to one of the following: 1, 5, 9, 13, or 17. To make things vary more, there is a choice of computer play level at the start. The computer will randomly respond with level 1 and choose a random response 1/4 of the time at level 2.
<langsyntaxhighlight lang="julia">
function trytowin(n)
if 21 - n < 4
Line 3,538 ⟶ 4,438:
 
play21game()
</syntaxhighlight>
</lang>
 
=={{header|Koka}}==
<syntaxhighlight lang="koka">
import std/num/random
import std/os/readline
 
effect exit
final ctl exit(): ()
 
type player
Player
Computer
 
fun other(p: player): player
match p
Player -> Computer
Computer -> Player
 
fun show(p: player): string
match p
Player -> "Player"
Computer -> "Computer"
 
fun get-selection(max-int: int)
val i = readline().trim().parse-int()
match i
Just(x) | x >= 1 && x <= max-int -> x
_ ->
println("Please enter a number between 1 and " ++ max-int.show ++ " or press q to quit")
get-selection(max-int)
 
fun play(p: player, total: int)
println("Total: " ++ total.show)
match total
21 ->
// The player who reaches 21 wins the game, which is the player in the last loop
println(p.other.show ++ " wins!")
return ()
_ -> ()
val max = if total + 3 > 21 then 21 - total else 3
match p
Player ->
println("Player's turn")
val selection = get-selection(max)
play(p.other, total + selection)
Computer ->
println("Computer's turn")
val selection = (random-int() % max) + 1
println("Computer chooses " ++ selection.show)
play(p.other, total + selection)
 
fun main()
with final ctl exit() ()
"21 is a two player game. The game is played by choosing a number (1, 2, 3) to".println
"be added to the running total. The game is won by the player whose chosen number".println
"causes the running total to reach exactly 21. The running total starts at zero.".println
"".println
"You can quit the game at any time by typing 'q'.".println
val playerGoesFirst = random-bool()
val p1 = if playerGoesFirst then Player else Computer
play(p1, 0)
</syntaxhighlight>
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
gamewon = false
running_total = 0
Line 3,591 ⟶ 4,552:
 
end
</syntaxhighlight>
</lang>
 
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">SeedRandom[1234];
ClearAll[ComputerChoose, HumanChoose]
ComputerChoose[n_] := If[n < 18, RandomChoice[{1, 2, 3}], 21 - n]
Line 3,627 ⟶ 4,587:
If[runningtotal == 21, Print["You won!"]; Break[]];
];
]</langsyntaxhighlight>
{{out}}
<pre>You choose = 2
Line 3,657 ⟶ 4,617:
There is a simple strategy which allows the first player to win in any case. It consists to choose a value which gives
a running total equal to 1, 5, 9, 13 or 17. So never let the computer starts as the program uses this strategy.
<syntaxhighlight lang="nim">
<lang Nim>
# 21 game.
 
Line 3,759 ⟶ 4,719:
echo "Quitting game."
break
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,826 ⟶ 4,786:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">class TwentyOne {
@quit : Bool;
@player_total : Int;
Line 3,920 ⟶ 4,880:
return 0;
}
}</langsyntaxhighlight>
 
=={{header|Pascal|Delphi}}==
<langsyntaxhighlight lang="pascal">
program Game21;
 
Line 4,127 ⟶ 5,087:
end;
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">print <<'HERE';
The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
The player whose turn it is when the total reaches 21 wins. Enter q to quit.
Line 4,166 ⟶ 5,126:
my $i = $insults[1+int rand($#insults)];
print "$i, $g is not an integer between 1 and 3...\n"
}</langsyntaxhighlight>
{{out}}
<pre>The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
Line 4,187 ⟶ 5,147:
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
If the computer goes first you cannot win.<br>
{{libheader|Phix/online}}
Once the computer stops displaying "no clear strategy" you cannot win.<br>
If the computer goes first you cannot win, it will say "(you've already lost)" as soon as you have.<br>
The computer_first flag only applies to the first game. After winning, losing, or conceding, you go first.
You can run this online [http://phix.x10.mx/p2js/21Game.htm here]. (As noted below, a few improvements are in order.)
<!--<lang Phix>(notonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">bool</span> <span style="color: #000000;">computer_first</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
<span style="color: #000080;font-style:italic;">--
<span style="color: #004080;">bool</span> <span style="color: #000000;">show_spoiler</span> <span style="color: #0000FF;">=</span> <span style="color: #004600;">false</span>
-- demo\rosetta\21_Game.exw
-- ========================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- DEV NORMALIZESIZE, CANFOCUS, "You" not checked, VALUE_HANDLE.
-- The radio_texts simply don't do anything at all in p2js.</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"21 Game"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">help_text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Play by choosing 1, 2, or 3 to add to the running total (initially 0).
The first player to reach 21 wins.
If the computer goes first you cannot win.
If you leave your opponent on 18, 19, or 20, they will play {3,2,1} and win.
If you leave your opponent on 17, simply match their play {1,2,3} with {3,2,1} and win.
If you leave your opponent on 14, 15, or 16, they'll leave you on 17 and win.
So the aim is 21 (doh), and before that 17, 13, 9, 5, and 1. Anything else loses.
"""</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">radio_texts</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"You"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Computer"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Random"</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">button_text</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"three"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"concede"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"new game"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"quit"</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">procedureinclude</span> <span style="color: #000000;">computer_playpGUI</span><span style="color: #0000FF;">().</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0040800000FF;">integer,</span> <span style="color: #000000;">movevbox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">frame</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">radios</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0playstate</span>
<span style="color: #008080004080;">forsequence</span> <span style="color: #000000;">iradioset</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to,</span> <span style="color: #000000;">3</span> <span style="color: #008080;">dobuttons</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000008080;">movefunction</span> <span style="color: #0000FF000000;">=show_help</span> <span style="color: #0000000000FF;">i()</span>
<span style="color: #7060A8;">IupMessage</span><span style="color: #0000FF;">(</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">help_text</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">return</span> <span style="color: #008080004600;">endIUP_IGNORE</span> <span style="color: #008080000080;font-style:italic;">if-- (don't open browser help!)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">forfunction</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">move</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8008080;">putsfunction</span> <span style="color: #0000FF000000;">(play</span><span style="color: #0000000000FF;">1(</span><span style="color: #0000FF004080;">,integer</span> <span style="color: #008000000000;">"no clear strategy\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000008080;">moveif</span> <span style="color: #0000FF000000;">=</span> <span style="color: #7060A8;">randn</span><span style="color: #0000FF;">(</span><span style!="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">21</span><span style="color: #0000FF;">-</span><span style="color: #000000;">total</span><span style="color: #0000FF008080;">))then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">6</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">title</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Total is %d. I play %d.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">move</span><span style="color: #0000FF;">})</span>
<span style="color: #000000008080;">totalif</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">+></span><span style="color: #000000;">3</span> <span style="color: #000000008080;">movethen</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span> <span style="color: #0000FF000080;">=</span><span font-style="color: #000000italic;">21</span>-- <spanconcede style="color:or #008080;">thennew_game</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1total</span> <span style="color: #0000FF;">,=</span><span style="color: #008000;">"21! I win!\n"</span><span style="color: #0000FF000000;">)0</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"(conceded) "</span><span style="color: #0000FF;">:</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080000000;">endtitle</span> <span style="color: #0080800000FF;">procedure&=</span> <span style="color: #008000;">"Total is 0"</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttributePtr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">radios</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE_HANDLE"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">putsfind</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1r</span><span style="color: #0000FF;">,</span><span style="color: #008000000000;">"\n21 game\n\n"radioset</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8008080;">putsif</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">(=</span><span style="color: #000000;">12</span> <span style="color: #008080;">or</span> <span style="color: #0000FF;">,(</span><span style="color: #008000000000;">n</span><span style="Presscolor: escape#0000FF;">=</span><span orstyle="color: q#000000;">3</span> to<span quitstyle="color: the#008080;">and</span> game,<span cstyle="color: to#7060A8;">rand</span><span concedestyle="color: and#0000FF;">(</span><span startstyle="color: a#000000;">2</span><span newstyle="color: game#0000FF;">)=</span><span fromstyle="color: 0\n\n#000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">","</span> <span style="color: #000080;font-style:italic;">-- trigger a computer move</span>
<span style="color: #008080;">if</span> <span style="color: #000000008080;">computer_firstend</span> <span style="color: #008080;">thenif</span>
<span style="color: #7060A8;">printfIupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1buttons</span><span style="color: #0000FF;">,[</span><span style="color: #008000000000;">1</span><span style="Totalcolor: is %d#0000FF;">.\n.</span><span style="color: #000000;">3</span><span style="color: #0000FF;">],{</span><span style="color: #000000008000;">total"ACTIVE"</span><span style="color: #0000FF;">}),</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">computer_play</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">show_spoiler</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- The secret to winning!</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Uif!pomz!xbz!up!xjo!jt!qmbz!2!gjstu-!uifo!5.=dpnqvufs!npwf?!fwfsz!ujnf"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Total is %d. enter 1, 2, or 3: "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">total</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #000000;">#1B</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"esc"</span><span style="color: #0000FF;">:</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'1'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'3'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">-=</span> <span style="color: #008000;">'0'</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #000000;">21</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Too big\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000000080;">total</span> <span font-style="color: #0000FFitalic;">+=</span>-- <spann style="color: #000000;">ch1..3</span>
<span style="color: #008080000000;">iftitle</span> <span style="color: #0000000000FF;">total=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Total is %d"</span><span style="color: #0000000000FF;">21,</span><span style="color: #000000;">total</span><span style="color: #0080800000FF;">then)</span>
<span style="color: #7060A8008080;">putsif</span> <span style="color: #0000FF000000;">(total</span><span style="color: #0000000000FF;">1=</span><span style="color: #0000FF000000;">,21</span><span style="color: #008000;">"21! You win!\n"</span> <span style="color: #0000FF000080;font-style:italic;">-- (from key_cb)</span>
<span style="color: #008080;">or</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">+</span><span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">21</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (invalid)</span>
<span style="color: #008080;">else</span>
<span style="color: #000000008080;">computer_playreturn</span> <span style="color: #0000FF004600;">()IUP_IGNORE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">", you play %d (-&gt; %d),"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">=</span><span style="color: #000000;">21</span> <span style="color: #008080;">then</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" you win"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">elsifif</span> <span style="color: #0000007060A8;">chfind</span><span style="color: #0000FF;">=(</span><span style="color: #000000008000;">#1B','</span> <span style="color: #0080800000FF;">or,</span> <span style="color: #7060A8000000;">lowertitle</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">and</span> <span style="color: #000000;">chtotal</span><span style="color: #0000FF;">)!=</span><span style="color: #008000000000;">'q'21</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000000080;">1</span><span font-style="color: #0000FFitalic;">,</span><span-- style="color:computer #008000;">"Quitting\n"</span><span style="color: #0000FF;">)move</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">moves</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">),</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">exit</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">moves</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)=</span><span style="color: #008000;">'c'</span> <span style="color: #008080;">or</span> <span style="color: #000000;">total</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">21</span> <span style="color: #008080;">thenn</span>
<span style="color: #000000;">totaltitle</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" computer plays %d (-&gt; %d)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">0n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">=</span><span style="color: #000000;">21</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">", computer wins"</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">total</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">", (you've already lost)"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">=</span><span style="color: #000000;">21</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">title</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" GAME OVER"</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buttons</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">total</span><span style="color: #0000FF;">></span><span style="color: #000000;">18</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buttons</span><span style="color: #0000FF;">[</span><span style="color: #000000;">22</span><span style="color: #0000FF;">-</span><span style="color: #000000;">total</span><span style="color: #0000FF;">..</span><span style="color: #000000;">3</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buttons</span><span style="color: #0000FF;">[</span><span style="color: #000000;">4</span><span style="color: #0000FF;">],</span><span style="color: #008000;">"ACTIVE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">total</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">IupSetFocus</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (stops inactive button beeping)</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">playstate</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">endreturn</span> <span style="color: #008080004600;">whileIUP_IGNORE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</lang>-->
{{out}}
<span style="color: #008080;">function</span> <span style="color: #000000;">button_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<pre>
<span style="color: #004080;">string</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ih</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">)</span>
21 game
<span style="color: #008080;">return</span> <span style="color: #000000;">play</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">button_text</span><span style="color: #0000FF;">))</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Press escape or q to quit the game, c to concede and start a new game from 0
<span style="color: #008080;">constant</span> <span style="color: #000000;">cb_button</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"button_cb"</span><span style="color: #0000FF;">)</span>
 
Total is 0. enter 1, 2, or 3: 1
<span style="color: #008080;">function</span> <span style="color: #000000;">key_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*dlg*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
no clear strategy
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (standard practice for me)</span>
Total is 1. I play 3.
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_F5</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (let browser reload work)</span>
Total is 4. enter 1, 2, or 3: 1
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_F1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">show_help</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
no clear strategy
<span style="color: #008080;">return</span> <span style="color: #000000;">play</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"123CNQ"</span><span style="color: #0000FF;">))</span>
Total is 5. I play 1.
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Total is 6. enter 1, 2, or 3: 3
no clear strategy
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
Total is 9. I play 1.
<span style="color: #000000;">playstate</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"EXPAND=HORIZONTAL, PADDING=10x10"</span><span style="color: #0000FF;">)</span>
Total is 10. enter 1, 2, or 3: 1
<span style="color: #000000;">radioset</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupToggle</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">radio_texts</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"RIGHTBUTTON=YES, CANFOCUS=NO"</span><span style="color: #0000FF;">}})</span>
Total is 11. I play 2.
<span style="color: #000000;">buttons</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">button_text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cb_button</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"PADDING=5x5"</span><span style="color: #0000FF;">}})</span>
Total is 13. enter 1, 2, or 3: 3
<span style="color: #000000;">radios</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupRadio</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">(</span><span style="color: #000000;">radioset</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"GAP=45"</span><span style="color: #0000FF;">))</span>
Total is 16. I play 1.
<span style="color: #000000;">frame</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`First Player:`</span><span style="color: #0000FF;">),</span><span style="color: #000000;">radios</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"NORMALIZESIZE=VERTICAL"</span><span style="color: #0000FF;">)</span>
Total is 17. enter 1, 2, or 3: 2
<span style="color: #000000;">vbox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">frame</span><span style="color: #0000FF;">,</span><span style="color: #000000;">playstate</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">(</span><span style="color: #000000;">buttons</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"GAP=10"</span><span style="color: #0000FF;">)},</span><span style="color: #008000;">"MARGIN=20x10"</span><span style="color: #0000FF;">)</span>
Total is 19. I play 2.
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vbox</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="%s", MINSIZE=540x200`</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">})</span>
21! I win!
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
Total is 0. enter 1, 2, or 3: q
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">({</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #000000;">buttons</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"KEY_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"key_cb"</span><span style="color: #0000FF;">))</span>
Quitting
<span style="color: #7060A8;">IupSetAttributeHandle</span><span style="color: #0000FF;">(</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"PARENTDIALOG"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
</pre>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">play</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"new game"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">button_text</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
The solution as a server-side PHP7 script and HTML5.
<langsyntaxhighlight PHPlang="php"><!DOCTYPE html>
<html lang="en">
 
Line 4,419 ⟶ 5,410:
?>
 
</body></langsyntaxhighlight>
 
=={{header|Picat}}==
{{trans|Julia}}
<syntaxhighlight lang="picat">import util.
 
main =>
N = 0,
Level = prompt("Level of play (1=dumb, 3=smart)"),
Algo = choosewisely,
if Level == "1" then
Algo := choosefoolishly
elseif Level == "2" then
Algo := choosesemiwisely
elseif Level != "3" then
println("Bad choice syntax--default to smart choice")
end,
Whofirst = prompt("Does computer go first? (y or n)"),
if Whofirst[1] == 'y' || Whofirst[1] == 'Y' then
N := apply(Algo, N)
end,
while (N < 21)
N := playermove(N),
if N == 21 then
println("Player wins! Game over, gg!"),
halt
end,
N := apply(Algo,N)
end.
trytowin(N) =>
if 21 - N < 4 then
printf("Computer chooses %w and wins. GG!\n", 21 - N),
halt
end.
 
choosewisely(N) = NextN =>
trytowin(N),
Targets = [1, 5, 9, 13, 17, 21],
once ((member(Target, Targets), Target > N)),
Bestmove = Target - N,
if Bestmove > 3 then
printf("Looks like I could lose. Choosing a 1, total now %w.\n", N + 1),
NextN = N+1
else
printf("On a roll, choosing a %w, total now %w.\n", Bestmove, N + Bestmove),
NextN = N + Bestmove
end.
choosefoolishly(N) = NextN =>
trytowin(N),
Move = random() mod 3 + 1,
printf("Here goes, choosing %w, total now %w.", Move, N+Move),
NextN = N+Move.
choosesemiwisely(N) = NextN =>
trytowin(N),
if frand() > 0.75 then
NextN = choosefoolishly(N)
else
NextN = choosewisely(N)
end.
prompt(S) = Input =>
printf(S ++ ": => "),
Input = strip(read_line()).
playermove(N) = NextN =>
Rang = cond(N > 19, "1 is all", cond(N > 18, "1 or 2", "1, 2 or 3")),
Prompt = to_fstring("Your choice (%s), 0 to exit", Rang),
Nstr = prompt(Prompt),
if Nstr == "0" then
halt
elseif Nstr == "1" then
NextN = N+1
elseif Nstr == "2" && N < 20 then
NextN = N + 2
elseif Nstr == "3" && N < 19 then
NextN = N + 3
else
NextN = playermove(N)
end.
</syntaxhighlight>
 
=={{header|Python}}==
Line 4,425 ⟶ 5,498:
 
{{works with|Python 2.X and 3.X}}
<langsyntaxhighlight lang="python">
from random import randint
def start():
Line 4,487 ⟶ 5,560:
print("Computer wins {0} game, human wins {1} games".format(c,m))
t = raw_input("Another game?(press y to continue):")
r = (t=="y")</langsyntaxhighlight>
 
{{out}}
Line 4,620 ⟶ 5,693:
 
===Python: using tkinter===
<langsyntaxhighlight lang="python">
''' Python 3.6.5 code using Tkinter graphical user interface.
Starting player chosen randomly. '''
Line 4,864 ⟶ 5,937:
g = Game(root)
root.mainloop()
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ say
"Who goes first: Computer, Player"
say " or Random?" cr
[ $ "Enter C, P or R: " input
dup size 1 != iff drop again
0 peek
dup char C = iff [ drop 0 ] done
dup char P = iff [ drop 1 ] done
char R = iff [ 2 random ] done
again ]
cr
dup iff [ say "You go first." ]
else [ say "I will go first." ]
cr ] is chooseplayer ( --> n )
 
forward is player ( n --> n x )
 
[ [ dup 17 > iff 1 done
4 over 4 mod
dup 0 = if [ drop 3 ]
- ]
dup say "Computer chooses " echo
say "." cr
+ ' player ] is computer ( n --> n x )
 
[ say "Choose 1 2 or 3 (running "
$ "total must not exceed 21, Q to quit): " input
dup $ "Q" = iff [ drop 21 999 ] done
trim reverse trim reverse
$->n not iff drop again
dup 1 4 within not iff drop again
2dup + 21 > iff drop again
+ ' computer ] resolves player ( n --> n x )
 
[ say "The player who makes 21 loses." cr
0 chooseplayer
iff [ ' player ] else [ ' computer ]
[ say "Running total is "
over echo say "." cr cr
do
over 21 = until ]
cr
dup 999 = iff
[ drop 2drop say "Quitter!" ] done
' computer = iff
[ say "The computer won!" ]
else [ say "You won! Well done!" ]
drop ] is play ( --> )</syntaxhighlight>
 
{{out}}
 
As a dialogue in the Quackery shell.
 
<pre>/O> play
...
The player who makes 21 loses.
Who goes first: Computer, Player or Random?
Enter C, P or R: C
 
I will go first.
Running total is 0.
 
Computer chooses 1.
Running total is 1.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): Q
 
Quitter!
Stack empty.
 
/O> play
...
The player who makes 21 loses.
Who goes first: Computer, Player or Random?
Enter C, P or R: R
 
You go first.
Running total is 0.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 2
Running total is 2.
 
Computer chooses 2.
Running total is 4.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 3
Running total is 7.
 
Computer chooses 1.
Running total is 8.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 1
Running total is 9.
 
Computer chooses 3.
Running total is 12.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 4
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 1
Running total is 13.
 
Computer chooses 3.
Running total is 16.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 3
Running total is 19.
 
Computer chooses 1.
Running total is 20.
 
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 2
Choose 1 2 or 3 (running total must not exceed 21, Q to quit): 1
 
The computer won!
Stack empty.
 
/O> </pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">game21<-function(first = c("player","ai","random"),sleep=.5){
state = 0
finished = F
Line 4,915 ⟶ 6,108:
turn = turn + 1
}
}</langsyntaxhighlight>
 
<syntaxhighlight lang="text">game21()</langsyntaxhighlight>
{{out}}
<pre>The total is now 0
Line 4,940 ⟶ 6,133:
You win!</pre>
 
<langsyntaxhighlight Rlang="r">game21(first = "ai")</langsyntaxhighlight>
{{out}}
<pre>The total is now 0
Line 4,951 ⟶ 6,144:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define limit 21)
Line 4,986 ⟶ 6,179:
[(= new-total limit) (win human-turn?)]
[(> new-total limit) (win (not human-turn?))]
[else (loop new-total (not human-turn?))]))</langsyntaxhighlight>
 
{{out}}
Line 5,035 ⟶ 6,228:
{{works with|Rakudo|2018.09}}
Since there is no requirement that the computer play sensibly, it always plays a random guess so the player has some chance to win.
<syntaxhighlight lang="raku" perl6line>say qq :to 'HERE';
The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
The player whose turn it is when the total reaches 21 wins. Enter q to quit.
Line 5,065 ⟶ 6,258:
print ('Yo mama,', 'Jeez,', 'Ummmm,', 'Grow up,', 'Did you even READ the instructions?').roll;
say " $g is not an integer between 1 & 3..."
}</langsyntaxhighlight>
{{out|Sample game}}
<pre>The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
Line 5,100 ⟶ 6,293:
 
This REXX version allows the user to choose if the computer should go first.
<langsyntaxhighlight lang="rexx">/*REXX program plays the 21 game with a human, each player chooses 1, 2, or 3 which */
/*──────────── is added to the current sum, the first player to reach 21 exactly wins.*/
sep= copies('─', 8); sep2= " "copies('═', 8)" " /*construct an eye─catching msg fences.*/
Line 5,136 ⟶ 6,329:
if bad then iterate /*Had an error? Then get another number*/
x= x/1; if $+x>goal then call ser "Number will cause the sum to exceed " goal': ' x
end /*until*/; return</langsyntaxhighlight>
{{out|output|text=''':'''}}
<pre>
Line 5,176 ⟶ 6,369:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : 21 Game
 
Line 5,285 ⟶ 6,478:
}
}
</syntaxhighlight>
</lang>
Output:<br>
[http://kepkezelo.com/images/1hyutakip6vo1t1rpypy.jpg 21 Game]
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
# 21 Game - an example in Ruby for Rosetta Code.
 
Line 5,397 ⟶ 6,590:
end
puts 'Good bye!'
</syntaxhighlight>
</lang>
 
=={{header|rustRust}}==
<langsyntaxhighlight lang="rust">use rand::Rng;
use std::io;
 
Line 5,625 ⟶ 6,818:
println!("player: {} win: {}", players[1].get_name(), players[1].wins);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">
<lang Scala>
object Game21 {
 
Line 5,720 ⟶ 6,913:
}
}
</syntaxhighlight>
</lang>
 
=={{header|uBasic/4tH}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="text">dim @p(4)
 
push 1, 1, 3, 2
for i = 3 to 0 step -1 : @p(i) = pop() : next
a = 0 : t = rnd(2)
do while s < 21
t = 1 - t
print using "The sum is _#"; s
if t = 1 then
print "It is your turn."
do
while (a < 1) + (a > 3) + (a+s > 21)
input "How many would you like to add? ", a
loop
else
print "It is the computer's turn."
a = @p(s % 4)
print using "The computer adds #."; a
endif
 
print
s = s + a
a = 0
loop
if t = 1 then
print "Congratulations. You win."
else
print "Bad luck. The computer wins."
endif</syntaxhighlight>
=={{header|Visual Basic .NET}}==
 
Line 5,732 ⟶ 6,958:
<p>
The file MainWindow.xaml.vb with Visual Basic source code.
</p><langsyntaxhighlight lang="vbnet">' Game 21 in VB.NET - an example for Rosetta Code
 
Class MainWindow
Line 5,795 ⟶ 7,021:
End If
End Sub
End Class</langsyntaxhighlight>
<p>
The file MainWindow.xaml with GUI source code written in XAML.
</p><langsyntaxhighlight lang="xml"><Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Line 5,827 ⟶ 7,053:
</Grid>
</Window>
</syntaxhighlight>
</lang>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import os
import rand
import rand.seed
import strconv
 
fn get_choice(mut total &int) bool {
for {
text := os.input("Your choice 1 to 3 : ")
if text == "q" || text == "Q" {
return true
}
input := strconv.atoi(text) or {-1}
if input == -1 {
println("Invalid number, try again")
continue
}
new_total := *total + input
match true {
input < 1 || input > 3 {
println("Out of range, try again")
}
new_total > 21 {
println("Too big, try again")
}
else {
total = new_total
println("Running total is now ${*total}")
return false
}
}
}
return false
}
fn main() {
rand.seed(seed.time_seed_array(2))
mut computer := rand.intn(2) or {0} != 0
println("Enter q to quit at any time\n")
if computer {
println("The computer will choose first")
} else {
println("You will choose first")
}
println("\nRunning total is now 0\n")
mut choice := 0
mut total := 0
for round := 1; ; round++ {
println("ROUND $round:\n")
for i := 0; i < 2; i++ {
if computer {
if total < 18 {
choice = 1 + rand.intn(3) or {1}
} else {
choice = 21 - total
}
total += choice
println("The computer chooses $choice")
println("Running total is now $total")
if total == 21 {
println("\nSo, commiserations, the computer has won!")
return
}
} else {
quit := get_choice(mut total)
if quit {
println("OK, quitting the game")
return
}
if total == 21 {
println("\nSo, congratulations, you've won!")
return
}
}
println('')
computer = !computer
}
}
}</syntaxhighlight>
 
{{out}}
Sample game:
<pre>
Enter 0 to quit at any time
 
You will choose first
 
Running total is now 0
 
ROUND 1:
 
Your choice 1 to 3: 3
Running total is now 3
 
The computer chooses 2
Running total is now 5
 
ROUND 2:
 
Your choice 1 to 3: 3
Running total is now 8
 
The computer chooses 1
Running total is now 9
 
ROUND 3:
 
Your choice 1 to 3: 3
Running total is now 12
 
The computer chooses 3
Running total is now 15
 
ROUND 4:
 
Your choice 1 to 3: 2
Running total is now 17
 
The computer chooses 3
Running total is now 20
 
ROUND 5:
 
Your choice 1 to 3: 1
Running total is now 21
 
So, congratulations, you've won!
</pre>
 
=={{header|Wren}}==
Line 5,833 ⟶ 7,189:
{{libheader|Wren-fmt}}
{{libheader|Wren-ioutil}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Conv
import "./ioutil" for Input
import "random" for Random
 
Line 5,895 ⟶ 7,251:
}
round = round + 1
}</langsyntaxhighlight>
 
{{out}}
2,023

edits