日期:2018.9.11

用时:150min

项目:贪吃蛇(C语言--数组   结构体实现)

开发工具:vs2013

关键知识:数组,结构体,图形库,键位操作

源代码:

 #include<stdio.h>
#include<graphics.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h> #define N 200
int i, key;
int score = ;
int gamespeed = ; void init(void);
void Draw();
void Playgame();
void Prscore();
void Gameover(); struct Food {
int x;
int y;
int yes;
}food; struct Snake{
int x[N];
int y[N];
int node;
int direcion;
int life;
}snake; void main()
{
init();
Draw();
Playgame();
_getch();
} void init(void)
{
initgraph(,);
setbkcolor(WHITE);
cleardevice();
} void Draw()
{
setcolor(BLACK);
for (i = ; i <= ; i += )
{
rectangle(i, , i + , );
rectangle(i, , i + , );
}
for (i = ; i <= ; i += )
{
rectangle(, i, , i + );
rectangle(, i, , i + );
}
} void Playgame()
{
srand((unsigned)time(NULL));//用时间做种,每次产生的随机数不一样。
food.yes = ;//1表示需要出现食物,0表示已有食物
snake.life = ;//0,活着,1 死亡
snake.direcion = ;
snake.x[] = ; snake.y[] = ;
snake.x[] = ; snake.y[] = ;
snake.node = ;
Prscore();
while ()
{
while (!_kbhit())
{
if (food.yes == )
{
food.x = rand() % + ;
food.y = rand() % + ;
while (food.x % != )
food.x++;
while (food.y % != )
food.y++;
food.yes = ;
}
if (food.yes == )
{
setcolor(RED);
rectangle(food.x, food.y, food.x + , food.y + );
}
for (i = snake.node - ; i > ; i--)
{
snake.x[i] = snake.x[i - ];
snake.y[i] = snake.y[i - ];
}
switch (snake.direcion)
{
case :snake.x[] += ; break;
case :snake.x[] -= ; break;
case :snake.y[] -= ; break;
case :snake.y[] += ; break;
}
for (i = ; i < snake.node; i++)
{
if (snake.x[i] == snake.x[] && snake.y[i] == snake.y[])
{
Gameover();
snake.life = ;
break;
}
}
if (snake.x[]< || snake.x[]> || snake.y[]< || snake.y[]>)
{
Gameover();
snake.life = ;
}
if (snake.life == )
break;
if (snake.x[] == food.x&&snake.y[] == food.y)
{
setcolor(BLACK);
rectangle(food.x, food.y, food.x + , food.y + );
snake.x[snake.node] = -; snake.y[snake.node] = -;
snake.node++;
food.yes = ;
score += ;
Prscore();
}
setcolor(GREEN);
for (i = ; i < snake.node; i++)
rectangle(snake.x[i], snake.y[i],snake.x[i] + , snake.y[i] + );
if (food.yes == )
{
if (gamespeed >= )
gamespeed -= ;// 速度最大不超过
} Sleep(gamespeed);
setcolor(WHITE);
rectangle(snake.x[snake.node - ], snake.y[snake.node - ], snake.x[snake.node-] + , snake.y[snake.node - ] + );
}
if (snake.life == )
break;
switch (_getch())
{
case 'w':
case 'W':
if (snake.direcion != )
{
snake.direcion = ;
}
break;
case 'd':
case 'D':
if (snake.direcion != )
{
snake.direcion = ;
}
break;
case 'a':
case 'A':
if (snake.direcion != )
{
snake.direcion = ;
}
break;
case 's':
case 'S':
if (snake.direcion != )
{
snake.direcion = ;
}
break;
}
}
} void Prscore()
{
char str[];
setfillstyle(SOLID_FILL, YELLOW);
bar(, , , );
setcolor();
sprintf_s(str, "score:%d", score);
outtextxy(, , str);
} void Gameover()
{
cleardevice();
setbkcolor(WHITE);
Prscore();
setcolor(RED);
settextstyle(, , "楷体");
outtextxy(, , "GAME OVER");
_getch();
}

运行截图:

C语言实现贪吃蛇-LMLPHP

C语言实现贪吃蛇-LMLPHP

05-11 17:21