I am trying to make a program to play a game of craps where the user enters a bet amount, then they roll 2 six sided dice. If the sum of the dice s 2,3 or 12 they lose. 7 or 11 they win. if any other number is rolled the player keeps rolling until they get the point number to win or 7 to lose. However for some reason if I select n to not play again it still loops the game a second time before quitting. I am not sure why
any help would be appreciated.
static void processCraps()
{
string gameStatus = null;
double betAmount =0;
double netWinning = 0;
int point;
do
{
try
{
Console.WriteLine("Enter the amount to bet");
betAmount = double.Parse(Console.ReadLine());
}
catch (Exception)
{
Console.WriteLine("Invaid input try again");
}
var diceRoll = RollDice();
if (diceRoll == 2 || diceRoll == 3 || diceRoll == 12)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (diceRoll == 7 || diceRoll == 11)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
else if (diceRoll != 2 || diceRoll != 3 || diceRoll != 12 || diceRoll != 7 || diceRoll != 11)
{
point = diceRoll;
Console.WriteLine($"Point is {point}");
for (int rollCount = 0; rollCount >= point; rollCount++)
{
var roll = RollDice();
if (roll == 7)
{
Console.WriteLine($"You lost {betAmount}");
netWinning = netWinning - betAmount;
}
else if (roll == point)
{
Console.WriteLine($"You won {betAmount}");
netWinning = netWinning + betAmount;
}
}
}
try
{
Console.WriteLine("Do you want to play again (y/n)");
gameStatus = Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("answer must be a letter");
}
} while (gameStatus != "n") ;
Console.WriteLine($"Your net winning is {netWinning}");
}
You read input twice.
You may want to split the logic into two loops. 1. Read bet amount. 2. Play game.
do
{
Console.WriteLine("Enter the amount to bet, or 'q' to quit:");
var betStr = Console.ReadLine();
if( betStr == "q") return;
double.TryParse(betStr, out betAmount);
} while (betAmount != 0);
do
{
//Play
Console.WriteLine("Do you want to play again (n = quit)?");
gameStatus = Console.ReadLine();
} while (gameStatus != "n");
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!");
}
}
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
Console app rock paper scissors game well i have trouble explaining it you just have to test it and see also whenever i press y it's suppose to clear the console and start the game over but that is just 1/2 the problem whenever i type 'rock' it translates it to 'ock' same with paper and scissor it takes out the first letter.
enum Rock_Paper_Scissor
{
rock,
paper,
scissor
}
class Computer
{
Random rand = new Random();
public Rock_Paper_Scissor Choice()
{
Rock_Paper_Scissor element = (Rock_Paper_Scissor)rand.Next(3);
return element;
}
}
class Game_Logic
{
static void Main()
{
Computer Comp = new Computer();
bool PlayAgain = true;
ConsoleKeyInfo input = Console.ReadKey();
Rock_Paper_Scissor ComputerChoice = Comp.Choice();
do
{
string PlayerChoice = Console.ReadLine();
Console.Clear();
while (PlayerChoice == ComputerChoice.ToString())
{
ComputerChoice = Comp.Choice();
}
Console.WriteLine("Player: "+ PlayerChoice);
Console.WriteLine("Computer: " + ComputerChoice);
if (PlayerChoice == "rock" && ComputerChoice.ToString() == "scissor")
Console.WriteLine("You won!");
else if (PlayerChoice == "scissor" && ComputerChoice.ToString() == "rock")
Console.WriteLine("Computer won!");
else if (PlayerChoice == "paper" && ComputerChoice.ToString() == "rock")
Console.WriteLine("You won!");
else if (PlayerChoice == "rock" && ComputerChoice.ToString() == "paper")
Console.WriteLine("Computer won");
else if (PlayerChoice == "scissor" && ComputerChoice.ToString() == "paper")
Console.WriteLine("You won!");
else if (PlayerChoice == "paper" && ComputerChoice.ToString() == "scissor")
Console.WriteLine("Computer won!");
else
{
Console.WriteLine("invalid value");
}
Console.WriteLine("\n"+"Play again? <y/n>");
PlayAgain = input.KeyChar == 'y';
} while (PlayAgain);
}
}
ConsoleKeyInfo input = Console.ReadKey();
Rock_Paper_Scissor ComputerChoice = Comp.Choice();
do
{
string PlayerChoice = Console.ReadLine();
The issue lies with this snippet. Your first letter will be eaten triggering the first Console.Readkey meaning the Console.ReadLine() you are intending to pass the value too will only receive the rest.
The Console.ReadKey() line will do you no good outside the do loop anyway, you may as well remove it and do
///
Console.WriteLine("\n"+"Play again? <y/n>");
} while (Console.ReadKey.KeyChar == 'y');
Directly. Solving both problems.
I am using the following method which works but wondering if there is a better algorithm to perform the test. Is there a better way to do it? Doing this in C# but putting syntax aside, believe the algorithm is going to be the same across OOP languages. Thank you.
public String play(int userInput)
{ //ComputerIn is a randomly generated number between 1-3
ComputerIn = computerInput();
if (ComputerIn == userInput)
return "Draw";
else if (ComputerIn == 1 && userInput == 2)
return "Win";
else if (ComputerIn == 2 && userInput == 3)
return "Win";
else if (ComputerIn == 3 && userInput == 1)
return "Win";
else if (ComputerIn == 1 && userInput == 3)
return "Lose";
else if (ComputerIn == 2 && userInput == 1)
return "Lose";
else
return "Lose";
}
if ((ComputerIn) % 3 + 1 == userInput)
return "Win";
else if ((userInput) % 3 + 1 == ComputerIn)
return "Lose"
else
return "Draw"
If you wrap 3 around to 1 (using %) then the winner is always 1 greater than the loser.
This approach is more natural when you use 0-2, in which case we would use (ComputerIn+1)%3. I came up with my answer by subbing ComputerIn with ComputerIn-1 and UserInput with UserInput-1 and simplifying the expression.
Edit, looking at this question after a long time. As written, if the ComputerIn is not used anywhere else, and is only used to determine win/lose/draw, then this method is actually equivalent to:
if (ComputerIn == 1)
return "Win";
else if (ComputerIn == 2)
return "Lose"
else
return "Draw"
This can even be further simplified to
return new String[]{"Win", "Lose", "Draw"}[ComputerIn-1];
The results from this are entirely indistinguishable. Unless the randomly generated number is exposed to outside of this method. No matter what your input is, there's always 1/3 chance of all possibilities. That is, what you're asking for, is just a complicated way of returning "Win", "Lose", or "Draw" with equal probability.
Here's one of many possible solutions. This will print Win.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Input userInput = Input.Rock;
Result result = Play(userInput);
Console.WriteLine(Enum.GetName(result.GetType(), result));
Console.ReadKey();
}
static Result Play(Input userInput)
{
Input computer = Input.Scissors;
switch (userInput)
{
case Input.Paper:
switch (computer)
{
case Input.Paper: return Result.Draw;
case Input.Rock: return Result.Win;
case Input.Scissors: return Result.Lose;
default: throw new Exception("Logic fail.");
}
case Input.Rock:
switch (computer)
{
case Input.Paper: return Result.Lose;
case Input.Rock: return Result.Draw;
case Input.Scissors: return Result.Win;
default: throw new Exception("Logic fail.");
}
case Input.Scissors:
switch (computer)
{
case Input.Paper: return Result.Win;
case Input.Rock: return Result.Lose;
case Input.Scissors: return Result.Draw;
default: throw new Exception("Logic fail.");
}
default: throw new Exception("Logic fail.");
}
}
}
enum Input
{
Rock,
Paper,
Scissors
}
enum Result
{
Lose,
Draw,
Win
}
}
This is how I would do it:
public class Program
{
public enum RPSPlay { Rock, Scissors, Paper }
public enum RPSPlayResult { Win, Draw, Loose }
public static readonly int SIZE = Enum.GetValues(typeof(RPSPlay)).Length;
static RPSPlayResult Beats(RPSPlay play, RPSPlay otherPlay)
{
if (play == otherPlay) return RPSPlayResult.Draw;
return ((int)play + 1) % SIZE == (int)otherPlay
? RPSPlayResult.Win
: RPSPlayResult.Loose;
}
static void Main(string[] args)
{
Random rand = new Random();
while (true)
{
Console.Write("Your play ({0}) (q to exit) : ", string.Join(",", Enum.GetNames(typeof(RPSPlay))));
var line = Console.ReadLine();
if (line.Equals("q", StringComparison.OrdinalIgnoreCase))
return;
RPSPlay play;
if (!Enum.TryParse(line, true, out play))
{
Console.WriteLine("Invalid Input");
continue;
}
RPSPlay computerPlay = (RPSPlay)rand.Next(SIZE);
Console.WriteLine("Computer Played {0}", computerPlay);
Console.WriteLine(Beats(play, computerPlay));
Console.WriteLine();
}
}
}
I would prefer to use a static 3x3 matrix to store the possible outcomes. But it is a question of taste, and I am a mathematician.
Here is one-liner that we created at lunchtime.
using System;
public class Rps {
public enum PlayerChoice { Rock, Paper, Scissors };
public enum Result { Draw, FirstWin, FirstLose};
public static Result Match(PlayerChoice player1, PlayerChoice player2) {
return (Result)((player1 - player2 + 3) % 3);
}
public static void Main() {
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Rock), Result.Draw);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Paper), Result.Draw);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Scissors), Result.Draw);
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Scissors), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Paper), Result.FirstLose);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Rock), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Scissors), Result.FirstLose);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Paper), Result.FirstWin);
Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Rock), Result.FirstLose);
}
public static void Test(Result sample, Result origin) {
Console.WriteLine(sample == origin);
}
}
\From A java beginner Perspective. User plays with the computer to infinity.
import java.util.Scanner;
public class AlgorithmDevelopmentRockPaperScissors{
public static void main(String[] args){
System.out.println("\n\nHello Eric today we are going to play a game.");
System.out.println("Its called Rock Paper Scissors.");
System.out.println("All you have to do is input the following");
System.out.println("\n 1 For Rock");
System.out.println("\n 2 For Paper");
System.out.println("\n 3 For Scissors");
int loop;
loop = 0;
while (loop == 0){
System.out.println("\n\nWhat do you choose ?");
int userInput;
Scanner input = new Scanner(System.in);
userInput = input.nextInt();
while (userInput > 3 || userInput <= 0 ){ //ensure that the number input by the sure is within range 1-3. if else the loop trap.
System.out.println("Your choice "+userInput+" is not among the choices that are given. Please enter again.");
userInput = input.nextInt();
}
switch (userInput){
case 1:
System.out.println("You Chose Rock.");
break;
case 2:
System.out.println("You Chose Paper.");
break;
case 3:
System.out.println("You Chose Scissors");
break;
default:
System.out.println("Please Choose either of the choices given");
break;
}
int compInput;
compInput = (int)(3*Math.random()+1);
switch (compInput){
case 1:
System.out.println("\nComputer Chooses Rock.");
break;
case 2:
System.out.println("\nComputer Chooses Paper.");
break;
case 3:
System.out.println("\nComputer Chooses Scissors");
break;
}
if (userInput == compInput){
System.out.println(".........................................");
System.out.println("\nYou Both chose the same thing, the game ends DRAW.");
System.out.println(".........................................");
}
if (userInput == 1 && compInput == 2){
System.out.println(".........................................");
System.out.println("\nComputer wins because Paper wraps rock.");
System.out.println(".........................................");
}
if (userInput == 1 && compInput == 3){
System.out.println(".........................................");
System.out.println("\nYou win because Rock breaks Scissors.");
System.out.println(".........................................");
}
if (userInput == 2 && compInput == 1){
System.out.println(".........................................");
System.out.println("\nYou win Because Paper wraps Rock");
System.out.println(".........................................");
}
if (userInput == 2 && compInput == 3){
System.out.println(".........................................");
System.out.println("\nComputer wins because Scissors cut the paper");
System.out.println(".........................................");
}
if (userInput == 3 && compInput == 1){
System.out.println(".........................................");
System.out.println("\nComputer Wins because Rock Breaks Scissors.");
System.out.println(".........................................");
}
if (userInput == 3 && compInput == 2){
System.out.println(".........................................");
System.out.println("\nYou win because scissors cut the paper");
System.out.println(".........................................");
}
}
}
}
A simple JavaScript implementation using sine wave function to calculate result:
<script>
var tab = ["Lose","Draw","Win"];
var dict = ["Paper","Stone","Scissors"];
var i,text = '';
for (i = 0; i < dict.length; i++) {
text += i + '-' + dict[i] + ' ';
}
var val1 = parseInt(prompt(text));
var val2 = Math.floor(Math.random() * 3);
alert('Computer chose: ' + dict[val2]);
result = Math.sin((val1*180+1) - (val2*180+1));
alert(tab[Math.round(result)+1]);
</script>
No if's required, just for fun...
Check it
Observation: The user wins if userInput is only one ahead of computerInput (case of (1,2), (2,3)) or lag two (case of (3,1)).
Conversely, if userInput lags one behind computerInput or two ahead, the user loses.
In the modulo 3, the lag one is the same as the advance two.
(-1 mod 3 == 2 mod 3 == 2)
int decision = (userInput - computerInput + 3) % 3;
String[] answer = {"Draw", "Win", "Lose"};
return answer[decision];
This is my first year in a Computer Programming course and one of my current assignments is to create a working Rock, Paper, Scissors game.
I have most of it working but my teacher has said that I have a lot of unnecessary code without actually telling me what it is. I'd like to get this streamline as best as possible as I'm not just satisfied with whatever works.
As well, the second validation of user input (user makes a choice, program runs through and displays who wins then is asked to make a choice again) doesn't work like the first one and I can't figure out what's going wrong. I've been looking at this for the past 2 weeks and can't figure it out so any help is appreciated.
The code that I have is as follows:
namespace Assignment04
{
class Program
{
static void Main(string[] args)
{
// Declare variables
int gamesPlayed = 0, userWins = 0, computerWins = 0, draws = 0, userSelection, computerSelection;
bool inputIsValid = false;
// Prompt user
Console.WriteLine("Welcome to the Rock, Paper, Scissors game!");
Console.WriteLine("1 - Rock");
Console.WriteLine("2 - Paper");
Console.WriteLine("3 - Scissors");
Console.WriteLine("4 - Quit program and view record");
// Create a loop to validate user's selection
do
{
Console.Write("Please make a selection: ");
// loop and test using TryParse()
while (!int.TryParse(Console.ReadLine(), out userSelection))
{
// invalid data type
Console.WriteLine("Invalid input.");
Console.Write("Please make a selection: ");
}
// test if input is within acceptable range
if (userSelection >= 1 && userSelection <= 4)
{
inputIsValid = true;
}
else
{
// valid integer, but out of acceptable range
Console.WriteLine("Number out of range.");
}
} while (!inputIsValid);
// Display user's choice
while (userSelection >= 1 && userSelection <= 3)
{
if (userSelection == 1)
{
Console.WriteLine("\nYou have selected Rock");
gamesPlayed = gamesPlayed + 1;
}
else if (userSelection == 2)
{
Console.WriteLine("\nYou have selected Paper");
gamesPlayed = gamesPlayed + 1;
}
else if (userSelection == 3)
{
Console.WriteLine("\nYou have selected Scissors");
gamesPlayed = gamesPlayed + 1;
}
// Generate computer's choice
Random randomNumber = new Random();
computerSelection = randomNumber.Next(1, 4);
// Display computer's choice
if (computerSelection == 1)
{
Console.WriteLine("Computer has chosen Rock");
}
else if (computerSelection == 2)
{
Console.WriteLine("Computer has chosen Paper");
}
else if (computerSelection == 3)
{
Console.WriteLine("Computer has chosen Scissors");
}
// Calculate and display who wins
if (userSelection == computerSelection)
{
draws = draws + 1;
}
else if (userSelection == 1 && computerSelection == 3 || userSelection == 2 && computerSelection == 1 || userSelection == 3 && computerSelection == 2)
{
userWins = userWins + 1;
}
else if (userSelection == 1 && computerSelection == 2 || userSelection == 2 && computerSelection == 3 || userSelection == 3 && computerSelection == 1)
{
computerWins = computerWins + 1;
}
// Display results and statistics
Console.WriteLine("\nYou have played {0} games with {1} wins, {2} draws, and {3} losses.", gamesPlayed, userWins, draws, computerWins);
do
{
Console.Write("Please make a selection: ");
// loop and test using TryParse()
while (!int.TryParse(Console.ReadLine(), out userSelection))
{
// invalid data type
Console.WriteLine("Invalid input.");
Console.Write("Please make a selection: ");
}
// test if input is within acceptable range
if (userSelection >= 1 && userSelection <= 4)
{
inputIsValid = true;
}
else
{
// valid integer, but out of acceptable range
Console.WriteLine("Number out of range.");
}
} while (!inputIsValid);
}
if (gamesPlayed == 0 && userSelection == 4)
{
Console.WriteLine("\nGoodbye");
}
else if (gamesPlayed > 0 && userSelection == 4)
{
Console.WriteLine("\nGames played = " + gamesPlayed);
Console.WriteLine("User wins = " + userWins);
Console.WriteLine("Computer wins = " + computerWins);
Console.WriteLine("Draws = " + draws);
}
Console.ReadLine();
}
}
}
If you find yourself writing almost the same thing multiple times, you should look for ways to refactor it. Here's an example of unnecessary repeated code:
if (userSelection == 1)
{
Console.WriteLine("\nYou have selected Rock");
gamesPlayed = gamesPlayed + 1;
}
else if (userSelection == 2)
{
Console.WriteLine("\nYou have selected Paper");
gamesPlayed = gamesPlayed + 1;
}
else if (userSelection == 3)
{
Console.WriteLine("\nYou have selected Scissors");
gamesPlayed = gamesPlayed + 1;
}
Can be simplified to:
Console.WriteLine("\nYou have selected " + tools[userSelection - 1]);
gamesPlayed++;
Where tools is defined as:
string[] tools = { "Rock", "Paper", "Scissors" };