python - 如何在不得到 2 个不同数字的情况下从敌人的 HP 中减去 Randint 在 while 循环中生成的数量?
问题描述
如果您运行代码,您应该会看到打印内容为“14”,但它会从敌人的 HP 中收回其他内容。
计算每个“法术”的攻击伤害:
from random import randint
import time
class Player(object):
def __init__(self, health):
self.health = health
@staticmethod
def use_heal():
return randint(9, 21)
@staticmethod
def attack_slice():
return randint(5, 29)
@staticmethod
def attack_bash():
return randint(11, 18)
class Enemy(object):
def __init__(self, health):
self.health = health
@staticmethod
def enemy_attack():
return randint(9, 19)
设置HP:
player = Player(100)
enemy = Enemy(100)
作为“游戏”的循环:
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
print(f"You hit for {Player.attack_bash()}")
enemy.health -= Player.attack_bash()
elif attack_choice == 2:
print(f"You hit for {Player.attack_slice()}")
enemy.health -= Player.attack_slice()
elif attack_choice == 3:
print(f"You heal for {Player.use_heal()}")
player.health += Player.use_heal()
解决方案
当它调用 Player.attack_* 时,它返回一个要打印的随机值,然后第二次调用它以实际伤害敌人,因此它可能是一个默认值。它应该做的是调用一次,将其存储在一个变量中并使用该变量
while True:
print(f"Your hp: {player.health}\nEnemy hp: {enemy.health}\n")
print("(1) Bash _ (2) Slice _ (3) Heal")
attack_choice = int(input(">>"))
if attack_choice == 1:
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 2:
damage = Player.attack_slice()
print(f"You hit for {damage}")
enemy.health -= damage
elif attack_choice == 3:
damage = Player.use_heal()
print(f"You heal for {damage}")
player.health += damage
推荐阅读
- vba - 使用 VBA 在 Excel 中扫描时,将扫描的值从一个单元格移动到一个范围内的另一个单元格
- c# - 使用 .NET Core MSTest 运行单元测试:“未找到以下 TestContainer...”
- angularjs - 出现错误:添加 angular-bootstrap-lightbox 依赖项时出现 $injector:modulerr 模块错误
- python - Pyinstaller 的构建提前退出而没有错误
- php - Woocommerce产品循环展示,产品和类别令人头疼
- python - 为什么转推时 Tweepy 完全没有返回任何内容?
- c# - Windows 10 Photo App 无法修改 AppData 文件夹中的图像
- php - 解析错误:语法错误,意外 ':',期待 ';' 大批
- ios - 如何在 swift 中在 VLC 播放器上方添加全屏按钮
- google-cloud-platform - 如何将“Stackdriver Provisioning Service Private”添加到 GCP API 和服务?