自己用DevC 编写的贪吃蛇小游戏,带难度选择、计时、加速、暂停功能。
int play(HANDLE hout) {
system("cls");
unsigned char ch = 77;
struct Snake s, *snake = &s;
struct Food f, *food = &f;
selectcover(hout, snake);
makeframe(snake);
initsnake(snake);
printfood(hout, snake, food);
Sleep(500);
CLK = 0;
HANDLE hThread;
DWORD ThreadID;
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)gettime, NULL, 0, &ThreadID);
while (1) {
infor(hout, snake);
//保存蛇尾横纵坐标
a[0] = snake->x[0];
a[1] = snake->y[0];
j = 0;
//如果用户敲击键盘
if (kbhit()) {
//用ch接收输入 ,注意是getch(),不需敲击回车
ch = getch();
if (kbhit()) {
//长按时间
Sleep(20);
j = 1;
}
}
switch(ch) {
//向上移动
case 'W':
case 'w':
case 72: {
movesnake(hout, snake);
//蛇头纵坐标减一
snake->y[snake->length - 1] -= 1;
break;
}
//向下移动
case 'S':
case 's':
case 80: {
movesnake(hout, snake);
//蛇头纵坐标加一
snake->y[snake->length - 1] = 1;
break;
}
//向左移动
case 'A':
case 'a':
case 75: {
movesnake(hout, snake);
//蛇头横坐标减二
snake->x[snake->length - 1] -= 2;
break;
}
//向右移动
case 'D':
case 'd':
case 77: {
movesnake(hout, snake);
//蛇头横坐标加二
snake->x[snake->length - 1] = 2;
break;
}
//主菜单
case 'E':
case 'e': {
system("cls");
return 1;
break;
}
default: {
break;
}
} eatfood(hout, snake, food);
printsnake(hout,snake);
//如果判断蛇死亡,跳出循环
if (ifdead(snake) == 0 || ch==27 /*||snake->speed==0*/ || snake->count == HEIGHT_POINTS) {
gotoxy(hout, framex wide / 2, framey - 2);
//if(snake->speed==0)
if (snake->count == HEIGHT_POINTS)
printf("恭喜你通关了!!!");
else
printf("你输了!!!");
break;
} if (j == 0)
//如果没有长按,蛇滞留的时间为
Sleep(snake->delay);
//如果长按,蛇滞留的时间为 20ms,即加速
else
Sleep(20);
}
ECK = CLK;
//跳出循环时 ,滞留场景一段时间
Sleep(3000);
//清屏
system("cls");
//显示结束界面
//if(snake->speed==0)
if (snake->count == HEIGHT_POINTS)
printf("\n\n\n\n\n\t\t\t你赢了\n\n\t\t\t你得到了满分:%d\n\n\t\t\t你用了:%02d:%02d:%02d\n\n\n", HEIGHT_POINTS, ECK / 60 / 60, ECK / 60, ECK % 60);
else
printf("\n\n\n\n\n\t\t\t你输了\n\n\t\t\t你的最终得分是:%d\n\n\t\t\t你用了:%02d:%02d:%02d\n\n\n", snake->count, ECK / 60 / 60, ECK / 60, ECK % 60);
printf("\t\t\t按Y继续玩,按N退出。\n\n\n");
char x;
x = _getch();
if (x == 'Y' || x == 'y') {
system("cls");
return 1;
}
else return 0;
}
评论