WillKen's Blog.

贪吃蛇(字符版)

Word count: 896Reading time: 3 min
2017/12/26 Share

贪吃蛇(字符版)

  “贪吃蛇游戏将会伴随你的大学四年”,软导老师如是说道。身为大一萌新,我只做了最最最简单的字符版贪吃蛇。在这篇文章中,我将向大家介绍字符版贪吃蛇的游戏设计及部分算法。

设计要求

  首先,明确设计要求:

1、玩法
  贪吃蛇游戏是一款经典的益智游戏,有PC和手机等多平台版本。既简单又耐玩。该游戏通过控制蛇头方向吃蛋,从而使得蛇变得越来越长。
2、游戏表示
  给定一个1010的字符矩阵表示蛇的生存空间,其中有一条长度5的蛇(HXXXX), “H”表示蛇头,“X”表示蛇身体。空间中可能有食物(“$”表示)和障碍物(“”表示)
你可以使用“ADWS”按键分别控制蛇的前进方向“左右上下”, 当蛇头碰到自己的身体或走出边界,游戏结束,否则蛇按你指定方向前进一步。

编程思想

  自顶向下,逐步求精。将游戏分为不同的几块(函数)。例如,移动、放置食物、打印、是否死亡的判定等。
  先写好总框架,再逐步完善各个函数。

代码及算法简介

  定义良好的头部,将使得程序更加易于阅读,易于维护。包括:常数定义、函数定义等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#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)
void snake_move();
//put a food randomized on a blank cell
void put_money(void);
// output the cells of the grid
void output(void);
// outs when gameoverr
int gameover(void);
char map[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
void snake_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
void put_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
int gameover()
{
if(snake_location_x[snake_length-1]==11||snake_location_x[snake_length-1]==0)
{ //if 蛇撞墙 DO gameover
return 0;
}
if(snake_location_y[snake_length-1]==11||snake_location_y[snake_length-1]==0)
{ //if 蛇撞墙 DO gameover
return 0;
}
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
return 0;
}
}
return 1;
}

  当然,还有主函数、结果输出、蛇的身体边长等函数,就不在这里一一赘述了。

效果图

  以上就是我的字符版贪吃蛇的介绍了,算法有些麻烦,大佬们见笑了。

CATALOG
  1. 1. 贪吃蛇(字符版)
    1. 1.0.0.1. 设计要求
    2. 1.0.0.2. 编程思想
    3. 1.0.0.3. 代码及算法简介
    4. 1.0.0.4. 效果图