如何修复“UnboundLocalError:分配前引用的局部变量‘user_score’”?

时间:2021-05-05 13:41:59

标签: python

我对编码还很陌生,我正在制作一款游戏,用户可以在其中对着计算机玩随机抽卡游戏。目标是首先达到 50 分,然后通过抽牌来达到。例如,2 个 Clubs 的值应该是 2,而 King of Hearts 的值应该是 13。但是,在我编辑代码时,它随机显示了一个我不熟悉的错误,也不知道如何修理。有人可以帮我吗?

# 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!")

这是我能做的尽可能多的最小可重复示例。您基本上可以忽略从“class Card”到“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)

1 个答案:

答案 0 :(得分:2)

因为您在 user_score 内分配给 game_turn,所以它是函数中无处不在的局部变量。因此,第一行试图使用未定义的局部变量 user_score,而不是全局变量 user_score。它需要标记为全局:

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

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

    ...