最近整理下电脑,看到了自己在上个学期打的贪吃蛇游戏的c代码,觉得真的是略微有点冗长,但是实现起来应该也算是比较好理解,于是把自己的代码搬上来,网络上写贪吃蛇的c语言的文章很多,我这篇也仅是给大家作为一个参考而已。
我的代码是在Windows下运行的,因为需要用到windows.h这个库。
然后也做了一个简单的ai模式,这在没有障碍物的情况下前期还是蛮不错的,但是到了后期蛇变长了之后就会有bug了。
好了,直接上代码吧:
1)头文件和宏定义
#include
#include
#include
#include
#include
#define SNAKE_MAX_LENGTH 20
#define SNAKE_HEAD 'H'
#define SNAKE_BODY 'X'
#define BLANK_CELL ''
#define SNAKE_FOOD '$'
#define WALL_CELL '*'
2)各种实现函数的声明
/*snake stepping: dy = -1(up) 1(dowm) 0(no move); dx = -1(left), 1(right), 0(no move)*/
void snakemove(int, int);
//to write dowm the current location of the snake
void put_money(void);
void output(void);
// to put the current map on the screen
void initial_the_game(void);
void put_accelerate(void);
// @ is a special food which can speed up your snake.
int judge(int, int);
/* when it comes to ai, it is used to judge whether the next step is movable. */
int dis(int, int);
// when it coomes to ai, it is used to calculate the current distence //between the snake head and the food.
void welcome(void); // the game introduction.
void gameover(void);
void edition_handed(void);
// the edition in which you can play by yourself.
void edition_presentation(void);
// the edition in which the snake can go automatically.
3)各种全局变量
// define vars for snake,notice name of vars in c
int snakeX[SNAKE_MAX_LENGTH] = {1, 2, 3, 4, 5};
int snakeY[SNAKE_MAX_LENGTH] = {1, 1, 1, 1, 1};
int snakeLength = 5;
int gamestate = 1;
int current_speed = 600;
int score = 0;
char edition_choose; // for player to choose the edition.
int con = 1; // to judge the initial state of the game;
int energy = 0; // write down the condition to accelerate by eating $.
//the following part is to realize the simple ai .
const char movable[4] = {'a', 'd', 's', 'w'};
int distance[4] = {9999, 9999, 9999, 9999};
int fx = 6, fy = 6; // the coordinate of the food $
4)地图
char map[12][12] =
{"************",
"*XXXXH *",
"* *",
"* *",
"* *",
"* *",
"* $ *",
"* *",
"* @ *",
"* *",
"* *",
"************"};
5)主函数(可选模式)
int main() {
while (con) {
welcome