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

合集下载

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

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

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

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

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

贪吃蛇 C语言代码

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

c语言贪吃蛇源码

c语言贪吃蛇源码

#include <stdio.h>#include <Windows.h>#include <conio.h>#include <time.h>#define MAX_WIDE 50 //宽#define MAX_HIGH 16 //高short randxy, score = 0; //score是所得分数static int dx = 1,dy = 0;int SLEEP;COORD coord;/*一、如果用户定义了COORD coord,那么coord其实是一个结构体变量,其中X和Y是它的成员,通过修改coord.X和coord.Y的值就可以实现光标的位置控制。

二、计算的时候按位计算,&两边操作数对应位上全为1时,结果的该位值为1。

否则该位值为0三、举例:short int a=8;a=a>>1;1.a=0 000 10002.右移一位后:a= 0 000 1003.补0:a=0 000 01004.化为十进制数:a=4*/struct Snake{short len;short body[MAX_WIDE*MAX_HIGH];}snake; //蛇的结构体/*********************测试函数********************/void test1(){coord.X = 0;coord.Y = 0;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar(getch());return;}void test2(){printf("(%d,%d)",dx,dy);}/***********************在制定位置设置出现****************************/void draw(){//画出蛇的身体for(short i = 0; i < snake.len; i++){coord.X = snake.body[i] & 127; //127二进制为:00000000 11111111coord.Y = snake.body[i] >> 8; // X等于body的低8位,Y等于body的高8位SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); //设置控制台光标位置,使光标到(x,y)putchar('*');}//画出最新点coord.X = randxy & 127;coord.Y = randxy >> 8;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);putchar('*');}/***********************控制snake函数********************/void run(){char key;short i, j;//snake.body[0]蛇头位置,while()条件指的是蛇在制定区域内,区域大小:MAX_WIDE*MAX_HIGHwhile( snake.body[0] > 0 && ( (snake.body[0] & 127) < MAX_WIDE) && (snake.body[0]>>8 < MAX_HIGH) ){for(;kbhit();) key = getch(); // kbhit()检查当前是否有键盘输入,若有则返回一个非0值,否则返回0switch(key){case 'w': dx = 0, dy = -1; break;case 's': dx = 0, dy = 1; break;case 'a': dx = -1, dy = 0; break;case 'd': dx = 1, dy = 0; break;}for(j = 1; j < snake.len; j++) // 蛇撞到自己会结束退出if(snake.body[j] == snake.body[0])return;if(randxy == snake.body[0]) //蛇吃到最新点的变动{snake.len++, score += 10;randxy = ((rand() % 16 + 0) <<8) | (rand() % 50 + 0); //原来的点被吃掉后产生新的点//rand()函数是产生随机数的一个随机函数//“|”按位或运算,在这里是指把(rand() % 16 + 0)这个八位二进制数向左移动8位,//尾部拼接上(rand() % 50 + 0)形成一个16位二进制数赋值给randxy }for(i = snake.len-1; i > 0; i--) //移动前准备,前一项赋值给后一项snake.body[i] = snake.body[i-1];//移动蛇身snake.body[0] = ((snake.body[0] & 127) + dx) | ((snake.body[0] >>8) + dy)<<8;draw();Sleep(SLEEP);system("cls");}}int main(){int level;again:snake.body[MAX_WIDE*MAX_HIGH] = 0;snake.body[0] = (MAX_HIGH/2)<<8 | MAX_WIDE/2;snake.len = 1;srand((unsigned)time(NULL)); //把系统时间作为种子,初始化// srand()它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。

贪吃蛇的c语言源程序

贪吃蛇的c语言源程序

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

贪吃蛇游戏代码(C语言编写)

贪吃蛇游戏代码(C语言编写)

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); }
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))
struct 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};

贪吃蛇游戏c语言源代码

贪吃蛇游戏c语言源代码
settextstyle(0,0,4);
outtextxy(160,220,"Game Over");
loop1:key=bioskey(0);
if(key==Enter)
{cleardevice();
TheFirstBlock();
}
else
if(key==ESC)
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);
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);
{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)
void Snake_Bodyadd(void);

C语言编写贪吃蛇游戏

C语言编写贪吃蛇游戏

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

C语言贪吃蛇代码

C语言贪吃蛇代码
x=y=17;
head->x=17;
head->y=17;
score=0;
ms=300;
for(int i=0;i<35;++i)
outtextxy(i,35,"▓");
outtextxy(2,41,"游戏速度");
outtextxy(4,42,"300");
outtextxy(8,42,"得分");
ontimer(tally[2],ms*2,AI());
}
}
void kmsg(UINT ch)
{
switch(ch)
{
case 72:
if(x&&!map[x-1][y])
move(--x,y);
else if(map[x-1][y]==2)
add(--x,y);
else
end();
break;
case 80:
break;
case 77:
if(ch!=75)
ch=77;
break;
}
if(GetKeyState(VK_SPACE)&0x80)//如果空格键是按下状态,将速度临时调整至60ms
ontimer(tally[0],60,kmsg(ch));
else
ontimer(tally[1],ms,kmsg(ch));//否则按照变量ms的速度运行游戏
head=head->n;
head->x=x;
head->y=y;
map[x][y]=1;
outtextxy(x,y,"■");

贪吃蛇C语言源代码

贪吃蛇C语言源代码

#include <stdio.h>#include <stdlib.h>#include <Windows.h>//windows编程头文件#include <time.h>#include <conio.h>//控制台输入输出头文件#ifndef __cplusplustypedef char bool;#define false 0#define true 1#endif//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }#define SNAKESIZE 100//蛇的身体最大节数#define MAPWIDTH 78//宽度#define MAPHEIGHT 24//高度//食物的坐标struct {int x;int y;}food;//蛇的相关属性struct {int speed;//蛇移动的速度int len;//蛇的长度int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标}snake;//绘制游戏边框void drawMap();//随机生成食物void createFood();//按键操作void keyDown();//蛇的状态bool snakeStatus();//从控制台移动光标void gotoxy(int x, int y);int key = 72;//表示蛇移动的方向,72为按下“↑”所代表的数字//用来判断蛇是否吃掉了食物,这一步很重要,涉及到是否会有蛇身移动的效果以及蛇身增长的效果int changeFlag = 0;int sorce = 0;//记录玩家的得分int i;void drawMap(){//打印上下边框for (i = 0; i <= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置{//将光标移动依次到(i,0)处打印上边框gotoxy(i, 0);printf("■");//将光标移动依次到(i,MAPHEIGHT)处打印下边框gotoxy(i, MAPHEIGHT);printf("■");}//打印左右边框for (i = 1; i < MAPHEIGHT; i++){//将光标移动依次到(0,i)处打印左边框gotoxy(0, i);printf("■");//将光标移动依次到(MAPWIDTH, i)处打印左边框gotoxy(MAPWIDTH, i);printf("■");}//随机生成初试食物while (1){srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致,因为一个字符占两个字节位置,若不一致//会导致吃食物的时候只吃到一半if (food.x % 2 == 0)break;}//将光标移到食物的坐标处打印食物gotoxy(food.x, food.y);printf("*");//初始化蛇的属性snake.len = 3;snake.speed = 200;//在屏幕中间生成蛇头snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数snake.y[0] = MAPHEIGHT / 2;//打印蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");//生成初试的蛇身for (i = 1; i < snake.len; i++){//蛇身的打印,纵坐标不变,横坐标为上一节蛇身的坐标值+2snake.x[i] = snake.x[i - 1] + 2;snake.y[i] = snake.y[i - 1];gotoxy(snake.x[i], snake.y[i]);printf("■");}//打印完蛇身后将光标移到屏幕最上方,避免光标在蛇身处一直闪烁gotoxy(MAPWIDTH - 2, 0);return;}void keyDown(){int pre_key = key;//记录前一个按键的方向if (_kbhit())//如果用户按下了键盘中的某个键{fflush(stdin);//清空缓冲区的字符//getch()读取方向键的时候,会返回两次,第一次调用返回0或者224,第二次调用返回的才是实际值key = _getch();//第一次调用返回的不是实际值key = _getch();//第二次调用返回实际值}/**蛇移动时候先擦去蛇尾的一节*changeFlag为0表明此时没有吃到食物,因此每走一步就要擦除掉蛇尾,以此营造一个移动的效果*为1表明吃到了食物,就不需要擦除蛇尾,以此营造一个蛇身增长的效果*/if (changeFlag == 0){gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每一节依次向前移动一节(蛇头除外)for (i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}//蛇当前移动的方向不能和前一次的方向相反,比如蛇往左走的时候不能直接按右键往右走//如果当前移动方向和前一次方向相反的话,把当前移动的方向改为前一次的方向if (pre_key == 72 && key == 80)key = 72;if (pre_key == 80 && key == 72)key = 80;if (pre_key == 75 && key == 77)key = 75;if (pre_key == 77 && key == 75)key = 77;/***控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*///判断蛇头应该往哪个方向移动switch (key){case 75:snake.x[0] -= 2;//往左break;case 77:snake.x[0] += 2;//往右break;case 72:snake.y[0]--;//往上break;case 80:snake.y[0]++;//往下break;}//打印出蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(MAPWIDTH - 2, 0);//由于目前没有吃到食物,changFlag值为0changeFlag = 0;return;}void createFood(){if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到食物{//蛇头碰到食物即为要吃掉这个食物了,因此需要再次生成一个食物while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机生成的食物不能在蛇的身体上for (i = 0; i < snake.len; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){flag = 0;break;}}//随机生成的食物不能横坐标为奇数,也不能在蛇身,否则重新生成if (flag && food.x % 2 == 0)break;}//绘制食物gotoxy(food.x, food.y);printf("*");snake.len++;//吃到食物,蛇身长度加1sorce += 10;//每个食物得10分snake.speed -= 5;//随着吃的食物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了食物,就不用再擦除蛇尾的那一节,以此来造成蛇身体增长的效果}return;}bool snakeStatus(){//蛇头碰到上下边界,游戏结束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return false;//蛇头碰到左右边界,游戏结束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return false;//蛇头碰到蛇身,游戏结束for (i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return false;}return true;}int main(){drawMap();while (1){keyDown();if (!snakeStatus())break;createFood();Sleep(snake.speed);}gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);printf("Game Over!\n");gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);printf("本次游戏得分为:%d\n", sorce);Sleep(5000);return 0;}。

贪吃蛇c语言代码

贪吃蛇c语言代码

贪吃蛇c语言代码#include <graphics.h>#include <conio.h>#include <stdlib.h>#include <dos.h>#define NULL 0#define UP 18432#define DOWN 20480#define LEFT 19200#define RIGHT 19712#define ESC 283#define ENTER 7181struct snake{int centerx;int centery;int newx;int newy;struct snake *next;};struct snake *head;int grade=60; /*控制速度的*******/int a,b; /* 背静遮的位置*/void *far1,*far2,*far3,*far4; /* 蛇身指针背静遮的指针虫子*/int size1,size2,size3,size4; /* **全局变量**/int ch=RIGHT; /**************存按键开始蛇的方向为RIGHT***********/int chy=RIGHT;int flag=0; /*********判断是否退出游戏**************/int control=4; /***********判断上次方向和下次方向不冲突***/int nextshow=1; /*******控制下次蛇身是否显示***************/int scenterx; /***************随即矩形中心坐标***************/int scentery;int sx; /*******在a b 未改变前得到他们的值保证随机矩形也不在此出现*******/int sy;/************************蛇身初始化**************************/void snakede(){struct snake *p1,*p2;head=p1=p2=(struct snake *)malloc(sizeof(struct snake));p1->centerx=80;p1->newx=80;p1->centery=58;p1->newy=58;p1=(struct snake *)malloc(sizeof(struct snake));p2->next=p1;p1->centerx=58;p1->newx=58;p1->centery=58;p1->newy=58;p1->next=NULL;}/*******************end*******************/void welcome() /*************游戏开始界面,可以选择速度**********/ {int key;int size;int x=240;int y=300;int f;void *buf;setfillstyle(SOLID_FILL,BLUE);bar(98,100,112,125);setfillstyle(SOLID_FILL,RED);bar(98,112,112,114);setfillstyle(SOLID_FILL,GREEN);bar(100,100,110,125);size=imagesize(98,100,112,125);buf=malloc(size);getimage(98,100,112,125,buf);cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(240,300,390,325);outtextxy(193,310,"speed:");setfillstyle(SOLID_FILL,RED);bar(240,312,390,314);setcolor(YELLOW);outtextxy(240,330,"DOWN");outtextxy(390,330,"UP");outtextxy(240,360,"ENTER to start..." );outtextxy(270,200,"SNAKE");fei(220,220);feiyang(280,220);yang(340,220);putimage(x,y,buf,COPY_PUT);setcolor(RED);rectangle(170,190,410,410);while(1){ if(bioskey(1)) /********8选择速度部分************/ key=bioskey(0);switch(key){case ENTER:f=1;break;case DOWN:if(x>=240){ putimage(x-=2,y,buf,COPY_PUT);grade++;key=0;}case UP:if(x<=375){ putimage(x+=2,y,buf,COPY_PUT);grade--;key=0;break;}}if (f==1)break;} /********** end ****************/ free(buf);}/*************************随即矩形*****************//***********当nextshow 为1的时候才调用此函数**********/void ran(){ int nx;int ny;int show; /**********控制是否显示***********/int jump=0;struct snake *p;p=head;if(nextshow==1) /***********是否开始随机产生***************/{show=1;randomize();nx=random(14);ny=random(14);scenterx=nx*22+58;scentery=ny*22+58;while(p!=NULL){if(scenterx==p->centerx&&scentery==p->centery||scenterx==sx&&scentery==sy) {show=0;jump=1;break;}elsep=p->next;if(jump==1)break;}if(show==1){putimage(scenterx-11,scentery-11,far3,COPY_PUT);nextshow=0;break;}}}/***********过关动画**************/ void donghua(){ int i;cleardevice();setbkcolor(BLACK);randomize();while(1){for(i=0;i<=5;i++){putpixel(random(640),random(80),13); putpixel(random(640),random(80)+80,2); putpixel(random(640),random(80)+160,3); putpixel(random(640),random(80)+240,4); putpixel(random(640),random(80)+320,1); putpixel(random(640),random(80)+400,14); }setcolor(YELLOW);settextstyle(0,0,4);outtextxy(130,200,"Wonderful!!"); setfillstyle(SOLID_FILL,10);bar(240,398,375,420);feiyang(300,400);fei(250,400);yang(350,400);if(bioskey(1))if(bioskey(0)==ESC){flag=1;break;}}}/*************************end************************//***********************初始化图形系统*********************/ void init(){int a=DETECT,b;int i,j;initgraph(&a,&b,"");}/***************************end****************************/ /***画立体边框效果函数******/void tline(int x1,int y1,int x2,int y2,int white,int black){ setcolor(white);line(x1,y1,x2,y1);line(x1,y1,x1,y2);setcolor(black);line(x2,y1,x2,y2);line(x1,y2,x2,y2);}/****end*********//*************飞洋标志**********/int feiyang(int x,int y){int feiyang[18][18]={ {0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,0,0,0}, {0,0,0,0,0,1,1,1,0,0,1,1,1,1,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0},{0,0,1,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0},{0,0,1,1,1,0,0,0,0,1,0,1,1,1,0,0,0,0},{0,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,0,0,1,1,0,0,1,1,0,0,1,0,0},{0,0,1,1,1,1,0,1,1,1,1,1,1,0,1,1,0,0},{0,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,0,0},{0,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0},{0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (feiyang[i][j]==1)putpixel(j+x,i+y,RED);}}/********"飞"字*************/int fei(int x,int y){int fei[18][18]={{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0},{0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0},{0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (fei[i][j]==1)putpixel(j+x,i+y,BLUE);}}/*********"洋"字**************/int yang(int x,int y){int yang[18][18]={{0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0}, {1,1,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0},{0,1,1,1,0,0,0,1,1,1,0,1,1,0,0,0,0,0},{0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,1,0,0},{0,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0},{0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,0,0,0},{0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,1,1,0},{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},{0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0}};int i,j;for(i=0;i<=17;i++)for(j=0;j<=17;j++){if (yang[i][j]==1)putpixel(j+x,i+y,BLUE);}}/******************主场景**********************/ int bort(){ int a;setfillstyle(SOLID_FILL,15);bar(49,49,71,71);setfillstyle(SOLID_FILL,BLUE);bar(50,50,70,70);size1=imagesize(49,49,71,71);far1=(void *)malloc(size1);getimage(49,49,71,71,far1);cleardevice();setfillstyle(SOLID_FILL,12);bar(49,49,71,71);size2=imagesize(49,49,71,71);far2=(void *)malloc(size2);getimage(49,49,71,71,far2);setfillstyle(SOLID_FILL,12);bar(49,49,71,71);setfillstyle(SOLID_FILL,GREEN);bar(50,50,70,70);size3=imagesize(49,49,71,71);far3=(void *)malloc(size3);getimage(49,49,71,71,far3);cleardevice(); /*取蛇身节点背景节点虫子节点end*/ setbkcolor(8);setfillstyle(SOLID_FILL,GREEN);bar(21,23,600,450);tline(21,23,600,450,15,8); /***开始游戏场景边框立体效果*******/ tline(23,25,598,448,15,8);tline(45,45,379,379,8,15);tline(43,43,381,381,8,15);tline(390,43,580,430,8,15);tline(392,45,578,428,8,15);tline(412,65,462,85,15,8);tline(410,63,464,87,15,8);tline(410,92,555,390,15,8);tline(412,94,553,388,15,8);tline(431,397,540,420,15,8);tline(429,395,542,422,15,8);tline(46,386,377,428,8,15);tline(44,384,379,430,8,15);setcolor(8);outtextxy(429,109,"press ENTER ");outtextxy(429,129,"---to start"); /*键盘控制说明*/outtextxy(429,169,"press ESC ");outtextxy(429,189,"---to quiet");outtextxy(469,249,"UP");outtextxy(429,289,"LEFT");outtextxy(465,329,"DOWN");outtextxy(509,289,"RIGHT");setcolor(15);outtextxy(425,105,"press ENTER ");outtextxy(425,125,"---to start");outtextxy(425,165,"press ESC ");outtextxy(425,185,"---to quiet");outtextxy(465,245,"UP");outtextxy(425,285,"LEFT");outtextxy(461,325,"DOWN");outtextxy(505,285,"RIGHT"); /*******end*************/ setcolor(8);outtextxy(411,52,"score");outtextxy(514,52,"left");setcolor(15);outtextxy(407,48,"score");outtextxy(510,48,"left");size4=imagesize(409,62,465,88); /****分数框放到内存********/ far4=(void *)malloc(size4);getimage(409,62,465,88,far4);putimage(500,62,far4,COPY_PUT); /*******输出生命框***********/setfillstyle(SOLID_FILL,12);setcolor(RED);outtextxy(415,70,"0"); /***************输入分数为零**********/outtextxy(512,70,"20"); /*************显示还要吃的虫子的数目*********/ bar(46,46,378,378);feiyang(475,400);fei(450,400);yang(500,400);outtextxy(58,390,"mailto:");outtextxy(58,410,"snake game");outtextxy(200,410,"made by yefeng");while(1){ if(bioskey(1))a=bioskey(0);if(a==ENTER)break;}}/******************gameover()******************/void gameover(){ char *p="GAME OVER";int cha;setcolor(YELLOW);settextstyle(0,0,6);outtextxy(100,200,p);while(1){if(bioskey(1))cha=bioskey(0);if(cha==ESC){flag=1;break;}}}/***********显示蛇身**********************/void snakepaint(){struct snake *p1;p1=head;putimage(a-11,b-11,far2,COPY_PUT);while(p1!=NULL){putimage(p1->newx-11,p1->newy-11,far1,COPY_PUT);p1=p1->next;}}/****************end**********************//*********************蛇身刷新变化游戏关键部分*******************/ void snakechange(){struct snake *p1,*p2,*p3,*p4,*p5;int i,j;static int n=0;static int score;static int left=20;char sscore[5];char sleft[1];p2=p1=head;while(p1!=NULL){ p1=p1->next;if(p1->next==NULL){a=p1->newx;b=p1->newy; /************记录最后节点的坐标************/ sx=a;sy=b;}p1->newx=p2->centerx;p1->newy=p2->centery;p2=p1;}p1=head;while(p1!=NULL){p1->centerx=p1->newx;p1->centery=p1->newy;p1=p1->next;}/********判断按键方向*******/if(bioskey(1)){ ch=bioskey(0);if(ch!=RIGHT&&ch!=LEFT&&ch!=UP&&ch!=DOWN&&ch!=ESC) /********chy为上一次的方向*********/ch=chy;}switch(ch){case LEFT: if(control!=4){head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}else{ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}chy=ch;break;case DOWN:if(control!=1){ head->newy=head->newy+22;head->centery=head->newy; control=3;if(head->newy>377)gameover();}else{ head->newy=head->newy-22; head->centery=head->newy;control=1;if(head->newy<47)gameover();}chy=ch;break;case RIGHT: if(control!=2){ head->newx=head->newx+22;head->centerx=head->newx;control=4;if(head->newx>377)gameover();}else{ head->newx=head->newx-22;head->centerx=head->newx;control=2;if(head->newx<47)gameover();}chy=ch;break;case UP: if(control!=3){ head->newy=head->newy-22;head->centery=head->newy;control=1;if(head->newy<47)gameover();}else{ head->newy=head->newy+22;head->centery=head->newy;control=3;if(head->newy>377)gameover();}chy=ch;break;case ESC:flag=1;break;}/* if 判断是否吃蛇*/if(flag!=1){ if(head->newx==scenterx&&head->newy==scentery){ p3=head;while(p3!=NULL){ p4=p3;p3=p3->next;}p3=(struct snake *)malloc(sizeof(struct snake));p4->next=p3;p3->centerx=a;p3->newx=a;p3->centery=b;p3->newy=b;p3->next=NULL;a=500;b=500;putimage(409,62,far4,COPY_PUT); /********** 分数框挡住**************/ putimage(500,62,far4,COPY_PUT); /*********把以前的剩下虫子的框挡住********/ score=(++n)*100;left--;itoa(score,sscore,10);itoa(left,sleft,10);setcolor(RED);outtextxy(415,70,sscore);outtextxy(512,70,sleft);nextshow=1;if(left==0) /************判断是否过关**********/donghua(); /*******如果过关,播放过关动画*********************/}p5=head; /*********************判断是否自杀***************************/ p5=p5->next;p5=p5->next;p5=p5->next;p5=p5->next; /****从第五个节点判断是否自杀************/while(p5!=NULL){if(head->newx==p5->centerx&&head->newy==p5->centery){ gameover();break;}elsep5=p5->next;}}}/************snakechange()函数结束*******************//*****************************主函数******************************************/ int main(){ int i;init(); /**********初始化图形系统**********/ welcome(); /*********8欢迎界面**************/ bort(); /*********主场景***************/ snakede(); /**********连表初始化**********/ while(1){ snakechange();if(flag==1)break;snakepaint();ran();for(i=0;i<=grade;i++)delay(3000);}free(far1);free(far2);free(far3);free(far4);closegraph();return 0;}。

C语言贪吃蛇源代码

C语言贪吃蛇源代码

C语言贪吃蛇源代码 TTA standardization office【TTA 5AB- TTAK 08- TTA 2C】#include<stdio.h>#include<process.h>#include<windows.h>#include<conio.h>#include<time.h>#include<stdlib.h>#define WIDTH 40#define HEIGH 12enum direction{//方向LEFT,RIGHT,UP,DOWN};struct Food{//食物int x;int y;};struct Node{//画蛇身int x;int y;struct Node *next;};struct Snake{//蛇属性int lenth;//长度enum direction dir;//方向};struct Food *food; //食物struct Snake *snake;//蛇属性struct Node *snode,*tail;//蛇身int SPEECH=200;int score=0;//分数int smark=0;//吃食物标记int times=0;int STOP=0;void Initfood();//产生食物void Initsnake();//构造snakevoid Eatfood();//头部前进void Addnode(int x, int y);//增加蛇身void display(struct Node *shead);//显示蛇身坐标void move();//蛇移动void draw();//画蛇void Homepage();//主页void keybordhit();//监控键盘按键void Addtail();//吃到食物void gotoxy(int x, int y)//定位光标{COORD pos;pos.X = x - 1;pos.Y = y - 1;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void Initsnake()//构造snake{int i;snake=(struct Snake*)malloc(sizeof(struct Snake));tail=(struct Node*)malloc(sizeof(struct Node));food = (struct Food*)malloc(sizeof(struct Food));snake->lenth=5;//初始长度 5snake->dir=RIGHT;//初始蛇头方向右for(i=2;i<=snake->lenth 2;i )//增加 5 个结点{Addnode(i,2);}}void Initfood()//产生食物{struct Node *p=snode;int mark=1;srand((unsigned)time(NULL));//以时间为种子产生随机数while(1){food->x=rand()%(WIDTH-2) 2;//食物X坐标food->y=rand()%(HEIGH-2) 2;//食物Y坐标while(p!=NULL){if((food->x==p->x)&&(food->y==p->y))//如果食物产生在蛇身上{//则重新生成食物mark=0;//食物生成无效break;}p=p->next;if(mark==1)//如果食物不在蛇身上,生成食物,否则重新生成食物{gotoxy(food->x,food->y);printf("%c",3);break;}mark=1;p=snode;}}void move()//移动{struct Node *q, *p=snode;if(snake->dir==RIGHT){Addnode(p->x 1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==LEFT){Addnode(p->x-1,p->y);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}if(snake->dir==UP){Addnode(p->x,p->y-1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}if(snake->dir==DOWN){Addnode(p->x,p->y 1);if(smark==0){while(p->next!=NULL){q=p;p=p->next;}q->next=NULL;free(p);}}}void Addnode(int x, int y)//增加蛇身{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;newnode->next=snode;newnode->x=x;newnode->y=y;snode=newnode;//结点加到蛇头if(x<2||x>=WIDTH||y<2||y>=HEIGH)//碰到边界{STOP=1;gotoxy(10,19);printf("撞墙,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}while(p!=NULL)//碰到自身{if(p->next!=NULL)if((p->x==x)&&(p->y==y)){STOP=1;gotoxy(10,19);printf("撞到自身,游戏结束,任意键退出!\n");//失败_getch();free(snode);//释放内存free(snake);exit(0);}p=p->next;}}void Eatfood()//吃到食物{Addtail();score ;}void Addtail()//增加蛇尾{struct Node *newnode=(struct Node *)malloc(sizeof(struct Node)); struct Node *p=snode;tail->next=newnode;newnode->x=50;newnode->y=20;newnode->next=NULL;//结点加到蛇头tail=newnode;//新的蛇尾}void draw()//画蛇{struct Node *p=snode;int i,j;while(p!=NULL){gotoxy(p->x,p->y);printf("%c",2);tail=p;p=p->next;}if(snode->x==food->x&&snode->y==food->y)//蛇头坐标等于食物坐标{smark=1;Eatfood();//增加结点Initfood();//产生食物}if(smark==0){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点}else{times=1;}if((smark==1)&&(times==1)){gotoxy(tail->x,tail->y);//没吃到食物清除之前的尾结点printf("%c",' ');//如果吃到食物,不清楚尾结点smark=0;}gotoxy(50,12);printf("食物: %d,%d",food->x,food->y);gotoxy(50,5);printf("分数: %d",score);gotoxy(50,7);printf("速度: %d",SPEECH);gotoxy(15,14);printf("按o键加速");gotoxy(15,15);printf("按p键减速");gotoxy(15,16);printf("按空格键暂停");}void HideCursor()//隐藏光标{CONSOLE_CURSOR_INFO cursor_info = {1, 0};SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info); }void Homepage()//绘主页{int x,y;HideCursor();//隐藏光标printf("----------------------------------------\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("|\t\t\t\t |\n");printf("----------------------------------------\n");gotoxy(5,13);printf("任意键开始游戏!按W.A.S.D控制方向");_getch();Initsnake();Initfood();gotoxy(5,13);printf(" ");}void keybordhit()//监控键盘{char ch;if(_kbhit()){ch=getch();switch(ch){case 'W':case 'w':if(snake->dir==DOWN)//如果本来方向是下,而按相反方向无效{break;}elsesnake->dir=UP;break;case 'A':case 'a':if(snake->dir==RIGHT)//如果本来方向是右,而按相反方向无效{break;}elsesnake->dir=LEFT;break;case 'S':case 's':if(snake->dir==UP)//如果本来方向是上,而按相反方向无效{break;}elsesnake->dir=DOWN;break;case 'D':case 'd':if(snake->dir==LEFT)//如果本来方向是左,而按相反方向无效{break;}elsesnake->dir=RIGHT;break;case 'O':case 'o':if(SPEECH>=150)//速度加快{SPEECH=SPEECH-50;}break;case 'P':case 'p':if(SPEECH<=400)//速度减慢{SPEECH=SPEECH 50;}break;case ' '://暂停gotoxy(15,18);printf("游戏已暂停,按任意键恢复游戏"); system("pause>nul");gotoxy(15,18);printf(" "); break;default:break;}}}int main(void)//程序入口{Homepage();while(!STOP){keybordhit();//监控键盘按键move();//蛇的坐标变化draw();//蛇的重绘Sleep(SPEECH);//暂时挂起线程}return 0;}。

C语言课程设计贪吃蛇源代码

C语言课程设计贪吃蛇源代码

C语言程序贪吃蛇代码#include<stdio.h>#include<windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#define N 21FILE *fp;int S;void boundary(void);//开始界面void end(void); //结束void gotoxy(int x,int y)//位置函数{COORD pos;pos.X=x;pos.Y=y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos); }void color(int a)//颜色函数{SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);}void init(int food[2])//初始化函数(初始化围墙、显示信息、苹果){system("cls");int i,j;//初始化围墙int wall[N+2][N+2]={{0}};//初始化围墙的二维数组for(i=1;i<=N;i++){for(j=1;j<=N;j++)wall[i][j]=1;}color(10);for(i=0;i<N+2;i++)//畵围墙{for(j=0;j<N+2;j++){if(wall[i][j])printf(" ");else printf("#") ;}printf("\n") ;}gotoxy(N+3,3);//显示信息color(14);printf("\t\t按a,b,c,d改变方向\n");gotoxy(N+3,1);color(14);printf("\t\t按任意键暂停,按1返回,按2退出\n"); gotoxy(N+5,3);color(14);printf("score:\n");food[0]=rand()%N+1;//随机出现食物food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");}void play()//具体玩的过程{system("cls");int i,j;int** snake=NULL;//定义蛇的二维指针int food[2];//食物的数组,food[0]代表横坐标,food[1]代表纵坐标int score=0;//为得分int tail[2];//此数组为了记录蛇的头的坐标int node=3;//蛇的节数char ch='p';srand((unsigned)time(NULL));//随机数发生器的初始化函数init(food);snake=(int**)realloc(snake,sizeof(int*)*node);//改变snake所指内存区域的大小为node长度for(i=0;i<node;i++)snake[i]=(int*)malloc(sizeof(int)*2);for(i=0;i<node;i++)//初始化蛇的长度{snake[i][0]=N/2;snake[i][1]=N/2+i;gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}while(1)//进入消息循环{gotoxy(5,0);color(10);printf("#");gotoxy(0,5);color(10);printf("#");gotoxy(0,7);color(10);printf("#");gotoxy(0,9);color(10);printf("#");tail[0]=snake[node-1][0];//将蛇的后一节坐标赋给tail数组tail[1]=snake[node-1][1];gotoxy(tail[0],tail[1]);color(0);printf(" ");for(i=node-1;i>0;i--)//蛇想前移动的关键算法,后一节的占据前一节的地址坐标{snake[i][0]=snake[i-1][0];snake[i][1]=snake[i-1][1];gotoxy(snake[i][0],snake[i][1]);color(14);printf("*\n");}if(kbhit())//捕捉输入信息gotoxy(0,N+2);ch=getche();}switch(ch){case 'w':snake[0][1]--;break;case 's':snake[0][1]++;break;case 'a':snake[0][0]--;break;case 'd':snake[0][0]++;break;case '1':boundary() ;break;case '2':end();break;default: break;}gotoxy(snake[0][0],snake[0][1]);color(14);printf("*\n");Sleep(abs(200-0.5*score));//使随着分数的增长蛇的移动速度越来越快if(snake[0][0]==food[0]&&snake[0][1]==food[1])//吃掉食物后蛇分数加1,蛇长加1 {score++;//分数增加S=score;node++;//节数增加snake=(int**)realloc(snake,sizeof(int*)*node);snake[node-1]=(int*)malloc(sizeof(int)*2);food[0]=rand()%N+1;//产生随机数且要在围墙内部food[1]=rand()%N+1;gotoxy(food[0],food[1]);color(12);printf("*\n");gotoxy(N+12,3);color(14);printf("%d\n",score);//输出得分}if(snake[0][1]==0||snake[0][1]==N+1||snake[0][0]==0||snake[0][0]==N+1)//撞到围墙后失败{gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);}}//从蛇的第四节开始判断是否撞到自己,因为蛇头为两节,第三节不可能拐过来for (i=3; i<node; i++){for(j=0;j<node;j++){if (snake[i][0]==snake[j][0] && snake[i][1]==snake[j][1]){gotoxy(N/2,N/2);color(30);printf("GAME OVER\n");for(i=0;i<node;i++)free(snake[i]);Sleep(INFINITE);exit(0);;}}}}void end()//结束函数{system("cls");system("cls");printf("EXIT\n");}void grade()//成绩记录函数{system("cls");int i=0;char s;if( (fp=fopen("f:\\贪吃蛇\\贪吃蛇.txt","ar") )==NULL)//打开文件{printf("\nCannot open file!\n");exit(0);}if(i<S)i=S;color(14);fwrite(&i,sizeof(i),1,fp);fclose(fp);printf("最高的分为:%d\n\n",i);printf("\t按1返回\n\n");printf("\t按2退出\n\n");s=getche();switch(s){case '1':boundary();break;case '2': end();break;}}void boundary()//开始界面{system("cls");char s;color(14);printf("\t\t欢迎来玩!!\n\n");printf("\t\t1:开始\n\n");printf("\t\t2:查看成绩\n\n");printf("\t\t3:退出\n\n");printf("\t\t请选择:");s=getche();switch(s){case '1': play();break;case '2': grade();break;case '3': end();break;}}int main(){boundary();getchar();return 0;}。

C语言贪吃蛇源代码

C语言贪吃蛇源代码

贪吃蛇的源码,用'A''S''D''W'操作#include<stdio.h>#include<stdlib.h>#include<time.h>#include<conio.h>typedef struct snake{int a;int b;struct snake *u;struct snake *n;}snake,*snake1;typedef struct food{int a;int b;}food;void main(){char c,c0 = 'd';int i,j,k,n=1,t,at;snake p,q;snake *dd,*dd0,*dd1,*dd2;food f;srand(time(NULL));p.u = NULL;p.n = &q;p.a = 5;p.b = 6;q.a = 5;q.b = 5; q.u = &p;q.n = NULL;dd=dd2= &q;f.a=(rand()%15+1);f.b=(rand()%15+1);while(1){srand(time(NULL));system("cls");for(i = 0;i < 17;i ++){for(j = 0; j < 17;j++){if(i == 0 )printf("▁");else if(i == 16)printf("▔");else if(j == 0)printf("▕");else if(j == 16)printf("▏");else if(i == p.a && j == p.b) printf("■");else if(i == f.a && j == f.b)printf("★");else{t = 0;dd = dd2;for(k = 0; k < n ;k++){if(i == dd->a && j == dd->b) {printf("□");t = 1;break;}dd = dd->u;}if(t == 0)printf(" ");}}printf("\n");}at = 0;dd =dd2;for(i=0;i<n;i++){if(p.a == dd->a && p.b == dd->b) {printf("game over!!\n");exit(0);}dd = dd->u;}if(p.a == f.a && p.b == f.b) {dd = dd2;at =1;f.a = (rand()%15+1);f.b = (rand()%15+1);for(i=0;i<n;i++){if(f.a == dd->a && f.b == dd->b) {f.a = dd2->a;f.b = dd2->b;break;}}n++;}if(kbhit()){c = getch();dd = dd2;if(c == 'w' && c0 != 's'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.a == 1)p.a = 15;elsep.a = (p.a-1)%15;}else if(c == 's' && c0 != 'w'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.a = (p.a%15)+1;}else if(c == 'a' && c0 != 'd'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.b == 1)p.b = 15;elsep.b = (p.b-1)%15;}else if(c == 'd' && c0 != 'a') {if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}p.b = (p.b%15)+1;}else{goto qq;}c0 = c;}else{qq: if(c0 == 'w'){if(at == 1){dd0 =(snake1)malloc(sizeof(snake)); dd0->a = dd2->a;dd0->b = dd2->b;dd0->n = NULL;dd0->u = dd2;dd2=dd0;}dd = dd2;for(i = 0; i<n ; i++){dd1 = dd->u;dd->b = dd1->b;dd->a = dd1->a;dd = dd->u;}if(p.a == 1)p.a = 15;elsep.a=(p.a-1)%15; 继续阅读。

贪吃蛇-c语言课程设计源码

贪吃蛇-c语言课程设计源码

贪吃蛇-c语言课程设计源码#define N 200#include <graphics.h>#include <stdlib.h>#include <dos.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011bint i,key;int score=0;/*得分*/int gamespeed=50000;/*游戏速度自己调整*/ struct Food{int x;/*食物的横坐标*/int y;/*食物的纵坐标*/int yes;/*判断是否要出现食物的变量*/ }food;/*食物的结构体*/struct Snake{int x[N];int y[N];int node;/*蛇的节数*/int direction;/*蛇移动方向*/int life;/* 蛇的生命,0活着,1死亡*/ }snake;void Init(void);/*图形驱动*/void Close(void);/*图形结束*/void DrawK(void);/*开始画面*/void GameOver(void);/*结束游戏*/void GamePlay(void);/*玩游戏具体过程*/void PrScore(void);/*输出成绩*//*主函数*/void main(void){Init();/*图形驱动*/DrawK();/*开始画面*/GamePlay();/*玩游戏具体过程*/Close();/*图形结束*/}/*图形驱动*/void Init(void){int gd=DETECT,gm;initgraph(&gd,&gm,"c:\\tc");cleardevice();}/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/ void DrawK(void){/*setbkcolor(LIGHTGREEN);*/setcolor(11);setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设置线型*/for(i=50;i<=600;i+=10)/*画围墙*/{rectangle(i,40,i+10,49); /*上边*/rectangle(i,451,i+10,460);/*下边*/}for(i=40;i<=450;i+=10){rectangle(50,i,59,i+10); /*左边*/ rectangle(601,i,610,i+10);/*右边*/ }}。

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语言代码,一个C语言写简单贪吃蛇源代码.doc

简单贪吃蛇c语⾔代码,⼀个C语⾔写简单贪吃蛇源代码.doc ⼀个C语⾔写简单贪吃蛇源代码#include#include#include#include#include#includeint grade=5,point=0,life=3;voidset(),menu(),move_head(),move_body(),move(),init_insect(),left(),upon(),right(),down(),init_graph(),food_f(),ahead(),crate(); struct bug{int x;int y;struct bug *last;struct bug *next;};struct fd{int x;int y;int judge;}food={0,0,0};struct bug *head_f=NULL,*head_l,*p1=NULL,*p2=NULL;void main(){char ch;initgraph(800,600);set();init_insect();while(1){food_f();Sleep(grade*10);setcolor(BLACK);circle(head_l->x,head_l->y,2);setcolor(WHITE);move_body();if(kbhit()){ch=getch();if(ch==27){ahead();set();}else if(ch==-32){switch(getch()){case 72:upon();break;case 80:down();break;case 75:left();break;case 77:right();break;}}else ahead();}else{ahead();}if(head_f->x==food.x&&head_f->y==food.y) {Sleep(100);crate();food.judge=0;point=point+(6-grade)*10;if(food.x<30||food.y<30||food.x>570||food.y>570)life++;menu();}if(head_f->x<5||head_f->x>595||head_f->y<5||head_f->y>595) {Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();}for(p1=head_f->next;p1!=NULL;p1=p1->next){if(head_f->x==p1->x&&head_f->y==p1->y){Sleep(1000);life--;food.judge=0;init_graph();init_insect();menu();break;}}if(life==0){outtextxy(280,300,"游戏结束!");getch();return;}move();};}void init_graph(){clearviewport();setlinestyle(PS_SOLID,1,5);rectangle(2,2,600,598);setlinestyle(PS_SOLID,1,1);}void set(){init_graph();outtextxy(640,50,"1、开始 / 返回");outtextxy(640,70,"2、退出");outtextxy(640,90,"3、难度");outtextxy(640,110,"4、重新开始");switch(getch()){case '1': menu();setcolor(GREEN);circle(food.x,food.y,2);setcolor(WHITE);return; case '2': exit(0);break;。

贪吃蛇C程序(gtk)

贪吃蛇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;}。

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码

《贪吃蛇》游戏程序代码1. 游戏初始化:设置游戏窗口、蛇的初始位置和长度、食物的初始位置等。

2. 蛇的移动:根据用户输入的方向键,更新蛇的位置。

确保蛇的移动不会超出游戏窗口的边界。

3. 食物的:在游戏窗口中随机食物的位置。

确保食物不会出现在蛇的身体上。

4. 碰撞检测:检测蛇头是否撞到食物或自己的身体。

如果撞到食物,蛇的长度增加;如果撞到自己的身体,游戏结束。

5. 游戏循环:不断更新游戏画面,直到游戏结束。

6. 游戏结束:显示游戏结束的提示,并询问用户是否重新开始游戏。

import random游戏窗口大小WIDTH, HEIGHT = 800, 600蛇的初始位置和长度snake = [(WIDTH // 2, HEIGHT // 2)]snake_length = 1食物的初始位置food = (random.randint(0, WIDTH // 10) 10,random.randint(0, HEIGHT // 10) 10)蛇的移动方向direction = 'RIGHT'游戏循环while True:更新蛇的位置if direction == 'UP':snake.insert(0, (snake[0][0], snake[0][1] 10)) elif direction == 'DOWN':snake.insert(0, (snake[0][0], snake[0][1] + 10)) elif direction == 'LEFT':snake.insert(0, (snake[0][0] 10, snake[0][1])) elif direction == 'RIGHT':snake.insert(0, (snake[0][0] + 10, snake[0][1]))检测碰撞if snake[0] == food:food = (random.randint(0, WIDTH // 10) 10, random.randint(0, HEIGHT // 10) 10)else:snake.pop()检测游戏结束条件if snake[0] in snake[1:] or snake[0][0] < 0 or snake[0][0] >= WIDTH or snake[0][1] < 0 or snake[0][1] >= HEIGHT:break游戏画面更新(这里使用print代替实际的游戏画面更新) print(snake)用户输入方向键direction = input("请输入方向键(WASD): ").upper() print("游戏结束!")。

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

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 0x011bint 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;}game;/*定义函数*/void init(void);/*定义图形驱动*/void close(void);/*定义关闭函数*/void drawk(void);/*定义界面函数*/void gameover(void);/*定义游戏结束函数*/void gameplay(void);/*定义游戏主函数*/void prscore(void);/*定义得分函数*/void main(void){/*主函数体,调用以下四个函数*/init();setbkcolor(7);drawk();gameplay();close();}void init(void){/*构建图形驱动函数*/int gd=DETECT,gm;initgraph(&gd,&gm,"");cleardevice();}void drawk(void){/*构建游戏界面函数*//*setbkcolor(LIGHTGREEN);*/char str3[50];setfillstyle(SOLID_FILL,BLUE);/*条型边框,显示版本信息*/ bar3d(48,9,610,38,1,45);setcolor(YELLOW);/*版本信息*/sprintf(str3,"Version:5.01,Powerwing Studio");outtextxy(330,20,str3);setfillstyle(LTSLASH_FILL,YELLOW);/*设定墙边的填充形式*/ bar3d(48,48,58,462,0,0);/*设定墙边*/bar3d(48,39,611,48,0,0);bar3d(48,452,611,462,0,0);bar3d(602,39,611,462,0,0);}void gameplay(void){/*构建游戏主函数*//*初始化游戏角色*/randomize();/*随机数发生器*/goods.yes=1;block.yes=1;food.yes=1;/*场景中需建立新的食物*/snake.life=1;/*初始化蛇生命值*/snake.direction=1;/*蛇起始的移动方向定义为向右*/snake.x[0]=100;snake.y[0]=100;/*蛇头的位置坐标初始化*/ snake.x[1]=110;snake.y[1]=100;snake.node=2;/*蛇初始化节数,共两节只有蛇头*//*初始化障碍物的数组*/block.x[0]=170;block.y[0]=270;/*level 1*/block.x[1]=410;block.y[1]=310;block.x[2]=300;block.y[2]=200;block.x[3]=320;block.y[3]=420;block.x[4]=250;block.y[4]=350;block.x[5]=220;block.y[5]=320;/*level 2*/block.x[6]=310;block.y[6]=410;block.x[7]=400;block.y[7]=500;block.x[8]=230;block.y[8]=230;block.x[9]=280;block.y[9]=280;block.x[10]=170;block.y[10]=280;/*level 3*/block.x[11]=420;block.y[11]=310;block.x[12]=310;block.y[12]=200;block.x[13]=320;block.y[13]=400;block.x[14]=250;block.y[14]=260;/*level 4*/block.x[15]=220;block.y[15]=330;block.x[16]=130;block.y[16]=410;block.x[17]=310;block.y[17]=510;block.x[18]=230;block.y[18]=340;block.x[19]=280;block.y[19]=380;block.x[20]=270;block.y[20]=170;/*level 5*/block.x[21]=410;block.y[21]=450;block.x[22]=190;block.y[22]=200;block.x[23]=150;block.y[23]=320;block.x[24]=270;block.y[24]=350;block.x[25]=340;block.y[25]=320;game.score=0;game.speed=50000;game.level=1;prscore();/*得分初始化*/while(1){/*判断为真可以按Esc退出循环结束游戏*/while(!kbhit()){/*无按键按下时,蛇自己移动身体*/if(game.level==1){/*画出障碍物*/for(j=0;j<5;j++){setcolor(5);/**/rectangle(block.x[j],block.y[j],block.x[j]+10,block.y[j]-10);block.yes=0;}}if(game.level==2){/*画出障碍物*/for(j=0;j<9;j++){setcolor(5);/**/rectangle(block.x[j],block.y[j],block.x[j]+10,block.y[j]-10); block.yes=0;}}if(game.level==3){/*画出障碍物*/for(j=0;j<14;j++){setcolor(5);/**/rectangle(block.x[j],block.y[j],block.x[j]+10,block.y[j]-10); block.yes=0;}}if(game.level==4){/*画出障碍物*/for(j=0;j<19;j++){setcolor(5);/**/rectangle(block.x[j],block.y[j],block.x[j]+10,block.y[j]-10); block.yes=0;}}if(game.level==5){/*画出障碍物*/for(j=0;j<25;j++){setcolor(5);/**/rectangle(block.x[j],block.y[j],block.x[j]+10,block.y[j]-10); block.yes=0;}}if(food.yes==1){/*需要画出新的食物*/food.x=rand()%400+60;/*获得间隔60的随机数食物坐标值*/food.y=rand()%350+60;while(food.x%10!=0)/*判断坐标值是否满足被10整除,否,自动增加*/ food.x++;while(food.y%10!=0)food.y++;food.yes=0;/*新的食物已经产生*/}if(goods.yes==1){/*需要画出新的宝物*/goods.x=rand()%380+60;/*获得间隔60的随机数宝贝坐标值*/goods.y=rand()%320+80;while(goods.x%10!=0)/*判断坐标值是否满足被10整除,否,自动增加*/ goods.x++;while(goods.y%10!=0)goods.y++;goods.yes=0;/*新的宝贝已经产生*/}if(goods.yes==0){/*新宝贝产生,应显示出来*/setcolor(0);/*擦除*/rectangle(goods.x,goods.y,goods.x+10,goods.y-10);delay(50);/*延时*/setcolor(YELLOW);goods.x=goods.x+random(10)-random(20);/*随机数增量*/goods.y=goods.y+random(10)-random(20);while(goods.x%10!=0)/*判断变化后的坐标值是否满足被10整除,否,自动增加*/goods.x++;while(goods.y%10!=0)goods.y++;rectangle(goods.x,goods.y,goods.x+10,goods.y-10);/*重画出宝贝*/if(goods.x<65||goods.x>585||goods.y<65|goods.y>445){/*判定宝贝是否越界*/setcolor(0);/*擦除越界的宝贝*/rectangle(goods.x,goods.y,goods.x+10,goods.y-10);goods.yes=1;/*越界后重新生成宝贝*/}}if(food.yes==0){/*新食物产生,应显示出来*/setcolor(GREEN);setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设定当前线型*/rectangle(food.x,food.y,food.x+10,food.y-10);}for(i=snake.node-1;i>0;i--){/*取得需重画的蛇的节数*/snake.x[i]=snake.x[i-1];/*最后一节的坐标值等于倒数第二节的坐标值*/ snake.y[i]=snake.y[i-1];}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;/*向下*/}for(i=3;i<snake.node;i++){/*超过4节后,判断蛇自身碰撞*/if(snake.x[i]==snake.x[0]&&snake.y[i]==snake.y[0]){/*即自身的任一节坐标值与蛇头坐标相等*/for(i=1;i<snake.node-1;i++){/*擦除自己碰撞后位置蛇的身子*/setcolor(0);rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10); rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);}snake.life-=1;/*生命值减少一*/snake.node-=5;prscore();/*输出结果*/if(snake.life==0){/*判断生命值是否为0*/gameover();/*游戏结束*/break;/*退出内循环*/}}}if(snake.x[0]<55||snake.x[0]>595||snake.y[0]<55||snake.y[0]>455){/*判断蛇是否与墙体碰撞*/for(i=1;i<snake.node-1;i++){/*擦除撞墙后位置蛇的身子*/setcolor(0);rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10); rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);}snake.x[0]=100;snake.y[0]=100;/*蛇头的位置坐标重新初始化*/snake.x[1]=110;snake.y[1]=100;snake.direction=1;/*蛇起始的移动方向定义为向右*/snake.life-=1;/*生命值减少一*/snake.node-=5;/*相应节数减少5节*/prscore();if(snake.life==0){gameover();break;}}/*判断蛇与障碍物碰撞,食物是否与障碍物重叠*/if(game.level==1){/*判断级别,并设定相应的障碍物数量,即数组个数*/ k=5;}else if(game.level==2){k=9;}else if(game.level==3){k=14;}else if(game.level==4){k=19;}else if(game.level==5){k=25;}for(j=0;j<k;j++){if(snake.x[0]==block.x[j]&&snake.y[0]==block.y[j]){for(i=1;i<snake.node-1;i++){/*擦除撞墙后位置蛇的身子*/setcolor(0);rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10); rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);}if(food.x==block.x[j]&&block.y[j]==food.y){/*防止障碍物与食物重叠*/ setcolor(0);/*设定食物的颜色为背景色,即擦除*/rectangle(food.x,food.y,food.x+10,food.y-10);food.yes=1;/*食物重新生成*/}snake.x[0]=100;snake.y[0]=100;/*蛇头的位置坐标重新初始化*/snake.x[1]=110;snake.y[1]=100;snake.direction=1;/*蛇起始的移动方向定义为向右*/snake.life-=1;snake.node-=5;prscore();if(snake.life==0){gameover();break;}}}if(snake.x[0]==food.x&&snake.y[0]==food.y){/*判断蛇是否吃到食物*/setcolor(0);/*设定食物的颜色为背景色,即擦除*/rectangle(food.x,food.y,food.x+10,food.y-10);snake.x[snake.node]=-20;/*新的一节放在不可见的位置*/snake.y[snake.node]=-20;snake.node++;/*蛇身增加一节*/if(snake.node>2){/*当节数每增加5节生命值增加一*/snake.life=1+fabs((snake.node-2)/5);}food.yes=1;/*场景需要增加食物*/game.score+=20;/*加分*/prscore();/*输出得分*/}if(snake.x[0]==goods.x&&snake.y[0]==goods.y){/*判定蛇是否得到宝贝*/ setcolor(0);/*设定宝贝的颜色为背景色,即擦除*/rectangle(goods.x,goods.y,goods.x+10,goods.y-10);goods.yes=1;/*场景需要增加新的宝贝*/game.score+=100;/*得到宝贝后加100分*/prscore();/*输出得分*/}if(game.score<500){/*设定游戏速度和难度级别*/game.speed=50000;game.level=1;}else if(game.score>=500&&game.score<1000){game.level=2;game.speed=40000;}else if(game.score>=1000&&game.score<1500){game.level=3;game.speed=30000;}else if(game.score>=1500&&game.score<2000){game.level=4;game.speed=20000; }else if(game.score>=5000){game.level=5;game.speed=10000;}setcolor(4);/*画出移动的蛇*/setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设定当前线型*/for(i=0;i<snake.node;i++)rectangle(snake.x[i],snake.y[i],snake.x[i]+10,snake.y[i]-10);delay(game.speed);setcolor(0);/*用背景色擦去最后一节*/rectangle(snake.x[snake.node-1],snake.y[snake.node-1],snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);} /*endwhile(! kbhit) */if(snake.life==0)/*判断循环结束条件:蛇死或者检测到Esc按键*/ break;key=bioskey(0);/*判断按键*/if(key==Esc)break;/*判断蛇头接收到的用户按键响应的移动方向*/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 gameover(void){/*游戏结束处理*/cleardevice();/*清屏*/prscore();/*输出得分*/setcolor(RED);/*打印出“Game Over”字样*/settextstyle(0,0,4);outtextxy(200,200,"Game Over!");getch();}void prscore(void){/*定义分数输出函数*/char str1[10];char str2[10];char str4[20];setfillstyle(SOLID_FILL,BLUE);/*用于清除旧的显示信息*/ bar(49,10,320,37);setcolor(WHITE);settextstyle(0,0,1);sprintf(str1,"score:%d",game.score);/*输出得分*/ outtextxy(55,20,str1);sprintf(str2,"level:%d",game.level);/*输出级别*/ outtextxy(250,20,str2);sprintf(str4,"life:%d",snake.life);/*输出级别*/ outtextxy(150,20,str4);}void close(void){/*定义关闭函数,退出图形模式*/getch();closegraph();}。

相关文档
最新文档