0

I am new to coding and I am trying to build a simple rock-paper-scissor game.

While trying to implement lives in the game I cannot seem to be able to loop while lives > 0. Although I tried to make the lives variable global to be able to use it outside the function it does not seem to work. Instead I get an error like this when I run the program:

NameError: name 'lives' is not defined

Maybe my understanding of global variables is wrong. Any help would be much appreciated. Thank you in advance.

Here is my code

import random

def play():
    player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ")
    choices = ['r', 'p', 's', 'q']
    global lives
    lives = 3

    if player in choices:
        if player == 'q':
            exit()

        computer = random.choice(['r', 'p', 's'])
        print(f'Computer chose {computer}')

        if player == computer:
            return f"It's a tie! You still have {lives} lives"

        if is_win(player, computer):
            lives += 1
            print('+1 life')
            return f'You now have {lives} lives'

        lives -= 1
        print('-1 life')
        return f'You now have {lives} lives'

    else:
        print('Invalid input. Please enter a valid value')
        return play()

def is_win(user, opponent):
    if (user == 'r' and opponent == 's') or (user == 's' and opponent == 'p') or (user == 'p' and opponent == 'r'):
        return True

while lives > 0:
    print(play())
else:
    print('You have 0 lives left. GAME OVER')
  • 1
    `global lives` means take a variable `lives` from global scope. You have no defined `lives` variable before calling `global lives`, so it gives you an error. Also note that global variables are [considered bad](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) – sudden_appearance Jan 07 '23 at 18:40
  • Don't use recursion to implement a potentially infinite loop. Just use a regular `while` loop in your `play` function. – chepner Jan 07 '23 at 19:29

1 Answers1

0

Put your lives outside the function def play()

import random
lives = 3
def play():
    player = input("Choose 'r' for rock, 'p' for paper, 's' for scissor or 'q' to quit: ")
    choices = ['r', 'p', 's', 'q']
    global lives
.....
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • Thank you so much. I tried doing that before but I moved the `global lives` out of the function too. Thanks again. – Coding Noob Jan 07 '23 at 18:55