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

229人阅读 评论(0)

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，现在开始尽情肆虐吧~

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：6535次
• 积分：113
• 等级：
• 排名：千里之外
• 原创：5篇
• 转载：1篇
• 译文：0篇
• 评论：6条
文章分类
评论排行
最新评论