python - 我的答题器游戏中出现 UnbloundLocalError,我不知道为什么
问题描述
在声明变量增量之前,我遇到了一个错误。所以,当我打开商店并每次点击购买更多 $$$
请帮忙。
这是我的代码:
from time import sleep as wait
import os
coin = 0
autoclick = 0
incrementation = 25
uppergrades_bought = 1
increment = 1
clear = lambda: os.system('clear')
def store():
cmd = int(input("What do you want to do? 1 to buy autoclick and 2 to buy more money per click").strip())
if cmd == 1:
coin-incrementation*uppergrades_bought
autoclick+=1
elif cmd == 2:
coin-incrementation*uppergrades_bought
increment+=1
clear()
while 1 == 1:
print("You have {} coins!".format(coin))
coins = input("Press enter")
clear()
coin+=increment
if coin>=incrementation*uppergrades_bought:
storeyn = input("Hi, would you like to go into the store? you have enough to buy the next uppergrade")
if storeyn.strip().lower() == "yes" or storeyn.strip().lower() == "y":
store()
elif storeyn.strip().lower() == "no" or storeyn.strip().lower() == "n" :
pass
else:
pass
else:
pass
解决方案
您的store
函数无权访问它尝试更新的值。有很多方法可以解决这个问题 - global
/nonlocal
正如另一个答案所建议的那样,现在需要更改最少的代码,但随着程序的增长,它可能会在以后给你带来很多问题,作为初学者,你应该完全避免这种情况国际海事组织。我的建议是重组你的程序,以便所有这些信息都存储在一个类中:
from time import sleep as wait
import os
class ClickerGame:
def __init__(self):
self.coin = 0
self.autoclick = 0
self.incrementation = 25
self.upgrades_bought = 1
self.increment = 1
def click(self) -> None:
"""Click once, gaining coins"""
self.coin += self.increment
def can_afford_upgrade(self) -> bool:
"""Check if there are enough coins to afford an upgrade"""
return self.coin >= self.incrementation * self.upgrades_bought
def buy(self, upgrade: int) -> None:
"""1 to buy autoclick and 2 to buy more money per click"""
if upgrade == 1:
self.autoclick += 1
elif upgrade == 2:
self.increment += 1
else:
raise ValueError(f"Invalid upgrade option {upgrade}")
self.coin -= self.incrementation * self.upgrades_bought
self.upgrades_bought += 1
def store(self) -> None:
"""Visit the store, prompting the user for a purchase."""
try:
cmd = int(input(
f"What do you want to do? {self.buy.__doc__}"
).strip())
self.buy(cmd)
except ValueError as e:
print(e)
def clear() -> None:
os.system('clear')
clicker = ClickerGame()
while True:
print(f"You have {clicker.coin} coins!")
input("Press enter")
clear()
clicker.click()
if clicker.can_afford_upgrade():
storeyn = input(
"Hi, would you like to go into the store? "
"you have enough to buy the next upgrade"
).strip().lower()
if storeyn in {"yes", "y"}:
clicker.store()
elif storeyn in {"no", "n"}:
pass
else:
pass
else:
pass
推荐阅读
- javascript - checkValidity() 和 reportValidity() 在 for 循环中不起作用
- oracle - 我需要在一个事务中执行多个 Breeze SaveChanges
- python - Django视图不接收Json数据?
- c++ - std::vector (ab) 使用自动存储
- php - move_uploaded_file():copy() 函数的第二个参数不能是目录
- c# - C#使用正则表达式删除行,包括换行
- c++ - 为什么类成员变量调用已删除的复制构造函数,而局部变量调用构造函数?
- sql-server - 在 SSIS 加载期间将 Oracle rowidtochar() 字段评估为 SQL Server nvarchar(18) 字段时遇到问题
- swift - 我可以将成员初始化器添加到符合 Codable 的对象吗?
- sql - 使用查询中的计算字段更新表