说明
根据网上别人的代码经过改编在大一计算机实训时写的,其中较难理解的应该是句柄,需要自己网上查找资料
代码及注释
#include<stdio.h>
#include<conio.h>
#include<windows.h>
#include<time.h>
#define framex 5
#define framey 5
#define wide 20
#define high 20
int i,j,a[2];
//将光标移动到指定位置
void gotoxy(HANDLE hout,int x,int y){
//COORD是WindowsAPI中定义的一种结构,表示一个字符在控制台屏幕上的坐标
COORD pos;
pos.X=x;
pos.Y=y;
//SetConsoleCursorPosition是API中定位光标位置的函数。
SetConsoleCursorPosition(hout,pos);
}
//游戏封面
void cover (HANDLE hout){
gotoxy(hout,framex+wide,framey);
printf("欢迎使用贪吃蛇游戏1.2");
gotoxy(hout,framex+wide,framey+5);
printf("开始游戏前请关闭中文输入法");
gotoxy(hout,framex+wide*2,framey+20);
printf( "游戏制作者:Lin");
gotoxy(hout,framex+wide*2,framey+22);
printf("制作时间:2016年12月");
char a;
a=getchar();
system("cls");
}
//定义蛇的结构体
struct Snake{
int x[100];
int y[100];
int speed;
int length;
int count;
};
//定义食物的结构体
struct Food{
int x;
int y;
};
//制作框架
void makeframe(struct Snake snake){
//定义显示器变量句柄
HANDLE hout=GetStdHandle(STD_OUTPUT_HANDLE);
gotoxy(hout,framex+wide*2+5,framey);
printf( " 贪吃蛇游戏");
gotoxy(hout,framex+wide*2+5,framey+3);
printf("使用方向键或wasd移动");
gotoxy(hout,framex+wide*2+5,framey+5);
printf("长按方向键可加速");
gotoxy(hout,framex+wide*2+5,framey+7);
printf("按任意键暂停,方向键继续");
//打印上边框
for(i=0;i<wide*2+1;i++){
gotoxy(hout,framex+i,framey);
printf("*");
}
//打印下边框
for(i=0;i<wide*2+2;i++){
gotoxy(hout,framex+i,framey+high);
printf("*");
}
//打印左边框
for(i=0;i<high;i++){
gotoxy(hout,framex,framey+i);
printf("*");
}
//打印右边框
for(i=0;i<high;i++){
gotoxy(hout,framex+wide*2+1,framey+i);
printf("*");
}
}
//游戏信息
void infor(HANDLE hout,struct Snake* snake){
gotoxy(hout,framex+wide*2+5,framey+15);
printf("当前速度:%d",-snake->speed+500);
gotoxy(hout,framex+wide*2+5,framey+17);
printf("当前得分:%d",snake->count);
gotoxy(hout,framex+wide*2+5,framey+19);
printf("当前长度:%d",snake->length);
}
//初始化蛇
void initsnake(struct Snake *snake){
snake->x[0]=framex+2;
snake-&g