Nim game: Difference between revisions

Content added Content deleted
(add Rust)
(add Smalltalk)
Line 1,107: Line 1,107:
Computer takes 3 tokens.
Computer takes 3 tokens.
0 tokens remaining.
0 tokens remaining.

Computer wins!
</pre>

=={{header|Smalltalk}}==
===GNU Smalltalk===
<lang smalltalk>
Object subclass: Nim [
| tokens |
<comment: 'I am a game of nim'>
Nim class >> new [
<category: 'instance creation'>
^(super new) init: 12
]
init: t [
<category: 'instance creation'>
tokens := t.
^self
]
pTurn [
| take |
<category: 'gameplay'>
Transcript nextPutAll: 'How many tokens will you take?: '.
take := (stdin nextLine) asNumber.
((take < 1) | (take > 3))
ifTrue: [Transcript nextPutAll: 'Invalid input';nl;nl. self pTurn]
ifFalse: [tokens := tokens - take]
]
cTurn [
| take |
<category: 'gameplay'>
take := tokens - (4 * (tokens // 4)).
Transcript nextPutAll: 'Computer takes '.
take printOn: Transcript.
Transcript nextPutAll: ' tokens';nl.
tokens := tokens - take
]
mainLoop [
<category: 'main loop'>
Transcript nextPutAll: 'Nim game';nl.
Transcript nextPutAll: 'Starting with '.
tokens printOn: Transcript.
Transcript nextPutAll: ' tokens';nl;nl.
1 to: 5 do: [ :n |
self pTurn.
self printRemaining.
self cTurn.
self printRemaining.
(tokens = 0)
ifTrue:[Transcript nextPutAll: 'Computer wins!';nl. ^0]
]
]
printRemaining [
<category: 'information'>
tokens printOn: Transcript.
Transcript nextPutAll: ' tokens remaining';nl;nl
]
]

g := Nim new.
g mainLoop.
</lang>
{{out}}
sample game:
<pre>
Nim game
Starting with 12 tokens

How many tokens will you take?: foo
Invalid input

How many tokens will you take?: 3
9 tokens remaining

Computer takes 1 tokens
8 tokens remaining

How many tokens will you take?: 4
Invalid input

How many tokens will you take?: 2
6 tokens remaining

Computer takes 2 tokens
4 tokens remaining

How many tokens will you take?: 1
3 tokens remaining

Computer takes 3 tokens
0 tokens remaining


Computer wins!
Computer wins!