如何在上课时去掉健康点?

2024-04-19 15:44:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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()

Tags: importselfyouactionsgamefordefprint
2条回答

您需要以下内容:

self.castlehealth -= attack

尝试类似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.castlehealthGameActions类的实例变量。函数GameActions.attack()创建一个新的attack变量作为随机整数,然后从GameActions类的实例变量self.castlehealth中减去该值。现在self.castlehealth将是更新的值。还可以考虑跟踪数据结构中的各种攻击和由此产生的健康状况,因为每次您有一个新的attackself.castlehealthself.attack都会更改值,并且您将失去访问以前的值的能力。你知道吗

相关问题 更多 >