簡體   English   中英

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

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

我在編碼方面相當新,我正在制作一個游戲,用戶在其中玩隨機抽卡游戲對電腦。 目標是首先達到 50 分,然后通過抽牌來達到這一點。 例如,梅花 2 的值應為 2,紅心王的值應為 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)

因為您在game_turn user_score所以它是 function 中各處的局部變量。 結果,第一行嘗試使用未定義的局部變量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":

    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM