简体   繁体   中英

How can I fix "UnboundLocalError: local variable 'user_score' referenced before assignment"?

I'm fairly new at coding and I'm making a game in which the user plays a random card drawing game against the computer. The goal is to reach 50 points first and you reach that by drawing the cards. For example, a 2 of Clubs should have a value of 2 and a King of Hearts should have a value of 13. However, as I was editing my code, it randomly showed an error that I'm not familiar with, nor know how to fix. Can anyone help me?

# Useful Definitions
user_score = 0
computer_score = 0
user_turn_score = 0
computer_turn_score = 0
type = "user"
winner = "none"
import random



class Card:
    suits = {'c': '♣','h': '♥','s': '♠','d': '♦'}
    faces = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
    def __init__(self, rank, suit):
        '''Called when you create a new card. For example `Card(10, 'h')`'''
        self.rank = rank
        self.suit = suit
    
    def __repr__(self):
        '''A string representation of the card'''
        face = self.faces.get(self.rank, self.rank)
        return f'{face}{self.suits[self.suit]}'
        
    def __add__(self, other):
        '''What happens when you add a card to another (or to an integer)
           For example this_card + someOther_card'''
        if isinstance(other, int):
            return self.rank + other
        return self.rank + other.rank

    def __radd__(self, other):
        '''What happens when you add another or integer to this card. 
           For example `someOther_card + this_card`'''
        if isinstance(other, int):
            return other + self.rank
        return self.rank + other.rank
        
sorted_deck = [Card(n, s) for s in Card.suits for n in range(1, 14)]



# Introduction code
print("Hello, Welcome to the Pig Card Game!")
user_name = input("What's your name? ")
cont = input("Press enter to learn how to play, " + user_name)
print()
print("***************************************************************")
print()


#Main Menu Function
def main_menu(name):
    print()
    print("What would you like to do, " + user_name + "?")
    print("1. Learn the Rules of Pig")
    print("2. Play!!")
    print("3. Exit.")
    choice = input("Enter your selection: ")
    print("*****************************************************")
    print()
    return choice
    

# Instructions
def game_rules():
    
    print("1. In the game, you will play against the computer in a luck-based")
    print("card game.")
    print("2. During your turn, you will draw a random card from  standard")
    print("deck of cards.")
    print("Each card is worth its standard numerical value - A 2 is worth 2")
    print("points and a King is worth 13 Points")
    print("3. You may choose to continue your turn as long as you want, by")
    print("drawing more random cards and adding those to your point total.")
    print("4. However, if at any point in your turn, you draw an ace or a")
    print("jack of any suit, you will lose all of your points collected in")
    print("your turn and your turn will end.")
    print("5. The first player to reach a score of 50 points loses.")
    print()
    cont = input("Press enter to go back to the main menu")
    print()
    print("***************************************************************")
    print()


def game_turn(type):
    
    while user_score != 50 and computer_score != 50:
        global random_drawn_card
        if type == "user":
            cont = input("It is your turn, " + user_name + ". Press enter to draw a random card.")
            random_drawn_card = random.choice(sorted_deck)
            print("Your card: " + str(random_drawn_card))
            sorted_deck.remove(random_drawn_card)
            if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
                user_turn_score = 0
                print("You drew an Ace or a Jack. You will not gain any points this turn.")
                type = "computer"
            else:
                value = random_drawn_card.rank
                user_turn_score = user_turn_score + value
                print("Your points this round: " + str(user_turn_score))
                turn_type = input("Do you want to continue your turn? (Y/N) ")
                if turn_type == "Y":
                    type = "user"
                else:
                    type = "computer"
                    user_score = user_score + user_turn_score
                    print("Your total score: " + user_score)
            print()
            print("***************************************************************")
            print()
        
        else:
            computer_turn_score = 0
            print("It is the computer's turn. Drawing a random card.")
            random_drawn_card = random.choice(sorted_deck)
            print("Computer's Card: " + str(random_drawn_card))
            sorted_deck.remove(random_drawn_card)
            if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
                computer_turn_score = 0
                print("The computer drew an Ace or a Jack. It will not gain any points this turn.")
                type = "computer"
            else:
                value = random_drawn_card.rank
                computer_turn_score = computer_turn_score + value
                print("Computer's points this round: " + str(computer_turn_score))
                computer_turn = random.randint(1,2)
                if computer_turn == 1:
                    type = "computer"
                    print("The computer will take another turn.")
                else:
                    type = "user"
                    computer_score = computer_score + computer_turn_score
                    print("The computer will not take another turn.")
                    print("Computer's total score: " + computer_score)
            print()
            print("***************************************************************")
            print()


main_choice = main_menu(user_name)

#Loop that encompasses the entire game that determines if user goes to rules, plays, or leaves
while main_choice != "3":
    
    if main_choice == "1":
        game_rules()
    elif main_choice == "2":
        user = game_turn(type)
    else:
        print("Invalid Selection. Choose a number between 1 and 3.")

    main_choice = main_menu(user_name)
    
    
if winner == "user":
    print("Congrats! You won the game!")
else:
    print("Sorry, the computer won the game. Better luck next time!")
    
#Outro message to user
print("Thanks for playing, " + user_name + ". See you next time!")

Here is as much of a minimal reproducible example as I could make. You can basically ignore everything from "class Card" to "sorted_deck = [Card(n, s) for s in Card.suits for n in range(1, 14)]".

# Useful Definitions
user_score = 0
computer_score = 0
user_turn_score = 0
computer_turn_score = 0
type = "user"
winner = "none"
import random



class Card:
    suits = {'c': '♣','h': '♥','s': '♠','d': '♦'}
    faces = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
    def __init__(self, rank, suit):
        '''Called when you create a new card. For example `Card(10, 'h')`'''
        self.rank = rank
        self.suit = suit
    
    def __repr__(self):
        '''A string representation of the card'''
        face = self.faces.get(self.rank, self.rank)
        return f'{face}{self.suits[self.suit]}'
        
    def __add__(self, other):
        '''What happens when you add a card to another (or to an integer)
           For example this_card + someOther_card'''
        if isinstance(other, int):
            return self.rank + other
        return self.rank + other.rank

    def __radd__(self, other):
        '''What happens when you add another or integer to this card. 
           For example `someOther_card + this_card`'''
        if isinstance(other, int):
            return other + self.rank
        return self.rank + other.rank
        
sorted_deck = [Card(n, s) for s in Card.suits for n in range(1, 14)]




def game_turn(type):
    
    while user_score != 50 and computer_score != 50:
        global random_drawn_card
        if type == "user":
            cont = input("It is your turn, " + user_name + ". Press enter to draw a random card.")
            random_drawn_card = random.choice(sorted_deck)
            print("Your card: " + str(random_drawn_card))
            sorted_deck.remove(random_drawn_card)
            if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
                user_turn_score = 0
                print("You drew an Ace or a Jack. You will not gain any points this turn.")
                type = "computer"
            else:
                value = random_drawn_card.rank
                user_turn_score = user_turn_score + value
                print("Your points this round: " + str(user_turn_score))
                turn_type = input("Do you want to continue your turn? (Y/N) ")
                if turn_type == "Y":
                    type = "user"
                else:
                    type = "computer"
                    user_score = user_score + user_turn_score
                    print("Your total score: " + user_score)
            print()
            print("***************************************************************")
            print()
        
        else:
            computer_turn_score = 0
            print("It is the computer's turn. Drawing a random card.")
            random_drawn_card = random.choice(sorted_deck)
            print("Computer's Card: " + str(random_drawn_card))
            sorted_deck.remove(random_drawn_card)
            if random_drawn_card == "Ace♣" or random_drawn_card == "Ace♥" or random_drawn_card == "Ace♦" or random_drawn_card == "Ace♠" or random_drawn_card == "Jack♣" or random_drawn_card == "Jack♥" or random_drawn_card == "Jack♦" or random_drawn_card == "Jack♠":
                computer_turn_score = 0
                print("The computer drew an Ace or a Jack. It will not gain any points this turn.")
                type = "computer"
            else:
                value = random_drawn_card.rank
                computer_turn_score = computer_turn_score + value
                print("Computer's points this round: " + str(computer_turn_score))
                computer_turn = random.randint(1,2)
                if computer_turn == 1:
                    type = "computer"
                    print("The computer will take another turn.")
                else:
                    type = "user"
                    computer_score = computer_score + computer_turn_score
                    print("The computer will not take another turn.")
                    print("Computer's total score: " + computer_score)
            print()
            print("***************************************************************")
            print()

user = game_turn(type)

Because you assign to user_score inside game_turn , it is a local variable everywhere in the function. As a result, the very first line is trying to use the undefined local variable user_score , not the global variable user_score . It needs to be marked as global:

def game_turn(type):
    global user_score, random_drawn_card, computer_score

    while user_score != 50 and computer_score != 50:
        if type == "user":

    ...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM