python: Create a NimGame in class that implements the simplest form of two-playe
ID: 3683611 • Letter: P
Question
python: Create a NimGame in class that implements the simplest form of two-player Nim-style games (http://en.wikipedia.org/wiki/Nim), sometimes called the "subtraction game." The game starts with some specific number of items - pebbles, coins, matchsticks, balls. Players take turns removing between 1 and 3 items. The player who removes the last item loses. You can play an interactive on-line version of the game here:http://upload.wikimedia.org/wikipedia/commons/4/4d/Subtraction_game_SMIL.svg
assume there's one human player playing against the computer and that the human always goes first.
To create the NimGame class, you only need to implement two methods:
an __init__ method, with an argument specifying how many items (we'll call them balls) the game should start with
a take method, with an argument specifying how many balls the human player wishes to remove. This method should check that the specified number of balls is valid and, if so, remove that many balls, and check whether or not the player has lost. Next, it should automatically select a number of balls for the computer to remove, and update the game state accordingly (and check whether the computer has lost).
A sample use of the class might produce these results:
Explanation / Answer
Hi, following is the required source code in python.
import random
class NimGame:
#initialization
def __init__(self, nob):
self.nob = nob;
print "Nim game initialized with ", nob, " balls."
def take(self, balls):
if (balls < 1 or balls > 3):
print "You can only remove between 1 and 3 balls."
else:
if (self.nob - balls >= 0):
self.nob = self.nob - balls
print "You took ", balls, " balls. ", self.nob, " remain."
if(self.nob == 0):
print "Computer wins."
else:
compBalls = 0
if(self.nob >= 3):
compBalls = random.randint(1,3)
else:
compBalls = 1
self.nob = self.nob - compBalls
print "Computer took ", compBalls, " balls. ", self.nob, " remain."
if(self.nob == 0):
print "You win."
else:
print "You can't remove ", balls, " balls. You have only ", self.nob, " balls remaining."
Please upvote the answer if it is helpful for you.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.