实现效果:
源码:
#include <stdio.h>
#include <Windows.h>
#include <time.h>
#include <conio.h>
#include <stdlib.h>
#define hang 25
#define lie 50
void init();
void gotoxy(int x,int y);
void begin();
void console();
void move();
void Food();
int outside();
void through_wall();
int death();
int i;
//定义蛇的位置
struct fun {
int x;
int y;
}snake[1000];
//定义食物位置
struct f{
int x;
int y;
}food;
int len=2,choose=80,food_in=0,flag=1,speed=500;
int main()
{
//初始化地图
init();
//生成食物
Food();
//出蛇
begin();
return 0;
}
void init()
{
for (i = 1; i <= hang; ++i)//输出两列
{
gotoxy(1, i);
printf("*");
gotoxy(lie, i);
printf("*");
}
for (i = 1; i <= lie; ++i)//输出两行
{
gotoxy(i, 1);
printf("*");
gotoxy(i, hang);
printf("*");
}
}
int wherex()
{
CONSOLE_SCREEN_BUFFER_INFO pBuffer;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
return (pBuffer.dwCursorPosition.X + 1);
}
int wherey()
{
CONSOLE_SCREEN_BUFFER_INFO pBuffer;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &pBuffer);
return (pBuffer.dwCursorPosition.Y + 1);
}
//移动光标函数
void gotoxy(int x, int y)//控制光标位置
{
COORD c;
c.X = x - 1;
c.Y = y - 1;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void begin()
{
snake[0].x = lie / 2;
snake[0].y = hang / 2;
while (flag==1)
{
Sleep(speed);
if (_kbhit() != 0)
{
//调用控制函数
console();
}
//如果吃到食物
if (snake[0].x == food.x && snake[0].y == food.y)
{
Food();
food_in = 0;
len++;
if (speed > 100)
{
speed -= 10;//吃到食物速度加快
}
}
else {
//消去之前的尾巴
gotoxy(snake[len - 1].x, snake[len - 1].y);
printf(" ");
}
//蛇头之后的身子向前移动
for (i = len-1; i>0; --i)
{
snake[i] = snake[i - 1];
}
//蛇头移动
move();
//输出蛇头
gotoxy(snake[0].x, snake[0].y);
printf("@");
//输出蛇长
for (i = 1; i < len; ++i)
{
gotoxy(snake[i].x, snake[i].y);
printf("*");
}
//输出食物
if (food_in == 0)
{
food_in = 1;
gotoxy(food.x, food.y);
printf("$");
}
}
system("cls");
printf("游戏失败!");
return;
}
void console()
{
_getch();
choose = _getch();
return;
}
//蛇头移动
void move()
{
switch (choose)
{
case 72:
snake[0].y--;
break;
case 75:
snake[0].x--;
break;
case 77:
snake[0].x++;
break;
case 80:
snake[0].y++;
break;
}
through_wall();
if (death())
{
flag = 0;
}
}
//随机产生食物
void Food()
{
do {
srand((unsigned) time(NULL));
food.x = rand() % (lie-2) + 2;
food.y = rand() % (hang - 2) + 2;
} while (outside());
}
//结合Food函数,保证食物生成在蛇的外部
int outside()
{
for (i = 0; i < len; ++i)
{
if (food.x == snake[i].x&&food.y==snake[i].y)
{
return 1;
}
}
return 0;
}
//穿墙
void through_wall()
{
if (snake[0].x >= lie)
{
snake[0].x -= lie - 2;
}
else if (snake[0].x <= 1)
{
snake[0].x += lie - 2;
}
else if (snake[0].y >= hang)
{
snake[0].y -= hang - 2;
}
else if (snake[0].y <= 1)
{
snake[0].y += hang - 2;
}
return;
}
int death()
{
for (i = 1; i < len; ++i)
{
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y)
{
return 1;
}
}
return 0;
}