Cocos2d-x Road ~ Make the first word game (one)

Source: Internet
Author: User
Tags addchild

Objective

Memories of last year. In addition, in the third, they developed their first game of April, it is the game. So I decided to embark on the path of independent development. The The first game achieves its proper level of profitability. However, this game was developed in the time. I didn't get any more. There is a piece of work that makes you feel comfortable.

Until March or April this year, I used cocos2d-x to develop my first word game.

The portal of the first game

Portal for the first word game

Since the use of cocos2d-x. Found myself in love with this engine.

It may not be strong enough and intact. but use it. Be able to experience the fun of coding. It also gives me the ability to regain the C + + technology (which is so persistent with C + +) and to improve the NDK and JNI learning. Just to meet my various pursuits.

This first text game. Name I take as Anagram Puzzle. In fact, this game is adapted to this tutorial on Raywenderlich. The tutorial is written using iOS uikit. Although the principle is interlinked. But in the process of rewriting still encountered a lot of places to toss. Because the first writing cocos2d-x game. So mistakes are inevitable, hope readers mercy, point to stop ... Needless to say, start coco2d-x the way ~ How to make the first word game!


Anagram Brief Introduction

Anagram is a game that disrupts the alphabetical order of words or phrases and then arranges them into a new word or phrase.

For example, the word cinema can be arranged again into Iceman. The game requires the player to make another arrangement of the words or phrases you provide. After the game, the screen will see:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmtc4mtgzna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">


In the course of developing this game, you will be exposed to the following knowledge:

    • MVC type of game structure
    • How to load levels from a file configuration
    • Loading third-party fonts
    • Easy to use music sound
    • Separating the HUD layer from the game layer
    • Gesture Drag and animation
    • The effect of particle
There are other basic knowledge of cocos2d-x that will come into contact during the development process.
Initialize Project

The first and foremost of all, of course, is to use the command line to create Cocos2d-xproject, but there are other ways to create project. But I think mastering command line to create is essential to the basic skills.

The creation method can be found here. The project catalogs for each platform are available after the creation is complete. Our main project directory is proj.android and Proj.ios two.

Throughout the development process, I use the Mac OS to develop, so the encoding is done on Xcode, while the Androidproject compiler uses the command line, the specific tutorial can refer here.

After you have set up project, copy the required resource files to the resource directory. Open Xcodeproject, the current resource directory or the original resource file, by right-clicking the resource directory, add files to ..., add the resource files to project. After editing, project will



1) Load Level profile

Open Level1.plist to see what's inside.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmtc4mtgzna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

There are three top key keys, each of which is:

Pointspertile: The score after each word is filled.
Timetosolve: The time to resolve this shutdown (in seconds).


Anagrams: is a list of topics, including two item (s). Each is the original phrase and the last phrase to be spelled out.

The introduction of the level file ends here. Start by writing the level class and add the following to the Level.h

Class Level:public ccobject{public:static level * Levelwithnum (int levelnum);p ublic:int mpointpertile;int MTimeToSovle ; Ccarray * PANAGRAMS;};

Among these, three variables correspond to the three topmost item in the level file. Another initialization function. is to initialize the level file to an external call.

Now. Open Level.cpp. Implementing the Levelwithnum function

Level * Level::levelwithnum (int levelnum) {char Filename[50];char fullpath[150];sprintf (fileName, "level%d.plist", Levelnum); Ccfileutils::sharedfileutils ()->fullpathfromrelativefile (Filename,fullpath); Ccdictionary * plistdict = Ccdictionary::createwithcontentsoffile (FileName), if (plistdict = = NULL) {cclog ("level config Not found ");} Level * L = new level (); ccstring * tempstr;tempstr = dynamic_cast<ccstring*> (Plistdict->objectforkey ("PointsPerTile"));l-> Mpointpertile = Tempstr->intvalue (); tempstr = dynamic_cast<ccstring*> (Plistdict->objectforkey (" Timetosolve ")); L->mtimetosovle = Tempstr->intvalue (); l->panagrams = Dynamic_cast<ccarray*> ( Plistdict->objectforkey ("anagrams")); L->panagrams->retain (); return l;}

This first reads the values in the level file with Ccdictionary, then reads the value in the corresponding key and stores it.

Now. Open the main interface file. The default is the Helloworldscene class, but I changed to write Mainscene, MainScene.h is this

Class Mainscene:public Cocos2d::cclayer{public:    ~mainscene ();    Here ' s a difference. Method ' init ' in cocos2d-x returns BOOL, instead of the returning ' ID ' in cocos2d-iphone    virtual bool init ();      There ' s no ' id ' in CPP, so we recommend returning the class instance pointer    static cocos2d::ccscene* scene ();        Implement the "Static node ()" Method manually    Create_func (mainscene);p rivate:level * plevel;};

Visible. The level variable was added. The init function in MainScene.cpp. Write

Plevel = Level::levelwithnum (1);

Of course. Here you can print out the contents of the Plevel in the Cclog to see. Will get what they see.


Add a new function to the Mainscene

void Dealrandomanagram ();

Detailed implementation to do so

void Mainscene::d ealrandomanagram () {common::random (0, Plevel->panagrams->count ()-1); int randomindex =  Common::random (0, Plevel->panagrams->count ()-1); Ccassert ((randomindex >= 0 && Randomindex < Plevel->panagrams->count ()), "Error random index!"); Ccarray * anagram = (ccarray*) plevel->panagrams->objectatindex (Randomindex); ccstring * ana1 = (ccstring*) anagram->objectatindex (0); ccstring * Ana2 = (ccstring*) anagram->objectatindex (1); int ana1len = Ana1->length (); int ana2len = Ana2->length ( );}

Common::random I wrote it myself. Generates a random number between two values

int common::random (int s,int e) {Float i = ccrandom_0_1 () * (e-s+1) +s;return (int) i;}
This takes the initial state of the phrase and finally the phrase to the state, and adds the Dealrandomanagram function to the Mainscene init function.

Plevel = Level::levelwithnum (1);d ealrandomanagram ();

2) Create a view of the word

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmtc4mtgzna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

Add a class in project that inherits from Ccnode, named Tileview, and adds the following code to TileView.h

Public:static Tileview * Initwithletter (const char * l,float sidelen);p rivate:ccsprite * Psprite;char mLetter;bool MIsMat Ch

The initwithletter is the initialization function, and the Psprite is the display sprite. The mletter is the corresponding letter. Mismatch indicates whether the result is paired (the location where the letter should be found).

In the TileView.cpp. Add the following code

#include "TileView.h" Tileview * tileview::initwithletter (const char * l, float sidelen) {Tileview * tile = new Tileview (); C Csprite * bg = ccsprite::create ("Tile.png"); Tile->addchild (bg); tile->psprite = bg;float scale = Sidelen/bg->ge Tcontentsize (). Width;bg->setscale (scale), Char chletter[2];sprintf (chletter, "%c", L[0]-32); Cclabelttf * letter = Cclabelttf::create (Chletter, "Arial", the * scale); Letter->setcolor (ccwhite); tile->addchild (letter); Tile->mismatch = False;tile->mletter = Chletter[0];return tile;}

function, the first is to create a tile.png-patterned sprite. Then create the letters on the pattern

The next step is to display it in the interface. Join in the Mainscene

Private:level * PLEVEL; Ccarray * ptiles; Ccarray * ptargets;

Ptiles is an array of Tileview, Ptargets is an array of TargetView, where Tileview is the individual words of the phrase given at the bottom, and targetview is the individual words of the target phrase. Continue to add code in MainScene.cpp's Dealrandomanagram function

int ana1len = Ana1->length (), int ana2len = Ana2->length (), Float tileside = Ceilf (Common::getcamerawith () *0.9/(Flo at) Std::max (Ana1len, Ana2len))-Ktilemargin;float Xoffset = (Common::getcamerawith ()-Std::max (Ana1len,ana2len) * (til Eside + ktilemargin)/2;xoffset + + TILESIDE/2;
At this point, you start to calculate the location of each tileview.

First, the longest length in the original phrase and the target phrase is drawn. Then figure out the width tileside required for each view, and the interval between each view Xoffset

By the right, don't forget to define the global void.

#define Ktilemargin 20

Next, we're going to create our tileview.

Ptiles = ccarray::createwithcapacity (Ana1len); const char * ana1letter = ana1->getcstring (); for (int i = 0;i < Ana1len ; i++) {char letter[3];sprintf (letter, "%c", Ana1letter[i]), if (letter[0]! = ") {Tileview * tile = Tileview::initwithletter (letter,tileside); Tile->setposition (CCP (Xoffset + i * (Tileside + ktilemargin), Common::getcameraheight ()/4)); This->addchild (tile);p tiles->addobject (tile);}} Ptiles->retain ();

The creation method is relatively simple. Note, however, that you can have null characters in the original phrase. Empty characters need to be left blank. What you see.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvdtaxmtc4mtgzna==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

3) Word View optimization

Square's tileview looked somewhat prim, and some of the following optimizations were made to make them lively.

Adding the Randomize function to the Tileview

void Tileview::randomize () {Float rotation = common::random (0,50)/(float) 100-0.2;this->setrotation (rotation * 10); int yoffset = Common::random (0,10); This->setpositiony (This->getpositiony () + Yoffset);}

Let the tileview be rotated and shifted slightly, and then in the Mainscene dealrandomanagram function This-AddChild(tile); Statement, add the following statement after the

Tile->randomize ();
4) Join TargetView

With the original phrase, you will start to create a view of the target phrase. Control Tileview. TargetView to be relatively simple. Because it is a fixed position and does not need to display letters.

Add the following code to the TargetView.h:

Class Targetview:public Ccnode{public:targetview (void); ~targetview (void); static TargetView * Initwithletter (const char * l,float sidelen);p rivate:ccsprite * Psprite;char mletter;bool mismatch;};

Similar to Tileview. An initialization function, three private variables.

With the Tileview is the one by one corresponding.

TargetView * Targetview::initwithletter (const char * l, float sidelen) {TargetView * tile = new TargetView (); Ccsprite * bg = ccsprite::create ("Slot.png"); Tile->addchild (bg); tile->psprite = bg;float scale = Sidelen/bg->g Etcontentsize (). Width;bg->setscale (scale), Char chletter[2];sprintf (chletter, "%c", l[0]-+);/*cclabelttf * Letter = Cclabelttf::create (Chletter, "Arial", the scale) Letter->setcolor (ccwhite); Tile->addchild (letter); */ Tile->mismatch = False;tile->mletter = Chletter[0];return tile;}

In TargetView's Initwithletter function, the gaze statement is to show the result. But in the actual game is not to display the TargetView on the letter.

Next, the TargetView will be shown to the scene. Find the Mainscene Dealrandomanagram method and add the following code at the end

Ptargets = ccarray::createwithcapacity (Ana2len); const char * ana2letter = ana2->getcstring (); for (int i = 0;i < ana2l En i++) {char letter[3];sprintf (letter, "%c", Ana2letter[i]), if (letter[0]! = ") {TargetView * target = TargetView:: Initwithletter (letter,tileside); Target->setposition (CCP (Xoffset + i * (Tileside + ktilemargin), Common:: Getcameraheight ()/4 * 3); This->addchild (target);p targets->addobject (target);}} Ptargets->retain ();

Whether can see TargetView also come out, here. We're done. The first part of the development work of Anagrampuzzle, last last


It feels good, and it's easy to show the game interface you need.

This time contact to cocos2d-x knowledge or less. The main thing is how to add content to the main scene and how to create sprites. Next time, we're going to write something a little bit more challenging. For example, how to drag the wizard, how to infer whether placed in the correct position, how to Countdown and so on, the real code fun to play!

Please listen to tell.







Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Cocos2d-x Road ~ Make the first word game (one)

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.