智能贪吃蛇
来源:互联网 发布:linux根目录创建文件 编辑:程序博客网 时间:2024/05/24 11:14
所谓智能蛇,就是自己动起来吃食物的蛇,下面给出代码的函数头:
#include <stdio.h>#include <stdlib.h>#include <time.h>#include <math.h>#define SNAKE_MAX_LENGTH 20#define SNAKE_HEAD 'H'#define SNAKE_BODY 'X'#define SNAKE_FOOD '$'#define WALL_CELL '*'#define MAP_LENGTH 12int snakeLength = 5;int snakeX[SNAKE_MAX_LENGTH] = {1,2,3,4,5};//record the x-axis every part of the body at the beginningint snakeY[SNAKE_MAX_LENGTH] = {1,1,1,1,1};//record the y-axis every part of the body at the beginningchar map[15][15] = //initial the map{ "************", "*XXXXH *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "* *", "************"};void Creat_Food();void Print();//when eating food or moving print the map once void Clear();//when the food is eaten clear itvoid Draw();//change the snakeint eatfood(int x, int y);//check whether the next step can eat the foodint is_ok(int x,int y);//check whether the next step can be executedvoid snakeMove(int x,int y);//next step have several selecions, analyse themint headi,headj,foodi,foodj;//record the location of the head of the snake and food;void find_head();//find where the head of the snake isvoid find_food();//find wher the food isint movable[4];//check which direction is availablevoid find_way();//find how to move next step int distance[4];//store four distancesvoid count_distance();void SmartSnake();
蛇移动 snakeMove
void snakeMove(int x,int y){ if(!is_ok(x,y)) { getchar(); printf("Sorry,GAME OVER! PUSH \"C\" TO CONTINUE\n"); getchar(); return ; } if(eatfood(x,y)) { Creat_Food(); } int i; for(i = 0; i < snakeLength-1; i++) { snakeX[i] = snakeX[i+1]; snakeY[i] = snakeY[i+1]; } snakeX[snakeLength-1] += x; snakeY[snakeLength-1] += y; Clear(); Draw();}
是否可行 is_ok
int is_ok(int x,int y){ int headX = snakeX[snakeLength-1]+x; int headY = snakeY[snakeLength-1]+y; int i; if(headX <= 0 || headX >= 11 || headY <= 0 || headY >= 11) return 0; if(map[headY][headX] == '*') return 0; for(i = 0; i < snakeLength; ++i) { int bodyX = snakeX[i]; int bodyY = snakeY[i]; if(headX == bodyX && headY == bodyY) return 0; } return 1;}
吃食物eat_food
int eatfood(int x, int y){ int headX = snakeX[snakeLength-1]+x; int headY = snakeY[snakeLength-1]+y; if(map[headY][headX] == '$') { snakeLength++; snakeX[snakeLength-1] = headX; snakeY[snakeLength-1] = headY; return 1; }return 0;}
实际上,多亏宿舍的大佬跟我讲思路并给我看了他的代码
这是他的博客:qq_40316686
大家可以去看看。
阅读全文