Rock Paper Scissors Game Using AI Java - 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.

Related

How to compare a String with an integer?

How can I compare a string with an int? I am making a Rock-paper-scissors game and how do I turn the string the user enters in to a int so the program can check who had won? Such as if the users enters "rock" the program registers that as 0 and so on?
package rpc;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
/* Random number generator */
Random random = new Random();
/* Scanner object for input */
Scanner scanner = new Scanner(System.in);
/*
* Integer variables to hold the user and computer choice.
* 0 = Rock
* 1 = Paper
* 2 = Scissors
*/
String userChoice;
int computerChoice;
// Showing prompt and user input
System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
userChoice = scanner.nextLine();
// Checking if userChoice is 0, 1, or 2.
if (!userChoice.equalsIgnoreCase("Scissors") && !userChoice.equalsIgnoreCase("Paper")
&& !userChoice.equalsIgnoreCase("rock")) {
System.out.println("Invalid choice. Ending program.");
// Exit program
Main.main(args);
}
// Generating random computer choice
computerChoice = random.nextInt(3);
// Determining the winner
// If the choices are equal, it's a tie.
if (userChoice == computerChoice) {
if (userChoice == 0) {
System.out.println("Both players chose rock!");
} else if (userChoice == 1) {
System.out.println("Both players chose paper!");
} else {
System.out.println("Both players chose scissors!");
}
// Exit program
System.exit(0);
}
if (userChoice == 0) { // User chooses rock
if (computerChoice == 1) {
System.out.println("You chose rock; Computer chose paper");
System.out.println("Computer wins!");
} else {
System.out.println("You chose rock; Computer chose scissors");
System.out.println("You win!");
}
} else if (userChoice == 1) { // User chooses paper
if (computerChoice == 0) {
System.out.println("You chose paper; Computer chose rock");
System.out.println("You win!");
} else {
System.out.println("You chose paper; Computer chose scissors");
System.out.println("Computer wins!");
}
} else { // User chooses scissors
if (computerChoice == 0) {
System.out.println("You chose scissors; Computer chose rock");
System.out.println("Computer wins!");
} else {
System.out.println("You chose scissors; Computer chose paper");
System.out.println("You win!");
}
}
scanner.close();
}
}
You could use an enum to enumerate the three possible choices:
enum Hand {
ROCK,
PAPER,
SCISSORS;
public static Hand from(String input) {
for (Hand hand : values()) {
if (hand.name().equalsIgnoreCase(input)) {
return hand;
}
}
throw new IllegalArgumentException("Invalid choice: " + input);
}
}
Enums have an intrinsic integer value (that corresponds to the position they were defined at). ROCK.ordinal() will return 0, for example.
Just use pareseInt and convert string to int
For ex :
if(Integer.parseInt(userChoice) == computerChoice)
Make sure that the inputs are not null and formattable to int
edit : change parese to parse
Retrieving a random item from ArrayList
This is not the exact answer to your question (Integer.parseInt(myInt)) but you could try something more readable like this, avoiding the use of unnecessary Integers. And simplifies your code
Generate your arrayList and then pick the random "computer" choice.
List<String> posibilities = Arrays.asList("rock","paper","scissors");
String computerChoice = possibilites.get(Math.random(3));
then do your comparaison ;)
/* Chose the possibilities */
List<String> posibilities = Arrays.asList("rock","paper","scissors");
/* Scanner object for input */
Scanner scanner = new Scanner(System.in);
// Showing prompt and user input
System.out.println("Enter move (0 = Rock; 1 = Paper; 2 = Scissors):");
String userChoice = scanner.nextLine();
userChoice = possibilities.get(Integer.parseInt(userChoice));
// Checking if userChoice is 0, 1, or 2.
if(!possibilities.contains(userChoice)) {
System.out.println("Invalid choice. Ending program.");
// Exit program
Main.main(args);
}
// Generating random computer choice
String computerChoice = possibilites.get(Math.random(3));
// Determining the winner
// If the choices are equal, it's a tie.
if(userChoice.equals(computerChoice)) {
System.out.println("Both players chose " + userChoice);
// Exit program
System.exit(0);
}
System.out.println("You chose " + userChoice + "; Computer chose " + computerChoice);
if(userChoice.equals("rock")) { // User chooses rock
if(computerChoice.equals("paper")) {
System.out.println("Computer wins!");
} else {
System.out.println("You win!");
}
}
else if(userChoice.equals("paper")) { // User chooses paper
if(computerChoice.equals("rock")) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
} else { // User chooses scissors
if(computerChoice.equals("Scissors")) {
System.out.println("Computer wins!");
} else {
System.out.println("You win!");
}
}
scanner.close();

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.

how to stop a loop in java if a value is incremented consecutively for three times?

i'm new to java. i'm writing a sample of rock paper scissors game. the user input 0,1,2 for rock, paper, scissors respectively. the program randomly generated the result. i almost managed to get it work but the only thing i'm stuck at is how to STOP THE FOR LOOP IF ONE OF THE SIDE WINS CONSECUTIVELY FOR THREE TIMES.
THIS IS THE ORIGINAL QUESTION
Write a program that plays scissor-rock-paper game. The rule is that a scissor wins against a paper, a
rock wins against a scissor, and a paper wins against a rock. The program represent scissor as 0, rock
as 1, and paper as 2.
The game is to be played between the computer and a player. The program will prompt the user to
enter the number of rounds to win. For example, if the user enter 4 then the winner has to win at
least 3 out of the 4 rounds. If either party win 3 times consecutively, the game ends early without the
fourth round. If the user enter 5 rounds, the winner has to win at least 3 out of the 5 rounds. The
same rule of consecutive 3-wins also apply. After the user has entered the number of rounds, the
computer randomly generates a number between 0 and 2. The program then prompts the user to
enter a number 0, 1, or 2. After the last round (subject to the above mentioned early-winner-rule),
the program display a message indicating whether the computer or the user wins, loses, or draws.
THIS IS MY CODE.
package assignment1;
import java.util.Scanner;
import java.util.Random;
public class question1_9 {
// This program is used to play scissor-rock-paper game.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random random = new Random();
int scissor = 0, rock = 1, paper = 2, round, userinput,comprand, userresult = 0, compresult = 0, control,j,k;
// Variables used in this program is declared and initialized.
/* Number of rounds wished to be play are obtained from user. */
System.out.println("WELCOME TO ROCK PAPER SCISSOR GAME. ");
System.out.println("PLEASE ENTER THE NUMBER OF ROUND YOU WANT TO PLAY: ");
round = scan.nextInt();
control = (round/2)+1;
for(int i = 0; i<round; i++)
{
if (compresult == control | userresult == control)
{
break;
}
System.out.println("ROUND " + (i+1));
System.out.println("PLEASE ENTER:\n 0 for scissor \n 1 for rock \n 2 for paper \n");
userinput = scan.nextInt();
comprand = random.nextInt(3);
if (userinput == 0)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("DRAW!!!");
i--;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("YOU WIN!!!");
userresult++;
}
}
else if (userinput == 1)
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("YOU WIN!!!");
userresult++;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("DRAW!!!");
i--;
}
}
else
{
if (comprand == 0)
{
System.out.println("COMPUTER IS SCISSOR");
System.out.println("YOU WIN!!!");
userresult++;
}
else if (comprand == 1)
{
System.out.println("COMPUTER IS ROCK");
System.out.println("DRAW!!!");
i--;
}
else
{
System.out.println("COMPUTER IS PAPER");
System.out.println("COMPUTER WINS!!!");
compresult++;
}
}
}
if(compresult == userresult)
System.out.println("\n\nFINAL RESULT IS DRAW!!!");
else if (compresult > userresult)
System.out.println("\n\nFINAL RESULT IS COMPUTER WIN!!!");
else
System.out.println("\n\nFINAL RESULT IS YOU WIN!!!");
}
}
use break; statement when you want to get out of current loop.
At top of loop,
store the wins in an array
String[] results=new String[rounds];
store your results as "user" or "comp" for each round and at the end of loop do this
if((results[i].equals("user") && results[i-1].equals("user") && results[i-2].equals("user") || (results[i].equals("comp") && results[i-1].equals("comp") && results[i-2].equals("comp")))
{
break;
}
Like shreyas said, use a break statement when you want to exit a loop.
I would set compresult to zero whenever the player wins a round, and set userresult to zero whenever the computer wins. Then, at the top of the loop, right after the { add:
if(userResult == 3 || computerResult == 3 || round/2 > 10)
{
break;
}
Some code comes from shreyas's original post.

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.

Rock Paper Scissors game

I'm new to programming and I've been trying to create a simple Rock Paper Scissors game. Basically, it uses a while loop and asks the user whether they want to play (or continue). Once they no longer want to, the program has to print out the total number of games, number of wins, number of losses and percentage of wins. I've got the entire program to work, except it always says the percentage of wins is 0.0%, even when it's not. I already used an if statement to avoid any divide by zero error. I'm not getting any runtime or compiler errors, so I'm either missing something or there's a logic error I just cannot find. I would like to continue using the Scanner.
import java.util.Scanner;
public class RockPaperScissors {
/*
* Program allows user to play Rock, Paper and Scissors as many times as desired by entering Y until they enter N.
* Program will print amount of games played, amount lost, amount won and percentage won.
* User must enter "Y", "N", "Rock", "Paper" or "Scissors" with correct capitalization and spelling.
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int playerWins = 0;
int compWins = 0;
int gamesPlayed = 0;
while (true) {
System.out.println("Do you want to play Rock Paper Scissors (Y/N): ");
String play = input.nextLine();
// user terminates game and program prints number of wins, losses and percentage of wins.
if (play.equals("N")) {
System.out.println("You played a total of " + gamesPlayed + " matches against the computer");
System.out.println("The computer won " + compWins + " matches");
System.out.println("You won " + playerWins + " matches");
// 0% wins when no games are played.
if (gamesPlayed == 0) {
System.out.println("You won 0% of the time!");
break;
} else if (gamesPlayed > 0) {
double totalWins = (int)(playerWins / gamesPlayed) * 100;
System.out.println("You won " + totalWins + "% of the time!");
break;
}
} else if ((!play.equals("N")) && (!play.equals("Y"))) {
System.out.println("Invalid entry");
} else {
System.out.println("Welcome to Rock, Paper and Scissors!");
System.out.print("Select \"Paper\", \"Rock\" or \"Scissors\": ");
String decision = input.nextLine();
System.out.println("Your selection: " + decision);
// random number generator producing integer values between 1 to 3 for computer's choices.
// 1 is for Rock, 2 is for Paper and 3 is for Scissors.
int num = (int)(Math.random() * (3-0) + 1);
switch (num) {
// Computer picks Rock
case 1:
if (decision.equals("Rock")) {
System.out.println("Tie, you and the computer selected rock");
gamesPlayed++;
} else if (decision.equals("Paper")) {
System.out.println("You win, paper beats rock!");
gamesPlayed++;
playerWins++;
} else if (decision.equals("Scissors")) {
System.out.println("Computer wins, rock beats scissors!");
gamesPlayed++;
compWins++;
} else {
System.out.println(decision + " is not a valid input");
}
break;
case 2:
// computer picks Paper
if (decision.equals("Rock")) {
System.out.println("Computer wins, rock beats paper!");
gamesPlayed++;
compWins++;
} else if (decision.equals("Paper")) {
System.out.println("Tie, you and the computer selected paper");
gamesPlayed++;
} else if (decision.equals("Scissors")) {
System.out.println("You win, scissors beats paper");
gamesPlayed++;
playerWins++;
} else {
System.out.println(decision + " is not a valid input");
}
break;
case 3:
// computer picks Scissors
if (decision.equals("Rock")) {
System.out.println("You win, rock beats scissors");
gamesPlayed++;
playerWins++;
} else if (decision.equals("Paper")) {
System.out.println("Computer wins, scissors beats paper");
gamesPlayed++;
compWins++;
} else if (decision.equals("Scissors")) {
System.out.println("Tie, you and the computer selected scissors");
gamesPlayed++;
} else {
System.out.println(decision + " is not a valid input");
}
break;
}
}
}
}
}
The problem is at double totalWins = (int)(playerWins / gamesPlayed) * 100;. Since playerWins and gamesPlayed are both integral type (specifically int type), Java is doing 'Integer Division', which returns the quotient of the division as result and ignore the remainder. So to prevent it from doing this you are best changing that line to:
double totalWins = (playerWins * 100.0) / gamesPlayed;
// /------------------\
// This converts the `playerWins` to a `double` and does the division as you expect

Categories