Implementing a 4×4 Game Board

Implementing a 4×4 Game Board

I struggle with efficiency in code, and I want to start my game off on the right foot.
I have a game that I'm making a 4 x 4 map of 'tiles' that a user can build their 'town' on.  To keep track of the tiles, I'm planning on simply having a size-16 array of the type of my 'mapTile' enum. EX:
enum MapTiles { defaultTile, homeBase, farm1, farm2 /*...and so on...*/ };
static MapTiles playerMap[] = MapTiles[16] { /* ... default map setup ... */ };

Is there a way that is more efficient or more easy-to-extend way to implement such a map?
I'm using Unity and C# mostly, though i'm willing to work with any Unity-capable language if you have a clever answer.

Solutions/Answers:

Answer 1:

enum is actually a good idea here, but what you want is for the enum to be:

enum MapTileBuilding { defaultTile, homeBase, farm1, farm2 /*...and so on...*/ };

and a class

class MapTile
{
   MapTileBuilding building;
   ... //other members e.g.
   //structuralStrength
   //isOnFire
   //troopCount
   //incomeGenerated
   //etc.
}

…which gives you the ability to support your initial building type property, as well as other properties you may wish to add to each tile later.

Finally, your array:

MapTile[,] map = new MapTiles[4, 4];

Do not inherit when composition will do (i.e. what you are already doing), otherwise you end up restricting yourself into narrowly-defined class hierarchies as you continue to try to extend the system. You want your tiles to be composable and inheritance is at odds with that idea. You’ll begin adding new components as other concepts come into play (see examples above), and you don’t want inheritance chains in your way at that point.

Re array dimensionality, the only time you will ever use a 1D array for a 2D concept is when you want precise control over memory access in low-level code (say in C or ASM), that is, in your case and in C# in general, just use the conceptually simpler 2D array.

P.S. Sorry if syntax is slightly off, C# isn’t my first language these days.

Answer 2:

Maybe enum is not the best choice in this case. You could try building a “tile” class and derive several subclasses from it (farm from your example). This way you could implement some sort of levelling system (instead of having to create a value for each level (farm1, farm2 etc)) inside the class and give the several kinds of tiles unique abilities in form of functions.

What you could also do is replacing the one-dimensional array with a two dimensional one.
MapTiles[,] playerMap = new MapTiles[4, 4]

Long story short: Try to stay objectoriented and use classes, makes expansion of functionalities much easier.

References