Rock, Paper, Scissors

Rock, Paper, Scissors 12/2/2010

Another Java forum classic: rock, paper, scissors. Or chifoumi, as it is called in France.

An interesting solution involves an enum (which I called Choice below). The only “fancy” thing in the code is checkWinner which checks if the first value is equal to the second value + 1, modulo 3 (as paper is stronger than rock, scissors stronger than paper, and rock stronger than scissors, so there’s a circular thing going on there). I haven’t bothered checking the user’s input, but that should really be done.

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {
    public enum Choice {
        ROCK(0),
        PAPER(1),
        SCISSORS(2);

        private final int value;

        Choice(int value) {
            this.value = value;
        }

        public int value() {
            return value;
        }
    }

    private int checkWinner(Choice choice1, Choice choice2) {
        if (choice2 == choice1) {
            return 0;
        } else if (choice1.value() == ((choice2.value() + 1) %3)) {
            return 1;
        } else return 2;
    }

    private Choice getChoiceAtRandom() {
        return Choice.values()[new Random().nextInt(3)];
    }

    private Choice readChoice() {
        System.out.println("Rock, paper or scissors?");
        Scanner scanner = new Scanner(System.in);
        String choice = scanner.next();
        return Choice.valueOf(choice.toUpperCase());
    }

    public void doGameLoop() {
        int counter = 0;
        while (counter < 3) {
            Choice userChoice = readChoice();
            Choice computerChoice = getChoiceAtRandom();

            int winner = checkWinner(userChoice, computerChoice);
            if (winner == 0) {
                System.out.println("Both " + userChoice + ". It's a tie"); 
            } else if (winner == 1) {
                System.out.println("You win!  You played " + userChoice 
                        + " and computer played " + computerChoice) ; 
            } else {
                System.out.println("You lose.  You played " + userChoice 
                        + " and computer played " + computerChoice) ;
            }

            counter++;
        }
    }

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

And that’s pretty much it — connoisseurs will appreciate the use of Scanner which I usually spit upon!

I highly recommend reading the Wikipedia entry for Rock, paper, scissors, it’s quite entertaining… Did you know it’s been used in a (US) federal court?!

 
---

Comment

your_ip_is_blacklisted_by sbl.spamhaus.org

---