Rock Paper Scissors Lizards Spock - java

I need to print the number of user wins, losses, and ties in a program. It took me forever to resolve the looping issue, but I finally got it. I am new to Java, but have coded in HTML and other scripting languages before.
import java.io.InputStream;
import java.util.Random;
import java.util.Scanner;
public class RPSLS {
//AUTHOR: JOSEPH CLAY
//TODO make program continue until user chooses to stop.
//TODO then print # of user wins, losses, and ties.
public static void main(String[] args) {
//declare objects
String user;
String comp= "";
Random comprand;
String answer=null;
do
{
//scanner and random setup and imported
Scanner scan=new Scanner(System.in);
//Random gen=new Random();
//prompt to play game/instructions
System.out.println("Yo, let's play a game of Rock, Paper, Scissors, Lizard, Spock");
System.out.println("Please enter R for rock, P for paper, S for scissors, L for lizard, or V for Spock");
//User selection input
System.out.println("Pick your poison: ");
user=scan.next();
//Randomly generated # of 5
System.out.println();
comprand=new Random();
int x=comprand.nextInt(5)+1;
//translate random # to string
if(x==1)
comp="R";
else if(x==2)
comp="P";
else if(x==3)
comp="S";
else if(x==4)
comp="L";
else if(x==5)
comp="V";
//capitalize user selection
user=user.toUpperCase();
//print computer choice
System.out.println("Your adversary chose: "+comp);
//conditions of possible outcomes
//tie
if (user.equals(comp))
System.out.println("Tie!");
//if user enters r
else if (user.equalsIgnoreCase("R"))
if (comp.equals("S"))
System.out.println("Rock crushes scissors. You win!");
else if (comp.equals("P"))
System.out.println("Paper envelopes rock. You lose.");
else if (comp.equals("L"))
System.out.println("Rock destroys lizard. You win!");
else if (comp.equals("V"))
System.out.println("Spock crushes rock. You lose.");
//if user enters p
if (user.equalsIgnoreCase("P"))
if (comp.equals("R"))
System.out.println("Paper envelopes rock. You win!");
else if (comp.equals("S"))
System.out.println("Scissors cuts paper. You lose");
else if (comp.equals("L"))
System.out.println("Lizard eats paper. You lose.");
else if (comp.equals("V"))
System.out.println("Paper disproves Spock. You win!");
//if user enters s
if (user.equalsIgnoreCase("S"))
if (comp.equals("R"))
System.out.println("Rock crushes scissors. You lose.");
else if (comp.equals("P"))
System.out.println("Scissors cuts paper. You win!");
else if (comp.equals("L"))
System.out.println("Scissors eviscerates lizard. You win!");
else if (comp.equals("V"))
System.out.println("Spock vaporizes scissors. You lose.");
//if user enters l
if (user.equalsIgnoreCase("L"))
if (comp.equals("R"))
System.out.println("Rock crushes lizard. You lose.");
else if (comp.equals("P"))
System.out.println("Lizard eats paper. You win!");
else if (comp.equals("S"))
System.out.println("Scissors eviscerate lizard. You lose.");
else if (comp.equals("V"))
System.out.println("Lizard poisons Spock. You win!");
//if user enters v
if (user.equalsIgnoreCase("V"))
if (comp.equals("R"))
System.out.println("Spock crushes rock. You win!");
else if (comp.equals("P"))
System.out.println("Paper disproves Spock. You lose!");
else if (comp.equals("S"))
System.out.println("Spock vaporizes scissors. You win!");
else if (comp.equals("L"))
System.out.println("Lizard poisons Spock. You lose.");
System.out.println("Would you like to continue? (yes or no)");
answer = scan.next();
}
while(answer.equals("y"));
while (answer.equalsIgnoreCase("n"))
break;
}
}

Per your comments on your question, here is how you could implement keeping track of how many wins, losses, and ties the user has.
You declare variables to track each before you start your do loop. Since you want to count them I'd suggest a simple integer variable for each:
int wins = 0;
int losses = 0;
int ties = 0;
Then inside your loop you increment each counter when that situation occurs. For example:
if (comp.equals("R")){
System.out.println("Spock crushes rock. You win!");
wins++;
}
else if (comp.equals("P")){
System.out.println("Paper disproves Spock. You lose!");
losses++;
}
After your loop ends, i.e. after your while you then print these numbers.
while(answer.equals("y"));
System.out.println("You won "+wins+" times");
System.out.println("You lost "+losses+" times");
System.out.println("You tied "+ties+" times");
Lastly, some code review items for you. You generally never want to write code like this:
while(answer.equals("y"));
The reason is that if answer is null this will throw a NullPointerException at runtime. It's safer to write:
while("y".equals(answer));
In the code above "y" can never be null so you will never have a NullPointerException thrown by this code.
Secondly, hardcoding all of the possible scenarios is not the most efficient and maintainable way to write your program. Instead if you think in terms of objects (and you should since Java is an object oriented language) you could create an object to represent each possible choice and each object can contain others of its kind representing which choices will defeat it. Then you can simply do something like this:
if(userChoice.defeats(computerChoice)){
//handle user win here
}else if(computerChoice.defeats(userChoice){
//handle computer win here
}else{
//handle tie here
}
Hope this helps you!

Related

if else block is not printing out statement for rock paper scissors game

hey all I'm trying to figure out what I'm doing wrong here. I have been making a rock paper scissors game in java through netbeans IDE. I know Ive seen alot of questions regarding this but in my if else statements I am trying to get it to print out some statements if a condition is met. It does it if player 1 throws rock and player two throws anything, including a tie, but anything else than that is not printing out the statement when ran. my code is below, know you guys like specific question and smaller sections of code but i feel the need to post the full code to see where I went wrong. if that makes sense! thanks for any help.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String personPlay; //Player A -- "R", "P", or "S"
String secondUser; //Player B
Scanner scan = new Scanner(System.in);
System.out.println("Player 1Please enter your name");
String name1;
name1 = scan.next();
System.out.println("Hello " + name1);
System.out.println("Hello Player 2");
System.out.println("Player 2 Please enter your name");
String name2;
name2 = scan.next();
System.out.println("Hello "+name2);
System.out.println(name1 + " enter r for Rock, p for Paper, s for Scissors: "); //Get player's play -- note that this is stored as a string
personPlay = scan.next();
personPlay = personPlay.toLowerCase();
System.out.println(name2 + " enter r for Rock, p for Paper, and s for Scissors");
secondUser = scan.next();
secondUser = secondUser.toLowerCase();
if (personPlay.equals(secondUser)) {
System.out.println("It's a tie!");
} else if (personPlay.equals("r")) {
if (secondUser.equals("s")) {
System.out.println("Rock beats scissors! Victory to "+name1);
} else if (secondUser.equals("p")) {
System.out.println("Paper beats Rock! Victory to "+name2);
} if (personPlay.equals("p")) {
if (secondUser.equals("s")) {
System.out.println("Scissors cut Paper! Victory to "+name2);
} else if (secondUser.equals("r")) {
System.out.println("Paper covers rock! Victory to "+name1);
} if (personPlay.equals("s")) {
if (secondUser.equals("p")) {
System.out.println("Scissors beat paper! Victory to "+name1);
}
} else if (secondUser.equals("r")) {
System.out.println("Rock beats Scissors! Victory to "+name2);
}
}
}
}
}
Your conditions that check if the person threw paper ("p") or scissors ("s") or nested inside the condition that the person threw rock ("r") and thus will never be true.
You need to check if the person threw paper or scissor in separate else if cases after you've checked for rock.
} else if (personPlay.equals("r")) {
if (secondUser.equals("s")) {
System.out.println("Rock beats scissors! Victory to "+name1);
} else if (secondUser.equals("p")) {
System.out.println("Paper beats Rock! Victory to "+name2);
}
} else if (personPlay.equals("p")) {
// Test second user is rock and scissors here
} else if (personPlay.equals("s")) {
// Test second user is paper and rock here
}
You should also add some validation checks so that the entries made by both players are limited to the 3 legal choices.

Please, how do I get the code to terminate after two computer or user wins

Please, how do I get my code to terminate after two wins by either the computer or the user? I am asked to write a program that plays the popular scissor-rock-paper game. (A scissor can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. The user is expected to continuously play until either the user or the computer wins more than two times. Unfortunately, the code game doesn't end after more than two wins.
Thank you.
package scissors;
import java.util.Scanner;
public class Scissors {
public static void main(String[] args) {
//generate random number
int count=0;
int computerWin=0;
int youWin= 0;
while (computerWin <2 || youWin<2){
int computer = (int)(Math.random()*3);
// prompt user for input
Scanner s = new Scanner(System.in);
System.out.println("Enter a number; scissor(0),rock(1), paper(2): ");
int you = s.nextInt();
switch(computer){
case 0:
if(you==0){
System.out.println("The computer is scissor and you are scissor. It's a Draw");
}
else if (you==1){
System.out.println("The computer is scissor and you are rock. You won");
youWin++;
}
else if (you==2){
System.out.println("The computer is scissor and you are paper. You lost");
computerWin++;
}
break;
case 1:
if(you==0){
System.out.println("The computer is rock and you are scissor. You lost");
computerWin++;
}
else if (you==1){
System.out.println("The computer is rock and you are rock. It's a Draw");
}
else if(you==2){
System.out.println("The computer is rock and you are paper. You won");
youWin++;
}
break;
case 2:
if (you==0){
System.out.println("The computer is paper and you are scissor. You won");
youWin++;
}
else if (you==1){
System.out.println("The computer is papare and you are rock. You lost");
computerWin++;
}
else if (you==2){
System.out.println("The computer is paper and you are paper. It's a draw");
}
break;
}
if (computerWin>youWin)
System.out.println("Computer wins");
else
System.out.println("You win");
}
}
}
Right now, the player and computer share a counter. If the player wins, the counter goes up. If the computer wins, it goes down. This does not track how many wins each one has.
You need a variable to count how many wins a player has for both the user and the computer.
int userPoints = 0, compPoints = 0;
while(userPoints < 2 || compPoints < 2) {
//..
}
if(compPoints > userPoints) {
//computer won
} else {
//user won
}
When the computer wins, add one to compPoints. When the user wins, add one to userPoints
The bug in your code is the while statement:
while (count<=2 || count<=-2)
In this case it runs anytime that count <= 2 because the second condition says count <= -2 instead of >= -2, but it looks like you want it to run only if count is between 2 and negative 2. Also, you probably don't want it to be inclusive (<=) since you want it to break when one person wins 2 more than the other person. So, you want your loop to definition to look like:
while (count<2 || count>-2)
Just change to while (computerWin <2 && youWin<2){.
Your code should iterate while computer and you have less then 2 wins (not or). When any of players have 2 or more wins iteration should be broken.

Not equal to conditions in while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to Java and am building a Rock, Paper, Scissors game. I am trying to figure out why my while statement will not recognize the correct input on the first try. Thank you for any help in advance.
`
import java.util.Scanner;
import java.util.Random;
public class RPC
{
public static void main (String[] args)
{
//Utilities
Scanner in = new Scanner (System.in);
Random r = new Random ();
//variables
int userwins =0;
int computerwins =0;
int numberofgames = 0;
int randomnumber = 0;
String userpick = "";
String computerpick = "";
// Welcome statement
System.out.println("Welcome to Rock, Paper, Scissors!");
//Get the number of games from the user
System.out.println("Please enter the number of rounds you would like to play:");
numberofgames = in.nextInt();
//Flush the buffer
in.nextLine();
// Game play for the number of times the user specified.
for (int i=1; i <= numberofgames; i++)
{
System.out.println("Rock, Paper, or Scissors?:");
userpick = in.nextLine();
while (!userpick.equalsIgnoreCase("rock") && !userpick.equalsIgnoreCase("paper") && !userpick.equalsIgnoreCase("scissors"));
{
System.out.println("Sorry," +userpick+ " is not a valid entry.Please enter Rock, Paper, or Scissors.");
userpick = in.nextLine();
}
//Make a random choice
randomnumber = r.nextInt(3)+1;
if (randomnumber == 1)
{
computerpick = ("rock");
}
if (randomnumber == 2)
{
computerpick = ("paper");
}
if (randomnumber == 3)
{
computerpick = ("scissors");
}
//Decide who wins the round
if (userpick.equalsIgnoreCase("rock")) {
if (computerpick.equalsIgnoreCase("scissors"))
System.out.println("Rock beats scissors. You win!");
else if (computerpick.equalsIgnoreCase("paper"))
System.out.println("Paper beats rock. The computer wins!");
else
System.out.println("Computer chooses rock. It's a tie.");
}
else if (userpick.equalsIgnoreCase("paper")) {
if (computerpick.equalsIgnoreCase("scissors"))
System.out.println("Scissors beats paper. The computer wins!");
else if (computerpick.equalsIgnoreCase("rock"))
System.out.println("Paper beats rock. You win!");
else
System.out.println("Computer chooses paper. It's a tie.");
}
else if (userpick.equalsIgnoreCase("scissors")) {
if (computerpick.equalsIgnoreCase("rock"))
System.out.println("Rock beats scissors. The computer wins!");
else if (computerpick.equalsIgnoreCase("paper"))
System.out.println("Scissors beats paper. You win!");
else
System.out.println("Computer chooses scissors. It's a tie.");
}
}
}
}`
Remove the semi-colon which is terminating the while statement
while (...);
^
Remove semicolon after the for loop. Semicolon after while/for/if means its a null statement which means the very next block of codes with in braces acts just as a block which will always gets evaluated irrespective of whether the condition holds true or not.
The semicolon generally ends a line in java. In order to make the while loop to run you need to remove the semi column.

How to loop a JOptionsPane

Alright well, I semi figured it out with some searching, but now I have another issue
When the second box pops up and I click 'no' the first box still runs and if I cancel it I get an error. What am I doing wrong?
import javax.swing.*;
import java.util.*;
import java.util.Scanner;
public class RPS {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
String input;
int user;
int computer;
while (true){//here we go
input = JOptionPane.showInputDialog("What'll it be? Rock, paper, or scissors?\n" +
"1 for rock, 2 for paper, and 3 for scissors: ",JOptionPane.YES_NO_OPTION);
user = Integer.parseInt(input);
Random randomnum = new Random ();
computer = randomnum.nextInt(3);
if (user == 1 && computer == 0){System.out.println ("You played Rock! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 1 && computer == 1){System.out.println ("You have played Rock! You have lost");
JOptionPane.showMessageDialog(null, "Paper beats rock. You lose!");}
else if (user == 1 && computer == 2){System.out.println ("You have played Rock! You have won");
JOptionPane.showMessageDialog(null, "Rock beats scissors. You win!");}
else if (user == 2 && computer == 0){System.out.println ("You have played Paper! You have won");
JOptionPane.showMessageDialog(null, "Paper beats rock. You win!");}
else if (user == 2 && computer == 1){System.out.println ("You have played Paper! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
else if (user == 2 && computer == 2){System.out.println ("You have played Paper! You have lost");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You lose!");}
else if (user == 3 && computer == 0){System.out.println ("You have played Scissors! You have lost");
JOptionPane.showMessageDialog(null, "Rock beats Scissors. You lose!");}
else if (user == 3 && computer == 1){System.out.println ("You have played Scissors! You have won");
JOptionPane.showMessageDialog(null, "Scissors beats paper. You win!");}
else if (user == 3 && computer == 2){System.out.println ("You have played Scissors! You have tied");
JOptionPane.showMessageDialog(null, "Tie!");}
int n = JOptionPane.showConfirmDialog(null,"Would you like to play again?", "Confirmation",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null,"Let's start");
} else {
JOptionPane.showMessageDialog(null,"Goodbye");
}
}
}
}
Put a return; statement after JOptionPane.showMessageDialog(null,"Goodbye");. otherwise it doesn't know to end the while loop.
The error when you press cancel would happen also if you chose cancel right away. It's because parseInt doesn't know how to read the resulting input. You should check the return value of showInputDialog to see that it's valid output. I would suggest checking for "1", "2", or "3" (or "rock", "paper", or "scizzors") instead of using parseInt, and then if it doesn't match any of them to come up with an error message of some sort.

Rock Paper Scissors Game Using AI Java

For My Assignment, I am supposed to create a Rock, Paper, Scissors game using java. However, there is an added twist. The computer should select the weapon most likely to beat the user, based on the user’s previous choice of weapons. For instance, if the user has selected Paper 3 times but Rock and Scissors only 1 time each, the computer should choose Scissors as the weapon most likely to beat Paper, which is the user’s most frequent choice so far. Here is what I've got so far:
import java.util.Random;
import java.util.Scanner;
public class CSCD210HW3
{
public static void main(String[] args)
{
displayGreeting();
computerChoice();
gameCode();
}
public static void displayGreeting()
{
System.out.print("This is the classic Rock, Paper, Scissors game everyone has grown to know and love. The \nrules are the same. Paper beats rock, rock beats scissors, scissors beats paper. Good luck fool!");
System.out.println();
}
public static String computerChoice()
{
Random randomGenrator = new Random();
int randomNumber = randomGenrator.nextInt(3);
int cpuRock = 0;
int cpuPaper = 0;
int cpuScissors = 0;
String weapon = "nothing";
switch(randomNumber)
{
case 0:
weapon = "rock";
cpuRock++;
break;
case 1:
weapon = "paper";
cpuPaper++;
break;
case 2:
weapon = "scissors";
cpuScissors++;
break;
}
return weapon;
}
public static String playerChoice()
{
Scanner kb = new Scanner(System.in);
String input = "";
System.out.println();
System.out.print("Please Choose Your Weapon: ");
input = kb.next();
String inputLower = input.toLowerCase();
return inputLower;
}
public static void gameCode()
{
int ties = 0;
int playerWins = 0;
int compWins = 0;
int userScissors = 0;
int userRock = 0;
int userPaper = 0;
String player;
String comp;
do
{
player = playerChoice();
if(player == "scissors")
{
userScissors++;
}
else if(player == "rock")
{
userRock++;
}
else if(player == "paper")
{
userPaper++;
}
comp = computerChoice();
if(player.equals("rock")&&comp.equals("rock"))
{
System.out.println("You and the Computer Both Chose Rock. It's a Tie!");
ties++;
userRock++;
}
else if(player.equals("paper")&&comp.equals("paper"))
{
System.out.println("You and the Computer Both Chose Paper. It's a Tie!");
ties++;
userPaper++;
}
else if(player.equals("scissors")&&comp.equals("scissors"))
{
System.out.println("You and the Computer Both Chose Scissors. It's a Tie!");
ties++;
userScissors++;
}
else if (player.equals("rock") && comp.equals("scissors"))
{
System.out.println("You Chose Rock and the Computer Chose Scissors. You Win!");
playerWins++;
userRock++;
}
else if(comp.equals("rock") && player.equals("scissors"))
{
System.out.println("You Chose Scissors and the Computer Chose Rock. You Lose!");
compWins++;
userScissors++;
}
else if(player.equals("scissors")&& comp.equals("paper"))
{
System.out.println("You Chose Scissors and the Computer Chose Paper. You Win!");
playerWins ++;
userScissors++;
}
else if(comp.equals("scissors") && player.equals("paper"))
{
System.out.println("You Chose Paper and the Computer Chose Scissors. You Lose!");
compWins++;
userPaper++;
}
else if(player.equals("paper") && comp.equals("rock"))
{
System.out.println("You Chose Paper and the Computer Chose Rock. You Win!");
playerWins++;
userPaper++;
}
else if(comp.equals("paper")&& player.equals("rock"))
{
System.out.println("You Chose Paper and the Computer Chose Rock. You Lose!");
compWins++;
userRock++;
}
else
{
System.out.println("Invalid Input. Please Re-Enter. ");
System.out.println();
}
}while(!(player.equals("quit")));
System.out.println("Here are the results: ");
System.out.println("Ties: " + ties);
System.out.println("Computer Wins: " + compWins);
System.out.println("Player Wins: " + playerWins);
System.out.println();
System.out.println("Times Rock Chosen: "+userRock);
System.out.println("Times Paper Chosen: "+userPaper);
System.out.println("Times Scissors Chosen: "+userScissors);
return;
}//end
}
I've got no idea how to make the computer select the weapon most likely to beat the user. I've heard an AI might work, but I've never used one before. How would I go about doing that?
There is no way a computer may succeed better at guessing than a human if computer's opponent chooses rock, paper or scissors at random. However, as a human rarely does anything completely at random, there may be approaches to weigh a likeliness of an outcome given previous outcomes. So I think you could go with pattern recognition. For example, for each combination or rock, paper or scissors of length n (so there would be 3^n of those), you could remember how often has it appeared in the sequence produced by human player. So on each turn you remember n-1 previous turns, and after each turn you increment the counter (one of 3^n counters) associated with a combination of outcomes in the last n turns. You can easily see that the time and space required to solve the problem grow exponentially with n, so I suggest choosing a small n, like 4 or 5. So start off with your program guessing at random (33.3% chance for choosing each option), and then, after certain amount of statistics has been collected by playing against a human, start biasing each of three possible outcomes by consulting your counters.

Categories