[Tutor] The game of nim in python

Alan Gauld alan.gauld at yahoo.co.uk
Fri Apr 22 17:57:33 EDT 2016


On 22/04/16 13:45, Henderson, Kevin (GE Aviation, US) wrote:
> Python to Jython.
> 
> Can you help me with a Jython code for the Nim game?
> 

There shouldn't be much difference between a Jython or Python
implementation - unless you are building a GUI of course!

> Removing 1-4 sticks out of 13, last player who picks up the last stick wins

Ive no idea how nim is played although I re,em,ber my math
teacher talking about it as being the only practical use
of binary outside computing...

But what kind of help do you need? Does your code work?
Is there an error (if so send us the full text)?
Do you want a general code review?
What exactly do you want from us?

> 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()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list