Rock Paper Scissors game - java

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

Related

how to subtract from a for loop in java

i am making a rock paper scissors game in java for collage and was wondering how to subtract 1 from a for loop.
the full code works but if some one enters a invalid number (lower then 1 or higher then 3) my code asks them to reenter a number(1, 2, 3)
but the for loop counts it as a loop so i end up with less moves.
i need to change something in the last "else if" but i cant figure it out
could some one point me in the right direction?
thanks.
the full code is this:
import java.io.*;
import java.util.Random;
public class RockPaperScissors {
static int loss = 0;
static int win = 0;
static int tie = 0;
int draw;
static int playerHand;
static int compHand;
int gameLoop;
public void playerMoves() {
if ( playerHand == compHand ){ //if both hands (player and computer) are the same
System.out.println("Draw, your picked " + playerHand + " and the computer picked " + compHand );
tie++; // add 1 to tie score
}
else if (playerHand == 1 && compHand == 2){ // if player picks Rock and computer picks paper
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, You lose");
loss++; // add 1 to loss score
}
else if (playerHand == 1 && compHand == 3){ // if player picks rock and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, You win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 1){ //if player picks paper and computer picks rock
System.out.println("the computer picks " + compHand + "! " + "Paper beats rock, you win!");
win++; // add 1 to win score
}
else if (playerHand == 2 && compHand == 3){ // if player picks paper and computer scissors
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 1){ // if player picks scissors and computer rock
System.out.println("the computer picks " + compHand + "! " + "Rock beats Scissors, you lose!");
loss++; // add 1 to loss score
}
else if (playerHand == 3 && compHand == 2){ // if player picks scissors and computer paper
System.out.println("the computer picks " + compHand + "! " + "Scissors beats Paper, you win!");
win++; // add 1 to win score
}
else if (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid number. Try again...");// if not valid number ask again.
gameLoop = gameLoop - 1; // subtract 1 from gameLoop
}
else {
System.out.println("Great job, you broke it...");
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Welcome to Rock Paper Scissors");
System.out.println("Lets play ten games and see if you can outsmart the computer!");
for (int gameLoop = 0; gameLoop < 10; gameLoop++) { // a for loop to keep the game running 10 times
Random randomNumber = new Random(); // create a new random number everytime
compHand = (int) randomNumber.nextInt(3); // generate a random number for the computer (compHand)
compHand++;
// while (playerHand < 1 || playerHand > 3) {
// System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
draw.playerMoves(); // go to public void playerMoves and use that.
System.out.println("the score is: " + win + " Games won. " + loss + " Games lost. " + tie + " Games tie."); // print out the game score at the end of every game
System.out.println("");
}
}
}
It is a scope issue. You are declaring a new variable gameLoop in your for loop, which hides the variable gameLoop that has been declared at the beginning of your class.
public class RockPaperScissors {
...
int gameLoop; // 1. variable with name gameLoop declared
...
// 2. variable with name gameLoop declared; hides 1. declaration
for (int gameLoop = 0; gameLoop < 10; gameLoop++) {
^ this is not the same variable as above
A quick and easy solution would be to just omit the 'int' in the for-loop:
for (gameLoop = 0; gameLoop < 10; gameLoop++) {
Now, when you decrement it in the else-branch of your playerMoves() method, it should be noticed by the for-loop.
You could look towards keeping that while loop in main which checks if the playerHand is < 1 or > 3, and inside it, validate until the user inputs a valid number. The
below is a sample idea of what you can look towards doing. It is not perfect.
//Taking in the first input
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors draw = new RockPaperScissors();
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
//Validating the input repeatedly until it is valid
while (playerHand < 1 || playerHand > 3) {
System.out.println(playerHand + " is not a valid move. Try again...");
System.out.println("Rock(1), Paper(2), or Scissors(3) Please enter the number");
RockPaperScissors.playerHand = Integer.parseInt(br.readLine());
}
//Continue with your program
draw.playerMoves(); // go to public void playerMoves and use that.
I personally find validating here to be more convenient than validating in the playerMoves method, which is a bit long already as it is.
Alternatively, if you want to subtract the invalid guess from the for loop, you can do a gameLoop-- in the for loop for invalid guesses (and not execute the method by doing something like a continue after decrementing gameLoop).

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();

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 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