简体   繁体   English

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

[英]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.目标是首先达到 50 分,然后通过抽牌来达到这一点。 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.例如,梅花 2 的值应为 2,红心王的值应为 13。但是,在我编辑代码时,它随机显示了一个我不熟悉的错误,也不知道如何修理。 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)]".您基本上可以忽略从“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)

Because you assign to user_score inside game_turn , it is a local variable everywhere in the function.因为您在game_turn user_score所以它是 function 中各处的局部变量。 As a result, the very first line is trying to use the undefined local variable user_score , not the global variable user_score .结果,第一行尝试使用未定义的局部变量user_score ,而不是全局变量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":

    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UnboundLocalError:赋值前引用了局部变量“Score” - UnboundLocalError: local variable 'Score' referenced before assignment “UnboundLocalError:赋值前引用了局部变量‘score’” - “UnboundLocalError: local variable 'score' referenced before assignment” 我该如何解决:UnboundLocalError:分配前引用的局部变量“生成” - how can i fix: UnboundLocalError: local variable 'generate' referenced before assignment 如何解决此错误“UnboundLocalError:分配前引用的局部变量'a'” - How can I fix this error “UnboundLocalError: local variable 'a' referenced before assignment” 如何修复“UnboundLocalError:赋值前引用的局部变量‘books’”? - How to fix "UnboundLocalError: local variable 'books' referenced before assignment"? 如何修复 UnboundLocalError:在 Python 中分配之前引用的局部变量“df” - How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python 如何修复 UnboundLocalError:赋值前引用的局部变量“o1” - How to fix UnboundLocalError: local variable 'o1' referenced before assignment 分配前在/本地变量'user'处引用了UnboundLocalError - UnboundLocalError at / local variable 'user' referenced before assignment UnboundLocalError:分配前已引用本地变量“用户” - UnboundLocalError: Local variable 'user' referenced before assignment UnboundLocalError:赋值前引用了局部变量“i” - UnboundLocalError: local variable 'i' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM