[英]Constantly checking a variable Python
Started trying to learn python yesterday, and I have run into a wall already TT I am trying to make a health function in a game in python, and I need the variable health checked constantly to make sure it does not go below 0. 昨天开始尝试学习python,现在我已经碰壁了。TT我正在尝试在python游戏中创建运行状况函数,并且需要不断检查变量运行状况以确保其不低于0。
health = 10
health = (health - 5)
health = (health - 6)
Here I need the program to run a completely separate line of code, since health is now equal to -1. 在这里,我需要程序运行完全独立的代码行,因为运行状况现在等于-1。 I do not want to have
我不想有
if(health <= 0):
...
because I would need to copy paste this everywhere health is changed. 因为我需要将复制粘贴到所有更改健康的地方。
Would appreciate any help, thanks! 希望得到任何帮助,谢谢!
You don't need to check health
constantly. 您不需要经常检查
health
。 Anytime you call a function reducing health (eg attack(character, damage)
), you could simply check if health > 0
. 任何时候调用降低健康状况的函数(例如
attack(character, damage)
),您都可以简单地检查一下health > 0
。 If not, you should call game_over()
. 如果不是,则应调用
game_over()
。
Here's some code from a related question: 以下是相关问题中的一些代码:
class Character:
def __init__(self, name, hp_max):
self.name = name
self.xp = 0
self.hp_max = hp_max
self.hp = hp_max
# TODO: define hp_bar here
def is_dead(self):
return self.hp <= 0
def attack(self, opponent, damage):
opponent.hp -= damage
self.xp += damage
def __str__(self):
return '%s (%d/%d)' % (self.name, self.hp, self.hp_max)
hero = Character('Mario', 1000)
enemy = Character('Goomba', 100)
print(enemy)
# Goomba (100/100)
hero.attack(enemy, 50)
print(enemy)
# Goomba (50/100)
hero.attack(enemy, 50)
print(enemy)
# Goomba (0/100)
print(enemy.is_dead())
# True
print(hero.xp)
# 100
I'm not familar with the python language, but my proposal can be tranferred to python. 我不熟悉python语言,但是我的建议可以转移到python。
Create a function that decreases the health value but never returns a value lower than zero. 创建一个减少运行状况值但从不返回小于零的值的函数。 This is the pseudo-code:
这是伪代码:
function integer decreaseHealth(parameter health, parameter loss)
{
integer newHealth = health - loss
if (health < 0)
return 0
else
return newHealth
}
So I would need to type something like 所以我需要输入类似
if(health <= 0)"
print("Game over")
else:
print("New health")
Shame there isn't something in python for this, wish I could put before my code: 可惜在python中没有这个功能,希望我可以在代码之前放:
cont if(health <= 0):
print("Game over")
This would mean that whenever the health reached 0 or below, no matter where in the code after this, Game Over would print. 这意味着只要健康状况达到0或以下,无论此后代码在什么位置,都将打印Game Over。
Then I wouldn't need to type anything when health is taken away apart from health = health - 1 然后,除了health = health-1之外,我不需要键入任何其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.