#include<stdafx.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define N 21
char apple[2];
char tail[2];
char **snake = NULL;
int score = 0;
int len = 3;
char max = 0;
void gotoxy(int x, int y) //输出坐标
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void color(int b) //颜色函数
{
HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE));
SetConsoleTextAttribute(hConsole, b);
}
int block(char head[2])//判断出界
{
int i;
if ((head[0]<1 || head[0]>N) || (head[1]<1 || head[1]>N))return 1;//判断出界
for (i = 1; i<len; i++)
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) return 1;//判断是否碰到自己的身体
return 0;
}
int eat()//判断吃苹果
{
if (snake[0][1] == apple[1] && snake[0][0] == apple[0])
{
apple[0] = apple[1] = 0;
gotoxy(N * 2 + 10, 9);
color(14);
score++;
printf("你现在得分:%d", score * 10);
len++;//若吃了苹果,增加分数,蛇长度
gotoxy(tail[1] * 2, tail[0]);
color(14);
printf("★");
return 1;
}
else
{
gotoxy(tail[1] * 2, tail[0]);
color(11);
printf("■");
return 0;
}//处理蛇的尾巴
}
void move(char ch)//蛇移动
{
void creat();
int i, a;
if (ch == 'w' || ch == 'W' || ch == 's' || ch == 'S' || ch == 'a' || ch == 'A' || ch == 'd' || ch == 'D')//输入非wasd字符暂停移动
{
memcpy(tail, snake[len - 1], 2);
for (i = len - 1; i>0; i--)
memcpy(snake[i], snake[i - 1], 2);
switch (ch)
{
case 'w': case 'W':--snake[0][0]; break;
case 's': case 'S':++snake[0][0]; break;
case 'a': case 'A':--snake[0][1]; break;
case 'd': case 'D':++snake[0][1]; break;
default:;
}
gotoxy(snake[0][1] * 2, snake[0][0]);
color(14);
printf("★");//移动蛇头
if (a = eat())
{
snake = (char **)realloc(snake, sizeof(char *)*(len));
snake[len - 1] = (char *)malloc(sizeof(char) * 2);
memcpy(snake[len - 1], tail, 2);//为蛇身开辟新空间储存地址
creat();
}
}
}
int f()//判断苹果是否在蛇身上
{
int i, n;
for (i = 0; i<len; i++)if (apple[0] == snake[i][0] && apple[1] == snake[i][1]) break;
if (i<len || (apple[0] == snake[len - 1][0] && apple[1] == snake[len - 1][1])) n = 1;
else n = 0;
return n;
}
void creat()//随机生成苹果
{
int n, a = 0;
srand((unsigned)time(NULL));
apple[0] = rand() % N + 1;
apple[1] = rand() % N + 1;
apple[2] = 1;
while (int n=f())//若苹果在蛇身上,重复随机生成苹果
{
apple[0] = rand() % N + 1;
apple[1] = rand() % N + 1;
apple[2] = 1;
n = f();
a++;
if (a == 100000) //判断蛇身是否满屏
{
gotoxy(10, 10);
color(12);
printf("恭喜您打破记录");
}
}
gotoxy(apple[1] * 2, apple[0]);
color(12);
printf("●");
}
void p()//界面初始化
{
int a[N + 2][N + 2] =