Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.rps.logic;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.Random;
- import javax.swing.JOptionPane;
- /**
- * @author _Jordan <jordan.abraham1997@gmail.com>
- */
- public class RPSActionListener implements ActionListener {
- /**
- * @author _Jordan <jordan.abraham1997@gmail.com>
- */
- public enum Action {
- ROCK("paper"), PAPER("scissors"), SCISSORS("rock");
- /**
- * Represents the weakness to each action.
- */
- private final String weakness;
- /**
- * Constructs a new {@code Action} object.
- *
- * @param weakness The weakness to each action.
- */
- private Action(String weakness) {
- this.weakness = weakness;
- }
- /**
- * Gets the weakness.
- *
- * @return the weakness
- */
- public String getWeakness() {
- return weakness;
- }
- }
- /**
- * Represents a random instance to perform 'computer' actions.
- */
- private final Random random = new Random();
- /*
- * (non-Javadoc)
- *
- * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
- */
- @Override
- public void actionPerformed(ActionEvent event) {
- /** TRIM IT JUST INCASE lol */
- switch (event.getActionCommand().trim()) {
- case "Rock":
- case "Paper":
- case "Scissors":
- performAction(Action.valueOf(event.getActionCommand().toUpperCase()), getRandomComputerAction(random.nextInt(3)));
- break;
- }
- }
- /**
- * Performs a game action.
- *
- * @param playerAction The action of the player.
- * @param computerAction The action of the computer.
- */
- private void performAction(Action playerAction, Action computerAction) {
- if (playerAction.equals(computerAction)) {
- performAction(playerAction, getRandomComputerAction(random.nextInt(3)));
- return;
- }
- if (playerAction.getWeakness().equalsIgnoreCase(computerAction.name())) {
- JOptionPane.showMessageDialog(null, "Player: " + playerAction.name() + ", Computer: " + computerAction.name() + " = LOSE!", "LOSE!", JOptionPane.PLAIN_MESSAGE);
- } else {
- JOptionPane.showMessageDialog(null, "Player: " + playerAction.name() + ", Computer: " + computerAction.name() + " = WIN!", "WIN!", JOptionPane.PLAIN_MESSAGE);
- }
- }
- /**
- * Generates a random computer action.
- *
- * @param id The action id.
- * @return The action generated.
- */
- private Action getRandomComputerAction(int id) {
- for (Action i : Action.values()) {
- if (i.ordinal() == id) {
- return i;
- }
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement