gpt4 book ai didi

javascript - 比较多个数组的各个值

转载 作者:行者123 更新时间:2023-11-28 09:12:50 25 4
gpt4 key购买 nike

您好,这是我第一次在这个网站上发帖,所以我会尽量说得清楚。

我正在使用 javaScript 创建战舰游戏来生成随机船舶放置。我为游戏板创建了两个数组(X 和 Y),创建了一个类来生成随机放置,并为不同的船只创建了一个对象数组,如下所示......

// game board
var xAxis = ["a","b","c","d","e","f","g","h","i","j"];
var yAxis = [1,2,3,4,5,6,7,8,9,10];

// Location Class decleration //

function Location (size,name){
//// Parameters ///////////////////////////////////////////
this.size = size;
this.name = name;
//// Class functions //////////////////////////////////////

// sets the ship to a random position
this.shipPosition = function(){
var orientation = Math.random();
var area = [];
if (orientation < 0.5){
x = Math.floor(Math.random()*(xAxis.length-size+1));
y = Math.floor(Math.random()*(yAxis.length));
for (i=x; i < (size + x); i++){
area.push([xAxis[i],yAxis[y]]);
}
} else {
x = Math.floor(Math.random()*(xAxis.length));
y = Math.floor(Math.random()*(yAxis.length-size+1));
for (i=y; i < (size + y); i++){
area.push([xAxis[x],yAxis[i]]);
}
}
return area;
};
///// Stored variables /////////////////////////////////////////

//stores position
var positionArray = this.shipPosition();
//assigns value to each element in array for checking
//and makes the private value public. ex. a = ['h',1]
var a = positionArray[0];
var b = positionArray[1];
var c = positionArray[2];
var d = positionArray[3];
var e = positionArray[4];
this.getA = a;
this.getB = b;
this.getC = c;
this.getD = d;
this.getE = e;

// locator console logging function

this.whereIs = function(){
console.log(this.name);
console.log("ship size is "+ size);
console.log("-- X - Y --");
console.log(a);
console.log(b);
if (size > 2){console.log(c);}
if (size > 3){console.log(d);}
if (size > 4){console.log(e);}
console.log(" *********************************** ");
};
}
//ship array
var computerShip = new Array();
computerShip[0] = new Location(2, "SHIP 1");
computerShip[1] = new Location(3, "SHIP 2");
computerShip[2] = new Location(3, "SHIP 3");
computerShip[3] = new Location(4, "SHIP 4");
computerShip[4] = new Location(5, "SHIP 5");

//used to call whereIs method for each ship

var genetateComputerShip = function(){
for(i=0; i<computerShip.length; i++){
computerShip[i].whereIs();
}
};
genetateComputerShip();

如何检查船舶数组的每个值以检查是否重叠?我尝试了多种方法,但在挑选元素或找到一种轻松交叉引用它们的方法时遇到了麻烦。有什么想法吗?

最佳答案

我对您的代码进行了一些更改,以维护全局“板”概念,该概念表示为多维数组。请参阅此处的代码:

http://jsfiddle.net/mchail/ytwyS/1/

点击“运行”后,检查浏览器的 JavaScript 控制台,您应该在完整棋盘的末尾看到每艘船都已放置的打印输出。我修改了 shipPosition(现在称为 setShipPosition),以便在放置船舶之前检查板上的冲突。

顺便说一句,干得好!

更新

修改了 jsfiddle 以将板也打印到屏幕上。继续点击“运行”即可查看更多随机生成的棋盘。

关于javascript - 比较多个数组的各个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com