Skip to content

示例程序

角色扮演游戏战斗

题目描述

在大部分角色扮演游戏中,玩家角色会与非玩家角色战斗,这些非玩家角色通常是怪物或者“坏人”。 通常,一场战斗由各角色组成,每个角色会使用骰子生成一个随机值,该值就是从对手的生命值中减掉的部分。 一旦角色的生命值变为零,它们就失去或消失。

在此挑战中,我们归纳出互动过程的本质。 英雄和怪物在开始时的生命值相同。 在英雄攻击时,它们将生成一个随机值,该值将从怪物的生命值中减去。 如果怪物的生命值大于零,则会轮到它们攻击英雄。 只要英雄和怪物的生命值大于零,战斗就会继续进行。

游戏规则

  • 英雄和怪物在开始时的生命值为 10。
  • 所有攻击都是介于 1 到 10 之间的值。
  • 英雄首先攻击。
  • 打印怪物损失的生命值,以及剩余的生命值。
  • 如果怪物的生命值大于 0,则它会攻击英雄。
  • 打印打印英雄损失的生命值,以及剩余的生命值。
  • 继续此攻击顺序,直到怪物或英雄任意一方的生命值为零或更低。
  • 打印胜利者。

重要事项:

  • 必须使用 do-while 语句或 while 语句。

可能的输出:

Monster was damaged and lost 1 health and now has 9 health.
Hero was damaged and lost 1 health and now has 9 health.
Monster was damaged and lost 7 health and now has 2 health.
Hero was damaged and lost 6 health and now has 3 health.
Monster was damaged and lost 9 health and now has -7 health.
Hero wins!

很明显,由于代码的随机特性,每次都会产生不同的结果,因此结果将与上面显示的输出完全不同。 但可以将其用作代码应生成的输出的示例。

源码

int hero = 10;
int monster = 10;

Random dice = new Random();

do
{
    int roll = dice.Next(1, 10);
    monster -= roll;
    Console.WriteLine($"Monster was damaged and lost {roll} health and now has {monster} health.");

    if (monster <= 0) continue;

    roll = dice.Next(1, 10);
    hero -= roll;
    Console.WriteLine($"Hero was damaged and lost {roll} health and now has {hero} health.");

} while (hero > 0 && monster > 0);

Console.WriteLine(hero > monster ? "Hero wins!" : "Monster wins!");

// 输出: 
// Monster was damaged and lost 1 health and now has 9 health.
// Hero was damaged and lost 2 health and now has 8 health.
// Monster was damaged and lost 1 health and now has 8 health.
// Hero was damaged and lost 4 health and now has 4 health.
// Monster was damaged and lost 7 health and now has 1 health.
// Hero was damaged and lost 6 health and now has -2 health.
// Monster wins!