Make a Rock, Paper, Scissors Game in Java
Rock, Paper, Scissors is a hand game played by two people. Both people would say "rock, paper, scissors" and then simultaneously form one of three objects (rock, paper, or scissors) with an outstretched hand. The winner is determined by the hand formations. Scissors beats paper, paper beats rock, and rock beats scissors. If both players play the same hand formation, it is considered a tie. We will write a simple game in Java to simulates Rock, Paper, Scissors where one player is the user and the other player is the computer.
Steps
- Create the main class and call it
RockPaperScissors. This will be the class where we will write the game. You may choose to name it something else such asGameorMain. Write in method declarations for the constructor and the main method. Template:CodeBox - Create an enumeration for the hand gestures (rock, paper, or scissors). We could use strings to represent rock, paper, or scissors, but an enumeration allows us to predefine our constants which means that using the enumeration is a better design. We will call our enum type
Movewith the valuesROCK,PAPER, andSCISSORS. Template:CodeBox - Create two private classes
UserandComputer. These classes will represent our players in the game. You may choose to make these classes public. TheUserclass will be the class that prompts the user for either rock, paper, or scissors, so we will need to write agetMove()method. TheComputerclass will also need to have agetMove()method so that the computer can also make a move. We will put placeholders in these methods and implement them later. TheUserclass will require a constructor that sets up theScannerobject to take in the user input. We will put theScanneras a private field for the user and then initiate it in the constructor. Since we are using theScannerclass, we need to write an import statement for it at the top of our code. TheComputerclass does not require a constructor, so we do not need to write one; when we initiate theComputerobject, we will just be calling the default constructor. Here is what ourRockPaperScissorsclass looks like now: Template:CodeBox - Write the
getMove()method for theComputerclass. This method will return a randomMove. We can get an array ofMoveenumerations by calling thevalues()method:Move.values(). To choose a randomMoveenumeration in this values array, we need to generate a random index that is an integer between 0 and the length of our values array. To do this, we can use thenextInt()method of theRandomclass which we need to import fromjava.util. After we have gotten the random index, we can return theMoveof that index from our values array. Template:CodeBox - Write the
getMove()method for theUserclass. This method will return aMovecorresponding to what the user has input. We will expect the user to write either "rock", "paper", or "scissors". First, we need to prompt the user for an input:System.out.print("Rock, paper, or scissors? "). Then use thenextLine()method of theScannerobject to get the user input as a string. We need now need to check if the user has submitted a valid move, but we can be lenient if the user has misspelled a word. So we will only check if the first letter of the user input is either "R" (for rock), "P" (for paper), or "S" (for scissors), and we won't care about the case because we will first use thetoUpperCase()method of theStringclass to make the user input string all uppercase. If the user has not entered a remotely correct input, we will prompt the user again. Then, depending on what the user has put in, we will return a corresponding move. Template:CodeBox - Write a
playAgain()method for theUserclass. The user should be able to play the game over and over again. In order to determine whether the user wants to play again, we need to write aplayAgain()method that returns a boolean telling the game whether the user has determined to play again or not. In this method, we are using theScannerthat we had previously initiated in the constructor to get a "Yes" or a "No" from the user. We will only check if the first letter is 'Y' to determine whether the user wants to play again. Any other input will mean that the user does not want to play again. Template:CodeBox - Connect the
UserandComputerclasses together in theRockPaperScissorsclass. Now that we have finished writing theUserandComputerclasses, we can focus on working on our actual game. Create private fields for theUserandComputerclasses in theRockPaperScissorsclass. We will need to access these fields to access thegetMove()methods when we're playing the game. In the constructor for theRockPaperScissorsclass, initiate these fields. We will also need to keep track of the score inuserScoreandcomputerScorefields, which we need to initiate as 0 in the constructor. We need to keep track of the number of games as well, which will also be a field initiated as 0. Template:CodeBox - Extend the
Moveenum to include a method that tells us which move wins in each case. We need to write acompareMoves()method that returns 0 if the moves are the same, 1 if the current move beats the other move, and -1 if the current move loses to the other move. This will be useful for determining the winner in the game. To implement this method, we will first return 0 if the moves are the same and therefore we have a tie. Then write a switch statement for returning 1 or -1. Template:CodeBox - Create a
startGame()method in theRockPaperScissorsclass. This method will be the playing of the game. Start out by putting a simpleSystem.out.printlnin the method. Template:CodeBox - Get moves from the user and the computer. In the
startGame()method, use thegetMove()methods from theUserclass and theComputerclass to get the user and the computer's moves. Template:CodeBox - Compare the two moves and determine whether the user won or the computer won. Use the
compareMoves()method from theMoveenum to to determine whether the user won or not. If the user won, increment the user score by 1. If the user lost, increment the computer score by 1. If there was a tie, do not increment any of the scores. Then increment the number of games played by one. Template:CodeBox - Ask if the user wants to play again. If the user wants to play again, call
startGame()again. Otherwise, callprintGameStats()which will print out the statistics of the game. We will write this method in the next step. Template:CodeBox - Write the
printGameStats()method. This method will display the statistics of the game: number of wins, number of losses, number of ties, number of games played, and percentage of games won by the user. The percentage of games won is calculated by the (# wins + (# ties/2))/(# games played). This method usesSystem.out.printfto print out formatted text. Template:CodeBox - Start the game in the main class. In the main class, initialize an instance of the
RockPaperScissorsclass and call thestartGame()method. Template:CodeBox - Test out your game. Now that we have gone through all the effort of writing the Rock, Paper, Scissors game, it's time to compile and test everything out!
Sample Program
Related Articles
- Make Mobile Games Using Java
- Install Java Games
- Create a Swing GUI in Java
- Program in Java
- Write Your First Program in Java
- Make a Java Applet