【发布时间】:2022-12-11 13:00:01
【问题描述】:
我正在编写一个名为 battle bots 的程序,该程序非常简单,但我是使用 python 的 OOP 新手,因此我正在努力使其正常运行。我最大的问题是更新我的生命值在里面方法。在里面在里面我有 self.lifepoints = 100,但是当“机器人”受到损坏时,我需要将该数字更新为与损坏相当的数字。这是代码,我真的可以使用一些建议
import random
class player:
def __init__(self):
self.lifepoints = 100
def getStrength(self):
self.strength = random.randint(1, 40)
return self.strength
def doDamage(self):
self.damage = self.lifepoints - self.strength
return self.damage
class botGame:
bot1 = player()
bot2 = player()
while True:
print("Welcome to Battle Bots...")
choice = input("Bot 1 it's your turn, press 'h' to Hit or 'q' to Quit: ")
while True:
print("Bot 1 life points: ", bot1.lifepoints, '\n', "Bot 2 life points: ", bot2.lifepoints)
if choice == 'q':
quit
if choice == 'h':
print("Bot 1's strength: ",bot1.getStrength())
print("Bot 2's strength: ",bot2.getStrength())
# if statement for .getstrength() for each bot
if bot1.strength > bot2.strength:
print(bot1.doDamage())
else:
print(bot2.doDamage())
print("Bot 1 life points: ",bot1.lifepoints)
print("Bot 2 life points: ",bot2.lifepoints)
break
while True:
print("Bot 2, your turn!")
choice = input("Bot 1 it's your turn, press 'h' to Hit or 'q' to Quit: ")
if choice == 'h':
print("Bot 1's strength: ",bot1.getStrength())
print("Bot 2's strength: ",bot2.getStrength())
print(player.doDamage(bot1, bot2))
print("Bot 1 life points: ",bot1.lifepoints)
print("Bot 2 life points: ",bot2.lifepoints)
if bot1.lifepoints > bot2.lifepoints:
print("Bot 1 Wins this round!", '\n'," Thanks for playing!", '\n', "Goodbye!")
else:
print("Bot 2 Wins this round!", '\n'," Thanks for playing!", '\n', "Goodbye!")
break
【问题讨论】:
-
IMO,
botGame看起来更像是一个函数而不是一个类。 -
你可以在 botGame
bot1.lifepoints -= damage的某个地方。不要在__init__函数中更新它,因为你想更新它后您创建了实例。 -
@IgnatiusReilly 谢谢你的反馈。我还意识到我有一个更大的问题,那就是计算每个机器人点受到的伤害。所以我需要伤害是从较高强度中减去较低强度的机器人,而强度较低的机器人从他们的生命点中减去该量。但我不确定我是否应该比较 player class 或 botGame 中的优势
-
if bot1.strength > bot2.strength: bot2.lifepoints -= bot2.strength - bot1.strength(我正在为评论写一行)。请注意,doDamage方法试图以最直接的方式对自身造成伤害:对本应造成伤害并发挥其自身力量的机器人造成伤害。 -
所有这些代码绝对不应该出现在
class botGame的主体中