Hey! This is probably very easily solved, but I simply can’t find what’s wrong with my code. This is what I want it to do: If I enter “attack” it attacks, then if I enter “defend” it defends, and if I then enter “attack” again, it does that, and so on and so on. It simply loops from the beginning and ignores what you just wrote.
And this is what it does:
Let’s say I enter “attack”. It then does the “attack”, but then no matter what I enter after that, it only does “attack”. So even if I write “defend” or “bkjwkjfknd” it still just attacks.
What am I missing? I’ve tried so many different things, for example, changing the if else-statements to just several if-statements, I’ve also tried using switch cases, and that got a different error (the first answer I entered was ignored completely, the second answer was done, and then the first answer was ignored, but the second was done and so on).
Here’s my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
Random attack = new Random();
//player variables
int playerHealth = 50;
int playerAttack = attack.Next(5, 15);
string playerName;
//strings with enemy type and name + randomising
string[] enemyType = "warrior|goblin|elf|evil princess".Split('|');
int typeChoice = new Random().Next(enemyType.Length);
string[] enemyName = "Leia|Nora|Baron|Cahira".Split('|');
int nameChoice = new Random().Next(enemyType.Length);
// enemy variables
int enemyHealth = 50;
int enemyAttack = attack.Next(5, 15);
string randomEnemyType = enemyType[typeChoice];
string randomEnemyName = enemyName[nameChoice];
// Starting of the game
Console.WriteLine("What is your name?");
playerName = Console.ReadLine();
// here I have a lot of text not relevant to the problem
Console.WriteLine("What will you do? Type 'attack' or 'defend'.");
string input = Console.ReadLine();
do
{
if (input == "attack")
{
enemyHealth -= playerAttack;
playerHealth -= enemyAttack;
Console.WriteLine("\n" + playerName + " attacks " + randomEnemyName + "! " + randomEnemyName + " attacks back!");
}
else if (input == "defend")
{
Console.WriteLine("\n" + playerName + " puts up their shield and defends themselves. ");
playerHealth -= enemyAttack / 2;
}
else
{
Console.WriteLine("\nThat is not a valid command. Please write 'attack' or 'defend'.");
}
// health status
Console.WriteLine(playerName + "s health is now " + playerHealth + " and " + randomEnemyName +
"s health is now " + enemyHealth + ". What will you do next?");
Console.ReadLine();
} while (playerHealth > 0 && enemyHealth > 0);
if (playerHealth <=0)
{
Console.WriteLine(randomEnemyName + " slayed " + playerName + "!!");
Console.ReadLine();
}
if (enemyHealth <=0)
{
Console.WriteLine(playerName + " slayed " + randomEnemyName + "!!");
Console.ReadLine();
}
}
}
}