[英]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.