显示标签为“MVC”的博文。显示所有博文
显示标签为“MVC”的博文。显示所有博文

2011年11月6日星期日

cocos2d meets MVC – Implementing simple board game part 2 [Bartek Wilczyński]

cocos2d meets MVC – Implementing simple board game part 2 [Bartek Wilczyński]:
In the first part of the cocos2d meets MVC series I described how to start implementing MVC paradigm for cocos2d based board game. The first post only scratched the surface, we have prepared a skeleton but we still have a lot to do.

Introducing model


In the previous part we introduced the View and the Controller. To comply with MVC paradigm we need to add a model which will represent the current state of a game board. Our implementation now should contain the following classes:

  1. GameBoardView - the View,
  2. GameBoardController - the Controller.
  3. GameBoard – the Model.

MVC diagram - introduced model


Model implementation


GameBoard implementation


Our requirement (described in the first part) is that:

…A game board is defined by a number of rows and columns, which may vary for different application levels.

We implement it in the following way:



@interface GameBoard : NSObject {
NSInteger numberOfRows;
NSInteger numberOfColumns;
}

- (id)initWithRows:(NSInteger)aNumberOfRows columns:(NSInteger)aNumberOfColumns;

@property (nonatomic) NSInteger numberOfRows;
@property (nonatomic) NSInteger numberOfColumns;

@end



Please notice that the model extends NSObject – the model should contain just the state of a game board (and the methods to update this state) – we shouldn’t put any view related concerns here.

GameBoardView implementation


We need to modify the View and pass it the Model, we do this in initWithGameBoard method.



@interface GameBoardView : CCNode {
GameBoard *gameBoard;
}

@property (nonatomic, retain) GameBoard *gameBoard;

- (id)initWithGameBoard:(GameBoard *)aGameBoard;

@end



Our implementation of a GameBoardView can look like this (rendering game board spaces omitted to simplify the code):



- (id)initWithGameBoard:(GameBoard *)aGameBoard {
if ((self = [super init])) {
// retain gameboard
self.gameBoard = aGameBoard;

// render gameboard background
CCSprite *gameboardSprite = [CCSprite spriteWithFile:@"gameboard.png"];
gameboardSprite.anchorPoint = CGPointMake(0, 0);

[self addChild:gameboardSprite];

// render spaces
for (int i = 0; i < gameBoard.numberOfRows; i++) {
for (int j = 0; j < gameBoard.numberOfColumns; j++) {
// position and render game board spaces
}
}
}

return self;
}



GameBoardViewController


Finally the implementation of an init method in the Controller should be updated – the View needs to have the GameBoard model injected in its init method so we construct the game board in Controller (just for now) and pass it to the View (later on we will create a game board based on a level definition).



- (id)init {
if ((self = [super init])) {
// initialize model
gameBoard = [[GameBoard alloc] initWithRows:7 columns:9];

// initialize view
view = [[GameBoardView alloc] initWithGameBoard:gameBoard];

[self addChild:view];
}

return self;
}



Handling touches


GameBoardView updates


In order to handle touches we need to slightly modify the View. We make it extend CCLayer instead of CCNode to have a possibility to handle touch events inside of it:



@interface GameBoardView : CCLayer {
...
}



The View itself should not be responsible for handling the actions that are results of user interaction with the game board so we will pass it to the Controller using protocol.



@protocol GameBoardViewDelegate
- (void)gameBoard:(GameBoard *)gameBoard touchedAtRow:(int)row column:(int)column;
@end



We also modify the init method of a GameBoardView so we can pass a delegate object that will be responsible for handling the touches:



- (id)initWithGameBoard:(GameBoard *)aGameBoard delegate:(id)aDelegate;



And the implementation is:



- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint point = [self convertTouchToNodeSpace:touch];

// calculate row and column touched by the user and call a delegate method
// ...
[self.delegate gameBoard:self.gameBoard touchedAtRow:row column:column];
}



GameBoardController updates


GameBoardController will be responsible for handling user touches, so we need to implement a GameBoardViewDelegate in a GameBoardController:



@interface GameBoardController : CCNode





- (void)gameBoard:(GameBoard *)gameBoard touchedAtRow:(int)row column:(int)column {
// do the game logic here and update view accordingly
}



The last step is to modify the View initialization in the following way (in init method):



// initialize view
view = [[GameBoardView alloc] initWithGameBoard:gameBoard delegate:self];



Summary


In this part we implemented the Model and we did the necessary steps to make it visible to the View and to Controller. We also setup an indirect link between the View and the Controller so if the user touches the space on a game board the Controller will be able to handle the action according to game rules. The next part will cover:

  • Updating the Model inside the Controller,
  • Notifying the View about the changes in the Model.

If you have any questions or remarks feel free to leave a comment after this post.



cocos2d meets MVC – Implementing simple board game part 1

cocos2d meets MVC – Implementing simple board game part 1

This is a first part of a series of posts that aim to help to understand how we can build a game in cocos2d using MVC pattern (or its variation adapted to cocos2d programming model). This is a follow up post to the previous posts that I wrote some time ago so if you haven’t read it before I suggest to at least read the first part which explains a bit of a theory.

Scenario

We are going to build a simple “framework” for building board puzzle games. This framework will be used in my new game and its core functionalities are as follows:
  1. A game board is defined by a number of rows and columns, which may vary for different application levels.
  2. The game board stores game pieces, and each game board’s space can contain only one game piece.
  3. The game board can be initialized with a number of “fixed” game pieces that cannot be moved by a player during the game.
  4. A toolbox is defined by a number of toolbox items that represents slots for movable game pieces.
  5. Toolbox item (slot) can contain many toolbox items of the same type.
  6. Game pieces can be moved from the toolbox item (slot) and put on the game board.
GameBoard example

Basic concepts

From wikipedia:
The model manages the behaviour and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller). In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.
The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it.
The controller receives user input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and a viewport to perform actions based on that input.
Following the definition from wikipedia we can identify the following main classes (we will add the model later on):
  1. GameBoardView that represents the main view of an application,
  2. GameBoardController that represents a controller for GameBoardView.
GameBoardController & GameBoardView relationship
Please notice that the solid line represents a direct association (controller holds a reference to the view), the dashed line is an indirect association (via observer). The indirect association will be used later on to implement touches.

Implementation

Project structure

After creating a new project in XCode 4 based on a default cocos2d template we create the following groups:
  1. View – views & controller classes (you can also divide it into two different groups but I like to keep it in the same place as those classes are tightly connected).
  2. Model – we will use it later for storing model classes.
MVC - project structure

GameBoardView implementation

We start with GameBoardView implementation. We make GameBoardView extend CCNode.
@interface GameBoardView : CCNode {
}
Then we implement init method of GameBoardView and we do some drawing here to check if everything works fine.
- (id)init {
    if ((self = [super init])) {
        // create and initialize a Label
 CCLabelTTF *label = [CCLabelTTF labelWithString:@"Hello World from view" fontName:@"Marker Felt" fontSize:48];
 
 // ask director the the window size
 CGSize size = [[CCDirector sharedDirector] winSize];
 
 // position the label on the center of the screen
 label.position =  ccp( size.width /2 , size.height/2 );
 
 // add the label as a child to this Layer
 [self addChild: label];
    }
 
    return self;
}

GameBoardController implementation

GameBoardController is responsible for initializing the view. It also holds a reference to GameBoardView for future needs.
@interface GameBoardController : CCNode {
    GameBoardView *view;
}
Because GameBoardController extends CCNode we can add GameBoardView as a child of GameBoardController.
- (id)init {
    if ((self = [super init])) {
        view = [GameBoardView node];
 
        [self addChild:view];
    }
 
    return self;
}

Final modifications

We modify AppDelegate and we run our newly created controller:
[[CCDirector sharedDirector] runWithScene: [GameBoardController node]];
And here it is for now. When you run your project the effect should be quite similar to default cocos2d template behavior. The difference is that we created a part of MVC project skeleton ready to implement necessary application logic.

Next steps

The project structure at this point is ready to introduce more advanced concepts:
  1. Handling touches.
  2. Introducing model.
If you are interested how I am going to approach it please follow my next #iDevBlogADay post in two weeks. Follow me @bwilczyn to get the latest updates and notification about a new post.
This entry was posted in idevblogaday, iPhone and tagged , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.