简单的游戏开发,比较适合和我一样的小白练手,除了游戏结束场景,全部包含在了HelloWorldScene中,先上源码,注释已经比较全面,但是具体细节会陆续更新。
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;
//贪食蛇移动方向
typedef enum{
UP=1,
DOWN,
LEFT,
RIGHT
}DIR_DEF;
//蛇的头 身体 食物 共用这个node
class SnakeNode:public Node{
public:
int row; //行
int col; //列
int dir; //方向
DrawNode *pic;//要加载的图片
};
//欢迎场景
class HelloWorld : public Layer{
public:
virtual bool init();//初始化函数
static Scene * createScene();//获取欢迎画面的scene
void menuCloseCallback(Ref * pSender);
CREATE_FUNC(HelloWorld);
};
//帮助画面
class GameHelp: public Layer{
public:
virtual bool init();
static Scene * createScene();
CREATE_FUNC(GameHelp);
void menuBackToMain(Ref * pSender);
};
//游戏画面
class GameLayer : public Layer{
protected:
bool pause_resume=0;//是否暂停 0为继续,1为暂停
SnakeNode *sHead;//贪食蛇的头部
SnakeNode *sFood;//食物
Vector <SnakeNode*> allbody;//身体
//暂存起点坐标 网格单位长度
int ox = 50;
int oy = 60;
int unit =20;
//获得分数
int score = 0;
public:
//初始化
virtual bool init();
static Scene * createScene();
CREATE_FUNC(GameLayer);
//游戏逻辑
void logic01(float t);
void menuBackToMain( Ref * pSender);//返回主菜单
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
#include "HelloWorldScene.h"
#define START_TAG 10
#define HELP_TAG 11
#define EXIT_TAG 12
#define MAINMENU_TAG 13
#define UP_TAG 14
#define DOWN_TAG 15
#define LEFT_TAG 16
#define RIGHT_TAG 17
#define PAUSE_TAG 18
#define SCORE_TAG 19
#define MENU_TAG 20
USING_NS_CC;
using namespace cocos2d;
//************************************************************************//
//** **//
//** 欢迎界面 **//
//** **//
//************************************************************************//
//欢迎界面方法
Scene * HelloWorld::createScene(){
Scene * scene = Scene::create();
HelloWorld * layer = HelloWorld::create();
scene-> addChild(layer);
return scene;
}
//欢迎界面初始化方法
bool HelloWorld::init(){
if (!Layer::init())
return false;
//游戏名称标签
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);
//开始 按钮
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);
//帮助 按钮
auto help = Label::createWithTTF("Help", "fonts/Marker Felt.ttf", 24);
help->setColor(Color3B(0,0,255));
auto help_button = MenuItemLabel::create(help,CC_CALLBACK_1(HelloWorld::menuCloseCallback, th