CSC

 

Lab assignment 3 - Rock, paper, scissors

A grafic client program where a user plays against a server

In lecture 5 or 6 a server program was written which plays "rock, paper, scissors" with its clients. The code is available here. Your task is to write a graphical client program using Swing components, namely JFrame, JTextField, JLabel, JButton, ImageIcon and Box or JPanel. Feel free to replace or add to these suggested components! The game is widely known, and you can find useful material at Rock, paper, scissors, e.g. three gif images.

Note: the server speaks Swedish, so either change the server code (and run the server locally), or translate the replies from the server inside the client program ("STEN" --> ROCK, "SAX" --> SCISSORS, "PÅSE" --> PAPER).

This program connects to a server. If the server is down, start it on the computer you're working on. Intructions for running a local server are available here: localserver.html

Server program free from swedish letters. A version of the server without åäöÅÄÖ runs through port 4713, its code is available here: Server4713.java. It plays STEN, SAX, PASE. Of course you may copy it and replace the swedish words with english.

A simple client

Start off by making a client without the graphics, using the following code to open a connection to the server.
  try{
     Socket socket=new Socket("p6-ray.nada.kth.se",4712);
     BufferedReader in=new BufferedReader(new InputStreamReader(
                           socket.getInputStream()));
     PrintWriter ut=new PrintWriter(socket.getOutputStream());
     ut.println("Charlotta"); ut.flush();
     System.out.println(in.readLine());
  }
If the server is down, try the one at rungner by replacing "p6-ray.nada.kth.se" with "rungner.nada.kth.se". The client should send your name to the server listening on port 4712 and display the answer from the server. Remember to do ut.flush(), or the name won't be sent. The code above must be supplemented before it runs and in order to test the server. Send a few messages to the server and verify that it answers with "STEN", "SAX" or "PÅSE" (or your replacements, if you chose to change the server). To close the connection, send some input that the server reads as null or as the empty string. You can e.g. use an empty String (""), Ctrl-D och Ctrl-Z. Once the simple client works you can focus completely on the graphical interface.

The Swing components

Your program could be a
public class Client extends JFrame implements ActionListener{
where the left half of the window is your game area and the right half is that of the computer. Use BoxLayout since this often gives good results. Each game area is a vertical Box which contains, in order from top to bottom:
  • Header, a JLabel with either Me: or Computer:.
  • Message, a JTextField where whatever is being sent from you or from the server is shown (first the greeting, then "ROCK", "PAPER" or "SCISSORS").
  • A button showing "rock"
  • A button showing "paper"
  • A button showing "scissors"
  • Result, a JLabel which after one click displays ONE..., after a second click TWO... and after a third click displays WINS, DRAW or LOSES (further explanations below under The game.
  • Score, a JTextField which displays Score: 7
All the little text fields above can be represented with JLabel but JTextField is sometimes preferred when you create components that are initially empty (no text). It is mainly a matter of taste which you use.

Define a class GameArea and create two instances of it next to each other in a horizontal box. One advantage of a box is the ability to put fixed spaces between the components inside. With the declaration

   Box box=Box.createHorizontalBox();
you can do this:
   GameArea me=new GameArea("Me:");
   GameArea you=new GameArea("Computer:");
   box.add(me);
   box.add(Box.createHorizontalStrut(20)); //Spacer
   box.add(you);
The Box-object may now be added to the JFrame by calling the method add.

JPanel and GridLayout

If Java and its graphic components are new to you, it may be a better idea to use a JPanel with a GridLayout. This layout is more basic and easier to manage but less flexible than BoxLayout but it is certainly possible to create a nice looking layout with this one too! The game area should be divided into five fields where the tree buttons will occupy the three middle fields. For the upper and lower fields, use JPanels with GridLayout with subdivision into two or more fields.

The game

The user clicks the "ROCK", "PAPER" and "SCISSORS"-buttons and the third click is registered as the user's move. The two preceding clicks must be counted and texts "ONE..." and "TWO..." respectively displayed in the result field. The third click also causes the computer to make its move and the program to settle the winner or that the game is undecided (no winner or loser). Fields for Message, Result and Score must be updated. The game goes on forever if you do not program it to stop which is up to you.

Hints and advice

  • If GameArea inherits from Box you can start the constructor with
    super(BoxLayout.Y_AXIS) to make it vertical.
  • The images can be created in the declaration ImageIcon rock=new ImageIcon("rock.gif") and collected in an array Icon[] imgs={rock,scissors,paper}.
  • You may have use for a corresponding text array String[]text={"ROCK","PAPER","SCISSORS"}.
  • In the GameArea class there could be an array of buttons. Although there is no text on the buttons, one can associate them with a text by using button[i].setActionCommand(text[i]). This can then be retrieved in actionPerformed by e.getActionCommand().
  • Current moves must be indicated in the game area by color change of the corresponding button (for both player and computer). Design a method in class GameArea for this purpose. This method may also do other updates of the game area but it is probably most convenient to have a couple of updating methods.
  • For each click which is a user move, receive a server message which is sent to one of the updating methods of the computer area.
  • You need a global variable which counts to three, and then returns to zero. And every player needs a score counter. Where should that be placed?
  • The idea is that the first two clicks don't count. They are just preparations for the third and final click.
  • You are not forced to use the Model-View-Controller pattern (like in the last assignment) or make a text-based client, but it might be a good idea.
  • It is quite nice but not required to have a button that closes the server connection and exits from the program.

Lab demonstration

  • Run the grafic client program using the server to play the game. The gameareas must fullfill the requirements above.
  • The program must have at least two classes and the two game areas must be different objects of one class.
  • After each move, buttons must change color (e.g. to yellow) to reveal the moves of the person and the computer.
  • After each move, information must be displayed showing the moves as texts, the outcome as winner, loser or undecided (draw) in the message field, and the score.
  • A move is made after each tree clicks by the person. Clicks number one and two must be indicated by displaying "ONE..." and "TWO..." in the result field.
  • Think carefully about the logics of the program so that it does not become unnecessarily long and complicated. E.g., to find out who is the winner can take 9 if-statements or only two. Go for the latter! It is actually possible to do it without ifs, if you set up the proper data structure in advance. Also avoid repetition of code!
  • Updating of the game areas must be made by calling a few methods, direct setting of variables is not allowed.
  • Consult the lab demonstration rules and make sure you can answer all questions applicable to lab 3!

As extra assignment, choose one of the following::

Extra assignment, alt. 1 Add sound effects! This may require headphones on some computers. There must be at least three different sounds (move, win, lose). It must be possible to interactively turn the sound on and off while playing.

Extra assignment, alt. 2 Extends the graphical interface of the program so that the server connection is initiated interactively. Let the user choose server and port number, either from predefined alternatives or by writing into TextFields.


Published by: <ann@nada.kth.se>
Last updated: april 23, 2010
Technical support: <webmaster@nada.kth.se>