bild
Skolan för
elektroteknik
och datavetenskap

Lab assignment 2

Goals

  • To understand Javas interface concept and how to use it to specify the dependence between classes and keep the dependance small.
  • To understand Model-View-Control and use it in an implementation with a Model class and a ViewControl class (i.e. the View and Control parts are implemented together in ONE class).
  • To understand and create a Mock object (Mock object is here defined as a minimal implementation of an interface).
  • To be able to handle many buttons with listeners and to build a simple GUI.
  • To implement the logics of a small game clear and simple.

Model

Choose a simple game that is played on a square gameboard by choosing on one square at a time. Examples of such games: Fifteen puzzle, 3x3 TicTacToe, nxn TicTacToe, Memory, Othello. Write a class that implements a Model of the game using the following interface:
public interface Boardgame {
   boolean move(int i, int j); //returns true for a successful move, false otherwise
   String getStatus(int i, int j);
   String getMessage();
}
In each move, a square is chosen (indices i and j). The status of the game is updated inside the Model class which must contain a representation of the nxn squares of the game e.g. as a String matrix. The value of each matrix position is available through method getStatus. Calling method getMessage() returns a message telling the user whether the last move was successful or not. If the last move was erroneous, the nature of the error should be contained in the message. The class may be used with a text based ViewControl or a graphical ViewControl.

NO GRAPHICS IN THE MODEL CLASS!
NO REFERENCE TO ANY CLASS INCLUDING GRAPHICS IN THE MODEL CLASS!
.

For a two-person-game, the model must keep track of which player is in turn to play. The message returned b getMessage() should include this information. After every other successful move, the turn toggles to the other player.

The following detailed instructions cover the game Fifteen puzzle. TicTacToe has the same level of difficulty as Fifteen puzzle. Memory is a bit more difficult and Othello is much more difficult.

Task 1 – Implement a Fifteen puzzle

Before you start, read at least to (including) task 2. which implies testing the model.

Are you not familiar with the Fifteen puzzle? If not, read wikipedia:
http://en.wikipedia.org/wiki/Fifteen_puzzle.

Run Anns Fifteen puzzle here: Run Fifteen_puzzle (only swedish message texts)

Write a class

// Pleas note! No import statements are needed in FifteenModel.
// No graphics in FifteenModel. !!!

class FifteenModel implements Boardgame {
  // Implement the Boardgame-methods
  // Declare other variables and methods 
  // needed in the Fifteen puzzle.
}
Let the Boardgame methods be public and all other variables och methods private. The following data may be handy in the Model class:
  private String currentMessage = "No message yet";
  private String[][] status = new String[4][4];  // representation of the board
  private int iemp, jemp;                        // index to empty square in 15-puzzle
When the game is running, the current player chooses a square next to the empty one. The chosen square is then moved to the empty square.
  • At the start of the game, the numbers should be in a "shuffled" order.
    Can be achieved by repeatedly calling move(i,j).
  • It is not required to detect that the puzzle is solved.
Please note: No buttons, colours, windows or other graphical components in the Model class.
Study the test program and the example run of the program carefully.

Task 2 – Test of FifteenModel

Try out your game with the following test program. Download the program here. Text15.java.
import java.util.*;
class Text15 {
    public static void main(String[] u) {
        Scanner scan = new Scanner(System.in);
        Boardgame thegame = new FifteenModel();                 // new
        System.out.println("\nWelcome to Fifteen puzzle\n");
        while (true) {
            // Print out the current status
            for (int i=0; i<4; i++) {
                for (int j=0; j<4; j++)
                    System.out.print("  " + thegame.getStatus(i,j)); // getStatus
                System.out.println();
            }
            System.out.println();
            System.out.print("Your move: ");
            int i = scan.nextInt();  // get integer from the terminal
            int j = scan.nextInt();
            thegame.move(i,j);	                             // move
            System.out.println(thegame.getMessage());	     // getMessage
        }
    }
}
Study the testprogram carefully and look especially at the communication with the model class. It is done only through the interface methods. The model is created on the first commented line. Interface methods are called to show the status, to make moves and to display the current message. In Text15 is also demonstrated how a Java program can read input from a terminal with help class Scanner. Click here to see a printout from running Text15: Text15-demo.

It is slow and a bit difficult to play the Fifteen puzzle in a text window. The graphical version is more fun.

Task 3 – View-Control

Write a graphical class that shows and plays a nxn Boardgame with nxn buttons. Constructor parameters must be n and an object of Boardgame. Above or under the buttons there must be a message field where the result of calling getMessage() is displayed. In ViewControl the game is played, i.e. the methods of interface Boardgame are called but the ViewControl class does not "know" anything about the actual game (if it is TicTacToe or Fifteen puzzle or something else). All that is known to ViewControl is the methods of the interface. The communication is similar to that of the testmethod in Text15.

When a user is playing he/she clicks a button, the button represents an (i,j)-position of the board. i and j are detected somehow (perhaps read from the button object). Then the interface methods are called: move(i,j) to make a move and getMessage() to comment the move. In most games only a few of the positions of the board are updated in each move. For simplicity, update all the buttons each time, i.e. write nested for loops and call getStatus(i,j) for all positions of the board. Class ViewControl could start like this:

// appropriate import statements
class ViewControl extends JFrame implements ActionListener {

    private Boardgame game;
    private int size;
    private Square[][] board;        // Square is a subclass of JButton
    private JLabel mess = new JLabel();

    ViewControl (Boardgame gm, int n){  // Additional parameters are OK 
         ...
    }
Suggestions

  • A subclass of JButton that stores the indices i and j is recommended.

  • Test the class before it is complete by making button clicks print out texts like

       "You pressed button 3 1 " i the terminal.

    It may be a good idea to introduce Boardgame in ViewControl as the very last thing, when the button pressing seems to be working. Another option is to set the Boardgame-parameter to null while testing ViewControl.

  • All squares (JButtons) in ViewControl are the same colour but their texts differ.

Task 4 – Combine Model and ViewControl

Combine Model and ViewControl to a playable game.

Task 5 – A Mock Object for another game

Implement Boardgame for another game but without the functionality of the game, as a Mock Object. No logics at all is required and the methods can do next to nothing. They may return the same answer on every call, just make it the correct type. Use another size of board than in Task 4! Combine the mock object with ViewControl.

To demonstrate for the basic assignment

  1. A class that implements Boardgame and is the Model class of simple game. No graphics is allowed in the class.
  2. The running of a text based program or main method in the Model class that test the Model. It is fine to use the program Text15 above.
  3. A general ViewControl-klass with nxn buttons playing a Boardgame. ViewControl only knows the interface methods.
  4. A program that combines the model and the ViewControl to a playable game.
  5. A mini-implementation of another game using ViewControl and a "Mock Object" for the game model.
  6. UML class diagram including names of the most important classes and interfaces and the public methods. Other methods and variables need not be included.

Ask for a signature on your signature sheet!

Extra assignment

Two alternatives, choose ONE!
  1. Choose another game than in the basic assignment. Implement its model class as an implementation of interface Boardgame, combine with ViewControl to a playable game. The textbased test is not required.
  2. The Othello game is much harder to implement than TicTacToe or Fifteen puzzle. If you choose Othello as your first game, it counts as both basic assignment and extra assignment.

    Two of the important learnings from this assignemnt is how to work with an interface and to make the dependency between classes small. To create a pretty-looking game does not have high priority. Othello can be played with two different text symbols. If you think this looks too dull, you are free to make small changes in the Boardgame interface in order to get a prettier Othello. But, make sure you fully understand the "transparent" version of ViewControl required in the basic assignment.

Copyright © Sidansvarig: Ann Bengtsson <ann@nada.kth.se>
Uppdaterad 2014-03-30