C程序贪吃蛇游戏无法继续游戏,帮帮看哪里出错了

每天一个台阶,fighting!!!
C语言实现贪吃蛇(一)----数组实现
本人是一个C语言新手,在网上看到有的人用C实现了贪吃蛇的游戏,想着为了巩固一下自己的C语言,然后就学着写了一个,当然基本上是Copy别人的代码,然后加上自己的理解。在这里做一下记录,也希望能够帮助那些跟我差不多的同学。
一、贪吃蛇实现原理:
贪吃蛇游戏在理论上是可以无限的进行下去的(除了撞墙和咬到自己),那么游戏主体就一定是个循环。
蛇是如何动起来的?在这里就是通过不断改变蛇的坐标,然后根据蛇的坐标不断刷新屏幕在视觉上形成蛇的移动效果。
食物出现在随机位置(当然不能出现在障碍物和蛇身上)。
蛇能吃到食物其实就是蛇头的坐标与食物的坐标重合时。
当蛇咬到自己或者撞到墙的时候游戏结束(坐标判断)
还有一点要注意的是:命令行的坐标轴长这样:
因为后面在处理坐标的时候可能会乱(我在看的时候就思维混乱过)。
二、代码实现:
现在我们来看看整个程序的最主要部分:主函数
int main(void){
int dir = UP;
print_game();
dir = get_dir(dir);
move_snake(dir);
if(!isalive()){
printf("Game Over!\n");
从主函数中我们看到,游戏的整体思路是比较简单的,仅仅只有那么几个函数。有了框架我们再来具体实现。
首先考虑使用的数据结构,正如博客名所示,这次我只用数组,不使用链表和结构体。在这里我们用一个二维数组 char map[17][17] 来表示地图,用一维数组 unsigned char snake[50] 来表示蛇的坐标。这里之所以用char是因为本着能省则省的原则,我们这是一个17*17大小的小游戏,char足够了。
上面的这些基本上是Copy原作者的话,但是还是有必要解释一下。用一维数组 unsigned char snake[50] 来表示蛇的坐标,这里假设了我们玩的蛇能达到的最大长度为 50(能玩到这个长度已经很牛逼了,满足吧!),也就是说我们用一个 unsigned char 类型的数字表示蛇的坐标。怎么表示?还是引用原作者的话:
只用数组做贪吃蛇的话,在蛇坐标与食物坐标的存储上会比较麻烦,毕竟我们的游戏坐标是二维的,这里我采用位运算的方法,一个unsigned char类型的变量八位,前四位记录x坐标,后四位记录y坐标,四位的话,最大值也就是15,所以我设置的是17*17的大小,(15+边界)*(15+边界)。要是觉得地图太小的话,用int(4位)或者long(4位或8位)也是可以的。
好了,屁话说了这么多,我们先来看看程序开始应该定义的一些变量和函数声明:
#include &stdio.h&
#include &conio.h&
#include &stdlib.h&
#include &windows.h&
#include &time.h&
#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
#define SNAKE 1
#define FOOD 2
#define BAR 3
char map[17][17] = {0};
unsigned char snake[50] = {77};
unsigned char food = 68;
char len = 1;
void tran(unsigned char num,unsigned char * x,unsigned char * y);
void print_game(void);
int get_dir(int old_dir);
void move_snake(int dir);
unsigned char generate_food(void);
int isalive(void);
int main(void){
int dir = UP;
print_game();
dir = get_dir(dir);
move_snake(dir);
if(!isalive()){
printf("Game Over!\n");
//存储坐标数字与x、y的转换函数
void tran(unsigned char num,unsigned char * x,unsigned char * y);
该函数实现了将 num 的前四位代表的值赋给 x,后四位赋给 y,得到对应的坐标(x,y)
void tran(unsigned char num,unsigned char * x,unsigned char * y){
*x = num && 4;
*y = (unsigned char)(num && 4) && 4;
碰到被调用函数需要返回两个以上参数的时候,应该像上述函数一样,将要返回的值写成指针参数。
//打印游戏
void print_game(void);
void print_game(void){
for(j = 0;j & 17;j ++){
for(i = 0;i & 17;i ++){
if(map[i][j] == 0){
putchar(' ');
else if(map[i][j] == SNAKE){
putchar('*');
else if(map[i][j] == BAR){
putchar('#');
else if(map[i][j] == FOOD){
putchar('$');
putchar('\n');
Sleep(500);
system("cls");
//获取方向函数(注意当蛇身长度超过一节时不能回头)
int get_dir(int old_dir);
这里有一个注意的点:当蛇身长度超过一节的时候,我们就不能往回走了。
在这里我们是用 kbhit() 与 getch() 组合实现键盘响应
int get_dir(int old_dir){
int new_dir = old_
if(_kbhit()){
new_dir = _getch();
if(len & 1 && (abs(new_dir - old_dir) == 2 || abs(new_dir - old_dir) == 8)){
new_dir = old_
return new_
原作者提示:getch()和kbhit()前面的下划线是因为在vs环境下一些函数需要使用加下划线的版本,更安全。
//移动蛇身函数(游戏大部分内容在其中)
void move_snake(int dir);
void move_snake(int dir){
int last = snake[0],
int grow=0;
unsigned char x, y,fx,
tran(food, &fx, &fy);
tran(snake[0], &x, &y);
switch (dir){
case DOWN:
case LEFT:
case RIGHT:
snake[0] = ((x ^ 0) && 4) ^
if (snake[0] == food) {
food = generate_food();
for (i = 0; i&len; i++) {
if (i == 0)
current = snake[i];
snake[i] =
if (grow) {
snake[len] =
for (j = 0; j & 17; j ++){
for (i = 0; i & 17; i ++){
if (i == 0 || i == 16 || j == 0 || j == 16){
map[i][j] = BAR;
else if (i == fx&&j == fy){
map[i][j] = FOOD;
map[i][j] = 0;
for (i = 0; i & len; i++) {
tran(snake[i], &x, &y);
if (snake[i] & 0){
map[x][y] = SNAKE;
//生产食物的函数
unsigned char generate_food(void);
随机数生成函数,一般由srand()和rand()函数组成,前者以当前时间为参数提供种子供rand()函数生成更为随机的数。这里用do while语句做了一个筛选,最后产生在边界内且不再蛇身上的食物。
unsigned char generate_food(void)
unsigned char food_,fx,
int in_snake=0,i;
srand((unsigned int)time(NULL));
food_ = rand() % 255;
tran(food_, &fx, &fy);
for (i = 0; i & i++){
if (food_ == snake[i]){
in_snake = 1;
} while (fx == 0 || fx == 16 || fy == 0 || fy == 16 || in_snake);
return food_;
//判断蛇死活的函数(判断了蛇是否撞到边界或者自食)
int isalive(void);
int isalive(void)
int self_eat = 0,
unsigned char x,
tran(snake[0], &x, &y);
for (i = 1; i & i++){
if (snake[0] == snake[i]){
self_eat = 1;
return (x == 0 || x == 16 || y == 0 || y &= 16 || self_eat) ? 0 : 1;
终于好了,我们看看效果图:
虽然相当得简陋,由于用的是全屏刷新的方法,闪屏也比较严重,但也算是麻雀虽小五脏俱全,该有的功能也都有了。在接下来我还会跟着原作者的步伐对这个小游戏进行改进,直到比较”顺眼“为止。也希望大家在看的时候有啥疑问或不对的地方,请提出来。大神路过的话,就不要喷我这种小白了。
本博客有相当一部分(0.9+)是参考自
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!用c语言设计贪吃蛇游戏_百度知道
用c语言设计贪吃蛇游戏
贪吃蛇游戏
【游戏规则】
游戏开始时弹出初始菜单,游戏者按任意键进入游戏。游戏者用←↓→↑键来控制蛇在游戏场景内运动,每吃到一个食物,游戏者得10分,分数累加结果会在计分板上显示;与此同时蛇身长出一节。当贪吃蛇的头部撞击到游戏场景边框或者蛇的...
我有更好的答案
//&&Copyright&liaoqb&#include&&windows.h&#include&&stdlib.h&#include&&time.h&const&int&LENGTH&=&40;const&int&WIDTH&=&10;const&int&RANGE&=&50;const&int&BeginLength&=&5;const&int&speed&=&300;#define&SNAKE_COLOR&RGB(176,&196,&222)#define&BACKGROUND_COLOR&RGB(255,&255,&0)#define&DRAW_SNAKE(x)&(x)&*&WIDTHenum&IsSnake&{isSnake,&isNotSnake,&isFood};IsSnake&map[LENGTH][LENGTH];struct&snake&{&&int&x;&&int&y;&&snake*&&&snake(int&x,&int&y,&snake*&n&=&NULL)&{&&&&this&-&&x&=&x;this&-&&y&=&y;next&=&n;&&}};&&//&snaketypedef&struct&snake&SSnake*&head&=&NULL;&&//&queueSnake*&tail&=&NULL;&&//&queueint&direct&=&0;&&//&directionRECT&&&//&districtTCHAR&szAppName[]&=&TEXT(&-*-&snake&game&-*&&);&&//&The&project&nameLRESULT&CALLBACK&WndProc(HWND,&UINT,&WPARAM,&LPARAM);&&//&message&functionvoid&Initializer();void&Controller(Snake*,LPVOID);&&//&control&the&snakevoid&Move(HWND);void&PutFood();int&WINAPI&WinMain(HINSTANCE&hInstance,&HINSTANCE&hPreInstance,&PSTR&szCmdLine,&int&iCmdShow)&{&&MSG&&&HWND&&&WNDCLASS&&&while&(TRUE)&{wndclass.cbClsExtra&=&0;wndclass.cbWndExtra&=&0;wndclass.hbrBackground&=&CreateSolidBrush(RGB(255,&255,&255));wndclass.hCursor&=&LoadCursor(NULL,&IDC_ARROW);wndclass.hIcon&=&LoadIcon(NULL,&IDI_APPLICATION);wndclass.hInstance&=&hIwndclass.lpfnWndProc&=&WndPwndclass.lpszClassName&=&szAppNwndclass.lpszMenuName&=&NULL;wndclass.style&=&CS_HREDRAW&|&CS_VREDRAW;if&(!RegisterClass(&wndclass))&{&MessageBox(NULL,&TEXT(&Please&try&again!!!&),&szAppName,&MB_ICONERROR);&return&0;}&&}&&hwnd&=&CreateWindow(szAppName,&TEXT(&&^_^&&Snake&Game&&^_^&&),&WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,&CW_USEDEFAULT,&CW_USEDEFAULT,&CW_USEDEFAULT,NULL,&NULL,&hInstance,&NULL);&&ShowWindow(hwnd,&SW_NORMAL);&&UpdateWindow(hwnd);&&while&(TRUE)&{if&(PeekMessage(&msg,&NULL,&0,&0,&PM_REMOVE))&{&if&(msg.message&==&WM_QUIT)&&&&TranslateMessage(&msg);&DispatchMessage(&msg);}&else&{&Move(hwnd);}&&}&&return&msg.wP}LRESULT&CALLBACK&WndProc(HWND&hwnd,&UINT&message,&WPARAM&wParam,&LPARAM&lParam)&{&&HDC&&&PAINTSTRUCT&&&HBRUSH&hB&&switch&(message)&{&&case&WM_DESTROY:PostQuitMessage(0);return&0;&&case&WM_CREATE:Initializer();MoveWindow(hwnd,&RANGE,&RANGE,&WIDTH&*&LENGTH&+&RANGE&*&3,&WIDTH&*&LENGTH&+&RANGE&*&3,&TRUE);return&0;&&case&WM_KEYDOWN:switch&(wParam)&{case&VK_LEFT:&if&(direct&!=&VK_RIGHT)direct&=&VK_LEFT;&case&VK_RIGHT:&if&(direct&!=&VK_LEFT)direct&=&VK_RIGHT;&case&VK_UP:&if&(direct&!=&VK_DOWN)direct&=&VK_UP;&case&VK_DOWN:&if&(direct&!=&VK_UP)direct&=&VK_DOWN;&default:&}return&0;&&case&WM_PAINT:hdc&=&BeginPaint(hwnd,&&ps);SetViewportOrgEx(hdc,&RANGE,&RANGE,&NULL);hBrush&=&CreateSolidBrush(BACKGROUND_COLOR);SelectObject(hdc,&hBrush);Rectangle(hdc,playground.left,&playground.top,&playground.right,&playground.bottom);DeleteObject(hBrush);hBrush&=&CreateSolidBrush(SNAKE_COLOR);SelectObject(hdc,hBrush);for&(int&i&=&0;&i&&&LENGTH;&++i)&{&for&(int&j&=&0;&j&&&LENGTH;&++j)&{if&(map[i][j]&==&isSnake&||&map[i][j]&==&isFood)&{&Rectangle(hdc,&DRAW_SNAKE(i),&DRAW_SNAKE(j),&DRAW_SNAKE(i&+&1),&DRAW_SNAKE(j&+&1));}&}}DeleteObject(hBrush);EndPaint(hwnd,&&ps);&&}&&return&DefWindowProc(hwnd,&message,&wParam,&lParam);}void&Initializer()&{&&for&(int&i&=&0;&i&&&LENGTH;&++i)&{for&(int&j&=&0;&j&&&LENGTH;&++j)&{&map[i][j]&=&isNotS}&&}&&for&(i&=&0;&i&&&BeginL&++i)&{if&(i&==&0)&{&head&=&tail&=&new&snake(i,&0);}&else&{&snake*&temp&=&new&snake(i,&0);&tail&-&&next&=&&tail&=&}map[i][0]&=&isS&&}&&playground.left&=&playground.top&=&0;&&playground.right&=&playground.bottom&=&WIDTH&*&LENGTH;&&direct&=&VK_RIGHT;&&PutFood();}void&PutFood()&{&&srand(static_cast&unsigned&(time(NULL)));&&int&x,&y;&&do&{&&&&x&=&rand()&%&LENGTH;y&=&rand()&%&LENGTH;&&}&while&(map[x][y]&==&isSnake);&&map[x][y]&=&isF}&&//&put&foodvoid&Move(HWND&hwnd)&{&&snake*&&&switch&(direct)&{&&case&VK_LEFT:temp&=&new&snake(tail&-&&x&-&1,&tail&-&&y);&&case&VK_RIGHT:temp&=&new&snake(tail&-&&x&+&1,&tail&-&&y);&&case&VK_UP:temp&=&new&snake(tail&-&&x,&tail&-&&y&-&1);&&case&VK_DOWN:temp&=&new&snake(tail&-&&x,&tail&-&&y&+&1);&&}&&Controller(temp,hwnd);&&//InvalidateRect(hwnd,NULL,FALSE);&&Sleep(speed);&&//&control&speed}&&//&snake&movingvoid&Controller(Snake*&temp,LPVOID&lParam)&{HWND&hwnd=(HWND)lP&&if&(temp&-&&x&&&0&||&temp&-&&x&&=&LENGTH&||&temp&-&&y&&&0&||&temp&-&&y&&=&LENGTH||&map[temp&-&&x][temp&-&&y]&==&isSnake)&{&&//&the&snake&is&died&&&&MessageBox(NULL,TEXT(&&Copyright&liaoqb&&Sorry&!!!&Game&Over&!!!&&Copyright&liaoqb&&),szAppName,0);delete&while&(head&!=&NULL)&{&Snake*&ptr&=&&head&=&head&-&&&delete&}head&=&tail&=&temp&=&NULL;Initializer();&&}&else&if&(map[temp&-&&x][temp&-&&y]&==&isNotSnake)&{&&//&move&&&&map[temp&-&&x][temp&-&&y]&=&isSmap[head&-&&x][head&-&&y]&=&isNotSsnake*&ptr&=&head&=&head&-&&delete&tail&-&&next&=&tail&=&InvalidateRect(hwnd,NULL,FALSE);&&}&else&{&&//&if&eat&food&&&&map[temp&-&&x][temp&-&&y]&=&isStail&-&&next&=&tail&=&PutFood();//InvalidateRect(hwnd,NULL,FALSE);&&}}
可以运行吗??
那为什么我把这个复制到vc6.0显示不能运行啊。。
你是直接双击打开,然后编译运行吗?
复制 然后调试
你有没有先创建application工程
解压后双击.dsw文件
还是不明白=_=
那用这个吧,比较简单
采纳率:41%
来自团队:
为您推荐:
其他类似问题
您可能关注的内容
贪吃蛇游戏的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。一个C语言编写的贪吃蛇游戏
在VC6.0平台上,通过C语言和EasyX图形库编写的贪吃蛇小游戏,为了使用图形库函数,建立的文件是.cpp文件,使用的是C语言编写,游戏具有背景音乐,代码长度500行左右,代码和算法,都是我自己源生的,分享给有兴趣的朋友看看。
#include&stdio.h&
#include&graphics.h&
#include&time.h&
#include&conio.h&
#include&easyx.h&
#define MAXLEN 30
#define MAXFOD 6
#define eror 1
#define ok 0
#pragma comment ( lib, "Winmm.lib" )
enum direction
{left,up,right,down
int pos[MAXLEN][2];
int food[MAXFOD][2];
int LENFOD=0;
int LENGTH=0;
int MARK=0;
int HIGHESTM=0;
direction DIT;
int snake();
int drawLine();
int init();
int controlfood();
int saveMark();
boolean isdead();
boolean iswin();
int countmark();
void main()
{int i=0,count=1;srand((unsigned)time(0));initgraph(600,900);setcolor(YELLOW);setfont( 30, 0,"楷体");mciSendString( "open ./source/skycity.mp3 alias skycity", 0, 0, 0 );mciSendString( "play skycity repeat ", 0, 0, 0 );
start:cleardevice();init();/*for(i=0;i&LENGTH;i++)printf("\n%d %d",pos[i][0],pos[i][1]);printf("\n");pos[0][1] -= 1;for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}closegraph();for(i=0;i&LENGTH;i++)printf("\n%d %d",pos[i][0],pos[i][1]);Sleep(50000);*/BeginBatchDraw();drawLine();
snake();FlushBatchDraw();while(true){if(kbhit()){switch(getch()){case 27:saveMark();closegraph();exit(ok);case 72:case 'w':case 'W':if(DIT!=down){DIT=for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}pos[0][1] -= 1;}case 80:case 's':case 'S':if(DIT!=up){DIT=for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}pos[0][1] += 1;}case 75:case 'a':case 'A':if(DIT!=right){DIT=for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}pos[0][0] -= 1;}case 77:case 'd':case 'D':if(DIT!=left){DIT=for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}pos[0][0] += 1;}}cleardevice();controlfood();drawLine();countmark();snake();count=1;FlushBatchDraw();}if(LENGTH&10){if(count==20){count=0;}}else if(LENGTH&15&&LENGTH&9){if(count==15)count=0;}else if(LENGTH&20&&LENGTH&14){if(count==10)count=0;}else{if(count==5)count=0;}if(count==0){for(i=LENGTH-1;i&0;i--){pos[i][0]=pos[i-1][0];pos[i][1]=pos[i-1][1];}switch(DIT){case up:pos[0][1] -= 1;case down:pos[0][1] += 1;case left:pos[0][0] -= 1;case right:pos[0][0] += 1;}cleardevice();controlfood();drawLine();countmark();snake();FlushBatchDraw(
);}if(isdead()){mciSendString( "play Lose ", 0, 0, 0 );outtextxy(240,275,"LOSSING!");FlushBatchDraw();while(true){if(kbhit()){switch(getch()){case 13:mciSendString( "close Lose ", 0, 0, 0 );mciSendString( "close win ", 0, 0, 0 );case 27:mciSendString( "close skycity ", 0, 0, 0 );closegraph();exit(ok);}}}}if(iswin()){mciSendString( "play win ", 0, 0, 0 );outtextxy(240,275,"WINNING!");FlushBatchDraw();while(true){if(kbhit()){switch(getch()){case 13:mciSendString( "close Lose ", 0, 0, 0 );mciSendString( "close win ", 0, 0, 0 );case 27:mciSendString( "close skycity ", 0, 0, 0 );closegraph();exit(ok);}}}}count++;Sleep(20);}
int snake()
{int i=0,j=0;setfillcolor(YELLOW);for(i=0;i&LENGTH;i++)solidcircle(pos[i][0]*20+10,pos[i][1]*20+10,10);setfillcolor(RED);i=0;if(DIT==left){solidcircle(pos[i][0]*20+5,pos[i][1]*20+5,3);solidcircle(pos[i][0]*20+5,pos[i][1]*20+15,3);}else if(DIT==right){solidcircle(pos[i][0]*20+15,pos[i][1]*20+5,3);solidcircle(pos[i][0]*20+15,pos[i][1]*20+15,3);}else if(DIT==down){solidcircle(pos[i][0]*20+5,pos[i][1]*20+15,3);solidcircle(pos[i][0]*20+15,pos[i][1]*20+15,3);}else{solidcircle(pos[i][0]*20+5,pos[i][1]*20+5,3);solidcircle(pos[i][0]*20+15,pos[i][1]*20+5,3);}setfillcolor(GREEN);//setfont( 18, 0,"楷体");for(i=0;i&LENFOD;i++){ solidcircle(food[i][0]*20+10,food[i][1]*20+10,7);/*j=rand()%2;if(j==0){outtextxy(food[i][0]*20+1,food[i][1]*20+1,"");}else if(j==1){outtextxy(food[i][0]*20+1,food[i][1]*20+1,"");}else{outtextxy(food[i][0]*20+1,food[i][1]*20+1,"");}*/}//setfont( 30, 0,"楷体");//solidcircle(food[i][0]*20+10,food[i][1]*20+10,7);setfillcolor(GREEN);
int drawLine()
{for(i=20;i&600;i+=20){line(0,i,600,i);line(i,0,i,600);}line(0,i,600,i);line(0,i+5,600,i+5);
int init()
{int i,j,k,l;FILE *mciSendString( "open ./source/Lose.mp3 alias Lose", 0, 0, 0 );mciSendString( "open ./source/win.mp3 alias win", 0, 0, 0 );LENGTH=0;LENFOD=0;MARK=0;if((fp=fopen("highestscore.txt","r"))==NULL){printf("File open eror!\n");exit(eror);}else{fscanf(fp,"%d",&HIGHESTM);if(fclose(fp)){printf("file close eror\n");exit(eror);}}setlinecolor(GREEN);setfillcolor(YELLOW);i=rand()%10+10;j=rand()%10+10;k=rand()%4;
pos[0][0] =pos[0][1] =if(k==0){for(i=1;i&5;i++){pos[i][1]=pos[i-1][1]+1;pos[i][0]=pos[i-1][0];DIT=}}else if(k==1){for(i=1;i&5;i++){pos[i][0]=pos[i-1][0]-1;pos[i][1]=pos[i-1][1];DIT=}}else if(k==2){for(i=1;i&5;i++){pos[i][1]=pos[i-1][1]-1;pos[i][0]=pos[i-1][0];DIT=}}else{for(i=1;i&5;i++){pos[i][0]=pos[i-1][0]+1;pos[i][1]=pos[i-1][1];DIT=}}LENGTH=5;k=rand()%4+1;for(l=0;l&k;l++)
{i=rand()%30;
j=rand()%30;food[LENFOD][0]=i;food[LENFOD++][1]=j;for(int m=0;m&LENGTH;m++)if(i==pos[m][0]&&j==pos[m][1]){l--;LENFOD--;}}
int controlfood()
{int i=0,j,k,l;for(i=0;i&LENFOD;i++){if(pos[0][0]==food[i][0]&&pos[0][1]==food[i][1]){if(LENGTH&10){MARK+=5;}else if(LENGTH&15){MARK+=10;}else if(LENGTH&20){MARK+=15;}else if(LENGTH&25){MARK+=20;}else{MARK+=25;}}}if(i&LENFOD){for(j=i;j&LENFOD-1;j++){food[j][0]=food[j+1][0];food[j][1]=food[j+1][1];}LENFOD--;LENGTH++;pos[LENGTH-1][0]=pos[LENGTH-2][0]*2-pos[LENGTH-3][0];pos[LENGTH-1][1]=pos[LENGTH-2][1]*2-pos[LENGTH-3][1];}if(LENFOD&2){k=rand()%4+1;for(l=0;l&k;l++)
{i=rand()%30;j=rand()%30;food[LENFOD][0]=i;food[LENFOD++][1]=j;for(int m=0;m&LENGTH;m++)if(i==pos[m][0]&&j==pos[m][1]){l--;LENFOD--;}}}
boolean isdead()
{if(pos[0][0]&0||pos[0][0]&30||pos[0][1]&0||pos[0][1]&30){saveMark();}for(i=3;i&LENGTH;i++)if(pos[0][0]==pos[i][0]&&pos[0][1]==pos[i][1])
boolean iswin()
{if(LENGTH==MAXLEN&&!isdead()){saveMark();}else
int countmark()
{char num[10];sprintf(num, "%d", HIGHESTM);outtextxy(60,610,"Highest:");outtextxy(200,610,num);outtextxy(350,610,"YouScore:");sprintf(num, "%d", MARK);outtextxy(490,610,num);
int saveMark()
{FILE *if(MARK&HIGHESTM){if((fp=fopen("highestscore.txt","w"))==NULL){printf("File open eror!\n");exit(eror);}else{fprintf(fp,"%d",MARK);if(fclose(fp)){printf("file close eror\n");exit(eror);}}}
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!欢迎访问C语言网www.dotcpp.com
比赛栏每月有奖月赛!举办比赛联系QQ:问题反馈、粉丝交流
蓝桥杯训练群:
申请群时请备注排名里的昵称C语言研究中心 为您提供有图、有料、解渴的C语言专题! 欢迎讨论!
今天笔者为大家展示C语言写的贪吃蛇游戏,让大家玩一玩自己写的游戏~ 是纯C语言哦~VC6.0开发 无问题
首先,开始界面:
游戏界面如下:
代码如下:
笔者VC6.0下编写,测试无问题,可复制代码直接到VC6源文件下,后缀为.c文件 可以编译通过运行~
#include&stdio.h&
#include&time.h&
#include&windows.h&
#include&stdlib.h&
#define U 1
#define D 2
#define L 3
#define R 4 //蛇的状态,U:上 ;D:下;L:左 R:右
typedef struct SNAKE //蛇身的一个节点
struct SNAKE *
//全局变量//
int score=0,add=10;//总得分与每次吃食物得分。
int status,sleeptime=200;//每次运行的时间间隔
snake *head, *//蛇头指针,食物指针
snake *q;//遍历蛇的时候用到的指针
int endgamestatus=0; //游戏结束的情况,1:撞到墙;2:咬到自己;3:主动退出游戏。
//声明全部函数//
void Pos();
void creatMap();
void initsnake();
int biteself();
void createfood();
void cantcrosswall();
void snakemove();
void pause();
void gamecircle();
void welcometogame();
void endgame();
void gamestart();
void Pos(int x,int y)//设置光标位置
hOutput=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hOutput,pos);
void creatMap()//创建地图
for(i=0;i&58;i+=2)//打印上下边框
printf(&■&);
Pos(i,26);
printf(&■&);
for(i=1;i&26;i++)//打印左右边框
printf(&■&);
Pos(56,i);
printf(&■&);
void initsnake()//初始化蛇身
tail=(snake*)malloc(sizeof(snake));//从蛇尾开始,头插法,以x,y设定开始的位置//
tail-&x=24;
tail-&y=5;
tail-&next=NULL;
for(i=1;i&=4;i++)
head=(snake*)malloc(sizeof(snake));
head-&next=
head-&x=24+2*i;
head-&y=5;
while(tail!=NULL)//从头到为,输出蛇身
Pos(tail-&x,tail-&y);
printf(&■&);
tail=tail-&
int biteself()//判断是否咬到了自己
self=head-&
while(self!=NULL)
if(self-&x==head-&x && self-&y==head-&y)
self=self-&
void createfood()//随机出现食物
snake *food_1;
srand((unsigned)time(NULL));
food_1=(snake*)malloc(sizeof(snake));
while((food_1-&x%2)!=0) //保证其为偶数,使得食物能与蛇头对其
food_1-&x=rand()%52+2;
food_1-&y=rand()%24+1;
while(q-&next==NULL)
if(q-&x==food_1-&x && q-&y==food_1-&y) //判断蛇身是否与食物重合
free(food_1);
createfood();
Pos(food_1-&x,food_1-&y);
food=food_1;
printf(&■&);
void cantcrosswall()//不能穿墙
if(head-&x==0 || head-&x==56 ||head-&y==0 || head-&y==26)
endgamestatus=1;
endgame();
void snakemove()//蛇前进,上U,下D,左L,右R
cantcrosswall();
nexthead=(snake*)malloc(sizeof(snake));
if(status==U)
nexthead-&x=head-&x;
nexthead-&y=head-&y-1;
if(nexthead-&x==food-&x && nexthead-&y==food-&y)//如果下一个有食物//
nexthead-&next=
while(q!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
score=score+
createfood();
else //如果没有食物//
nexthead-&next=
while(q-&next-&next!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
Pos(q-&next-&x,q-&next-&y);
printf(& &);
free(q-&next);
q-&next=NULL;
if(status==D)
nexthead-&x=head-&x;
nexthead-&y=head-&y+1;
if(nexthead-&x==food-&x && nexthead-&y==food-&y) //有食物
nexthead-&next=
while(q!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
score=score+
createfood();
else //没有食物
nexthead-&next=
while(q-&next-&next!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
Pos(q-&next-&x,q-&next-&y);
printf(& &);
free(q-&next);
q-&next=NULL;
if(status==L)
nexthead-&x=head-&x-2;
nexthead-&y=head-&y;
if(nexthead-&x==food-&x && nexthead-&y==food-&y)//有食物
nexthead-&next=
while(q!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
score=score+
createfood();
else //没有食物
nexthead-&next=
while(q-&next-&next!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
Pos(q-&next-&x,q-&next-&y);
printf(& &);
free(q-&next);
q-&next=NULL;
if(status==R)
nexthead-&x=head-&x+2;
nexthead-&y=head-&y;
if(nexthead-&x==food-&x && nexthead-&y==food-&y)//有食物
nexthead-&next=
while(q!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
score=score+
createfood();
else //没有食物
nexthead-&next=
while(q-&next-&next!=NULL)
Pos(q-&x,q-&y);
printf(&■&);
Pos(q-&next-&x,q-&next-&y);
printf(& &);
free(q-&next);
q-&next=NULL;
if(biteself()==1) //判断是否会咬到自己
endgamestatus=2;
endgame();
void pause()//暂停
Sleep(300);
if(GetAsyncKeyState(VK_SPACE))
void gamecircle()//控制游戏
Pos(64,15);
printf(&不能穿墙,不能咬到自己\n&);
Pos(64,16);
printf(&用↑.↓.←.→分别控制蛇的移动.&);
Pos(64,17);
printf(&F1 为加速,F2 为减速\n&);
Pos(64,18);
printf(&ESC :退出游戏.space:暂停游戏.&);
Pos(64,20);
printf(&c语言研究中心 www.dotcpp.com&);
Pos(64,10);
printf(&得分:%d &,score);
Pos(64,11);
printf(&每个食物得分:%d分&,add);
if(GetAsyncKeyState(VK_UP) && status!=D)
else if(GetAsyncKeyState(VK_DOWN) && status!=U)
else if(GetAsyncKeyState(VK_LEFT)&& status!=R)
else if(GetAsyncKeyState(VK_RIGHT)&& status!=L)
else if(GetAsyncKeyState(VK_SPACE))
else if(GetAsyncKeyState(VK_ESCAPE))
endgamestatus=3;
else if(GetAsyncKeyState(VK_F1))
if(sleeptime&=50)
sleeptime=sleeptime-30;
add=add+2;
if(sleeptime==320)
add=2;//防止减到1之后再加回来有错
else if(GetAsyncKeyState(VK_F2))
if(sleeptime&350)
sleeptime=sleeptime+30;
add=add-2;
if(sleeptime==350)
add=1; //保证最低分为1
Sleep(sleeptime);
snakemove();
void welcometogame()//开始界面
Pos(40,12);
system(&title c语言研究中心 www.dotcpp.com&);
printf(&欢迎来到贪食蛇游戏!&);
Pos(40,25);
system(&pause&);
system(&cls&);
Pos(25,12);
printf(&用↑.↓.←.→分别控制蛇的移动, F1 为加速,2 为减速\n&);
Pos(25,13);
printf(&加速将能得到更高的分数。\n&);
system(&pause&);
system(&cls&);
void endgame()//结束游戏
system(&cls&);
Pos(24,12);
if(endgamestatus==1)
printf(&对不起,您撞到墙了。游戏结束.&);
else if(endgamestatus==2)
printf(&对不起,您咬到自己了。游戏结束.&);
else if(endgamestatus==3)
printf(&您的已经结束了游戏。&);
Pos(24,13);
printf(&您的得分是%d\n&,score);
void gamestart()//游戏初始化
system(&mode con cols=100 lines=30&);
welcometogame();
creatMap();
initsnake();
createfood();
int main()
gamestart();
gamecircle();
endgame();
(www.dotcpp.com)
C语言网, 版权所有丨如未注明 , 均为原创丨本网站采用协议进行授权 , 转载请注明!}

我要回帖

更多关于 贪吃蛇游戏 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信