字符游戏-智能蛇

智能蛇与人工蛇的不同之处在于一个不需要手动输入字符,另一个则需要手动控制方向。因此两个蛇的移动的算法不相同。

先来看智能蛇在判定移动方向时的伪代码:
Head_x,Head_y: 头的位置
Food_x,Food_y:食物的位置
function whereGoNext(hx,hy,fx,fy) {
用数组move[4]={“a”,”d”,”w”,”s”} 记录可走的方向
用数组distance[4]={0,0,0,0} 记录离食物的距离
分别计算蛇头周边四个位置到食物的距离。H头的位置,F食物位置
例如:假设输入”a” 则distance[0] = |Food_x – (Head_x-1)| + |Food_y – Head_y|
如果 Head_x-1,Head_y 位置不是空白的,则 distance[0] = 9999
选择distance中存最小距离的下标p,注意最小距离不能是9999
返回 move[p]
}

则总控代码为:

输出字符矩阵
WHILE not 游戏结束 DO
wait(time)
ch=whereGoNext(Head_x,Head_y,Food_x,Food_y)
CASE ch DO
‘A’:左前进一步,break
‘D’:右前进一步,break
‘W’:上前进一步,break
‘S’:下前进一步,break
END CASE
输出字符矩阵
END WHILE
输出 GAME OVER!!!

// 在全局变量中用数组move[4]={“a”,”d”,”w”,”s”} 记录可走的方向,用数组distance[4]={0,0,0,0} 记录离食物的距离
char whereGoNext(int hx, int hy, int fx, int fy) {// Head_x,Head_y: 头的位置
// Food_x,Food_y:食物的位置(简单起见以hx,hy,fx,fy代替Head_x,Head_y,Food_x,Food_y)
int p = 0, min = 9999;
distance[0] = abs(fx - (hx - 1)) + abs(fy - hy);
distance[1] = abs(fx - (hx + 1)) + abs(fy - hy);
distance[2] = abs(fx - hx) + abs(fy - (hy - 1));
distance[3] = abs(fx - hx) + abs(fy - (hy + 1));

whereGoNext函数代码如下:
// 分别计算蛇头周边四个位置到食物的距离。Head头的位置,Food食物位置

if (distance[0] <= min && (map[hy][hx - 1] == ' ' || map[hy][hx - 1] ==' $')
 {
        min = distance[0];
        p = 0;
    }
if (distance[1] <= min && (map[hy][hx + 1] == ' ' || map[hy][hx + 1] == '$'))
 {
        min = distance[1];
        p = 1;
    }
if (distance[2] <= min && (map[hy - 1][hx] == ' ' || map[hy - 1][hx] == '$')) 
{
        min = distance[2];
        p = 2;
    }
if (distance[3] <= min && (map[hy + 1][hx] == ' ' || map[hy + 1][hx] == '$'))
 {
        min = distance[3];
        p = 3;
    }
// 选择distance中存最小距离的下标p,最小距离不能是9999
min = 9999;
return move[p];  // 返回 move[p]
}

至此,再结合原版贪吃蛇代码便可以做出一条智能(zhizhang)蛇了。
游戏效果如下:
这里写图片描述
GAME OVER!!!
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值