In all the Java code you write from now on you are expected to adhere to the elements of good programming practice identified in lectures, and illustrated in any example Java source code you are provided with.
This chapter covers
good programming practice
and
enumerations.
these topics were outlined in the
good practice and enumerations presentation
(opens in new window) that you should review.
One aspect of good programming practice is the appropriate use of enumerations and so we shall review these here and apply to the tiled map case study.
In the previous tiled map model we used an array of boolean values to represent the tiles. this is fine when we are in a terrain context that only requires to discriminate between passable and impassable tiles. What if we require to use a more complex terrain context with, for example, grass, hedge, water, fence and soil tiles?
An obvious solution is to use a 2D array of integers rather than booleans, with different integer values representing different terrain types. For example, 0=grass, 1=hedge, 2=water, 3=fence, 4=soil.
However this approach is not very readable, robust or maintainable.
A preferred representation of multiple terrain types is an enum, with one value for each different kind of terrain type. This also looks forward to a more featured terrain type representation where the enum is used to define associated attributes such as rendering character/colour and other features.
switch (mMap[x][y]) { case TerrainType.GRASS: ... ... ... ... ... ... }
While the use of the switch statement in printing out a tile as a character works effectively it results in the tiledMap3 class being what we call strongly coupled to the Terraintype enumeration. That is, we explicitly code in specific enum balues in the case elements.
This means that our TiledMap3 class is now specific to only one particular terrain context; for example, what would we have to change if we were now to map an computer room that had floor, table, chair and computer terrain types?
there is a more elegant solution to our problem in which we can do away with the switch statement and leave the TiledMap3 class entirely de-coupled of the actual Terraintype values (although obviously it still needs the type). We do this by amending the Terraintype definition to expose an attribute that will provide a single character representation for each value. This character can then be used in the render() method to print a more readable version of a map.
We will code this in the following steps and you can follow the details by reviewing again the Oracle enum types tutorial.
public enum TerrainType { GRASS ('.', true), ...; ... ... ... } // end Terraintype enumeration.
Remember that from now on you are expected to adhere to the elements of good programming practice identified in lectures and illustrated in any example Java source code you are provided with.