|
First Summer 2008 |
Here's how my program works:
Here's a solution:>>> >>> 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. >>>
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."