c# console dice roll
I am having problems with a program. I need to compare the number of combinations, if they are the same, the higher value wins. Else if the number of combinations are the same and the value are the same, it is a tie. here what I hav开发者_高级运维e so far.
int[] player1 = new int[6];
int[] player2 = new int[6];
Random rndGen = new Random();
for (int i = 0; i < 5; i++)
{
int diceRoll = 0;
diceRoll = rndGen.Next(6);
player1[diceRoll]++;
Console.WriteLine("Computer rolled: {0}", diceRoll + 1);
}//end for
for (int i = 0; i < 5; i++)
{
int diceRoll = 0;
diceRoll = rndGen.Next(6);
player2[diceRoll]++;
Console.WriteLine("You rolled: {0}", diceRoll + 1);
}//end for
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 1; i < 5; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for
if (player1[maxPlayer1] > player2[maxPlayer2])
Console.WriteLine("Computer won with {0} of a kind", player1[maxPlayer1], maxPlayer1 + 1);
else
if (player2[maxPlayer2] > player1[maxPlayer1])
Console.WriteLine("You won with {0} of a kind", player2[maxPlayer2], maxPlayer2 + 1);
else
Console.WriteLine("Tie");
}//end main
}
}
Is player1[diceRoll]++
really what you mean to do?
At a glance, here are some things you should check:
for (int i = 1; i < 5; i++)
This loop will execute 4 times, where i = 1, 2, 3, 4. That's almost certainly not what you were trying to do.
Arrays are zero-indexed. That means that the first value is at index 0, the second at index 1, etc. For an array of length 6, the last value will be at index 5.
When using formatted strings, the first parameter is the format and then every other parameter is referred to with a number, starting at 0. So for this line:
Console.WriteLine("You won with {0} of a kind", player2[maxPlayer2], maxPlayer2 + 1);
the parameter maxPlayer2 + 1
is never used.
I think you have a bug at the third for-loop:
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 1; i < 5; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for
It should be:
int maxPlayer1 = 0, maxPlayer2 = 0;
for (int i = 0; i < 6; i++)
{
if (player1[i] > player1[maxPlayer1]) maxPlayer1 = i;
if (player2[i] > player2[maxPlayer2]) maxPlayer2 = i;
}//end for
精彩评论