目录
源码展示
#include <stdio.h>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#define SNAKE_HEAD ●//蛇头
#define SNAKE_BODY ○//蛇身
#define initSIZE 3//初始化蛇长
#define MAP_HEAD 30//初始化地图高
#define MAP_WIDETH 80//初始化地图宽
#define SNAKE_MAXLENGTH 100//蛇的最大长度
int flag = 1;
int dir = 'a';
int score = 0;
int speed = 250;
struct Snake//蛇的坐标
{
int x[SNAKE_MAXLENGTH];
int y[SNAKE_MAXLENGTH];
int length;
}snake;
struct Food//食物坐标
{
int food_x;
int food_y;
}food;
void color(int c);
void gotoxy(int x, int y);//控制光标
void HideCursor();//隐藏光标
void MAP();
void beginGame();
void snake_ADDRESS();
void snake_FOOD();
void snake_MOVE();
int snake_DEATH();
void snake_SCORE();
int main()
{
MAP();
beginGame();
MAP();
snake_ADDRESS();
while (1)
{
snake_SCORE();
HideCursor();
if (flag)
snake_FOOD();
Sleep(speed);
if (snake_DEATH())
{
gotoxy(MAP_WIDETH / 2, MAP_HEAD / 2);
printf("游戏结束,您的最终得分为:%d\n", score);
gotoxy(MAP_WIDETH / 2, MAP_HEAD / 2 + 2);
color(3);
system("pause");
gotoxy(95, 29);//移除光标
return 0;
}
snake_MOVE();
}
return 0;
}
void gotoxy(int x, int y)
{
COORD pos = { x,y };
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);// 获取标准输出设备句柄
SetConsoleCursorPosition(hOut, pos);//两个参数分别是指定哪个窗体,具体位置
}
void HideCursor() // 用于隐藏光标
{
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 }; // 第二个值为0表示隐藏光标
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);//函数和结构体都在windows.h中定义。
}
void color(int c)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), c); //颜色设置
}
//打印地图
void MAP()
{
color(4);
for (int i = 1; i < MAP_WIDETH; i += 2) //地图宽80,高30
{
gotoxy(i, 0);//上边界
printf("■");
gotoxy(i, MAP_HEAD - 1);//下边界
printf("■");
}
for (int i = 1; i < MAP_HEAD; i++)
{
gotoxy(0, i);//左边界
printf("■");
gotoxy(MAP_WIDETH, i);//右边界
printf("■");
}
gotoxy(0, 0); //移动光标
}
//打印蛇
void snake_ADDRESS()
{
snake.x[0] = MAP_WIDETH / 2;
snake.y[0] = MAP_HEAD / 2;
snake.length = initSIZE;
color(7);
//打印蛇头
gotoxy(snake.x[0], snake.y[0]);
printf("◎");
//循环打印蛇身
color(14);
for (int i = 1; i < snake.length; i+&