C# DO While loop - Hangman - c#

I'm in the process of learning to code using C#. I have not been able to figure out why my loop won't end after 10 entries into my Hangman program, although the program works if set at a lesser number such as 6. I'm using a do while loop, and, when set to 10, I keep getting what seems to be an infinite loop, as it just keeps repeating and not ending as expected. I have no compiler errors. This is an assignment. Any help is appreciated. Here is the code I have wrote:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace hangman_projectW4
{
class Program
{
static void Main(string[] args)
{
//variable list
char letter0 = 'k';
char letter1 = 'i';
char letter2 = 'd';
char letter3 = 'd';
char letter4 = 'e';
char letter5 = 'r';
char letter;
int score = 0;
string user = "";
//inputs inputs
Console.ForegroundColor = ConsoleColor.Green;
user = Console.ReadLine();
Console.WriteLine("Hi! Welcome to Hangman.");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Player, please enter a letter at prompt.");
Console.Write("_________________________________________________________________");
user = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Green;
do
{
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
user = Console.ReadLine();
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
user = Console.ReadLine();
if (letter == letter0 || letter == letter1 || letter == letter2 || letter == letter3 || letter == letter4 || letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
}while (score <= 10);
//outputs
user = Console.ReadLine();
user = Console.ReadLine();
Console.Write("_________________________________________________________________");
user = Console.ReadLine();
Console.Write("Guessed Incorrectly: " + score);
Console.ReadLine();
Console.ReadLine();
Console.Write("Thank you for playing Hangman.");
Console.ReadLine();
}
}
}
Also, if there is a better way to write the code so that I'm not repeating the if else ten times...pointers would be great! Thanks.

If you try hard enough it will end. Once you've reached your score of 11 or more, your code may just continue and continue asking for another try. Stop copying code. Be smarter and minimize your code! Your loop repeats the same thing over and over again without even checking whether you have already reached more than 10 points (score).
Shorten your loop to something like this:
do
{
Console.WriteLine("Please enter a letter: ");
letter = char.Parse(Console.ReadLine());
if (letter == letter0 ||
letter == letter1 ||
letter == letter2 ||
letter == letter3 ||
letter == letter4 ||
letter == letter5)
{
Console.WriteLine("You guessed correctly!");
}
else
{
Console.WriteLine("Incorrect. Try Again.");
score++;
}
} while (score <= 10);
Next step is to add all your letters to a collection or list and shorten your if statement. ;-)

Related

losing streak loop in hangman C#

I'm trying to make a Hangman game in C#. It has a 5 tries limit, then the user will get a "you lose" message. If the user gets a letter wrong, it was supposed to get them a "wrong letter -- try again"
class Program
{
static void Main(string[] args)
{
string word;
int correct = 0;
int errors = 0;
Console.WriteLine("Enter a word");
word = Console.ReadLine();
char[] letters = word.ToCharArray();
char[] hanged = word.ToCharArray();
char digits;
for (int i = 0; i < word.Length; i++)
{
if (letters[i] == ' ')
{
hanged[i] = ' ';
}
else
{
hanged[i] = '_';
}
}
Console.Clear();
do
{
Console.Write(" ________\n" +
"| |\n" +
"| |\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n\n");
Console.SetCursorPosition(2, Console.CursorTop - 2);
for (int i = 0; i < word.Length; i++)
{
Console.Write(hanged[i] + " ");
}
Console.WriteLine("\n\n\nEnter a letter");
digits = Convert.ToChar(Console.Read());
for (int i = 0; i < word.Length; i++)
{
if (digits == hanged[i])
{
Console.WriteLine("\nletter already in there -- press enter");
Console.ReadKey();
}
else if (digits == letters[i])
{
hanged[i] = digits;
correct++;
}
else if (digits != letters[i])
{
Console.WriteLine("\nwrong letter -- try again");
errors++;
Console.ReadKey();
}
if (errors == 5)
{
Console.WriteLine("\nYou lose");
Console.ReadKey();
break;
} else if (correct == word.Length)
{
Console.WriteLine("\nYou win");
Console.ReadKey();
break;
}
}
Console.Clear();
} while (correct < word.Length);
Console.ReadKey();
}
}
However, my program is stuck in a loop when counting the losses. The code thats messing it up is this section
else if (digits != letters[i])
{
Console.WriteLine("\nwrong letter -- try again");
errors++;
Console.ReadKey();
}
When I delete this section and run the code, in case of a wrong letter it just runs over it infinitely and the player will get infinite chances to try when they were supposed to have only 5 chances. How can I fix this?
The problem is that the 2nd loop for (int i = 0; i < word.Length; i++) that is responsible for finding a letter should not perform other logic in there. E.g., if the user types a letter matching the third position, then this will count 2 errors before counting one correct letter and also do extra console input and output.
I suggest using Array.IndexOf to get the index of a letter. This returns -1 if it is not found. Also, I found that the different kinds of Console.ReadXY can interfere with each other. E.g. calling Console.Read() and pressing a letter plus Enter makes the next Console.ReadLine() just return without waiting for user input.
My attempt (content of static void Main(string[] args)):
string word;
int correct = 0;
int errors = 0;
Console.WriteLine("Enter a word");
word = Console.ReadLine();
char[] letters = word.ToCharArray();
char[] hanged = word.ToCharArray();
char digits;
for (int i = 0; i < word.Length; i++) {
if (letters[i] == ' ') {
hanged[i] = ' ';
} else {
hanged[i] = '_';
}
}
Console.Clear();
do {
Console.Write(" ________\n" +
"| |\n" +
"| |\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n" +
"|\n\n");
Console.SetCursorPosition(2, Console.CursorTop - 2);
for (int i = 0; i < word.Length; i++) {
Console.Write(hanged[i] + " ");
}
Console.Write("\n\n\nEnter a letter: ");
ConsoleKeyInfo key = Console.ReadKey();
digits = key.KeyChar;
int hangedIndex = Array.IndexOf(hanged, digits);
int lettersIndex = Array.IndexOf(letters, digits);
if (hangedIndex >= 0) {
Console.WriteLine("\nletter already in there -- press enter");
Console.ReadLine();
} else if (lettersIndex >= 0) {
hanged[lettersIndex] = digits;
correct++;
} else {
Console.Write("\nwrong letter -- try again (press enter) ");
Console.ReadLine();
errors++;
}
if (errors == 5) {
Console.WriteLine("\nYou lose");
break;
} else if (correct == word.Length) {
Console.WriteLine("\nYou win");
break;
}
Console.Clear();
} while (correct < word.Length);
Console.ReadKey();

How can I prevent players from overwriting one another in tic tac toe?

I have tried to program a tic tac toe game in C# (with the help of tutorials). Overall it seems to be working fine (although the amount of code seems very excessive so sorry for that) but there appears to be one problem: Say, player 1 decides on row 1, column 1 and player 2 does the same afterwards, then player 2 overwrites player 1.
So far, this is the code:
namespace TicTacToe
{
class Program
{
static int turns = 1;
static char[] board =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
static char playerSignature = 'X';
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
DrawBoard(board);
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
DrawBoard(board);
}
}
private static void PlayAgain()
{
Console.WriteLine("Play again? y/n");
string playagain = Console.ReadLine();
switch (playagain)
{
case "n":
Console.WriteLine("Thanks for playing!");
Console.Clear();
break;
case "y":
Console.Clear();
ResetBoard();
break;
}
}
private static void DrawBoard(char[] board)
{
string row = "| {0} | {1} | {2} |";
string sep = "|___|___|___|";
Console.WriteLine(" ___ ___ ___ ");
Console.WriteLine(row, board[0], board[1], board[2]);
Console.WriteLine(sep);
Console.WriteLine(row, board[3], board[4], board[5]);
Console.WriteLine(sep);
Console.WriteLine(row, board[6], board[7], board[8]);
Console.WriteLine(sep);
}
private static void ResetBoard()
{
char[] newBoard =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
board = newBoard;
DrawBoard(board);
turns = 0;
}
private static void Draw()
{
Console.WriteLine("It's a draw!\n" +
"Press any key to play again.");
Console.ReadKey();
ResetBoard();
//DrawBoard(board);
}
public static void Main()
{
Introduction();
while(true)
{
bool isrow = false;
bool iscol = false;
int row = 0;
int col = 0;
while (!isrow)
{
Console.WriteLine("Choose a row (1-3): ");
try
{
row = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (row == 1 || row == 2 || row == 3)
{
isrow = true;
}
else
{
Console.WriteLine("\nInvalid row!");
}
}
while (!iscol)
{
Console.WriteLine("Choose a column (1-3): ");
try
{
col = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (col == 1 || col == 2 || col == 3)
{
iscol = true;
}
else
{
Console.WriteLine("\nInvalid column!");
}
}
int[] input = { row, col };
int player = 2;
if (player == 2)
{
player = 1;
XorO(player, input);
}
else
{
player = 2;
XorO(player, input);
}
DrawBoard(board);
turns++;
CheckForDiagonal();
CheckForVertical();
CheckForHorizontal();
if (turns == 10 && (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature && board[3] == playerSignature &&
board[4] == playerSignature && board[5] == playerSignature && board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature))
{
Draw();
}
}
}
private static void CheckForVertical()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[3] == playerSignature && board[6] == playerSignature ||
board[1] == playerSignature && board[4] == playerSignature && board[7] == playerSignature ||
board[2] == playerSignature && board[5] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForHorizontal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature ||
board[3] == playerSignature && board[4] == playerSignature && board[5] == playerSignature ||
board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForDiagonal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[6] == playerSignature && board[4] == playerSignature && board[2] == playerSignature ||
board[0] == playerSignature && board[4] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void XorO(int player, int[] input)
{
if (player == 1)
{
playerSignature = 'X';
}
else if (player == 2)
{
playerSignature = 'O';
}
if (input[0] == 1 && input[1] == 1)
{
board[0] = playerSignature;
}
else if (input[0] == 1 && input[1] == 2)
{
board[1] = playerSignature;
}
else if (input[0] == 1 && input[1] == 3)
{
board[2] = playerSignature;
}
else if (input[0] == 2 && input[1] == 1)
{
board[3] = playerSignature;
}
else if (input[0] == 2 && input[1] == 2)
{
board[4] = playerSignature;
}
else if (input[0] == 2 && input[1] == 3)
{
board[5] = playerSignature;
}
else if (input[0] == 3 && input[1] == 1)
{
board[6] = playerSignature;
}
else if (input[0] == 3 && input[1] == 2)
{
board[7] = playerSignature;
}
else if (input[0] == 3 && input[1] == 3)
{
board[8] = playerSignature;
}
}
}
}
I have tried adding something like this: if(input[0] == 1 && input[1] == 1 && (board[0] != 'X' && board[0] != 'O') in the XorO method. But that didn't solve my issue.
Does somebody maybe have some suggestions as to how I can fix that?
You are doing way too much work in some of those methods...
For instance, here's a shorter XorO() method that also makes sure the spot is BLANK before assigning it to a player:
private static void XorO(int player, int[] input)
{
playerSignature = (player == 1) ? 'X' : 'O';
int index = ((input[0] - 1) * 3) + (input[1] - 1);
if (board[index] == ' ') {
board[index] = playerSignature;
}
else {
// ... output an error message? ...
Console.WriteLine("That spot is already taken!");
}
}
Could you maybe explain why you set index the way you did?
Sure! Here is the layout of the board, 3 rows with 3 cols, and the corresponding Index value of each position:
1 2 3
1 0 1 2
2 3 4 5
3 6 7 8
Note that because there are 3 columns, the value of the Index as we move down from one row to the next in the same column goes up by 3. Also note that the starting values in column 1 for each row are 0, 3, and 6, which are all multiples of 3. So to convert your row value from 1, 2, and 3 into 0, 3, and 6, we first subtract 1 from the row value and then multiply it by 3.
Next, each column simply increments by one as you move to the right. Thus we subtract one from the column value and add that to the computed beginning row value. This maps the (row, col) to the indices 0 through 8, seen here as a single dimension array:
1,1 | 1,2 | 1,3 | 2,1 | 2,2 | 2,3 | 3,1 | 3,2 | 3,3
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
But how was am I supposed to think of something like that? I would
never have thought of that.
It's a fairly common setup to represent a 2D structure in a single dimensional array, known as a compact layout. The math involved to convert a row/column to the equivalent index value or vice-versa is just something that all programmers learn at some point.
Lot of refactoring here, look closely:
class Program
{
static int turns;
static char[] board;
static bool playerOne;
public static void Main(string[] args)
{
Introduction();
bool playAgain = true;
while (playAgain)
{
ResetBoard();
bool gameOver = false;
while (!gameOver)
{
DrawBoard(board);
int row = getNumber(true);
int col = getNumber(false);
if (XorO(row, col)) {
turns++; // valid move was made
String msg = "";
String playerNumber = playerOne ? "1" : "2";
if (CheckForDiagonal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a diagonal win!";
}
else if (CheckForVertical())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a vertical win!";
}
else if (CheckForHorizontal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a horizontal win!";
}
else if (turns == 9)
{
gameOver = true;
msg = "It's a draw!";
}
else
{
playerOne = !playerOne;
}
if (gameOver)
{
DrawBoard(board); // show last move
Console.WriteLine(msg);
}
}
}
Console.WriteLine("Play again (y/n)?");
string response = Console.ReadLine().ToLower();
playAgain = (response == "y");
}
}
private static void ResetBoard()
{
turns = 0;
playerOne = true;
board = new char[] {
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
}
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game.\nEnter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine().ToLower();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
}
}
private static void DrawBoard(char[] board)
{
Console.WriteLine(" ___ ___ ___ ");
for(int r=1; r<=3;r++)
{
Console.Write("|");
for(int c=1; c<=3; c++)
{
Console.Write(" {0} |", board[(r - 1) * 3 + (c - 1)]);
}
Console.WriteLine();
Console.WriteLine("|___|___|___|");
}
}
private static int getNumber(bool row)
{
int value = -1;
string description = row ? "row" : "column";
bool isValid = false;
while (!isValid)
{
Console.Write("Player '" + (playerOne ? "X" : "O") + "', choose a " + description + " (1-3): ");
if (int.TryParse(Console.ReadLine(), out value))
{
if (value >= 1 && value <= 3)
{
isValid = true;
}
else
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
}
else
{
Console.WriteLine("\nInvalid " + description + "!");
}
}
return value;
}
private static bool XorO(int row, int col)
{
int index = ((row - 1) * 3) + (col - 1);
if (board[index] == ' ')
{
board[index] = playerOne ? 'X' : 'O';
return true;
}
else
{
Console.WriteLine("That spot is already taken!");
return false;
}
}
private static bool CheckForDiagonal()
{
return ((board[6] != ' ' && board[4] == board[6] && board[2] == board[6]) ||
(board[0] != ' ' && board[4] == board[0] && board[8] == board[0]));
}
private static bool CheckForVertical()
{
for(int c=0; c<=2; c++)
{
if (board[c] != ' ' && board[c+3] == board[c] && board[c+6] == board[c])
{
return true;
}
}
return false;
}
private static bool CheckForHorizontal()
{
for (int r=0; r<=6; r=r+3)
{
if (board[r] != ' ' && board[r + 1] == board[r] && board[r + 2] == board[r])
{
return true;
}
}
return false;
}
}

Backspace won't function correctly

I am trying to create a screen where the user would be able to write down their name with StringBuilder. The problems I have is with the functionality of backspace. I can remove all letters except the first letter that was pressed. Also, it seems like I can press whatever character and it would be submitted.
ConsoleKeyInfo cki = new ConsoleKeyInfo();
bool enterPressed = false;
StringBuilder name = new StringBuilder();
int temp = 61;
do
{
Console.SetCursorPosition(temp, 14);
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter && name.Length > 0 && name.Length < 12)
{
enterPressed = true;
Console.SetCursorPosition(61, 18);
Console.Write(name);
}
else if ("qwertyuiopasdfghjklzxcvbnm".Contains(cki.KeyChar) && name.Length < 12)
{
name.Append(cki.KeyChar);
Console.Write(cki.KeyChar);
temp += 1;
}
else if(cki.Key == ConsoleKey.Backspace && name.Length > 0)
{
name.Remove(name.Length-1, 1);
Console.Write("\b \b");
}
} while (name.Length > 0 && !enterPressed);
You forgot to do temp--;
This code snippet should solve your problem
name.Remove(name.Length - 1, 1);
temp--;
Console.Write("\b \b");
You can try below code
console.Writeline("Enter Your Name");
string name= console.Readline();
and below is something for you to update if you don't want to use above solution.
if(cki.Key == ConsoleKey.Backspace && name.Length >= 0)
{
if (name.Length == 0)
{
name.Remove(0, 0);
}
else
{
name.Remove(name.Length - 1, 1);
}
temp--;
Console.Write(" ");
}

C# use of unassigned variable?

So basically I have a class for a TicTacToe game and a derived class just to practice using inheritance. The class has several methods and all should work perfectly fine but in the main function, when I finally make three objects of the derived class I get three errors "use of unassigned local variable 'boardOne'" "use of unassigned local variable 'boardTwo'" and "use of unassigned local variable 'boardThree'". I do not understand why this is, they are objects, not variables.
public class TicTacToe
{
protected char[] boardCells = new char[9];
public int boardSpacesUsed;
public TicTacToe() //constructor
{
boardCells[0] = '1';
boardCells[1] = '2';
boardCells[2] = '3';
boardCells[3] = '4';
boardCells[4] = '5';
boardCells[5] = '6';
boardCells[6] = '7';
boardCells[7] = '8';
boardCells[8] = '9';
boardCells[9] = '\0';
int boardSpacesUsed = 0;
}
public void playerOneMove()
{
bool space = false;
char cell = '\0';
while (space == false)
{
Console.WriteLine("Please enter cell number you wish to mark: ");
cell = Convert.ToChar(Console.ReadLine());
switch (cell)
{
case '1':
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
Console.WriteLine("Illegal Move");
}
else
{
boardCells[0] = 'X';
space = true;
}
break;
case '2':
if (boardCells[1] == 'X' || boardCells[1] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[1] = 'X';
space = true;
}
break;
case '3':
if (boardCells[2] == 'X' || boardCells[2] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[2] = 'X';
space = true;
}
break;
case '4':
if (boardCells[3] == 'X' || boardCells[3] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[3] = 'X';
space = true;
}
break;
case '5':
if (boardCells[4] == 'X' || boardCells[4] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[4] = 'X';
space = true;
}
break;
case '6':
if (boardCells[5] == 'X' || boardCells[5] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[5] = 'X';
space = true;
}
break;
case '7':
if (boardCells[6] == 'X' || boardCells[6] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[6] = 'X';
space = true;
}
break;
case '8':
if (boardCells[7] == 'X' || boardCells[7] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[7] = 'X';
space = true;
}
break;
case '9':
if (boardCells[8] == 'X' || boardCells[8] == 'O')
Console.WriteLine("Illegal Move");
else
{
boardCells[8] = 'X';
space = true;
}
break;
default:
Console.WriteLine("Cell Does NOT Exist!");
break;
}// end of switch statement
}//end of while loop
boardSpacesUsed++;
}// end of playerOneMove();
public void CPUMove() //method marks cell for CPU
{
int iCell = 0;
bool space = false;
while (space == false)
{
Random rand = new Random();
iCell = rand.Next(1, 9);
switch (iCell) //switch statement to mark the cell
{
case 1:
if (boardCells[0] == 'X' || boardCells[0] == 'O')
{
space = false;
}
else
{
boardCells[0] = 'O';
space = true;
}
break;
case 2:
if (boardCells[1] == 'X' || boardCells[1] == 'O')
space = false;
else
{
boardCells[1] = 'O';
space = true;
}
break;
case 3:
if (boardCells[2] == 'X' || boardCells[2] == 'O')
space = false;
else
{
boardCells[2] = 'O';
space = true;
}
break;
case 4:
if (boardCells[3] == 'X' || boardCells[3] == 'O')
space = false;
else
{
boardCells[3] = 'O';
space = true;
}
break;
case 5:
if (boardCells[4] == 'X' || boardCells[4] == 'O')
space = false;
else
{
boardCells[4] = 'O';
space = true;
}
break;
case 6:
if (boardCells[5] == 'X' || boardCells[5] == 'O')
space = false;
else
{
boardCells[5] = 'O';
space = true;
}
break;
case 7:
if (boardCells[6] == 'X' || boardCells[6] == 'O')
space = false;
else
{
boardCells[6] = 'O';
space = true;
}
break;
case 8:
if (boardCells[7] == 'X' || boardCells[7] == 'O')
space = false;
else
{
boardCells[7] = 'O';
space = true;
}
break;
case 9:
if (boardCells[8] == 'X' || boardCells[8] == 'O')
space = false;
else
{
boardCells[8] = 'O';
space = true;
}
break;
}
}
boardSpacesUsed++;
}
public void getBoardCells()
{
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[0] + " | " + boardCells[1] + " | " + boardCells[2]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[3] + " | " + boardCells[4] + " | " + boardCells[5]);
Console.WriteLine("__" + "_" + "__|__" + "_" + "__|__" + "_");
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
Console.WriteLine(" " + boardCells[6] + " | " + boardCells[7] + " | " + boardCells[8]);
Console.WriteLine(" " + " " + " | " + " " + " | " + " ");
}
public bool playerOneWinCheck(ref int score)
{
bool check = false;
if (boardCells[0] == 'X' && boardCells[1] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (boardCells[3] == 'X' && boardCells[4] == 'X' && boardCells[5] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[7] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[3] == 'X' && boardCells[6] == 'X')
{
check = true;
score++;
}
if (boardCells[1] == 'X' && boardCells[4] == 'X' && boardCells[7] == 'X')
{
check = true;
score++;
}
if (boardCells[2] == 'X' && boardCells[5] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[0] == 'X' && boardCells[4] == 'X' && boardCells[8] == 'X')
{
check = true;
score++;
}
if (boardCells[6] == 'X' && boardCells[4] == 'X' && boardCells[2] == 'X')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
public bool CPUWinCheck(ref int score) //Method to check to see if CPU won INCRAMENTS SCORE UP ONE IF ANYTHING HOLDS TRUE
{
bool check = false;
if (boardCells[0] == 'O' && boardCells[1] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (boardCells[3] == 'O' && boardCells[4] == 'O' && boardCells[5] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[7] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[3] == 'O' && boardCells[6] == 'O')
{
check = true;
score++;
}
if (boardCells[1] == 'O' && boardCells[4] == 'O' && boardCells[7] == 'O')
{
check = true;
score++;
}
if (boardCells[2] == 'O' && boardCells[5] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[0] == 'O' && boardCells[4] == 'O' && boardCells[8] == 'O')
{
check = true;
score++;
}
if (boardCells[6] == 'O' && boardCells[4] == 'O' && boardCells[2] == 'O')
{
check = true;
score++;
}
if (check == true)
return true;
else
return false;
}
~TicTacToe()
{
for (int c = 0; c <= 10; c++)
{
boardCells[c] = '\0';
}
boardSpacesUsed = 0;
}
}
public class ThreeD : TicTacToe
{
public void threeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check to see ThreeD wins
{
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[0] == 'X' && boardThree.boardCells[0] == 'X')
{
score++;
Console.WriteLine("did it make it");
}
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[2] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[4] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[4] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[6] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[8] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[1] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[3] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[5] == 'X')
score++;
if (boardOne.boardCells[5] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[3] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[7] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[3] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[1] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[7] == 'X')
score++;
if (boardOne.boardCells[7] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[1] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[5] == 'X' && boardThree.boardCells[2] == 'X')
score++;
if (boardOne.boardCells[0] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[8] == 'X')
score++;
if (boardOne.boardCells[8] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[0] == 'X')
score++;
if (boardOne.boardCells[2] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[6] == 'X')
score++;
if (boardOne.boardCells[6] == 'X' && boardTwo.boardCells[4] == 'X' && boardThree.boardCells[2] == 'X')
score++;
}
public void CPUThreeDWinCheck(ThreeD boardOne, ThreeD boardTwo, ThreeD boardThree, ref int score) //new function to check CPU ThreeD wins
{
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[0] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[2] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[4] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[4] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[6] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[8] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[1] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[3] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[5] == 'O')
score++;
if (boardOne.boardCells[5] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[3] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[7] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[3] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[1] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[7] == 'O')
score++;
if (boardOne.boardCells[7] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[1] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[5] == 'O' && boardThree.boardCells[2] == 'O')
score++;
if (boardOne.boardCells[0] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[8] == 'O')
score++;
if (boardOne.boardCells[8] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[0] == 'O')
score++;
if (boardOne.boardCells[2] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[6] == 'O')
score++;
if (boardOne.boardCells[6] == 'O' && boardTwo.boardCells[4] == 'O' && boardThree.boardCells[2] == 'O')
score++;
}
~ThreeD()
{
for (int c = 0; c < 10; c++)
{
boardCells[c] = '\0';
}
}
}
static void Main(string[] args)
{
ThreeD boardOne; //1st of three objects for first board
ThreeD boardTwo; //2nd
ThreeD boardThree; //3rd
int boardSelection = 0; //picks witch object to mark in
int counter = 0; //counter for while loop
int playerOneScore = 0; //score for user
int CPUScore = 0; //score for cpu
int CPUBoardSelection = 0;
Random rand = new Random();
int randomNum = rand.Next(1, 2);
if (randomNum == 1) // if randomNum = 1, user goes first
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells();
boardTwo.getBoardCells();
boardThree.getBoardCells();
Console.WriteLine("Choose which board you wish to mark in. (1 - 3)"); //promts you to pick board
bool board = false;
Yes, the compiler is right: you're trying to use unassigned variables:
static void Main(string[] args)
{
// It's just a declaration; no value assigned to boardOne; boardOne contains trash
ThreeD boardOne;
// It's just a declaration; no value assigned to boardTwo; boardTwo contains trash
ThreeD boardTwo;
// It's just a declaration; no value assigned to boardThree; boardThree contains trash
ThreeD boardThree;
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- And here you're trying to access the trash
It should be something like that:
static void Main(string[] args)
{
// boardOne is declared and assigned
ThreeD boardOne = new ThreeD();
// boardTwo is declared and assigned
ThreeD boardTwo = new ThreeD();
// boardThree is declared and assigned
ThreeD boardThree = new ThreeD();
....
if (randomNum == 1)
{
Console.WriteLine("You first");
while (true)
{
boardOne.getBoardCells(); // <- Quite OK
Firstly, boardOne, boardTwo and boardThree are variables, in this case are local variables scoped to the Main() method. Like any other variable, they need a valid data type, in your case the type is the ThreeD class. But this alone don't makes them objects, only defines their data type.
The variables only become objects when you use this class to create a new instance (a new single object in memory). So they must be initialized:
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();
This way, when the method getBoardCells() is called, each variable points to the object in memory they represent, which contains that method. Without the assignment, the variables are equal null by default. And of course, as null haven't a method getBoardCells() the compiler error you got makes all sense.
You need to instantiate the class:
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();
If you don't do this you cannot access the non-static class members.
In order to use a local variable, you have to initialize it:
var boardOne = new ThreeD();
var boardTwo = new ThreeD();
...
You have to initialize your board objects becuase C# compiler does not allow the use of uninitialized variables. Check this link : Compiler Error CS0165
static void Main(string[] args)
{
ThreeD boardOne = new ThreeD(); //1st of three objects for first board
ThreeD boardTwo = new ThreeD(); //2nd
ThreeD boardThree = new ThreeD();
//..............
// ..............
}
your missing creating object instance
ThreeD boardOne = new ThreeD();
ThreeD boardTwo = new ThreeD();
ThreeD boardThree = new ThreeD();

Why is this while loop getting stuck?

I just wrote a simple c# code for calculating the factorial of a number but the the program is getting stuck on the last name. Could someone why it's getting stuck?
Thanks,
Omin
using System;
//1. Write a program which finds the factorial of a number entered by the user.
namespace Beginner1{
class ProblemOne
{
static void Main (string[] args)
{
bool play = true;
while ( play ) {
Console.Write ("Type in the number you would like to find Factorial of: ");
int num = Convert.ToInt16( Console.ReadLine ());
int sum = 1;
for (int i = 2; i <= num; i++) {
sum = sum * i;
}
Console.WriteLine ("The Factorial of {0} is {1}", num, sum);
Console.Write ( "Would you like to play again? (Y or N): " );
string ans = Console.ReadLine();
do {
if( ans == "Y" || ans == "y" ) {
play = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
ans = Console.ReadLine();
}
} while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") );
}
}
}
}
`
Look at your while condition:
while ( (ans != "Y") || (ans != "y") || (ans != "N") || (ans != "n") )
In order to break out, all of those sub-conditions have to be false (so that the overall value is false).
The only way for the first condition to be true is if ans is "Y"... which means it definitely won't be equal to "y"...
In other words, your loop is equal to:
while (!(ans == "Y" && ans == "y" && ans == "N" && ans == "n"))
It would have to be a pretty special string to be equal to all four values.
You actually want:
while (ans != "Y" && ans != "y" && ans != "N" || ans != "n")
In other words, keep going while the value is not equal to any of the desired values. (An alternative would be to keep a set of "good answers"...
do {
string ans = Console.ReadLine();
if( ans == "Y" || ans == "y" ) {
play = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
//ans = Console.ReadLine();
}
} while ( (ans != "Y") && (ans != "y") && (ans != "N") && (ans != "n") );
I would do something like this:
bool isValid = false;
do
{
if( ans == "Y" || ans == "y" ) {
play = true;
isValid = true;
//break;
}
else if( ans == "N" || ans == "n" ) {
play = false;
isValid = true;
//break;
}
else
{
Console.Write( "You have entered an invalid answer. Please choose from either Y or N: ");
ans = Console.ReadLine();
isValid = false;
}
}while(isValid == false);
Relevant fiddle:https://dotnetfiddle.net/bxHY27

Categories

Resources