基于c++的简约贪吃蛇小游戏编程

基于c++的贪吃蛇简约游戏编程(还是头文件的原因,大家可以手动把头文件放进<>里)
#include<>iostream
#include
#include
#include<>ctime
using namespace std;
constexpr auto MAPHEIGHT=25;
constexpr auto MAPWIDTH=60;
constexpr auto SNAKESIZE=50;
struct
{
int x;//食物的坐标
int y;
}food;
struct
{
int x[SNAKESIZE];
int y[SNAKESIZE];
int len;//蛇的长度
int speed;//蛇的速度
}snake;
//全局变量
int key = ‘w’;//蛇的初始化移动方向
int changFlag = 0;//蛇的变化标志
//画地图
void drawMap();
//食物的生成
void createFood();
//按键操作
void keyDown();
//蛇的状态:判断是否结束游戏
int snakeStatus();
//辅助函数:光标移动
void gotoxy(int x, int y);

int main()
{
drawMap();
while (1)
{
createFood();
Sleep(snake.speed);
keyDown();
if (!snakeStatus())
{
break;
}
}
gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);
cout << “GameOver”;
system(“pause”);
return 0;
}
void gotoxy(int x, int y)
{
//找到控制台窗口
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
//光标的结构体
COORD coord;
//设置坐标
coord.X = x;
coord.Y = y;
//同步到控制台
SetConsoleCursorPosition(handle, coord);
}
void drawMap()
{
srand((unsigned int)time(NULL));
//设置活动范围
for (int i = 0; i <= MAPHEIGHT; i++)
{
gotoxy(0, i);
cout << “□”;
gotoxy(MAPWIDTH, i);
cout << “□”;
}
for (int i = 0; i <= MAPWIDTH; i+=2)//□占用两个字符
{
gotoxy(i, 0);
cout << “□”;
gotoxy(i, MAPHEIGHT);
cout << “□”;
}
//画蛇□
snake.len = 3;
snake.speed = 300;
snake.x[0] = MAPWIDTH / 2;
snake.y[0] = MAPHEIGHT / 2;
//画蛇头
gotoxy(snake.x[0], snake.y[0]);
cout << “□”;
//画身体
for (int k = 1; k < snake.len; k++)
{
snake.x[k] = snake.x[k - 1] + 2;
snake.y[k] = snake.y[k - 1];
gotoxy(snake.x[k], snake.y[k]);
cout << “□”;
}
//画食物⊙
food.x = rand() % (MAPWIDTH - 4) + 2;//两边边框占4个字符
food.y = rand() % (MAPHEIGHT - 2) + 1;
gotoxy(food.x, food.y);
cout << “⊙”;
}
void createFood()
{
if (snake.x[0] == food.x&&snake.y[0] == food.y)
{
srand((unsigned int)time(NULL));
snake.len++;
changFlag = 1;
//产生的食物不能在蛇身上,且由于蛇身占两个字符,所以食物x坐标必须为偶数
while (1)
{
int flag = 1;
food.x = rand() % (MAPWIDTH - 4) + 2;
food.y = rand() % (MAPHEIGHT - 2) + 1;
for (int k = 0; k < snake.len; k++)
{
if (snake.x[k] == food.x&&snake.y[k]== food.y)
{
flag = 0;//食物不合适
break;
}
}
if (flag&&food.x % 2 == 0)
{
break;
}
}
}
gotoxy(food.x, food.y);
cout << “⊙”;

}
void keyDown()
{
//无按键按下
if (_kbhit())
{
fflush(stdin);
key=_getch() ;
}
//擦除最后一节
if (!changFlag)
{
gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);
cout << " ";
}
//后面的蛇身移动
for (int i = snake.len - 1; i > 0; i–)
{
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1];
}
switch (key)
{
case ‘w’:
case ‘W’:
snake.y[0]–;
break;
case ‘s’:
case ‘S’:
snake.y[0]++;
break;
case ‘a’:
case ‘A’:
snake.x[0] -= 2;
break;
case ‘d’:
case ‘D’:
snake.x[0] += 2;
break;
}
gotoxy(snake.x[0], snake.y[0]);
cout << “□”;
changFlag = 0;
gotoxy(MAPHEIGHT + 2, 0);

}
int snakeStatus()
{
if (snake.x[0] == 0 || snake.x[0] == MAPHEIGHT - 2 || snake.y[0] == 0 || snake.y[0] == MAPWIDTH - 2)
{
return 0;
}
for (int k = 1; k < snake.len; k++)
{
if (snake.x[0] == snake.x[k] && snake.y[0] == snake.y[k])
{
return 0;
}
}
return 1;
}

你可能感兴趣的:(c++)