Skip to content Skip to sidebar Skip to footer

Python 2.7.8 How To Restart The Game Code

I am looking on how to restart this code without actually restarting the game. I want to be able have the game restart on its on. print 'Welcome to the game of NIM: ' player=1 stat

Solution 1:

You can put your code in a function, and call that function in a while loop:

from sys import exit #To exit if the user does not want to try again
print 'Welcome to the game of NIM: '
def game():
    player=1
    state=21
    print 'The number of objects is now ',state
    while True:
        print 'Player ',player
        while True:
            move=input('What is your move? ')
            if move in [1,2,3] and move<state:
                break
            print 'Illegal move.'
        state=state-move
        print 'The number of objects is now ',state

        if state==1:
            print 'Player ',player,' wins!'
            break
        if player==1:
            player=2
        else:
            player=1
    if raw_input('Would you like to try again? ').lower().startswith('y'):
        return #To exit from the function cleanly
    exit() #To exit from the program cleanly if the user does not want to try again
def run():
    while True:
        game()
if __name__ == '__main__':
    run()

Post a Comment for "Python 2.7.8 How To Restart The Game Code"