贪吃蛇大家都很熟悉,即控制一条蛇,让那条蛇吃到果子,然后蛇的身体会自动变长一截,并获得相应的分数,在这个过程中,不能让蛇的头部撞到墙壁,同时也不能让蛇自己咬到自己,否则,游戏就会结束。
而智能蛇,则比贪吃蛇更加高级,顾名思义,是让蛇有一定的智能,让蛇自己决策,自己行动。当然,进一步的,还可以让蛇与另一条蛇抢夺食物。
上图就是对智能蛇的简单描述,它比传统的贪吃蛇更加高级。
在简单的贪吃蛇游戏里面,我们已经知道了如何去让蛇移动,如何让蛇吃到果子,并让他的身体随着吃到果子而变长,以及决定游戏如何结束。而智能蛇相比于传统的贪吃蛇,则还要加上更多的元素,加入新的算法。
static struct termios ori_attr, cur_attr;
static __inline
int tty_reset(void)
{
if (tcsetattr(STDIN_FILENO, TCSANOW, &ori_attr) != 0)
return -1;
return 0;
}
static __inline
int tty_set(void)
{
if ( tcgetattr(STDIN_FILENO, &ori_attr) )
return -1;
memcpy(&cur_attr, &ori_attr, sizeof(cur_attr) );
cur_attr.c_lflag &= ~ICANON;
// cur_attr.c_lflag |= ECHO;
cur_attr.c_lflag &= ~ECHO;
cur_attr.c_cc[VMIN] = 1;
cur_attr.c_cc[VTIME] = 0;
if (tcsetattr(STDIN_FILENO, TCSANOW, &cur_attr) != 0)
return -1;
return 0;
}
static __inline
int kbhit(void)
{
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 0;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1) {
perror("select()");
return 0;
} else if (retval)
return 1;
/* FD_ISSET(0, &rfds) will be true. */
else
return 0;
return 0;
}
//将你的 snake 代码放在这里
int main()
{
//设置终端进入非缓冲状态
int tty_set_flag;
tty_set_flag = tty_set();
//将你的 snake 代码放在这里
printf("pressed `q` to quit!\n");
while(1) {
if( kbhit() ) {
const int key = getchar();
printf("%c pressed\n", key);
if(key == 'q')
break;
} else {
;// fprintf(stderr, "<no key detected>\n");
}
}
//恢复终端设置
if(tty_set_flag == 0)
tty_reset();
return 0;
}
上面的则是实现kbhit()的代码,而对于我们这些初学者来说,要知道把蛇的代码放到哪里并将它运行出来即可。
while (1) {
int cx[800]; int cy[800]; memcpy(cx, x, sizeof(int)*len); memcpy(cy, y, sizeof(int)*len);
if (s == ‘w’) { x[0]–; move = 1; if (x[0] <= 0) { printf(“Game over\n”); break; } }
else if (s == ‘s’) { x[0]++; move = 1; if (x[0] >= 19) { printf(“Game over\n”); break; } }
else if (s == ‘a’) { y[0] –; move = 1; if (y[0] <= 0) { printf(“Game over\n”); break; }
else if (s == ‘d’) { y[0]++; move = 1; if (y[0] >= 39) { printf(“Game over\n”); break; } }
int i; for (i = 1; i < len; i++) { x[i] = cx[i - 1]; y[i] = cy[i - 1]; }
上面这段代码,则是记录蛇的方向得到一段代码,而在智能蛇中则要加以改进
// Hx,Hy: 头的位置
// Fx,Fy:食物的位置
function whereGoNext(Hx,Hy,Fx,Fy) {
// movable[4]={“a”,”d”,”w”,”s”} 记录可走的方向
// distance[4]={0,0,0,0} 记录离食物的距离
// 分别计算蛇头周边四个位置到食物的距离。H头的位置,F食物位置
// 如果 Hx-1,Hy 位置不是Blank,则 distance[0] = 9999
// 选择distance中存最小距离的下标p,
// 返回 movable[p]
}
上面,则是控制智能蛇的伪代码。