How to separate UI and logic in Objective-C based mobile games?
To develop games, I use Cocos2d library.
I need a good reference to separate my UI code from game logic code.
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.Sign up to join this community
The usual way to loosely couple complex objects in Objective-C is to use delegates with formal protocols.
In an iOS board game I'm working on, I have
@class PMGameState which stores the board and controls how you can move on it. And I have a
@class PMGameView that knows how to draw the board tiles. Each has a protocol associated with it:
@protocol PMGameStateDelegate <NSObject> - (void)game:(PMGameState *)game didApply:(YUUPoint)position; - (void)game:(PMGameState *)game didMoveFrom:(YUUPoint)a to:(YUUPoint)b; - (void)gameDidWin:(PMGameState *)game; @end @protocol PMGameViewDelegate <NSObject> - (void)gameView:(PMGameView *)view didTap:(YUUPoint)position; - (void)gameView:(PMGameView *)view didSwipeTowards:(YUUPoint)position; @end
And in the classes themselves, e.g.
@property (nonatomic, weak) id <PMGameViewDelegate> delegate;
Then, a controller implements both and mediates between them:
@interface PMViewController : UIViewController <PMGameStateDelegate, PMGameViewDelegate>
This controller is the delegate for both the game controller and the view. It handles
game:didMoveFrom:to: and can tell the view to update that position. It handles
gameView:didTap: and can tell the game controller how the player wants to move.
You can see many more examples of this style in Apple's own APIs. Almost all objects with non-trivial state or feedback use a formal protocol rather than inheritance or a big set of selector/target pairs.
Hmm...I'm not quite sure about this but I treat UI as MVC. I separate them into those domains. The game will only talk to the controllers so that you will not need to know anything about the view. That way the game logic, UI logic, and the view itself are all separated.
I actually did a CCView and CCViewController myself (though it needs more refinement). This helps me to change view whenever I want (esp. we have iPhone5 now).
The game itself has a different architecture. I'm using Component Design for the game.
I'm still not sure about this because I just made it up myself since it seems to work for me. If there are better approach, I'm open to it.