`
include <graphics.h>
include <conio.h>
include <stdio.h>
include <time.h>
define screen_x 1000
define screen_y 700
define len 10
struct Point {
int x;
int y;
};
struct Snake {
int num;//蛇的节数
Point p[30];//蛇最多有30节
char direction;//方向
}snake;
struct Food {
Point p2;
int exist;//食物是否存在
}food;
enum Dire{right=72,left=75,up=80,down=77};
void init_snake() {
snake.p[0].x = 2*len;
snake.p[0].y = 0;
snake.p[1].x = len;
snake.p[1].y = 0;
snake.p[2].x = 0;
snake.p[2].y = 0;
snake.num = 3;
snake.direction = right;//蛇初始方向
}
void init_food() {
food.p2.x = rand() % 65 * len;
food.p2.y = rand() % 48 * len;
food.exist = 1; //食物存在
//食物碰到蛇就重新生成食物
for (int i = 0; i < snake.num; i++) {
if (food.p2.x == snake.p[i].x && food.p2.y == snake.p[i].y) {
food.p2.x = rand() % 65 * len;
food.p2.y = rand() % 48 * len;
}
}
}
void draw_snake() {
for (int i = 0; i < snake.num; i++) {
setlinecolor(BLACK);//矩形边框线
setfillcolor(GREEN);
fillrectangle(snake.p[i].x,snake.p[i].y, snake.p[i].x+len, snake.p[i].y+len);//画矩形
}
}
void draw_food() {
setfillcolor(RED);
fillrectangle(food.p2.x,food.p2.y,food.p2.x+len,food.p2.y+len);
}
void move() {
//除了第一节以外的移动
for (int i = snake.num - 1; i > 0; i--) {
snake.p[i].x = snake.p[i - 1].x;
snake.p[i].y = snake.p[i - 1].y;
}
//第一节的移动
switch (snake.direction) {
case right:
snake.p[0].x += len;
break;
case left:
snake.p[0].x -= len;
break;
case down:
snake.p[0].y += len;
break;
case up:
snake.p[0].y -= len;
break;
default:
break;
}
}
void key_down() {
//按键盘上的四个箭头进行移动,不按WASD
char user = 0;
user = _getch();
switch (user) {
case right:
if (snake.direction != down)snake.direction = up;
break;
case left:
if (snake.direction != right)snake.direction = left;
break;
case down:
if (snake.direction != left)snake.direction = right;
break;
case up:
if (snake.direction != up)snake.direction = down;
break;
}
}
void eat() {
if (food.p2.x == snake.p[0].x && food.p2.y == snake.p[0].y) {
snake.num++;
food.exist = 0;
}
}
int main() {
srand(time(0));
initgraph(screen_x, screen_y);
setbkcolor(WHITE);
init_snake();//初始化蛇
while (1) {
cleardevice();
draw_food();
if (food.exist == 0) {
init_food();
}
eat();
draw_snake();//屏幕上画出蛇
move();//移动蛇
while (_kbhit()) {
key_down();
}
//蛇身体过长
if (snake.num >= 30) {
closegraph();
exit(0);
}
//蛇撞墙(碰到窗口边框)
if (snake.p[0].x > screen_x || snake.p[0].x < 0 || snake.p[0].y <0 || snake.p[0].y > screen_y) {
closegraph();
exit(0);
}
//自己撞自己
for (int i = 1; i < snake.num; i++) {
if (snake.p[0].x == snake.p[i].x && snake.p[0].y == snake.p[i].y) {
closegraph();
exit(0);
}
}
Sleep(100);//本质上控制了蛇的速度
}
getchar();//防止闪屏
closegraph();
return 0;
}
`