Some icing on the cake after cocos2d-x finishes the game

Source: Internet
Author: User

In this chapter, we will add new scenarios. When You get rid of a certain number of monsters, "You Win" is displayed on the screen, and "You Lose" is displayed when a monster escapes from the left side of the screen ".

Next we will create two new files in the class directory, GameOverScene. cpp and GameOverScene. h.

Contents of GameOverScene. h

1 # ifndef _ GAME_OVER_SCENE_H _

2 # define _ GAME_OVER_SCENE_H _

3

4 # include "cocos2d. h"

5

6 class GameOverLayer: public cocos2d: CCLayerColor

7 {

8 public:

9 GameOverLayer (): _ label (NULL ){};

10 virtual ~ GameOverLayer ();

11 bool init ();

12 LAYER_NODE_FUNC (GameOverLayer );

13

14 void gameOverDone ();

15

16 CC_SYNTHESIZE_READONLY (cocos2d: CCLabelTTF *, _ label, Label );

17 };

18

19 class GameOverScene: public cocos2d: CCScene

20 {

21 public:

22 GameOverScene (): _ layer (NULL ){};

23 ~ GameOverScene ();

24 bool init ();

25 SCENE_NODE_FUNC (GameOverScene );

26

27 CC_SYNTHESIZE_READONLY (GameOverLayer *, _ layer, Layer );

28 };

29

30 # endif // _ GAME_OVER_SCENE_H _

1 # import "cocos2d. h"

2 @ interface GameOverLayer: CCLayerColor

3 {

4 CCLabel * _ label;

5}

6

7 @ property (nonatomic, retain) CCLabel * label;

8 @ end

9

10 @ interface GameOverScene: CCScene

11 {

12 GameOverLayer * _ layer;

13}

14 @ property (nonatomic, retain) GameOverLayer * layer;

15 @ end

Conversion points:

1. In the objc header file, the class member functions can be directly implemented in the. m file without declaring them. Cpp does not allow this. So we will have multiple bool init ();

2. since cpp does not have a powerful keyword such as self, the CCLayer: node () and CCScene: node () methods must be implemented by the derived class, it cannot be inherited from the parent class as objc and changed to an object pointing to itself by the self keyword. The node () method is very convenient. It integrates methods such as new, init, and autorelease to reduce the amount of code of the caller. However, since the code for each node method is similar, we have made two macros to facilitate LAYER_NODE_FUNC and SCENE_NODE_FUNC. to use these two macros, you must implement the bool init () method in the derived class.

3. constructor and init method. When the cocos2d-x is rewritten from objc to cpp, it does not directly turn the content of init into the C ++ constructor, mainly for this consideration: C ++ constructor has a natural defect-no return value. This causes the C ++ constructor to rely on try-catch to catch logical exceptions. Generally, try-catch is not used by many people. Enabling try-catch will increase the size of compiled binary programs, and try-catch is not supported in android NDK. Therefore, we adopt the popular "two-stage constructor" method, that is, to call the constructor before calling init to process the initialization logic. This idea applies to both the interface design of Apple iOS (for example, [[NSString alloc] init], that is, the two-phase structure) and the C ++ class used by the samsung bada operating system.

4. @ synthesize in objc implements the setter and getter attributes of _ label and _ layer. We have implemented a series of macro definitions in cocos2dx \ include \ Cocos2dDefine. h to simulate the functions of @ property and @ synthesize. In the above Code, we use the CCX_SYNTHESIZE_READONLY macro to implement read-only class member variables. Only getter does not have a setter. Because the VC ++ rule is that the inline function can only be implemented in the header file, @ synthesize is from objc. m file to. in the H file, it is implemented together with the member variable declaration.

Content of GameOverScene. cpp

1 // cpp with cocos2d-x

2 # include "GameOverScene. h"

3 # include "HelloWorldScene. h"

4

5 using namespace cocos2d;

6

7 bool GameOverScene: init ()

8 {

9 if (CCScene: init ())

10 {

11 this-> _ layer = GameOverLayer: node ();

12 this-> _ layer-> retain ();

13 this-> addChild (_ layer );

14

15 return true;

16}

17 else

18 {

19 return false;

20}

21}

22

23 GameOverScene ::~ GameOverScene ()

24 {

25 if (_ layer)

26 {

27 _ layer-> release ();

28 _ layer = NULL;

29}

30}

31

32 bool GameOverLayer: init ()

33 {

34 if (CCLayerColor: initWithColor (ccc4 (255,255,255,255 )))

35 {

36 CCSize winSize = CCDirector: sharedDirector ()-> getWinSize ();

37 this-> _ label = CCLabelTTF: labelWithString ("", "Artial", 32 );

38 _ label-> retain ();

39 _ label-> setColor (ccc3 (0, 0, 0 ));

40_label-> setPosition (ccp (winSize. width/2, winSize. height/2 ));

41 this-> addChild (_ label );

42

43 this-> runAction (CCSequence: actions (

44 CCDelayTime: actionWithDuration (3 ),

45 CCCallFunc: actionWithTarget (this,

46 callfunc_selector (GameOverLayer: gameOverDone )),

47 NULL ));

48

49 return true;

50}

51 else

52 {

53 return false;

54}

55}

56

57 void GameOverLayer: gameOverDone ()

58 {

59 CCDirector: sharedDirector ()-> replaceScene (HelloWorld: scene ());

60}

61

62 GameOverLayer ::~ GameOverLayer ()

63 {

64 if (_ label)

65 {

66 _ label-> release ();

67 _ label = NULL;

68}

69}

1 // objcwith cocos2d-iphone

2 # import "GameOverScene. h"

3 # import "HelloWorldScene. h"

4

5 @ implementation GameOverScene

6 @ synthesize layer = _ layer;

7

8-(id) init

9 {

10 if (self = [super init])

11 {

12 self. layer = [GameOverLayer node];

13 [self addChild: _ layer];

14}

15 return self;

16}

17

18-(void) dealloc

19 {

20 [_ layer release];

21 _ layer = nil;

22 [super dealloc];

23}

24

25 @ end

26 @ implementation GameOverLayer

27 @ synthesize label = _ label;

28

29-(id) init

30 {

31 if (self = [super initWithColor: ccc4 (255,255,255,255)])

32 {

33 CGSize winSize = [[CCDirector shareddire] winSize];

34 self. label = [CCLabel

35 labelWithString: @ "" fontName: @ "Arial" fontSize: 32];

36

37 _ label. color = ccc3 (0, 0 );

38 _ label. position = ccp (winSize. width/2, winSize. height/2 );

39 [self addChild: _ label];

40

41 [self runAction: [CCSequence actions:

42 [CCDelayTime actionWithDuration: 3],

43 [CCCallFunc actionWithTarget: self

44 selector: @ selector (gameOverDone)],

45 nil];

46}

47 return self;

48}

49

50-(void) gameOverDone

51 {

52 [[CCDirector shareddire]

53 replaceScene: [HelloWorld scene];

54}

55

56-(void) dealloc

57 {

58 [_ label release];

59 _ label = nil;

60 [super dealloc];

61}

62

63 @ end

Note: The above GameOverScene. cpp has two objects, one scene and one layer. A scene can contain multiple layers, this layer only has a text label in the middle of the screen, which is displayed in three seconds and then returned to HelloWorldScene.

Conversion points

1. Pay attention to the GameOverLayer. _ label and GameOverScene. _ layer attributes again. These two attributes are declared as @ property (nonatomic, retain) in the objc header file, that is, they are retaken once. Therefore, the release method must be called in dealloc. Similarly, we are ~ GameOverLayer () and ~ In the GameOverScene () destructor, the release () attributes must correspond to a retain, therefore, _ label-> retain () and _ layer-> retain () are added to both init methods ();

2. with regard to the NSAID utoreleasepool, there is also an imitation implementation in the cocos2d-x, this simple garbage collection mechanism is a good news for C ++ programming; it uses the same principles as the NSAID utoreleasepool on iOS, reference Apple documentation http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSAutoreleasePool_Class/Reference/Reference.html

Simply put, when using an object pointer that inherits from the NSObject class in a cocos2d-x, the following two situations require the user to call a release

The users class object is new by the user. For example, CCSprite * sprite = new CCSprite ();

The struct class object is created and returned through a static function, such as CCSprite * sprite = CCSprite: spriteWithFile (...), in this case, user release is not required. However, if you call sprite-> retain (), a corresponding sprite-> release () is required.

Back to the problem, GameOverScene should be called under certain conditions: a certain number of monsters have been killed or some monsters have jumped out.

We add a variable in HelloWorldScene to calculate how many monsters a hero has killed.

11 // cpp with cocos2d-x

22 protected:

33 int _ projectilesDestroyed;

11 // objc with cocos2d-iphone

22

33 int _ projectilesDestroyed;

And initialize it in HelloWorld: HelloWorld,

1 // cpp with cocos2d-x

2_projectilesDestroyed = 0;

GameOverScene. h is included in HelloWorldScene. cpp.

1 // cpp with cocos2d-x

2 # include "GameOverScene. h"

1 // objcwith cocos2d-iphone

2 # import "GameOverScene. h"

In the targetsToDelete loop after removeChild (target) in the HelloWorld: update method, add the count and check the winning condition. If the target is exceeded, "You Win!" is displayed! "Interface

1 // cpp with cocos2d-x

2_projectilesDestroyed ++;

3if (_ projectilesDestroyed> 30)

4 {

5 GameOverScene * gameOverScene = GameOverScene: node ();

6 gameOverScene-> getLayer ()-> getLabel ()-> setString ("You Win! ");

7 CCDirector: sharedDirector ()-> replaceScene (gameOverScene );

8}

1

2 // objc with cocos2d-iphone

3_projectilesDestroyed ++;

4if (_ projectilesDestroyed> 30)

5 {

6 GameOverScene * gameOverScene = [GameOverScene node];

7 [gameOverScene. layer. label setString: @ "You Win! "];

8 [[CCDirector shareddire] replaceScene: gameOverScene];

9}

Match the failure condition: if any monster crosses the far left of the screen, you will be down. Then modify the spriteMoveFinished method and add the "You Lose" code in the if (sprite-> getTag () = 1) condition:

1 // cpp with cocos2d-x

2 GameOverScene * gameOverScene = GameOverScene: node ();

Jsonameoverscene-> getLayer ()-> getLabel ()-> setString ("You Lose :[");

4 CCDirector: sharedDirector ()-> replaceScene (gameOverScene );

1 // objcwith cocos2d-iphone

2 GameOverScene * gameOverScene = [GameOverScene node];

3 [gameOverScene. layer. label setString: @ "You Lose: ["];

4 [[CCDirector shareddire] replaceScene: gameOverScene];

Now, everything is ready for use. Compile and run it. All types of effects will be displayed. Monsters and bullets are full-screen flying, which is very H background music, A prompt page is displayed when you lose or win.

The entire game is now complete. Congratulations!

IPhone

Android

Win32

Wophone

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.