Search code examples
pythonuser-input

How to restart my game with user input of 'y'? Created a user defined function for after-game


i=1

Play Another or Quit Game

def done():

    quitvalue=str(input("Play Again?(y/n):"))
    if quitvalue=='n' and i==0:
            SystemExit
    elif quitvalue=="y":
                i=1



#Loop to Restart Game

def rps(play1,play2):

        #Check Winner of Game
        if play1==play2:
            print("It's a tie!")
            done()

        elif play1=='r':
            if play2=='s':
                print(play1name+" Wins!")
                done()

            else:
                print(play2name+" Wins!")
                done()


        elif play1=='p':
            if play2=='r':
                print(play1name+" Wins!")
                done()

            else:
                print(play2name+" Wins!")
                done()

        elif play1=='s':
            if play2=='p':
                print(play1name+" Wins!")
                done()

            else:
                print(play2name+" Wins!")
                done()


#Player Input
while i==1:
    play1name=str(input("Player 1 Name?:"))
    play2name=str(input("Player 2 Name?:"))
    play1= str(input(play1name+" Choose Rock(r),Paper(p), Scissors(s):"))
    play2= str(input(play2name+" Choose Rock(r),Paper(p), Scissors(s):"))
    i=0
    rps(play1,play2)

Solution

  • The issue here is that the i in the done() function refers to a variable i that is being declared locally in the function by deafult, not the global variable i declared at the beginning of your program. To fix this issue, add global i in your done() function prior to i being referenced there:

    def done():
        global i
        quitvalue=str(input("Play Again?(y/n):"))
        if quitvalue=='n' and i==0:
                SystemExit
        elif quitvalue=="y":
                    i=1