我正在使用python开发游戏,一旦发生攻击功能,我就无法弄清楚如何消除健康。我可以运行该程序,并且攻击功能可以正常工作,它显示1到50之间的随机整数,但实际上并没有从castlehealth
= 100
在print("You attacked for " + str(self.attack))
下,我将下一行留空,因为我不知道要输入什么,我尝试了许多不同的操作,只是无法从castlehealth
那里夺走攻击力
这是我的代码:
import os
import time
from random import randint
class GameActions:
def __init__(self):
castlehealth = 100
self.castlehealth = castlehealth
def health(self):
print("Castle health is: " + str(self.castlehealth))
print()
def attack(self):
attack = randint(0, 50)
self.attack = attack
print("You attacked for " + str(self.attack))
def game():
while True:
game_actions = GameActions()
print("What do you want to do?")
print()
print("attack, view hp")
ans = input()
if ans == "hp":
game_actions.health()
if ans == "attack":
game_actions.attack()
答案 0 :(得分:2)
您需要以下内容:
self.castlehealth -= attack
答案 1 :(得分:1)
尝试类似self.castlehealth -= attack
的操作。我还为您解决了一些潜在的缩进问题。
您的完整代码示例可能看起来像这样:
import os
import time
from random import randint
class GameActions:
def __init__(self):
castlehealth = 100
self.castlehealth = castlehealth
def health(self):
print("Castle health is: " + str(self.castlehealth))
print()
def attack(self):
attack = randint(0, 50)
self.attack = attack
print("You attacked for " + str(self.attack))
self.castlehealth -= attack
def game():
while True:
game_actions = GameActions()
print("What do you want to do?")
print()
print("attack, view hp")
ans = input()
if ans == "hp":
game_actions.health()
if ans == "attack":
game_actions.attack()
说明:self.castlehealth
是GameActions
类的实例变量。函数GameActions.attack()
创建一个新的attack
变量作为随机整数,然后从self.castlehealth
类的实例变量GameActions
中减去该值。现在self.castlehealth
将是更新后的值。考虑还应跟踪数据结构中的各种攻击和由此带来的健康状况,因为每次您拥有新的attack
self.castlehealth
和self.attack
都会更改值,并且您将无法访问以前的值值。