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
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
print 'Game is over.'
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.