I have a basic GameController with a finite state machine to handle game logic.
I'm adding game modes and coming across problems cleanly implementing them. The core functionality of the game stays the same--Physics, input handling, level creation--but I have many places where I need an if/else block because functionality is slightly different. At two game modes it was manageable but not the nicest implementation. I'm adding an extra game mode and want to clean it up.
Here's some simplified example code (in C#):
void OnBlocksCleared(int count) {
score += getScoreFromClearedBlocks(count);
scoreController.setScore(score);
if (currentMode == GameMode.Endless) {
DataManager.Instance.AddTotalBlocksCleared(count);
} else if (currentMode == GameMode.Rush) {
// Do nothing
} else if (currentMode == GameMode.TimeAttack) {
if (allBlocks.Count <= 0) {
currentState = GameState.Win;
}
}
}
There are methods that have much more logic and only a single line if/else for a specific game mode (if TimeAttack time is up, if Rush level is completed, etc), and some methods like above where the if/else blocks take a lot of space. I was thinking about implementing an interface for each game mode but it wasn't easy to cleanly implement. Here is what I was planning:
public interface IGameBehavior {
void SetHighscore();
void OnBlocksCleared(int count);
void SetRemainingTime(float remainingTime);
}
Then I would have a EndlessBehavior, TimeAttackBehavior, RushBehavior and at the bottom of corresponding methods call the specific method like so.
void OnBlocksCleared(int count) {
// Do everything that's shared
gameBehavior.OnBlocksCleared(count);
}
This doesn't seem to work well because if the behavior needs to modify specifics of the gameController it will become tightly coupled. Also in many cases only one or two of the game behaviors actually do anything.