我想在敌人的生命值为0时打破密码。我在哪里破解代码?
我如何获得两个while循环以不断重复直到敌人的生命值达到0?我是否将第二个while循环嵌套在第一个while循环中?
p1.hp = 100
e1.hp = 100
g = False
while g == False:
g = True
chanceR = chance[randint(0,1)]
choiceR = choice[randint(0,1)]
print("Your turn!")
p1c = input("Choose an option: [attack] or [block] ")
if p1c == "attack":
if choiceR == "attack" and chanceR == "succcess":
print("Enemy countered your attack!")
elif choiceR == "attack" and chanceR == "fail":
print("Attack sucessful! Enemy loses 10HP!")
e1.hp -= 10
print("Enemy's health:", e1.hp)
elif choiceR == "block" and chanceR == "success":
print("Enemy blocked your attack!")
elif choiceR == "block" and chanceR == "fail":
print("Enemy failed to block! Enemy loses 10HP!")
e1.hp -= 10
print("Enemy's health:", e1.hp)
elif p1c == "block":
if choiceR == "attack" and chanceR == "success":
print("Attack blocked successfully!")
elif choiceR == "attack" and chanceR == "fail":
print("Enemy failed to attack. Nothing happens")
elif choiceR == "block":
print("Enemy blocks. Nothing happens")
else:
print("That is not a valid input. Please try again")
g = False
while g == True:
print("Enemy's turn")
chanceRp = chance[randint(0,1)]
choiceRp = choice[randint(0,1)]
chanceRe = chance[randint(0,1)]
choiceRe = choice[randint(0,1)]
if choiceRe == "attack" and chanceRe == "success":
if choiceRp == "attack" and chanceRp == "success":
print("You successfully countered the enemy's attack!")
elif choiceRp == "attack" and chanceRp == "fail":
print("Enemy successfully attacked you! You lose 10 HP!")
p1.hp -= 10
print("Your health:", p1.hp)
elif choiceRp == "block" and chanceRp == "success":
print("You successfully blocked the enemy's attack!")
elif choiceRp == "block" and chanceRp == "fail":
print("You failed to block the enemy's attack! You lose 10HP!")
p1.hp -= 10
print("Enemy's health:", p1.hp)
elif choiceRe == "attack" and chanceRe == "fail":
if choiceRp == "attack" and chanceRe == "success":
print("You successfully attacked the enemy! Enemy loses 10HP!")
e1.hp -= 10
print("Enemy's health:", e1.hp)
elif choiceRp == "attack" and chanceRp == "fail":
print("Both the enemy and you failed to attack! Nothing happens!")
elif choiceRp == "block" and chanceRp == "success":
print("Enemy failed to attack! Nothing happens!")
elif choiceRp == "block" and chanceRp == "fail":
print("Enemy failed to attack! Nothing happens!")
elif choiceRe == "block" and chanceRe == "success":
if choiceRp == "attack" and chanceRp == "success":
print("Enemy successfully blocked your attack!")
elif choiceRp == "attack" and chanceRp == "fail":
print("You failed to attack!")
elif choiceRp == "block" and chanceRp == "success":
print("Both the enemy and you blocked! Nothing happens!")
elif choiceRp == "block" and chanceRp == "fail":
print("Both the enemy and you blocked! Nothing happens!")
elif choiceRe == "block" and chanceRe == "fail":
if choiceRp == "attack" and chanceRp == "success":
print("Enemy failed to block! Enemy loses 10HP!")
e1.hp -= 10
print("Enemy's health:", e1.hp)
elif choiceRp == "attack" and chanceRp == "fail":
print("You failed to attack!")
elif choiceRp == "block" and chanceRp == "success":
print("Both the enemy and you blocked! Nothing happens!")
elif choiceRp == "block" and chanceRp == "fail":
print("Both the enemy and you blocked! Nothing happens!")
g = False
g表示游戏 p表示玩家 e表示敌人
这段代码基本上表明了玩家和敌人在每次回合中都有可能出局
chance = ["success", "fail"]
choice = ["attack", "block"]
这是代码的机会和选择变量
我真的很陌生,所以如果您能帮助我,我将非常感谢。谢谢:)
答案 0 :(得分:0)
在找到hp部件之前,请先简要说明一下:不要重复自己!在这里,您定义了两个完全相同的类,并使用丢弃的值对其进行了初始化:
class Enemy:
def __init__(self, health):
self.hp = health
class Player:
def __init__(self,health):
self.hp = health
p1 = Player("player 1")
e1 = Enemy("Orc")
p1.hp = 100
e1.hp = 100
相反,您可以这样做:
class Character:
def __init__(self, name: str):
self.name = name
self.hp = 100
player = Character("player 1")
enemy = Character("Orc")
现在player
和enemy
都具有100 hp的功率,并且它们具有name
的属性,这些属性与您传入的内容相同(在先前的代码中,您传入的名称被覆盖了,因为您将它们作为health
参数传递了。
需要注意的另一件事是,通过使用字符串文字来表示所有内容,您会在输入字符串的错误中发现自己的错误:
if choiceR == "attack" and chanceR == "succcess":
请注意"succcess"
中的拼写错误!这张支票只会悄悄地变成False
。更好的选择是使用Enum
,如果您尝试以明显不正确的方式使用它们,则会给您错误(在运行时或在运行类型检查工具时)。
要保持攻击/反击序列的进行,是的,您需要将所有内容放入另一个循环中。如果您为每个“转弯”定义一个函数(包含它们自己的循环),然后在一个外部循环中运行这些函数,则将更易于阅读,例如:
while True:
player_turn()
if game_over():
break
enemy_turn()
if game_over():
break
执行此操作的另一种方法是使用异常,该异常具有自动打破它们发生的任何上下文的好特性:
try:
while True:
player_turn()
enemy_turn()
except GameOverException as e:
print(e)
实现这些功能后,它们的外观可能会像这样:
from enum import Enum, auto
import random
from typing import Dict, Tuple
class Action(Enum):
ATTACK = "attack"
BLOCK = "block"
class Character:
def __init__(self, name: str):
self.name = name
self.hp = 100
class GameOverException(Exception):
pass
def get_player_action() -> Action:
"""Prompt the user for an action."""
while True:
try:
return Action(input(
"Choose an option: [attack] or [block] "
))
except ValueError:
print("That is not a valid input. Please try again")
def player_turn(player: Character, enemy: Character) -> None:
"""Take the player's turn. Raises GameOverException if game over."""
print("Your turn!")
player_action = get_player_action()
damage = 0
enemy_action = random.choice(list(Action))
enemy_success = random.choice([True, False])
if player_action == Action.ATTACK:
if enemy_action == Action.ATTACK:
if enemy_success:
print("Enemy countered your attack!")
else:
damage = 10
print(f"Attack successful! Enemy loses {damage} HP!")
elif enemy_action == Action.BLOCK:
if enemy_success:
print("Enemy blocked your attack!")
else:
damage = 10
print(f"Enemy failed to block! Enemy loses {damage} HP!")
elif player_action == Action.BLOCK:
if enemy_action == Action.ATTACK:
if enemy_success:
print("Attack blocked successfully!")
else:
print("Enemy failed to attack. Nothing happens")
elif enemy_action == Action.BLOCK:
print("Enemy blocks. Nothing happens")
if damage > 0:
enemy.hp -= damage
print(f"Enemy's health: {enemy.hp}")
if enemy.hp <= 0:
raise GameOverException(f"{enemy.name} is dead. You win!")
def enemy_turn(player: Character, enemy: Character) -> None:
"""Enemy's turn. Raises GameOverException if game over."""
print("Enemy's turn")
enemy_action = random.choice(list(Action))
enemy_success = random.choice([True, False])
player_action = random.choice(list(Action))
player_success = random.choice([True, False])
# Rather than have a bunch of deeply nested if/elifs, let's just make
# a table of all the possible (message, enemy_damage, player_damage)
# results based on (enemy_action, success, player_action, success).
results: Dict[Tuple[Action, bool, Action, bool], Tuple[str, int, int]] = {
# Successful enemy attack results
(Action.ATTACK, True, Action.ATTACK, True):
("You successfully countered the enemy's attack", 0, 0),
(Action.ATTACK, True, Action.ATTACK, False):
("Enemy successfully attacked you! You lose 10 HP!", 0, 10),
(Action.ATTACK, True, Action.BLOCK, True):
("You successfully blocked the enemy's attack!", 0, 0),
(Action.ATTACK, True, Action.BLOCK, False):
("You failed to block! You lose 10 HP!", 0, 10),
# Failed enemy attack results
(Action.ATTACK, False, Action.ATTACK, True):
("You successfully attacked the enemy! Enemy loses 10HP!", 10, 0),
(Action.ATTACK, False, Action.ATTACK, False):
("You both failed to attack! Nothing happens!", 0, 0),
(Action.ATTACK, False, Action.BLOCK, True):
("Enemy failed to attack! Nothing happens!", 0, 0),
(Action.ATTACK, False, Action.BLOCK, False):
("Enemy failed to attack! Nothing happens!", 0, 0),
# Successful enemy block results
(Action.BLOCK, True, Action.ATTACK, True):
("Enemy successfully blocked your attack!", 0, 0),
(Action.BLOCK, True, Action.ATTACK, False):
("You failed to attack!", 0, 0),
(Action.BLOCK, True, Action.BLOCK, True):
("Both the enemy and you blocked! Nothing happens!", 0, 0),
(Action.BLOCK, True, Action.BLOCK, False):
("Both the enemy and you blocked! Nothing happens!", 0, 0),
# Failed enemy block results
(Action.BLOCK, False, Action.ATTACK, True):
("Enemy failed to block! Enemy loses 10HP!", 10, 0),
(Action.BLOCK, False, Action.ATTACK, False):
("You failed to attack!", 0, 0),
(Action.BLOCK, False, Action.BLOCK, True):
("Both the enemy and you blocked! Nothing happens!", 0, 0),
(Action.BLOCK, False, Action.BLOCK, False):
("Both the enemy and you blocked! Nothing happens!", 0, 0),
}
message, enemy_damage, player_damage = results[
(enemy_action, enemy_success, player_action, player_success)
]
print(message)
if enemy_damage > 0:
enemy.hp -= enemy_damage
print(f"Enemy's health: {enemy.hp}")
if enemy.hp <= 0:
raise GameOverException(f"{enemy.name} is dead. You win!")
if player_damage > 0:
player.hp -= player_damage
print(f"Your health: {player.hp}")
if player.hp <= 0:
raise GameOverException(f"You have been slain. You lose!")
if __name__ == '__main__':
player = Character("player 1")
enemy = Character("Orc")
try:
while True:
player_turn(player, enemy)
enemy_turn(player, enemy)
except GameOverException as game_over:
print(game_over)
答案 1 :(得分:0)
您的两个单独匝是同一循环的一部分。按照现在的结构,游戏将先运行AAAAAAA,然后运行BBBBBBB,而不是ABABABABABABAB。
将while条件视为实际发生的情况-战斗。
while True:
k = input("type: ")
if k == 'exit':
break
else:
k = int(k)
l = k % 2
if l == 0:
print("luwi")
elif l != 0:
print("kenti")
玩家回合和敌人回合是在每个战斗循环中依次发生的事件序列。现在,您的if和elif的事件树有些杂乱无章,因此,它的冗长程度超出了需要。除此之外,一个回合和另一回合的编码方式几乎没有什么不同,因此您可以编写一个函数来定义一个回合,传递哪个玩家在该回合中扮演哪个角色,但这不在本文的讨论范围之内。对于休息,请这样想:
fighting = True
while fighting:
# Player turn
# Enemy turn