Moving trough Array by using ReadKey() - c#

In the beginning i will tell that I'm new with C# and Programming. Trying to learn as much as i can alone.
My first learning project is simple. Moving trough array 10x10 by using "W, S, A, D". It is "game" which is letting user to move his character trough array. The problem is that i want "my character" to move as long as his position will be out of range. So i think i'm trying to make infitive loop which is printing position and lets moving forward. If i'm using for example do{}while(true), position is changing all the time after pressing one key. I'm looking for suggestion how should i construct loop for this kind of "movement".
I'm attaching my code which is responsible for moving character.
int axisx = 0;
int axisy = 0;
var movement = Console.ReadKey();
int[,] level = new int[10, 10];
if (movement.Key.ToString() == "W"){axisy = axisy+1;}
else if (movement.Key.ToString() == "S"){axisy = axisy-1;}
else if (movement.Key.ToString() == "D"){axisx = axisx+1;}
else if (movement.Key.ToString() == "A"){axisx = axisx-1;}
Console.WriteLine("{2} is on position:{0},{1}", axisx, axisy, Player1.getBuilderName());
if (movement.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed Escape, Goodbye");
}

You can use a while(true) loop:
int axisx = 0;
int axisy = 0;
while (true)
{
var movement = Console.ReadKey();
if (movement.KeyChar == 'W' || movement.KeyChar == 'w')
{
axisy += 1;
}
else if (movement.KeyChar == 'S' || movement.KeyChar == 's')
{
axisy -= 1;
}
else if (movement.KeyChar == 'D' || movement.KeyChar == 'd')
{
axisx += 1;
}
else if (movement.KeyChar == 'A' || movement.KeyChar == 'a')
{
axisx -= 1;
}
Console.WriteLine("{2} is on position:{0},{1}", axisx, axisy, Player1.getBuilderName());
if (movement.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed Escape, Goodbye");
break;
}
}
The break; in the ConsoleKey.Escape block will get you out of the loop.
You can also use movement.KeyChar instead of movement.Key.ToString(), strings are immutable in .NET, so every time you do a ToString() you are creating a new string.

Related

Detecting multiple keys in Unity

I'm following along with a tutorial about creating a mini-RTS in Unity, but I've hit something of a roadblock when it comes to the selection feature for assigning selection groups for multiple units.
The pertinent parts are below:
In the Update() method of my UnitsSelection class
//manage selection groups with alphanumeric keys
if (Input.anyKeyDown)
{
int alphaKey = Utils.GetAlphaKeyValue(Input.inputString);
if (alphaKey != -1)
{
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
_CreateSelectionGroup(alphaKey);
}
else
{
_ReselectGroup(alphaKey);
}
}
}
And the GetAlphaKeyValue method from Utils:
public static int GetAlphaKeyValue(string inputString)
{
if (inputString == "0") return 0;
if (inputString == "1") return 1;
if (inputString == "2") return 2;
if (inputString == "3") return 3;
if (inputString == "4") return 4;
if (inputString == "5") return 5;
if (inputString == "6") return 6;
if (inputString == "7") return 7;
if (inputString == "8") return 8;
if (inputString == "9") return 9;
return -1;
}
This is the code that is used in the tutorial, but to my understanding there is no way that _CreateSelectionGroup() would ever be called.
I've seen the tutorial demonstrate this functionality working, but whenever I try to run it GetAlphaKeyValue turns the Left and Right control keys into a -1 value so the if statement that checks for them never runs.
Am I missing something here? How does Unity normally handle things like Ctrl+1?
If you use the inputString I would always rather check for Contains instead of an exact string match. However, I tried to use the inputString in the past and I found it too unpredictable for most usecases ^^
While holding control keys your Keyboard most likely simply won't generate any inputString.
Only ASCII characters are contained in the inputString.
But e.g. CTRL+1 will not generate the ASCII symbol 1 but rather a "non-printing character", a control symbol - or simply none at all.
You should probably rather use e.g.
public static bool GetAlphaKeyValue(out int alphaKey)
{
alphaKey = -1;
if (Input.GetKeyDown(KeyCode.Alpha0) alphaKey = 0;
else if (Input.GetKeyDown(KeyCode.Alpha1) alphaKey = 1;
else if (Input.GetKeyDown(KeyCode.Alpha2) alphaKey = 2;
else if (Input.GetKeyDown(KeyCode.Alpha3) alphaKey = 3;
else if (Input.GetKeyDown(KeyCode.Alpha4) alphaKey = 4;
else if (Input.GetKeyDown(KeyCode.Alpha5) alphaKey = 5;
else if (Input.GetKeyDown(KeyCode.Alpha6) alphaKey = 6;
else if (Input.GetKeyDown(KeyCode.Alpha7) alphaKey = 7;
else if (Input.GetKeyDown(KeyCode.Alpha8) alphaKey = 8;
else if (Input.GetKeyDown(KeyCode.Alpha9) alphaKey = 9;
return alphaKey >= 0;
}
And then use it like
//manage selection groups with alphanumeric keys
if(Utils.GetAlphaKeyValue(out var alphaKey)
{
if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
{
_CreateSelectionGroup(alphaKey);
}
else
{
_ReselectGroup(alphaKey);
}
}
As it turns out it may just be an issue with my keyboard. Different keyboards handle key presses in different ways. Mine just refuses to tell Unity that control + (some other key) are being pressed together. Changed the code to respond to Shift + (some other key) and it works fine.

Can't get method to exit and skip turn properly on keypress

So I'm building this RPG turn based game for a class. I'm not trying to get my homework done for me, but this one problem is REALLY spinning me out, I've been at this for like 3 hours and I can't figure out how to fix this problem.
Essentially, I have an update method that controls whos turn it is (either the player or the computer)
public bool Update()
{
// clears console for a fresh start
Console.Clear();
//branch who's turn it is and add a line indicating so
if (playerTurn)
{
//print that it's the player's turn
Console.WriteLine("It's Your Turn to Attack!");
//run the player turn
PlayerTurn();
}
else
{
//print the rivals turn label
Console.WriteLine("It's the Enemy's Turn to Attack!");
}
//run the rivals turn
RivalsTurn();
{
}
//end game check
return EndTurn();
}
Then, I have the player turn method ---
void PlayerTurn()
{
// print instructions to select an attacker
Console.WriteLine($"Select which character will attack!\n(1) To Select {playerArray[0].Name()}\n(2) To Select {playerArray[1].Name()}\n(3) To Select {playerArray[2].Name()}\n(4) to view your teams current status\n(5) To Heal An Ally");
// Loop until an attacker is chosen
while (Attacker == null)
{
// use num 1-3 to select player party member that is the attacker
ConsoleKeyInfo k = Console.ReadKey();
if (k.KeyChar == '1')
{
Attacker = playerArray[0];
Console.WriteLine($"\nYou've chosen to attack with {Attacker.Name()}");
}
else if (k.KeyChar == '2')
{
Attacker = playerArray[1];
Console.WriteLine($"You've chosen to attack with {Attacker.Name()}");
}
else if (k.KeyChar == '3')
{
Attacker = playerArray[2];
Console.WriteLine($"You've chosen to attack with {Attacker.Name()}");
}
else if(k.KeyChar == '4')
{
PrintParties();
continue;
} else if (k.KeyChar == '5') {
HealAlly();
break;
}
// start a new line after user input
Console.WriteLine();
// Data Validation: make sure the key typed is a valid key
if (k.KeyChar < '1' || k.KeyChar > '5')
{
Console.WriteLine("Please Enter (1), (2), or (3) to select your attacking character. Press (4) to view your stats, and (5) to Heal an Ally");
continue;
}
else // convert from key input (1-3) to array element space (0-2)
curSelection = int.Parse(k.KeyChar.ToString()) - 1;
{
}
if (Attacker.GetHP() <= 0)
{
//check to make sure the selected character is alive HP > 0
//print the attackers name
//character's dead choose again
Console.WriteLine($"{Attacker.Name()} is dead! Choose someone who is alive!");
Console.WriteLine("Please Enter (1), (2), or (3) to select your attacking character. Press (4) to view your stats, and (5) to Heal an Ally");
Attacker = null;
}
else
{
Console.WriteLine($"{Attacker.Name()} will attack!");
Thread.Sleep(1000);
}
}
//print instructions for choosing a rival.
Console.WriteLine($"Select which enemy to attack!\n(1) To Attack {enemyArray[0].Name()}\n(2) To Attack {enemyArray[1].Name()}\n(3) To Attack {enemyArray[2].Name()}\n(4) To see the Enemies Current Stats.");
//loop until a defender is choosen
while (Defender == null)
{
// use 1-3 to select player party member that is the attacker
ConsoleKeyInfo k = Console.ReadKey();
if (k.KeyChar == '1')
{
Defender = enemyArray[0];
Console.WriteLine($"\nYou will attack {Defender.Name()}");
} else if(k.KeyChar == '2') {
Defender = enemyArray[1];
Console.WriteLine($"\nYou will attack {Defender.Name()}");
}
else if (k.KeyChar == '3')
{
Defender = enemyArray[2];
Console.WriteLine($"\nYou will attack {Defender.Name()}");
} else if (k.KeyChar == '4')
{
playerTurn = false;
PrintParties();
playerTurn = true;
}
{ }
//add a new line aft er the user input
Console.WriteLine();
// Data Validation: make sure the key typed is a valid key
if (k.KeyChar < '1' || k.KeyChar > '3')
{
// repeat instructions
Console.WriteLine("Select an enemy to attack by pressing either 1, 2, or 3.\n");
// loop again
continue;
}
else // convert from key input (1-3) to array element space (0-2)
curSelection = int.Parse(k.KeyChar.ToString()) - 1; //minus one to use as index
//check to make sure the selected character is alive HP > 0
//print the defenders name
//assign the selected character as the defender
if (Defender.GetHP() <= 0)
{
//print instructions again
Console.WriteLine($"{Defender.Name()} is already dead! Pick another enemy!");
Console.WriteLine("Select an enemy to attack by pressing either 1, 2, or 3.\n");
Defender = null;
} else
{
Console.WriteLine($"{Attacker.Name()} attacks {Defender.Name()}!");
Thread.Sleep(2000);
}
}
//damage the defender by the attacker's Strength value
Defender.ApplyDamage(Attacker.GetStrength());
//change color for rival team
Console.BackgroundColor = Attacker.GetTeamColor();
//print the new rival's health
Console.WriteLine($"{Defender.Name()} was hit by {Attacker.Name()}! {Defender.Name()} now only has {Defender.GetHP()} HP!");
EndTurn();
//change color back for normal
Console.BackgroundColor = ConsoleColor.Black;
//pause for 2 seconds
Thread.Sleep(2000);
//reset attacker/defender for next attack
Attacker = null;
Defender = null;
}
What I am trying to do is when the player selects "5" and runs the HealAlly() Method, I want the program to Take the users next input (who to heal), tell the player whether or not they can heal (if the character is either dead or full health) and then switch turns.
Instead, the code jumps back to the middle of the PlayerTurn method and tries to execute from there, but since the Attacker was never set (the user hit 5 so they didn't pick an Attacker) the game will crash.
Here is the HealAlly() method:
void HealAlly()
{
float healing = 3;
while (Healee == null)
{
Console.WriteLine("\nWhich Ally Do You Want To Heal?");
Console.WriteLine($"(1) for {playerArray[0].Name()}\n(2) for {playerArray[1].Name()}\n(3) for {playerArray[2].Name()}");
// use 1-3 to select player party member that is being healed
ConsoleKeyInfo k = Console.ReadKey();
if (k.KeyChar == '1')
{
Healee = playerArray[0];
Console.WriteLine($"\nYou will heal {Healee.Name()}");
Console.WriteLine("Healing...");
}
else if (k.KeyChar == '2')
{
Healee = playerArray[1];
Console.WriteLine($"\nYou will heal {Healee.Name()}");
Console.WriteLine("Healing...");
}
else if (k.KeyChar == '3')
{
Healee = playerArray[2];
Console.WriteLine($"\nYou will heal {Healee.Name()}");
Thread.Sleep(1000);
Console.WriteLine("Healing...");
}
else if (k.KeyChar > 3 || k.KeyChar < 1)
{
Console.WriteLine("Choose which character you want to heal!");
continue;
}
if (Healee.GetHP() >= 12)
{
Thread.Sleep(1000);
Console.WriteLine($"{Healee.Name()} has full health! You can't heal them!");
EndTurn();
}
else if (Healee.GetHP() <= 0)
{
Thread.Sleep(1000);
Console.WriteLine($"{Healee.Name()} is dead! You can't heal them!");
EndTurn();
}
else
{
Healee.ApplyHealing(healing);
Thread.Sleep(2000);
Console.WriteLine($"{Healee.Name()} has been healed, and now has {Healee.GetHP()} HP!");
EndTurn();
}
I thought that adding the call to EndTurn() at the end of the HealAlly() method would cause the turn to end, but instead all it does is give me the delay message and then shoot back to the middle of the PlayerTurn() method. I'm sure it's because there was no Attacker set, but that's not what I want, because I don't want the player to be able to attack after healing.
Here is the EndTurn() method if that will help
bool EndTurn()
{
//switch turns for next loop
playerTurn = !playerTurn;
// loop through players to see if they're alive and store in a variable counting if they're alive or not
bool playersAlive = true;
for (int i = 0; i < playerArray.Length; i++)
{
if (playerArray[0].GetHP() <= 0 && playerArray[1].GetHP() <= 0 && playerArray[2].GetHP() <= 0)
{
playersAlive = false;
}
}
// same for rivals
bool rivalsAlive = true;
for (int i = 0; i < enemyArray.Length; i++)
{
if (enemyArray[0].GetHP() <= 0 && enemyArray[1].GetHP() <= 0 && enemyArray[2].GetHP() <= 0)
{
rivalsAlive = false;
}
}
// if both have things alive start the next round, pause the game, and return true to continue playing
if (playersAlive && rivalsAlive)
{
Console.WriteLine("Next Round Starts in 5 seconds");
Thread.Sleep(5000);
return true;
} // if only the players have members alive you win
else if (playersAlive)
{
//clear screen for results
Console.Clear();
//print you've won and parties
Console.WriteLine("Congrats you win! Final Standings:");
playerTurn = false;
PrintParties();
playerTurn = true;
PrintParties();
Thread.Sleep(5000);
Console.WriteLine("Thanks For Playing!");
Console.WriteLine("Press Any Key to Play Again");
Console.ReadKey();
Console.Clear();
Init();
return false;
} // only rival members are alive
else
{
//clear screen for results
Console.Clear();
//Print you've lost and parties
Console.WriteLine("You Lose :( Final Standings:");
playerTurn = false;
PrintParties();
playerTurn = true;
PrintParties();
Thread.Sleep(5000);
Console.WriteLine("Thanks For Playing!");
Console.WriteLine("Press Any Key to Play Again");
Console.ReadKey();
Console.Clear();
Init();
return false;
}
}
This is bugging me, can anyone help?
void PlayerTurn()
{
// ...
while (Attacker == null)
{
// ...
if (k.KeyChar == '5') {
HealAlly();
break;
}
}
// ...code that depends on Attacker...
}
The break statement here only causes the flow to break out of the while loop and continue with the code the depends on Attacker. If you want to leave the PlayerTurn() method altogether, replace the break; with a return;

MessageBox.Show being displayed too fast

I'm trying to create my own version of "Fleet battle", but I'm stuck at 99.9%. And here is why. After a ship was destroyed, its color should change to red and then a MessageBox "You won" or "You lost" should come. So now, if the AI destroys my last ship, everything is going fine, all the ships are becoming red one by one and then comes this "You lost" message. But in the opposite case - if I win, the AI ships are becoming red, but the last cell of the last ship becomes red after I click "OK" at the MessageBox "You won". I'm using the same algorithm in both cases and wondering what I'm doing wrong with it. Here is the AI part:
// AI hits a ship
if ((arrayOccupiedCellsBattlefield1[rowIndex, columnIndex] == "1") || (arrayOccupiedCellsBattlefield1[rowIndex, columnIndex] == "2") ||
(arrayOccupiedCellsBattlefield1[rowIndex, columnIndex] == "3") || (arrayOccupiedCellsBattlefield1[rowIndex, columnIndex] == "4"))
{
AIHuntingAShip = true;
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = " X";
arrayShipsHitbyAIMap[rowIndex, columnIndex] = " X"; // AI marks the burning enemy ships
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
arrayAITakenShots[transformCoordinatesToCellNumber(rowIndex, columnIndex)] = transformCoordinatesToCellNumber(rowIndex, columnIndex);
storeRowIndex = rowIndex;
storeColumnIndex = columnIndex;
arrayShipsHitbyAIXY[detectedShipLength] = transformCoordinatesToCellNumber(rowIndex, columnIndex);
detectedShipLength++;
if (detectedShipLength == int.Parse(arrayOccupiedCellsBattlefield1[rowIndex, columnIndex])) // AI destroys a ship (the array stores the length of the ship in each of the ship's cells)
{
for (int i = 0; i < detectedShipLength; i++) // placing " o"s around the destroyed ship
{
restrictArea(int.Parse(tranformCellNumberToCoordinates(arrayShipsHitbyAIXY[i])[0].ToString()),
int.Parse(tranformCellNumberToCoordinates(arrayShipsHitbyAIXY[i])[1].ToString()),
dataGridView1,
arrayShipsHitbyAIMap,
arrayAITakenShots);
}
detectedShipLength = 0;
AIHuntingAShip = false;
playerShips--;
textBox6.Text = playerShips.ToString();
if (playerShips == 0)
{
MessageBox.Show("You lost!", "Try it again!", MessageBoxButtons.OK);
dataGridView2.Enabled = false;
}
}
and here is my part:
// player hits a ship
if ((arrayOccupiedCellsBattlefield2[e.RowIndex, e.ColumnIndex] != null) && (arrayOccupiedCellsBattlefield2[e.RowIndex, e.ColumnIndex] != " ."))
{
dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = " X";
arrayShipsHitbyPlayerMap[e.RowIndex, e.ColumnIndex] = " X";
dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
arrayPlayerTakenShots[transformCoordinatesToCellNumber(e.RowIndex, e.ColumnIndex)] = transformCoordinatesToCellNumber(e.RowIndex, e.ColumnIndex);
int shipIdent = int.Parse(arrayOccupiedCellsBattlefield2[e.RowIndex, e.ColumnIndex][0].ToString()); // ship ID
int playersShipLength = int.Parse(arrayOccupiedCellsBattlefield2[e.RowIndex, e.ColumnIndex][1].ToString()); // ship length
arrayForPlayersShipsXY[shipIdent] += e.RowIndex.ToString() + e.ColumnIndex.ToString() + ";"; // save the coordinates of this particular ship
arrayForPlayerCounters[shipIdent]++; // increase this particular cell counter basing on the "shipIdent"
if (arrayForPlayerCounters[shipIdent] == playersShipLength) // ship destroyed, so mark the area with " o"
{
for (int i = 0; i < playersShipLength; i++)
{
string xy = extractXYForPlayersShip(arrayForPlayersShipsXY[shipIdent])[i].ToString();
int x = int.Parse(xy.ToString()[0].ToString());
int y = int.Parse(xy.ToString()[1].ToString());
restrictArea(x, y, dataGridView2, arrayShipsHitbyPlayerMap, arrayPlayerTakenShots);
}
AIShips--;
textBox7.Text = AIShips.ToString();
}
if (AIShips == 0)
{
dataGridView2.Enabled = false;
MessageBox.Show("You won!", "Congrats!", MessageBoxButtons.OK);
}
}
Does anybody have an idea? Thank you for your help.
The algorithms might seem the same, but they are not. There is a lot of repeated code, and it is hard to make sure they both do the "same thing". Try and break out parts of this code into smaller methods so you can reuse them.
Without seeing everything, I think this is the issue:
AI:
if (...) //Ship is destroyed
{
// ...
if (ships == 0)
{
MessageBox.Show(...);
}
}
Player
if (...) //ship is destroyed
{
// ...
}
if (ships == 0)
{
MessageBox.Show(...);
}
MessageBox.Show is called inside vs. outside the "ship destroyed" if block.
This question is not exactly the best for StackOverflow because the code is fairly messy and not simplified. Check out this link for how to ask good questions. But keep at it!
As you said both algorithms are equal but windows refresh your form after you hit the 'OK' button.
So I suggest refresh it yourself before displaying msgbox.
if (AIShips == 0)
{
dataGridView2.Refresh(); // <-------- +
dataGridView2.Enabled = false;
MessageBox.Show("You won!", "Congrats!", MessageBoxButtons.OK);
}
Your code is a bit messy I'm not sure about the grid view name, If your problem is about the first one, try this: dataGridView1.Refresh();

Guessing game gets stuck in infinite loop

am trying to make a hangman game where it picks a random word from a text file of words. It then displays the word in asterisks and asks the user to guess each letter of the word if they guess right it uncovers that letter.They keep playing until they guess all the letters in the word.After the word is guessed it will display the number of misses and ask if they want to play again.
The Problem I am having is when the word is guessed correctly it just keeps asking for a letter even if the word is uncovered. I am not sure how to fix this. I would like to do this without using linq if possible.
any help would be appericated
static void Main(string[] args)
{
char[] guessed = new char[26];
char guess = ' ';
char playAgain= ' ';
bool validLetterInput = false;
bool validAnswer = false;
int amountMissed = 0, index = 0;
do
{
// initilization of word and testword so that we could generate a testword with the same length as original
char[] word = RandomLine().Trim().ToCharArray();
char[] testword = new string('*', word.Length).ToCharArray();
char[] copy = word;
Console.WriteLine(testword);
Console.WriteLine("I have picked a random word on animals");
Console.WriteLine("Your task is to guess the correct word");
//Check if the 2 arrays are equal
while (testword != word)
{
while (!validLetterInput)
{
try
{
Console.Write("Please enter a letter to guess: ");
guess = char.Parse(Console.ReadLine().ToLower());
//Checks if guess is letter or not
if (((guess >= 'A' && guess <= 'Z') || (guess >= 'a' && guess <= 'z')))
{
validLetterInput = true;
}
else
{
Console.WriteLine("Invalid Input");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validLetterInput = false;
bool right = false;
for (int j = 0; j < copy.Length; j++)
{
if (copy[j] == guess)
{
Console.WriteLine("Your guess is correct.");
testword[j] = guess;
guessed[index] = guess;
index++;
right = true;
}
}
if (right != true)
{
Console.WriteLine("Your guess is incorrect.");
amountMissed++;
}
else
{
right = false;
}
Console.WriteLine(testword);
}
Console.WriteLine($"The word is {string.Join("",testword)}. You missed {amountMissed} times.");
while (!validAnswer)
{
try
{
Console.WriteLine("Do you want to guess another word? Enter y or n: ");
playAgain = char.Parse(Console.ReadLine());
if(playAgain == 'y' || playAgain == 'Y' || playAgain == 'n' || playAgain == 'N')
{
validAnswer = true;
}
else
{
Console.WriteLine("Invalid input try again");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
validAnswer = false;
} while (playAgain == 'y' || playAgain == 'Y');
Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
}
public static string RandomLine()
{
// store text file in an array and return a random value
string[] lines = File.ReadAllLines("E:\\Amimals1.csv");
Random rand = new Random();
return lines[rand.Next(lines.Length)].ToLower();
}
}
There are various ways to compare two arrays / lists. Simple method i see for character arrays / lists is to convert them to strings and then compare.
Array Comparison thread on stackoverflow
testword.ToString() != word.ToString()
In regards to what Flydog57, use this link to learn how to debug code:
Compare the arrays with "SequenceEqual" instead of !=. This way you will need to change your while statement to:
while (!testword.SequenceEqual(word))
This is noted by Quartermeister and further explained by ohn Buchanan in the question "Easiest way to compare arrays in C#". link is here:
Easiest way to compare arrays in C#
Otherwise great program!
Note when you are trying debugging, a simple thing I like to put in there is a write of what response I want to see initially if I cannot figure out through debug. you can always remove the line later. I put this at the end of the while statement.
Console.WriteLine(testword.SequenceEqual(word));

Game of craps looping more than once after quitting the game

I am trying to make a program to play a game of craps where the user enters a bet amount, then they roll 2 six sided dice. If the sum of the dice s 2,3 or 12 they lose. 7 or 11 they win. if any other number is rolled the player keeps rolling until they get the point number to win or 7 to lose. However for some reason if I select n to not play again it still loops the game a second time before quitting. I am not sure why
any help would be appreciated.
static void processCraps()
{
string gameStatus = null;
double betAmount =0;
double netWinning = 0;
int point;
do
{
try
{
Console.WriteLine("Enter the amount to bet");
betAmount = double.Parse(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Invaid input try again");
}
var diceRoll = RollDice();
if (diceRoll == 2 || diceRoll == 3 || diceRoll == 12)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (diceRoll == 7 || diceRoll == 11)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
else if (diceRoll != 2 || diceRoll != 3 || diceRoll != 12 || diceRoll != 7 || diceRoll != 11)
{
point = diceRoll;
Console.WriteLine($"Point is {point}");
for (int rollCount = 0; rollCount >= point; rollCount++)
{
var roll = RollDice();
if (roll == 7)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (roll == point)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
}
}
try
{
Console.WriteLine("Do you want to play again (y/n)");
gameStatus = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("answer must be a letter");
}
} while (gameStatus != "n") ;
Console.WriteLine($"Your net winning is {netWinning}");
}
You read input twice.
You may want to split the logic into two loops. 1. Read bet amount. 2. Play game.
do
{
Console.WriteLine("Enter the amount to bet, or 'q' to quit:");
var betStr = Console.ReadLine();
if( betStr == "q") return;
double.TryParse(betStr, out betAmount);
} while (betAmount != 0);
do
{
//Play
Console.WriteLine("Do you want to play again (n = quit)?");
gameStatus = Console.ReadLine();
} while (gameStatus != "n");

Categories