用简单思路开发游戏----贪吃蛇

struct TEgg
{
int x;
int y;
};

std::vector<TEgg> m_snake;//蛇

std::vector<TEgg> m_eggs;//吃到的蛋

TEgg m_egg;

void Snake::initMap()
{
for(int i = 0; i < KWidth; ++i)
{
for(int j = 0; j < KHeight; ++j)
{
m_pos[i][j] = Vec2(118 + KEggSize / 2 + KEggSize * i, 70 + KEggSize / 2 + KEggSize * j);
}
}
}

void Snake::initSnake()
{
m_snake.clear();
m_snakeSprite.clear();

int x = 3;
int y = 5;

for(int i = 0; i < 3; ++i)
{
TEgg egg;
egg.x = x - i;
egg.y = y;
m_snake.push_back(egg);

auto sprite = Sprite::create("test/egg.png");
sprite->setPosition(m_pos[egg.x][egg.y]);
m_snakeSprite.push_back(sprite);
}

m_eggSprite = Sprite::create("test/egg.png");
m_eggSprite->setPosition(Vec2(-200, -200));
}

void Snake::initEgg()
{
int x = rand() % KWidth;
int y = rand() % KHeight;

bool flag = false;

for(int i = 0; i < m_snake.size(); ++i)
{
if(x == m_snake[i].x && y == m_snake[i].y)
{
flag = true;
break;
}
}

if(flag)
{
initEgg();
}
else
{
m_egg.x = x;
m_egg.y = y;

m_eggSprite->setPosition(m_pos[x][y]);
}
}

void Snake::step(float dt)
{
//先取出蛇尾,便于吃到蛋后长大
TEgg lastSnake = m_snake[m_snake.size() - 1];

//后续的蛇身都挨个跟进
for(int i = (int)m_snake.size() - 1; i > 0; --i)
{
m_snake[i].x = m_snake[i - 1].x;
m_snake[i].y = m_snake[i - 1].y;
}

//判断方向,确定蛇头位置
if(m_curDir == EDirL)
{
m_snake[0].x--;
}
else if(m_curDir == EDirR)
{
m_snake[0].x++;
}
else if(m_curDir == EDirT)
{
m_snake[0].y++;
}
else if(m_curDir == EDirB)
{
m_snake[0].y--;
}

//判断是否撞墙
if(m_snake[0].x < 0 || m_snake[0].x > KWidth - 1 || m_snake[0].y < 0 || m_snake[0].y > KHeight - 1)
{
//gameover
unschedule(schedule_selector(Snake::step));
return;
}

//判断蛇头是否撞蛇身
for(int i = 1; i < m_snake.size(); ++i)
{
if(m_snake[0].x == m_snake[i].x && m_snake[0].y == m_snake[i].y)
{
//gameover
unschedule(schedule_selector(Snake::step));
return;
}
}

//判断是否吃到egg
if(m_snake[0].x == m_egg.x && m_snake[0].y == m_egg.y)
{
m_eggs.push_back(m_egg);
initEgg();//蛋被吃了，重新生成一个

//每吃一个蛋，蛇速度增大0.02f
m_dt -= 0.01f;
unschedule(schedule_selector(Snake::step));
schedule(schedule_selector(Snake::step), m_dt);
}

//判断是否蛇应该长大了
if(m_eggs.size() > 0 && m_eggs[0].x == lastSnake.x && m_eggs[0].y == lastSnake.y)
{
m_snake.push_back(m_eggs[0]);
m_eggs.erase(m_eggs.begin());

auto sprite = Sprite::create("test/egg.png");
sprite->setPosition(m_pos[lastSnake.x][lastSnake.y]);
m_snakeSprite.push_back(sprite);
}

//修改eggsprite位置
for(int i = 0; i < m_snakeSprite.size(); ++i)
{
m_snakeSprite[i]->setPosition(m_pos[m_snake[i].x][m_snake[i].y]);
}
}

schedule(schedule_selector(Snake::step), m_dt);

OK，现在开始尽情肆虐吧~

用pygame写个简单的贪吃蛇游戏

2014-04-08 21:01:50

Java之贪吃蛇游戏的开发

2017-05-30 22:51:03

简单贪吃蛇游戏的C++实现

2016-04-13 08:36:40

c#开发的贪吃蛇小游戏 代码简单易懂 适合新手学习 熬了2天夜做出来的……

2010年01月15日 62KB 下载

c++经典项目控制台贪吃蛇小游戏详细教程

2017-02-12 21:05:19

关于用Java写的贪吃蛇游戏的一些感想

2014-03-31 21:53:13

【贪吃蛇，C++实现】，由简单游戏开始学习OOP，的编程新手

2015-05-07 16:07:25

JS实现简单的贪吃蛇小游戏

2017-04-10 12:35:28

js开发实现简单贪吃蛇游戏（20行代码）

2016-03-30 09:45:31

Python写的贪吃蛇游戏例子

2015-03-21 16:54:22