主要使用system函数清屏刷新游戏状态,导致墙壁每次循环需要重新绘制,画面异常卡顿。
首先定义结构体:
typedef struct coor{
int x;
int y;
} COOR;
//主要存储蛇身或者食物的坐标
定义蛇身:
typedef struct Snake{
COOR sn[MAX];//蛇身
int n;//当前节数
char dir;//蛇方向
} SNAKE;
定义食物结构体:
struct Food{
COOR food_s;
int flag;//判断吃否
} food
在贪吃蛇中我们需要一个重要的函数来确定坐标:
void gotoxy(int x, int y)
{
COORD coord = { x, y };
/*COORD是Windows API中定义的一种结构,表示一个字符在控制台屏幕上的坐标。其定义为:
typedef struct _COORD {
SHORT X; // horizontal coordinate
SHORT Y; // vertical coordinate
} COORD;*/
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
}
第一步,我们需要绘制墙壁:
void paintwall()
{
int i, j;
for (i = 0; i < 81; i++) {//绘制上下边框
gotoxy(i,0);
printf("*");
gotoxy(i, 28);
printf("*");
}
for (i = 1; i < 28; i++){//绘制左右边框
gotoxy(0,i );
printf("*");
gotoxy(81, i);
printf("*");
}
}
第二步,绘制蛇身:
void initial()
{
//初始化两节蛇身
srand((unsigned int)time(NULL));
snake.sn[0].x = 10;
snake.sn[0].y = 2;
snake.sn[1].x = 0;
snake.sn[1].y = 0;
snake.n = 2;
snake.dir = 'd';//缺省方向,右
food.flag = 0;//食物初始状态
}
让蛇移动起来!
void MoveSnake()
{
int i;
for (i = snake.n - 1; i > 0; i--){
snake.sn[i].x = snake.sn[i - 1].x;
snake.sn[i].y = snake.sn[i - 1].y;
}
switch (snake.dir){
case 'd':
snake.sn[0].x+=2;
break;
case 's':
snake.sn[0].y+=1;
break;
case 'w':
snake.sn[0].y-=1;
break;
case 'a':
snake.sn[0].x-=2;
break;
default:
break;
}
for (i = 0; i < snake.n; i++){
gotoxy(snake.sn[i].x, snake.sn[i].y);
printf("%s", "蛇");
}
}
改变蛇方向:
void ChangeDir()
{
char ch;
ch = _getch();
switch (ch){
case 'w':
if (snake.dir != 's')
snake.dir = 'w';
break;
case 's':
if (snake.dir != 'w')
snake.dir = 's';
break;
case 'a':
if (snake.dir != 'd')
snake.dir = 'a';
break;
case 'd':
if (snake.dir != 'a')
snake.dir = 'd';
break;
default:
break;
}
}
初始化食物:
void inifood()
{
int i;
int judge=0;
do{
food.food_s.x = rand() % (400 / 10)*2;
food.food_s.y = rand() % (150 / 10)*2;
for (i = 0; i < snake.n; i++)
if (snake.sn[i].x == food.food_s.x&&snake.sn[i].y == food.food_s.y){
judge = 1;
break;
}
} while (judge == 1 || food.food_s.y == 0 || food.food_s.y == 28 || food.food_s.x == 0 || food.food_s.x == 81);
food.flag = 1;
}
void DrawFood()
{
gotoxy(food.food_s.x, food.food_s.y);
printf("豆");
}
当蛇吃东西:
void EatFood()
{
if (snake.sn[0].x == food.food_s.x&&snake.sn[0].y == food.food_s.y){
snake.n++;//当吃东西的时候蛇身加一
food.flag = 0;//食物状态重置为0
}
}
主函数:
void main()
{
initial();
while (1){
while (!_kbhit()){//kbhit检查是否有键盘输入
paintwall();
if (food.flag==0)
inifood();
MoveSnake();
DrawFood();
EatFood();
Sleep(200);
system("cls");
}
ChangeDir();
}
getchar();
}