Here’s what I recently did for nims.py
…
# nims.py
# May 12, 2015
# G.A.R.
def play_nims(pile, max_stones):
'''
An interactive two-person game; also known as Stones.
@param pile: the number of stones in the pile to start
@param max_stones: the maximum number of stones you can take on one turn
'''
## Basic structure of program (feel free to alter as you please):
while pile > 0:
stones = 0
while stones < 1 or stones > min(max_stones, pile):
stones = int(raw_input("Player 1 - Number to remove (1 to " + str(min(max_stones, pile)) + "): "))
pile -= stones
print(str(pile) + " remain")
if pile == 0:
player = "1"
break
stones = 0
while stones < 1 or stones > min(max_stones, pile):
stones = int(raw_input("Player 2 - Number to remove (1 to " + str(min(max_stones, pile)) + "): "))
pile -= stones
print(str(pile) + " remain")
if pile == 0:
player = "2"
break
print("Game over. Player " + player + " wins.")
play_nims(48, 7)
Concerning invalid input, it does not check whether the input can be converted to int
; it assumes that it can. The checking is here …
while stones < 1 or stones > min(max_stones, pile):
So, valid moves are between 0
and max_stones
, inclusive, as long as the pile contains at least max_stones
. After that, a valid move is between 0
and pile
, inclusive. But, of course, that occurs only when a player is in a position to immediately win the game.
But during a previous run of the MMOOC, I was less lazy, and put more effort into this exercise, distilling the two players into a single loop, and checking the input more rigorously. To check for non-integer input, it uses a try
- except
structure.
# nims_rand.py
# Last modified November 5, 2013
import random
def play_nims(pile, max_stones):
'''
An interactive two-person game; also known as Stones.
@param pile: the number of stones in the pile to start
@param max_stones: the maximum number of stones you can take on one turn
'''
print("maximum number of stones that can be taken in one turn: " + str(max_stones))
player = 1
while pile > 0:
ans = 0
print(str(pile) + " stones remaining")
# Get input; loop until valid
while not 1 <= ans <= max_stones:
try:
ans = int(raw_input("Player " + str(player) + " > Number of stones (1 - " + str(max_stones) + "): "))
except:
ans = 0
pile -= ans
print()
max_stones = min(pile, max_stones)
# Switch players
player = player % 2 + 1
print("Game over")
print("Player " + str(player % 2 + 1) + " wins!")
# Choose, randomly, the game parameters
play_nims(random.randint(21, 31), random.randint(5, 8))