首页 > 解决方案 > 如何在不得到 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()

标签: pythonpython-3.xrandomwhile-loop

解决方案


当它调用 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

推荐阅读