让AI追逐最近的食物

我之前问过一个关于如何让AI在我的Agar.io克隆游戏中追逐食物的的问题,后来我自己解决了,但现在我无法让它追逐离它最近的食物。我尝试通过创建两个数组来存储食物细胞与电脑之间的(x, y)距离(如这个fiddle所示),但AI仍然会追逐更远的食物。以下是我代码的相关部分:

返回必要的值:

var x = [];var y = [];x.push(cell.x - computerX);y.push(cell.y - computerY);return [Math.min.apply(null, x), Math.min.apply(null, y)];

应用它们:

this.xxx = xy()[0];this.yyy = xy()[1];this.dist2 = Math.sqrt(this.xxx * this.xxx + this.yyy * this.yyy);this.speedX = (this.xxx / this.dist2) * this.speed.x;this.speedY = (this.yyy / this.dist2) * this.speed.y;computerX += 28 * this.speedX / computerRadius;computerY += 28 * this.speedY / computerRadius;

(注意:’xy’是返回这些值的函数)

如何让AI尝试吃离它最近的食物,而不是任意一个细胞?


回答:

对它们进行排序:

food.sort(function(cell1, cell2){    var a1 = cell1.x - computerX, b1 = cell1.y - computerY,        a2 = cell2.x - computerX, b2 = cell2.y - computerY,        cell1Dist = Math.sqrt(a1*a1 + b1*b1),        cell2Dist = Math.sqrt(a2*a2 + b2*b2);    return (cell1Dist > cell2Dist)? 1 : ((cell1Dist < cell2Dist)? -1 : 0)})

这假设food = [{x: 4, y: 3}, {x: 7, y: 9}...],并且computerYcomputerX已经设置,如您的问题中所述。

编辑:

您不需要使用sqrt。这很耗费资源,而且没有必要。试试这个替代方案:

calcDist = function(cell){    var a = cell.x - computer.x, b = cell.y - computer.y;    return a*a + b*b;}food.sort(function(cell, cell2){    return calcDist(cell) - calcDist(cell2);})

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注