Title: Rock Paper Scissors
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

Rock Paper Scissors

RPS Game:

- You pick one of { r, p, s} for Rock Paper Scissors.
- Another player also picks from the choices: {r,p, s}
- Neither player knows the other player's pick until both have made a pick, and then the game can report the winner/loser
- Results:
  - If both players pick the same thing, the game is a tie
  - Rock beats Scissors ( Rock breaks Scissors)
  - Scissors beats paper (Scissors can cut paper)
  - Paper beats Rock (Paper can cover Rock .... I never quit understood this logic??????)

MyMain.java

same as everything else including guiChat

MyGameInput.java


package rps;

import java.io.Serializable;


public class MyGameInput  implements Serializable
{

    private static final long serialVersionUID = 1L;

    static final char EXITING='e';
    static final char CONNECTING ='c';
    static final char PAPER ='p';
    static final char ROCK = 'r';
    static final char SCISSORS ='s';
    static final char NO_PICK=' ';

    String sendersName;
    char pick;


    public void setName(String name)
    {
        sendersName = name;
    }
    public void setPick(char pick)
    {
        this.pick = pick;
    }

}



MyGameOutput.java


package rps;

import java.io.Serializable;

public class MyGameOutput  implements Serializable
{
    private static final long serialVersionUID = 1L;
    MyGame gameStatus=null;

    public MyGameOutput(MyGame gs)
    {
        gameStatus =gs;
    }

}




MyGame.java


package rps;

import gameNet.GameNet_CoreGame;

import java.io.Serializable;
import java.util.ArrayList;

public class MyGame extends GameNet_CoreGame implements Serializable{

    private static final long serialVersionUID = 1L;

    //List of players (max of 2) currently playing
    private ArrayList<String> currPlayers = new ArrayList<String>();

    // RPS Rounds played so far
    private ArrayList<RpsRound> rpsRounds = new ArrayList<RpsRound>();

    public Object process(Object ob)
    {
        MyGameInput myGameInput= (MyGameInput)ob;
        int playerIndex = getClientIndex(myGameInput.sendersName);
        // If we already have 2 players, we will ignore additional attempts to
        // connect;
        if (playerIndex < 0)
        {
            System.out.println("We already have 2 players ... ignoring new request");
            return null;
        }
        if (myGameInput.pick == MyGameInput.EXITING)
        {
            currPlayers.remove(myGameInput.sendersName);
            System.out.println("Player Exiting: " + myGameInput.sendersName);
        }
        else if (myGameInput.pick != MyGameInput.CONNECTING)
        {
            if (RpsRound.choiceName(myGameInput.pick)== null)
            {
                System.out.println("Illegal Pick: " + myGameInput.pick);
                return null;
            }
            // Add the User's Pick to the RPS Rounds
            if (!add2RpsRounds(playerIndex, myGameInput.pick))
                return null;  // This user has already picked in this round
        }

        // Send back Updated game to all clients
        return new MyGameOutput(this);

    }

    // Routine for adding a current player's pick to the RPS Rounds
    private boolean add2RpsRounds(int playerIndex, char pick)
    {
        // Must always have at least one
        if (rpsRounds.size() == 0)
            rpsRounds.add(new RpsRound());

        // If the last round is complete, then we need to start a new one
        RpsRound topRound = rpsRounds.get(rpsRounds.size()-1);
        if (topRound.isComplete())
            rpsRounds.add(new RpsRound());

        // Get the latest Round and try to add user's pick to it
        RpsRound currRound = rpsRounds.get(rpsRounds.size()-1);
        if (!currRound.insert(playerIndex, pick))
        {
            System.out.println("Player already made a pick on this round ... ignoring");
            return false;
        }
        return true;
    }

// The following will return the player's current index (0 or 1).
// If the player is new and we don't yet have 2 players, then this player will be added
// and his index will be returned.
// If we already have 2 players and this is a new player, then -1 is returned.

    private int getClientIndex(String name)
    {
        // The following will return -1 if the name can't be found
        int retval = currPlayers.indexOf(name);

        if (retval < 0 && currPlayers.size() < 2)
        {
            retval = currPlayers.size();
            currPlayers.add(name);
            if (currPlayers.size() == 2)
            {
                // Once we have 2 players, we will reset rpsRounds
                // This clears out games played with other opponents.
                rpsRounds.clear();
            }
        }
        return retval;
    }

    // If a player is already in the game, then his index is returned (0 or 1)
    // Otherwise, -1 is returned

    private int getYourIndex(String name)
    {
        return currPlayers.indexOf(name);
    }

    // Return the name of the other player
    private String otherPlayerName(String yourName)
    {
        if (currPlayers.size() < 2)
            return null;
        if (yourName.equals(currPlayers.get(0)))
            return currPlayers.get(1);
        else
            return currPlayers.get(0);
    }

    // Return a String with the results of all of the rounds.

    public String publish_status(String name)
    {
        String end_of_line = System.getProperty("line.separator");
        int yourIndex = getYourIndex(name);
        if (yourIndex < 0)
            return "Disconnected from Rock Paper Scissors";

        String otherName = otherPlayerName(name);

        StringBuilder sb = new StringBuilder();
        for (int i=0; i < rpsRounds.size(); i++)
        {
            RpsRound rr = rpsRounds.get(i);
            sb.append(rr.publish(yourIndex,  otherName)+end_of_line);
        }
        return sb.toString();
    }
}






RpsRound.java


package rps;

import java.io.Serializable;

class RpsRound implements Serializable
{
    char[] picks = new char[2];
    RpsRound()
    {
        picks[0] = picks[1] = MyGameInput.NO_PICK;
    }
    boolean isComplete()
    {
        if (picks[0] == MyGameInput.NO_PICK || picks[1] == MyGameInput.NO_PICK)
            return false;
        else
            return true;
    }
    boolean insert(int index, char pick)
    {
        if (picks[index] == MyGameInput.NO_PICK)
        {
            picks[index] = pick;
            return true;
        }
        else
            return false; // Already filled in
    }
    String publish(int yourIndex,  String otherName)
    {
        int otherIndex;
        if (yourIndex == 1)
            otherIndex = 0;
        else
            otherIndex=1;

        char yourPick=picks[yourIndex];
        char otherPick = picks[otherIndex];
        String retStr="";
        if (otherName == null)
            return "Needing a Player";

        if (yourPick != MyGameInput.NO_PICK && otherPick !=  MyGameInput.NO_PICK)
        {
            retStr = "You:"+ choiceName(yourPick) +
                " -  " + otherName + ":" + choiceName(otherPick) +
                " =====> " + rps_results(yourPick, otherPick);
        }
        else
        {
            retStr = "Waiting on: " + ((yourPick==MyGameInput.NO_PICK)? "YOU, ": "") +
                    ((otherPick==MyGameInput.NO_PICK)? otherName: "");
        }

        return retStr;
    }



    public static String rps_results(char userInput,  char otherInput)
    {
        String response=" LOSE :-) !!";

        if ( userInput == otherInput)
        {
            response =  " Tied";
        }
        else
        {
            switch (userInput)
            {
            case MyGameInput.SCISSORS:
                if (otherInput == MyGameInput.PAPER)
                    response= " WIN!!";
                break;
            case MyGameInput.ROCK:
                if (otherInput == MyGameInput.SCISSORS)
                    response =  " WIN!!";
                break;
            case MyGameInput.PAPER:
                if (otherInput == MyGameInput.ROCK)
                    response = " WIN!!";
                break;
            default:
                response = " had bad input: " +userInput +
                            " -- Enter r,p,s for MyGameInput.ROCK, MyGameInput.PAPER, MyGameInput.SCISSORS";
            }
        }
        return response;
    }
    public static String choiceName(char choice)
    {
        switch(choice)
        {
        case MyGameInput.PAPER:
            return "PAPER";
        case MyGameInput.ROCK:
            return "ROCK";
        case MyGameInput.SCISSORS:
            return "SCISSORS";
        case MyGameInput.NO_PICK:
            return "NO-PICK";
        default:
            return null;
        }
    }
}



MyUserInterface.java


package rps;

import gameNet.GamePlayer;
import gameNet.GameNet_UserInterface;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

    class MyUserInterface extends JFrame
        implements GameNet_UserInterface, ActionListener
    {
        private GamePlayer myGamePlayer;
        private MyGameInput myGameInput;
        private JTextArea resultsTextArea = new JTextArea(20, 70);
        private JTextField pickTextField = new JTextField(5);

        public MyUserInterface()
        {
            super("RPS Game");
        }

        public void startUserInterface (GamePlayer player)
        {
            myGamePlayer = player;
            myGameInput = new MyGameInput();
            myGameInput.setName(myGamePlayer.getPlayerName());

            myLayout();

            myGameInput.setPick(MyGameInput.CONNECTING); // Send a msg to connect to the game
            myGamePlayer.sendMessage(myGameInput);
        }


        public void receivedMessage(Object ob)
        {
            MyGameOutput mg = (MyGameOutput)ob;
            String playerName = myGamePlayer.getPlayerName();
            String status = mg.gameStatus.publish_status(playerName);
            resultsTextArea.setText(status);
        }

        // We go here when hit the enter key on the pick pickTextField
        public void actionPerformed(ActionEvent e) {
            String str = pickTextField.getText();

            char pick=MyGameInput.NO_PICK;
            if ("q".equals(str))
            {
                exitProgram();
                return;
            }

            if ("r".equals(str))
                pick = MyGameInput.ROCK;
            else if ("p".equals(str))
                pick=MyGameInput.PAPER;
            else if ("s".equals(str))
                pick=MyGameInput.SCISSORS;

            myGameInput.setPick(pick);
            if (pick != MyGameInput.NO_PICK)
                myGamePlayer.sendMessage(myGameInput);
            else
                resultsTextArea.append(" Bad Input: " + str);

        }

        // Nice to let people know that you are going away.
        private void exitProgram()
        {
            myGameInput.setPick(MyGameInput.EXITING);
            myGamePlayer.sendMessage(myGameInput);
            myGamePlayer.doneWithGame();
            System.exit(0);
        }

        // Inner Class
        class Termination extends WindowAdapter
        {
            public void windowClosing(WindowEvent e)
            {
                exitProgram();
            }
        }

        // Setup all of the screen stuff
        private void myLayout()
        {
            setLayout(new BorderLayout());
            JPanel topPanel = new JPanel();
            topPanel.setLayout(new GridLayout(0,1));
            pickTextField.setBackground(Color.yellow);
            topPanel.add(new JLabel(myGamePlayer.getPlayerName()));
            topPanel.add(new JLabel("Enter r p s q for (Rock, Paper, Scissors, Quit)"));
            topPanel.add(pickTextField);
            add(topPanel, BorderLayout.NORTH);

            resultsTextArea.setBackground(Color.lightGray);
            JScrollPane scrolledText = new JScrollPane(resultsTextArea);
            scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

            add(scrolledText, BorderLayout.CENTER);
            pickTextField.addActionListener(this);
            addWindowListener (new Termination());

            setSize(800, 600);
            setVisible(true);
        }


    }



October 9, 2013 11:05 AM