Hi I am making a simple shotgun game where the user vs the computer and pick shoot, shield or reload But when I try to set the enumeration to random it gives me the error
Cannot implicitly convert type int to ShotgunGame.Program.ShotgunOption. An explicit conversion exists (are you missing a cast?),
I am not sure how to fix this.
Any Guidance would be appreciated
//Declare Variables
Console.Title = "Welcome To The Shotgune Game";
int CPUBullets = 3, userBullets = 3;
ShotgunOption UserOption;
int computerChoice, userScore = 0;
bool QUIT = false;
double gameCount = 0.0;
Random computer = new Random();
Console.Clear();
Console.WriteLine("SHOOT RELOAD SHIELD");
do
{
do
{
//Console.Write("Please enter choice, or enter QUIT to quit: ");
UserOption = GetOptionFromUser();
if (UserOption.ToUpper() == "QUIT")
{
break;
}
ShotgunOption CPUOption = computer.Next(1, 3); // 1 is Shot, 2 is Reload, 3 is Shield
switch (UserOption.ToUpper())
{
case "SHOOT":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. It was a tie!", userChoice);
; userBullets --;CPUBullets --; ++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
++gameCount;
}
break;
case "RELAOD":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You Both Gain A bullet", userChoice);
userBullets++; CPUBullets++; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
}
break;
case "SHIELD":
if (computerChoice == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", userChoice);
++gameCount;
}
else if (computerChoice == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", userChoice);
++userScore; ++gameCount;
}
else if (computerChoice == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", userChoice);
++gameCount;
}
break;
}
}
while (UserOption != ShotgunOption.Shield || CPUOption != 4);
} while (QUIT == false || gameCount == 3);
Shotgune game
As the error message suggests, you're trying to assign an int to a variable that is expecting an enum value. You can cast the int to an enum, though:
(EnumName)integerValue
So in this case:
ShotgunOption CPUOption = (ShotgunOption)computer.Next(1, 3);
Array values = Enum.GetValues(typeof(ShotgunOption));
Random computer = new Random();
ShotgunOption CPUOption = (ShotgunOption)values.GetValue(computer.Next(values.Length));
Try this...
Related
So when I run the code I can press 1 and that runs fine but when I try entering 2 or 3 then the computer makes me enter 2 or 3 multiple times before running that line of code.
I don't know what the problem with this is.
I'm new so if there is a better way to run something like this instead of if statements please let me know.
using System;
namespace PracticeScript
{
class Program
{
static void Main()
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
if (Console.ReadLine() == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (Console.ReadLine() == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (Console.ReadLine() == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
You need to store the result of Console.ReadLine before testing its value:
string line = Console.ReadLine();
if (line == "1")
{
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
}
else if (line == "2")
{
Console.WriteLine("You prepaired your sheild for the incoming attack");
}
else if (line == "3")
{
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!" );
}
Otherwise your program will call Console.ReadLine 3 times and prompt the user 3 times in the worst case.
Console.ReadLine() will prompt for input every time you call it.
You can use a switch statement instead to ask for input once and compare it against every value you want to handle:
switch (Console.ReadLine())
{
case "1":
// ...
break;
case "2":
// ...
break;
// Add rest of cases here
}
Basically, you are evaluating each Console.Readline() each time the user enters a value. So, user enter 2, if (Console.ReadLine() == "1") evaluates to false. Enters 2 again, else if (Console.ReadLine() == "2") evaluates to true. As others have stated, use Console.ReadLine() once per loop, store the value, and check it in your if statements:
string userinput = Console.ReadLine();
if(userinput == "1")
// do stuff
else if(userinput == "2")
// do other stuff
//etc.
I suggest you to use a switch
The problem was the fact that you repeated 3 time Console.ReadLine() instead of storing and using its value!
Plus, I added a check of the user input, you didn't think about the possibility to have an invalid input!
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int playerHp = 100;
int enemyHp = 100;
int playerD = rnd.Next(10, 15);
int enemyD = rnd.Next(10, 15);
int potion = 25;
Console.Write("Get Ready! It's time to battle! ");
Console.WriteLine("You stare into the eyes of the ugly goblin and are ready to slay it with your sword \n");
do
{
Console.WriteLine(" what will you do now?");
Console.WriteLine("\n 1. Attack 2. Defend 3. Use potion");
bool isInputValid = false;
while (isInputValid == false)
{
isInputValid = true;
switch (Console.ReadLine())
{
case "1":
enemyHp -= playerD;
Console.WriteLine("you swung your sword and struck the goblin in the body leaving it " + enemyHp + "HP left over");
break;
case "2":
Console.WriteLine("You prepaired your sheild for the incoming attack");
break;
case "3":
playerHp += potion;
Console.WriteLine("You chugged down the potion as quick as you could and now have " + playerHp + " left!");
break;
default:
Console.WriteLine("Invalid input, please choose a listed action!");
isInputValid = false;
break;
}
}
Console.WriteLine("\nEnemy Turn!");
playerHp -= enemyD;
Console.WriteLine("The goblin struck you with his mace and left you with " + playerHp + "HP left!");
} while (playerHp > 0 || enemyHp > 0);
}
}
I am very confused, this is only my second project in coding/scripting and i do not understand how to have multiple choices for a player to choose between. the loop goes back after the second or third question without continuing and it keeps skipping a few lines of code just wondering what I am doing wrong.
static void Main(string[] args)
{
Random rng = new Random();
int stuff = 0;
bool gameGo = true;
string yourAnswer = "";
string choice1 = "";
string choice2 = "";
string choice3 = "";
string choice4 = "";
int healthPoints = 100;
int deathNumber = rng.Next(0, 10);
deathNumber = deathNumber = 0;
int stabbed = rng.Next(1, 4);
string name = "";
int trap = rng.Next(1, 5);
int arrow = rng.Next(7, 14);
int menu = 0;
int potion = rng.Next(1, 10);
int flyHealth = rng.Next(5, 10);
int flyAttack = rng.Next(3, 5);
int tribeAttack = rng.Next(80, 100);
int playersSword = rng.Next (3, 5);
while(true)
{
break;
}
while (gameGo || stuff == 1 )
{
Console.Write("You have ");
Console.Write(healthPoints);
Console.Write(", health points left");
Console.Write(" \nIf your health points drops to ");
Console.Write(deathNumber);
Console.Write(", you will DIE!");
Console.WriteLine("\nWell now that that's out of the way, excuse me for being so rude but,\nmay i have your name? Please hit enter after to continue.");
name = Console.ReadLine();
Console.Clear();
if (name == "Dustin")
{
Console.Write("You have");
Console.Write(healthPoints);
Console.Write(", health points left");
Console.WriteLine("\nI am so proud of you for figuring out your name, {0}", name);
Console.WriteLine("Shall we move on to the story?\n Hit Enter to continue.");
Console.ReadLine();
menu = 2;
}
else if (name != "Dustin")
{
healthPoints -= stabbed;
Console.Clear();
Console.WriteLine("Seriously you cant figure out your name, how dumb are you?");
}
if (menu == 2)
{
Console.WriteLine("You see a cave in the distance.");
Console.WriteLine(" You have to make a choice.");
Console.WriteLine("Do you go in to explore or do you pass on by?");
Console.WriteLine("a) Do you go in\nOr B) do you pass by?");
choice1 = Console.ReadLine();
}
if (choice1 == "a")
{
Console.WriteLine("You enter a dark cave with no idea where to go but you found a sword.");
Console.WriteLine("The sword can do 1-5 damage.\n This is your only defense.");
Console.Write("\nTap enter once to continue");
Console.ReadLine();
menu = 3;
Console.Clear();
}
if (choice1 == "b")
{
Console.WriteLine("What, are you scared of the dark?");
healthPoints -= stabbed;
Console.WriteLine("A masked man stabbed you for not going in the cave and says");
Console.Write("you now have,");
Console.Write(healthPoints);
Console.Write(" health points left");
Console.WriteLine("Hit enter to continue.");
Console.ReadLine();
menu = 4;
continue;
}
{
while (menu == 3)
{
Console.WriteLine("You wander further in the cave and look around");
Console.WriteLine("You see a torch on the wall");
Console.WriteLine("You have another choice.\nDo you a) Light the torch \n or b) Leave it unlit");
choice2 = Console.ReadLine();
Console.Clear();
}
if (choice2 == "a")
{
Console.WriteLine("Well done my good sir, you have brought light to this wretched cave.");
Console.WriteLine("You move along slowly and encounter a giant fly.");
Console.Clear();
menu = 5;
}
if (choice2 == "b")
{
Console.WriteLine("What do you enjoy being in the dark?");
healthPoints -= stabbed;
Console.WriteLine("A masked man snuck up on you and stabbed you in the dark");
Console.Write("you now have,");
Console.Write(healthPoints);
Console.Write(" health points left");
Console.ReadLine();
Console.WriteLine("You move along slowly in the dark and encounter a giant fly.");
Console.ReadLine();
Console.Clear();
menu = 6;
}
}
{
while (menu == 4)
{
Console.WriteLine("You chose to keep walking along and not go into the cave.");
Console.WriteLine("You stumble across a large valley.");
Console.WriteLine("Time for another choice.");
Console.WriteLine("Do you a) Climb down the valley hoping for cool treasure?\nOR b) Keep walking along?");
choice3 = Console.ReadLine();
Console.Clear();
}
if (choice3 == "a")
{
Console.WriteLine("You decided to go into the valley");
Console.WriteLine("Little did you know there was a trap that got sprung as you climbed down");
healthPoints -= trap;
Console.Clear();
menu = 7;
}
if (choice3 == "b")
{
Console.WriteLine("How much more boring can you get, do you ever go on real adventures.");
Console.WriteLine("as you are walking along a stray arrow comes out of no where and strikes you in the leg.");
healthPoints -= arrow;
Console.Clear();
menu = 8;
}
}
{
while (menu == 5)
{
//giant fly fight
Console.Write("The giant fly swoops in to attack");
flyAttack -= healthPoints;
Console.WriteLine("The fly does {0} damage to your health", flyAttack);
Console.Write("You now have,");
Console.Write(healthPoints);
Console.Write(" health.");
Console.WriteLine("You attack back, with your sword you found");
playersSword -= flyHealth;
Console.WriteLine("You did {0} damage to the flys health points.", playersSword);
menu = 9;
}
while (menu == 6)
{
Console.Write("The giant fly swoops in to attack");
flyAttack -= healthPoints;
Console.WriteLine("The fly does {0} damage to your health", flyAttack);
Console.Write("You now have,");
Console.Write(healthPoints);
Console.Write(" health.");
Console.WriteLine("You attack back, with your sword you found");
playersSword -= flyHealth;
Console.WriteLine("You did {0} damage to the flys health points.", playersSword);
menu = 9;
}
while (menu == 7)
{
Console.WriteLine("You reach the bottom and come across a tribe of people.");
Console.WriteLine("This tribe has never seen another human before.");
Console.WriteLine("Hit enter to continue.");
Console.ReadLine();
Console.Clear();
Console.WriteLine("You hesitate for a bit wondering what to do. \nWhen all of a sudden the tribe attacks.");
healthPoints -= tribeAttack;
Console.Write("You have ");
Console.Write(healthPoints);
Console.Write(", health points left");
}
if (menu == 8)
{
//kept walking
}
if (menu == 9)
{
while loops happen until a condition is satisfied.
Something written like this (which is taken from your example above) will never stop.
while (menu == 3 {
// do stuff here, but menu never changes
}
The loop is entered when menu is 3. menu is never changed from within the loop, so it will never change from 3 - thus the loop will never exit. It will simply start back at the beginning of the loop until menu is not 3.
For further clarification, if statements cause code to be executed based on a condition. Unlike a while loop, the block of code that is executed is not looped through. If the condition is false, no code within the block is executed. If the condition is true, the code within the block is only executed once.
You'll be able to make some progress once you think about how things flow. To help with this, if you're using a modern IDE, you can set a breakpoint at the beginning and step through the program, watching how decisions are made one line at a time.
I am trying to make a simple shotgun game where the user vs the CPU and the both pick shot, shield or reload using enumeration but When I go to run my code it just keeps looping what the user and computer picked. I am not sure as to how to fix this
Any guidance would be appreciated
//Declare Variables
Console.Title = "Welcome To The Shotgune Game";
int CPUBullets = 3, userBullets = 3;
ShotgunOption UserOption;
int userScore = 0;
bool QUIT = false;
double gameCount = 0.0;
Random computer = new Random();
Console.Clear();
Console.WriteLine("SHOOT RELOAD SHIELD");
UserOption = GetOptionFromUser();
ShotgunOption CPUOption = (ShotgunOption)computer.Next(1, 3); // 1 is Shot, 2 is Reload, 3 is Shield
do
{
// if (UserOption == "QUIT")
//{
//break;
//}
do
{
//Console.Write("Please enter choice, or enter QUIT to quit: ");
switch (UserOption)
{
case ShotgunOption.Shoot:
if((int)CPUOption == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. It was a tie!", UserOption);
; userBullets --;CPUBullets --; ++gameCount;
}
else if ((int)CPUOption == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", UserOption);
++userScore; ++gameCount;
}
else if ((int)CPUOption == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", UserOption);
++gameCount;
}
break;
case ShotgunOption.Reload:
if((int)CPUOption == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", UserOption);
++userScore; ++gameCount;
}
else if ((int)CPUOption == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You Both Gain A bullet", UserOption);
userBullets++; CPUBullets++; ++gameCount;
}
else if ((int)CPUOption == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", UserOption);
}
break;
case ShotgunOption.Shield:
if((int)CPUOption == 1)
{
Console.WriteLine("You chose {0} and the computer chose Shoot. You lose!", UserOption);
++gameCount;
}
else if ((int)CPUOption == 2)
{
Console.WriteLine("You chose {0} and the computer chose Reload. You win!", UserOption);
++userScore; ++gameCount;
}
else if ((int)CPUOption == 3)
{
Console.WriteLine("You chose {0} and the computer chose Shield. No Damage!", UserOption);
++gameCount;
}
break;
}
}
while (UserOption != ShotgunOption.Shield || CPUOption != ShotgunOption.Shield);
} while (QUIT == false || gameCount != 3 || UserOption != ShotgunOption.Shield || CPUOption != ShotgunOption.Shield);
if (gameCount > 1)
{
DisplayResults(UserOption, CPUOption, userScore, userBullets, CPUBullets);
}
You are never updating the user's input within your loop. Once the user makes a choice, it is never changed.
UserOption = GetOptionFromUser(); should also occur in your loop. At least that's what I can tell from a quick glance.
I'm a beginner with programming so any hints would be greatly appreciated!
I'm trying to create a program where the user guesses whether a 'coin toss' will produce heads (0) or tails (1) using a random number generator and a loop as the 'coin'. The program must output the percent of correct guesses out of the total games played.
I've tried many different ways and it's far from right! It's v discouraging.
Thanks in advance for any tips!!
-C
This is basically the closest I've come:
for (numPlays = 0; ; numPlays++)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Convert.ToChar(Console.ReadLine());
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'Q' || userChoice == 'q')
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
Console.WriteLine("\nYOU LOSE");
if (userChoice == 'q' || userChoice == 'Q')
{
percentWin = (double)(numWins / numPlays);
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
}
}
}
Console.ReadKey();
}
}
I optimized your code a little bit,I hope this helps:
int numPlays = 0, numWins = 0;
int compChoice = 0;
char userChoice;
double percentWin;
Random rnd = new Random();
while (true)
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
userChoice = Console.ReadKey().KeyChar;
compChoice = rnd.Next(0, 2);
if (char.ToLowerInvariant(userChoice) != 'q')
{
if (char.ToLowerInvariant(userChoice) == 'h' && compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else if (char.ToLowerInvariant(userChoice) == 't' && compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
numPlays++;
}
else
{
percentWin = (double) numWins/numPlays;
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
break;
}
}
I think you don't need an explanation, all of the code is self-explanatory.But you have an obvious mistake when you calculating the percentage:
percentWin = (double)(numWins / numPlays);
Here you are performing an integer division,then casting that result to double,it's pointless because you already lose your decimal points.Instead you should cast one of the operands to double so it will perform a double division and you will get the correct result.
Just invoke this method and play your game!
public static void SomeMethod()
{
Console.Write("\nWrite H/h to guess Heads, T/t to guess Tails, or Q/q to quit => ");
char userChoice;
int numWins = 0;
int numPlays = 0;
double percentWin = 0d;
while ((userChoice = Convert.ToChar(Console.ReadLine())).ToString().ToLower() != "q")
{
numPlays++;
int compChoice = new Random().Next(2);
if (userChoice == 'H' || userChoice == 'h')
{
if (compChoice == 0)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
if (userChoice == 'T' || userChoice == 't')
{
if (compChoice == 1)
{
Console.WriteLine("\nYOU WON");
numWins++;
}
else
{
Console.WriteLine("\nYOU LOSE");
}
continue;
}
}
if (numPlays != 0)
{
percentWin = (double)numWins / numPlays;
}
Console.WriteLine("\nYou won {0} out of {1} game(s) or {2:P} of the games played.", numWins, numPlays, percentWin);
Console.ReadKey();
}
This should not be any difficult, you just need to make a clear algorithm
Let me suggest one
Char playOrExit= 'y'
Int32 gameCount = 0;
Int32 Wins = 0;
While (playOrExit.ToUpper.Equals('Y'))
{
Console.Write("Press Y to continue playing and N to exit");
playOrExit = Convert.ToChar(Console.ReadLine());
//Computer choice will be math.random from 0 and 1
//now take user choice
//compare and show if he won or lost
}
if(gameCount >0)
{
Console.WriteLine("\nYou played {0} times, out of which {1} game(s) were won.", gameCount,Wins);
}
I need to return back to the beginning of the code shown here after a user enters the wrong key. Is there any simple line of code that will just return back to another line? As you can see I already have an if statement set up so I can just add something that can return back to the beginning or to another area in my code. I am really quite new to c# and programming in general. I really just don't want to have to enter all the code again into another if statement that would produce the same issue. I would preferably like to have the code just run again after a user enters a wrong key, because then they can re-read it without having to start from scratch again.
//Runs battle interactive
Console.WriteLine("");
Console.WriteLine("You have encountered a simple guard! He deals 2 damage per attack and has 1 HP.");
Console.WriteLine("You currently have: " + Program.Inventory);
Console.WriteLine("Choose a weapon!");
var input2 = Console.ReadKey();
//Key checker for items
switch (input2.Key)
{
case ConsoleKey.D1:
Console.WriteLine("");
if (Items.iniFists == true)
{
Console.WriteLine("You have attacked with your Fists for 1 DMG!");
}
else
{
//this will never run, just a placeholder
Console.WriteLine("You Don't have your fists!");
switch (input2.Key)
{
case ConsoleKey.D1:
Console.WriteLine("");
if (Items.iniFists == true)
{
Console.WriteLine("You have attacked with your Fists for 1 DMG!");
}
else
{
//this will never run, just a placeholder
Console.WriteLine("You Don't have your fists!");
}
break;
case ConsoleKey.D2:
Console.WriteLine("");
if (Items.iniLongsword == true)
{
Console.WriteLine("You have chosen to attack with the Longsword for 2 DMG!");
}
else
{
Console.WriteLine("You don't have a longsword!");
}
break;
case ConsoleKey.D3:
Console.WriteLine("");
if (Items.iniBow == true)
{
Console.WriteLine("You have chosen to attack with the Bow for 3 DMG!");
}
else
{
Console.WriteLine("You don't have a Bow!");
}
break;
case ConsoleKey.D4:
Console.WriteLine("");
if (Items.iniLightstaff == true)
{
Console.WriteLine("You have chosen to attack with the Lightstaff for 4 DMG!");
}
else
{
Console.WriteLine("You don't have a Lightstaff!");
}
break;
case ConsoleKey.D5:
Console.WriteLine("");
Console.WriteLine("You can't attack with an Apple!");
break;
case ConsoleKey.D6:
Console.WriteLine("");
Console.WriteLine("You can't attack with a Golden Key!");
break;
case ConsoleKey.D7:
Console.WriteLine("");
Console.WriteLine("You can't attack with a Steak!");
break;
}
}
break;
case ConsoleKey.D2:
Console.WriteLine("");
if (Items.iniLongsword == true)
{
Console.WriteLine("You have chosen to attack with the Longsword for 2 DMG!");
}
else
{
Console.WriteLine("You don't have a longsword!");
}
break;
case ConsoleKey.D3:
Console.WriteLine("");
if (Items.iniBow == true)
{
Console.WriteLine("You have chosen to attack with the Bow for 3 DMG!");
}
else
{
Console.WriteLine("You don't have a Bow!");
}
break;
case ConsoleKey.D4:
Console.WriteLine("");
if (Items.iniLightstaff == true)
{
Console.WriteLine("You have chosen to attack with the Lightstaff for 4 DMG!");
}
else
{
Console.WriteLine("You don't have a Lightstaff!");
}
break;
case ConsoleKey.D5:
Console.WriteLine("");
Console.WriteLine("You can't attack with an Apple!");
break;
case ConsoleKey.D6:
Console.WriteLine("");
Console.WriteLine("You can't attack with a Golden Key!");
break;
case ConsoleKey.D7:
Console.WriteLine("");
Console.WriteLine("You can't attack with a Steak!");
break;
}
C# supports labels in code, however it is not recommended due to the fact that it violates many coding best practices, but I guess there is always an exception to any rule.
class Program
{
static void Main(string[] args)
{
Start:
Console.WriteLine("Start Here... Press any key");
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.A:
goto MyLabel;
case ConsoleKey.B:
goto MyLabel2;
case ConsoleKey.C:
goto MyLabel3;
default:
Console.WriteLine("Bad Choice");
goto Start;
}
MyLabel:
Console.WriteLine("MyLabel: A");
goto Start;
MyLabel2:
Console.WriteLine("MyLabel: B");
goto Start;
MyLabel3:
Console.WriteLine("MyLabel: C");
goto Start;
}
}
You can find more information here:
http://msdn.microsoft.com/en-us/library/d96yfwee.aspx
http://msdn.microsoft.com/en-us/library/13940fs2.aspx
you have a couple options, you can use a while loop
bool continue = true;
while(continue == true)// or you can simply type "while(continue)"
{
/* everything inside the `while` loop will be
repeated until `continue` is not `true`. */
}
you can also use methods
public static void doStuff()
{
// insert stuff here
}
and then you can call that from elsewhere in your class
if(x = 6)
{
doStuff(); //this line does the stuff
doStuff(); // this line does the stuff again.
}
One answer to this is to check that you have valid input in a loop like this:
while (true)
{
ConsoleKey i = Console.ReadKey()
if (i == ConsoleKey.D1 || ... ) //Check if it's equal to any valid key, you
//might be able to simplify it with <= and
//>= if valid keys are sequential.
break;
Console.WriteLine("You have entered an invalid key");
}
Alternatively, you can add a goto statement at the end of your switch block:
SwitchStatement: switch(input2.Key)
...
default:
Console.WriteLine("Invalid key pressed");
goto SwitchStatement;
break;
}