Cocos2d-x Development Log 10--Snake source _cocos2d-x

Source: Internet
Author: User
Tags addchild rand

Simple game development, more suitable and I like the small Bailian hand, in addition to the game end scene, all included in the Helloworldscene, the first source, the comments have been more comprehensive, but the details will be updated.

HelloWorldScene.h

#ifndef __helloworld_scene_h__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "GameOverScene.h" #include
<string.h> #include <stdlib.h> #include <iostream> #include <sstream> using namespace cocos2d;
using namespace Std;

Gluttonous snake moves in the direction of the TypeDef enum{Up=1, down, left, right}dir_def;  Snake head body food shared this Node class snakenode:public node{public:int row;//row int col;//column int dir;//Direction Drawnode

*pic;//to load the picture}; Welcome Scene Class Helloworld:public layer{public:virtual bool init ();//Initialize function static Scene * Createscene ();//Get Welcome screen
    Scene void Menuclosecallback (REF * psender);

Create_func (HelloWorld);

};
    Help Screen class Gamehelp:public layer{public:virtual bool Init ();
    Static Scene * Createscene ();
    Create_func (GAMEHELP);
void Menubacktomain (REF * psender);

};
    Game Screen class Gamelayer:public layer{Protected:bool pause_resume=0;//suspend 0 for continuation, 1 for pause Snakenode *shead;//Snake Head Snakenode *sfood;Food Vector <SnakeNode*> allbody;//body//staging Start coordinate grid unit length int ox = 50;
    int oy = 60;
    int unit = 20;
Get the score int score = 0;
    Public://Initialize virtual BOOL init ();
    Static Scene * Createscene ();
    Create_func (Gamelayer);
    Game logic void Logic01 (float t);


void Menubacktomain (REF * psender);//Return to main menu}; #endif//__helloworld_scene_h__

HelloWorldScene.cpp

#include "HelloWorldScene.h" #define START_TAG #define HELP_TAG #define EXIT_TAG #define MAINMENU_TAG #define Up_tag #define DOWN_TAG #define LEFT_TAG #define RIGHT_TAG #define PAUSE_TAG #define SCORE_TAG #define M
Enu_tag using_ns_cc;

using namespace cocos2d;                                                                    //************************************************************************//
//**                                                                    **////** Welcome Interface **////** **//
//***********************************************************
    Welcome interface Method Scene * Helloworld::createscene () {Scene * Scene = Scene::create ();
    HelloWorld * layer = helloworld::create ();
    scene-> addChild (layer);
return scene; }//Welcome interface initialization method BOOL Helloworld::init () {if (!)

    Layer::init ()) return false; Game Name label Auto label = Label::createwithttf ("SNAKE"," Fonts/marker Felt.ttf ", 50);
    Label->setcolor (color3b (0,120,100)); Label->setposition (Director::getinstance ()->getwinsize (). WIDTH/2, Director::getinstance ()
    ; Getwinsize (). height/2+ label->getcontentsize (). height*1.5);

    This->addchild (label);
    Start button Auto start = Label::createwithttf ("Start Game", "Fonts/marker Felt.ttf", 24);
    Start->setcolor (color3b (0,255,0));
    Auto Start_button = Menuitemlabel::create (Start,cc_callback_1 (Helloworld::menuclosecallback, this));
    Start_button->setpositiony (Start->getpositiony () +start_button->getcontentsize (). height*1.5);
    Start_button->settag (Start_tag);
    Help button Auto Assist = Label::createwithttf ("Aid", "Fonts/marker Felt.ttf", 24);
    Help->setcolor (color3b (0,0,255));
    Auto Help_button = Menuitemlabel::create (Help,cc_callback_1 (Helloworld::menuclosecallback, this));
    Help_button->settag (Help_tag); Exit Button Auto EXit = Label::createwithttf ("Exit", "Fonts/marker Felt.ttf", 24);
    Exit->setcolor (color3b (200,0,200));
    Auto Exit_button = Menuitemlabel::create (Exit,cc_callback_1 (Helloworld::menuclosecallback, this));
    Exit_button->setpositiony (Start->getpositiony ()-exit_button->getcontentsize (). height*1.5);
    Exit_button->settag (Exit_tag);
    New Menu Auto Menu = Menu::create (start_button,help_button,exit_button,null);

    This->addchild (menu);
return true;
        }//Welcome interface menu callback function void Helloworld::menuclosecallback (REF * psender) {switch ((menuitemlabel*) Psender)->gettag ()) {
            Case start_tag:{Auto scene = Gamelayer::createscene ();
            Director::getinstance ()->replacescene (scene);
        Break
            Case help_tag:{Auto scene = Gamehelp::createscene ();
            Director::getinstance ()->replacescene (scene);
        Break Case Exit_tag:director::getinstance ()->end ();
#if (Cc_target_platform = = Cc_platform_ios) exit (0);

        #endif break;
    Default:break;                                                                    }
}

//************************************************************************//
//**                                                                    **////** Help Interface **////** **//
//*****************************************************
    Help Screen Method Scene * Gamehelp::createscene () {Auto Scene = Scene::create ();
    Auto layer = Gamehelp::create ();
    scene-> addChild (layer);
return scene; //Help picture initialization method bool Gamehelp::init () {if (!)

    Layer::init ()) return false;
    Help text Auto label = Label::createwithttf ("Do Don't tell ME you CAN ' T does this, you fool!", "Fonts/marker Felt.ttf", 24);
    Label->setcolor (color3b (200,70,200)); Label->setposition (Director::getinstance ()->Getwinsize (). WIDTH/2, Director::getinstance ()->getwinsize (). height/2+50);

    This->addchild (label);
    Returns the main menu button Auto MainMenu = Label::createwithttf ("Main Menu", "Fonts/marker Felt.ttf", 24);
    Mainmenu->setcolor (color3b (0,200,200));
    Auto Mainmenu_button = Menuitemlabel::create (Mainmenu,cc_callback_1 (Gamehelp::menubacktomain, this));
    Mainmenu_button->setpositiony (Mainmenu_button->getpositiony ()-50);
    Mainmenu_button->settag (Exit_tag);
    New Menu Auto Menu = Menu::create (mainmenu_button,null);

    This->addchild (menu);
return true;
    //Help screen menu callback method void Gamehelp::menubacktomain (REF * psender) {Auto scene = Helloworld::createscene ();
Director::getinstance ()->replacescene (scene);                                                                    }


//************************************************************************//
//** **////** Game Interface **//
//**                                                                    **//
//***************************************
    Game interface Method Scene * Gamelayer:: Createscene () {Auto Scene = Scene::create ();
    Auto layer = Gamelayer::create ();
    Scene->addchild (layer);
return scene; BOOL Gamelayer::init () {if (!


    Layer::init ()) return false;
    Return to main menu button Auto MainMenu = Label::createwithttf ("Main Menu", "Fonts/marker Felt.ttf", 24);
    Mainmenu->setcolor (color3b (0,200,200));
    Auto Mainmenu_button = Menuitemlabel::create (Mainmenu,cc_callback_1 (Gamelayer::menubacktomain, this));
    Mainmenu_button->settag (0); Mainmenu_button->setposition (Director::getinstance ()->getwinsize (). width*0.3,-Direc
    Tor::getinstance ()->getwinsize (). height*0.3);
    Pause button Auto Pause = Label::createwithttf ("Pause", "Fonts/marker Felt.ttf", 24);
   Pause->setcolor (color3b (255,100,100)); Auto Pause_button = Menuitemlabel::create (Pause,cc_callback_1 (Gamelayer::menubacktomain, this));
    Pause_button->settag (Pause_tag); Pause_button->setposition (Director::getinstance ()->getwinsize (). width*0.3,-director::get
    Instance ()->getwinsize (). height*0.3+140);
    Up button Auto up = Label::createwithttf ("Up", "Fonts/marker Felt.ttf", 24);
    Up->setcolor (color3b (0,255,0));
    Auto Up_button = Menuitemlabel::create (Up,cc_callback_1 (Gamelayer::menubacktomain, this));
    Up_button->settag (Up_tag); Up_button->setposition (Director::getinstance ()->getwinsize (). width*0.3,-director::getinstan

    CE ()->getwinsize (). height*0.3+100);
    Down button Auto down = Label::createwithttf ("Down", "Fonts/marker Felt.ttf", 24);
    Down->setcolor (color3b (0,255,0));
   Auto Down_button = Menuitemlabel::create (Down,cc_callback_1 (Gamelayer::menubacktomain, this));
    Down_button->settag (Down_tag); Down_bUtton->setposition (Director::getinstance ()->getwinsize (). width*0.3,-director::getinstanc

    E ()->getwinsize (). height*0.3+40);
    Keys left = Label::createwithttf ("Ieft", "Fonts/marker Felt.ttf", 24);
    Left->setcolor (color3b (0,255,0));
    Auto Left_button = Menuitemlabel::create (Left,cc_callback_1 (Gamelayer::menubacktomain, this));
    Left_button->settag (Left_tag); Left_button->setposition (Director::getinstance ()->getwinsize (). width*0.3-30,-Director:

    : getinstance ()->getwinsize (). height*0.3+70);
    Key right = Label::createwithttf ("Right-hand", "Fonts/marker Felt.ttf", 24);
    Right->setcolor (color3b (0,255,0));
    Auto Right_button = Menuitemlabel::create (Right,cc_callback_1 (Gamelayer::menubacktomain, this));
    Right_button->settag (Right_tag); Right_button->setposition (Director::getinstance ()->getwinsize (). width*0.3+30,-Director ::GetInstance ()->getwinsize (). height*0.3+70);
    New Menu Auto Menu = Menu::create (mainmenu_button,up_button,left_button,down_button,right_button,pause_button,null);
    This->addchild (menu);

    Menu->settag (Menu_tag);
    Show fractional Char a[3];
    StringStream stream;
    Stream << score;
    Stream >> A;
    Auto Score_label = Label::createwithttf (A, "Fonts/marker Felt.ttf", 40); Score_label->setposition (Director::getinstance ()->getwinsize (). width*0.8, Director::ge
    Tinstance ()->getwinsize (). height*0.8);
    Score_label->settag (Score_tag);


    This->addchild (Score_label);
            Set grid for (int i=0; i<11; i++) {for (int j=0; j<11; j +) {Auto Head1 = Drawnode::create ();
            Head1->drawdot (Point (0,0), 1, color4f (1, 1, 1, 0.5));
            Head1->setposition (VEC2 (Ox+unit*i, oy+unit*j));
        This->addchild (head1,4); }//init snake head shead = new SnaKenode ();
    Shead->row = Arc4random ()%10;
    Shead->col = Arc4random ()%10;
    Shead->dir = Arc4random ()%4+1;
    Cclog ("%d%d", shead->row,shead->col);
    Shead->pic = Drawnode::create ();
    Shead->pic->drawsolidrect (Point (0,0), point (Unit,unit), color4f (1, 0, 0, 0.8));
    Shead->pic->setposition (VEC2 (ox+shead->col*unit,oy+shead->row*unit));

    This->addchild (shead->pic,2);
    Initialize Food sfood = new Snakenode;
    Sfood->row = Arc4random ()%10;
    Sfood->col = Arc4random ()%10;
    Sfood->pic = Drawnode::create ();
    Sfood->pic->drawsolidrect (Point (0,0), point (Unit,unit), color4f (1,1,1,1));
    Sfood->pic->setposition (VEC2 (ox+sfood->col*unit,oy+sfood->row*unit));

    This->addchild (sfood->pic,2);
    Initialization of the body//allbody.reserve (1);
    Execution Plan Task This->schedule (Schedule_selector (GAMELAYER::LOGIC01), 0.8);
return true; }//Game interface Menu callback method void Gamelayer::menubacktomain (REF * psender) {Auto P =(menuitemlabel*) Psender;
            Switch (P->gettag ()) {case 0:{auto scene = Helloworld::createscene ();
            Director::getinstance ()->replacescene (scene);
        Break
            Case up_tag:{if (shead->dir!=dir_def::D own) Shead->dir = Dir_def::up;
        Break
            Case down_tag:{if (shead->dir!=dir_def::up) Shead->dir = dir_def::D own;
        Break
            Case left_tag:{if (shead->dir!=dir_def::right) Shead->dir = Dir_def::left;
        Break
            Case right_tag:{if (shead->dir!=dir_def::left) Shead->dir = dir_def::right;
        Break
                Case pause_tag:{if (Pause_resume = = 0) {pause_resume = 1;
                Unschedule (Schedule_selector (GAMELAYER::LOGIC01)); menuitemlabel* L = (menuitemlabel*) this-> Getchildbytag (Menu_tag)-> Getchildbytag (Pause_tag);
            L->setstring ("RESUME");
                } else{//director::getinstance ()->resume ();
                Pause_resume = 0;
                Schedule (Schedule_selector (GAMELAYER::LOGIC01), 0.8);
                Menuitemlabel * L = (menuitemlabel*) this->getchildbytag (Menu_tag)->getchildbytag (PAUSE_TAG);
            L->setstring ("PAUSE");
        } break;
    } Default:break; }//Scheduled task void Gamelayer::logic01 (float t) {//Mobile body for (int i = Allbody.size ()-1; i>=0; i--) {Snak
        Enode * sn = allbody.at (i);
            if (i>0) {Auto Snpre = allbody.at (i-1);
            Sn->dir = snpre->dir;
            Sn->row = snpre->row;
        Sn->col = snpre->col;
            }//Move first node else if (i==0) {Sn->dir = shead->dir;
  Sn->row = shead->row;          Sn->col = shead->col;
            }//Mobile snake Head switch (shead->dir) {case dir_def::up:{shead->row++;
            if (Shead->row >=) shead->row = 0;
        Break
            Case DIR_DEF::D own:{shead->row--;
            if (Shead->row < 0) Shead->row = 9;
        Break
            Case dir_def::left:{shead->col--;
            if (Shead->col < 0) Shead->col = 9;
        Break
            Case dir_def::right:{shead->col++;
            if (shead->col >=) shead->col = 0;
        Break

    }//Head node resets the image position Shead->pic->setposition (VEC2 (ox+shead->col*unit,oy+shead->row*unit));
        Collision Detection if (Shead->row==sfood->row && shead->col==sfood->col) {score + +;
        Char a[3]; StringStream streAm
        Stream << score;
        Stream >> A;
        Auto L = (Label *) This->getchildbytag (Score_tag);

        L->setstring (a);
            Food disappears while (1) {bool flag = true;
            Sfood->row = rand ()%10;
            Sfood->col = rand ()%10; for (int i=0; i<allbody.size (); i++) {if (allbody.at (i)->row==sfood->row && allbody.at (i)
            -&GT;COL==SFOOD-&GT;COL) flag = false;
        } if (flag = = true) break;
        } sfood->pic->setposition (VEC2 (ox+sfood->col*unit,oy+sfood->row*unit));
        Add body to set Snakenode * SN;
        sn = new Snakenode;
        Snakenode *lastnode;
        if (Allbody.size () >0) Lastnode = allbody.at (Allbody.size ()-1);
        else lastnode = Shead;
                Switch (lastnode->dir) {Case Dir_def::up:sn->row = lastnode->row-1; sn-&Gt;col = lastnode->col;

            Break
                Case DIR_DEF::D own:sn->row = lastnode->row+1;
                Sn->col = lastnode->col;

            Break
                Case Dir_def::left:sn->row = lastnode->row;
                Sn->col = lastnode->col+1;

            Break
                Case Dir_def::right:sn->row = lastnode->row;
                Sn->col = lastnode->col-1;
        Break
        } Sn->dir = lastnode->dir;
        This->allbody.pushback (SN);
        Sn->pic = Drawnode::create ();
        Sn->pic->drawsolidrect (Point (0,0), point (Unit,unit), color4f (0, 1, 0, 0.8));
        Sn->pic->setposition (VEC2 (ox+sn->col*unit,oy+sn->row*unit));

    This->addchild (Sn->pic); //Reset body position for (int i = 0; I<allbody.size (); i++) {allbody.at (i)->pic->setposition Vec2 (Ox+allbo dy.at (i)->col*unit,oy+allbody.at (i)->row*unit)); //game over decision for (int i=0; i<allbody.size (); i++) if (allbody.at (i)->row==shead->row &&am P
            allbody.at (i)->col==shead->col) {Auto scene = Gameover::createscene ();
        Director::getinstance ()->replacescene (scene); }
}

GameOverScene.h

//  GameOverScene.h
//  Snakegame////
Created by Jiumiao on  15/8/9.
//

#ifndef __snakegame__gameoverscene__
#define __SNAKEGAME__GAMEOVERSCENE__

#include < stdio.h>
#include "cocos2d.h"
#include "HelloWorldScene.h"
using_ns_cc;

Class Gameover:public layer{public
:
    BOOL Init ()//Initialize function
    static Scene * Createscene ();//Get Welcome screen scene< C19/>void menuclosecallback (REF * psender);
    Create_func (Gameover);

};

#endif/* Defined (__snakegame__gameoverscene__) * *

GameOverScene.cpp

GameOverScene.cpp//Snakegame////Created by Jiumiao on 15/8/9. #include "GameOverScene.h"//initialization function bool Gameover:: Init () {if (!)
    Layer::init ()) return false;
    Game over Auto label = Label::createwithttf ("Game over", "Fonts/marker Felt.ttf", 50);
    Label->setcolor (color3b (255,120,100)); Label->setposition (Director::getinstance ()->getwinsize (). WIDTH/2, Director::getinstance ()
    ; Getwinsize (). height/2+ label->getcontentsize (). height*1.5);

    This->addchild (label);
    Back to Game button auto Tryagain = Label::createwithttf ("Try Again", "Fonts/marker Felt.ttf", 24);
    Tryagain->setcolor (color3b (0,200,200));
    Auto Tryagain_button = Menuitemlabel::create (Tryagain,cc_callback_1 (Gameover::menuclosecallback, this));
    Tryagain_button->setpositiony (Tryagain_button->getpositiony ()-50);
    Tryagain_button->settag (20);
    Auto Menu = Menu::create (tryagain_button,null); ThIs->addchild (menu);
return true;
    //Get End screen Scene * Gameover::createscene () {Auto Scene = Scene::create ();
    Auto layer = Gameover::create ();
    scene-> addChild (layer);
return scene;
    } void Gameover::menuclosecallback (REF * psender) {Auto scene = Gamelayer::createscene ();
Director::getinstance ()->replacescene (scene); }

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.