[Tutor] The game of nim in python

Yasin El Guennouni marocko_87 at hotmail.com
Wed Mar 27 13:30:59 CET 2013


Hello,

I am trying to modify a game of nim code. The game in the code works as: 
"You need to remove from 1 to 3 straws from the pile.
The player that removes the final straw is the loser."

But I would like it to be like the classic game, where you have 4 piles containing 1,3,5 and 7 sticks
where the drawer of the last stick is the winner. It would be awsome if I could print how
many sticks there are left in each pile, e.g. : I III IIIII IIIIIII.

Thanks in advance!

The code I have:

player1=str(input("Enter your name. "))
player2="Computer"
howMany=0
gameover=False
strawsNumber=random.randint(10,20)

if (strawsNumber%4)==1:
    strawsNumber+=1

def removingStrawsComputer():
    removedNumber=random.randint(1,3)
    global strawsNumber
    while removedNumber>strawsNumber:
        removedNumber=random.randint(1,3)
    strawsNumber-=removedNumber
    return strawsNumber

def removingStrawsHuman():
    global strawsNumber
    strawsNumber-=howMany
    return strawsNumber

def humanLegalMove():
    global howMany
    legalMove=False
    while not legalMove:
        print("It's your turn, ",player1)
        howMany=int(input("How many straws do you want to remove?(from 1 to 3) "))
        if  howMany>3 or howMany<1:
            print("Enter a number between 1 and 3.")
        else:
            legalMove=True
    while howMany>strawsNumber:
        print("The entered number is greater than a number of straws remained.")
        howMany=int(input("How many straws do you want to remove?"))
    return howMany

def checkWinner(player):
    if strawsNumber==0:
        print(player," wins.")
        global gameover
        gameover=True
        return gameover

def resetGameover():
    global gameover
    gameover=False
    return gameover

def game():
    while gameover==False:
        print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer())
        checkWinner(player1)
        if gameover==True:
            break
        humanLegalMove()        
        print("The number of straws left: ",removingStrawsHuman())
        checkWinner(player2)
game()
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130327/22d1ccaf/attachment-0001.html>


More information about the Tutor mailing list