#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
const
int
H = 8;
const
int
L = 16;
char
GameMap[H][L];
int
key;
int
sum = 1, over = 0;
int
dx[4] = {0, 0, -1, 1};
int
dy[4] = {-1, 1, 0, 0};
struct
Snake
{
int
x, y;
int
now;
}Snake[H*L];
const
char
Shead =
'@'
;
const
char
Sbody =
'#'
;
const
char
Sfood =
'*'
;
const
char
Snode =
'.'
;
void
Initial();
void
Create_Food();
void
Show();
void
Button();
void
Move();
void
Check_Border();
void
Check_Head(
int
x,
int
y);
int
main()
{
Initial();
Show();
return
0;
}
void
Initial()
{
int
i, j;
int
hx, hy;
system
(
"title 贪吃蛇"
);
memset
(GameMap,
'.'
,
sizeof
(GameMap));
system
(
"cls"
);
srand
(
time
(0));
hx =
rand
()%H;
hy =
rand
()%L;
GameMap[hx][hy] = Shead;
Snake[0].x = hx; Snake[0].y = hy;
Snake[0].now = -1;
Create_Food();
for
(i = 0; i < H; i++)
{
for
(j = 0; j < L; j++)
printf
(
"%c"
, GameMap[i][j]);
printf
(
"\n"
);
}
printf
(
"\n小小C语言贪吃蛇\n"
);
printf
(
"按任意方向键开始游戏\n"
);
getch();
Button();
}
void
Create_Food()
{
int
fx, fy;
while
(1)
{
fx =
rand
()%H;
fy =
rand
()%L;
if
(GameMap[fx][fy] ==
'.'
)
{
GameMap[fx][fy] = Sfood;
break
;
}
}
}
void
Show()
{
int
i, j;
while
(1)
{
_sleep(500);
Button();
Move();
if
(over)
{
printf
(
"\n**游戏结束**\n"
);
printf
(
" >_<\n"
);
getchar
();
break
;
}
system
(
"cls"
);
for
(i = 0; i < H; i++)
{
for
(j = 0; j < L; j++)
printf
(
"%c"
, GameMap[i][j]);
printf
(
"\n"
);
}
printf
(
"\n小小C语言贪吃蛇\n"
);
printf
(
"按任意方向键开始游戏\n"
);
}
}
void
Button()
{
if
(kbhit() != 0)
{
while
(kbhit() != 0)
key = getch();
switch
(key)
{
case
75: Snake[0].now = 0;
break
;
case
77: Snake[0].now = 1;
break
;
case
72: Snake[0].now = 2;
break
;
case
80: Snake[0].now = 3;
break
;
}
}
}
void
Move()
{
int
i, x, y;
int
t = sum;
x = Snake[0].x; y = Snake[0].y; GameMap[x][y] =
'.'
;
Snake[0].x = Snake[0].x + dx[ Snake[0].now ];
Snake[0].y = Snake[0].y + dy[ Snake[0].now ];
Check_Border();
Check_Head(x, y);
if
(sum == t)
for
(i = 1; i < sum; i++)
{
if
(i == 1)
GameMap[ Snake[i].x ][ Snake[i].y ] =
'.'
;
if
(i == sum-1)
{
Snake[i].x = x;
Snake[i].y = y;
Snake[i].now = Snake[0].now;
}
else
{
Snake[i].x = Snake[i+1].x;
Snake[i].y = Snake[i+1].y;
Snake[i].now = Snake[i+1].now;
}
GameMap[ Snake[i].x ][ Snake[i].y ] =
'#'
;
}
}
void
Check_Border()
{
if
(Snake[0].x < 0 || Snake[0].x >= H
|| Snake[0].y < 0 || Snake[0].y >= L)
over = 1;
}
void
Check_Head(
int
x,
int
y)
{
if
(GameMap[ Snake[0].x ][ Snake[0].y ] ==
'.'
)
GameMap[ Snake[0].x ][ Snake[0].y ] =
'@'
;
else
if
(GameMap[ Snake[0].x ][ Snake[0].y ] ==
'*'
)
{
GameMap[ Snake[0].x ][ Snake[0].y ] =
'@'
;
Snake[sum].x = x;
Snake[sum].y = y;
Snake[sum].now = Snake[0].now;
GameMap[ Snake[sum].x ][ Snake[sum].y ] =
'#'
;
sum++;
Create_Food();
}
else
over = 1;
}