我正在控制台中进行一场为期数天的小游戏。游戏首先将矿工的矿石和金钱金额初始化为0。当他进行采矿时,我的函数会选择一个介于20到71之间的随机整数,然后将其奖励为“矿石”。我正在尝试将已开采的矿石分配给玩家的矿石量。我遇到一个经常发生的错误,指出+ =是method和int的不受支持的操作数。完整的代码和跟踪如下。
码
import pyautogui as pag import time import sys import random class Miner: def __init__(self, oreDeposit, moneyDeposit): self.oreAmount = oreDeposit self.moneyAmount = moneyDeposit def oreDeposit(self, oreAmount): self.oreDeposit += oreAmount def oreWithdraw(self, oreAmount): self.oreWithdraw -= oreAmount # -------------end of ore def moneyDeposit(self, moneyAmount): self.moneyDeposit += moneyAmount def moneyWithdraw(self, moneyAmount): self.moneyWithdraw -= moneyAmount # -------------end of money def oreBalance(self): return self.oreAmount def moneyBalance(self): return self.moneyAmount # -------------end of balances def miningAction(): x = random.randint(20, 71) for i in range(x): time.sleep(0.1) print(i) oreRecovered = i player.oreDeposit(oreRecovered) player = Miner(0, 0) miningAction() print (player.oreAmount)
完整回溯
0 Traceback (most recent call last): File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 41, in <module> miningAction() File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 38, in miningAction player.oreDeposit(oreRecovered) File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 12, in oreDeposit self.oreDeposit += oreAmount TypeError: unsupported operand type(s) for +=: 'method' and 'int' Process finished with exit code 1
self.moneyDeposit是对该moneyDeposit方法的引用,不能将其递增一个数字(即使可以,也不会执行您想要的操作)。
self.moneyDeposit
moneyDeposit
你应该改变
def moneyDeposit(self, moneyAmount): self.moneyDeposit += moneyAmount def moneyWithdraw(self, moneyAmount): self.moneyWithdraw -= moneyAmount
进入
def moneyDeposit(self, moneyAmount): self.moneyAmount += moneyAmount def moneyWithdraw(self, moneyAmount): self.moneyAmount -= moneyAmount
和其他方法类似。