Java Tutorial Lesson 10: Restructuring classes

From Erlands Wiki

Jump to: navigation, search

In the last lesson the “Game” class and the main method were getting a bit to large, so in this lesson its your job to try to restructuring it a bit.

The “Game” class has now been modified an looks like this:

public class Game {
    public static void main(String[] args) {
        if(args.length<2) {
            System.err.println("You must specify width and height of map");
            System.exit(1);
        }
        int mapX = 0;
        int mapY = 0;
        try {
            mapX = Integer.valueOf(args[0]).intValue();
            mapY = Integer.valueOf(args[1]).intValue();
        } catch (NumberFormatException e) {
            System.err.println("The width and height of map must be integers");
            System.exit(1);
        }
 
        int roomId=1;
        GameMap map = new GameMap(mapY,mapX);
        for (int y = 0; y < mapY; y++) {
            for (int x = 0; x < mapX; x++) {
                Room r = new Room(String.valueOf(roomId++));
                map.setRoom(y,x,r);
            }
        }
 
        System.out.println("Lesson 10");
        System.out.println();
        map.print();
    }
}

As you can see some of the logic has been extracted into a new class “GameMap”, your work is to implement this new “GameMap” class so the program can be called with:

java Game 3 3

The output should look something like the following:

Lesson 10
 
------------------------------
|        ||        ||        |
|   1    ||   2    ||   3    |
|        ||        ||        |
------------------------------
------------------------------
|        ||        ||        |
|   4    ||   5    ||   6    |
|        ||        ||        |
------------------------------
------------------------------
|        ||        ||        |
|   7    ||   8    ||   9    |
|        ||        ||        |
------------------------------

The “Room” class is exactly the same as in Lesson 9, so you can take the source from there.

Some optional extensions in the same line

  1. Write a separate LevelManager class that works with the following Game class. The Game class is called with a single in-parameter which is the level number. A suggestion is to make the LevelManager.getLevel method return a differently looking GameMap for different level numbers.
public class Game {
    public static void main(String[] args) {
        if(args.length<1) {
             System.err.println("You must specify level");
             System.exit(1);
        }
        int levelNo = 0;
 
        try {
            levelNo = Integer.valueOf(args[2]).intValue();
        } catch (NumberFormatException e) {
            System.err.println("The level must be integers");
            System.exit(1);
        }
 
        GameMap map = LevelManager.getLevel(levelNo);
 
        System.out.println("Lesson 10");
        System.out.println();
        map.print();
    }
}
Personal tools