28 — Game: an opponent that knows the rule
An opponent worth playing needs a rule, not only luck. In this game you take 1, 2 or 3 stones from a pile, and whoever takes the last stone loses. The computer follows a rule that keeps it in a winning position, and the whole rule is one remainder.
Steps
The rule first. If the pile you hand over is a multiple of four, then whatever your opponent takes, you can make it a multiple of four again. So the computer takes the remainder of the pile divided by four:
run it →set pile to 9 set mine to the remainder of pile divided by 4 show mineNine divided by four leaves one, so it takes one and leaves eight.
When the remainder is nought there is no winning move, so it plays at random:
run it →set pile to 8 set mine to the remainder of pile divided by 4 if mine equals 0 set mine to random number from 1 to 3 end show mineYour turn asks for a number, and asks again when it is not 1 to 3.
skipabandons the rest of this turn and goes back to the top of the loop:
run it →repeat forever ask number taken How many? 1, 2 or 3 if taken is less than 1 show it has to be 1, 2 or 3 skip end stop endskiponly works inside a loop. Outside one, the compiler stops you.Take the stones off the pile; at nought, whoever just took has lost:
run it →set pile to 12 set taken to 3 subtract taken from pile show pileHere is the whole game. Put it in
nim.nmeand play:
run it →set pile to 12 repeat forever show stones left show pile ask number taken How many? 1, 2 or 3 if taken is less than 1 show it has to be 1, 2 or 3 skip end if taken is greater than 3 show it has to be 1, 2 or 3 skip end subtract taken from pile if pile equals 0 show you took the last stone, you lose stop end set mine to the remainder of pile divided by 4 if mine equals 0 set mine to random number from 1 to 3 end subtract mine from pile show the computer took show mine if pile equals 0 show the computer took the last stone, you win stop end endTry 3, then 1, then 3. The computer keeps handing back a multiple of four, so from a pile of twelve you are the one who wins.
Try it yourself
Change the starting pile to 15. Fifteen is not a multiple of four, so the computer takes the good position first. Play a few rounds and work out why. A name that counts your wins is a good next step.
What you learned
the remainder of … divided by …is what is left over, and it is this whole strategy.skipgives up the rest of this turn and starts the loop again.- An opponent's "thinking" is one rule worked out from where the game is now.
- A random move where the rule cannot win keeps the opponent from collapsing.