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语言小游戏源代码《贪吃蛇》
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编译本程序为贪吃蛇游戏,想必大家都玩过这个游戏,程序源代码用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语言代码
}
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版
#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语言源程序
#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语⾔写的贪吃蛇游戏,供⼤家参考,具体内容如下#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语言编写贪吃蛇游戏
#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上坐标为身子的位置。
c语言贪吃蛇小游戏程序课程设计
void GameOver(); //游戏结束判断函数 void Pause(); //游戏暂停函数 void MyCount1(); //统计边栏,用来做提示 void MyCount2(); //统计边栏,用来做一些统计 void Menu( int ); //开始界面 void Inti_Data(); //初始化数据
3.主函数int main()
int main()
//主函数
{
START:
Inti_Data();
fixConsoleSize(18,15);
Hid_Cursor();
SurFace();
PlaySound(TEXT("m22.wav"), NULL, SND_FILENAME | SND_ASYNC );
2.函数定义和声明
(1)头文件 #include<iostream> #include<windows.h> #include<conio.h> #include<time.h> #include<stdlib.h> #include "mmsystem.h" #pragma comment (lib,"winmm.lib") #include"pcc32.h"
}
}
return 0;
}
4.界面函数Surface()
SurFace()是通过接受按键信息来调用Menu(); SurFace()中给出了四个菜单选项, 上下键实现对菜单的选择, ENTER键实现对菜单的进入; temp用于存放按键信息, keytemp用于记录当前菜单的位置, 实现了在第一个菜单选项按上方向键会走到最后一个菜单选项(keytemp+=4), 在最后一个菜单选项按下方向键会走到第一个菜单选项(keytemp%4)
C课程设计贪吃蛇小游戏内附完整源码及附件.doc
温馨提示程序语言:C、C++、C#、Python(红色字体表示本课设使用的程序设计语言)图形功能选项:Win32控制台程序(黑框、文本界面)、Win32程序、MFC、WinForm、DirectX10(黑体标明表示本课设的程序图形类别,默认为非图形界面Win32控制台程序)数据结构:基础类型、数组、链表、双向链表、搜索树(非平衡二叉树)、平衡二叉树、链表与平衡二叉树相结合、堆栈、队列、串、图(黑体标明表示本课设使用的数据结构)C++语言项:STL库(黑体标明表示使用C++的STL库)编译环境:Windows 7 64位旗舰版(Linux及其他环境请谨慎下载)集成开发环境:Visual C++ 6.0、DEVC++、CodeBlocks、Visual Studio 2015均可通过编译。
(浅蓝色字体表示需要运行修改后的版本,请用户自行选择源代码测试)分多头文件编译:否(所有代码基本都包含在一个文件内,如需试验头文件功能,请自行参考相关文献)内容说明:1、课设题目及预览内容将在第二页开始展示。
2、代码行数:259行3、目录所示内容,本文基本涵盖,如无内容,会在本页进行说明。
4、附录绝对包含用户使用手册及程序完整源代码和详细注释。
5、如需下载其他头文件(例如DirectX需另行配置),本文会在此进行说明。
6、本文撰写内容仅供学习参考,另外,由于本人水平有限,编写之处难免存在错误和纰漏,恳请各位老师或同学批评指正。
上机报告程序实践名称:________________________________学生姓名:________________________________专业:________________________________班级:________________________________学号:________________________________指导教师:________________________________上机成绩:________________________________上机地点:________________________________上机时间:____________年_______月_______日一、上机目的与上机要求(可以有多个目标及要求,对应多个上机内容)1、上机目的(具体的目的,类似于“提出问题”)将理论用于实践,更充分的掌握课本的知识,巩固并加深对课本知识的理解,进一步提高我们的动手编程能力。
C语言小游戏-贪吃蛇程序清单
setcolor(6);
settextstyle(0,0,2);
sprintf(str,"score:%d",score);
outtextxy(55,20,str);
{
setcolor(0);
rectangle(food.x,food.y,food.x+10,food.y-10);
snake.x[snake.node]=-20;
}
setcolor(4);
for(i=0;i<snake.node;i++)
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);
#define UP 0x4800
#define ESC 0x011b
int i,key;
int score=0;
int gamespeed=50000;
struct food
{
int x;
int y;
int yes;
}food;
struct snake
}
void colse(void)
{
getch();
closegraph();
}
{
gameover();
snake.life=1;
}
if(snake.life==1) break;
if(snake.x[0]==food.x&&snake.y[0]==food.y)
rectangle(601,i,610,i+10);
使用ncurses库编写贪吃蛇小游戏
复制代码
gcc -o snake snake.c -lncurses
然后运行生成的可执行文件:
复制代码
./sna需求和想法进行扩展和修改。
while (1) { clear(); mvprintw(y, x, "o"); refresh();
int key = getch(); if (key == KEY_UP && direction != KEY_DOWN) {
direction = KEY_UP; } else if (key == KEY_DOWN && direction != KEY_UP) {
direction = KEY_RIGHT; }
switch (direction) { case KEY_UP: y--; break;
case KEY_DOWN: y++; break;
case KEY_LEFT: x--; break;
case KEY_RIGHT: x++; break;
}
int main() { int x = WIDTH / 2; int y = HEIGHT / 2; int direction = KEY_RIGHT;
initscr(); curs_set(0); keypad(stdscr, TRUE); nodelay(stdscr, TRUE); noecho(); timeout(100);
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) { break;
贪吃蛇游戏代码(C语言编写)
贪吃蛇游戏代码(C语言编写)#include "graphics.h"#include "stdio.h"#define MAX 200#define MAXX 30#define MAXY 30#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181#define PAGEUP 18688#define PAGEDOWN 20736#define KEY_U 5749#define KEY_K 9579#define CTRL_P 6512#define TRUE 1#define FALSE 0#define GAMEINIT 1#define GAMESTART 2#define GAMEHAPPY 3#define GAMEOVER 4struct SPlace{int x;int y;int st;} place[MAX];int speed;int count;int score;int control;int head;int tear;int x,y;int babyx,babyy;int class;int eat;int game;int gamedelay[]={5000,4000,3000,2000,1000,500,250,100}; int gamedelay2[]={1000,1};static int hitme=TRUE,hit = TRUE; void init(void);void nextstatus(void);void draw(void);void init(void){int i;for(i=0;i<max;i++)< p="">{place[i].x = 0;place[i].y = 0;place[i].st = FALSE;}place[0].st = TRUE;place[1].st = TRUE;place[1].x = 1;speed = 9;count = 0;score = 0;control = 4;head = 1;tear = 0;x = 1;y = 0;babyx = rand()%MAXX;babyy = rand()%MAXY;eat = FALSE;game = GAMESTART;}void nextstatus(void){int i;int exit;int xx,yy;xx = x;yy = y;switch(control){case 1: y--; yy = y-1; break;case 2: y++; yy = y+1; break;case 3: x--; xx = x-1; break;case 4: x++; xx = x+1; break;}hit = TRUE;if ( ((control == 1) || (control ==2 )) && ( (y < 1) ||(y >= MAXY-1)) || (((control == 3) || (control == 4)) && ((x < 1) ||(x >= MAXX-1) ) ) ){}if ( (y < 0) ||(y >= MAXY) ||(x < 0) ||(x >= MAXX) ){game = GAMEOVER;control = 0;return;}for (i = 0; i < MAX; i++){if ((place[i].st) &&(x == place[i].x) &&(y == place[i].y) ){game = GAMEOVER;control = 0;return;}if ((place[i].st) &&(xx == place[i].x) &&(yy == place[i].y) ){hit = FALSE;goto OUT;}}OUT:if ( (x == babyx) && (y == babyy) ) {count ++;score += (1+class) * 10;}head ++;if (head >= MAX) head = 0;place[head].x = x;place[head].y = y;place[head].st= TRUE;if (eat == FALSE){place[tear].st = FALSE;tear ++;if (tear >= MAX) tear = 0;}else{eat = FALSE;exit = TRUE;while(exit){babyx = rand()%MAXX;babyy = rand()%MAXY;exit = FALSE;for( i = 0; i< MAX; i++ )if( (place[i].st)&&( place[i].x == babyx) && (place[i].y == babyy))exit ++;}}if (head == tear) game = GAMEHAPPY;}void draw(void){char temp[50];int i,j;for (i = 0; i < MAX; i++ ){setfillstyle(1,9);if (place[i].st)bar(place[i].x*15+1,place[i].y*10+1,place[i].x*15+14,place[i]. y*10+9);}setfillstyle(1,4);bar(babyx*15+1,babyy*10+1,babyx*15+14,babyy*10+9);setcolor(8);setfillstyle(1,8);bar(place[head].x*15+1,place[head].y*10+1,place[head].x*1 5+14,place[head].y*10+9); /* for( i = 0; i <= MAXX; i++ ) line( i*15,0, i*15, 10*MAXY);for( j = 0; j <= MAXY; j++ )line( 0, j*10, 15*MAXX, j*10); */rectangle(0,0,15*MAXX,10*MAXY);sprintf(temp,"Count: %d",count);settextstyle(1,0,2);setcolor(8);outtextxy(512,142,temp);setcolor(11);outtextxy(510,140,temp);sprintf(temp,"1P: %d",score);settextstyle(1,0,2);setcolor(8);outtextxy(512,102,temp); setcolor(12);outtextxy(510,100,temp); sprintf(temp,"Class: %d",class); setcolor(8);outtextxy(512,182,temp); setcolor(11);outtextxy(510,180,temp);}main(){int pause = 0;char temp[50];int d,m;int key;int p;static int keydown = FALSE; int exit = FALSE;int stchange = 0;d = VGA;m = VGAMED;initgraph( &d, &m, "" ); setbkcolor(3);class = 3;init();p = 1;while(!exit){if (kbhit()){key = bioskey(0);switch(key){case UP: if( (control != 2)&& !keydown)control = 1;keydown = TRUE;break;case DOWN: if( (control != 1)&& !keydown)control = 2;keydown = TRUE;break;case LEFT: if( (control != 4)&& !keydown)control = 3;keydown = TRUE;break;case RIGHT: if( (control != 3)&& !keydown)control = 4;keydown = TRUE;break;case ESC: exit = TRUE;break;case ENTER: init();break;case PAGEUP: class --; if (class<0) class = 0; break;case PAGEDOWN: class ++;if (class>7) class = 7; break;case KEY_U: if( ( (control ==1) ||(control ==2))&& !keydown) control = 3;else if(( (control == 3) || (control == 4))&& !keydown)control = 1;keydown = TRUE;break;case KEY_K: if( ( (control ==1) ||(control ==2))&& !keydown) control = 4;else if(( (control == 3) || (control == 4))&& !keydown)control = 2;keydown = TRUE;break;case CTRL_P:pause = 1 - pause; break;}}stchange ++ ;putpixel(0,0,0);if (stchange > gamedelay[class] + gamedelay2[hit]){stchange = 0;keydown = FALSE;p = 1 - p;setactivepage(p);cleardevice();if (!pause)nextstatus();else{settextstyle(1,0,4);setcolor(12);outtextxy(250,100,"PAUSE");}draw();if(game==GAMEOVER){settextstyle(0,0,6);setcolor(8);outtextxy(101,101,"GAME OVER"); setcolor(15);outtextxy(99,99,"GAME OVER"); setcolor(12);outtextxy(100,100,"GAME OVER"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}if(game==GAMEHAPPY){settextstyle(0,0,6);setcolor(12);outtextxy(100,300,"YOU WIN"); sprintf(temp,"Last Count: %d",count); settextstyle(0,0,2);outtextxy(200,200,temp);}setvisualpage(p);}}closegraph();}</max;i++)<>。
纯C语言编写贪吃蛇(附源码,无EasyX、MFC)
纯C语⾔编写贪吃蛇(附源码,⽆EasyX、MFC)⼤⼀下学期,我所选的C语⾔⼯程实践是写⼀个贪吃蛇游戏。
那⼏天真的挺肝的,完成本专业的答辩之后就没怎么动过这程序了。
那时候写的贪吃蛇,还有⼀个栈溢出的问题没有解决,是因为当时所学知识有限,还没想到较好的解决⽅法。
现在⼤⼆上学期,在上了好⼏节数据结构之后,对栈有了⼀定的了解,随着对栈的学习,我想出了解决我写的贪吃蛇栈溢出的办法。
其实是前两天刚刚有这个想法,刚刚才测试并实现了,办法可⾏。
现在我加⼊了计算机学院的创新开放实验室,打算做的⼀个项⽬是微信⼩程序。
以后想记录⼀下我的开发过程和⼀些经历,⼜刚刚完善好贪吃蛇的代码,就简单记录⼀下吧。
因为代码⽐较长,先把参考资料写⼀下,想⾃⼰⼿写⼀遍的建议先看参考资料,再看这⾥的代码参考资料源代码/*预处理*/#include <windows.h>#include <stdio.h>#include <conio.h>#include <string.h>#include <time.h>/*宏定义*/#define YES 1#define NO 0//蛇的移动⽅向#define U 1 //上#define D 2 //下#define L 3 //左#define R 4 //右#define RESPEED 250 //蛇的移动速度/*定义节点*/typedef struct SNAKE{int x;int y;struct SNAKE* next;}snake;/*全局变量*/snake* head, * food; //蛇头指针,⾷物指针snake* q; //遍历蛇的时候⽤到的指针/*【以下为所有函数的声明】*/void HideCursor(void); //隐藏光标void color(short int num); //颜⾊函数void StartWindow(void); //开始界⾯int gotoxy(int x, int y); //定位光标位置void creatMap(void); //创建地图void notice(int* score, int* highscore, int* Time, int* LongTime); //提⽰void initsnake(void); //初始化蛇⾝int biteself(unsigned long* sleeptime); //判断是否咬到了⾃⼰int createfood(void); //随机出现⾷物void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime); //结束游戏void pause(int* PauseBegin, int* PauseEnd); //暂停游戏void gamecontrol(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //控制游戏(包含蛇不能穿墙)void snakemove(unsigned long* sleeptime, int* count, int* score, int* status, int* endgamestatus); //蛇移动void gamestart(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime, int* TimeBegin); //游戏初始化void gamecontinue(unsigned long* sleeptime, int* count, int* score, int* highscore, int* status, int* endgamestatus,int* Time, int* LongTime, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //再来⼀局void stop(unsigned long* sleeptime); //蛇停⽌移动void start(unsigned long* sleeptime); //蛇恢复移动void reset(int* count, int* score, int* Time, int* TimeBegin, int* TimeEnd, int* TimePause, int* PauseBegin, int* PauseEnd); //重置多项数据void updatescore(int* score, int* highscore, int* Time, int* LongTime); //更新多项数据int main(void){unsigned long sleeptime = RESPEED;int score = 0, highscore = 0, count = 0; //count是记录吃到⾷物的次数int status, endgamestatus = 0; //游戏结束情况,0未开始游戏前退出,1撞到墙,2咬到⾃⼰,3主动退出游戏,4通关HideCursor();gamestart(&score, &highscore, &endgamestatus, &Time, &LongTime, &TimeBegin);gamecontrol(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &Pa useBegin, &PauseEnd);endgame(&score, &highscore, &endgamestatus, &Time, &LongTime);gamecontinue(&sleeptime, &count, &score, &highscore, &status, &endgamestatus, &Time, &LongTime, &TimeBegin, &TimeEnd, &TimePause, &P auseBegin, &PauseEnd);return 0;}void HideCursor(void) //隐藏光标{CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);}void color(short int num){HANDLE hConsole = GetStdHandle((STD_OUTPUT_HANDLE));SetConsoleTextAttribute(hConsole, num);}void StartWindow(void){short int i;system("mode con cols=120 lines=30"); //设置窗⼝⼤⼩printf("温馨提⽰:请使⽤键盘操作(⿏标点击可能会导致程序出错)\n");printf("╔═══════════════════════════════════════════════════╗ \n");for (i = 0; i < 26; i++){printf("║ ║ \n");}printf("╚═══════════════════════════════════════════════════╝ \n");gotoxy(23, 2);color(3);printf("贪吃蛇");for (i = 15; ; i--){gotoxy(18, 4);color(i);printf("按任意键加载程序");Sleep(600);if (i == 1){i = 15;}if (kbhit()) //判断是否按键,等待输⼊按键为0,按键为1{break;}}gotoxy(10, 4);printf("1.开始游戏 2.退出游戏");getch();}int gotoxy(int x, int y){HANDLE handle; //定义句柄变量handle,创建⼀个句柄COORD pos; //定义结构体coord (坐标系coord)pos.X = x; //横坐标xpos.Y = y; //纵坐标yhandle = GetStdHandle(STD_OUTPUT_HANDLE); //获取控制台输出句柄(值为-11)SetConsoleCursorPosition(handle, pos); //移动光标return YES;}void creatMap(void){int i;//地图⼤⼩:长24×宽20printf("■");gotoxy(i, 27);printf("■");}for (i = 7; i < 28; i++) //打印左右边框{gotoxy(2, i);printf("■");gotoxy(50, i);printf("■");}}void notice(int* score, int* highscore, int* Time, int* LongTime){system("title 2018051170 Project:贪吃蛇");gotoxy(4, 4);color(15);printf("得分:%3d 最⾼分:%3d ⽣存:%4ds 最久⽣存:%4ds", *score, *highscore, *Time, *LongTime); gotoxy(60, 7);printf("Author: 2018051170 Project: 贪吃蛇");gotoxy(60, 9);printf("游戏说明:");gotoxy(60, 10);printf("不能穿墙,不能咬到⾃⼰");gotoxy(60, 11);printf("↑↓←→控制蛇的移动");gotoxy(60, 12);printf("ESC:退出游戏空格:暂停游戏");}void initsnake(void){int i;snake* tail;tail = (snake*)malloc(sizeof(snake)); //从蛇尾开始,插头法,以x,y设定开始的位置tail->x = 26;tail->y = 14;tail->next = NULL;for (i = 1; i < 3; i++){head = (snake*)malloc(sizeof(snake));head->next = tail;head->x = 26 - 2 * i;head->y = 14;tail = head;}while (tail != NULL) //从头到为,输出蛇⾝{gotoxy(tail->x, tail->y);if (i == 3){color(2);printf("●");i++;}else if (tail != NULL){color(2);printf("■");}tail = tail->next;}}int biteself(unsigned long* sleeptime){snake* self;self = head->next;while (self != NULL){if (self->x == head->x && self->y == head->y)self = self->next;}return NO;}int createfood(void){snake* food_1;food_1 = (snake*)malloc(sizeof(snake));srand((unsigned)time(NULL)); //产⽣⼀个随机数while ((food_1->x % 2) != 0) //保证其为偶数,使得⾷物能与蛇头对其{food_1->x = rand() % 50; //保证其在墙壁⾥X1 < X < X2if (food_1->x <= 4){food_1->x = food_1->x + 4;}}food_1->y = rand() % 27; //保证其在墙壁⾥Y1 < Y < Y2if (food_1->y < 7){food_1->y = food_1->y + 7;}q = head;while (q != NULL) //判断蛇⾝是否与⾷物重合{if (q->x == food_1->x && q->y == food_1->y){free(food_1);return 1;}if (q->next == NULL){break;}q = q->next;}gotoxy(food_1->x, food_1->y);food = food_1;color(3);printf("★");return 0;}void endgame(int* score, int* highscore, int* endgamestatus, int* Time, int* LongTime) {color(15);gotoxy(60, 14);if (*endgamestatus == 0){printf("您退出了游戏。
贪吃蛇游戏c语言源代码
Ì°³ÔÉßÓÎÏ·cÓïÑÔÔ´´úÂë.txtÊÀÉÏ×îÕä¹óµÄ²»ÊÇÓÀÔ¶µÃ²»µ½»òÒѾ-µÃµ½µÄ£¬¶øÊÇÄãÒѾ-µÃµ½²¢ÇÒËæʱ¶¼ÓпÉÄÜʧȥµÄ¶«Î÷£¡°®ÇéÊǵƣ¬ÓÑÇéÊÇÓ°×Ó¡£µÆÃðʱ£¬Äã»á·¢ÏÖÖÜΧ¶¼ÊÇÓ°×Ó¡£ÅóÓÑ£¬ÊÇÔÚ×îºó¿ÉÒÔ¸øÄãÁ¦Á¿µÄÈË¡£#include <stdlib.h>#include <graphics.h>#include <bios.h>#include <dos.h>#include <conio.h>#define Enter 7181#define ESC 283#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endifvoid interrupt (*oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS);void SetTimer(void interrupt (*IntProc)(__CPPARGS));void KillTimer(void);void Initgra(void);void TheFirstBlock(void);void DrawMap(void);void Initsnake(void);void Initfood(void);void Snake_Headmv(void);void Flag(int,int,int,int);void GameOver(void);void Snake_Bodymv(void);void Snake_Bodyadd(void);void PrntScore(void);void Timer(void);void Win(void);void TheSecondBlock(void);void Food(void);void Dsnkorfd(int,int,int);void Delay(int);struct Snake{int x;int y;int color;}Snk[12];struct Food{int x;int y;int color;}Fd;int flag1=1,flag2=0,flag3=0,flag4=0,flag5=0,flag6=0,checkx,checky,num,key=0,Times,Score,Hscore,Snkspeed,TimerCounter,TureorFalse; char Sco[2],Time[6];void main(){ Initgra();SetTimer(newhandler);TheFirstBlock();while(1){DrawMap();Snake_Headmv();GameOver();Snake_Bodymv();Snake_Bodyadd();PrntScore();Timer();Win();if(key==ESC)break;if(key==Enter){cleardevice();TheFirstBlock();}TheSecondBlock();Food();Delay(Snkspeed);}closegraph();KillTimer();}void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(0x1c);disable();setvect(0x1c,IntProc);enable();}void KillTimer(){disable();setvect(0x1c,oldhandler);enable();}void Initgra(){int gd=DETECT,gm;initgraph(&gd,&gm,"d:\\tc");}void TheFirstBlock(){setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The First Block");loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=10;num=2;Times=0;key=0;TureorFalse=1;TimerCounter=0;Time[0]='0';Time[1]='0';Time[2]=':';Time[3]='1';Time[4]='0';Time[5]='\0'; }else if(key==ESC) cleardevice();else goto loop;}void DrawMap(){line(10,10,470,10);line(470,10,470,470);line(470,470,10,470);line(10,470,10,10);line(480,20,620,20);line(620,20,620,460);line(620,460,480,460);line(480,460,480,20);}void Initsnake(){randomize();num=2;Snk[0].x=random(440);Snk[0].x=Snk[0].x-Snk[0].x%20+50;Snk[0].y=random(440);Snk[0].y=Snk[0].y-Snk[0].y%20+50;Snk[0].color=4;Snk[1].x=Snk[0].x;Snk[1].y=Snk[0].y+20;Snk[1].color=4;}void Initfood(){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;}void Snake_Headmv(){if(bioskey(1)){key=bioskey(0);switch(key){case UP:Flag(1,0,0,0);break;case DOWN:Flag(0,1,0,0);break;case LEFT:Flag(0,0,1,0);break;case RIGHT:Flag(0,0,0,1);break;default:break;}}if(flag1){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag2){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].y+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color); }if(flag3){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x-=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}if(flag4){checkx=Snk[0].x;checky=Snk[0].y;Dsnkorfd(Snk[0].x,Snk[0].y,0);Snk[0].x+=20;Dsnkorfd(Snk[0].x,Snk[0].y,Snk[0].color);}}void Flag(int a,int b,int c,int d){flag1=a;flag2=b;flag3=c;flag4=d;}void GameOver(){int i;if(Snk[0].x<20||Snk[0].x>460||Snk[0].y<20||Snk[0].y>460) {cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop1:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();elsegoto loop1;}for(i=3;i<num;i++){if(Snk[0].x==Snk[i].x&&Snk[0].y==Snk[i].y){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop2:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}elseif(key==ESC)cleardevice();else goto loop2;}}}void Snake_Bodymv(){int i,s,t;for(i=1;i<num;i++){Dsnkorfd(checkx,checky,Snk[i].color); Dsnkorfd(Snk[i].x,Snk[i].y,0);s=Snk[i].x;t=Snk[i].y;Snk[i].x=checkx;Snk[i].y=checky;checkx=s;checky=t;}}void Food(){if(flag5){randomize();Fd.x=random(440);Fd.x=Fd.x-Fd.x%20+30;Fd.y=random(440);Fd.y=Fd.y-Fd.y%20+30;Fd.color=random(14)+1;flag5=0;}Dsnkorfd(Fd.x,Fd.y,Fd.color);}void Snake_Bodyadd(){if(Snk[0].x==Fd.x&&Snk[0].y==Fd.y){if(Snk[num-1].x>Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x+20;Snk[num-1].y=Snk[num-2].y;Snk[num-1].color=Fd.color;}elseif(Snk[num-1].x<Snk[num-2].x){num++;Snk[num-1].x=Snk[num-2].x-20; Snk[num-1].y=Snk[num-2].y; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y>Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y+20; Snk[num-1].color=Fd.color;}elseif(Snk[num-1].y<Snk[num-2].y) {num++;Snk[num-1].x=Snk[num-2].x; Snk[num-1].y=Snk[num-2].y-20; Snk[num-1].color=Fd.color;}flag5=1;Score++;}}void PrntScore(){if(Hscore!=Score){setcolor(11);settextstyle(0,0,3);outtextxy(490,100,"SCORE"); setcolor(2);setfillstyle(1,0);rectangle(520,140,580,180); floodfill(530,145,2);Sco[0]=(char)(Score+48);Sco[1]='\0';Hscore=Score;setcolor(4);settextstyle(0,0,3);outtextxy(540,150,Sco);}}void Timer(){if(TimerCounter>18){Time[4]=(char)(Time[4]-1);if(Time[4]<'0'){Time[4]='9';Time[3]=(char)(Time[3]-1);}if(Time[3]<'0'){Time[3]='5';Time[1]=(char)(Time[1]-1);}if(TureorFalse){setcolor(11);settextstyle(0,0,3);outtextxy(490,240,"TIMER");setcolor(2);setfillstyle(1,0);rectangle(490,280,610,320);floodfill(530,300,2);setcolor(11);settextstyle(0,0,3);outtextxy(495,290,Time);TureorFalse=0;}if(Time[1]=='0'&&Time[3]=='0'&&Time[4]=='0') {setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"Game Over");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();}else if(key==ESC) cleardevice();else goto loop;}TimerCounter=0;TureorFalse=1;}}void Win(){if(Score==3)Times++;if(Times==2){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(160,220,"You Win");loop:key=bioskey(0);if(key==Enter){cleardevice();TheFirstBlock();key=0;}else if(key==ESC) cleardevice();else goto loop;}}void TheSecondBlock(){if(Score==3){cleardevice();setcolor(11);settextstyle(0,0,4);outtextxy(100,220,"The Second Block"); loop:key=bioskey(0);if(key==Enter){cleardevice();Initsnake();Initfood();Score=0;Hscore=1;Snkspeed=8;num=2;key=0;}else if(key==ESC) cleardevice();else goto loop;}}void Dsnkorfd(int x,int y,int color) {setcolor(color);setfillstyle(1,color);circle(x,y,10);floodfill(x,y,color);}void Delay(int times){int i;for(i=1;i<=times;i++)delay(15000);}。
贪吃蛇C程序(gtk)
贪吃蛇源程序#include <gtk/gtk.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#define length 10/*最长蛇节数*/#define side 24/*每节蛇身以及食物的边长*/#define p_prize 20/*特殊食物概率*/GtkWidget *window;/*定义窗体*/GtkWidget *fixed;/*定义固定容器构件*/GtkWidget *snake[length];/*蛇的节数*/GtkWidget *food[length];/*食物数*/GtkWidget *border_up;/*上边界*/GtkWidget *border_down;/*下边界*/GtkWidget *border_left;/*左边界*/GtkWidget *border_right;/*右边界*/GtkWidget *game_score_label;/*当前分数标签*/GtkWidget *game_score[2*length-12];/*当前分数值*/GtkWidget *game_pause;/*游戏暂停*/GtkWidget *game_speed_label;/*速度调节标签*/GtkWidget *game_speed[4];/*当前速度*/GtkWidget *death;/*游戏失败提示窗口*/GtkWidget *win;/*游戏通关提示窗口*/GtkWidget *direction[4];/*改变蛇的方向*/GdkColor color[20];/*颜色值*/gint function(gpointer data);/*主体函数*/void up(void);/*往上*/void down(void);/*往下*/void left(void);/*往左*/void right(void);/*往右*/gboolean key_control(GtkWidget *widget,GdkEventKey *event);//键盘void show_pause(void);/*暂停|开始游戏*/void speed_control0(void);/*速度控制*/void speed_control1(void);void speed_control2(void);void eat(void);/*吃到食物*/void showwin(void);/*游戏通关*/void showdeath(void);/*游戏结束*/gpointer data;gint sign;/*定时器*/int i=0;/*暂停开始状态标记*/int j=0;/*累加变量*/int j1=0;int k=0;/*未设置速度前为0 游戏过程中为1 游戏结束时为-1*/int snake_x[length],snake_y[length],food_x[length],food_y[length];/*蛇及食物的坐标位置数组*/int flag=3;/*方向标记*/int jieshu=6;/*蛇当前节数*/int stop=1;/*蛇停止运动时stop=1*/int speed=0;int op_speed[3]={100,300,500};int prize[2*length-12]={0};charscore[41][8]={"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","1 6","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32"," 33","34","35","36","37","38","39","40"};char dir[4][4]={"上","下","左","右"};/*四个方向键的显示值*/int main(int argc,char *argv[ ]){gtk_init(&argc,&argv);/*初始化*/window=gtk_window_new(GTK_WINDOW_TOPLEVEL);/*游戏窗口*/gdk_color_parse ("#00F0F0", &color[0]);gdk_color_parse ("#F00000", &color[1]);gdk_color_parse ("#0F0000", &color[2]);gdk_color_parse ("#00F000", &color[3]);gdk_color_parse ("#000F00", &color[4]);gdk_color_parse ("#0000F0", &color[5]);gdk_color_parse ("#00000F", &color[6]);gdk_color_parse ("#F0F000", &color[7]);gdk_color_parse ("#FF0000", &color[8]);gdk_color_parse ("#0FF000", &color[9]);gdk_color_parse ("#00FF00", &color[10]);gdk_color_parse ("#F00F00", &color[11]);gdk_color_parse ("#F000F0", &color[12]);gdk_color_parse ("#F0F0F0", &color[13]);gdk_color_parse ("#F0000F", &color[14]);gdk_color_parse ("#0FF00F", &color[15]);gdk_color_parse ("#00FFF0", &color[16]);gdk_color_parse ("#F00FF0", &color[17]);gdk_color_parse ("#FF00F0", &color[18]);gdk_color_parse ("#F0F0FF", &color[19]);gtk_window_set_title(GTK_WINDOW(window),"贪吃蛇键盘、鼠标两种控制方式游戏前请先选择难度蛇不会咬到自己彩色食物加分多");/*设定游戏标题*/gtk_widget_set_usize(window,580,480);/*设置窗口大小*/gtk_widget_set_uposition(window,400,100);/*设定窗口位置*/g_signal_connect(GTK_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),N ULL);gtk_window_set_resizable(GTK_WINDOW(window),FALSE);/*不允许修改窗口大小*/fixed=gtk_fixed_new();/*创建固定容器构件*//*蛇与食物*/srand((int)time(0));/*设置随机数种子*/for(j=0;j<length;j++){snake[j]=gtk_button_new_with_label("ss");/*创建蛇身*/food[j]=gtk_button_new_with_label("food");/*创建食物*/gtk_widget_set_size_request(snake[j],side,side);/*蛇身尺寸*/gtk_widget_set_size_request(food[j],side,side);/*食物大小*/gtk_widget_modify_bg(snake[j], GTK_STATE_NORMAL,&color[0]);if((rand()%100+1)<=p_prize){gtk_widget_modify_bg(food[j],GTK_STATE_NORMAL,&color[(rand()%19 )+1]);for(j1=j+1;j1<2*length-12;j1++){prize[j1]++;}}}for(j=0;j<length;j++) /*将蛇身放在窗口的指定位置*/{gtk_fixed_put(GTK_FIXED(fixed),snake[j],snake_x[j]=side*(6-j),snake_y[j]=sid e);/*蛇身初始位置设定*/gtk_fixed_put(GTK_FIXED(fixed),food[j],food_x[j]=side*(rand()%10)+side,foo d_y[j]=side*((rand()%10))+side);/*食物位置随机设定,最好利用系统时间获得随机分布*/}for(j=0;j<6;j++) /*初始显示6节蛇身*/{gtk_widget_show(snake[j]);/*显示蛇身*/}gtk_widget_show(food[0]);/*显示第一个食物*//*键盘按键控制方向*/g_signal_connect(G_OBJECT(window), "key-press-event",G_CALLBACK(key_control), NULL);/*方向键鼠标控制*/for(j=0;j<4;j++){direction[j]=gtk_button_new_with_label(dir[j]);/*方向按键*/gtk_widget_modify_bg(direction[j], GTK_STATE_NORMAL, &color[10]);gtk_widget_set_size_request(direction[j],50,50);/*按键大小*/gtk_widget_set_sensitive(direction[j],FALSE);/*方向无效*/}/*4个方向键位置设置*/gtk_fixed_put(GTK_FIXED(fixed),direction[0],485,25);/*上键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[1],485,125);/*下键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[2],442,75);/*左键位置*/gtk_fixed_put(GTK_FIXED(fixed),direction[3],528,75);/*右键位置*//*4个方向键的功能设置*/g_signal_connect(GTK_OBJECT(direction[0]),"clicked",G_CALLBACK(up),NULL);g_signal_connect(GTK_OBJECT(direction[1]),"clicked",G_CALLBACK(down),NULL);g_signal_connect(GTK_OBJECT(direction[2]),"clicked",G_CALLBACK(left),NULL);g_signal_connect(GTK_OBJECT(direction[3]),"clicked",G_CALLBACK(right),NULL); /*显示4个方向键*/for(j=0;j<4;j++){gtk_widget_show(direction[j]);/*显示4个方向按键*/}/*游戏边界*/border_left=gtk_button_new();/*创建游戏范围左边界*/gtk_widget_set_sensitive(border_left,FALSE);/*设定左边界类型不敏感*/ border_right=gtk_button_new();/*创建游戏范围右边界*/gtk_widget_set_sensitive(border_right,FALSE);/*右边界不敏感*/border_up=gtk_button_new();/*创建游戏范围上边界*/gtk_widget_set_sensitive(border_up,FALSE);/*上边界不敏感*/border_down=gtk_button_new();/*创建游戏范围下边界*/gtk_widget_set_sensitive(border_down,FALSE);/*下边界不敏感*/gtk_widget_modify_bg(border_up, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_down, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_left, GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(border_right, GTK_STATE_NORMAL, &color[1]);gtk_fixed_put(GTK_FIXED(fixed),border_left,15,15);/*左边界加入固定容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_right,432,15);/*右边界加入固定容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_up,15,15);/*上边界加入固定>容器构件*/gtk_fixed_put(GTK_FIXED(fixed),border_down,15,432);/*将下边界加入固定容器构件*/gtk_widget_set_size_request(border_up,580,10);/*上边界尺寸*/gtk_widget_set_size_request(border_down,580,10);/*下边界尺寸*/gtk_widget_set_size_request(border_left,10,425);/*左边界尺寸*/gtk_widget_set_size_request(border_right,10,425);/*右边界尺寸*/gtk_widget_show(border_up);/*显示上边界*/gtk_widget_show(border_down);/*显示下边界*/gtk_widget_show(border_left);/*显示左边界*/gtk_widget_show(border_right);/*显示右边界*//*计分功能*/game_score_label=gtk_button_new_with_label("目前得分:");gtk_widget_modify_bg(game_score_label, GTK_STATE_NORMAL, &color[6]);gtk_widget_set_sensitive(game_score_label,FALSE);/*不敏感*/gtk_fixed_put(GTK_FIXED(fixed),game_score_label,15,440);/*放入固定容器构件*/gtk_widget_show(game_score_label);/*显示标签*/for(j=0;j<2*length-12;j++){game_score[j]=gtk_button_new_with_label(score[j]);gtk_widget_modify_bg(game_score[j], GTK_STATE_NORMAL, &color[7]);gtk_fixed_put(GTK_FIXED(fixed),game_score[j],80,440);}gtk_widget_show(game_score[0]);/*暂停|开始功能*/game_pause=gtk_button_new_with_label("暂停|开始");gtk_widget_modify_bg(game_pause, GTK_STATE_NORMAL, &color[13]);gtk_widget_set_size_request(game_pause,140,140);/*设定尺寸*/gtk_fixed_put(GTK_FIXED(fixed),game_pause,439,295);/*位置设定*/gtk_widget_set_sensitive(game_pause,FALSE);g_signal_connect(GTK_OBJECT(game_pause),"clicked",G_CALLBACK(show_pause) ,NULL);/*暂停|开始按键功能设置*/gtk_widget_show(game_pause);/*显示暂停|开始按键*//*游戏速度步进调节功能*/game_speed_label=gtk_button_new_with_label("游戏难度选择");gtk_widget_set_sensitive(game_speed_label,FALSE);/*标签不敏感*/game_speed[0]=gtk_button_new_with_label("1困难");/*快速按钮*/game_speed[1]=gtk_button_new_with_label("2一般");/*一般按钮*/game_speed[2]=gtk_button_new_with_label("3容易");/*慢速按钮*/gtk_widget_modify_bg(game_speed[0], GTK_STATE_NORMAL, &color[1]);gtk_widget_modify_bg(game_speed[1], GTK_STATE_NORMAL, &color[3]);gtk_widget_modify_bg(game_speed[2], GTK_STATE_NORMAL, &color[5]);gtk_fixed_put(GTK_FIXED(fixed),game_speed_label,465,190);/*速度调节标签位置*/for(j=0;j<3;j++){gtk_fixed_put(GTK_FIXED(fixed),game_speed[j],445+45*j,220);}/*速度按钮功能设置*/g_signal_connect(GTK_OBJECT(game_speed[0]),"clicked",G_CALLBACK(speed_con trol0),NULL);g_signal_connect(GTK_OBJECT(game_speed[1]),"clicked",G_CALLBACK(speed_con trol1),NULL);g_signal_connect(GTK_OBJECT(game_speed[2]),"clicked",G_CALLBACK(speed_con trol2),NULL);/*显示按钮*/gtk_widget_show(game_speed_label);for(j=0;j<3;j++){gtk_widget_show(game_speed[j]);}/*游戏通关*/win=gtk_button_new_with_label("!!!恭喜你!!!");/*通关提示*/gtk_widget_modify_bg(win, GTK_STATE_NORMAL, &color[9]);gtk_widget_set_size_request(win,200,100);/*通关提示大小*/gtk_fixed_put(GTK_FIXED(fixed),win,120,150);/*通关提示位置*/g_signal_connect(GTK_OBJECT(win),"clicked",G_CALLBACK(gtk_main_quit),NULL);/*设定点击游戏成功提示窗口后游戏关闭*//*游戏失败*/death=gtk_button_new_with_label("!!!你输了!!!");/*创建游戏失败提示*/ gtk_widget_modify_bg(death, GTK_STATE_NORMAL, &color[8]);gtk_widget_set_size_request(death,200,100);/*设置游戏失败提示大小*/gtk_fixed_put(GTK_FIXED(fixed),death,120,150);/*设定游戏失败提示位置*/g_signal_connect(GTK_OBJECT(death),"clicked",G_CALLBACK(gtk_main_quit),NUL L);/*设定点击游戏失败提示窗口后游戏关闭*//*显示游戏窗口*/gtk_container_add(GTK_CONTAINER(window),fixed);/*放入窗体*/gtk_widget_show(fixed);/*显示固定容器构件*/gtk_widget_show(window);/*显示窗体*/gtk_main();/*等待gtk_main_quit执行后正常退出程序*/}/*以下为回调函数部分*/gint function(gpointer data){int q;eat();/*调用吃食物函数*/if(!stop)/*判断是否处于暂停状态*/{switch(flag)/*判断当前运动方向标记值*/{case 0:if(snake_y[0]<48)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0],snake_y[0]-side);break;/*蛇未撞墙则把蛇头往运动方向移动一格*/ case 1:if(snake_y[0]>400)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0],snake_y[0]+side);break;/*蛇未撞墙蛇头往运动方向移动一格*/case 2:if(snake_x[0]<48)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0]-side,snake_y[0]);break;/*蛇未撞墙蛇头往运动方向移动一格*/case 3:if(snake_x[0]>400)/*蛇已撞墙*/{showdeath();break;/*显示游戏失败提示*/}gtk_fixed_move(GTK_FIXED(fixed),snake[0],snake_x[0]+side,snake_y[0]);break;/*蛇未撞墙蛇头往运动方向移动一格*/}for(j=length-1;j>0;j--)/*剩余蛇身位置处理*/{gtk_fixed_move(GTK_FIXED(fixed),snake[j],snake_x[j]=snake_x[j-1],snake_y[j]= snake_y[j-1]);/*后一节蛇身移至前一节蛇身的位置*/}switch(flag)/*根据当前运动方向改变蛇头位置坐标值*/{case 0:snake_y[0]=snake_y[0]-side;break;/*若向上则将y减去一节蛇身长度*/ case 1:snake_y[0]=snake_y[0]+side;break;/*若向下则将y加上一节蛇身长度*/ case 2:snake_x[0]=snake_x[0]-side;break;/*若向左则将x减去一节蛇身长度*/ case 3:snake_x[0]=snake_x[0]+side;break;/*若向右则将x加上一节蛇身长度*/ }}}gboolean key_control(GtkWidget *widget, GdkEventKey *event)//键盘{if(k==0)/*通过数字1 2 3选择难度*/{if(strcmp(gdk_keyval_name(event->keyval),"1")==0)speed_control0();else if(strcmp(gdk_keyval_name(event->keyval),"2")==0)speed_control1();else if(strcmp(gdk_keyval_name(event->keyval),"3")==0)speed_control2();}else if(k==1)/*游戏开始后回车键暂停和开始游戏*/{if(strcmp(gdk_keyval_name(event->keyval),"Return")==0) show_pause();}else if(k==-1)/*游戏结束后回车键退出游戏*/{if(strcmp(gdk_keyval_name(event->keyval),"Return")==0)gtk_main_quit();}if(!stop)/*暂停状态不记录键盘方向控制*/{if(strcmp(gdk_keyval_name(event->keyval),"Up")==0)up();else if(strcmp(gdk_keyval_name(event->keyval),"Down")==0)down();else if(strcmp(gdk_keyval_name(event->keyval),"Left")==0)left();else if(strcmp(gdk_keyval_name(event->keyval),"Right")==0)right();}}void up(void)/*按“上”方向键*/{if(flag!=1)/*当前运动方向不为“下”时才向上运动*/flag=0;/*修改方向标记*/}void down(void)/*按“下”方向键*/{if(flag!=0)/*当前运动方向不为“上”时才向下运动*/flag=1;/*修改方向标记*/}void left(void)/*按“左”方向键*/{if(flag!=3)/*当前运动方向不为“右”时才向左运动*/flag=2;/*修改方向标记*/}void right(void)/*按“右”方向键*/{if(flag!=2)/*当前运动方向不为“左”时才向右运动*/flag=3;/*修改方向标记*/}void show_pause(void)/*暂停|开始函数*/{if(i==0){stop=1;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*暂停时方向键无效*/}i=1;}else{stop=0;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*开始后方向键有效*/}i=0;}}void eat(void)/*吃食物函数*/{if(jieshu==length)/*蛇身长度已达极限,食物已吃完*/{stop=1;gtk_widget_hide(food[jieshu-6]);showwin();/*调用游戏通关处理函数*/}else if((snake_x[0]==food_x[jieshu-6])&&(snake_y[0]==food_y[jieshu-6]))/*判断是否成功吃到食物*/{gtk_widget_show(snake[jieshu]);/*蛇身增长一节*/gtk_widget_hide(food[jieshu-6]);/*除去本次所吃食物*/gtk_widget_hide(game_score[jieshu-6+prize[jieshu-6]]);/*除去上次得分*/ jieshu++;/*蛇身长度标记增长一节*/gtk_widget_show(game_score[jieshu-6+prize[jieshu-6]]);//新得分gtk_widget_show(food[jieshu-6]);/*显示下一个食物*/}}void speed_control0(void)/*游戏难度选择困难处理函数*/{gtk_widget_hide(game_speed[1]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[2]);/*隐藏其余难度值*/speed=0;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[0],FALSE);/*当前速度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void speed_control1(void)/*游戏难度选择一般处理函数*/{gtk_widget_hide(game_speed[0]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[2]);/*隐藏其余难度值*/speed=1;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[1],FALSE);/*当前难度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void speed_control2(void)/*游戏难度选择简单处理函数*/{gtk_widget_hide(game_speed[0]);/*隐藏其余难度值*/gtk_widget_hide(game_speed[1]);/*隐藏其余难度值*/speed=2;k=1;sign=g_timeout_add(op_speed[speed],function,data);/*创建定时器*/ gtk_widget_set_sensitive(game_speed[2],FALSE);/*当前难度不敏感*/ gtk_widget_set_sensitive(game_pause,TRUE);/*暂停|开始按钮有效*/ for(j=0;j<length;j++){gtk_widget_set_sensitive(snake[j],TRUE);gtk_widget_set_sensitive(food[j],TRUE);}for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],TRUE);/*使方向选择有效*/ }sleep(0.7);/*等待0.7S便于游戏者反应*/stop=0;/*开始游戏*/}void showwin(void)/*游戏通关处理函数*/{stop=1;for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*方向键无效*/}gtk_widget_set_sensitive(game_pause,FALSE);/*暂停键失效*/sleep(0.3);/*离开0.3S*/gtk_widget_show(win);/*显示通关提示*/k=-1;}void showdeath(void)/*游戏失败处理函数*/{gtk_timeout_remove(sign);for(j=0;j<4;j++){gtk_widget_set_sensitive(direction[j],FALSE);/*方向键无效*/}gtk_widget_set_sensitive(game_pause,FALSE);/*暂停键失效*/sleep(0.3);/*离开0.3S*/gtk_widget_show(death);/*显示失败提示*/k=-1;}。
C语言实现贪吃蛇小游戏
C语⾔实现贪吃蛇⼩游戏本⽂实例为⼤家分享了C语⾔实现贪吃蛇⼩游戏的具体代码,供⼤家参考,具体内容如下⼀、程序实现的原理:1、构造蛇⾝:定义⼀个坐标数组,存放的是蛇的每⼀节蛇⾝所在的坐标位置。
这样就将移动蛇⾝的操作转换为移动数组的操作,将吃⾷物增加蛇⾝体长度的操作转换为在数组后⾯追加元素的操作。
2、移动效果:每次移动时,将每⼀节蛇⾝(蛇头除外)依次往前移动⼀节,然后擦去蛇的最后⼀节,最后确定蛇头的⽅向,再绘制⼀个蛇头。
这样就会显⽰⼀个移动效果。
3、⾝体增加效果:每次移动时候,判断蛇头是否碰到了⾷物,如果碰到了⾷物,则吃掉它,并且只进⾏前移蛇⾝和增加蛇头的操作,不进⾏擦除蛇尾的操作(可以⽤⼀个标记变量判断是否吃掉了⾷物,然后在擦除蛇尾那⾥判断是否需要擦除蛇尾),这就会显⽰蛇⾝体增加的效果。
⼆、预备知识1、控制台窗⼝控制台窗⼝每⼀个位置都有它的坐标,且坐标系如下图所⽰(随箭头⽅向坐标逐渐增⼤)2、通过代码将光标移动到控制台指定位置这⾥⽤到了c语⾔windows编程中句柄的概念,不知道的可以百度。
实在不会也没关系,可以当做⼀个函数模板来使⽤,⽆需做太多了解。
#include <stdio.h>#include <Windows.h>//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}int main(){gotoxy(50,15);//将光标移动到控制台的(50,15)处printf("Hello World\n");system("pause");return 0;}从运⾏结果可以看到,程序在指定位置输出了待输出的内容。
C语言课程设计报告——贪吃蛇源程序
C 语言课程设计之杨若古兰创作(小游戏贪吃蛇的程序设计陈述)设计人:班级:201年月号目录一:概述1:研讨布景及意义2:设计的任务与须要常识点3:具体完成设计内容二:需求分析1:功能需求2:操纵方法三:整体设计1:模块划分2:数据结构设计四:具体设计1:主空摸块设计2:绘制游戏界面3:游戏的具体过程4:游戏的结束处理5:显示排行榜信息模块五:程序的调试与测试1:动画与音乐同步2:蛇的运转3:终止程序六:结论七::结束语八:程序清单九:参考文献一.概述本课程设计以软件工程方法为指导,采取了结构化,模块化的程序设计方法,以C说话技术为基础,使用TurboC++3.0为次要开发工具,对贪吃蛇游戏进行了需求分析,整体设计,具体设计,终极完成零碎的实现与测试.1.1 研讨的布景及意义随着社会的发展,人们生活的节奏日益加快,愈来愈多的人加入了全球化的世界.人们不再拘泥与一小块天地,加班,出差成了古代人不成防止的公务.而此时一款可以随时随地文娱的游戏成为了人们的须要.此次课程设计完成的贪吃蛇小游戏,恰是为了满足上述需求而设计出来的.贪吃蛇游戏虽小,却设计诸多的常识点.通过开发贪吃蛇游戏零碎,可使读者初步了解使用软件工程的和那个发,技术和工具开发软件的过程,进一步把握结构化,模块化的程序设计方法和步调,进一步把握整体数据结构设计,模块划分方法,把握局部变量,全局变量,结构体,共用体,数组,指针,文件等数据结构的使用方法,把握图形,声音,随机数等多种库函数的使用方法,进修动画,音乐,窗口,菜单,键盘等多项编程技术,进一步学会软件调试,测试,组装等软件测试方法,为后续课程的进修和将来实际软件开发打下坚实的基础.1.2 设计的任务和须要的常识点1.2.1 课程设计次要完成的任务1).通过编写“贪吃蛇游戏”程序,把握结构化,模块块化程序设计的思想,培养解决实际成绩的能力.2) 有同步播放动画,声音后果.3) 设计好数组元素与蛇,食物的对应关系.4) 随机发生食物.5) 有分数统计,排行榜,分数存储等功能.通过此次课程设计,但愿使读者能更深入的理解和把握课程教学中的基本概念,培养读者利用基本技术解决实际成绩的能力,从而进一步提高分析成绩和解决成绩的能力.1.2.3本次课程设计须要把握和应用如下的常识点:1) 数组的利用.2) 全局变量的使用.3) 按键处理.4)结构体的利用.5)图形,音乐和动画的有关常识.6)随即函数的使用.7)文件的基本出操纵.8) 结构化,模块化的设计方法.在本次课程设计中须要完成的任务有:包含命令,全局变量的定义和宏定义,函数声明等(50行),主控模块(MAIN函数,14行),动画,音乐播放模块(DRAWSNOW函数,3 3行),画出游戏开始界面模块,具体游戏过程模块,游戏结束处理模块.开发中工作量约为215行源代码.二 .需求分析贪吃蛇游戏是个简单的小游戏,能让游戏者的身心得到文娱,从而能够更好地投入到进修或工作当中.虽然此刻市面上出来这各种各样的游戏版本,可是贪吃蛇这类的小游戏其市场还是相当大的,因为它弄法简单易行,不管是手机,还是小游戏机,都能很顺利的运转.对于在外忙碌的人,不成能花费大量时间在文娱上,大型游戏是行欠亨的,如许的小游戏刚好逢迎了他们的需求.要开发贪吃蛇游戏程序,首先要分析改程序应实现哪些功能.对贪吃蛇游戏程序的功能需求可描述如下:程序运转后显示动画,音乐,按ESC 键退出游戏界面后,右边有一个矩形区,外游戏区域,在矩形区中有食物和贪食蛇,上方有统计分数及关数显示区域.蛇在封闭围墙利用绿色矩形暗示,围墙里随机的出现一个食物,通过按键盘四个光标键控制蛇向上,下,摆布四个方向挪动,蛇头撞到食物,则食物被吃掉,蛇身体长一节,接着又出现食物,等待蛇来吃.食物用一个点暗示,而且每次食物的地位都是随机出现的.游戏中要使贪吃蛇尽可能的长,但是不克不及使贪吃蛇撞到四周的墙壁,而且蛇的身体不克不及撞到一路,否则游戏结束.游戏中每吃掉一个食物要有积分,随着分数的添加可进入下一关,即使速度会加快.游戏结束时,如果分数进入前5名则从头排榜并存储.显示排行榜.因为有关贪吃蛇和食物的数据较多,而且关系密切,贪吃蛇及食物都是定义结构体数据类型,如许定义便于操纵与处理.2.2 操纵方法三 整体设计确定贪吃蛇游戏体系结构,给出整体模块结构图,确定程序的次要函数及之间的调用关系,同时设计蛇与游戏者等的数据结构.3.1 模块划分本程序采取结构化程序设计的方法,按照自顶向下,慢慢细化的方法对要解决的成绩进行逐层分解.首先画出顶层模块,即主控模块,之完成对基层模块的调用功能,即调用其他的功能模块;接着,按需求分析中的功能需求设计第一层模块,有音乐动画,图形驱动,画主界面,游戏过程,结束处理,退出等第6个次要功能;接着,画出第二层模块.整体模块结构如图6-1所示.3.1.1. 主控模块. 3.1.2. 动画音乐模块 3.1.3. 画主界面模块 3.1.4. 游戏过程模块 3.1.5. 游戏结束处理模块 3.1.6. 读取记录模块 3.1.7. 成绩排序模块 3.1.8. 写入文件模块 3.1.9. 排行榜模块 3.1.10. 退出3.2 整体数据结构设计设计思路:测序的关键在于暗示蛇的图形及蛇的挪动.用一个小局限性方块暗示蛇的一节身主 控 模 板 读取记录成绩排序写入文件排行榜动画音乐图形驱动退出结束处理 游戏过程画主界面体,身体每长一节,添加一个矩形块,蛇头业用同样的一节小矩形方块暗示挪动时必须从蛇可以上向前爬行,档案下无效方向键后,应先确定蛇头的地位,而后蛇的身体虽蛇头挪动,图形的实现是从身体新地位开始画出蛇.这时候,因为未清屏的缘由,本来的蛇的地位和新蛇的地位差一节蛇身,即看起来蛇多一节身体,所以将蛇的最初一节用布景色覆盖.食物的出现与消逝认识画矩形块和覆盖矩形块.为了便于理解,定义两个结构体:食物与蛇.上面介绍贪吃蛇游戏程序的次要数据结构.3.2.1 食物与蛇的数据结构暗示食物与蛇的矩形块设计为10*10个像素单位,食物的基本数据域为它所出现的地位,用X和Y坐标暗示,则矩形块用函数RECTANGLE(X,Y,X+10,Y+10)或RECTANGLE(X,Y ,X+10,Y-10)可以画出.因为每次只出现一个食物,所以设定YES暗示是否须要出现食物.YES=1暗示没有食物或食物曾经被蛇吃掉,须要画出食物.放置食物后,置YES=0.蛇的一节身体为一个矩形块,暗示矩形块只需左上角点坐标(X,Y).因为在游戏过程中蛇的身体不竭增加,需用数组存放每节坐标,最大设定为N=200,NODE暗示当前节数.DIRECTION是保管蛇的挪动方向的变量,其值可为1、2、3、4之一,分别暗示右、左、上、下的方向.LIFE是暗示生命的变量,LIFE=0暗示蛇活着,一旦LIFE=1,一旦LIFE=1,暗示蛇死,结束游戏.#define N 200Struct Food{ int x;int y;Int yes;}food;Struct Snake{ int x[N];Int y[N];Int node;Int derection;Int life;}snake;3.2.2 排行榜中优越者的数据结构排行榜次要记录优越者的姓名和成绩.为了存放排行榜信息,可定义如下的结构体类型,其中字符数组name成员存放优越者的姓名,整型变量score成员存放优越者的成绩.Struct person{ char name[20];Int score;};3.2.3 其他全局变量的定义Struct person per[5];Int score=0;Int gamespeed=400;3.2.4 符号常量的宏定义#define LEFT 0x4b00;#define RIGHT 0x4d00;#define DOWN 0x5000;#define UP 0x4800#define ESC 0x011b#define FILENAME四. 具体设计根据整体设计的模块功能和结构,完成所承担的程序模块的算法设计.给出每个模块的具体的算法,算法分别用传统流程图和文字说明来描述.4.1 主控模块main函数主函数是程序的主控模块.首先初始化图形零碎,然后使用drawsnow函数播放动画和声音,接着调用init函数初始化图形零碎,以后调用drawk函数画出游戏开始画面,在调用ga meplay函数,即开始了游戏的具体过程,游戏结束后调用endplay函数进行游戏结束处理;从文件中读取记录信息,排序,显示排行榜信息,最初关闭图形零碎,结束程序.主控模块的流程图如图6-2所示.其中带有两个竖线的矩形框暗示对自定义函数的调用.4.2函数主界面就是一个封闭的围墙,用两个轮回语句分别在水平方向和垂直方向输出连续的宽度和高的均为10个像素单位的距行小方块,围成封闭图形暗示围墙,为了夺目,设置为淡青色,用函数setlinestyle设直线型宽度为3个像素,设置3个像素的围墙线,.最初,在界面的左上部输出游戏程序的版本信息,在右上部输出游戏成绩(score)和关(level)的表头.4.3 游戏具体过程gameplay函数该函数是游戏的核心部分.游戏具体过程gameplay函数的大致算法流程图如图6-4所示.余下贱程图鄙人页4.3.1置这24.3.2while4.3.3这里的难点是暗示蛇的新地位并清除前一次的图形.采取的方法是每次挪动的时候从最初一节开始到第二节,将前一节的坐标值赋给后一节的坐标,挪动后只需把最初一节用布景色擦出即可,因为新地位0到n-1节还是要出此刻画面上的.这里用一个for轮回来确定蛇身的新坐标.4.3.4 吃到食物后的处理蛇吃到食物后,首先将食物擦除,即用布景色画出该食物,然后给蛇的节数加1,设置须要食物标记,是游戏成绩加10分,如果成绩达到50分的倍数,则给关数加1,并加快游戏速度.4.3.5 有按键判断蛇的方向这是一个内嵌的嵌套的条件选择结构,根据安东上下摆布键来设定蛇的挪动方向.其中1=向右,2=向左,3=向上,4=向下.判断是还考虑相反的方向键无效,比方蛇正在向上爬行,按下一键方向是无效的.4.4 游戏的结束处理木块ENDPLAY函数游戏结束时,应当用ENDPLAY函数进行游戏结束处理,其算法流程图如图6-5所示INI 其次,判断游戏者的成绩是否可以上排行榜.如果可以上榜,则画出淡蓝色矩形界面,在界面中输入游戏者姓名,对成绩进行赋值,然后调用 CompareScore 函数对记录排序,并调用Writefiles函数将记录写入排行榜帮文件;如果不克不及上榜,则直接在游戏界面输出不克不及上榜信息.最初,调用 pain_board 函数显示排行榜信息.函数void pain_board完成排行榜的绘制.五. 程序的调试与测试调试与测试软件的目标就是发现并改正潜伏的错误.一个程序,必须经过认真的调试和测试,才干尽量减少错误、包管程序满足功能、功能需求,达到最初的设计、使用请求,从而包管程序的开发质量.具体设计完成后,就可以用C说话根据各个模块的算法来设计程序,每个模块都要设计成一个自定义函数.几个模块可以放在一路构成一个原函数程叙文件,也能够一个模块构成一个源程叙文件.原程序设计好后,输入到计算机中,并存储到磁盘上;然后对每个源程叙文件都进行了独立编译和调试(具体代码可以参看程序清单);并针对分歧的模块程序设计测试用例进行单元测试;最初,将几个分别开发的模块组装在一路,构成一个完好的程序,进行集成测试,从而发现并改正了程序程序中存在的一些潜藏的错误,并使程序的容错能力大大加强.5.1 动画与音乐的同步播放预期结果:①片头在显示动画得同时播放音乐;②按任意键后进入游戏主界面;③进入游戏主界面后动画音乐同时停止.实际运转后果:满足①和②,不满足③,即进入游戏后仍然播放片头音乐.错误分析:程序中使用轮回播放动画,并在其轮回体中拔出发声函数以达到音乐和动画的同步.因为在结束动画时没有关闭扬声器,所以进入游戏界面后仍然发声.点窜:在动画播放完后加一条“nosound();”语句将扬声器关闭,成绩得到解决. 点窜后程序运转的实际后果与预期后果分歧.5.2 蛇的运转5.2.1 蛇撞到墙预期结果:蛇运转时如果撞到墙壁,则游戏结束.实际运后果:超出摆布墙壁后程序结束,但超出上面墙壁后仍然运转,如图6-9所示.错误分析:错误程序段在蛇运转中的条件判断语句中,其判断条件是:if(snake.x[0]<55|| snake.x[0]>595),即少了上、下两个方向的判断.点窜:在蛇的运转过程中添加两个逻辑表达式,判断蛇是否闯到上下的围墙.代码:If( snake.x[0]<55|| snake.x[0]>595|| snake.y[0]<55|| snake.y[0]>455)点窜后的程序运转结果与预期的结果分歧.5.2.2 蛇头闯到蛇身预期的结果:当蛇得头部与蛇身相撞时,游戏该当结束. 实际运转后果:蛇头撞到蛇身时,程序其实不终止.错误分析:在蛇的运转判断的程序出错,其代码如下Fori=3;i<snake.node;i++){ if(snake.x[i]=snake.x[0]&&snake.y[i]=snake.y[0]){snake.life=0;break;}}点窜:将轮回体中的snake.life=0改为snake.life=1;点窜后的结果与预期结果分歧.5.3 终止轮回经过对各个模块的调试和单元测试并点窜了错误后,将各个模块组装成一个零碎,并进行集成测试.在集成的过程中发现了一些错误,比方全局变量反复定义、函数反复声明等,分别进行了改正.最初连续运转了5次,以便测试该游戏程序的功能、功能是否达到了预期的目标,并根据所使用的具体机器对蛇的爬行速度进行适当的调整.测试内容包含蛇的运转、分数、关数、排行榜及排序、文件存储、音乐动画等功能,情况均正常.六. 结论通过2周的课程设计,在开发小组共同的努力下,终究完成了贪吃蛇游戏程序的开发任务.该游戏程序实现了用方向键控制蛇在围墙内爬行、随机发生食物、控制蛇吃掉食物并加分、控制游戏中闯关的数目和蛇的运转速度、实时显示得分和关数、结束时处理和显示排行榜等功能.该游戏程序具有界面敌对、操纵方便、控制精确和容错能力强等特点.这个贪吃蛇游戏还存在一些缺陷,还应当在如下几个方面加以改进.1)进入游戏后,到蛇死亡,只能玩一次就会退出程序.应加入多次游戏的控制能力.2)蛇的模样不美观,应将蛇头、蛇尾和蛇身进一步美化,使其更像真实的蛇.3)当分数达到400分时,蛇的速度变得非常快,一会儿就撞到围墙上了,应适当控制蛇的速度和关数,以便使游戏更具有吸引力.贪吃蛇游戏的编程练习思考数据结构:定义食物的坐标来控制它出现的地位,用一系列的函数时进行暗示,比方用函数rectangle来画出矩形,用life变量的值暗示蛇的生命,用direction变量的值暗示蛇挪动的方向等,还有效数组来存放蛇身各节的坐标,这些都让我们熟悉了对数组的操纵,此外还熟悉了各种函数的利用.贪吃蛇的设计有很多帮忙,进修编写贪吃蛇的游戏对把握C说话的常识有很大的帮忙.通过编程实践,还能拓展思路,让我们去寻觅须要调用那些函数,如何提高程序的质量等.要写出好的程序,须要我们有扎实的基础,如许碰到一些基本算法的时候就会熟能生巧了.在编程时我们要有丰富的想象力,不要拘泥与固定的思维方式,碰到成绩的时侯要多想几种解决成绩的方案.丰富的想象力是建立在丰富的常识基础上,所以我们要通过多个途径来帮忙本人建立较丰富的常识结构.在编程是我们碰倒了很多的困难,这就须要我们多与他人交流.在编程的过程中,我们也发现有良好的编程风格是十分次要的,至多在时间效力上就体现了这一点.养成良好的习气,代码的缩进编排,变量的命名规则要始终坚持分歧,这些都是提高我们编程能力的要点.在进行课程设计的过程中我们也学到了很多此外东西.首先,我们学会了合作,要以他人的目光看看成绩,或许如许得到的会比各自得到的都要多;其次,我们学会了分工,分工是为了更好地合作,分工才干提高合作的效力;最初,我们学会了奋斗,我们信任,通过四年的进修,我们必定能写出更精彩的程序,将来会描绘出更精彩的人生.在这里,我们要感谢指导课程设计的张凤君老师,给予我们悉心的指导.老师多次扣问编写进程,并为我们指导迷津,帮忙我们开拓研讨思路,精心点拨、热心鼓励.老师一丝不苟的工作风格,严谨求实的态度,踏踏实实的精神,不但受我以文,而且教我做人,给以毕生受益无量之道.我还要感谢我们开发小组的其他同学,在设计中他们给我很大的帮忙.恰是因为我们团结协作,才顺利的完成了课程设计任务.八.程序清单/*贪吃蛇游戏程序清单*/#include<stdio.h>#include<string.h>#include<time.h>#include<bios.h>#include<graphics.h>#include<conio.h>#include<stdlib.h>#include<dos.h>#define filename "c:\\person.dat" /*排行榜文件的文件全名*/#define esc 0x011b /*esc键*/#define n 200 /*蛇的最大节数*/#define left 0x4b00 /*左移方向键*/#define right 0x4d00 /*右移放向键*/#define down 0x5000 /*下移方向键*/#define up 0x4800 /*上移方向键*//*排行榜结构体*/struct person{int score; /*游戏者分数*/char name[20]; /*游戏者姓名*/}per[5];/*小蘑菇结构体*//*自定义的函数声明*/void drawmogu(); /*动画音乐函数*/void readfiles(); /*从文件中读取记录信息*/void writefiles(struct person *) ; /*将纪录写入文件中*/void initscorefiles(); /*初始化记录文件*/void comparescore(struct person); /*排行榜按分数进行排序*/void endplay(); /*游戏结束处理函数*/void paihb(); /*绘制排行榜函数*//*输出欢迎词并播放声音函数*/void pr(){ int s[15]={0,100,150,200,250,300,250,150,100,250,350};setcolor(change/10);/*改变欢迎词色彩*/settextstyle(0,0,4);outtextxy(20,200,"WELCOME TO OUR GAME");/*输出欢迎词*/sound(s[change/10]);/*使扬声器以括号内的频率发声*/}/*下雪的动画并同步播放音乐函数*/void DrawSnow(){ int i;int sx[62];selinestyle(SOLID_LINE,0,THICK_WIDTH);line(1,1,9,9);/*一次3行画出白色雪花的3条线*/line(0,5,10,5);line(9,1,1,9);save=malloc(200);/*在堆中申请200字节空间*/getimage(0,0,10,10,save);/*将雪花位图保管到save中*/cleardevice();/*清屏*/randomize();/*设置随机种子数*/for(i=0;i<62;i++)sx[i]=(i+2)*10/*计算雪花地位的横坐标数组*//*以下的键控while轮回控制播放音乐和下雪动画*/while(!kbhit())/*如果未按键,履行轮回体*/{ Pr();/*调用Pr函数输出欢迎词并播放声音*/if(snownum!=100){snow[snownum].speed=2+random(5);i=random(62);snow[snownum].x=sx[i];/*取横坐标*/snow[snownum].y=10-random(100);/*取纵坐标*/}/*轮回放置snownum个雪花*/for(i=0;i<snownum;i++)putimage(snow[i].x,snow[i].y,save,COPY_PUT);delay(100);/*延迟100ms以便看到雪花*/cleardevice();/*清屏*/Pr(); /*调用Pr函数输出欢迎词并播放声音*/if(snownum !=100) snownum++;setfillstyle(SOLID_FILL,15);for(i=0;i<snownum;i++) /*轮回画出snownum个雪花*/{ snow[i].y+=snow[i].speed;putimage(snow[i].x,snow[i].y,save,COPY_PUT);if(snow[i].y>500)snow[i].y=10-random(200);}change++;if(change==140) change=10;}nosound(); /*关闭扬声器*/cleardevice();/*清屏*/}/*图像零碎初始化函数*/void init(void){ int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc3\\BGI");cleardevice(); /*清屏*/}/*游戏开始界面,左上角坐标为(50,40),右下角坐标(610,460)的围墙*/ void drawk(void){int i;setcolor(BLUE);setlinestyle(SOLID_LINE,0,THICK_WIDTH); /*设置线性*/for(i=50;i<=600;i+=10) /*用轮回画围墙*/{setcolor(2*i+1);circle(i,40,5); /*画上边*/circle(i,451,5);circle(i,460,5); /*画下边*/}for(i=40;i<=450;i+=10){setcolor(2*i+1);circle(50,i,5); /*画右边*/circle(601,i,5);}for(i=40;i<=460;i+=10){setcolor(2*i+1);circle(41,i,5); /*画右侧*/circle(610,i,5);}setcolor(LIGHTCYAN);setlinestyle(SOLID_LINE,0,THICK_WIDTH);outtextxy(20,5," GREEDY SNAKE GAMES ji 11_1"); /*输出版本*/ outtextxy(480,10,"score level "); /*输出此文本*/}/*玩游戏具体过程*/void gameplay(void){food.yes=1; /*0暗示苹果曾经存在,1暗示须要出现新苹果*/snake.life=0; /*蛇活着*/int level=1; /*记录游戏等级*/char buffer[10]; /*字符数组用于转换整形数据*/randomize(); /*设置随机数的种子数*/snake.direction=1; /*方向向右*/snake.x[0]=110;snake.y[0]=100; /*蛇头坐标初值*/snake.x[1]=100;snake.y[1]=100; /*蛇身1节坐标初值*/snake.x[2]=90;snake.y[2]=100; /*蛇身2节坐标初值*/snake.node=3; /*蛇节数初值*/while(1) /*玩游戏死轮回,按esc键或蛇死时结束*/{ while(!kbhit()) /*在没有按键的情况下,蛇本人挪动身体*/{if(food.yes==1) /*须要出现新苹果*/{food.x=rand()%400+60; /*在墙内随机发生苹果横坐标*/food.y=rand()%350+60; /*在墙内随机发生苹果纵坐标*//*事物随机发生后必须让苹果能够在整格上,如许才干吃到*/ while(food.x%10!=0) food.x++;while(food.y%10!=0) food.y++;food.yes=0; /*画面上有苹果了*/}if(food.yes==0) /*画面上有苹果就要画出来*/{setcolor(GREEN);setfillstyle(SOLID_FILL,GREEN);circle(food.x,food.y,5);fillellipse(food.x,food.y,5,5);}setfillstyle(1,BLUE);bar(475,18,590,35); /*画出显示分数及关数蓝色矩形条*/setcolor(WHITE);itoa(score,buffer,10); /*将整形数据分数转换成字符串*/outtextxy(480,20,buffer); /*输出分数*/itoa(level,buffer,10); /*将整形数据关数转换成字符串*/outtextxy(560,20,buffer); /*输出关数*//*轮回使蛇的每一节往前挪动,这是贪吃蛇的“关键算法”*/for(i=snake.node-1;i>0;i--){snake.x[i]=snake.x[i-1];snake.y[i]=snake.y[i-1];}/*1、2、3、4暗示右、左、上、下四个方向,通过这个判断来挪动蛇头*/ switch(snake.direction){case 1:snake.x[0]+=10;break;case 2:snake.x[0]-=10;break;case 3:snake.y[0]-=10;break;case 4:snake.y[0]+=10;break;}/*判断蛇是否撞到墙*/if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<45||snake.y[0]>445){snake.life=1; /*置蛇死标记*/break;}/*从蛇的第四节开始判断是否撞到本人,*/for(i=3;i<snake.node;i++){ if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){snake.life=1; /*置蛇死标记*/break;}}if(snake.life==1) /*以上两种判断当前,如果蛇死就跳出内轮回*/break; /*跳出while(!kbhit)*/if(snake.x[0]==food.x&&snake.y[0]==food.y) /*吃到苹果当前*/{setcolor(BLACK); /*把画面上的苹果擦除*/circle(food.x,food.y,5);snake.node++; /*蛇的身体长一节*/food.yes=1; /*画面上须要出现新的苹果*/score+=10; /*没吃一个苹果添加10分*/if(score%50==0) /*吃够5个苹果进入下一关*/{level+=1; /*关数加1*/gamespeed-=60; /*控制速度的值减少60,以便加快速度*/}}setcolor(RED); /*画出红色蛇的轮回*/setfillstyle(SOLID_FILL,RED); /*用圆画出红色蛇头*/fillellipse(snake.x[0],snake.y[0],5,5);setcolor(GREEN);setfillstyle(SOLID_LINE,GREEN);circle(snake.x[0],snake.y[0],1); /*对蛇头填充绿色小圆作为眼睛*/setcolor(RED);setfillstyle(SOLID_FILL,BLUE);for(i=1;i<snake.node;i++) /*用圆画出红色蛇身*/{setcolor(RED);setfillstyle(SOLID_FILL,BLUE);fillellipse(snake.x[i],snake.y[i],5,5); /*对每节蛇身用蓝色填充*/setcolor(CYAN);circle(snake.x[i],snake.y[i],1); /*用青色小圆画在每节蛇身上*/}delay(gamespeed); /*延迟gamespeed毫秒,以便控制蛇的爬行速度*/setcolor(BLACK); /*用布景色黑色去除蛇的最初一节*/circle(snake.x[snake.node-1],snake.y[snake.node-1],5) ;setfillstyle(SOLID_FILL,BLACK);fillellipse(snake.x[snake.node-1],snake.y[snake.node-1],5,5);}if(snake.life==1) break; /*如果蛇死就跳出轮回*/key=bioskey(0); /*接收按键*/if(key==esc) break; /*按esc键退出*//*判断是否往相反的方向活动*/else if(key==up&&snake.direction!=4)snake.direction=3;else if(key==right&&snake.direction!=2)snake.direction=1;else if(key==left&&snake.direction!=1)snake.direction=2;else if(key==down&&snake.direction!=3)snake.direction=4;} /*endwhile(1)*/} /*结束游戏*//*读取文件操纵函数*/void readfiles(){FILE * fpread;/*如果文件不存在,则创建1个空文件,否则打开该文件*/if((fpread=fopen(filename,"ab+"))==NULL){printf("cant't open the file person.dat! ");exit(0);}if(fgetc(fpread)==EOF) /*如果文件内容为空*/initscorefiles(); /*调用函数进行记录初始化工作*/rewind(fpread); /*从头复位文件地位指针*/fread(per,sizeof(struct person),5,fpread);fclose(fpread); /*关闭排行榜文件*/}/*写入文件操纵函数*/void writefiles(struct person *tmp){FILE * fpwrite;/*以读写方式打开文件,文件内原本的数据将被清空*/if((fpwrite=fopen(filename,"wb+"))==NULL){printf("cant't open the file person.dat! ");exit(0);}fwrite(tmp,sizeof(struct person),5,fpwrite);fclose(fpwrite);}/*初始化记录函数*/void initscorefiles(){int i;struct person a[5];for(i=0;i<5;i++){a[i].score=0; /*5人的分数为0*/strcpy(a[i].name,"nobody"); /*5人的名为nobody*/}writefiles(a); /*调用记录写入函数*/}/*排序函数,如果玩家分数超出最低记录,则将玩家分数拔出到合适的地位,同时删除本来的最低记录 */void comparescore(struct person des)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 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;
}
}。