我正在做一个基于文本的小游戏,我的一个if/else语句没有给我预期的结果.当用户输掉它时,立即跳转到"Game Over!" 应该说monsterName +"击败了你!" 然后跳到游戏结束.
你们能帮忙指出我的逻辑错误吗?
// Main Game Loop
while (playerHealth > 0 && monsterHealth > 0)
{
bool playerAct = askAction();
if (playerAct == true)// User attacks
{
monsterHealth = monsterHealth - playerAtk;
if (monsterHealth < 0)
{
Console.WriteLine(monsterName + " falls to the ground, defeated. Congradulation, " + name + "!");
}
else
{
Console.WriteLine(monsterName + " takes a mighty swing back at you!");
playerHealth = playerHealth - monsterAtk;
}
}
else// User defends
{
playerHealth = playerHealth - defendAtk;
if (playerHealth < 0)
{
Console.WriteLine(monsterName + " has defeated you!");
}
else
{
Console.WriteLine(monsterName + " swings at you. It glances off your defenses.");
}
}
}
// End Game
Console.WriteLine("Game Over!");
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
我认为这是相关的代码,但以防万一,这是整个程序.
namespace textBasedGame
{
class Program
{
static void Main(string[] args)
{
//Variables
string name;
string monsterName;
int playerAtk = 5;
int monsterAtk = 2;
int defendAtk = 1;
int playerHealth = 2;
int monsterHealth = 3;
// Gathers information from the user
Console.WriteLine("What is your name?");
name = Console.ReadLine();
Console.WriteLine("What is your enemies name?");
monsterName = Console.ReadLine();
//Story Intro
Console.WriteLine("You are hunting in the swamp and in the darkness of the overgrowth you see a movement.");
Console.WriteLine("You creep closer to the silouette.");
Console.WriteLine("A little closer....");
Console.WriteLine("It looks familiar....");
Console.WriteLine("It is " + monsterName + "!!!");
Console.WriteLine("Now is your chance!");
// Main Game Loop
while (playerHealth > 0 && monsterHealth > 0)
{
bool playerAct = askAction();
if (playerAct == true)// User attacks
{
monsterHealth = monsterHealth - playerAtk;
if (monsterHealth < 0)
{
Console.WriteLine(monsterName + " falls to the ground, defeated. Congradulation, " + name + "!");
}
else
{
Console.WriteLine(monsterName + " takes a mighty swing back at you!");
playerHealth = playerHealth - monsterAtk;
}
}
else// User defends
{
playerHealth = playerHealth - defendAtk;
if (playerHealth < 0)
{
Console.WriteLine(monsterName + " has defeated you!");
}
else
{
Console.WriteLine(monsterName + " swings at you. It glances off your defenses.");
}
}
}
// End Game
Console.WriteLine("Game Over!");
Console.ReadLine();
}
static bool askAction()//Displays HP and asks for user action. Returns true or false
{
bool move;
Console.WriteLine("What would you like to do?(type: attack or defend)");
string playerAction = Console.ReadLine();
if (playerAction == "attack")
{
return move = true;
}
else
{
return move = false;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
while (playerHealth > 0 && monsterHealth > 0)
if (playerHealth < 0)
Run Code Online (Sandbox Code Playgroud)
while只要玩家的健康状况高于零,循环就会继续.该if声明火灾时,他们的健康是零度以下.如果他们的健康状况正好为零会怎样?