First Summer 2008


Lecture Notes 06/04: Objects Encapsulating a Game Behavior
Let's implement a game that works like this:

  1. The game starts with a pile of marbles.
  2. The user moves first.
  3. A move means removing at least one, at most half of the marbles.
  4. The computer always makes a random legal move.
  5. Wins the player who moves to make the pile a pile of size one.

Here's how my program works:

>>> 
>>> g = Nim(10)
>>> g.report()
The height is: 10
>>> g.move(6)
You want to move 6 but the move is illegal.
The game is over.
The computer wins.
>>> g = Nim(10)

>>> g.move(3)
You move: 3
The height is: 7
>>> g.computerMove()
Computer moves: 1
The height is: 6
>>> g.move(3)
You move: 3
The height is: 3
>>> g.computerMove()
Computer moves: 1
The height is: 2
>>> g.move(1)
You move: 1
The height is: 1
>>> g.computerMove()
Computer moves: 1
The game is over.
The user wins.
>>> g = Nim(10)
>>> g.move(5)
You move: 5
The height is: 5
>>> g.computerMove()
Computer moves: 2
The height is: 3

>>> g.move(1)
You move: 1
The height is: 2
>>>  g.computerMove()
Computer moves: 1
The height is: 1
>>> g.move(1)
You move: 1
The game is over.
The computer wins.
>>> 
Here's a solution:
import random

class Nim(object):
    def __init__(self, height):
        self.height = height
        self.player = 0
        self.names = ["user", "computer"]
        self.scores = {}
        self.scores["user"] = 0
        self.scores["computer"] = 0
    def move(self):
        if self.height == 1:
            print self.names[self.player], "has lost the game."
            winner = self.names[(self.player+1)%2]
            self.scores[winner] += 1
            self.player = 0
            self.height = int(raw_input("New height for new game:"))
        else:
            if self.player == 0:
                user = int(raw_input("How many? "))
                if user > 0 and user <= self.height / 2:
                    self.height -= user
                else:
                    print self.names[self.player], "has lost the game."
                    winner = self.names[(self.player+1)%2]
                    self.scores[winner] += 1
                    self.player = 0
                    self.height = int(raw_input("New height for new game:"))
            else:
                comp = random.randrange(1, self.height/2+1)
                print "The computer chooses", comp
                self.height -= comp
            self.player = (self.player + 1) % 2
            self.report()
    def report(self):
        print "The height is now:", self.height
        print "The",self.names[self.player],"moves."


Last updated: June 04, 2008 by Adrian German for A201/A597