2.10 The Game of Nim

Next, we will teach the computer to play Nim. The game of Nim begins with a pile of stones. Two players take turns nimming (stealing) 1, 2, or 3 stones from the pile. The player who steals the last stone wins the game. You can play this game with stones, coins, or any tokens you choose. We will play Nim with digital stones.

In this section, we will have the computer be both players so that the computer is essentially playing itself. But the computer will have two different strategies for making a play. Our first strategy will be to choose a random number of stones to remove. To do this, we need to explore how to generate a random number.

2.10.1 Random Numbers

To generate a random play, we will use the random module. This ...

Get Python Programming in Context, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.