我写了一个简单的游戏程序(两个战士之间的战斗)。每个战士都有名字,100点生命和伤害点列表。你知道吗
目前,这个程序运行良好,但我编写它是为了每次一个战斗机攻击另一个(“悟空”攻击“科南”)。名为startTheFight
的函数实现了这一点。你知道吗
悟空攻击空南。。。 悟空攻击空南。。。 悟空攻击空南。。。 ……等等
如何使该函数交替执行,以便我可以看到谁赢了(“悟空”或“河南”)?
另外,当我调用函数upgradeAttack
时,它不工作,我不知道为什么
我想要这样的输出:
悟空攻击空南。。。 空南攻击悟空。。。 悟空攻击空南。。。 空南攻击悟空。。。 ... 你知道吗
代码如下:
import random
class Fighters:
attackUp = 0
def __init__(self, name):
self.name = name
self.health = 100
self.damage = [5, 10, 15, 20]
def upgradeAttack(self, attUp):
self.attackUp = self.attackUp + attUp
print(self.attackUp)
return self.attackUp
def startTheFight(self, otherFighter):
while otherFighter.health > 0:
AttactDamage = random.choice(self.damage) + self.attackUp
otherFighter.health = otherFighter.health - AttactDamage
if otherFighter.health > 0:
print("{} attacts {}! Health -{}hp | {}'s Health: {}hp\n".format(self.name, otherFighter.name,
AttactDamage,otherFighter.name, otherFighter.health))
else:
otherFighter.health = 0
print("{} attacts {}! Health -{}hp | {}'s Health: {}hp\n".format(self.name, otherFighter.name,
AttactDamage,otherFighter.name, otherFighter.health))
else:
if otherFighter.health <= 0:
otherFighter.health = 0
print("{} killed {}! | {}'s Health: {}hp\n{} wins!\n\n".format(self.name, otherFighter.name,
otherFighter.name, otherFighter.health, self.name))
def __str__(self):
return "Fighters name: {}\nFighters health: {}hp\n".format(self.name, self.health)
Goku = Fighters("Goku")
Konan = Fighters("Konan")
#print(Goku)
#print(Konan)
Goku.startTheFight(Konan)
还有几个建议:一个模拟战斗机的类被称为
Fighters
是没有意义的。它应该是单数,Fighter
。战士没有名字,一个战士有名字。虽然可以想象一个斗士开始战斗,但奇怪的是一个斗士指挥它;我宁愿使用一个静态方法(Fighter.fight(goku, conan)
),或者使用一个不同的类Fight
,它表示两个人战斗的事件实例。它还将负责报告战斗情况。一个实例对另一个实例进行更改也不是很好;柯南可以命中,但只有小悟空应该对他的健康进行管理。while
循环比它需要的更复杂;战斗的结构是攻击者击中防御者,然后他们交换位置。这使得流量控制更加容易。最后,根据Python命名约定,实例变量应该是小写的;人们可能会被欺骗,以为Goku
和Conan
是类名。(这只是一个例子,还有其他的案例问题。)所以记住这一点,有点重写:从这里开始,一个高级的练习就是把战斗变成一个发电机,这样你就可以更容易地一轮一轮地运行它。你知道吗
我已经用一种黑客的方式修改了你下面的代码。Working example here。注意事项:
__str__
方法过于复杂,使用不当(实际上永远不应该直接print
)Fighters.hit()
方法)你可以给不同的战斗机分配不同的伤害数组,理论上代码应该仍然像预期的那样工作。你知道吗startTheFight
方法被用来在两个实例之间创建一个争斗(这本身并没有错,但我个人更希望startFight是一个类方法)。你知道吗f"{var_name}"
(仅在python3.6+中),并且您应该确保您的string方法是有意义的——与在整个函数中使用一堆随机语句给出输出相比,“构建”最终输出(要打印的string、list、dict等)通常更容易/更明智/更容易阅读。你知道吗代码:
输出示例:
相关问题 更多 >
编程相关推荐