How to write a rock, paper, scissors game in Java

Table of contents:

How to write a rock, paper, scissors game in Java
How to write a rock, paper, scissors game in Java
Anonim

Rock, Paper, Scissors is a finger game for two. Together, the players say “rock, scissors, paper” and throw their hand forward, using their fingers to form one of three shapes (rock, scissors, or paper). The winner is determined as follows: scissors beat paper, paper beats stone, stone beats scissors. If both players show the same piece, it is considered a draw. We'll write a simple Java game that lets you play rock, paper, scissors with your computer.

Steps

Step 1. Create a main class and name it

RockPaperScissors

.

In this class, we will describe the game. You can call it differently, for example

Game

or

Main

… Write the declarations for the constructor and the main method.

public class RockPaperScissors {public RockPaperScissors () {} public static void main (String [] args) {}}

Step 2. Create an enum to describe the possible moves (rock, scissors, paper).

We can specify moves with strings, but enumeration allows us to predefine constants, so using enum is better. Let's call our enumeration

Move

and set the values

ROCK

,

PAPER

and

SCISSORS

.

private enum Move {ROCK, PAPER, SCISSORS}

Step 3. Create two private (private keyword) classes

User

and

Computer

.

These classes will represent the players. You can also make these classes public (the public keyword). Class

User

will ask the user which move he is making - rock, scissors or paper - so we need to write a method

getMove ()

… Class

Computer

should also have a method

getMove ()

so that we can get the computer's progress. For now, we'll just declare these methods and write the implementation later. Class

User

must have a constructor in which the object is initialized

Scanner

that will read user input. We declare

Scanner

private class data member

User

and initialize it in the constructor. Since we are going to use the class

Scanner

, we have to connect it using the keyword

import

… Class

Computer

the constructor is not needed, so we will not write it; when initializing an object

Computer

we'll just call the default constructor. This is how the class

RockPaperScissors

looks now:

import java.util. Scanner; public class RockPaperScissors {private enum Move {ROCK, PAPER, SCISSORS} private class User {private Scanner inputScanner; public User () {inputScanner = new Scanner (System.in); } public Move getMove () {// TODO: Implementation of the method return null; }} private class Computer {public Move getMove () {// TODO: Method implementation return null; }} public RockPaperScissors () {} public static void main (String [] args) {}}

Step 4. Write the implementation of the method

getMove ()

for class

Computer

.

This method will return a random value

Move

… We can get an array of values

Move

by calling the method

values ()

like this:

Move.values ()

… To choose a random value

Move

from this array, we need to generate a random index between 0 and the number of elements in the array. To do this, call the method

nextInt ()

class

Random

, which we connect like this:

import java.util. Random

… Having received a random index, we return the value

Move

with that index in our array.

public Move getMove () {Move [] moves = Move.values (); Random random = new Random (); int index = random.nextInt (moves.length); return moves [index]; }

Step 5. Write the implementation of the method

getMove ()

for class

User

.

This method will return a value

Move

matching user input. The user can enter "rock", "scissors", or "paper". First, we will display the message:

System.out.print ("Rock, scissors or paper?")

… Then, using the method

nextLine ()

object

Scanner

, we will receive the user's input as a string. Now you need to check the correctness of the user input. However, we will not pay attention to typos, but just check the first letter "K", "H" or "B". Also, we will not pay attention to the case of letters, since, previously, we will call the method

toUpperCase ()

class

String

, converting user input to uppercase. If the user has not entered even an approximately correct choice, we will request his move again. Then, depending on user input, our method will return the appropriate value

Move

.

public Move getMove () {// Display a request for input System.out.print ("Rock, scissors or paper?"); // Read the user's input String userInput = inputScanner.nextLine (); userInput = userInput.toUpperCase (); char firstLetter = userInput.charAt (0); if (firstLetter == 'K' || firstLetter == 'N' || firstLetter == 'B') {// Input correct switch (firstLetter) {case 'K': return Move. ROCK; case 'Н': return Move. PAPER; case 'B': return Move. SCISSORS; }} // The input is invalid. Let's display the request for input again. return getMove (); }

Step 6. Write the implementation of the method

playAgain ()

class

User

.

The user should be able to play over and over again. To determine if the user wants to play again, write the method

playAgain ()

which will return a bool value and thus tell the game if the user wants to play again. In this method, we use the object

Scanner

which we initialized in the constructor to get "Yes" or "No" from the user. We will just check the first letter, if it is 'D', then the user wants to play again, any other letter will mean "No".

public boolean playAgain () {System.out.print ("Would you like to play again?"); String userInput = inputScanner.nextLine (); userInput = userInput.toUpperCase (); return userInput.charAt (0) == 'D'; }

Step 7. Link the class code

User

and class

Computer

in class

RockPaperScissors

.

By writing the code for the classes

User

and

Computer

, we can get down to the game itself. Declare classes

User

and

Computer

private data members of the class

RockPaperScissors

… We will refer to them by calling the method

getMove ()

to get player moves. Initialize them in the class constructor

RockPaperScissors

… We also need to store the account. Declare

userScore

and

computerScore

, then initialize them to zero. Finally, create a data field to store the number of games, also initializing it to zero.

private User user; private Computer computer; private int userScore; private int computerScore; private int numberOfGames; public RockPaperScissors () {user = new User (); computer = new Computer (); userScore = 0; computerScore = 0; numberOfGames = 0; }

Step 8. Complete the enumeration

Move

a method that will compare moves and determine the winner.

Let's write the code for the method

compareMoves ()

which will return 0 if the moves are the same, 1 - if the current move beats another and -1 - if another move beats the current one. The current move is represented by this pointer and another is passed in the otherMove parameter. This will come in handy for determining the winner. First, we will write the code to determine the draw and return 0, and then we will write the switch statement to determine the winner.

private enum Move {ROCK, PAPER, SCISSORS; / ** * Compares the current move with the one passed in the otherMove parameter and determines * a win, loss or draw. * * @param otherMove * the current move is compared to * @return 1 if the current move beats another, -1 if another move beats the current one, * 0 in case of a draw * / public int compareMoves (Move otherMove) {// Draw if (this == otherMove) return 0; switch (this) {case ROCK: return (otherMove == SCISSORS? 1: -1); case PAPER: return (otherMove == ROCK? 1: -1); case SCISSORS: return (otherMove == PAPER? 1: -1); } // This code should never be executed return 0; }}

Step 9. Declare the method

startGame ()

in class

RockPaperScissors

.

In this method, the game will take place. Start by calling the method

System.out.println

.

public void startGame () {System.out.println ("STONE, SCISSORS, PAPER!"); }

Step 10. Get computer and user moves.

In method

startGame ()

call

getMove ()

classes

User

and

Computer

to get their moves.

Move userMove = user.getMove (); Move computerMove = computer.getMove (); System.out.println ("\ nYour move" + userMove + "."); System.out.println ("Computer progress" + computerMove + ". \ N");

Step 11. Compare the turn of the computer and the turn of the player to determine who won.

Call the method

compareMoves ()

transfers

Move

to determine if the user won. If yes, increase its score by 1. If not, increase the computer's score. In case of a tie, the score remains the same. After that, increase the number of games played by 1.

int compareMoves = userMove.compareMoves (computerMove); switch (compareMoves) {case 0: // Draw System.out.println ("Draw!"); break; case 1: // Player won System.out.println (userMove + "beats" + computerMove + ". You won!"); userScore ++; break; case -1: // Computer won System.out.println (computerMove + "beats" + userMove + ". You lost."); computerScore ++; break; } numberOfGames ++;

Step 12. Ask the user if he wants to play again.

If yes, call the method

startGame ()

again. If not, call the method

printGameStats ()

which will display the statistics of the game. We will write its implementation in the next step.

if (user.playAgain ()) {System.out.println (); startGame (); } else {printGameStats (); }

Step 13. Write the implementation of the method

printGameStats ()

.

This method will display game statistics: the number of wins, losses, draws, the number of games played and the percentage of the player's wins. The percentage of games won is calculated as follows: (number of wins + (number of draws / 2)) / (number of games played). This method uses

System.out.printf

for formatted text output.

private void printGameStats () {int wins = userScore; int losses = computerScore; int ties = numberOfGames - userScore - computerScore; double percentageWon = (wins + ((double) ties) / 2) / numberOfGames; // Print line System.out.print ("+"); printDashes (68); System.out.println ("+"); // Print table headers System.out.printf ("|% 6s |% 6s |% 6s |% 12s |% 14s | \ n", "VICTORY", "DEFEAT", "DRAW", "TOTAL GAMES", " PERCENTAGE OF VICTORIES "); // Print line System.out.print ("|"); printDashes (10); System.out.print ("+"); printDashes (10); System.out.print ("+"); printDashes (10); System.out.print ("+"); printDashes (16); System.out.print ("+"); printDashes (18); System.out.println ("|"); // Print values System.out.printf ("|% 6d |% 6d |% 6d |% 12d |% 13.2f %% | \ n", wins, losses, ties, numberOfGames, percentageWon * 100); // Print line System.out.print ("+"); printDashes (68); System.out.println ("+"); }

Step 14. Start the game.

In the main class, initialize the object

RockPaperScissors

and call its method

startGame ()

.

public static void main (String [] args) {RockPaperScissors game = new RockPaperScissors (); game.startGame (); }

Screen Shot 2013 06 23 at 2.27.50 AM
Screen Shot 2013 06 23 at 2.27.50 AM

Step 15. Test the game

Now that all the work is over, it's time to compile and test our game!

Sample program

import java.util. Random; import java.util. Scanner; public class RockPaperScissors {private User user; private Computer computer; private int userScore; private int computerScore; private int numberOfGames; private enum Move {ROCK, PAPER, SCISSORS; / ** * Compares the current move with the one passed in the otherMove parameter and determines * a win, loss or draw.* * @param otherMove * the current move is compared to * @return 1 if the current move beats another, -1 if another move beats the current one, * 0 in case of a draw * / public int compareMoves (Move otherMove) {// Draw if (this == otherMove) return 0; switch (this) {case ROCK: return (otherMove == SCISSORS? 1: -1); case PAPER: return (otherMove == ROCK? 1: -1); case SCISSORS: return (otherMove == PAPER? 1: -1); } // This code should never be executed return 0; }} private class User {private Scanner inputScanner; public User () {inputScanner = new Scanner (System.in); } public Move getMove () {// Display a request for input System.out.print ("Rock, scissors or paper?"); // Read the user's input String userInput = inputScanner.nextLine (); userInput = userInput.toUpperCase (); char firstLetter = userInput.charAt (0); if (firstLetter == 'K' || firstLetter == 'N' || firstLetter == 'B') {// Input correct switch (firstLetter) {case 'K': return Move. ROCK; case 'Н': return Move. PAPER; case 'B': return Move. SCISSORS; }} // The input is invalid. Let's display the request for input again. return getMove (); } public boolean playAgain () {System.out.print ("Do you want to play again?"); String userInput = inputScanner.nextLine (); userInput = userInput.toUpperCase (); return userInput.charAt (0) == 'Y'; }} private class Computer {public Move getMove () {Move [] moves = Move.values (); Random random = new Random (); int index = random.nextInt (moves.length); return moves [index]; }} public RockPaperScissors () {user = new User (); computer = new Computer (); userScore = 0; computerScore = 0; numberOfGames = 0; } public void startGame () {System.out.println ("STONE, SCISSORS, PAPER!"); // Get moves Move userMove = user.getMove (); Move computerMove = computer.getMove (); System.out.println ("\ nYour move" + userMove + "."); System.out.println ("Computer progress" + computerMove + ". \ N"); // Compare moves and determine the winner int compareMoves = userMove.compareMoves (computerMove); switch (compareMoves) {case 0: // Draw System.out.println ("Tie!"); break; case 1: // Player won System.out.println (userMove + "beats" + computerMove + ". You won!"); userScore ++; break; case -1: // Computer won System.out.println (computerMove + "beats" + userMove + ". You lost."); computerScore ++; break; } numberOfGames ++; // Prompt the user to play again if (user.playAgain ()) {System.out.println (); startGame (); } else {printGameStats (); }} / ** * Display statistics. Draws count as half wins * when calculating the win percentage. * / private void printGameStats () {int wins = userScore; int losses = computerScore; int ties = numberOfGames - userScore - computerScore; double percentageWon = (wins + ((double) ties) / 2) / numberOfGames; // Print line System.out.print ("+"); printDashes (68); System.out.println ("+"); // Print table headers System.out.printf ("|% 6s |% 6s |% 6s |% 12s |% 14s | \ n", "WINS", "LOSSES", "TIES", "GAMES PLAYED", " PERCENTAGE WON "); // Print line System.out.print ("|"); printDashes (10); System.out.print ("+"); printDashes (10); System.out.print ("+"); printDashes (10); System.out.print ("+"); printDashes (16); System.out.print ("+"); printDashes (18); System.out.println ("|"); // Print values System.out.printf ("|% 6d |% 6d |% 6d |% 12d |% 13.2f %% | \ n", wins, losses, ties, numberOfGames, percentageWon * 100); // Print line System.out.print ("+"); printDashes (68); System.out.println ("+"); } private void printDashes (int numberOfDashes) {for (int i = 0; i <numberOfDashes; i ++) {System.out.print ("-"); }} public static void main (String [] args) {RockPaperScissors game = new RockPaperScissors (); game.startGame (); }}

Popular by topic