C# Blackjack - Freezing?
Posted: Sun Sep 19, 2010 2:46 pm
So, I've been working on a basic console application game of blackjack using C#. All is going well, until I come across a strange problem. I haven't done any programming in a long time, and C# is a relatively new language to me, so the problem may be obvious. However, I fail to see it. Basically, the following code (in the main function) appears to freeze after running the first Draw method of case 1. It runs perfectly fine if I enter break mode and step through the code line by line, but when left to run freely appears to freeze.
This is the Draw() method in the Deck class. It generates a random value and a random suit for the card from two arrays, and checks against another array to see if the card has been used before or not, if it has, it redoes the loop, if not, it adds the card to the used array and changes the player's hand and score accordingly:
The opponent version of this function is simply overloaded with a small amount of modifications. Any ideas as to why this would be freezing?
Code: Select all
Console.WriteLine("1 - Play Game");
Console.WriteLine("2 - See Rules");
int pChoice = Convert.ToInt32(Console.ReadLine());
switch (pChoice)
{
case 1:
deck.Draw(ref player);
deck.Draw(ref player);
Debug.WriteLine("Player hand initialized.");
deck.Draw(ref opponent);
deck.Draw(ref opponent);
int turn = generator.Next(2);
switch (turn)
{
case 1:
if (turn == 1)
player.Turn(ref deck, ref player);
else
opponent.Turn(ref deck, ref player);
Console.ReadKey();
break;
case 2:
opponent.Turn(ref deck, ref player);
break;
}
break;
case 2:
ShowRules();
break;
}
Code: Select all
public void Draw(ref Player player)
{
Random generator = new Random();
bool used = false;
while (true)
{
int value = generator.Next(Names.Length);
string name = Names[value] + Suits[generator.Next(Suits.Length)];
for (int i = 0; i < Used.Length; i++)
{
if (name == Used[i])
{
used = true;
break;
}
if (Used[i + 1] == null)
{
break;
}
}
if (used == false)
{
cards--;
player.cards++;
Used[iter] = name;
iter++;
player.hand += name;
player.score += value;
Console.WriteLine("You drew a {0}!", name);
break;
}
}
}