嗨,我是Python新手,我正在编写这个程序,我有一个问题

2024-09-29 20:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 我想在敌人生命值为0时破译密码。我在哪里破译密码

  2. 如何让两个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"]

下面是代码的机会和选择变量

我是个新手,如果你能帮我,我会非常感激。谢谢:)


Tags: andtoblockhpsuccessfailprintfailed
2条回答

您的两个独立转弯是同一环路的一部分。按照现在的结构,游戏将运行AAAAAAA,然后是BBBBBBB而不是abababab

把while条件想象成实际发生的事情——一场战斗

fighting = True
while fighting:
  # Player turn
  # Enemy turn

玩家回合和敌人回合是在战斗的每个循环中按顺序发生的事件序列。现在,if和elifs的事件树有点杂乱无章,因此比需要的要详细得多。除此之外,一个回合和另一个回合的编码方式几乎没有区别,因此您可以编写一个函数来定义一个回合,传递哪个玩家在该回合中扮演哪个角色,但这超出了本文的范围。在休息时,可以这样想:

fighting = True
while fighting:
  # P1 turn
  # Get input and random
  # Change HP
  # If after the change, the HP is <= 0:
    fighting = False
    break
...
enter code here

在找到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")

现在playerenemy都有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)

相关问题 更多 >

    热门问题