代码拉取完成,页面将自动刷新
#include "pch.h"
#include "Snake.h"
#include <list>
#include <random>
#define MAXx 34
#define MAXy 34
#define MINx 0
#define MINy 0
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
#define EXIST_ITEM 1
#define NON_EXIST_ITEM 0
Snake::Snake()
{
body.push_front({ 12,15 });
body.push_front({ 12,14 });
body.push_front({ 12,13 });
body.push_front({ 12,12 });
direction = RIGHT;
speed = 1;
length = 3;
score = 0;
lose = false;
itemOldTime = clock();
speedOldTime = clock();
memset(map, 0, sizeof map);
}
void Snake::move()
{
auto head = body.back();
//判断蛇是否会死亡
switch (direction)
{
case UP:
if (head.first - 1 < MINy || !checkIsOnSnake({ head.first - 1, head.second })) {
lose = true;
return;
}
break;
case DOWN:
if (head.first + 1 > MAXy || !checkIsOnSnake({ head.first + 1, head.second })) {
lose = true;
return;
}
break;
case LEFT:
if (head.second - 1 < MINx || !checkIsOnSnake({ head.first, head.second - 1 })) {
lose = true;
return;
}
break;
case RIGHT:
if (head.second + 1 > MAXx || !checkIsOnSnake({ head.first, head.second + 1 })) {
lose = true;
return;
}
break;
}
auto Tempit = body.begin(); //保存前一格蛇身的指针
auto tail = *Tempit; //保存蛇尾
for (auto it = ++body.begin(); it != body.end(); ++it) {
*Tempit = *it;
Tempit = it;
//判断是否为蛇头
if (next(it) == body.end()) {
switch (direction) //进行移动
{
case UP:
it->first--;
break;
case DOWN:
it->first++;
break;
case LEFT:
it->second--;
break;
case RIGHT:
it->second++;
break;
}
//判断是否吃到食物
if (map[it->second][it->first] == EXIST_ITEM) {
map[it->second][it->first] = NON_EXIST_ITEM;
//查找并删除食物
std::pair<int, int> point = { it->second, it->first };
auto tempit = find(item.begin(), item.end(), point);
item.erase(tempit);
length++;
body.push_front(tail);
score += speed;
}
}
}
}
bool Snake::gameOver()
{
if (lose == true) {
return true;
}
return false;
}
void Snake::addItem()
{
//添加食物
if (item.size() == 1) return;
//获取随机数
std::default_random_engine engine;
std::uniform_int_distribution<int> random(0, 50);
engine.seed(time(0));
//定时产生食物
if (clock() > itemOldTime + 1000) {
itemOldTime = clock();
int x, y;
do{
srand(time(NULL));
x = random(engine) % MAXy;
y = random(engine) % MAXx;
} while (map[x][y] == EXIST_ITEM && checkIsOnSnake({x, y}));
map[x][y] = EXIST_ITEM;
item.push_back({ x, y });
}
}
bool Snake::checkIsOnSnake(std::pair<int, int> temp)
{
//检测坐标是否不在蛇身上
for (auto it = body.begin(); it != body.end(); ++it) {
if (*it == temp) return false;
}
return true;
}
bool Snake::speedUp()
{
//定时加速
switch (speed)
{
case 1:
if (clock() > speedOldTime + 30000) speed += 2;
return true;
case 3:
if (clock() > speedOldTime + 60000) speed += 2;
return true;
case 5:
if (clock() > speedOldTime + 90000) speed += 2;
return true;
case 7:
if (clock() > speedOldTime + 120000) speed += 2;
return true;
}
return false;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。