问题
I'm curious if there is a good strategy for handling various game types inside a game that run off the same main game loop? In other words, I have a game with three different game types. There are only a few minor differences between each type, so they currently run using the same loop/classes. One is a 'how many X's can you get before time runs out', another is 'how long does it take you to capture 10 X's', and the last is a 'practice/ infinite time' game type. Right now my strategy is to run an if, then, else check at all differentiating parts of the game and perform the appropriate logic for each game type.
if (gameType == INFINITE)
{...}
else if (gameType == TIMED)
{...}
else
{...}
This seems horribly wrong to me, and also inefficient. I don't want to bog down the CPU with all these unnecessary checks when it seems like I could do this check once and proceed forward. I also do not want to copy-paste all of my classes to only make minor changes in each. Is there a good way to do this?
回答1:
One way to handle that is to create a screen manager system. This essentially means that you have an abstract class with update and draw operations. Each game (screen) you have then inherits from this, allowing each to have its own update/draw behavior. Ultimately you need to have an if-else or switch statement to decide which to draw/update. One way to minimize this is to keep track of the current "screen" using a variable of your abstract type, you can then polymorphically assign whichever screen needs to be update/drawn to that variable. Then when you call update or draw on the current screen you don't need to know it's concrete type.
There are lots of examples out there, a decent XNA one can be found at: http://xbox.create.msdn.com/en-US/education/catalog/sample/game_state_management
The idea is completely transferable. Most use this system to add menu screens and things, but there is no reason it couldn't be used for your purpose.
来源:https://stackoverflow.com/questions/15255241/game-design-handling-different-game-types