Nim game: Difference between revisions

Line 1,701:
 
Computer wins.
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
<syntaxhighlight lang=jq>
def play($tokens):
label $out
| "There are \($tokens) tokens. Take at most \([$tokens,3]|min) or enter q to quit.",
( foreach inputs as $in ( {$tokens};
if $in == "q" then break $out
else .in = $in
| if $in | test("^[0-9]+$") then .in |= tonumber else .in = null end
| if .in and .in > 0 and .in < 4
then (4 - .in) as $ct
| (if $ct == 1 then "" else "s" end) as $s
| .emit = " Computer takes \($ct) token\($s);"
| .tokens += -4
else .emit = "Please enter a number from 1 to \([3, .tokens]|min) inclusive."
end
end;
.emit,
if .tokens == 0
then "\nComputer wins!", break $out
elif .tokens < 0 then "\nCongratulations!", break $out
else "\(.tokens) tokens remain. How many tokens will you take?"
end )) ;
 
play(12)
</syntaxhighlight>
<pre>
$ jq -nRr -f nim-game.jq
There are 12 tokens. Take at most 3 or enter q to quit.
2
Computer takes 2 tokens;
8 tokens remain. How many tokens will you take?
1
Computer takes 3 tokens;
4 tokens remain. How many tokens will you take?
4
Please enter a number from 1 to 3 inclusive.
4 tokens remain. How many tokens will you take?
3
Computer takes 1 token;
 
Computer wins!
</pre>
 
2,442

edits