我在控制台中制作一个小型游戏,持续数天。它涉及一个矿工和他的采矿追求。游戏开始时将矿工矿石和金额初始化为0.当他开采时,我的功能选择一个20到71之间的随机整数,然后将该金额奖励给他。我正在尝试将已经开采的矿石分配给我的玩家的矿石量。我有一个reoccuring错误,指出+ =是方法和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/InsanePainz/PycharmProjects/BoardGame/mine.py", line 41, in <module>
miningAction()
File "C:/Users/InsanePainz/PycharmProjects/BoardGame/mine.py", line 38, in miningAction
player.oreDeposit(oreRecovered)
File "C:/Users/InsanePainz/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
答案 0 :(得分:1)
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
和其他方法类似。