#include<stdio.h> #include<string.h> #include<stdlib.h> #include<time.h> #define SNAKE_MAX_LENGTH 20 #define SNAKE_HEAD 'H' #define SNAKE_BODY 'X' #define BLANK_CELL ' ' #define SNAKE_FOOD '$' #define WALL_CELL '*' //snake stepping: y = -1(up),1(down),0(no move); x = -1(left), 1(right), 0 (no move) voidsnake_move(); //put a food randomized on a blank cell voidput_money(void); // output the cells of the grid voidoutput(void); // outs when gameoverr intgameover(void); charmap[12][12]= { //画出贪吃蛇的游戏框大小 "************", "*XXXXH *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "************", }; int snake_location_x[SNAKE_MAX_LENGTH]={1,2,3,4,5}; //定义蛇的位置 int snake_location_y[SNAKE_MAX_LENGTH]={1,1,1,1,1}; int food_x;//定义食物的位置 int food_y;// int snake_length=5;//定义蛇的初始长度 int a=0;//吃到食物判定数据
蛇的移动
1 2 3 4 5 6 7 8 9
voidsnake_move(){//蛇移动 int i;// int 计算字符 map[snake_location_y[0]][snake_location_x[0]]=' '; for(i=0;i<snake_length-1;i++){ snake_location_x[i]=snake_location_x[i + 1]; //WHILE not 游戏结束 DO 蛇在x轴移动 snake_location_y[i]=snake_location_y[i + 1]; //WHILE not 游戏结束 DO 蛇在y轴移动 map[snake_location_y[i]][snake_location_x[i]]='X';// WHILE not 游戏结束 DO 蛇的身体移动 } }
放置食物的代码。
1 2 3 4 5 6 7 8 9 10 11
voidput_money(){ //投放食物 $ srand((unsigned)(time(NULL))); //利用时间函数 随机找空白位置投放食物 food_x=rand()%10+1; // WHILE not gameover 随机int 食物的x坐标 food_y=rand()%10+1; // WHILE not gameover 随机int 食物的y坐标 while(map[food_y][food_x]!=' ') { //WHILE 食物坐标位置不空白 DO 刷新食物 food_x = rand() % 10 + 1; food_y = rand() % 10+ 1; } map[food_y][food_x]='$'; // // WHILE not gameover DO 输出食物 }
判断游戏是否结束
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intgameover() { if(snake_location_x[snake_length-1]==11||snake_location_x[snake_length-1]==0) { //if 蛇撞墙 DO gameover return0; } if(snake_location_y[snake_length-1]==11||snake_location_y[snake_length-1]==0) { //if 蛇撞墙 DO gameover return0; } int i; for (i = 0; i < snake_length-1; i++) { if (snake_location_x[snake_length-1] == snake_location_x[i] && snake_location_y[snake_length-1] == snake_location_y[i]) { //if 蛇头和自己身体的坐标重合 DO gameover return0; } } return1; }