I am trying to create a game with multiple levels (10 at the moment). I create a class for each level however this would be very, very tedious if more levels were to be added. My question is, how can I reuse a layer/class to have all levels of the game? The only difference for each level is the number of targets and the positions of the targets. Other than that, everything is pretty much the same.
Share
Make a class called something like LevelLayer which implements all of the logic from one of the levels. Now, create a new class called Level1Layer which implements LevelLayer.
Now progressively move code that is specific to level1 from LevelLayer into Level1Layer until LevelLayer contains only code that is useful to all levels.
Now create a Level2Layer that inherits from LevelLayer. Note that suddenly most of the code for this level is already done and can be called via the methods on the base class (LevelLayer).
By doing this iteratively you end up with a base class (LevelLayer) which consolidates all of the code to do with being a generic level, with the specific code for each level being hived off in a class corresponding to the particular level.
Note that after a while you should have gotten to a point where code that both level1 and level2 needs is in LevelLayer, and code and data that only level1 needs is in Level1Layer and code that only level2 needs is in Level2Layer.
After a while you may find that all of the levels differ only by a particular data item (e.g. an int array containing the map). In this case you may want to create a class that takes this data item via the constructor (or deserializes it from a file, the path of which is supplied to the constructor) which implements LevelLayer.
At this point you will be able to spend most of your time editing the data files (the “level” files) rather than code.