python - 如何修复“UnboundLocalError:分配前引用的局部变量'user_score'”?
问题描述
我在编码方面相当新,我正在制作一个游戏,用户在其中玩随机抽卡游戏对电脑。目标是首先达到 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)
解决方案
因为您分配给user_score
inside ,所以它是函数中任何地方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":
...
推荐阅读
- centos - yum 没有足够的缓存数据来继续。在这一点上,yum 唯一能做的安全的事情就是失败
- arrays - 返回嵌套数组中的数组元素
- c++ - 删除二维数组 C++ 的前三个元素
- c# - 如何将多个数组(表示数据列)组合成一个嵌套/锯齿状数组(甚至是二维)数组
- java - 为什么Java中的这个文件I/O操作会导致NullPointerException
- java - 在java中将一些字符串行发送到服务器(UDP)
- asp.net-core - 使用 Identity 的自定义存储提供程序实现角色
- javascript - 如何从页面的 javascript 文件而不是 html 中访问预编译的 Handlebars 模板?
- keras - keras 中一维卷积网络的输入形状
- python - Numpy 索引问题.....提前索引 X[0] 在这里做什么?