C语言贪吃蛇小程序

合集下载

C语言贪吃蛇程序设计说明书

C语言贪吃蛇程序设计说明书

C语言贪吃蛇程序设计说明书题目:贪吃蛇游戏学校: 系别: 专业班级: 姓名: 学号: 指导老师: 日期:一、设计题目:贪吃蛇是一款经典的休闲游戏,一条蛇在密闭的围墙内,随机出现一个食物,通过控制方向键操作小蛇不停的朝着食物前进,直到吃掉食物。

每吃一个食物,小蛇都会长长一截,随之难度增大;当小蛇头撞到墙或自己时,小蛇死亡。

二、功能设计:本游戏要求实现以下几个功能:(1) 用上、下、左、右键控制游戏区蛇的运动方向,使之吃食而使身体变长;(2) 用户可以调节蛇的运行速度来选择不同的难度;(3) 游戏分多个难度级别;(4) 用户可自选颜色;(5) 记录成绩前五名的游戏玩家;(6) 增加背景音乐;(7) 提高障碍物和游戏级别。

三、程序模块图:贪吃蛇游戏初画控设帮始图制置助模模模模化块块块块墙蛇食移食死变成等音体身物动物亡长绩级效2四、算法流程图:开始初始化界面和蛇身放置食物获取按键开始运动碰到边界是否否蛇吃到食是蛇长大蛇死亡是继续否结束3五、函数原型与功能 1.主函数:void main()启动程序,触动其他函数。

2.初始化:void init ()设置背景框大小、蛇体初始值,随机产生食物。

3.随机产生食物:void setfoodcrd()设置食物生成坐标,0表示食物被吃。

4.画食物:void showfood()用矩形框来画食物5.画蛇:void showsnake()根据蛇的坐标和节数,循环用矩形框来画蛇。

6.蛇移动:void snakemove() 根据按键,重设坐标7.改变蛇的方向:void changeskdir()响应用户的运动方向8.判断蛇是否死亡:void judgeslod判断蛇是否碰到自己或墙。

9.判断蛇是否吃到食物:void judgefood()判断是否吃到食物,吃食后变0,蛇增长一节。

10.结束游戏:void gameover()结束话语,并执行下一步。

六、基本代码#include<graphics.h> #include<conio.h>#include<stdio.h>#pragma comment(lib,"Winmm.lib")#include "MyTimer.h" #define SIZEMAX 100 /*蛇最大长度*/ #define SPEED 100 /*初始速度*/ #define len 20 /*蛇宽度*/#define lm 10 /*蛇每次移动距离*/ #define initlen 600 /*初始化窗口正方形的长度*/ #define Min_snakelen 2 /*蛇的最小长度*/typedef struct {int x,y;}DIR;int snakelen=Min_snakelen; /*蛇的长度*/4int isfood=1; /*食物状态*/ int isover=0; /*游戏状态*/int ispause=1; /*暂停状态*/int ismusic=1; /*音乐播放状态*/ char dir; /*记录蛇运动的方向*/ char c='d';DIR snake[500],food; /*定义蛇节点和食物的类型*/ int speed=SPEED;void drawmap() /*画地图函数*/ {IMAGE img;char str[10];loadimage(&img,"贪吃蛇.jpg"); /*游戏界面*/putimage(0,0,&img);loadimage(&img,"7.jpg"); /*侧栏提示*/putimage(600,0,&img);sprintf(str,"%d",snakelen);setfont(30,0,"宋体");setbkmode(TRANSPARENT);outtextxy(620,10,"操作说明:");setfont(20,0,"宋体");outtextxy(615,50,"awsd控制方向键");outtextxy(615,80,"p键暂停");outtextxy(615,110,"o键继续");outtextxy(615,200,"esc键退出");outtextxy(615,140,"l键暂停音乐");outtextxy(615,170,"k键继续播放");outtextxy(730,250,str);outtextxy(620,250,"蛇当前长度");}void init() /*初始化蛇函数*/ {int i;IMAGE img;snake[0].x=9*len+lm;snake[0].y=4*len+lm;loadimage(&img,"1.jpg");putimage(snake[0].x-lm,snake[0].y-lm,&img); for(i=1;i<snakelen;i++){snake[i].x=len*(9-i)+lm;snake[i].y=len*4+lm;5loadimage(&img, "2.jpg");putimage(snake[i].x-lm,snake[i].y-lm, &img); }}void showsnake() /*画蛇函数*/ {int i;IMAGE img;loadimage(&img, "1.jpg");putimage(snake[0].x-lm,snake[0].y-lm , &img);loadimage(&img, "2.jpg");for(i=1;i<snakelen;i++)putimage(snake[i].x-lm,snake[i].y-lm, &img); }void snakemove() /*画动蛇函数*/ {int i;int mx=snake[0].x;int my=snake[0].y;switch(dir){case 'a':mx-=len;break;case 'd':mx+=len;break;case 'w':my-=len;break;case 's':my+=len;break;default:break;}for(i=snakelen-1;i>=0;i--){snake[i+1].x=snake[i].x;snake[i+1].y=snake[i].y;}snake[0].x=mx;snake[0].y=my;showsnake();}int ceshiover() /*检测游戏结束函数*/ {int i;if(snake[0].x<0||snake[0].x>30*len-lm||snake[0].y<0||snake[0].y>30*len-lm)return 1;for(i=1;i<snakelen;i++)6{if(snake[0].x==snake[i].x&&snake[0].y==snake[i].y) return 1;}return 0;}int foodinsnake() /*检测食物是否在蛇上函数*/ {for(int i=0;i<snakelen;i++)if(food.x==snake[i].x&&food.y==snake[i].y)return 1;elsereturn 0;}void showfood() /*画食物函数*/{IMAGE img;do{food.x=(rand()%30)*len+lm;food.y=(rand()%30)*len+lm;}while(foodinsnake());loadimage(&img, "3.jpg");putimage(food.x-lm,food.y-lm , &img);isfood=0;}void kmusic(){if(ismusic==0)mciSendString("pause mymusic",NULL,0,NULL);if(ismusic==1)mciSendString("resume mymusic",NULL,0,NULL);}void playbkmusic() /*播放背景音乐函数*/{mciSendString("open 超级玛丽.mp3 alias mymusic", NULL, 0, NULL); mciSendString("play mymusic repeat", NULL, 0, NULL);}void playgame() /*玩游戏函数*/{c='d'; //蛇开始向右移动isover=0;7snakelen=Min_snakelen;dir='d';IMAGE img;MyTimer t; //定义精确延时对象int T=200; // 延长时间drawmap(); //画游戏地图init(); //画小蛇初始位置while(!isover){if(ispause){snakemove();FlushBatchDraw(); //批量绘图EndBatchDraw(); //结束批量绘图if(snake[0].x==food.x&&snake[0].y==food.y){ snakelen++;isfood=1;}if(isfood)showfood();if(snakelen<35)T=200-3*snakelen;t.Sleep(T);BeginBatchDraw(); // 开始批量绘图模式,防止闪烁问题drawmap();loadimage(&img, "3.jpg"); // 加载食物图片putimage(food.x-lm,food.y-lm , &img);};//按键控制if(kbhit())c=getch();switch(c){case 'a':if(dir!='d'){dir=c;}break;case 'd':if(dir!='a'){dir=c;}break;case 'w':if(dir!='s'){8dir=c;}break;case 's':if(dir!='w'){dir=c;}break;case 27: exit(0); break; //游戏退出case 'p': ispause=0;break; //p暂停case 'o': ispause=1;break; //o继续游戏case 'l': ismusic=0;break; //l暂停音乐case 'k': ismusic=1;break; //k继续播放default:break;}kmusic(); //音乐控制播放//判断游戏结束if(ceshiover())isover=1;//判断是否重新再来HWND wnd = GetHWnd(); //获取窗口句柄if(isover)if (MessageBox(wnd, "游戏结束。

C语言小游戏源代码《贪吃蛇》

C语言小游戏源代码《贪吃蛇》
void main(void){/*主函数体,调用以下四个函数*/ init(); setbkcolor(7); drawk(); gameplay(); close(); }
void init(void){/*构建图形驱动函数*/ int gd=DETECT,gm; initgraph(&gd,&gm,""); cleardevice(); }
欢迎您阅读该资料希望该资料能给您的学习和生活带来帮助如果您还了解更多的相关知识也欢迎您分享出来让我们大家能共同进步共同成长
C 语言小游戏源代码《贪吃பைடு நூலகம்》
#define N 200/*定义全局常量*/ #define m 25 #include <graphics.h> #include <math.h> #include <stdlib.h> #include <dos.h> #define LEFT 0x4b00 #define RIGHT 0x4d00 #define DOWN 0x5000 #define UP 0x4800 #define Esc 0x011b int i,j,key,k; struct Food/*构造食物结构体*/ { int x; int y; int yes; }food; struct Goods/*构造宝贝结构体*/ { int x; int y; int yes; }goods; struct Block/*构造障碍物结构体*/ { int x[m]; int y[m]; int yes; }block; struct Snake{/*构造蛇结构体*/ int x[N]; int y[N]; int node; int direction; int life; }snake; struct Game/*构建游戏级别参数体*/ { int score; int level; int speed;

C语言程序设计:贪吃蛇程序源代码用TC2.0编译

C语言程序设计:贪吃蛇程序源代码用TC2.0编译

C语言程序设计:贪吃蛇程序源代码用TC2.0编译本程序为贪吃蛇游戏,想必大家都玩过这个游戏,程序源代码用TC2.0编译通过,需要图形驱动文件的支持,在TC2.0的集成环境中有.本程序利用数据结构中的链表,来将蛇身连接,同时当蛇吃到一定数目的东西时会自动升级,及移动速度会加快,程序会时刻将一些信息显示在屏幕上,包括所得分数,要吃多少东西才能升级,并且游戏者可以自己手动选择游戏级别,级别越高,蛇的移动速度越快.另外,此游戏可能与CPU的速度有关系.源代码如下:******************************************************************************* ***/*******************************COMMENTS**********************************/ /* snake_game.c*//* it is a game for entermainment.*//* in the begin,there is only a snake head,and it will have to eat food *//* to become stronger,and it eat a piece of food each time,it will *//* lengthen it's body,with the number of food the snake eats going up,it *//* will become long more and more,and the score will goes up also. *//* there is always useful information during the game process. *//* if the path by which the snake goes to eat food is the shortest,the *//* score will add up a double.*//**//* enjoy yourself,and any problem,contact <blldw@> *//*************************************************************************//* all head file that will be used */#include<stdio.h>#include<time.h>#include<graphics.h>#include<stdlib.h>#include<ctype.h>#include<string.h>/* useful MACRO */#define FOOD_SIZE 8#define SCALE 8#define UP_KEY 0x4800#define DOWN_KEY 0x5000#define LEFT_KEY 0x4b00#define RIGHT_KEY 0x4d00#define MOVE_UP 1#define MOVE_LEFT 2#define MOVE_DOWN 3#define MOVE_RIGHT 4#define INV ALID_DIRECTION 0#define QUIT_KEYC 0x1051#define QUIT_KEY 0x1071#define SELECT_KEYC 0x1f53#define SELECT_KEY 0x1f73#define PAUSE_KEYC 0x1950#define PAUSE_KEY 0x1970#define DEFAULT_LEVEL 1#define HELP_COLOR WHITE#define WELCOME_COLOR WHITE#define DEFAULT_COLOR GREEN/* define the macro as follows to improve the game in future */#define FOOD_COLOR YELLOW#define SNAKE_HEAD_COLOR RED#define DEFAULT_SNAKE_COLOR YELLOW#define EXIT_COLOR WHITE#define SCORE_COLOR YELLOW/* sturcture for snake body mainly ,and food also */typedef struct food_infor *FOOD_INFOR_PTR;typedef struct food_infor{int posx; /* position for each piece of snake body */int posy;int next_move; /* next move direction */int pre_move; /* previous move direction,seems unuseful */int beEaten; /* xidentifier for snake body or food */FOOD_INFOR_PTR next; /* pointer to next piece of snake body */ FOOD_INFOR_PTR pre; /* pointer to previous piece of snake body */ }FOOD_INFOR;/* structure for snake head */typedef struct _snake_head{int posx;int posy;int next_move;int pre_move;int eatenC; /* number of food that have been eaten */int hop; /* number of steps to eat food */FOOD_INFOR_PTR next; /* pointer to the first piece of eaten food */ }SNAKE_HEAD;/* the left-up corner and right-down corner */typedef struct point{int x;int y;}POINT;/* standards for game speed*//* before level 5,the time interval is level_b[level - 1] / 10,and after */ /* level 5,the time interval is 1.00 / level_b[level - 1] */float level_b[9] = {10.0,8.0,6.0,3.0,1.0,20.0,40.0,160.0,640.0};/* available varary */SNAKE_HEAD snake_head;FOOD_INFOR *current; /* always point to food */POINT border_LT,border_RB;int driver,mode; /* for graphics driver */int maxx,maxy; /* max length and width of screen,in pixel */int eaten; /* identifier if the food is eaten */int score = 0; /* total score */int level = DEFAULT_LEVEL; /* level or speed */float interval; /* based on speed */int snake_color = DEFAULT_SNAKE_COLOR; /* snake body color */ int hopcount = 0; /* the shortest number of steps for snake *//* to eat food *//* all sub function */void init_graphics();void generate_first_step();int judge_death();int willeatfood();void generate_food();void addonefood();void redrawsnake();void show_all();void sort_all();void change_direction();void help();void show_score(int);void change_level();void show_level();void release(SNAKE_HEAD);int can_promote();void win();void show_infor_to_level();void show_eaten();void calculate_hop();/* main function or entry */void main(){char str[50] = "YOU LOSE!!!"; /* fail information */ clock_t start;int querykey;int tempx,tempy;/* if fail and want to resume game,go here */retry:init_graphics();show_all(); /* show wall */generate_first_step(); /* generate food and snake head */ show_score(score); /* show score to player */eaten = 0;/* begin to play game */while(1){if(judge_death() == 1) /* die */break;if(willeatfood() == 1){eaten = 1;addonefood();snake_head.hop ++;if(snake_head.hop == hopcount)score += level * 2;elsescore += level;can_promote();show_score(score);}sort_all();redrawsnake();snake_head.hop ++;show_infor_to_level();show_eaten();show_all();change_direction();if(eaten == 1){generate_food();calculate_hop();snake_head.hop = 0;eaten = 0;}if(level <= 5)interval = level_b[level - 1] / 10.0;elseinterval = 1.00 / level_b[level - 1];start = clock();while((clock() - start) / CLK_TCK < interval) {querykey = bioskey(1);if(querykey != 0){switch(bioskey(0)){case UP_KEY:snake_head.next_move = MOVE_UP;break;case LEFT_KEY:snake_head.next_move = MOVE_LEFT;break;case DOWN_KEY:snake_head.next_move = MOVE_DOWN;break;case RIGHT_KEY:snake_head.next_move = MOVE_RIGHT;break;case SELECT_KEYC:case SELECT_KEY:change_level();score = 0;show_score(score);show_level();break;case PAUSE_KEYC:case PAUSE_KEY:while(!bioskey(1));break;case QUIT_KEYC:case QUIT_KEY:goto exit_game;default:break;}}}}settextstyle(DEFAULT_FONT,0,2);setcolor(EXIT_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y + (border_RB.y - border_LT.y) / 2;outtextxy(tempx,tempy,str);strcpy(str,"press <R/r> to retry,or ENTER key to exit");tempy += textheight(str) * 2;settextstyle(DEFAULT_FONT,0,1);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; outtextxy(tempx,tempy,str);select:while(!bioskey(1));querykey = bioskey(0);if((querykey == 0x1372) || (querykey == 0x1352)){level = DEFAULT_LEVEL;score = 0;release(snake_head);closegraph();goto retry;}if(querykey != 0x1c0d)goto select;closegraph();return;exit_game:release(snake_head);closegraph();}/* sub function show_eaten() *//* function: to show the total number piece of food *//* that have been eaten by snake any time */void show_eaten(){int tempx,tempy;int size;void *buf;char str[15];settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);sprintf(str,"eaten:%d",snake_head.eatenC);tempx = 0;tempy = border_LT.y + textheight(str) * 6;size = imagesize(tempx,tempy,tempx + textwidth(str) + textwidth("A"), tempy + textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str) + textwidth("A"), tempy + textheight(str),buf);putimage(tempx,tempy,buf,XOR_PUT);outtextxy(tempx,tempy,str);free(buf);}/* sub function: show_infor_to_level *//* function:show information to player that how many pieces *//* of food have to been eaten to get to next level *//* ,and this is not related with score,but only *//* eaten number of food*//**//* level standard:let highlevel stand for the number of *//* pieces of food that can be put int the *//* vertical direction of play area,and *//* before level 5,as long as the snake eat *//* a quarter of highlevel,it will go to next *//* level,and between level 5 and 7,as long *//* as the snake eat one thirds of highlevel, *//* it will go to next level,and between *//* level 8 and 9,the snake will go to next *//* level as long as it eat half of highlevel *//* note: level is between 1 to 9. */void show_infor_to_level(){int highlevel;int size;int tempx,tempy;int toeat;void *buf;char str[50];highlevel = (border_RB.y - border_LT.y) / SCALE;switch(level){case 1:case 2:case 3:case 4:toeat = (highlevel / 4) * level - snake_head.eatenC;break;case 5:case 6:case 7:toeat = (highlevel + highlevel / 3 * (level - 4)) - snake_head.eatenC; break;case 8:case 9:toeat = (highlevel * 2 + highlevel / 2 * (level - 7)) -snake_head.eatenC;break;default:break;}settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);if(snake_head.next == NULL){sprintf(str,"next level");tempx = 0;tempy = border_LT.y + textheight(str) * 2;outtextxy(tempx,tempy,str);}if(toeat < 0)toeat = 0;sprintf(str,"%d:%d",level + 1,toeat);tempx = 0;tempy = border_LT.y + textheight(str) * 4;size = imagesize(tempx,tempy,tempx + textwidth(str) + textwidth("A"),tempy +textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str) + textwidth("A"),tempy +textheight(str),buf);putimage(tempx,tempy,buf,XOR_PUT);outtextxy(tempx,tempy,str);free(buf);}/* sub function: win() *//* function:if the player pass level 9,this function *//* will be called ,to show "YOU WIN information *//* and after a key is pressed,the game will go *//* on,but all is back to begin,excepte the *//* snake body length.*/void win(){char str[] = "YOU WIN";int tempx,tempy;settextstyle(DEFAULT_FONT,0,8);setcolor(WELCOME_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y + (border_RB.y - border_LT.y - textheight(str)) / 2;outtextxy(tempx,tempy,str);while(!bioskey(1));}/* sub function: can_promote() *//* function:see if the snake can go to next level on basis *//* of the snake length.*//**//* note:standards of promote level is instructed above */int can_promote(){/* compare SCORE with standard level score */int high_level;static int last_score = 0;high_level = (border_RB.y - border_LT.y) / SCALE;switch(level){case 1:case 2:case 3:case 4:if(snake_head.eatenC == (high_level / 4 * level))level ++;last_score = score;break;case 5:case 6:case 7:if(snake_head.eatenC == (high_level + high_level / 3 * (level - 4))) level ++;last_score = score;break;case 8:if(snake_head.eatenC == (high_level * 2 + high_level / 2 ))level ++;last_score = score;break;case 9:if(snake_head.eatenC == (high_level * 3)){win();score = 0;last_score = 0;level = DEFAULT_LEVEL;}break;default:break;}show_level();}/* sub function: calulate_hop() *//* function: calculate the shortest path from snake head to *//* the food it will eaten. */void calculate_hop(){hopcount = (snake_head.posx >= current->posx) ? ((snake_head.posx - current->posx) /SCALE) :((current->posx - snake_head.posx) / SCALE);hopcount += (snake_head.posy >= current->posy) ? ((snake_head.posy - current->posy) /SCALE) :((current->posy - snake_head.posy) / SCALE);}/* sub function: release()*//* function:free memory before exit game or restart */void release(SNAKE_HEAD snake_head){FOOD_INFOR_PTR traceon,last;traceon = snake_head.next;snake_head.eatenC = 0;snake_head.next = NULL;snake_head.hop = 0;while(traceon)if(traceon->next != NULL)traceon = traceon->next;elsebreak;while(traceon){last = traceon->pre;free(traceon);traceon = last;}}/* sub function: show_level()x *//* function:show level information to player anytime */void show_level(){char str[20];int size;void *buf;settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);sprintf(str,"Level:%d",level);size = imagesize(0,border_LT.y,textwidth(str),border_LT.y + textheight(str)); buf = malloc(size);getimage(0,border_LT.y,textwidth(str),border_LT.y + textheight(str),buf);putimage(0,border_LT.y,buf,XOR_PUT);free(buf);outtextxy(0,border_LT.y,str);}/* sub function: change_level() *//* function:if the play choose "select level <S/S>" item, *//* this function will be called */void change_level(){int c;int size;void *buf;int tempx,tempy;char str[] = "new level (1--9):";settextstyle(DEFAULT_FONT,0,1);setcolor(DEFAULT_COLOR);tempx = 0;tempy = border_LT.y - textheight("A") * 3 / 2;outtextxy(tempx,tempy,str);goon:while(!bioskey(1));c = bioskey(0);if((c == 0x1051) || (c == 0x1071))goto exit;if(isdigit(c&0x00ff))level = (c&0x00ff) - 48;elsegoto goon;exit:size = imagesize(tempx,tempy,tempx + textwidth(str),tempy + textheight(str)); buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str),tempy + textheight(str),buf); putimage(tempx,tempy,buf,XOR_PUT);free(buf);}/* sub function: show_score() *//* function:show score information to player anytime */void show_score(int count){int th;int size;char str[20];settextstyle(DEFAULT_FONT,0,2);setcolor(SCORE_COLOR);sprintf(str,"Score: %d",count);th = textheight("hello");if((count == 0) && (snake_head.next == NULL)){outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,str);}else{size = imagesize(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,border_LT.x + (border_RB.x - border_LT.x) / 4 +textwidth(str) + textwidth("100"),border_LT.y - 2 * th + th);buf = malloc(size);getimage(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th, border_LT.x + (border_RB.x - border_LT.x) / 4 + textwidth(str) +textwidth("100"),border_LT.y - 2 * th + th,buf);putimage(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,buf,XOR_PUT);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 4,border_LT.y - 2 * th,str);free(buf);}}/* sub function: help()*//* function: show help information at the beginning of game *//* and let player know how to play the game */void help(){int th;settextstyle(DEFAULT_FONT,0,1);setcolor(HELP_COLOR);th = textheight("hello");sprintf(str,"move left : %c",27);outtextxy(border_LT.x,border_RB.y,str);sprintf(str,"move up : %c",24);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y,str);sprintf(str,"move down : %c",25);outtextxy(border_LT.x,border_RB.y + th + 2,str);sprintf(str,"move right: %c",26);outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y + th + 2,str);outtextxy(border_LT.x,border_RB.y + th * 2 + 4,"quit <Q/q>");outtextxy(border_LT.x + textwidth("quit <Q/q>") * 3 / 2,border_RB.y + th * 2 + 4, "pause <P/p>");outtextxy(border_LT.x + (border_RB.x - border_LT.x) / 2,border_RB.y + th * 2 + 4,"select level <S/s>");}/* sub function: show_all()*//* function:redraw the play area,means show wall */void show_all(){int i,j;setcolor(DEFAULT_COLOR);/*for(i = border_LT.x; i <= border_RB.x; i += SCALE)for(j = border_LT.y; j <= border_RB.y; j += SCALE)rectangle(i,j,i + SCALE, j + SCALE);*/rectangle(border_LT.x,border_LT.y,border_RB.x,border_RB.y);}/* sub function: generate_food()*//* function:after the food is eaten by snake,the function will *//* be called to generate another food,and it will *//* ensure that the generated food shouldn't appeare *//* in the snake body.*/void generate_food(){FOOD_INFOR_PTR traceon;int tempx,tempy;generate:current->posx = random(border_RB.x - SCALE / 2);while((current->posx <= border_LT.x) || ((current->posx - border_LT.x) % SCALE == 0) || ((current->posx - border_LT.x) % SCALE % (SCALE / 2) != 0))current->posx ++;current->posy = random(border_RB.y - SCALE / 2);while((current->posy <= border_LT.y) || ((current->posy - border_LT.y) % SCALE == 0) || ((current->posy - border_LT.y) % SCALE % (SCALE / 2) != 0))current->posy ++;traceon = snake_head.next;while(traceon){if((traceon->posx == current->posx) && (traceon->posy == current->posy))goto generate;traceon = traceon->next;}if(current->posx - border_LT.x == SCALE / 2)current->posx += SCALE;if(border_RB.x - current->posx == SCALE / 2)current->posx -= SCALE;if(current->posy - border_LT.y == SCALE / 2)current->posy += SCALE;if(border_RB.y - current->posy == SCALE / 2)current->posy -= SCALE;setcolor(DEFAULT_COLOR);rectangle(current->posx - SCALE / 2,current->posy - SCALE / 2, current->posx + SCALE / 2,current->posy + SCALE / 2); setfillstyle(SOLID_FILL,YELLOW);floodfill(current->posx,current->posy,DEFAULT_COLOR);}/* sub function: init_graphics()*//* function:initialize the game interface */void init_graphics(){driver = DETECT;mode = 0;initgraph(&driver,&mode,"*.bgi");maxx = getmaxx();maxy = getmaxy();border_LT.x = maxx / SCALE;border_LT.y = maxy / SCALE;border_RB.x = maxx * (SCALE - 1) / SCALE;border_RB.y = maxy * (SCALE - 1) / SCALE;while((border_RB.x - border_LT.x) % FOOD_SIZE)(border_RB.x) ++;while((border_RB.y - border_LT.y) % FOOD_SIZE)(border_RB.y) ++;while((border_RB.y - border_LT.y) % ( 12 * SCALE))border_RB.y += SCALE;setcolor(DEFAULT_COLOR);rectangle(border_LT.x,border_LT.y,border_RB.x,border_RB.y);help();show_level();}/* sub function: generateX_first_step() *//* function:generate snake head and first food to prepare for *//* game to start,and this function will also initialize*//* the move direction of snake head,and show welcome *//* information to player.*/void generate_first_step(){char str[] = "welcome to snake game,press ENTER key to start";int size;int tempx,tempy;void *buf;randomize();/* generate snake head */snake_head.posx = random(border_RB.x - SCALE / 2);while((snake_head.posx <= border_LT.x) || ((snake_head.posx - border_LT.x) % SCALE == 0)||((snake_head.posx - border_LT.x) % SCALE % (SCALE / 2) != 0))snake_head.posx ++;snake_head.posy = random(border_RB.y - SCALE / 2);while((snake_head.posy <= border_LT.y) || ((snake_head.posy - border_LT.y) % SCALE == 0)||((snake_head.posy - border_LT.y) % SCALE % (SCALE / 2) != 0))snake_head.posy ++;setcolor(DEFAULT_COLOR);rectangle(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2,snake_head.posx + SCALE / 2,snake_head.posy + SCALE / 2);setfillstyle(SOLID_FILL,SNAKE_HEAD_COLOR);floodfill(snake_head.posx,snake_head.posy,DEFAULT_COLOR);/* generate first food */current = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));goon_generate:current->posx = random(border_RB.x - SCALE / 2);while((current->posx <= border_LT.x) || ((current->posx - border_LT.x) % SCALE == 0) || ((current->posx - border_LT.x) % SCALE % (SCALE / 2) != 0))current->posx ++;current->posy = random(border_RB.y - SCALE / 2);while((current->posy <= border_LT.y) || ((current->posy - border_LT.y) % SCALE == 0) || ((current->posy - border_LT.y) % SCALE % (SCALE / 2) != 0))current->posy ++;if((current->posx == snake_head.posx) && (current->posy == snake_head.posy))goto goon_generate;rectangle(current->posx - SCALE / 2,current->posy - SCALE / 2,current->posx + SCALE / 2,current->posy + SCALE / 2);setfillstyle(SOLID_FILL,FOOD_COLOR);floodfill(current->posx,current->posy,DEFAULT_COLOR);calculate_hop();snake_head.next = NULL;snake_head.eatenC = 0;snake_head.hop = 0;current->next = NULL;current->pre = NULL;current->beEaten = 0;current->next_move = INV ALID_DIRECTION;current->pre_move = INV ALID_DIRECTION;if(snake_head.posx == current->posx){if(snake_head.posy > current->posy)snake_head.next_move = MOVE_UP;elsesnake_head.next_move = MOVE_DOWN;}else{if(snake_head.posx < current->posx)snake_head.next_move = MOVE_RIGHT;elsesnake_head.next_move = MOVE_LEFT;}snake_head.pre_move = snake_head.next_move;settextstyle(DEFAULT_FONT,0,1);setcolor(WELCOME_COLOR);tempx = border_LT.x + (border_RB.x - border_LT.x - textwidth(str)) / 2; tempy = border_LT.y - textheight("A") * 6 / 2;outtextxy(tempx,tempy,str);size = imagesize(tempx,tempy,tempx + textwidth(str),tempy + textheight(str));buf = malloc(size);getimage(tempx,tempy,tempx + textwidth(str),tempy + textheight(str),buf);while(bioskey(0) != 0x1c0d);putimage(tempx,tempy,buf,XOR_PUT);free(buf);}/* sub function: judge_death()*//* function:judge if the snake will die because of incorrect *//* move,there are two things that will result *//* the snake to death:first,it run into the wall *//* ,and second,it run into its body.*/int judge_death(){/* return 1 means will die,and return 0 means will survive */int tempx,tempy;switch(snake_head.next_move){case MOVE_UP:tempx = snake_head.posx;tempy = snake_head.posy - SCALE;break;case MOVE_LEFT:tempx = snake_head.posx - SCALE;tempy = snake_head.posy;break;case MOVE_DOWN:tempx = snake_head.posx;tempy = snake_head.posy + SCALE;break;case MOVE_RIGHT:tempx = snake_head.posx + SCALE;tempy = snake_head.posy;break;default:break;}if((tempx < border_LT.x) || (tempx > border_RB.x) || (tempy < border_LT.y) || (tempy > border_RB.y))return 1;if(getpixel(tempx,tempy) == snake_color){FOOD_INFOR_PTR traceon;traceon = snake_head.next;while(traceon != NULL){if((traceon->posx == tempx) && (traceon->posy == tempy)) return 1;traceon = traceon->next;}}return 0; /* survive */}/* sub function: willeatfood() *//* function:judge if the sanke can eat food.the method like */ /* this:provided that the snake move a step based *//* on its next move direction,and if this place *//* have food,then the snake can eat food. */int willeatfood(){/* 1 means will eat food ,and 0 means won't eat food */int tempx,tempy;switch(snake_head.next_move){case MOVE_UP:tempx = snake_head.posx;tempy = snake_head.posy - SCALE;break;case MOVE_LEFT:tempx = snake_head.posx - SCALE;tempy = snake_head.posy;break;case MOVE_DOWN:tempx = snake_head.posx;tempy = snake_head.posy + SCALE;break;case MOVE_RIGHT:tempx = snake_head.posx + SCALE;tempy = snake_head.posy;break;default:break;}if(getpixel(tempx,tempy) == FOOD_COLOR)return 1;return 0;}/* sub function: addonefood() *//* function: this function will lengthen the snake body *//* this function is important because it will *//* not only locate memory for new snake body, *//* but also handle the relationship of pointer*//* between the new snake body and its previous*//* snake body.*/void addonefood(){FOOD_INFOR_PTR traceon;snake_head.eatenC ++ ;traceon = snake_head.next;if(snake_head.next == NULL) /* haven't eaten any food */{traceon = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));switch(snake_head.next_move){case MOVE_UP:traceon->posx = snake_head.posx;traceon->posy = snake_head.posy + SCALE;break;case MOVE_LEFT:traceon->posx = snake_head.posx + SCALE;traceon->posy = snake_head.posy;break;case MOVE_DOWN:traceon->posx = snake_head.posx;traceon->posy = snake_head.posy - SCALE;break;case MOVE_RIGHT:traceon->posx = snake_head.posx - SCALE;traceon->posy = snake_head.posy;break;default:break;}traceon->next_move = snake_head.next_move;traceon->pre_move = snake_head.next_move;traceon->next = NULL;traceon->pre = NULL;traceon->beEaten = 1;snake_head.next = traceon;}else{while(traceon){if(traceon->next != NULL)traceon = traceon->next;elsebreak;}traceon->next = (FOOD_INFOR_PTR)malloc(sizeof(FOOD_INFOR));traceon->next->next = NULL;traceon->next->pre = traceon;traceon = traceon->next;switch(traceon->pre->next_move){case MOVE_UP:traceon->posx = traceon->pre->posx;traceon->posy = traceon->pre->posy + SCALE;break;case MOVE_LEFT:traceon->posx = traceon->pre->posx + SCALE;traceon->posy = traceon->pre->posy;break;case MOVE_DOWN:traceon->posx = traceon->pre->posx;traceon->posy = traceon->pre->posy - SCALE;break;case MOVE_RIGHT:traceon->posx = traceon->pre->posx - SCALE;traceon->posy = traceon->pre->posy;break;default:break;}traceon->next_move = traceon->pre->next_move;traceon->pre_move = traceon->pre->next_move;traceon->beEaten = 1;}}/* sub function: sort_all()*//* function:this function will calculate the next position of snake *//* and it is assume the snake has move to next position,but*//* haven't appeared yet.*/void sort_all(){/* sort all food,include snake head,and virtual place */FOOD_INFOR_PTR traceon;void *buf;int size;size = imagesize(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2, snake_head.posx + SCALE / 2,snake_head.posy + SCALE /2);buf = malloc(size);getimage(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2, snake_head.posx + SCALE / 2,snake_head.posy + SCALE / 2,buf); putimage(snake_head.posx - SCALE / 2,snake_head.posy - SCALE / 2,buf,XOR_PUT);switch(snake_head.next_move){case MOVE_UP:snake_head.posy -= SCALE;break;case MOVE_LEFT:snake_head.posx -= SCALE;break;case MOVE_DOWN:snake_head.posy += SCALE;break;case MOVE_RIGHT:snake_head.posx += SCALE;break;default:break;}traceon = snake_head.next;while(traceon){getimage(traceon->posx - SCALE / 2,traceon->posy - SCALE / 2, traceon->posx + SCALE / 2,traceon->posy + SCALE / 2,buf); putimage(traceon->posx - SCALE / 2,traceon->posy - SCALE / 2, buf,XOR_PUT);switch(traceon->next_move){case MOVE_UP:traceon->posy -= SCALE;break;case MOVE_LEFT:traceon->posx -= SCALE;break;case MOVE_DOWN:traceon->posy += SCALE;break;case MOVE_RIGHT:traceon->posx += SCALE;break;default:break;}traceon = traceon->next;}free(buf);}/* sub function: redrawsnake()*//* function:the function will redraw the snake based on function*/ /* sort_all().*/void redrawsnake(){。

贪吃蛇 C语言代码

贪吃蛇 C语言代码
y=randno();
}
snake[x][y]=FOOD;
draw(snake);
/*---------------------------------------*/
/*--------控制的部分---------------------*/
while(judgeGO(snake))
}
if(x>0&&x<16&&y>0&&y<16)
{
if(a==0)
printf("█");
else printf("□");
return ;
}
}
void draw(int (*sna)[17])
draw(snake);
Sleep(100);
continue;
}
rightmove(snake);
draw(snake);
}
int randno()
{
srand(time(NULL)); //运用随机函数,取随机数,出现食物用
return rand()%15+1;
}
//判断游戏是否结束
bool judgeGO(int (*sna)[17])
{
int x,y,i=0,max=0,count=0;
while(!kbhit()&&key1!=77&&judgeGO(snake))
{
if(judgeF(snake,key))
{
draw(snake);
Sleep(100);

C语言贪吃蛇全部程序及说明Word版

C语言贪吃蛇全部程序及说明Word版

#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; //保存当前节点的方向, 0,1,2,3分别为左右上下}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); //延迟半秒(1000为1s),即每半秒刷新一次地图Button(); //先判断按键在移动Move();if(over) //自吃或碰墙即游戏结束{printf("\n**游戏结束**\n");printf("你的得分:%d\n",sum=10*(sum-1));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) //检查当前是否有键盘输入,若有则返回一个非0值,否则返回0 {while(kbhit() != 0) //可能存在多个按键,要全部取完,以最后一个为主key = getch(); //将按键从控制台中取出并保存到key中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 ] = '@';elseif(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(); //食物吃完了马上再产生一个食物}elseover = 1;}。

贪吃蛇的c语言源程序

贪吃蛇的c语言源程序

#include<stdio.h>#include<graphics.h>#include<stdlib.h>#include<dos.h>#include<bios.h>#include<time.h>#define NULL 0#define UP 4471#define LEFT 7777#define DOWN 8051#define RIGHT 8292#define PAUSE 6512#define ESC 283#define SNAKE_COLOR 4#define SNAKE_BOND_COLOR 2#define SNAKE_STYLE LTBKSLASH_FILL #define FOOD_STYLE CLOSE_DOT_FILL #define MAP_COLOR 8#define MAP_BOND_COLOR 6#define MAP_STYLE SOLID_FILLtypedef struct Snake_Node{int x,y;struct Snake_Node *next;}Snake_Node,*P_Snake_Node;struct{int x,y,color;}Food;struct{int dx;int dy;}Direct={0,1};static int speed=1,len=4,px,py;static P_Snake_Node Head;static P_Snake_Node Map;void paint_node(int,int,int,int,int);void Put_Food(int);void Put_Snake_Node(P_Snake_Node,int); void Init();void Grow_up(int,int);void Make_Map();void Auto_Make_Map();void Load_Game();void Auto_Start();int Snake_Dead();void GO_GO_GO();void Play_Game();void Exit_Save();void Failed();void main();void paint_node(int x,int y,int color1,int color2,int style){setfillstyle(SOLID_FILL,color2);bar(x*10,479-y*10,x*10+9,479-y*10-9);setfillstyle(style,color1);bar(x*10+1,479-y*10-1,x*10+9-1,479-y*10-9+1);setfillstyle(SOLID_FILL,15);}void Put_Food(int color){randomize();Food.x=random(46)+1;Food.y=random(46)+1;Food.color=color;paint_node(Food.x,Food.y,Food.color,Food.color,FOOD_STYLE);}void Put_Snake_Node(P_Snake_Node p,int flag){if(flag)paint_node(p->x,p->y,SNAKE_COLOR,SNAKE_BOND_COLOR,SNAKE_STYLE);elsepaint_node(p->x,p->y,getbkcolor(),getbkcolor(),SOLID_FILL);}void Init(){int gdrive=VGA,gmode=VGAHI;initgraph(&gdrive,&gmode,"d:\\TC20\\turboc2");setfillstyle(XHATCH_FILL,2);bar(490,0,509,479);setfillstyle(SOLID_FILL,6);bar(480,0,489,479);setfillstyle(SOLID_FILL,15);setcolor(9);setlinestyle(CENTER_LINE,0,3);line(490,0,490,479);setcolor(3);setlinestyle(SOLID_LINE,0,3);line(509,0,509,479);line(509,479,639,479);line(639,479,639,0);line(639,0,509,0);setlinestyle(SOLID_LINE,0,0);setcolor(10);settextstyle(TRIPLEX_FONT,HORIZ_DIR,3); outtextxy(530,12,"GREEDY");outtextxy(537,40,"SNAKE");settextstyle(0,0,0);setcolor(13);outtextxy(510,80,"<<============>>"); setcolor(1);setlinestyle(CENTER_LINE,0,3);line(573,90,573,305);outtextxy(510,310,"+++++++++++++++++"); setcolor(5);settextstyle(GOTHIC_FONT,0,5);outtextxy(512,390,"~~~~~~~");outtextxy(512,392,"~~~~~~~");outtextxy(512,388,"~~~~~~~");setcolor(10);settextstyle(SANS_SERIF_FONT,1,1); outtextxy(510,115,"->");outtextxy(510,165,"<-");settextstyle(SANS_SERIF_FONT,0,1); outtextxy(512,215,"->");outtextxy(512,265,"<-");setcolor(14);settextstyle(DEFAULT_FONT,0,1); outtextxy(550,128,":W");outtextxy(550,175,":S");outtextxy(550,222,":A");outtextxy(550,272,":D");setcolor(10);settextstyle(SMALL_FONT,0,5);outtextxy(575,125,"PAUSE /");outtextxy(575,140,"CONTINUE:");outtextxy(580,250,"EXIT:");/*************/}void Grow_Up(int x,int y){P_Snake_Node p;p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=x;p->y=y;p->next=Head->next;Head->next=p;Head=p;++len;++speed;}void Auto_Make_Map(){P_Snake_Node p,q;p=q=Map=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=0;p->y=0;p->next=NULL;while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)+1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)+1;q->next=p;p->next=NULL;q=p;if((p->y)==47) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=(q->x)-1;p->y=q->y;q->next=p;p->next=NULL;q=p;if((p->x)==0) break;}while(1){p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=q->x;p->y=(q->y)-1;q->next=p;p->next=NULL;q=p;if((p->y)==1) break;}p=Map;while(p){paint_node(p->x,p->y,MAP_COLOR,MAP_BOND_COLOR,MAP_STYLE);p=p->next;}}void Auto_Start(){int i=1;P_Snake_Node p,q;Head=p=(P_Snake_Node)malloc(sizeof(Snake_Node));p->x=24;p->y=24-3;p->next=NULL;q=p;while(i<=3){q=(P_Snake_Node)malloc(sizeof(Snake_Node));p->next=q;q->x=p->x;q->y=(p->y)+1;q->next=NULL;p=q;++i;}p->next=Head;Head=p;while(i>=1){Put_Snake_Node(p,1);p=p->next;i--;}Put_Food(14);Auto_Make_Map();}int Snake_Dead(){P_Snake_Node p;int i=1;p=Head->next->next;while(i<=len-4){if(p->x==px && p->y==py)return(1);++i;p=p->next;}p=Map;while(p){if(p->x==px && p->y==py)return(1);p=p->next;}return(0);}void GO_GO_GO(){px=(Head->x)+(Direct.dx);py=(Head->y)+(Direct.dy);if(!Snake_Dead()){if(px==Food.x&&py==Food.y){Grow_Up(px,py);Put_Snake_Node(Head,1);Put_Food(14);}else{Head=Head->next;Put_Snake_Node(Head,0);Head->x=px;Head->y=py;Put_Snake_Node(Head,1);}}elseFailed();}void Play_Game(){int wait;while(1){while(!kbhit()){GO_GO_GO();wait=0;while(wait<=2){delay(30000);++wait;}}switch(bioskey(0)){case UP:{if(Direct.dx!=0&&Direct.dy!=-1){Direct.dx=0;Direct.dy=1;}break;}case LEFT:{if(Direct.dx!=1&&Direct.dy!=0){Direct.dx=-1;Direct.dy=0;}break;}case DOWN:{if(Direct.dx!=0&&Direct.dy!=1){Direct.dx=0;Direct.dy=-1;}break;}case RIGHT:{if(Direct.dx!=-1&&Direct.dy!=0){Direct.dx=1;Direct.dy=0;}break;}case ESC:{exit(1);break;}}}}void Failed(){setcolor(4);settextstyle(TRIPLEX_FONT, HORIZ_DIR, 6);outtextxy(90,200,"GAME OVER!");getch();exit(1);/**********/ }void main(){Init();getch();Auto_Start();Play_Game();getch(); closegraph();}。

C语言实现贪吃蛇游戏(命令行)

C语言实现贪吃蛇游戏(命令行)

C语⾔实现贪吃蛇游戏(命令⾏)这是⼀个纯C语⾔写的贪吃蛇游戏,供⼤家参考,具体内容如下#include<stdio.h>#include<stdlib.h>#include<windows.h>#include<time.h>#include<conio.h>#define SNAKE_LENGTH 100//定义蛇的最⼤长度#define SCREEN_WIDETH 80#define SCREEN_HEIGHT 30//定义每⼀节蛇的坐标struct coor{int x;int y;};//枚举⽅向enum CH {right = VK_RIGHT,left = VK_LEFT,up = VK_UP,down = VK_DOWN};//定义蛇的属性struct snake{int len;//当前蛇的长度struct coor coord[SNAKE_LENGTH];//每⼀节蛇的坐标enum CH CH;//定义蛇的⽅向int SPEED;int flag;//定义蛇的状态 1表⽰存活 0表⽰死亡}snake;//光标移动函数void gotoxy(int x, int y){COORD pos;pos.X = x;pos.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);}//初始化游戏界⾯void init_sence(){//初始化上下墙for (int i = 0; i < SCREEN_WIDETH; i += 2){gotoxy(i,0);printf("■");gotoxy(i, SCREEN_HEIGHT);printf("■");}//初始化左右墙for (int i = 0; i <=SCREEN_HEIGHT; i++){gotoxy(0, i);printf("■");gotoxy(SCREEN_WIDETH,i);printf("■");}//打印提⽰信息gotoxy(SCREEN_WIDETH + 5, 2);printf("\t\t贪吃蛇");gotoxy(SCREEN_WIDETH + 5, 6);printf("2018//12//1");gotoxy(SCREEN_WIDETH + 5, 8);printf("作者:⼩⾖芽");gotoxy(SCREEN_WIDETH + 5, 10);printf("F1:加速\tF2:减速");gotoxy(SCREEN_WIDETH + 5, 12);printf("CTRL:继续\t空格:暂停");gotoxy(SCREEN_WIDETH + 5, 14);printf("ESC:退出游戏");gotoxy(SCREEN_WIDETH + 5, 28);printf("建议:QQ:2862841130:::");}struct foodcoord {int x;int y;int flag;//定义⾷物的状态}food;//**这是c程序**#include"snake.h"//蛇的移动void move_snake();//画出蛇void draw_snake();//产⽣⾷物void creatfood();//判断蛇是否吃到⾷物void eatfood();//判断蛇是否死掉void SnakeState();int main(){//设置窗⼝⼤⼩system("mode con cols=110 lines=31");//设置标题SetConsoleTitleA("贪吃蛇");//初始化蛇begin:snake.CH = VK_RIGHT;//初始化⽅向snake.len = 5; //初始化长度snake.SPEED = 300;//初始化蛇的移动速度snake.coord[1].x = SCREEN_WIDETH / 2;//初始化蛇头的坐标 snake.coord[1].y = SCREEN_HEIGHT / 2;snake.coord[2].x = SCREEN_WIDETH / 2-2;//初始化蛇头的坐标 snake.coord[2].y = SCREEN_HEIGHT / 2;snake.coord[3].x = SCREEN_WIDETH / 2-4;//初始化蛇头的坐标 snake.coord[3].y = SCREEN_HEIGHT / 2;//初始化⾷物状态food.flag = 1;//1表⽰吃到⾷物 0表⽰没有吃到⾷物//初始化⾷物状态snake.flag = 1;//1活 0死init_sence();//初始化游戏界⾯while (1){draw_snake();//画蛇Sleep(snake.SPEED);//蛇的移动速度move_snake();//移动蛇if(food.flag)creatfood();//产⽣⾷物eatfood();//判断是否吃到⾷物SnakeState();//判断蛇是否死亡if (!snake.flag)break;}system("cls");gotoxy(SCREEN_WIDETH/2, SCREEN_HEIGHT/2-4);printf(" GAME OVER");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+2);printf("你的得分是:\t\t\t%d ",snake.len-1);gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+4);printf("我不服再来:\t\t\tCTRL ");gotoxy(SCREEN_WIDETH / 2-6, SCREEN_HEIGHT / 2+6);printf("算了垃圾游戏毁我青春:\t\tESC");while (1){if (GetAsyncKeyState(VK_CONTROL)){system("cls");goto begin;}else if (GetAsyncKeyState(VK_ESCAPE))return 0;}}//蛇的移动void move_snake(){//判断是否有按键操作if (GetAsyncKeyState(up)){if(snake.CH!=down)snake.CH = up;}else if (GetAsyncKeyState(down)){if (snake.CH != up)snake.CH = down;}else if (GetAsyncKeyState(right)){if (snake.CH != left)snake.CH = right;}else if (GetAsyncKeyState(left)){if (snake.CH != right)snake.CH = left;}else if (GetAsyncKeyState(VK_F1)){if(snake.SPEED>=100)snake.SPEED -= 50;}else if (GetAsyncKeyState(VK_F2)){if (snake.SPEED <= 3000)snake.SPEED += 100;}//根据检测到的⽅向改变蛇头的位置switch (snake.CH){case right:snake.coord[1].x += 2; break;case left:snake.coord[1].x -= 2; break;case up:snake.coord[1].y -= 1; break;case down:snake.coord[1].y += 1; break;}}//画出蛇void draw_snake(){//画出蛇头gotoxy(snake.coord[1].x, snake.coord[1].y);printf("□");//画出蛇⾝,直接⼀个for循环实现for (int i = 2; i <= snake.len; i++){gotoxy(snake.coord[i].x, snake.coord[i].y);printf("□");}//擦掉尾巴gotoxy(snake.coord[snake.len].x, snake.coord[snake.len].y); printf(" ");//遍历每⼀节蛇for (int i = snake.len; i >1; i--){snake.coord[i].x = snake.coord[i - 1].x;snake.coord[i].y = snake.coord[i - 1].y;}gotoxy(0, 0);printf("■");gotoxy(85, 25);printf("得分:%d ", snake.len-1);}//产⽣⾷物void creatfood(){//随机种⼦⽣成srand((unsigned)time(NULL));if(food.flag)while (1){food.x = rand() % 80;food.y = rand() % 30;if (food.x % 2 == 0 && food.x >= 2 && food.x <= 78 && food.y > 1 && food.y < 30){int flag = 0;//判断产⽣的⾷物可不可能在蛇的⾝体上for (int i = 1; i <= snake.len; i++){if (snake.coord[i].x == food.x&&snake.coord[i].y == food.y){flag = 1;break;}}if (flag)continue;//绘制⾷物else{gotoxy(food.x, food.y);printf("⊙");food.flag = 0;break;}}}food.flag = 0;}//判断蛇是否吃到⾷物void eatfood(){//只需要判断蛇头是否与⾷物重合if (food.x == snake.coord[1].x&&food.y == snake.coord[1].y){snake.len+=1;food.flag = 1;}}//判断蛇是否死掉void SnakeState(){if (snake.coord[1].x < 2 || snake.coord[1].x>78 || snake.coord[1].y < 1 || snake.coord[1].y>29) snake.flag = 0;for (int i = 2; i <= snake.len; i++){if (snake.coord[1].x == snake.coord[i].x&&snake.coord[1].y == snake.coord[i].y)snake.flag = 0;}}更多有趣的经典⼩游戏实现专题,分享给⼤家:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C语言编写贪吃蛇游戏

C语言编写贪吃蛇游戏

#include<stdio.h> #include<conio.h>#include<windows.h>#include<time.h>#define food 7#define head 5#define body 6#define wall 1#define road 0#define up 1#define down 2#define left 3#define right 4#define kuan 25#define chang 30#define num 20int map[kuan][chang],hi,bj,fi,fj,t;//全局变量地图数组头部坐标,食物坐标,速度控制参数void gotoxy(int x,int y) //移动坐标{COORD coord;coord.X=x;coord.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);}void hidden()//隐藏光标{CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);cci.bVisible=0;//赋1为显示,赋0为隐藏SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci);}void paint(int xx,int yy){gotoxy(2*yy,xx);switch(map[xx][yy]){case 0:printf(" ");break;case 1:printf("□");break;case 5:printf("◎");break;case 6:printf("△");break;case 7:printf("●");break;}}void start()//初始化地图数组信息,随机蛇头位置,第一个食物位置{int i,j;for(i=0;i<=kuan-1;i++){map[i][0]=wall;map[i][chang-1]=wall;}for(j=0;j<=chang-1;j++){map[0][j]=wall;map[kuan-1][j]=wall;}for (i=0;i<=kuan-1;i++)for (j=0;j<=chang-1;j++)paint(i,j);gotoxy(64,2);printf("1.a减速//d加速");gotoxy(64,4);printf("2. esc暂停");gotoxy(65,5);printf(" 任意键继续");}int getkey(int ddd)//接收按键根据当前方向按动任意键暂停不响应与运动方向相反的按键{char c;while(c=getch()){switch(c) {case 72://1 {if(ddd==2) return down; elsereturn up; }case 80://2 {if(ddd==1) return up; elsereturn down; }case 75://3{if(ddd==4)return right;elsereturn left;}case 77://4{if(ddd==3)return left;elsereturn right;}case 27:continue;//esc暂停,a减速,d加速case 97:{t+=10;return ddd;}case 100:{t-=10;return ddd;}default:{return ddd;}}return 0;}}void game(){intfd=0,len=1,direction=4,a[100000],b[100000],k,m,kk=0,aa=0,bb=0,i,iii=0;int sj=0;//sj用来记录吃到的果实的存放其坐标的数组的角标int zz=0,mm=0,fa[num+2],fb[num+2];t=250;//全局变量在这里赋值hi=rand()%(kuan-7)+6;bj=rand()%(chang-8)+5;map[hi][bj]=head;paint(hi,bj);//在一定范围随机蛇头初始位置,身子为左侧3个格子(可以拓展写入game里面)a[3]=hi;b[3]=bj;//头部位置存放到 a b数组中第四项中for (i=0;i<3;i++){map[hi][bj-1-i]=body;paint(hi,bj-i-1);a[2-i]=hi;b[2-i]=(bj-i-1);}//身子位置按照尾巴至颈部存放到 0 1 2 项中k=4;m=4;//数组之后从第四位开始存放蛇头坐标while(1){while(!kbhit()&&len!=0)//当没有按键输入并且没有撞到墙使得len=0时候进入循环(防止撞到墙后没有按键输入仍终止不了){while (fd<=num)//如果fd<=num 则进入循环随机刷新一个新果实{do{fi=rand()%(kuan-3)+1;fj=rand()%(chang-3)+1;}while(map[fi][fj]>0);//不在墙或者蛇的身体内if(fd<20){map[fi][fj]=food;paint(fi,fj);fa[zz++]=fi;fb[mm++]=fj;fd++;}else{map[fi][fj]=food;paint(fi,fj);fa[sj]=fi;fb[sj]=fj;fd++;}//如果fd=20进来循环,就会把新生成的果实的坐标赋给被上次被吃的数组,便于之后的循环检测}switch(direction){case 1: {map[hi][bj]=body;paint(hi,bj);hi--;break;}case 2: {map[hi][bj]=body;paint(hi,bj);hi++;break;}case 3: {map[hi][bj]=body;paint(hi,bj);bj--;break;}case 4: {map[hi][bj]=body;paint(hi,bj);bj++;break;}}if ((map[hi][bj]==body)||(map[hi][bj]==wall))//在画出新的头部时刻先判断即将画出的位置是不是map上坐标为身子的位置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include<stdio.h>
#include<time.h>
#include<conio.h>
#include<stdlib.h>
int head=3,tail=0,f=0,s,t,m;
int main()
{ int i,j;
int zuobiao[2][80];
long start;
int direction=77;
int gamespeed;
int timeover;
int change(char qipan[30][80],int zuobiao[2][80],char direction);
printf("auto? Y/N\n");
m=getch();
if (m=='y')
{
zuobiao[0][tail]=1;zuobiao[1][tail]=1;zuobiao[0][1]=1;zuobiao[1][1]=2;zuobiao[0][2]=1;zuo biao[1][2]=3;zuobiao[0][head]=1;zuobiao[1][head]=4;
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<=19;i++)
for(j=0;j<=79;j++)
qipan[i][j]=' ';//初始化棋盘
qipan[1][1]=qipan[1][2]=qipan[1][3]='*';//初始化蛇的位置
qipan[1][4]='#';
printf("start\n");
printf("Input your game level,please.\ 1-1000\n");
scanf("%d",&gamespeed);
s=rand()%20;
t=rand()%80;
qipan[s][t]='$';
while(direction!='q')
{ system("cls"); // 清屏
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
printf("%c",qipan[i][j]);
timeover=1;
start=clock();
while(!kbhit()&&(timeover=clock()-start<=1000-gamespeed));
if(direction==72||direction==80)
if(s!=zuobiao[0][head])
if(s-zuobiao[0][head]<0)
direction=72;
else direction=80;
else
if(t-zuobiao[1][head]<0)
direction=75;
else direction=77;
else if(t!=zuobiao[1][head])
if(t-zuobiao[1][head]<0)
direction=75;
else direction=77;
else
if(t-zuobiao[1][head]<0)
direction=72;
else direction=80;
if(!(direction==72||direction==80||direction==75||direction==77))
{
return 0;
system("cls");
printf("GAME OVER!\n");
}
if(!change(qipan,zuobiao,direction))
{
direction='q';
system("cls");
printf("GAME OVER!\n");
}
if(f==1)
{
s=rand()%20;
t=rand()%80;
qipan[s][t]='$';
f=0;
}
}
return 0;
}
else
zuobiao[0][tail]=1;zuobiao[1][tail]=1;zuobiao[0][1]=1;zuobiao[1][1]=2;zuobiao[0][2]=1;zuo biao[1][2]=3;zuobiao[0][head]=1;zuobiao[1][head]=4;
/*处理棋盘*/
char qipan[20][80];//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]=' ';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=1;i<=20;i++)
qipan[i][0]='|';
for(i=1;i<=20;i++)
qipan[i][79]='|';
for(i=0;i<80;i++)
qipan[19][i]='_';
qipan[1][1]=qipan[1][2]=qipan[1][3]='*';//初始化蛇的位置
qipan[1][4]='#';
printf("start\n");
printf("Input your game level,please.\ 1-1000\n");
scanf("%d",&gamespeed);
s=rand()%20;
t=rand()%80;
qipan[s][t]='$';
while(direction!='q')
{ system("cls"); // 清屏
for(i=0;i<20;i++)//打印出棋盘
for(j=0;j<80;j++)
printf("%c",qipan[i][j]);
timeover=1;
start=clock();
while(!kbhit()&&(timeover=clock()-start<=1000-gamespeed));
if(timeover)
{
getch();
direction=getch();
}
else
direction=direction;
if(!(direction==72||direction==80||direction==75||direction==77)) {
return 0;
system("cls");
printf("GAME OVER!\n");
}
if(!change(qipan,zuobiao,direction))
{
direction='q';
system("cls");
printf("GAME OVER!\n");
}
if(f==1)
{
s=rand()%20;
t=rand()%80;
qipan[s][t]='$';
f=0;
}
}
return 0;
}
int change(char qipan[20][80],int zuobiao[2][80],char direction) {
int x,y;
{if(direction==72)
{x=zuobiao[0][head]-1;
y=zuobiao[1][head]; }
if(direction==80)
{x=zuobiao[0][head]+1;
y=zuobiao[1][head];}
if(direction==75)
{x=zuobiao[0][head];
y=zuobiao[1][head]-1;}
if(direction==77)
{x=zuobiao[0][head];
y=zuobiao[1][head]+1;}
if(x<0)
x=18;
else if(x>18)
x=0;
else if(y>78)
y=0;
else if(y<0)
y=78;
if(qipan[s][t]!='$')
f=1;
qipan[zuobiao[0][tail]][zuobiao[1][tail]]=' ';
tail=(tail+1)%80;
qipan[zuobiao[0][head]][zuobiao[1][head]]='*';
head=(head+1)%80;
zuobiao[0][head]=x;
zuobiao[1][head]=y;
qipan[zuobiao[0][head]][zuobiao[1][head]]='#';
return 1;
}
}。

相关文档
最新文档