让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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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