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
Related
I am trying to make a hangman game in the console app but got a message index out of range.
The image below shows that I can enter a letter. If I enter a wrong letter I can enter a new letter after entering a new letter I get the message system out of range.
I think the error can be found within the method public bool raadletter (char letter).
This program contains 2 classes, the first class is the galgjespel class (hangmangame) and the second class is the program class.
//I got this stacktrace value
~
error message
at galgje2.GalgjeSpel.Raadletter(Char letter) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Galgjespel.cs: line 37
at galgje2.Program.Speelgalgje(GalgjeSpel galgje) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 128
at galgje2.Program.Start() in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 28
at galgje2.Program.Main(String[] args) in C:\Users\surface pro\source\repos\week3opdracht1\galgje2\Program.cs: line 14
~
//
class GalgjeSpel
{
public string secretWord;
public string guessedWord;
public void Init(string secretword)
{
this.secretWord = secretword;
this.guessedWord="";
char[] letter = new char [secretword.Length];
for (int i =0; i< letter.Length; i++)
{
this.guessedWord += ".";
}
}
public bool Raadletter(char letter)
{
char[] guesses = guessedWord.ToArray();
guessedWord = "";
if (secretWord.Contains(letter))
{
for(int i=0; i<secretWord.Length; i++)
{
// somewhere on this place i get the index out of range message
if (secretWord[i]==letter)
{
guesses[i] = letter;
}
}
foreach(var element in guesses)
{
guessedWord += element;
if (element!='.')
{
Console.Write($"{element} ");
}
else
{
Console.Write($". ");
}
}
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("------------------------------");
Console.ResetColor();
Console.WriteLine();
// return true;
}
else
{
Console.WriteLine("letter does not match secretword");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("------------------------------");
Console.ResetColor();
}
return false;
}
}
////
class Program
{
static void Main(string[] args)
{
Program myProgam = new Program();
myProgam.Start();
Console.ReadKey();
}
void Start()
{
GalgjeSpel galgje = new GalgjeSpel();
galgje.Init("eetlepel");
List<string> woordenlijst = WoordenLijst();
string nieuwwoord= SelecteerWoord(woordenlijst);
galgje.Init(nieuwwoord);
ToonWoord(nieuwwoord);Speelgalgje(galgje);
//Console.WriteLine("Het geheime woord is: " + galgje.geheimWoord);
//Console.WriteLine("Het geraden woord is: " + galgje.geradenWoord);
}
List <string> WoordenLijst()
{
List<string> Woordenlijst = new List<string>();
Woordenlijst.Add("slapen");
Woordenlijst.Add("poepen");
Woordenlijst.Add("eten");
Woordenlijst.Add("vakantie");
Woordenlijst.Add("reizen");
return Woordenlijst;
}
string SelecteerWoord(List<string> woorden)
{
GalgjeSpel gaglje = new GalgjeSpel();
Random rnd = new Random();
int randomwoord = rnd.Next(1, 5);
string nieuwwoord = woorden[randomwoord];
gaglje.secretWord = nieuwwoord;
return nieuwwoord;
}
void ToonWoord(string woord)
{
GalgjeSpel galgje = new GalgjeSpel();
Console.Write($"The secret word is : ");
char[] letter = woord.ToArray();
for (int i = 0; i< woord.Length; i++)
{
galgje.secretWord += letter[i];
Console.Write($"{letter[i]} ");
}
Console.WriteLine();
Console.Write("the guessed word is : ");
for (int i = 0; i < woord.Length; i++)
{
galgje.guessedWord += (". ");
Console.Write(". ");
}
Console.WriteLine();
}
void ToonLetter(List<char> letters)
{
Console.Write("the letters entered are : ");
foreach (var element in letters)
{
Console.Write($" {element} ");
}
Console.WriteLine();
}
char LeesLetter(List<char> geheimeletters)
{
char letter;
do
{ Console.WriteLine();
Console.Write("enter a letter : ");
letter = char.Parse(Console.ReadLine());
return letter;
} while (geheimeletters.Contains(letter));
{
}
}
bool Speelgalgje(GalgjeSpel galgje)
{
//char lijst van ingevoerde letters
List<char> ingevoerdeLetters = new List<char>();
// char lijst van geheime letters
List<char> geheimeletters = new List<char>();
// zet elke geheime letter in een char array
char[]geheimewoord = galgje.secretWord.ToArray();
// voeg elke char letter toe aan lijst van geheime letters
for (int i=0; i<geheimewoord.Length; i++)
{
geheimeletters.Add(geheimewoord[i]);
if (galgje.guessedWord == galgje.secretWord)
{
return true;
}
else
{ char letter = LeesLetter(geheimeletters);
ingevoerdeLetters.Add(letter);
ToonLetter(ingevoerdeLetters);
galgje.Raadletter(letter);
}
}return false;
}
}
The problem lies in the code before the point of the exception
public bool Raadletter(char letter)
{
char[] guesses = guessedWord.ToArray();
// Here guessedWord is truncated
guessedWord = "";
// Now if the letter is not in the secretword you don repopulate the guessedword
// So at the next loop the code builds a guesses array
// that doesn't match anymore to the secretWord length
if (secretWord.Contains(letter))
{
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == letter)
{
guesses[i] = letter;
}
}
// Here you rebuild the guessedWord, but only if you have a match
foreach (var element in guesses)
{
guessedWord += element;
....
}
}
else
{
// fail messages
}
The solution is to close the if and rebuild the guessedWord in each case
char[] guesses = guessedWord.ToArray();
guessedWord = "";
if (secretWord.Contains(letter))
{
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == letter)
{
guesses[i] = letter;
}
}
}
foreach(var element in guesses)
{
guessedWord += element;
.....
}
I am trying to make a version of hangman in c# using the console application.
Right now what is working is for every letter that the user has not guessed it displays an * but what is not working is when the user guesses correctly it doesn't show the letter that the user inputted on the next turn.
Here is the code that I have that displays and shows of the user guessed any of the letters.
static void PlayHangMan(string randomWord)
{
char[] charArray;
char userGuess;
int counter = 0;
charArray = randomWord.ToCharArray();
while (counter < charArray.Length)
{
Console.Write("(Guess) Enter a letter in a word ");
foreach (char character in charArray)
{
Console.Write("*");
}
Console.Write(" > ");
userGuess = Console.ReadKey().KeyChar;
Console.WriteLine();
for (int index = 0; index < charArray.Length; index++)
{
if (charArray[index] == userGuess)
{
charArray[index] = userGuess;
Console.Write(charArray[index]);
}
else
{
Console.Write("*");
}
}
Console.WriteLine();
counter++;
}
}
---UPDATE---
I have been able to get the input to display correctly now thanks to the suggestions down below. But now I am trying to keep track of when the user guesses incorrectly. I have tried what is below. But I am getting very wired numbers. Like if I only guess wrong once I would want the guesses number to increase by one only , instead it is display 70 instead of one. Not too sure why
while (found.Any(c => c == '*'))
{
Console.Write("(Guess) Enter a letter in a word ");
Console.Write(found);
Console.Write(" > ");
userGuess = Console.ReadKey().KeyChar;
Console.WriteLine();
for (int index = 0; index < charArray.Length; index++)
{
if (charArray[index] == userGuess && userGuess != lettersUsed[index])
{
found[index] = userGuess;
lettersUsed[index] = userGuess;
}
else if (lettersUsed[index] == userGuess)
{
Console.WriteLine($"{userGuess} is already in the word");
}
else if (charArray[index] != userGuess && userGuess != lettersUsed[index])
{
guesses++;
}
}
}
Thanks for the suggestions!
You can solve it by introducing an additional array with found symbols, something like in code below. The solution is pretty simple and straightforward, test word is used as an example
int counter = 0;
var charArray = "test".ToCharArray();
var found = new char[charArray.Length];
for (int i = 0; i < charArray.Length; i++)
{
found[i] = '*';
}
while (counter < charArray.Length)
{
Console.Write("(Guess) Enter a letter in a word ");
foreach (char character in charArray)
{
Console.Write("*");
}
Console.Write(" > ");
var userGuess = Console.ReadKey().KeyChar;
Console.WriteLine();
for (int index = 0; index < charArray.Length; index++)
{
if (charArray[index] == userGuess)
{
found[index] = userGuess;
}
Console.Write(found[index]);
}
var any = false;
foreach (var c in found)
if (c == '*')
any = true;
if (!any)
break;
Console.WriteLine();
counter++;
}
Example output
"Would anybody have any suggestions on how I would go about ending the
program when the user guesses the word correctly before reaching the
length of the word?"
I took some other liberties as well.
static void PlayHangMan(string wordToGuess, int numberOfGuesses)
{
try
{
int counter = 0;
bool victory = false;
var charArray = wordToGuess.ToCharArray();
var found = new char[charArray.Length];
for (int i = 0; i < charArray.Length; i++)
{
found[i] = '*';
}
string hiddenWord = string.Empty;
foreach (char character in charArray)
{
hiddenWord = hiddenWord + "*";
}
while (counter < numberOfGuesses)
{
Console.Write($"(Guess left: {numberOfGuesses - counter}) Enter a letter in a word: {hiddenWord} > ");
// Wait for user input
var userGuess = Console.ReadKey().KeyChar;
hiddenWord = string.Empty;
Console.WriteLine();
for (int index = 0; index < charArray.Length; index++)
{
if (charArray[index] == userGuess)
{
found[index] = userGuess;
hiddenWord = hiddenWord + userGuess;
}
else
{
hiddenWord = hiddenWord + found[index];
}
}
counter++;
if (!found.Any(f => f == '*'))
{
Console.WriteLine($"You won! Word: {hiddenWord}");
victory = true;
break;
}
}
if (!victory)
Console.WriteLine("You are out of guesses.");
Console.Read();
}
catch (Exception ex)
{
var m = ex.Message;
}
}
or
My program shows the letter and then asks with what letter should you replace it:
static void Main(string[] args)
{
string textToEncode = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie2\TextSample.txt");
textToEncode = textToEncode.ToLower();
string distinctLetters = new string(textToEncode.Distinct().ToArray());
var count = textToEncode.Distinct().Count();
Console.WriteLine("Letters used in text: \n\n");
int iteration = 0;
for (int i = 0; i < count; i++)
{
if (Equals(distinctLetters[i], ' ')) { Console.Write(" <space> "); }
else if (Equals(distinctLetters[i], '\r')) { continue; }
else if (Equals(distinctLetters[i], '\n')) { continue; }
else { Console.Write(distinctLetters[i] + " "); }
}
Console.WriteLine("\n\nEncoding: \nPlease do not use single non-letter characters for coding (such as ',' or '?'");
List<string> charsUsedToEncode = new List<string>();
List<string> charsEncoded = new List<string>();
while (iteration < count)
{
if (Equals(distinctLetters[iteration], ' ')) { Console.Write("Swap <space> with "); }
else { Console.Write("Swap " + distinctLetters[iteration] + " with "); }
string string1 = Console.ReadLine();
if (string.IsNullOrEmpty(string1) == true)
{
Console.WriteLine("You have to type a character. ");
}
else if (string1.Length > 1)
{
Console.WriteLine("You entered more than one character. ");
}
else
{
char SwappingMark = char.Parse(string1);
if (charsUsedToEncode.Contains(SwappingMark.ToString()))
{
Console.WriteLine("\nThis character has already been used.");
}
else if (Equals(distinctLetters[iteration], '\r')) { continue; }
else if (Equals(distinctLetters[iteration], '\n')) { continue; }
else
{
charsEncoded.Add(distinctLetters[iteration].ToString());
charsUsedToEncode.Add(SwappingMark.ToString());
SwappingMark = char.ToUpper(SwappingMark);
textToEncode = textToEncode.Replace(distinctLetters[iteration], SwappingMark);
iteration++;
}
}
}
textToEncode = textToEncode.ToLower();
Console.ReadLine();
}
The problem is, after a '.' char The word "Swap" disappears. It looks like this:
Swap w with a
...
Swap . with x
y with l
The word "Swap" disappears. In my TextSample after a '.' text starts in new line and I don't know why, since there is a else if (Equals(distinctLetters[iteration], '\n')) { continue; } condition.
As I mentioned in the comments, the problem is that you skip the new-line characters before printing them but they're still in the string. So, you skip them again but after actually printing the "swap" statement to the user (causing those characters to be displayed before they're ignored).
What you should do instead is not include them in the array from the beginning. Also, there's no need to create a new string; you can just use a char array like this:
char[] distinctLetters = textToEncode.Distinct()
.Where(c=> !"\r\n".Contains(c))
.ToArray();
That way, you never have to check for \r or \n again since they don't exist.
Full example:
static void Main(string[] args)
{
string textToEncode = File.ReadAllText(#"C:\Users\ASUS\Desktop\szyfrowanie2\TextSample.txt");
textToEncode = textToEncode.ToLower();
char[] distinctLetters = textToEncode.Distinct()
.Where(c=> !"\r\n".Contains(c))
.ToArray();
var count = distinctLetters.Count();
Console.WriteLine("Letters used in text: \n\n");
int iteration = 0;
for (int i = 0; i < count; i++)
{
if (distinctLetters[i] == ' ') { Console.Write(" <space> "); }
else { Console.Write(distinctLetters[i] + " "); }
}
Console.WriteLine("\n\nEncoding: \nPlease do not use single non-letter characters for coding (such as ',' or '?'");
List<string> charsUsedToEncode = new List<string>();
List<string> charsEncoded = new List<string>();
while (iteration < count)
{
if (distinctLetters[iteration] == ' ') { Console.Write("Swap <space> with "); }
else { Console.Write("Swap " + distinctLetters[iteration] + " with "); }
string string1 = Console.ReadLine();
if (string.IsNullOrEmpty(string1))
{
Console.WriteLine("You have to type a character. ");
}
else if (string1.Length > 1)
{
Console.WriteLine("You entered more than one character. ");
}
else
{
char SwappingMark = char.Parse(string1);
if (charsUsedToEncode.Contains(SwappingMark.ToString()))
{
Console.WriteLine("\nThis character has already been used.");
}
else
{
charsEncoded.Add(distinctLetters[iteration].ToString());
charsUsedToEncode.Add(SwappingMark.ToString());
SwappingMark = char.ToUpper(SwappingMark);
textToEncode = textToEncode.Replace(distinctLetters[iteration], SwappingMark);
iteration++;
}
}
}
textToEncode = textToEncode.ToLower();
Console.ReadLine();
}
I am just in my early days of learning C# and I got the task to build a "Tik Tak Toe" - game via console application; but I have a huge problem seeing mistakes in my code: when I enter a line and a column, the program will just print the pawn and color from the first player. And somehow my second problem is, that when it comes to the next player, the console won't save the current game stats and will draw a new field.
What did I code wrong?
namespace Tik_Tak_Toe_
{
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int column;
static int line;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning==true)
{
UPDATE();
}
Console.ReadLine();
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
Console.WriteLine("Player " + (i + 1) + ", enter your name!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", choose a color: ");
ColorConfiguration();
Console.WriteLine("... and your symbol example: X or O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blue":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "yellow":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "white":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "red":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "darkblue":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Type one of the following colors: blue, pink, yellow, white, red oder darkblue");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", it's your turn!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for ( column=0; column<field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column+1) + "|");
Console.ResetColor();
for ( line=0; line<field.GetLength(0); line++)
{
if (field[column,line]==0 && (column != playercolumn || line != playerline))
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[playercolumn, playerline]].color;
Console.Write(" " + p[field[playercolumn, playerline]].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("First, choose a column: ");
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (column < 1 || column > 3)
{
Console.WriteLine("Choose a column.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Choose a column.");
}
}
playercolumn -= 1;
Console.WriteLine("... and now a line");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (line < 1 || line > 3)
{
Console.WriteLine("Choose a line.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Choose a line.");
}
}
playerline -= 1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
}
You just have just global variables to store playercolumn and playerline.
Each time you execute PlayerInputyou will replace the values this variables had.
You will need a 3x3 matrix to store the player choices, then print this matrix as a board. Id a column and row was already chosen, you need to refuse the user input.
Looks like you want to store user moves in field global variable, but you're not assigning that anywhere.
I modified the code, in update, repeat the PlayerInput until a its valid for update:
do
{
PlayerInput();
} while (!UpdateField());
In DrawField check onli for values in field variable, not the player input
static void DrawField()
{
for (column = 0; column < field.GetLength(1); column++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((column + 1) + "|");
Console.ResetColor();
for (line = 0; line < field.GetLength(0); line++)
{
if (field[column, line] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[column, line] - 1].color;
Console.Write(" " + p[field[column, line] - 1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
And implemented the UpdateField:
static bool UpdateField()
{
if (field[playercolumn, playerline] != 0)
{
Console.WriteLine("Column already chosen");
return false;
}
field[playercolumn, playerline] = currentplayer + 1;
return true;
}
It still need to check when the game finish.
You've got a lot of problems in your code. First of all, you was never storing the player input in the field array, so obviously when you were redrawing the table, only the last input was drawn. You were also exchanging some variables as line and playerline. After solving this problems and some minor ones and adding a Player class (i hope it is more or less like this as you don't provided it) , the code that correctly draws the board is more or less this:
class Program
{
static int[,] field = new int[3, 3];
static Player[] p;
static int i;
static bool gamerunning = true;
static Random rnd = new Random();
static int currentplayer = 0;
static int playercolumn = 7;
static int playerline = 7;
static void Main(string[] args)
{
INITIALIZE();
Console.Clear();
DrawField();
currentplayer = rnd.Next(1, 2);
while (gamerunning == true)
{
UPDATE();
}
Console.ReadLine();
}
public class Player
{
public string name { get; set; }
public char pawn { get; set; }
public ConsoleColor color { get; set;}
}
static void INITIALIZE()
{
playerconfiguration();
DrawField();
}
static void playerconfiguration()
{
p = new Player[2];
for (i = 0; i <= 1; i++)
{
p[i] = new Player();
Console.WriteLine("Spieler " + (i + 1) + ", gib deinen Namen ein!");
p[i].name = Console.ReadLine();
Console.WriteLine(p[i].name + ", wähle deine Farbe: ");
ColorConfiguration();
Console.WriteLine("... und nun dein Symbol z.B. X oder O: ");
p[i].pawn = Console.ReadKey().KeyChar;
Console.WriteLine();
}
}
static void ColorConfiguration()
{
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
bool whatcolorinput = true;
while (whatcolorinput == true)
{
string whatcolor = Console.ReadLine();
switch (whatcolor)
{
case "blau":
p[i].color = ConsoleColor.Cyan;
whatcolorinput = false;
break;
case "pink":
p[i].color = ConsoleColor.Magenta;
whatcolorinput = false;
break;
case "gelb":
p[i].color = ConsoleColor.Yellow;
whatcolorinput = false;
break;
case "weiss":
p[i].color = ConsoleColor.White;
whatcolorinput = false;
break;
case "rot":
p[i].color = ConsoleColor.Red;
whatcolorinput = false;
break;
case "dunkelblau":
p[i].color = ConsoleColor.DarkCyan;
whatcolorinput = false;
break;
default:
Console.WriteLine("Gib eine der folgenden Farben ein: blau, pink, gelb, weiss, rot oder dunkelblau");
break;
}
}
}
static void UPDATE()
{
DrawField();
Console.WriteLine(p[currentplayer].name + ", du bist dran!");
PlayerInput();
UpdateField();
currentplayer = (currentplayer + 1) % 2;
}
static void DrawField()
{
for (int line = 0; line < field.GetLength(1); line++)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.Write((line + 1) + "|");
Console.ResetColor();
for (int column = 0; column < field.GetLength(0); column++)
{
if (field[line, column] == 0)
{
Console.Write(" ");
}
else
{
Console.ForegroundColor = p[field[line, column]-1].color;
Console.Write(" " + p[field[line, column] -1].pawn + " ");
Console.ResetColor();
}
}
Console.WriteLine();
}
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine(" ________");
Console.WriteLine(" 1 2 3");
Console.ResetColor();
}
static void PlayerInput()
{
Console.WriteLine("Wähle zuerst eine Spalte: ");
bool lineinput = true;
while (lineinput == true)
{
try
{
playerline = Convert.ToInt32(Console.ReadLine());
if (playerline < 1 || playerline > 3)
{
Console.WriteLine("Wähle eine Spalte.");
}
else
{
lineinput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Spalte.");
}
}
bool columninput = true;
while (columninput == true)
{
try
{
playercolumn = Convert.ToInt32(Console.ReadLine());
if (playercolumn < 1 || playercolumn > 3)
{
Console.WriteLine("Wähle eine Zeile.");
}
else
{
columninput = false;
}
}
catch
{
Console.WriteLine("Wähle eine Zeile.");
}
}
playercolumn -= 1;
Console.WriteLine("... und nun eine Spalte");
//field[line-1, column] = new int();
playerline -= 1;
field[playerline, playercolumn] = currentplayer+1;
}
static void UpdateField()
{
}
static void FINISH()
{
}
}
Study this code and compare it with yours to see what were your mistakes. Of course, you must still check if a position is alreay taken,when one player has won and when there are no moves left and the result of the game is a draw.
First if works great
Second if throws an exception
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray;
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0);
}
if (numbersArray[i] > numbersArray[i - 1])
{
if (numInput == "") {
break;
}
}
}
i++;
}
Console.WriteLine("You entered this series: ");
for (int j = 0; j < numbersArray.Length; j++)
{
Console.WriteLine(" " + numbersArray[j]);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
}
}
You can't parse a string wihout digits like numInput = ""
EDIT: Try this code:
static void Main(string[] args)
{
Console.WriteLine("Enter a number and click enter, continue doing this process ");
Console.WriteLine("When you finish, just click enter without giving any input");
int i = 0;
int[] numbersArray = new []{1};
List<int> numbersList = new List<int>();
while (true)
{
String numInput = Console.ReadLine();
if (numInput == null || !numInput.All(char.IsDigit)) continue;
if (numInput != "")
{
numbersList.Add(Int32.Parse(numInput));
numbersArray = numbersList.ToArray();
if (i >= 1)
{
if (numbersArray[i] < numbersArray[i - 1])
{
Console.WriteLine("Your series is not going up!");
break;
Environment.Exit(0); // <-- Code is unreachable!
}
}
i++;
}
else if(i >= 1)
{
break;
}
}
Console.WriteLine("You entered this series: ");
foreach (int t in numbersArray)
{
Console.WriteLine(" " + t);
}
Console.WriteLine("The length of the series youve entered is: " + numbersArray.Length);
Console.ReadLine();
}
I assume you are trying to look at a index not existing.
Not sure of your language but I guess numbersArray[0] is the first index and numbersArray[1] is the second. So when you input your first number then you try to look at numbersArray[1] which doesn't exist.