Tic Tac Toe - Detecting win, lose, or draw - c#

This is a tic tac toe generator. Computer vs. Computer only, a little different than the usual Player vs. Computer. I have most of my code written for this, but the issue I am having is sometimes when I generate the game, the whole board fills up and there will be a line of X's and a line of O's and it will come up as a tie. Sometimes there is two lines of X's or two lines of O's generated, and the game doesn't stop after the first line with 3 in a row...any insights? Thank you.
namespace TicTacToe
{
public partial class Form1 : Form
{
private Random rn = new Random();
const int SIZE = 9;
char[] cell = new char[SIZE];
char firstPlayer = ' ', secondPlayer = ' ';
private void button1_Click(object sender, EventArgs e)
{
//Clear the labels and starting values
for (int i = 0; i < SIZE; i++)
{
cell[i] = ' ';
}
label10.Text = "";
//Pick X or O to go first
switch (rn.Next(2))
{
case 0: firstPlayer = 'O'; secondPlayer = 'X'; break;
case 1: firstPlayer = 'X'; secondPlayer = 'O'; break;
}
//Get five non-repeating numbers from 0 to 8
int[] positions = new int[5];
positions[0] = rn.Next(9);
for (int i = 1; i < 5; i++)
{
int temp = rn.Next(9);
for (int j = 0; j < i; j++)
{
if (temp == positions[j])
{
i--;
break;
}
else
{
positions[i] = temp;
}
}
}
//Set each position found to have first players letter
for (int i = 0; i < 5; i++)
{
cell[positions[i]] = firstPlayer;
}
for (int i = 0; i < SIZE; i++)
{
if (cell[i] != firstPlayer)
{
cell[i] = secondPlayer;
}
}
//Place cell values into the labels
label1.Text = cell[0].ToString();
label2.Text = cell[1].ToString();
label3.Text = cell[2].ToString();
label4.Text = cell[3].ToString();
label5.Text = cell[4].ToString();
label6.Text = cell[5].ToString();
label7.Text = cell[6].ToString();
label8.Text = cell[7].ToString();
label9.Text = cell[8].ToString();
//Check for a winner
switch(checkWinner())
{
case 'T' : label10.Text = "It's a tie!"; break;
case 'O' : label10.Text = "O Wins!"; break;
case 'X' : label10.Text = "X Wins!"; break;
default: label10.Text = "This will never appear"; break;
}
}
private char checkWinner()
{
//return either 'T' for tie, 'O' for O wins, and 'X' for X wins
char winner = ' ';
int winning_line = 0;
//check for a row win
if(cell[0].Equals(cell[1]) && cell[0].Equals(cell[2]))
{
winning_line++;
winner = cell[0];
}
if (cell[3].Equals(cell[4]) && cell[3].Equals(cell[5]))
{
winning_line++;
winner = cell[3];
}
if (cell[6].Equals(cell[7]) && cell[6].Equals(cell[8]))
{
winning_line++;
winner = cell[6];
}
//check for column wins
if (cell[0].Equals(cell[3]) && cell[0].Equals(cell[6]))
{
winning_line++;
winner = cell[0];
}
if (cell[1].Equals(cell[4]) && cell[1].Equals(cell[7]))
{
winning_line++;
winner = cell[1];
}
if (cell[2].Equals(cell[5]) && cell[2].Equals(cell[8]))
{
winning_line++;
winner = cell[2];
}
//check for diagonal winner
if (cell[0].Equals(cell[4]) && cell[0].Equals(cell[8]))
{
winning_line++;
winner = cell[0];
}
if (cell[2].Equals(cell[4]) && cell[2].Equals(cell[8]))
{
winning_line++;
winner = cell[2];
}
if (winning_line == 0 || winning_line > 1)
winner = 'T';
return winner;
}
public int i { get; set; }
}
}

if (winning_line == 0 || winning_line > 1)
If there are two lines, it will r port a tie. If you want to stop when a line is made, you needto check for a winner after each move, not after the entire board has been filled.

The second diagonal winner check should be 6 instead of 8.
You are currently checking:
X O O
O X O
O O X
and:
O O X
O X O
O O X
Obviously the last x should be to the left.
Additionaly as others have posted. Making two lines should not result in a tie. One player could even make two lines alone, causing a tie.
Change the function to return a result right away when it finds a winning row and check for it after every move.

This works: You need to get rid of the...
if (winning_line == 0 || winning_line > 1)
replace that line of code with these three piece of code:
if (winnerX == " X ")
{
theWinner = winnerX;
}
if (winnerO == " O ")
{
theWinner = winnerO;
}
if(winnerX == " X " && winnerO == " O ")
{
winnerT = " T ";
theWinner = winnerT;
}
So what I did was change a couple things. I didn't use the "winning_line++;" bit of code.
instead I did something like this for each of the if statement checks.
if (cell[2, 0].Equals(cell[1, 1]) && cell[2, 0].Equals(cell[0, 2]))
{
if (cell[2, 0] == 0)
{
winnerX = " X ";
}
else if (cell[2, 0] == 1)
{
winnerO = " O ";
}
}
So I have 4 strings that I'm using, one to keep track if X is has a winning line, same for O. I then have the winnerT string for keeping track of the Tie. its only used in place of where your old tie check if statement was.
You will also need to change your switch statement too if you decide to use strings instead of integers i.e
switch (checkWinner())
{
case " X ":
textBox1.Text = "X Wins!";
break;
case " O ":
textBox1.Text = "O Wins!";
break;
case " T ":
textBox1.Text = "It's a tie!";
break;
}

Hi think you should have a function that given a grid and a new pawn tell you if the game is over.
Then if the game is finished, you know that the winner is the last pawn played.
I think the Open source project MikMak of Marthyi has a perfect implementation of that, see
bool IsFinished(Grid currentState, Pawn newPawn)
in:
https://github.com/Marthyi/MikMak/blob/master/MikMakSolution/Morpion/MorpionManager.cs
Good luck!

Related

C# - Keeping total number of correct guesses inside a variable

Beginner to programming & have been assigned a heads or tails coin flip project.
I've figured out how to make it randomly generate the number of requested flips and print out the answers. However, I'm supposed to have it add up how many times the user's input came up into the correctCount variable and I can't find anywhere how to do it. I've tried searching on here and different sites from searching throughout Google. I assume I need to take their string input and convert it somehow, like if result == string, then correctCount + 1 basically, but can't figure out how to make that happen since you can't do that with int & string. Any info or hints would be very helpful - thank you!
class Coin
{
static void Main(string[] args)
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");```
As PMF mentioned, you have to not only receive user choice, but also analyse it.
A simple comparison should be more that enough here, although you might want to add some validation to user input.
static void Main(string[] args)
// UserInput
{
int choice; //variable for parsed user choice
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
if(headsOrTailsGuess.ToLower().Trim() == "heads"){ //here you look if its heads
choice = 0;
}
else{ //we can write additional if here to avoid other options from counting as tails
choice = 1;
}
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
if(result == choice){ //comparing result to parsed choice and incrementing the counter
correctCount++;
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");
}
Here's another way to do it using Linq.
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine();
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
List<string> resultList = new List<string>();
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
resultList.Add(result == 1? "Heads!" : "Tails!");
}
var guessCount = resultList.Where(a=>a.ToUpper().Contains(headsOrTailsGuess.ToUpper())).Count();
resultList.ForEach( a=> Console.WriteLine(a));
Console.WriteLine("Your guess, " + headsOrTailsGuess + " came up " + guessCount + " time(s).");
Console.WriteLine(headsOrTailsGuess);
}
}
}
using System;
Console.WriteLine("Guess which will have more: heads or tails?");
var headsChosen = false;
var input = string.Empty;
do
{
input = Console.ReadLine();
headsChosen = input.ToLower() == "heads";
} while (input.ToLower() != "heads" && input.ToLower() != "tails");
Console.WriteLine("How many times shall we flip the coin?");
var flips = 0;
do
{
} while (!int.TryParse(Console.ReadLine(), out flips));
var rnd = new Random();
var heads = 0;
var tails = 0;
for (int i = 0; i < flips; i++)
{
if (rnd.Next(0, 2) == 0)
{
Console.WriteLine("Heads!");
heads++;
}
else
{
Console.WriteLine("Tails!");
tails++;
}
}
var userGuessed = (headsChosen && heads > tails) || (!headsChosen && tails > heads);
Console.WriteLine($"You {(userGuessed ? "guess" : "loose")}!");

Need help setting up Win Condition for C# Connect Four Game

I'm trying to figure out how to set up my win condition (when the player lines up four chips as the same color horizontally, vertically, or diagonally). The win condition when met will display a win message, add 1 to a player win and player loss variable, add text to a list box, and clear the board.
I set up the board when the user presses the start button using the following code:
btnStartGame.Enabled = false;
btnStartGame.Visible = false;
btnExitGame.Enabled = true;
btnExitGame.Visible = true;
//This for loop creates the buttons used for the gameplay
for (int i = 0; i < gameButtons.Length; i++)
{
int index = i;
this.gameButtons[i] = new Button();
int x = 50 + (i % 7) * 50;
int y = 50 + (i / 7) * 50;
this.gameButtons[i].Location = new System.Drawing.Point(x, y);
this.gameButtons[i].Name = "btn" + (index + 1);
this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
this.gameButtons[i].TabIndex = i;
this.gameButtons[i].UseVisualStyleBackColor = true;
this.gameButtons[i].Visible = true;
gameButtons[i].Click += (sender1, ex) => this.PlaceChip(sender1, index);
this.Controls.Add(gameButtons[i]);
From there main game play uses the following code for "dropping" chips into the columns:
private void PlaceChip(object sender, int index)
{
var pressedButton = (Button)sender;
if (pressedButton.BackColor == Color.BlanchedAlmond)
{
var newBackColor = black ? Color.Red : Color.Black;
var buttonToChangeIndex = index;
while (buttonToChangeIndex + 7 < gameButtons.Count() &&
gameButtons[buttonToChangeIndex + 7].BackColor == Color.BlanchedAlmond)
{
buttonToChangeIndex += 7;
}
gameButtons[buttonToChangeIndex].BackColor = newBackColor;
black = !black;
}
}
Currently my Win Condition code looks like the following, I just am not sure how I need to set this up correctly (assuming I am making a mistake somewhere) or how I call this and set up the arguments correctly when I call it.
private void WinCondition(int a, int b, int c, int d)
{
if (gameButtons[a].BackColor == gameButtons[b].BackColor && gameButtons[a].BackColor == gameButtons[c].BackColor && gameButtons[a].BackColor == gameButtons[d].BackColor)
{
gamesPlayed += 1;
do
{
if (gameButtons[a].BackColor == Color.Red)
{
MessageBox.Show("Player 1 Wins!");
player1wins += 1;
player2loss += 1;
lstScoreBoard.Items.Add("Player One");
//add to file
ResetBoard();
}
else
{
MessageBox.Show("Player 2 Wins!");
player2wins += 1;
player1loss += 1;
lstScoreBoard.Items.Add("Player Two");
ResetBoard();
}
if(gamesPlayed == 5)
{
MessageBox.Show("Maximum number of games have been played!\nWin board will now be reset!");
gamesPlayed = 0;
player1wins = 0;
player2wins = 0;
player1loss = 0;
player2loss = 0;
}
} while (gamesPlayed > 5);
}
}
If there is a better way to set up this win condition (In regards to the arguments etc) I am open for it! I'm at a loss for how to properly set it up!
If my description of what I need doesn't make sense feel free to ask and I will try to clarify!

Experience error messages in C# Blackjack Code

I'm a beginner to C#, having previously used Python. I've been programming this Blackjack code and I'm experiencing a few errors. I can't seem to solve them and I think it is down to missing a brackets or something somewhere in the code as it worked fine before.
I've made efforts to try and figure it out for myself but I just can't. Getting the hang of C# formatting is a real change from Python.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
class Program
{
static void Main(string[] args)
{
// Creating array
string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
string[] cards = new string[13];
cards[0] = "A";
cards[1] = "2";
cards[2] = "3";
cards[3] = "4";
cards[4] = "5";
cards[5] = "6";
cards[6] = "7";
cards[7] = "8";
cards[8] = "9";
cards[9] = "10";
cards[10] = "J";
cards[11] = "Q";
cards[12] = "K";
int dealer_total = 0;
int player_total = 0;
int blackjack = 21;
// Dealing 2 player cards, then calculating and outputting card value
Random r = new Random();
for (int i = 0; i < 2; i++)
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
Console.WriteLine(full_name);
int cardValue = getcardvalue(card_name);
player_total = player_total + cardValue;
Console.WriteLine("You have a total of " + player_total); // Prints player's card value
}
bool hit = true;
while (hit)
{
Console.WriteLine("Would you like to stick or hit?");
string input = Console.ReadLine();
if (input.ToLower() == "stick")
{
hit = false;
// Dealing dealer cards
for (int i = 0; i < 2; i++)
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
int cardValue = getcardvalue(card_name);
dealer_total = dealer_total + cardValue;
Console.WriteLine("Dealer has a total of " + dealer_total);
if (dealer_total > player_total)
{
Console.WriteLine ("Dealer wins, you lose.");
}
else if ((player total) > (dealer_total))
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine ("Dealer total matches your total, draw.");
}
}
// if player chooses to hit, another card is drawn
 
else if (input.ToLower() == "hit")
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
Console.WriteLine(full_name);
int cardValue = getcardvalue(card_name);
player_total = player_total + cardValue;
Console.WriteLine("You have a total of " + player_total);
if (player_total > 21)
{
Console.WriteLine("You are bust; you lose.");
hit = false;
}
}
else
{
Console.WriteLine("Invalid response. Please choose either stick or hit.");
// Outputs an error message if anything else is input
}
}
}
private static int getcardvalue(string card_name)
{
int card_value = 0;
if (card_name == "A") // ie if the card is an Ace
{
card_value = 11;
}
else if (card_name == "K" || card_name == "Q" || card_name == "J") // if the card is a face card
{
card_value = 10;
}
else
{
card_value = int.Parse(card_name); //if the card is any other card, then it is worth its pip value
}
return card_value;
}
}
}
I'm receiving the following errors:
main.cs(67,22): error CS1525: Unexpected symbol `total'
main.cs(67,27): warning CS0642: Possible mistaken empty statement
main.cs(67,27): error CS1525: Unexpected symbol `)'
main.cs(67,45): error CS1525: Unexpected symbol `)', expecting `;' or `}'
main.cs(71,5): error CS1525: Unexpected symbol `else'
main.cs(85,4): error CS1525: Unexpected symbol `else'
main.cs(110,3): error CS1525: Unexpected symbol `private'
main.cs(110,34): error CS1525: Unexpected symbol `('
Below is the same code without the errors.
Changes:
Line 68: player total changed to player_total
Line 77: Added closing bracket for if, required before the else block
What editor/IDE are you using? These errors would be quite easy to spot in an IDE such as visual studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
class Program
{
static void Main(string[] args)
{
// Creating array
string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
string[] cards = new string[13];
cards[0] = "A";
cards[1] = "2";
cards[2] = "3";
cards[3] = "4";
cards[4] = "5";
cards[5] = "6";
cards[6] = "7";
cards[7] = "8";
cards[8] = "9";
cards[9] = "10";
cards[10] = "J";
cards[11] = "Q";
cards[12] = "K";
int dealer_total = 0;
int player_total = 0;
int blackjack = 21;
// Dealing 2 player cards, then calculating and outputting card value
Random r = new Random();
for (int i = 0; i < 2; i++)
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
Console.WriteLine(full_name);
int cardValue = getcardvalue(card_name);
player_total = player_total + cardValue;
Console.WriteLine("You have a total of " + player_total); // Prints player's card value
}
bool hit = true;
while (hit)
{
Console.WriteLine("Would you like to stick or hit?");
string input = Console.ReadLine();
if (input.ToLower() == "stick")
{
hit = false;
// Dealing dealer cards
for (int i = 0; i < 2; i++)
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
int cardValue = getcardvalue(card_name);
dealer_total = dealer_total + cardValue;
Console.WriteLine("Dealer has a total of " + dealer_total);
if (dealer_total > player_total)
{
Console.WriteLine("Dealer wins, you lose.");
}
else if ((player_total) > (dealer_total))
{
Console.WriteLine("You win!");
}
else
{
Console.WriteLine("Dealer total matches your total, draw.");
}
}
}
// if player chooses to hit, another card is drawn
else if (input.ToLower() == "hit")
{
int suit = r.Next(0, 4);
int card = r.Next(0, 13);
string suit_name = suits[suit];
string card_name = cards[card];
string full_name = card_name + " of " + suit_name;
Console.WriteLine(full_name);
int cardValue = getcardvalue(card_name);
player_total = player_total + cardValue;
Console.WriteLine("You have a total of " + player_total);
if (player_total > 21)
{
Console.WriteLine("You are bust; you lose.");
hit = false;
}
}
else
{
Console.WriteLine("Invalid response. Please choose either stick or hit.");
// Outputs an error message if anything else is input
}
}
}
private static int getcardvalue(string card_name)
{
int card_value = 0;
if (card_name == "A") // ie if the card is an Ace
{
card_value = 11;
}
else if (card_name == "K" || card_name == "Q" || card_name == "J") // if the card is a face card
{
card_value = 10;
}
else
{
card_value = int.Parse(card_name); //if the card is any other card, then it is worth its pip value
}
return card_value;
}
}
}
Here's a higher-level suggestion I hope you don't mind: don't try to force formatting - whatever development environment you're using (VisualStudio, something else) - let it control your braces.
Here's why - this is what your code looks like if you let VisualStudio do the formatting:
for (int i = 0; i < 2; i++)
{
... bunch of lines of code at this indenting level
}
else if (input.ToLower() == "hit")
... and it becomes obvious: something got missed in terms of brackets, because you can't end a For-Loop with an Else-If clause. Probably another bracket is missing, to exit out of that for() loop, likely after the dealer_total line.
It becomes a lot harder to spot errors like that if you're doing your indenting, because it's easy to mess up your indenting. As an example, from your code:
if (input.ToLower() == "stick")
{
hit = false;
// Dealing dealer cards
for (int i = 0; i < 2; i++)
... see the issue? You didn't indent the 'hit = false;' lines from that point onward.
Whatever your IDE is, just let it take care of formatting (and if you don't have an IDE, at least get VisualStudio community, which is free.) It'll save you quite a bit of headaches.

Stuck on how to make my scoring system work

So I am making a guess the word game in a windows form program in C#, and one of the requirements are that I must include a scoring system. (start out with 100 points, each time a wrong letter is guessed 10 points are subtracted from the total 100 and if you guess right it adds 10 to the total 100.) I have everything else working except for the points. I could really use some help as to how to fix this problem. Mind taking a look?`
public void CheckLetter(string word)
{
lblWord.Text = "";
corLetter += word[0];
score = score;
int amountToUpdate = 0;
score = score + amountToUpdate;
for (int i = 0; i < mysteryWord.Length; i++)
{
count = 0;
for (int j = 0; j < corLetter.Length; j++)
{
if (corLetter[j]== mysteryWord[i])
{
lblWord.Text += corLetter[j].ToString().ToUpper();
count++;
}
}
if (count == 0)
{
lblWord.Text += "_ ";
}
}
bool letterInWord = false;
for (int i = 0; i < word.Length; i++)
{
if (rtbGuess.Text == mysteryWord[i].ToString())
{
letterInWord = true;
}
}
score = score + amountToUpdate;
lblPoints.Text = (score).ToString();
if (!letterInWord)
{
lblPoints.Text = (score = score - 10).ToString();
}
}`
What exactly isn't working about the score? I just wrote some code up real quick, and had the score working fine. I see lots of things in your code I don't understand though, like:
score = score;
int amountToUpdate = 0;
score = score + amountToUpdate;
at the beginning, and:
score = score + amountToUpdate;
lblPoints.Text = (score).ToString();
at the end. Some of your variable names help, like rtbGuess tell me the guesses are typed into a rich text box.
Anyway, your code checks if the letter is incorrect, but not if it IS correct:
if (!letterInWord)
{
lblScore.Text = (int.Parse(lblScore.Text) - 10).ToString();
}
else
{
lblScore.Text = (int.Parse(lblScore.Text) + 10).ToString();
}

Keeping track of what the user inputs

This is my hangman code, and its almost good up to the point where it displays the guessed letters. It only displays the most recent guessed letter but I want it to continue on from whats left off. Such as if a person guess "A" and then "L" then Guessed letters are A, L.
I tried using a for loop after "Guessed letters are" but then it gives me the output
"A, A, A, A, A". What should I do to fix this problem?
class Hangman
{
public string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
public string[] torture = new string[6] { "left arm", "right arm", "left leg", "right leg", "body", "head" };
public char[] guessed = new char[26];
int i;
public void randomizedWord()
{
Random random = new Random();
int index = random.Next(0, 5);
char[] hidden = new char[words[index].Length];
string word = words[index];
Console.WriteLine(words[index]);
Console.Write("The word is: ");
for (i = 0; i < hidden.Length; i++)
{
Console.Write('-');
hidden[i] = '-';
}
Console.WriteLine();
int lives = 6;
do
{
Console.WriteLine("Guess a letter: ");
char userinput = Console.ReadLine().ToCharArray()[0];
index++;
guessed[index] = userinput;
Console.WriteLine("Guessed letters are: " + guessed[index]);
bool foundLetter = false;
for (int i = 0; i < hidden.Length; i++)
{
if (word[i] == userinput)
{
hidden[i] = userinput;
foundLetter = true;
Console.WriteLine("You guessed right!");
}
}
for (int x = 0; x < hidden.Length; x++)
{
Console.Write(hidden[x]);
}
if (!foundLetter)
{
Console.WriteLine(" That is not a correct letter");
lives--;
if (lives == 5)
{
Console.WriteLine("You lost a " + torture[0]);
}
else if (lives == 4)
{
Console.WriteLine("You lost the " + torture[1]);
}
else if (lives == 3)
{
Console.WriteLine("You lost your " + torture[2]);
}
else if (lives == 2)
{
Console.WriteLine("You lost the " + torture[3]);
}
else if (lives == 1)
{
Console.WriteLine("You lost your " + torture[4]);
}
else
{
Console.WriteLine("You lost your " + torture[5]);
Console.WriteLine("You lose!");
break;
}
}
bool founddash = false;
for (int y = 0; y < hidden.Length; y++)
{
if (hidden[y] == '-')
{
founddash = true;
}
}
if (!founddash)
{
Console.WriteLine(" You Win! ");
break;
}
Console.WriteLine();
} while (lives != 0);
}
I was going to post on your other thread Hangman Array C#
Try changing this line
Console.WriteLine("Guessed letters are: " + guessed[index]);
To
Console.WriteLine("Guessed letters are: " + string.Join(" ", guessed).Trim());
I had a play with your hangman game and came up with this solution (while we are doing your homework). Although not related to the question.
public class HangCSharp
{
string[] words = new string[5] { "ARRAY", "OBJECT", "CLASS", "LOOP", "HUMBER" };
List<char> guesses;
Random random = new Random();
string word = "";
string current = "";
int loss = 0;
readonly int maxGuess = 6;
int highScrore = 0;
public void Run()
{
word = words[random.Next(0, words.Length)];
current = new string('-', word.Length);
loss = 0;
guesses = new List<char>();
while (loss < maxGuess)
{
Console.Clear();
writeHeader();
writeLoss();
writeCurrent();
var guess = Console.ReadKey().KeyChar.ToString().ToUpper()[0];
while (!char.IsLetterOrDigit(guess))
{
Console.WriteLine("\nInvalid Guess.. Please enter a valid alpha numeric character.");
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
while (guesses.Contains(guess))
{
Console.WriteLine("\nYou have already guessed {0}. Please try again.", guess);
Console.Write(":");
guess = Console.ReadKey().KeyChar;
}
guesses.Add(guess);
if (!isGuessCorrect(guess))
loss++;
else if (word == current)
break;
}
Console.Clear();
writeHeader();
writeLoss();
if (loss >= maxGuess)
writeYouLoose();
else
doYouWin();
Console.Write("Play again [Y\\N]?");
while (true)
{
var cmd = (Console.ReadLine() ?? "").ToUpper()[0];
if (cmd != 'Y' && cmd != 'N')
{
Console.WriteLine("Invalid Command. Type Y to start again or N to exit.");
continue;
}
else if (cmd == 'Y')
Run();
break;
}
}
bool isGuessCorrect(char guess)
{
bool isGood = word.IndexOf(guess) > -1;
List<char> newWord = new List<char>();
for (int i = 0; i < word.Length; i++)
{
if (guess == word[i])
newWord.Add(guess);
else
newWord.Add(current[i]);
}
current = string.Join("", newWord);
return isGood;
}
void writeCurrent()
{
Console.WriteLine("Enter a key below to guess the word.\nHint: {0}", current);
if (guesses.Count > 0)
Console.Write("Already guessed: {0}\n", string.Join(", ", this.guesses));
Console.Write(":");
}
void writeHeader()
{
Console.WriteLine("Hang-CSharp... v1.0\n\n");
if (highScrore > 0)
Console.WriteLine("High Score:{0}\n\n", highScrore);
}
void writeYouLoose()
{
Console.WriteLine("\nSorry you have lost... The word was {0}.", word);
}
void doYouWin()
{
Console.WriteLine("Congratulations you guessed the word {0}.", word);
int score = maxGuess - loss;
if (score > highScrore)
{
highScrore = score;
Console.WriteLine("You beat your high score.. New High Score:{0}", score);
}
else
Console.WriteLine("Your score:{0}\nHigh Score:{1}", score, highScrore);
}
void writeLoss()
{
switch (loss)
{
case 1:
Console.WriteLine(" C");
break;
case 2:
Console.WriteLine(" C{0} #", Environment.NewLine);
break;
case 3:
Console.WriteLine(" C\n/#");
break;
case 4:
Console.WriteLine(" C\n/#\\");
break;
case 5:
Console.WriteLine(" C\n/#\\\n/");
break;
case 6:
Console.WriteLine(" C\n/#\\\n/ \\");
break;
}
Console.WriteLine("\n\nLives Remaining {0}.\n", maxGuess - loss);
}
}
Can be run as new HangCSharp().Run();
The index variable is being set to a random number when the random word is selected in this line.
int index = random.Next(0, 5);
Then that index is being used to store the guesses in the do..while loop. However, since index starts from a random number between 0 and 5 you see unexpected behaviour.
Set index to 0 in the line before the do..while loop and the for loop (or the alternatives suggested elsewhere) should work e.g. as so
index = 0;
int lives = 6;
do
{
// rest of the code

Categories