21 game: Difference between revisions

2,073 bytes added ,  2 years ago
no edit summary
No edit summary
No edit summary
Line 4,540:
</body></lang>
 
=={{header|PythonPicat}}==
{{trans|Julia}}
<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.
</lang>
 
=={{header|Python}}==
Anonymous user