how to return bool value from method - c#

I have a while loop that loops until bool done = true;
In the method TestMoves(), depending on user input, the method returns the bool done as either true or false. However, I do not know how to "send" this value back to the while loop in my Start() method to stop the loop. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
Start("r");
}
public static string Start(string move)
{
Console.Write("Welcome to the Shotgun App\nEnter s for single player and m for multiplayer: ");
string gameType = Console.ReadLine();
if (gameType == "s")
{
Console.Write("Single Player Controls:\n r = reload\n s = shield\n f = fire\n ***you start with ammo\n Ready to play?");
Console.ReadLine();
int ammo = 1;
bool done = false;
while (!done)
{
Console.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("\nYou have reloaded, press enter for Genius\n");
ammo++;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
string geniusMove = "";
Genius(geniusMove, move, done);
Console.ReadLine();
break;
case "s":
Console.Write("\nYou have shielded, press enter for Genius\n");
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
geniusMove = "";
Genius(geniusMove, move, done);
Console.ReadLine();
break;
case "f":
if (ammo != 0)
{
Console.Write("\nYou have fired, press enter for Genius\n");
ammo--;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
geniusMove = "";
Genius(geniusMove, move, done);
Console.ReadLine();
}
else
{
Console.Write("You don't have enough ammo, try again");
done = false;
}
break;
default:
Console.Write("\nInvalid move, try again\n");
done = false;
break;
}
}
return move;
}
else
{
return move;
}
}
static string Genius(string geniusMove, string move, bool done)
{
int geniusAmmo = 1;
geniusMove = "r";
if (geniusMove == "f")
{
geniusAmmo--;
Console.Write("Genius had decided to fire.\nGenius ammo is " + geniusAmmo + "\n");
}
else if (geniusMove == "r")
{
geniusAmmo++;
Console.Write("Genius had decided to reload.\nGenius ammo is " + geniusAmmo + "\n");
}
else if (geniusMove == "s")
{
Console.Write("Genius had decided to shield.\nGenius ammo is " + geniusAmmo + "\n");
}
TestMoves(move, geniusMove, done);
return geniusMove;
}
static bool TestMoves(string move, string geniusMove, bool done)
{
if (move == "s" && geniusMove == "f")
{
Console.Write("No one has died yet");
done = false;
return done;
}
else if (move == "f" && geniusMove == "f")
{
Console.Write("You both died! Good game!");
done = true;
return done;
}
else if (move != "s" && geniusMove == "f")
{
Console.Write("You died! Good game!");
done = true;
return done;
}
else if (move == "f" && geniusMove == "s")
{
Console.Write("No one has died yet");
done = false;
return done;
}
else if (move == "f" && geniusMove != "s")
{
Console.Write("Genius died! Good game!");
done = true;
return done;
}
else if (move != "f" && geniusMove != "f")
{
Console.Write("No one has died yet");
done = false;
return done;
}
else
{
return done;
}
}
}
}

Is there a reason you need to call TestMoves from inside of Genius instead of from your loop? It seems to me that your code could be rewritten like this:
//Every instance of:
string geniusMove = "";
Genius(geniusMove, move, done);
Console.ReadLine();
//seems like it could be rewritten as:
string geniusMove = "";
Genius(geniusMove, move, done);
done = TestMoves(geniusMove, move, done);
Console.ReadLine();
//and then you can remove the call to TestMoves from Genius
The overall flow of all the code is a bit confusing to me. You have each function returning a value, but don't appear to be doing anything with the return value. I have a feeling that with a bit of refactoring, you could make this code much shorter and more logical.
After looking at your code a bit more it looks like you could place the call to TestMoves at the very end of your loop:
default:
Console.Write("\nInvalid move, try again\n");
done = false;
break;
}
//add it here:
done = TestMoves(geniusMove, move, done);
}
return move;

You can pass the value by ref:
static string Genius(string geniusMove, string move, ref bool done) ...
And return it from TestMoves:
static bool TestMoves(string move, string geniusMove) ...
To call it:
Genius(geniusMove, move, ref done);

Since bool is a value type, not a reference type, you're not able to pass the bool through like that. Use the out keyword to explicitly specify that you want to pass it as a reference:
http://msdn.microsoft.com/en-us/library/ee332485.aspx

You could use the ref or the out keyword on the done parameter

Related

my if/else if statment makes me input multiple times before running

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);
}
}

Add a second command that calls another method?

I'm remaking a text-based adventure game. During the character creation, I'd like for the user, at any time, to type 'skillset' and list all the traits that a specific race has. I've tried for a couple hours and can't seem to figure it out.
This is my character creation class.
public string userCommand_SeachSkill;
SkillSet searchSkill = new SkillSet();
public void Create_Character()
{
// CHOOSE GENDER //
do
{
validate = 0;
Console.Clear();
Console.Write("Are you male or female? (f/m): ");
Sex = Console.ReadLine().ToUpper();
if (Sex == "M" || Sex == "F")
{
validate = 1;
}
else if (Sex != "M" || Sex != "F")
{
Console.WriteLine("You must enter 'm' or 'f'");
}
} while (validate == 0);
And this is my Skill Set Class. Everything in the if/else statements are methods to print the traits of a race to the console. Let me know if there is anything else I can add to better ask my question. Thank you in advance! :)
ClassAttributes classes = new ClassAttributes();
Character character = new Character();
skillset = Console.ReadLine().ToUpper();
do
{
validate = 0;
if (skillset == "HUMAN")
{
classes.SkillSetHuman();
}
else if (skillset == "ORC")
{
classes.SkillSetOrc();
}
else if (skillset == "ELF")
{
classes.SkillSetElf();
}
else if (skillset == "EXIT")
{
validate = 1;
character.Create_Character();
}
} while (validate == 0);
I think you're looking for something like an event. C# Console Applications only seem to have one kind of event, it fires when ctrl+c or ctrl+break happens. You could handle your skillset input/output logic in the function handler
You can read more here:
https://msdn.microsoft.com/library/system.console.cancelkeypress(v=vs.110).aspx
If you really need the word to be typed, you could capture everything that is typed in a special function, instead of using regular Console.ReadLine(). Something like this:
public static string CustomReadLine()
{
ConsoleKeyInfo cki;
string capturedInput = "";
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
break;
else if (cki.Key == ConsoleKey.Spacebar)
{
capturedInput += " ";
Console.Write(" ");
}
else if (cki.Key == ConsoleKey.Backspace)
{
capturedInput = capturedInput.Remove(capturedInput.Length - 1);
Console.Clear();
Console.Write(capturedInput);
}
else
{
capturedInput += cki.KeyChar;
Console.Write(cki.KeyChar);
}
if (capturedInput.ToUpper().Contains("SKILLSET"))
{
capturedInput = "";
skillsetTyped();
return "";
}
}
return capturedInput;
}
then inside your Create_Character, do
...
do
{
Console.Write("Are you male or female? (f/m): ");
Sex = CustomReadLine();
} while (String.IsNullOrEmpty(sex));
And finally, handle the skillset logic here
protected static void skillsetTyped()
{
Console.Write("\nWrite your skillset capture/display logic here\n");
}
This is just a draft and has some minor bugs, but I believe it's close to what you really want.

How to make number Count in loop in c#?

This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}

C# program for guessing coin toss

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);
}

Ending while loop

I wrote a small Shotgun app, however, the section of code that needs to stop the game when either the AI (called Genius), the user, or both, are shot, I can't get to work. What am I doing wrong? I feel like I over-complicated my code a ton by adding lots of returns with different booleans, in which some are being passed and others aren't.
In testing it right now, the loop ends no matter what if the user move (called string move) equals "f". In any other scenario, I can not get the loop to end.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
Start("r");
}
public static string Start(string move)
{
Console.Write("Welcome to the Shotgun App\nEnter s for single player and m for multiplayer: ");
string gameType = Console.ReadLine();
if (gameType == "s")
{
Console.Write("Single Player Controls:\n r = reload\n s = shield\n f = fire\nYou start with 1 ammo\nReady to play?");
Console.ReadLine();
int ammo = 1;
int geniusAmmo = 1;
string geniusMove = "";
bool done = false;
while (!done)
{
Console.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("\nYou have reloaded, press enter for Genius\n");
ammo++;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
break;
case "s":
Console.Write("\nYou have shielded, press enter for Genius\n");
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
break;
case "f":
if (ammo != 0)
{
Console.Write("\nYou have fired, press enter for Genius\n");
ammo--;
Console.Write("Your ammo is " + ammo);
Console.ReadLine();
Genius(geniusMove, move, geniusAmmo, done);
}
else
{
Console.Write("You don't have enough ammo, try again");
done = false;
}
break;
default:
Console.Write("\nInvalid move, try again\n");
done = false;
break;
}
done = EndLoop(move, geniusMove, done);
Console.ReadLine();
}
return move;
}
else
{
return move;
}
}
public static string Genius(string geniusMove, string move, int geniusAmmo, bool done)
{
Random RandomNumber = new Random();
int x = RandomNumber.Next(0,3);
if (x == 0)
{
geniusMove = "f";
geniusAmmo--;
Console.Write("Genius had decided to fire.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
else if (x == 1)
{
geniusMove = "r";
geniusAmmo++;
Console.Write("Genius had decided to reload.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
else if (x == 2)
{
geniusMove = "s";
Console.Write("Genius had decided to shield.\nGenius ammo is " + geniusAmmo + "\n");
TestMoves(move, geniusMove);
}
return geniusMove;
}
public static void TestMoves(string move, string geniusMove)
{
bool done = false;
if (move == "s" && geniusMove == "f")
{
Console.Write("Nice shield, no one has died yet");
}
else if (move == "f" && geniusMove == "f")
{
Console.Write("You both died! Good game!");
}
else if (move == "r" && geniusMove == "f")
{
Console.Write("No shield!? You died! Good game!");
}
else if (move == "f" && geniusMove == "s")
{
Console.Write("Genius is too good, no one has died yet");
}
else if (move == "f" && geniusMove != "s")
{
Console.Write("Genius let his guard down! Good game!");
}
else if (move != "f" && geniusMove != "f")
{
Console.Write("Keep playing it safe.");
}
else
{
}
}
static bool EndLoop(string move, string geniusMove, bool done)
{
done = false;
if (move == "s" && geniusMove == "f")
{
return false;
}
else if (move == "f" && geniusMove == "f")
{
return true;
}
else if (move != "s" && geniusMove == "f")
{
return true;
}
else if (move == "f" && geniusMove == "s")
{
return false;
}
else if (move == "f" && geniusMove != "s")
{
return true;
}
else if (move != "f" && geniusMove != "f")
{
return false;
}
else
{
return done;
}
}
}
}
You are setting done in a few different places, both in some execution branches in the switch cases, and when calling EndLoop. The assignment from EndLoop will overwrite any previous assignment, so make that The One Place You Set done.
Setting done with EndLoop in TestMoves does not have any effect since you immediately return a hard-coded value right after you call EndLoop.
I suggest you follow through EndLoop in a debugger. If it makes it easier for you to visualize what's happening, you might consider instead printing to the console the input parameters for EndLoop, and which if condition you end up selecting.
geniusMove will always be an empty string since you are not storing the result of the call to the Genius method.
Either store the result in the geniusMove variable or pass it in by reference
public static string Genius(ref string geniusMove, string move, int geniusAmmo, bool done)
or
geniusMove = Genius(geniusMove, move, geniusAmmo, done);

Categories

Resources