Cocos2d-x 3.0 game instance learning notes "card tower guard" Step 7 --- hero to upgrade & Attribute-parsing CSV configuration file

Source: Internet
Author: User
Tags addchild

New entry C ++ cocos2d-x3.0 tower anti-instance game

/* Description:

** 1. This game instance is the last game on the cocos2d-x game development journey, which is rewritten and noted down here with 3.0

** 2. I have also asked me about wood. He said: Write it as you like. First, do not copy the code completely. Second, You can note that it is a learning note-Good Guy.

** 3. Here With cocos2d-x 3.0 version rewriting, many places are different, but from the rewriting process also good learning cocos2d-x

*/

* ** All the code corresponding to each step and the resources used are packaged at the end.

* ** To avoid code overhead, the code in each step is marked. At first glance, the code is implemented in the first step to avoid errors and cannot be changed back (if not, git should be used again ?)

* ** You can follow the design idea (well, the name is too tall. The reality is this step to do) first self-implementation-cocos2d-x is so, the same function has many different implementation methods; first self-toss is quite good.

* ** For the convenience of porting to the mobile phone, Android testing is compiled for each step. Because the code can be compiled in Win32 many times, compilation will fail, the code is tested.

Note content:

1. Design Ideas

2. Train of Thought code &

3. Next Content preview

4. Download The resource & complete code

I. Design Ideas

1. First, the hero upgrade function is placed in hero, which has different effects.

2. The upgrade operation is extracted from an operator inherited from the node, and then bound to the turret. Then, click the turret. Three buttons are displayed: upgrade, close, and delete the hero.

3. A hero's upgrade is not only reflected in the appearance, but also has attributes. Attributes must be read from the CSV file.

5. Because the subsequent ideas are basically based on the book, we will not be able to make an axe to the class-end directly in the code

Ii. Train of Thought code &

First, update the function for the hero. Here, the function is completely written and only supports four levels of improvement. After each promotion, an action is overwritten.

Void hero: upgrade () {sprite * sprite = getsprite (); If (sprite = NULL | _ level> = 4) {return ;} // Add level _ Level ++; // If (_ Level = 2) {sprite * herotop = sprite: Create ("Sprite/hero/hero_top_1.png "); point Pos = CCP (sprite-> getcontentsize (). width/2, Sprite-> getcontentsize (). height/2); herotop-> setposition (POS); sprite-> addchild (herotop);} If (_ Level = 3) {sprite * herotop = sprite :: create ("Sprite/hero/hero_top_2.png"); herotop-> setopacity (255); point Pos = CCP (sprite-> getcontentsize (). width/2, Sprite-> getcontentsize (). height/2); herotop-> setposition (POS); sprite-> addchild (herotop); actioninterval * rotateby = rotateby: Create (25.0f, 360,360 ); actioninterval * repeat = repeatforever: Create (rotateby); herotop-> runaction (Repeat);} If (_ Level = 4) {point Pos = CCP (sprite-> getcontentsize (). width/2, Sprite-> getcontentsize (). height/2); sprite * herotop = sprite: Create ("Sprite/hero/hero_top_3.png"); herotop-> setposition (POS); sprite-> addchild (herotop ); actioninterval * rotateby = rotateby: Create (10.0f, 360,360); actioninterval * repeat = repeatforever: Create (rotateby); herotop-> runaction (Repeat );}}
The four basic effects are as follows:

LV1 ---- lv2 ---- lv3 ------ lv4

The effect is a dynamic action.

--------------------------------------------------------------

Let's take a look at the operator toweroperator; it needs to contact hero and the bastion host, and needs the two members.

Class toweroperator: Public node {public: toweroperator ();~ Toweroperator (); static toweroperator * Create (towerborder * towerborder, hero * hero); bool Init (towerborder * towerborder, hero * hero); Private: Hero * _ hero; towerborder * _ towerborder; void createoprbtns (); // ** 7 ** button event void closeevent (ref * psender, control: eventtype event); void upgradeevent (ref * psender, control: eventtype event); void deleteevent (ref * psender, control: eventtype event );};
Implementation

TowerOperator::TowerOperator(){_hero = NULL;_towerBorder = NULL;}TowerOperator::~TowerOperator(){CC_SAFE_RELEASE(_hero);CC_SAFE_RELEASE(_towerBorder);}TowerOperator* TowerOperator::create(TowerBorder* towerBorder,Hero* hero){TowerOperator* towerOperator = new TowerOperator();if(towerOperator && towerOperator->init(towerBorder,hero)){towerOperator->autorelease();}else{CC_SAFE_DELETE(towerOperator);}return towerOperator;}bool TowerOperator::init(TowerBorder* towerBorder, Hero* hero){CC_SAFE_RETAIN(towerBorder);_towerBorder = towerBorder;CC_SAFE_RETAIN(hero);_hero = hero;createOprBtns();return true;}void TowerOperator::createOprBtns(){    LabelTTF* title = LabelTTF::create("Close", "Arial", 25);auto m_pos = this->getPosition();    ControlButton* closeBtn = ControlButton::create(title, Scale9Sprite::create("Button/opr_btn_nor.png"));closeBtn->setBackgroundSpriteForState(Scale9Sprite::create("Button/opr_btn_light.png"), Control::State::HIGH_LIGHTED);closeBtn->addTargetWithActionForControlEvents(this,cccontrol_selector(TowerOperator::closeEvent), Control::EventType::TOUCH_UP_INSIDE);closeBtn->setPosition(ccp(m_pos.x+100,m_pos.y));this->addChild(closeBtn);    title = CCLabelTTF::create("Delete", "Arial", 25);    ControlButton* deleteBtn = ControlButton::create(title, Scale9Sprite::create("Button/opr_btn_nor.png"));    deleteBtn->setBackgroundSpriteForState(Scale9Sprite::create("Button/opr_btn_light.png"), Control::State::HIGH_LIGHTED);deleteBtn->addTargetWithActionForControlEvents(this, cccontrol_selector(TowerOperator::deleteEvent), Control::EventType::TOUCH_UP_INSIDE);deleteBtn->setPosition(ccp(m_pos.x-100,m_pos.y));this->addChild(deleteBtn);    title = CCLabelTTF::create("Upgrade",  "Arial", 25);    ControlButton* upgradeBtn = ControlButton::create(title, Scale9Sprite::create("Button/opr_btn_nor.png"));    upgradeBtn->setBackgroundSpriteForState(Scale9Sprite::create("Button/opr_btn_light.png"), Control::State::HIGH_LIGHTED);upgradeBtn->addTargetWithActionForControlEvents(this, cccontrol_selector(TowerOperator::upgradeEvent), Control::EventType::TOUCH_UP_INSIDE);upgradeBtn->setPosition(ccp(m_pos.x,m_pos.y+100));this->addChild(upgradeBtn);}void TowerOperator::closeEvent(Ref* pSender,Control::EventType event){CCLOG("close!");this->removeFromParentAndCleanup(true);}void TowerOperator::upgradeEvent(Ref* pSender,Control::EventType event){CCLOG("upgrade!");_hero->upgrade();}void TowerOperator::deleteEvent(Ref* pSender,Control::EventType event){CCLOG("delete!");_towerBorder->deleteHero();this->removeFromParentAndCleanup(true);}
Three buttons. Here, we also need to pay attention to the placement of relative positions, that is, the location of son & parent.

The functions of the three buttons are relatively simple, so the corresponding delete operation is completed by -- _ towerborder. The function is:

void TowerBorder::deleteHero(){_hero->removeFromParentAndCleanup(true);CC_SAFE_RELEASE_NULL(_hero);}
In addition, do not use _ hero to directly Delete the instance from the parent. Otherwise, the instance cannot be added next time.

Then our operator must be displayed. When we add a hero to the gun station, we will add it in the touch event when there is no hero on the gun station. If so, the following figure shows the operator:

Void towerborder: showoperator () {auto toweroperator = toweroperator: Create (this, _ hero); cc_safe_retain (toweroperator); toweroperator-> setposition (CCP (0, 0 )); this-> addchild (toweroperator);} // The setpostion here and the setpos in the operator are also related to the relative position mentioned above. bool heromanager: initwithlevel (INT curlevel) ***************** /listener-> ontouchended = [=] (touch * touch, event * event) ***************** /If (clickborder-> gethero () = NULL) {hero * hero = hero: createfromcsvfilebyid (1); hero-> setposition (clickborder-> getposition (); this-> addchild (HERO ); clickborder-> bindhero (HERO);} else {clickborder-> showoperator () ;};_ eventdispatcher-> addeventlistenerwithscenegraphpriority (listener, this); // returns true ;}
The effect is as follows:

Then, our hero's upgrades have an external representation.

However, our hero has never configured the attribute ----------------- this should be done through CSV;

The first thing to note is:

CSV is a simple file. You can use Excel to make it look like a table. The last saved format is CSV. But when you use NotePad to open it, you will find that it is actually separated by commas (,).

----------------------

So here the CSV needs to be parsed, and then put in our cocos2d-x, use these attributes;

I am not talking about it here, but I have modified many things in version 3.0. At the same time, some modifications have been made to port the file to the mobile phone. There are three classes for parsing CSV files:

Fileloadutil --- file loading, stringutil --- string parsing, csvutil --- the first two work together to complete the final parsing. If you know the specific work, the best way is step-by-step debugging, which is easy to understand.

Bytes ---------------------------------------------------------------------------------------------------------------

Let's take a look at hero. H, the hero's attribute:

Enum enumherotype {en_herotype_normal}; Enum category {enheropropconf_id, // hero category, // hero name enheropropconf_type, // hero type category, // Hero Model category, // basic attack strength, // attack interval (unit: seconds) enheropropconf_atkrange, // attack range (RADIUS) enheropropconf_upgradeatkbase, // upgrade the attack addition coefficient enheropropconf_upgradecostbase, // upgrade the consumption Base Value }; // -------------- the following are some class members-// ** 7 ** cc_synthesize (enumherotype, _ herotype, herotype); // the hero type cc_synthesize (INT, _ baseatk, baseatk); // basic attack cc_synthesize (INT, _ curatk, curatk); // current attack -- eg: After Upgrade cc_synthesize (INT, _ atkspeed, atkspeed ); // attack speed (interval) cc_synthesize (INT, _ atkrange, atkrange); // attack range (RADIUS) cc_synthesize (INT, _ upgradecostbase, upgradeconstbase ); // upgrade consumption cc_synthesize (float, _ upgradeatkbase, upgradeatkbase); // upgrade attack bonus
In the init function

// ** 7 ** csvutil * csvutil = csvutil: getinstance (); size csvsize = csvutil-> getfilerowcolnum ("CVS/hero. CVS "); const char * chheroid = _ string: createwithformat (" % d ", heroid)-> getcstring (); int line = csvutil-> findvalueinwithline (chheroid, enheropropconf_id, "CVS/hero. CVS "); If (line <0) {return false;} setid (heroid); setmodeid (csvutil-> getint (line, enheropropconf_modelid," CVS/hero. CVS "); setbaseatk (csvutil-> getint (line, enheropropconf_baseatk," CVS/hero. CVS "); setcuratk (getbaseatk (); setatkspeed (csvutil-> getint (line, enheropropconf_atkspeed," CVS/hero. CVS "); setatkrange (csvutil-> getint (line, enheropropconf_atkrange," CVS/hero. CVS "); setupgradeatkbase (csvutil-> getfloat (line, enheropropconf_upgradeatkbase," CVS/hero. CVS "); setupgradeconstbase (csvutil-> getint (line, enheropropconf_upgradecostbase," CVS/hero. CVS "); // ---------------- upgrade -------------------- // increase the hero's attack power. setbaseatk (getbaseatk () * _ upgradeatkbase); setcuratk (getbaseatk ());
Finally, in the constructor of appdelegate,

AppDelegate::AppDelegate() {CC_SAFE_RETAIN(CsvUtil::getInstance());}AppDelegate::~AppDelegate(){CC_SAFE_RELEASE(CsvUtil::getInstance());}
OK. This time is over.

Iii. Next Content preview

The hero's attributes cannot be seen because there is no monster to make it bully, so we need to add a monster later and let it walk according to the route we previously edited.

IV:

-----------------------------------

Source code & Resources

--------------------------------------
Personal ignorance. Thank you for your correction and discussion.







Cocos2d-x 3.0 game instance learning notes "card tower guard" Step 7 --- hero to upgrade & Attribute-parsing CSV configuration file

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.