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.
Related
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")}!");
I send a word to my scramble method that returns the scrambled word but when I try to output the word I get System.Char[]. I have seen another thread that is similar to mine but he used .ToCharArray and .ToString and that was his problem and I couldn't figure out mine from that. This is C# and I am still learning. I do not want answers. I want to know what am I doing wrong and suggestions on how to fix it. Thank you in advance.(I don't know why the for loop is showing up that way)
namespace Farmer_JumbleApp
{
//Author: Aaron Farmer
class Jumble
{
string hiddenWord = "";//chosen word from array
string[] words = new string[] { "sauce", "iphone", "tick", "time", "think", "dream", "awake" };
Random randy = new Random();
string display = " ";
public Jumble()
{ }
public void Master()
{
UIJumble Graphics = new UIJumble();
Admin Info = new Admin();
string userGuess = " ";
int randNum = 0;
int quit;
bool cont = true;//Loop condition
char[] scrambledWord = new char[] { };//Scrambled word
randNum = randy.Next(words.Length);
hiddenWord = words[randNum];
scrambledWord = Scramble(hiddenWord);
while (cont)
{
display = "The Scrambled Word is: ";
Graphics.DisplayOnLine(display);
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord;
Graphics.DisplayOnLine(display);
}
//display = " ";
//Graphics.DisplayString(display);
display = "\n\n\nEnter your guess: ";
Graphics.DisplayOnLine(display);
userGuess = Graphics.RecieveString();
if (userGuess == hiddenWord)
{
Graphics.CleanUp();
Info.MyInfo();
display = "You are correct";
Graphics.DisplayString(display);
}//end of if
else if (userGuess != hiddenWord)
{
display = "Sorry, You are Incorrect";
Graphics.DisplayString(display);
}//end of else if
display = "Would you like to quit?\n1. Yes\n2. No";
Graphics.DisplayString(display);
quit = Graphics.RecieveInt();
if (quit == 1)
{
cont = false;
}
}//End of While_Loop
display = "Hope you enjoyed";
Graphics.DisplayString(display);
Environment.Exit(0);
}//End of Master Method
-----------------------------Next Method--------------------
public char[] Scramble(string word)
{
int randNum = 0;
int random;
char temp;
randNum = randy.Next(words.Length);
hiddenWord = words[randNum];
var displayWord = new char[word.Length]; //initializing array
for (int i = 0; i < word.Length; i++)
{
do
random = randy.Next(word.Length);
while (displayWord[random] != 0);
temp = word[i];
displayWord[random] = temp;
}
return displayWord;
}//End of Scramble Method
}//End of Class
}//End of Namespace
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord;
Graphics.DisplayOnLine(display);
}
should be replaced with
for (int i = 0; i < scrambledWord.Length; i++)
{
display = "" + scrambledWord[i];
Graphics.DisplayOnLine(display);
}
as "" + scrambledWord will use scrambledWord.ToString() which returns System.Char[] (its type name)
OR
shortly put, as Joel Coehoorn has suggested:
Graphics.DisplayOnLine(new String(scrambledWord));
public class LetterArray
{
internal static string[] Alphabet()
{
var letterValues = new string[26];
letterValues[0] = "A";
letterValues[1] = "B";
letterValues[2] = "C";
letterValues[3] = "D";
letterValues[4] = "E";
letterValues[5] = "F";
letterValues[6] = "G";
letterValues[7] = "H";
letterValues[8] = "I";
letterValues[9] = "J";
letterValues[10] = "K";
letterValues[11] = "L";
letterValues[12] = "M";
letterValues[13] = "N";
letterValues[14] = "O";
letterValues[15] = "P";
letterValues[16] = "Q";
letterValues[17] = "R";
letterValues[18] = "S";
letterValues[19] = "T";
letterValues[20] = "U";
letterValues[21] = "V";
letterValues[22] = "W";
letterValues[23] = "X";
letterValues[24] = "Y";
letterValues[25] = "Z";
return letterValues;
}
}
public class decrypt
{
public static void Main() //Main method
{
int res = 34;
string[] letterValues = LetterArray.Alphabet();
//Create for loop that runs through every possible shift value
for (int shift = 0; shift <= 25; shift++)
{
Console.WriteLine("\nShift Value = " + shift + ": ");
// For each character in the text file
foreach (var ch in ReadText.cipherTxt()) {
if (ch == ' ')
{ }
else
{
for (int i = 0; i <= 25; i++)
{
if ((ch.ToString().ToUpper()) == letterValues[i])
{
res = i;
}
}
if (shift > res)
{
Console.WriteLine(letterValues[26 - (shift - res)][0]);
}
else
{
Console.WriteLine(letterValues[res - shift][0]);
}
}
}
}
}
}
Not sure how to output the following so be a continuous string instead of each letter being stacked on top of each other. I have tried to change the Console.WriteLine values but it seems to mess the program up and throw an error instead.
Use Console.Write if you don't want each value in a new line.
Console.Write(letterValues[res - shift]);
You can also use a StringBuilder and Append characters to it. Then print it once after the loop.
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
It says that in my array that I have gone over the index. My program is a Number Guessing game played by 5 players (5 indexes). I have used arrays to create the object and player classes.
I have reached a stump where my program crashes within the second or third round of the game. I noticed that during my second round, the index did not loop property: the loop counts the index 1 to 5 in the first loop, then counts 2 to 5 in the second loop, then if I even get to the 3rd round of the loop, all the indexes are shuffled around meaning I can't go from 1 to 5.
As each player gets 3 guesses, use those 3 guesses and your out of the game. I have taken the array of object I created for the player, created a temporary array smaller than the previous and referenced that to achieve the current array.
I looked over my references in the code and found as much code as I could fix, I cannot find the bug that is causing my System.IndexOutOfRangeException. It is being caused by my guessing game class.
Here is my GuessingGame Class:
using System; // only this using statement is needed here.
namespace GuessingGame
{
class GuessingGame
{
#region instance attributes
private const int GUESSES_ALLOWED = 3;
private const int NUMBER_OF_PLAYERS_TO_START = 5;
private const int MIN_VALUE = 1;
private const int MAX_VALUE = 15;
private Player[] players;
private Random randomSource;
#endregion
public GuessingGame()
{
Console.WriteLine("Starting Constructor of GuessingGame");
players = new Player[NUMBER_OF_PLAYERS_TO_START];
randomSource = new Random();
string playerName = "";
for (int index = 0; index < players.Length; index++)
{
Console.Write("What is the name for player #"
+ (index +1) + "?\t");
playerName = Console.ReadLine();
players[index] = new Player(playerName, randomSource);
Console.Write("\n");
}
Console.WriteLine("Ending GuessingGame Constructor");
}
public GuessingGame(string [] playerNames)
{
Console.WriteLine("Starting Constructor of GuessingGame");
players = new Player[playerNames.Length];
randomSource = new Random();
for (int index = 0; index < playerNames.Length; index++)
{
players[index] = new Player(playerNames[index], randomSource);
}
}
public void playGame()
{
int numberOfPlayersWhoHavePlayedThisRound = 0;
int index = 0;
bool[] playedThisRound = null;
string playerGuessEntry = "";
int playerGuessValue = -1;
Player[] tempArray = new Player[players.Length - 1];
bool roundOver = false;
Console.WriteLine(
"Starting playGame - press any key to continue");
//Console.Read()
while (roundOver == false) // Is this the right condition?
{
playedThisRound = new bool[players.Length];
while (playedThisRound[index] == false)
{
do
{
Console.Write(players[index].getName()
+ ", Enter a number between "
+ MIN_VALUE.ToString()
+ " and " + MAX_VALUE.ToString()
+ " inclusive\t");
playerGuessEntry = Console.ReadLine();
Console.Write("\n");
}
while (!int.TryParse(playerGuessEntry,
out playerGuessValue)
|| playerGuessValue < MIN_VALUE
|| playerGuessValue > MAX_VALUE);
if(playerGuessValue < MIN_VALUE || playerGuessValue > MAX_VALUE)
{
Console.Write("Invalid guess- try again");
}
else
{
Console.WriteLine("You entered "
+ playerGuessValue.ToString());
players[index].makeAGuess(playerGuessValue);
playedThisRound[index] = true;
if (index == players.Length)
{
Console.WriteLine("End of Round");
index = 0; //edit?
numberOfPlayersWhoHavePlayedThisRound = 0;
}
}
if (players[index].getGuessesUsed() == 3)
{//creating a temp array
Console.WriteLine("Guesses MAXED");
tempArray = players[index].deletePlayerFromArray(players, index);
players = tempArray; // referencing
bool[] tempBooleanArray = new bool[playedThisRound.Length - 1];//reducing size of played this round array
Console.WriteLine("Playedthisround length: " + playedThisRound.Length + " \nThe Index: " + index.ToString());
tempBooleanArray = players[index].deletePlayerBool(playedThisRound, index);
playedThisRound = tempBooleanArray;
Console.WriteLine("New Player Array Size: " + players.Length);
Console.WriteLine("New Boolean Array Size: " + playedThisRound.Length);
}
if (index == players.Length - 1)
{
index = 0;
numberOfPlayersWhoHavePlayedThisRound = 0;
}
if (players.Length == 1)
{
roundOver = true;
}
index++;
numberOfPlayersWhoHavePlayedThisRound++;
}
Console.WriteLine("WINNER:" + players[index].getName() +
"\nWins: " + players[index].getWins() + "\nArray Size: " + players.Length.ToString());
}//end of while
Console.WriteLine("Ending playGame - "
+ "press any key to continue");
Console.Read();
}
public bool playersAlreadyPlayed(bool[] thePlayer)
{
bool havePlayed = false;
for (int plays = 0; plays < thePlayer.Length; plays++)
{
if (thePlayer[plays] == false)
{
havePlayed = false;
}
else
{
havePlayed = true;
}
}
return havePlayed;
}
static void Main(string[] args)
{
GuessingGame newGame = new GuessingGame();
newGame.playGame();
}
}
}
And Here is the Player Class
using System;
namespace GuessingGame
{
class Player
{
private String name;
private int winningNumber;
private int guessesUsed;
private int wins;
private Random myWinningNumberSource;
public Player(string newName, Random random)
{
name = newName;
guessesUsed = 0;
wins = 0;
myWinningNumberSource = random;
winningNumber = myWinningNumberSource.Next(1, 16);
}
public bool makeAGuess(int guessValue)
{
bool isWinner = false;//edit
if (guessValue == winningNumber)
{
wins++;
Console.WriteLine("Congradulations, You have guessed correct number!\n");
Console.WriteLine("You have a total of " + wins + " wins!");
Console.WriteLine("You have " + (3 - guessesUsed) + " guesses left!\n");
winningNumber = myWinningNumberSource.Next(1, 16);
isWinner = true; //edit
}
else
{
guessesUsed++;
Console.WriteLine("Oh no! You have guessed incorretly!");
Console.WriteLine("You have used " + guessesUsed + " and have " + (3 - guessesUsed) + " guesses left!");
Console.WriteLine("HINT: You should have guessed " + winningNumber);
isWinner = false;
if (guessesUsed > 3)
{
Console.WriteLine("Sorry you have Lost, Game Over");
}
}
return isWinner;
}
public int getGuessesUsed()
{
return guessesUsed;
}
public string getName()
{
return name;
}
public int getWins()
{
return wins;
}
public Player[] getWinner(Player[] nPlayers)
{
int maxScore = 0; //edit
Player[] winningPlayers;
winningPlayers = new Player[5];
for (int i = 0; i < nPlayers.Length; i++)
{
if (nPlayers[i].wins >= maxScore)
{
winningPlayers[i].wins = nPlayers[i].getWins();
winningPlayers[i].name = nPlayers[i].getName();
}
}
return winningPlayers;
}
public bool[] deletePlayerBool(bool[] playedThisRound, int removeIndex)//edit
{
bool[] newArray = new bool[playedThisRound.Length - 1];
int tempIndex = 0;
for (int i = 0; i < playedThisRound.Length; i++)
{
if (i != removeIndex)
{
newArray[tempIndex++] = playedThisRound[i];
}
}
return newArray;
}
public Player[] deletePlayerFromArray(Player[] nPlayers, int removeIndex)
{
Player[] newArray = new Player[nPlayers.Length - 1];
int tempIndex = 0;
for (int i = 0; i < nPlayers.Length; i++)
{
if (i != removeIndex)
{
newArray[tempIndex++] = nPlayers[i];
}
}
return newArray;
}
}
}
i is within the bounds of nPlayer length not 0-4.
public Player[] getWinner(Player[] nPlayers)
{
int maxScore = 0; //edit
Player[] winningPlayers;
winningPlayers = new Player[5];
for (int i = 0; i < nPlayers.Length; i++)
{
if (nPlayers[i].wins >= maxScore)
{
winningPlayers[i].wins = nPlayers[i].getWins();
winningPlayers[i].name = nPlayers[i].getName();
}
}
return winningPlayers;
}
It means that you are trying to access an index bigger than the array. In the line:
while(playedThisRound[index] == false)
You don't check the boundaries before using the index, and your crash is probably there.
It means that you are trying to access an item in an array with an index higher than the limit of the array.