Reputation: 930
I am working on a project for class. It is my first time coding in C# and have ran into an issue. I need to randomly generate a number (1,2, or 3) for a rock paper scissors game but the program keeps outputting 3 and not a random number. Here is my code. Any suggestions on why this is occurring?
using System;
class elevator{
public static void Main(string[] args){
string response;
// Create an instance of the random class
Random random = new Random();
// Return a random non negative interger. Max is set to 4 as it is exclusive and will set the true max to 3.
int compChoice = random.Next(1, 4);
Console.Write("Do you want to play Rock, Paper, Scissors? ");
response = Console.ReadLine();
response = response.ToUpper();
while(response == "YES"){
// If statements displaying auto generated play for first player.
if(compChoice == 1){
Console.WriteLine("First player <computer> Selection - Rock");
}
if(compChoice == 2){
Console.WriteLine("First player <computer> Selection - Paper");
}
if(compChoice == 3){
Console.WriteLine("First player <computer> Selection - Scissors");
}
// Allow user to make selection
Console.Write("Second Player Selection - <Type 1,2, or 3. Rock = 1, Paper = 2, or Scissors = 3>: ");
int secondPlayer = Convert.ToInt32(Console.ReadLine());
// Determine Winner
if (secondPlayer == 1 & compChoice == 1) {
Console.WriteLine("You both chose rock!");
}
if (secondPlayer == 1 & compChoice == 2) {
Console.WriteLine("Player two wins! Paper covers rock.");
}
if (secondPlayer == 1 & compChoice == 3) {
Console.WriteLine("Player one wins! Rock smashes scissors.");
}
if (secondPlayer == 2 & compChoice == 1) {
Console.WriteLine("Player one wins! Paper covers rock.");
}
if (secondPlayer == 2 & compChoice == 2) {
Console.WriteLine("You both chose paper!");
}
if (secondPlayer == 2 & compChoice == 3) {
Console.WriteLine("Player two wins! Scissors cut paper.");
}
if (secondPlayer == 3 & compChoice == 1) {
Console.WriteLine("Player two wins! Rock smashes scissors.");
}
if (secondPlayer == 3 & compChoice == 2) {
Console.WriteLine("Player one wins! Scissors cut paper.");
}
if (secondPlayer == 3 & compChoice == 3) {
Console.WriteLine("You both chose scissors!");
}
// Ask user if they want to play another round
Console.Write("Do you want to play Rock, Paper, Scissors? ");
response = Console.ReadLine();
// Convert response to all caps
response = response.ToUpper();
}
Console.WriteLine("Thanks for playing!");
}
}
Upvotes: 0
Views: 460
Reputation: 1418
You need to put the random number generation in the loop :
while (response == "YES") {
int compChoice = random.Next(1, 4);
Otherwise, it will generate the number once and take that one all the time
See random.Next
as "Random, can I get the next random number", as you did it with the Console.ReadLine()
for the second player
Upvotes: 5