[英]how can I subtract the amount Randint generates in the while loop from enemies HP without getting 2 different numbers?
如果您运行代码,您应该会看到打印例如“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
问题是您要为每种情况生成两个随机数:一个是打印的,另一个是减去/添加的。
...
print(f"You hit for {Player.attack_bash()}") # Generates a random number
enemy.health -= Player.attack_bash() # Generates another random number
...
您需要使用一个临时变量,以便您可以两次使用相同的值:
...
damage = Player.attack_bash()
print(f"You hit for {damage}")
enemy.health -= damage
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.