制作贪吃蛇,首先为其确定移动范围大小,然后就是生成蛇头,蛇身,移动小蛇,其次就是食物的随机生成,判断是否吃到食物,蛇身的加长,游戏失败的判断。
代码中0表示空,1表示蛇头,大于1表示蛇身,-1表示边框,-2表示食物
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
一.定义范围大小
#define High 20
#define Width 30
这里面的数值可以根据需要而改变
二.清屏函数
void gotoxy(int x, int y)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(hOut, pos);
}
代替system(“cls”)完成清屏
三.进行数据初始化
int canvas[High][Width] = { 0 };
int i, j;
int move;
int food_i, food_j;
void startup()
{
int i, j;
for (i = 0;i < High;i++)
{
canvas[i][0] = -1;
canvas[i][Width - 1] = -1;
}
for (j = 0;j < Width;j++)
{
canvas[0][j] = -1;
canvas[High - 1][j] = -1;
}
canvas[High / 2][Width / 2] = 1;
for (i = 1;i < 5;i++)
{
canvas[High/2][Width /2-i] = i + 1;
}
move = 2;
food_i = rand() % High;
food_j = rand() % Width;
canvas[food_i][food_j] = -2;
}
通过rand来实现食物的随机生成(应注意边界范围,避免食物生成到边框处)
四.小蛇的移动原理,游戏失败的判断
void moveSnake()
{
int oldtail_i, oldtail_j, oldhead_i, oldhead_j;
int newhead_i, newhead_j;
int max = 0;
int i, j;
for (i = 0;i < High-1;i++)
for (j = 0;j < Width-1;j++)
{
if (canvas[i][j] > 0)
{
canvas[i][j]++;
if (canvas[i][j] > max)
{
max = canvas[i][j];
oldtail_i = i;
oldtail_j = j;
}
}
if (canvas[i][j] == 2)
{
oldhead_i = i;
oldhead_j = j;
}
}
if (move == 1)
{
newhead_i = oldhead_i;
newhead_j = oldhead_j - 1;
}
if (move == 2)
{
newhead_i = oldhead_i;
newhead_j = oldhead_j + 1;
}
if (move == 3)
{
newhead_i = oldhead_i - 1;
newhead_j = oldhead_j;
}
if (move == 4)
{
newhead_i = oldhead_i + 1;
newhead_j = oldhead_j;
}
if (canvas[newhead_i][newhead_j] == -2)
{
canvas[food_i][food_j] = 0;
food_i = rand() % (High-3)+2;
food_j = rand() % (Width-3)+2;
canvas[food_i][food_j] = -2;
}
else
canvas[oldtail_i][oldtail_j] = 0;
if (canvas[newhead_i][newhead_j] > 0 || canvas[newhead_i][newhead_j] == -1 )
{
printf("游戏失败\n");
exit(0);
}
else
canvas[newhead_i][newhead_j] = 1;
}
利用max来确定蛇尾的位置
五.用户输入
void scan()
{
char input;
if (kbhit())
{
input = getch();
if (input == 'a')
{
move = 1;
}
if (input == 'd')
{
move = 2;
}
if (input == 'w')
{
move = 3;
}
if (input == 's')
{
move = 4;
}
}
}
通过输入wasd来控制蛇移动方向
六.打印游戏界面
void display()
{
gotoxy(0, 0);
int i, j;
for (i = 0;i < High;i++)
{
for (j = 0;j < Width;j++)
{
if (canvas[i][j] == -1)
printf("#");
if (canvas[i][j] == 0)
printf(" ");
if (canvas[i][j] == 1)
printf("@");
if (canvas[i][j] > 1)
printf("*");
if (canvas[i][j] == -2)
printf("&");
}
printf("\n");
}
Sleep(100);
}
七.主函数
int main()
{
startup();
while (1)
{
display();
moveSnake();
scan();
}
return 0;
}