Rock, Paper, Scissors game - java

I have my app class for the game Rock, Paper, Scissors. My problem is if I win two times or the computer wins two times I need the game to stop generating but it keeps going one more time. How can I rectify this?
import javax.swing.JOptionPane;
public class RockPaperScissorsApp
{
public static void main(String args[])
{
String player1, winner;
int player2, gamesPlayed = 1, player1Wins = 0, player2Wins = 0;
do
{
RockPaperScissors myRock = new RockPaperScissors();
player1 = JOptionPane.showInputDialog(null,
"Please enter your choice, Rock, Paper or Scissors");
myRock.setPlayer1(player1);
myRock.compute();
winner = myRock.getWinner();
player2 = myRock.getPlayer2();
if(winner.equals("Player 1"))
{
if(player2 == 1)
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"Congratulations, you have beaten the computer! The computer chose Scissors");
}
player1Wins = player1Wins + 1;
}
else if(winner.equals("Player 2"))
{
if(player2 == 1)
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer!The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"Hard Luck, you have been beaten by the computer! The computer chose Scissors");
}
player2Wins = player2Wins + 1;
}
else if(winner.equals("draw"))
{
if(player2 == 1)
{
JOptionPane.showMessageDialog(null,
"It was a draw this time! The computer chose Rock");
}
else if(player2 == 2)
{
JOptionPane
.showMessageDialog(null,
"It was a draw this time! The computer chose Paper");
}
else
{
JOptionPane
.showMessageDialog(null,
"It was a draw this time! The computer chose Scissors");
}
gamesPlayed = gamesPlayed + 0;
}
else
{
JOptionPane.showMessageDialog(null,
"You have entered an invalid option");
gamesPlayed = gamesPlayed - 1;
}
if(player1Wins == 2)
{
JOptionPane.showMessageDialog(null, "You win");
gamesPlayed = gamesPlayed + 2;
}
else if(player2Wins == 2)
{
JOptionPane.showMessageDialog(null, "He wins");
gamesPlayed = gamesPlayed + 2;
}
if((gamesPlayed == 2) || (gamesPlayed == 3))
{
JOptionPane.showMessageDialog(null, "The score is "
+ player1Wins + " for player1 and " + player2Wins
+ " for player2");
}
gamesPlayed = gamesPlayed + 1;
}
while(gamesPlayed <= 3);
}
}

Change your while loop condition:
while(player1Wins < 2 && player2Wins < 2)
Also, I would advise against using magic numbers; this is more maintainable:
public static final int VICTORY_THRESHOLD = 2;
.
.
.
while(player1Wins < VICTORY_THRESHOLD
&& player2Wins < VICTORY_THRESHOLD)
Also, consider creating an Enum for ROCK,PAPER,SCISORS. Then consider making a Comparator that takes the two Enums and returns -1 for losses, 0, for draw, and 1 for win.
public Enum RPS {
ROCK(),PAPER(),SCISSORS();
public int compare(RPS that) {
if(this==that)
return 0;
switch(this) {
case ROCK: return that==RPS.PAPER ? -1 : 1;
case PAPER: return that==RPS.SCISSORS ? -1 : 1;
case SCISSORS: return that==RPS.ROCK ? -1 : 1;
default: return null; /* never reached */
}
}
public String toString() {
switch(this) {
case ROCK: return "Rock";
case PAPER: return "Paper";
case SCISSORS: return "Scissors";
default: return null; /* never reached */
}
}
}
Using an Enum would make your conditional code much cleaner:
RPS player1Choice = RPS.ROCK;
RPS player2Choice = RPS.SCISSORS;
int result player1Choice.compare(player2Choice); /* 1 */
if(result == 0)
System.out.println("Draw, you both chose "+player1Choice);
else
System.out.println("You "+ (result > 0 ? "won" : "lost") +
" with "+player1Choice+
"\nThe computer chose"+player2Choice);
if(result != 0)
result > 0 ? ++player1Wins : ++player2Wins;
++gamesPlayed;

You said do... while(gamesPlayed <= 3) which means after 3 games have been played, the statement is still true, so it goes ahead and loops again.
To fix this, you can either change that 3 to a 2 or change the <= sign to a < sign.

Related

Returning two values to main method without arrays

Create a program named rockPaperScissors.java
The program should validate user input.
Game should ask the user to play again and continue if yes and stop if no.
Once the user stops playing, program should print the total number of wins for the computer and
for the user.
I am trying to learn programming from a book, so I am not good at this. I need to return the values of Cwin and Uwin to the main method, but I know how to return one value to it. I also have a problem with looping the question. I cannot use arrays and could only use the basic while loops (without the (true) and break).
import java.util.*;
public class rockPaperScissors
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Play again? Type yes or no.");
String YoN= input.next();
if (YoN.equalsIgnoreCase("yes"))
{
game();
}
else
{
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static void game()
{
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int choice = console.nextInt();
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int result = -1;
if (choice > 1 || choice < 3)
{
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
int comp = r.nextInt(3) + 1;
if (comp == 1)
{
System.out.println("Computer chose rock.");
}
if (comp == 2)
{
System.out.println("Computer chose paper.");
}
if (comp == 3)
{
System.out.println("Computer chose scissors.");
}
if (choice == 1 && result == 2)
{
Cwin++;
}
if (choice == 2 && result == 3)
{
Cwin++;
}
if (choice == 3 && result == 1)
{
Cwin++;
}
if (choice == 2 && result == 1)
{
Uwin++;
}
if (choice == 3 && result == 2)
{
Uwin++;
}
if (choice == 1 && result == 3)
{
Uwin++;
}
}
}
If you want to return multiple values from a method you may use an array that stores the values in its elements. Check here.
However for this program there is no need for returning 2 values(and you also said "I cannot use arrays"). Instead you can have 2 global variables that record the number of times the player wins and the number of times the computer wins respectively. Lets call them playerWinCount and computerWinCount.
Now that we got that down, lets look at how we allow the user to replay the game. You say that can use only "basic while loops". Fine. What we do is we declare a variable choice that holds the user's entry when prompted to replay. We initialise choice to true and then keep asking the user if he'd like to play again until he decides not to.
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
The playGame() method has the code to play the game.
The way we validate the user's entry is by using a length check. If the entry is out of range(i.e. from 1 to 3 inclusive) he'll be prompted to enter again.
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
Having acquired a valid user input, the next thing we do is get a random number as the computer's pick(you've done that). Then we check who won the game and increment the number of times the winner has won. We can do this using a number of if statements like this:
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
Or we can just combine the 3 conditions of winning with the OR operator(||) and use just 2 if statements:
if(playerPick != computerPick)
{
if((playerPick == 1 && computerPick == 3) || (playerPick == 3 && computerPick == 2) || (playerPick == 2 && computerPick == 1))
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else
{
computerWinCount++ ;
System.out.println("Computer won!");
}
}
else
{
System.out.println("It's a tie!");
}
And that's about it.
Here's the entire code:
import java.util.* ;
public class RockPaperScissors
{
static Scanner scanner = new Scanner(System.in) ;
static int playerWinCount, computerWinCount ;
public static void main(String[] args)
{
playerWinCount = 0 ;
computerWinCount = 0 ;
String choice = "yes" ;
while(choice.equalsIgnoreCase("yes"))
{
playGame() ;
System.out.print("Play again(Yes/No)? ") ;
choice = scanner.next() ;
}
System.out.println("\nNumber of times you won: " + playerWinCount) ;
System.out.println("Number of times computer won: " + computerWinCount) ;
System.out.println("Goodbye!") ;
}
public static void playGame()
{
System.out.println("") ;
Random random = new Random() ;
int playerPick = -1 ;
int computerPick = -1 ;
boolean valid = false ;
while(valid == false) // loop will run until a valid number is entered
{
System.out.print("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors: ") ;
playerPick = scanner.nextInt() ;
// validation of the user's entry
if(playerPick < 1 || playerPick > 3)
System.out.println("Invalid entry! Try again.") ;
else
valid = true ;
}
computerPick = random.nextInt(3) + 1 ;
System.out.println("The computer picked " + computerPick) ;
// first we check if the computer and player did not pick the same thing
if(playerPick != computerPick)
{
if(playerPick == 1 && computerPick == 3) // check if the player picked rock(1) and the computer picked scissors(3)
{
playerWinCount++ ;
System.out.println("Player won!") ;
}
else if(playerPick == 3 && computerPick == 2) // check if the player picked scissors(3) and the computer picked paper(2)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else if(playerPick == 2 && computerPick == 1) // check if the player picked paper(2) and the computer picked rock(1)
{
playerWinCount++ ;
System.out.println("Player won!");
}
else // otherwise, the computer has won this round
{
computerWinCount++ ;
System.out.println("Computer won!") ;
}
}
else
{
System.out.println("It's a tie!");
}
}
}
Let's go point by point.
You aren't taking the user input for determining the choice of playing in a while loop, so your game won't run more than once. You can take that input as:
while (true) {
System.out.println("Play again? Type yes or no.");
String YoN= input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game():
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
break;
}
}
If user gives input other than yes, you're trying to print Cwin and Uwin, but you haven't declared those variables in the scope of main method. So your program won't compile anyways.
You can keep global variables in the class running main method.
public static int Cwin = 0;
public static int Uwin = 0;
Update
I've gone through your code and found a few more problems. As far as I understand, you want to receive choice input from user and validate it in this segment:
if (choice > 1 || choice < 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
Well, this condition doesn't supports what you've printed inside, this choice > 1 || choice < 3 condition always gets true. Also, you haven't prompted to take the entry from the user again.
You can fix this issue as below:
while (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
choice = console.nextInt();
}
Then you're trying to make random choices for Computer. But you're selecting through upper bound and adding 1 to it. Why not set the bound to 1 more?
int comp = r.nextInt(4);
Then, finally, you're trying to compare the choice and the result. Where result was assigned -1 at the time of declaration and was never changed. That's why it'll never enter any if blocks and the Cwin and Uwin will always print 0. I bet you wanted comp here, in place of result. Also, I've tried to make the program more understandable to user while running.
if (choice == 1 && comp == 2) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 3) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 3 && comp == 1) {
Cwin++;
System.out.println("Computer wins!");
return;
}
if (choice == 2 && comp == 1) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 3 && comp == 2) {
Uwin++;
System.out.println("You win!");
return;
}
if (choice == 1 && comp == 3) {
Uwin++;
System.out.println("You win!");
return;
}
System.out.println("It's a draw!");
It will work as expected if you fix the aforementioned issues.
Note: I haven't refactored your code, I've just pointed out the problems and fixed it without modifying it much. It can be made lot more better than the current condition. Let's keep the topic for another day's question.
I modify your code somewhat.
You mention in a comment that you don't want to use an array and static variable.
so, I tried some different method hope It will help you.
It is fully working code
import java.util.*;
public class rockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome To Rock Paper scissors Game Type yes to continue or no for close.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
game();
} else if(YoN.equalsIgnoreCase("yes")) {
System.out.println("Thank You");
}else {
System.out.println("Enter valid input");
}
}
public static void game() {
int Uwin = 0;//user win count
int Cwin = 0;//computer win count
int tie = 0;//Tie count
while (true) {
Scanner input = new Scanner(System.in);
System.out.println("Are you sure!!! Want to continue? Type yes or no.");
String YoN = input.nextLine();
if (YoN.equalsIgnoreCase("yes")) {
Scanner console = new Scanner(System.in);
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
int choice = console.nextInt();
int result = (int) (Math.random()*(3-1)) + 1;
if (choice < 1 || choice > 3) {
System.out.println("Invalid entry. Please type 1, 2, or 3.");
}
if((choice == 1 && result == 3) || (choice == 2 && result == 1) || (choice == 3 && result == 2)) {
System.out.println("Computer Choose"+result);
Uwin++;
}else if((choice == 1 && result == 2) || (choice == 2 && result == 3) || (choice == 3 && result == 1)) {
System.out.println("Computer Choose"+result
);
Cwin++;
}else {
System.out.println("Computer Choose"+result);
tie++;
}
} else if(YoN.equalsIgnoreCase("no")) {
System.out.println("Computer wins: " + Cwin + "\nUser wins: " + Uwin+"\nTie: "+tie);
System.out.println("Thank you");
break;
}else {
System.out.println("Enter valid input");
}
}
}
}
Track the score separately from the individual game
It looks you've written your game() method to play a single game of Rock, Paper, Scissors. In that case, you only need to return one value: who won that single game. Then your main method can keep track of the current scores and print out the totals after it's all done.
Consider an approach like the following:
import java.util.*;
public class rockPaperScissors {
public final static int USER_WON = 1; // Added these constants
public final static int COMPUTER_WON = 2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Uwin = 0;// user win count // Moved from `game()`
int Cwin = 0;// computer win count // Moved from `game()`
System.out.println("Play again? Type yes or no.");
String YoN = input.next();
if (YoN.equalsIgnoreCase("yes")) {
int winner = game(); // Modified this line
if (winner == USER_WON) { // Added this section
Uwin++;
} else {
Cwin++;
}
} else {
System.out.println("Computer wins: " + Cwin + "/nUser wins: " + Uwin);
}
}
public static int game() { // Modified this line
System.out.println("Choose rock, paper, or scissors. Type 1 for rock, 2 for paper, and 3 for scissors.");
Scanner console = new Scanner(System.in);
//// Truncating for brevity ////
if (choice == 3 && result == 1) {
return COMPUTER_WON; // Modified this line
}
if (choice == 2 && result == 1) {
return USER_WON; // Modified this line
}
//// Truncating for brevity ////
}
}
Notice that I moved the Uwin and Cwin variables out of game() and into your main method. Then I changed game() to return an integer instead of nothing (void) and replaced the Cwin++ and Uwin++ statements with a simple return COMPUTER_WON or return USER_WON based on the results of the rock, paper, scissors match. That return value can then be processed in your main method to keep a running total of how many games each player has won.
Use a class
If you're interested in trying something more advanced, consider creating an Object to encapsulate the two values you want to return.
For example, by storing both win counts in a simple Scoreboard object like the one below would enable you to return the two win counts at the same time and encapsulate the process of printing the scoreboard to the screen.
If you go this route, you'd have to make sure that all games reference the same Scoreboard. There are a variety of ways to do this from using a class variable, to passing the Scoreboard as a function parameter to the game() method, to moving all your logic for playing multiple games into the game() method. There are lots of options for you to try out and see which works best for you in this situation.
public class Scoreboard {
private int computerWins;
private int playerWins;
public Scoreboard() {
computerWins = 0;
playerWins = 0;
}
public void addComputerWin() {
computerWins++;
}
public void addPlayerWin() {
playerWins++;
}
#Override
public String toString() {
return "Scoreboard: "
+ "\n - Computer wins: " + computerWins
+ "\n - Player wins: " + playerWins;
}
}

Choosing Between 2 games in one code

I am doing a project to make a user login, then ask the user to select which game to play, then write the code for the game. I have done everything apart from being able to choose to between the 2 games. Any tips on how to do this would greatly help!
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.io.InputStreamReader;
public class SkillsDemo31 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
//******************************
//Rock,Paper,Scissors
//********************************
Random rnd = new Random();
int input;
int score = 0;
int B = 1;
System.out.println("Pick 1,2, or 3 for:");
System.out.println("Rock (1), Paper(2), or Scissors (3)");
while (B != 0) {
// 1 = rock
// 2 = paper
// 3 = scissors
// N= Integer.parseInt(br.readLine())
int Rock = 1, Paper = 2, Scissor = 3;
input = Integer.parseInt(br.readLine());
int randomNumber = rnd.nextInt(3 - 1 + 1) + 1;
if (randomNumber == Rock) {
if (input == Rock) {
System.out.println("Rock Vs. Rock: Tie");
} else if (input == Paper) {
System.out.println("Paper Vs. Rock: You Win!");
System.out.println("Congratulations!");
score++;
} else if (input == Scissor) {
System.out.println("Scissors Vs. Rock: You Lose");
}
} else if (randomNumber == Paper) {
if (input == Rock) {
System.out.println("Rock Vs. Paper: You Loose");
} else if (input == Paper) {
System.out.println("Paper Vs. Paper: Tie");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Paper: You Win");
System.out.println("Congratulations!");
score++;
}
} else if (randomNumber == Scissor) {
if (input == Rock) {
System.out.println("Rock Vs. Scissors: You Win");
System.out.println("Congratulations!");
score++;
} else if (input == Paper) {
System.out.println("Paper Vs. Scissors: You Loose");
} else if (input == Scissor) {
System.out.println("Scissors Vs. Scissors: Tie");
}
}
int Y=5, N=10;
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press(5) For Yes/(10) For No");
input = Integer.parseInt(br.readLine());
if(input==Y){
B=1;
System.out.println("Rock, Paper,Scissors");
}
else if(input==N)
{System.exit(0);
System.out.println("Have A Good Day!");
}
//***********************
//Pick Up Sticks
//***********************
Scanner scanner = new Scanner(System.in);
while (true) {
int numSticks = 21;
System.out.println("Would You Like to go first? (Yes/No)");
Scanner input1 = new Scanner(System.in);
String goFirst = input1.nextLine();
Scanner take = new Scanner (System.in);
int numToTake = 0;
int score2 = 0;
while (numSticks > 0) {
if (goFirst.equals("Yes") || goFirst.equals("yes")) {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1) {
numToTake = 1;
}
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You lose");
System.out.println("Your score is " + score );
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println(" You win ");
score++;
System.out.println("Your score is " + score );
}
}
}
else {
if((numSticks - 2) % 3 == 0 || numSticks - 2 == 0) {
numToTake = 1;
}
else {
numToTake = 2;
}
System.out.println("Computer takes " + numToTake + " sticks " );
numSticks = numSticks - numToTake;
if (numSticks <= 0) {
System.out.println("You win");
score++;
System.out.println("Your score is " + score );
}
else {
System.out.println("There are " + numSticks + " sticks ");
System.out.println("How many sticks do you want to take (1 or 2)");
numToTake = take.nextInt();
if (numToTake > 2) {
numToTake = 2;
}
else if (numToTake < 1){
numToTake = 1;
}
numSticks = numSticks - numToTake;
if(numSticks <0){
System.out.println("You win");
score++;
}
}
}
}
System.out.println("Do you want to play again, type (5) for yes or (10) for no");
if (scanner.nextLine().equals("10")) {
break;
}
}
}
}
}
You should create for every game a class and create a start method there to start the game based on your user input for example:
System.out.println("Please type 1 for game 1 or 2 for game2:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to game 1");
Game1 game1 = new Game1();
game1.start();
}
else if (action == 2)
{
System.out.println("\nYou have chosen game 2");
Game2 game2 = new Game2();
game2.start();
}
This code is based on your code.
Bob, I just check through your code.
According to what I saw, my understanding of your question is that "After user login and selected the game type, both game would run subsequently, while you only want to run the game user chose".
If that is the case, then the solution is easy:
Take the games code parts out from the
while(again){
// In this block, only keeps your user choice code.
}
block. That block would be just for getting user's choice.
After that choice block, you get your users' choice from variable "action". Now you just need to add a if block as below:
if(action == 1){
// Put your Rock,Paper,Scissors game code here, as user chose 1
//******************************
//Rock,Paper,Scissors
//********************************
...
}else if(action == 2){
// Put your Pick Up Sticks game code here, as user chose 2.
//***********************
//Pick Up Sticks
//***********************
...
}
As you only want to run one game at a time, you need a "IF" condition to tell the code which game to run.
So just "IF" is enough, but separating the "Choice" part and "Game" part, from my opinion, would make the code more simpler and easier to be understood.

Rock Paper Scissors simple java using methods

So my task today is to make a rock paper scissors game using methods. My first problem with my code is that I need it to ask the user if they want to play again or not. (y or n) Also, I need to implement scoring, 1 point if user wins, -1 if they lose, and for each time they play again add that score to total score. Any ideas on how to implement this? or what I need to change to my code. Also I am a rookie so sorry for the ugly formatting and feel free to critic every little detail, ill soak up all the information I can.
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice( ){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo( "Rock" ) == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0 ){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
a output that my professor gave us as an example is:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
Here is the finished code. I added two functions, one to call the actual game and one to check if the player wanted to play again. Also, there is the concluding sentence in the end
import java.util.Random;
import java.util.Scanner;
public class RPC
{
public static Scanner sc = new Scanner(System.in);
public static int score = 0;
public static int gameCount = 0;
public static void main(String[] args)
{
play();
while (playAgain())
{
play();
}
}
public static void play()
{
String computer = computerChoice();
String user = userChoice();
determineWinner(computer, user);
}
public static String computerChoice()
{
Random rand = new Random();
int cinput = rand.nextInt(3) + 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static boolean playAgain()
{
System.out.println("Play again?(y/n)");
String input = sc.nextLine();
if (input.toLowerCase().equals("y"))
{
return true;
} else if (input.toLowerCase().equals("n"))
{
return false;
} else
{
System.out.println("Invalid Input");
return playAgain();
}
}
public static String userChoice()
{
String user = "default";
do
{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
} while (!isValidChoice(user));
return user;
}
public static boolean isValidChoice(String choice)
{
boolean status;
if (choice.equals("Rock"))
status = true;
else if (choice.equals("Paper"))
status = true;
else if (choice.equals("Scissors"))
status = true;
else
{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static void determineWinner(String computer, String user)
{
gameCount++;
System.out.println(" Computer Choice: " + computer);
System.out.println("Your Choice : " + user);
if (computer.equals("Rock") && user.equals("Scissors"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Scissors") && user.equals("Paper"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Paper") && user.equals("Rock"))
{
score--;
System.out.println(" Computer wins! Better luck next time!");
}
if (computer.equals("Rock") && user.equals("Paper"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Scissors") && user.equals("Rock"))
{
score++;
System.out.println(" You win!!");
}
if (computer.equals("Paper") && user.equals("Scissors"))
{
score++;
System.out.println(" You win!!");
} else if (computer.equals(user))
{
System.out.println(" Tie! the game must be played again.");
}
System.out.println("We have matched wits" + gameCount + "times, and your score is" + score);
return;
}
}

A more efficient way that takes less space? this is a method btw

Here's part of a code for a Rock Paper Scissors project and im just wondering if there is a way to do this that takes up less space. Preferably more efficient too. Basically this is a method and what this method does is compare user inputs to see if one side beats the other.
Thanks.
public String determineWinner()
{
String winner = "yolo"; //if fail
if(compChoice.equals("S") && (playChoice.equals("s")))
{
winner = "nobody. There was a tie because you guessed the same thing.";
}
if(compChoice.equals("P") && (playChoice.equals("p")))
{
winner = "nobody. There was a tie because you guessed the same thing.";
}
if(compChoice.equals("R") && (playChoice.equals("r")))
{
winner = "nobody. There was a tie because you guessed the same thing.";
}
if(compChoice.equals(playChoice)) //R R, R P, R S
{
winner = "nobody. There was a tie because you guessed the same thing.";
}
if(compChoice.equals("R") && (playChoice.equals("P") || playChoice.equals("p"))) //R P
{
winner = "player because Paper beats Rock.";
}
if(compChoice.equals("R") && (playChoice.equals("S") || playChoice.equals("s"))) //R S
{
winner = "computer because Rock beats Scissors.";
}
if(compChoice.equals("P") && (playChoice.equals("R") || playChoice.equals("r")))//P R
{
winner = "computer because Paper beats Rock.";
}
if(compChoice.equals("P") && (playChoice.equals("S") || playChoice.equals("s")))//P S
{
winner = "player because Scissors beats Paper.";
}
if(compChoice.equals("S") && (playChoice.equals("R") || playChoice.equals("r"))) //S R
{
winner = "player because Rock beats Scissors.";
}
if(compChoice.equals("S") && (playChoice.equals("P") || playChoice.equals("p"))) //S P
{
winner = "computer because Scissors beats Paper.";
}
return winner;
}
You can do this
String[] words = "Rock,Paper,Scissors".split(",");
// turn the choice into an index where higher wins.
// i.e. 0 < 1 < 2 < 0 (using clock arithmetic)
int human = "RPS".indexOf(playChoice.toUpperCase());
int comp = "RPS".indexOf(compChoice.toUpperCase());
// if the index is the same, no winner
if (human == comp)
return "No winner, choices are the same";
// if the human has the higher index (using clock arithmetic), the human wins.
if (human == (comp+1) % 3)
return "Human winner as " + words[human] + " beats " + words[comp];
// otherwise the computer must have won.
return "Computer winner as " + words[comp] + " beats " + words[human];
String winner = "";
String playersChoice = playChoice.toUpperCase();
if(compChoice.equals(playersChoice))
return "tie";
switch(compChoice) {
case "S":
switch(playersChoice) {
case "P":
winner = "computer";
break;
case "R":
winner = "player";
break;
}
break;
case "P":
switch(playersChoice) {
case "S":
winner = "player";
break;
case "R":
winner = "computer";
break;
}
break;
case "R":
switch(playersChoice) {
case "S":
winner = "computer";
break;
case "P":
winner = "player";
break;
}
break;
}
return winner;
for more efficient I would suggest you to go for nested if else statements instead of only if statements like
if {} else{if(){} else{....}}
In your code each and every if loop will be executed which decreases the efficiency so use nested if else
Useful link for nested if else
You can use more efficient char comparison
char cc = compChoice.charAt(0);
char pc = playChoice.charAt(0);
if (cc == 'S' && pc == 's') {
...
} else if (
...
JqueryLearner is right, but you get a much cleaner if-else if you do this:
if () {
} else if () {
} else if () {
} else {
}
You need to think more about general rules and simplification and less about the specifics.
For example if you took the input and put it to lowercase you then just need to check for r, s etc rather than R, S as well.
If you then check for the two being equal (you don't care if its r and r, or s and s - you just need them to be the same) that handles all the draws.
You then just need to check r > s > p > r.
You can have an if clause for checking if both computer and player choices are same, for eg:
if(compChoice.equalsIgnoreCase(playerChoice)){
return "TIE"
}
Note i used ignoreCase to avoid your multiple if for lower and upper cases.
OR
Create an array for options : [ paper, rock, scissors]
Now paper beats rock, rock beats scissors and scissors beats paper.
You would have to calculate index of comp and player choice from this array and then use following formula for result:
int result = (playerChoiceNum - compChoiceNum) % 3
playerChoiceNum and compChoiceNum are indexes from array.
If result is 0 it is tie,else if result is negative comp wins and else result is positive player wins.
How about using an enum here's the entire game...
public static enum RPS {
ROCK, PAPER, SCISSORS;
// Simple method to get the appropriate enum.
public static RPS fromString(String in) {
if (in.toLowerCase().startsWith("r")) {
return ROCK;
} else if (in.toLowerCase().startsWith("p")) {
return PAPER;
} else if (in.toLowerCase().startsWith("s")) {
return SCISSORS;
}
return null;
}
// Calculate the winner in a contest.
public Boolean wins(RPS in) {
if (this == in) { // Tie!
return null;
}
switch (this) {
case ROCK:
if (in == SCISSORS) { // Rock beats scissors.
return true;
}
return false;
case PAPER:
if (in == ROCK) { // Paper beats rock.
return true;
}
return false;
case SCISSORS:
if (in == PAPER) { // Scissors beats paper.
return true;
}
return false;
}
return null;
}
}
public static void main(String[] args) {
Random r = new Random(System.currentTimeMillis());
String[] choices = new String[] { "R", "P", "S" };
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
System.out.println("Please enter (R)ock, (P)aper "
+ "or (S)cissors to play. (Q)uit.");
String c = in.nextLine();
c = c.trim();
if (c.toLowerCase().startsWith("q")) {
break;
}
RPS player = RPS.fromString(c);
RPS computer = RPS.fromString(choices[r
.nextInt(choices.length)]);
System.out.println("Computer picked " + computer);
if (player.wins(computer) == null) {
System.out.println("It's a Tie");
} else if (player.wins(computer)) {
System.out.println("You won");
} else {
System.out.println("The comptuer won");
}
}
}
ok first your question is misleading
but
if you use .equalsIgnoreCase() This will allow you you to check for both,
'P' and 'p' for paper so it stops you have to check both 'P' and 'p'.
The if and else if would work better here as:
if a statement is not true it will go to the else if to check if this is true and if this is not true it will move on to the next statement to see which is true.
The else then says that if none of the above if and else ifs are true it has to be this option.
if(compChoice.equalsIgnoreCase(playChoice)) //R R, R P, R S
{
winner = "nobody. There was a tie because you guessed the same thing.";
}
else if(compChoice.equals("R") && (playChoice.equalsIgnoreCase("P"))) //R P
{
winner = "player because Paper beats Rock.";
}
else if(compChoice.equals("R") && (playChoice.equalsIgnoreCase("S"))) //R S
{
winner = "computer because Rock beats Scissors.";
}
else if(compChoice.equals("P") && (playChoice.equalsIgnoreCase("R")))//P R
{
winner = "computer because Paper beats Rock.";
}
else if(compChoice.equals("P") && (playChoice.equalsIgnoreCase("S")))//P S
{
winner = "player because Scissors beats Paper.";
}
else if(compChoice.equals("S") && (playChoice.equalsIgnoreCase("R"))) //S R
{
winner = "player because Rock beats Scissors.";
}
else//S P
{
winner = "computer because Scissors beats Paper.";
}
return winner;
Thats as short and efficient I can make it.
This works as well
public String determineWinner() {
Map<String, String> shortcutMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
Map<String, Map<String, Integer>> winMap = new TreeMap<String, Map<String, Integer>>(String.CASE_INSENSITIVE_ORDER);
shortcutMap.put("R", "Rock");
shortcutMap.put("P", "Paper");
shortcutMap.put("S", "Scissors");
winMap.put("R", new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER));
winMap.put("P", new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER));
winMap.put("S", new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER));
winMap.get("R").put("R", 0); // Rock draw against Rock,
winMap.get("R").put("P", -1); // Rock loose against Paper,
winMap.get("R").put("S", 1); // Rock win against Scissors,
winMap.get("P").put("R", 1); // Paper win against Rock,
winMap.get("P").put("P", 0); // Paper draw against Paper,
winMap.get("P").put("S", -1); // Paper loose against Scissors,
winMap.get("S").put("R", -1); // Scissors loose against Rock,
winMap.get("S").put("P", 1); // Scissors win against Paper,
winMap.get("S").put("S", 0); // Scissors draw against Scissors,
String winner = "yolo"; // if fail
Integer result = winMap.get(compChoice).get(playChoice);
if (result > 0) {
winner = "computer because " + shortcutMap.get(compChoice) + " beats " + shortcutMap.get(playChoice) + ".";
}
else if (result < 0) {
winner = "player because " + shortcutMap.get(playChoice) + " beats " + shortcutMap.get(compChoice) + ".";
}
else {
winner = "nobody. There was a tie because you guessed the same thing.";
}
return winner;
}

How to fix the computerChoice always choosing rock which is integer 1

I'm trying to get a random number using the Random().nextInt() function. I don't know if it's right or if my logic is messed up or not reading right. Also for loop isn't working the way that it's suppose to be working. Can you please help? I'm trying to finish an assignment for class since we started Java like last month.
//DECLARE VARIABLES
String rounds, userChooses;
Random computerChooses = new Random();
int round = 1;
int userChoice = 0;
final int ONE = 1;
final int TWO = 2;
final int THREE = 3;
int computerChoice = computerChooses.nextInt(3) + 1;
//ASK USER FOR NUMBER OF ROUNDS
rounds = JOptionPane.showInputDialog(null, "How many rounds do you want to play?");
round = Integer.parseInt(rounds);
//TRACK NUMBER OF ROUNDS
for (int x = 1; x <= round; x++) {
JOptionPane.showMessageDialog(null, "This is round " + x + ".");
//CREATE THE INPUT FOR THE USER
try {
//START GAME
userChooses = JOptionPane.showInputDialog(null, "Enter 1)rock, 2)paper, or 3)scissors!");
userChoice = Integer.parseInt(userChooses);
if (userChoice > 3 || userChoice < 1) {
throw new Exception();
}
} catch (Exception ex) {
JOptionPane.showInputDialog(null, "That wasn't a number!", "Error!", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "You have not entered correct number! Terminating program!");
System.exit(0);
}
if (userChoice == ONE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You tied the computer.\nYou chose: rock\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: rock\nComputer chose: paper");
} else if (computerChoice == THREE){
JOptionPane.showMessageDialog(null, "You won!\nYou chose: rock\nComputer chose: scissors");
}
} else if (userChoice == TWO) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: paper\nComputer chose: rock");
} else if (userChoice == TWO) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: paper\nComputer chose: paper");
} else if (userChoice == THREE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: paper\nComputer chose: scissors");
}
} else if (userChoice == THREE) {
if (computerChoice == ONE) {
JOptionPane.showMessageDialog(null, "You lost!\nYou chose: scissors\nComputer chose: rock");
} else if (computerChoice == TWO) {
JOptionPane.showMessageDialog(null, "You won!\nYou chose: scissors\nComputer chose: paper");
} else if (computerChoice == THREE) {
JOptionPane.showMessageDialog(null, "You tied!\nYou chose: scissors\nComputer chose: scissors");
}
}
}
}
Every time I choose something, it says that the computer always chooses the rock option. Any idea?
Simply by using a Random object:
new Random().nextInt(3) + 1;
As for your for-loop, the closing brace should be put after your catch Exception-block and not after: JOptionPane.showMessageDialog(null, "This is round " + round + ".");
Here is something that seems to work better:
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class RockPaperScissors {
private static final int ROCK = 1;
private static final int PAPER = 2;
private static final int SCISSORS = 3;
private Random computerChooses = new Random();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RockPaperScissors().play();
}
});
}
protected void play() {
String rounds;
String userChooses;
int round = 0;
int userChoice;
// CREATE THE INPUT FOR THE USER
try {
rounds = JOptionPane.showInputDialog(null, "How many rounds do you want to play?");
round = Integer.parseInt(rounds);
// CREATE COUNTER
for (int x = 0; x < round; x++) {
int computerChoice = computerChooses.nextInt(3) + 1;
JOptionPane.showMessageDialog(null, "This is round " + x + ".");
// START GAME
userChooses = JOptionPane.showInputDialog(null, "Enter 1)rock, 2)paper, or 3)scissors!");
userChoice = Integer.parseInt(userChooses);
String message = null;
switch (userChoice) {
case ROCK:
switch (computerChoice) {
case ROCK:
message = "You tied computer. You both chose rock";
break;
case PAPER:
message = "You win.";
break;
case SCISSORS:
message = "You loose";
break;
}
break;
case PAPER:
switch (computerChoice) {
case ROCK:
message = "You win.";
break;
case PAPER:
message = "You tied computer. You both chose paper";
break;
case SCISSORS:
message = "You loose";
break;
}
break;
case SCISSORS:
switch (computerChoice) {
case ROCK:
message = "You loose";
break;
case PAPER:
message = "You win";
break;
case SCISSORS:
message = "You tied computer. You both chose scissors";
break;
}
break;
}
JOptionPane.showMessageDialog(null, message);
}
} catch (Exception ex) {
JOptionPane.showInputDialog(null, "That wasn't a number!", "Error!", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "You have not entered correct number! Terminating program!");
System.exit(0);
}
}
}

Categories