我一直在Javascript中制作战舰游戏,在地图上水平/垂直放置3个长度为3个区块的随机船只。
这是我创建字段并在其上放置1艘船的方式
function Ship (size, direction) {
this.coveredFields = [];
this.place = function (sizeY, sizeX) { // sizeX & sizeY: size of fields in both dimensions
// pick randomly within our limits
var locationX;
var locationY;
if (direction) {
locationX = Math.floor(Math.random() * (sizeX - 1 - size));
locationY = Math.floor(Math.random() * (sizeY - 1));
} else {
locationX = Math.floor(Math.random() * (sizeX - 1));
locationY = Math.floor(Math.random() * (sizeY - 1 - size));
}
// setting locations
for (var i = 0 ; i < size ; i++) {
if (direction) {
this.coveredFields.push(locationY * 10 + locationX + i)
} else {
this.coveredFields.push((locationY + i) * 10 + locationX)
}
}
}
}
var ship1 = new Ship(3, true);
ship1.place(7,7);
ship1.coveredFields;
然后我把船放在一个空数组
var shipsArray = [];
shipsArray.push(ship1.coveredFields
我的游戏唯一的问题是,当他们被随机地放在场上时,我的船只会相互重叠,我不希望这种情况发生。我一直试图制作这样的碰撞功能:
function collision(direction)
{
for (var i = 0; i < shipsArray.length; i++)
{
for (var j = 0; j < direction.length; j++)
{
if (shipsArray[i].direction.indexOf(direction[j]) != -1)
{
return true;
}
}
}
return false;
}
目前这个功能没有返回任何错误,但由于船只有时仍会发生碰撞,所以它也没有给我任何解决方案。
与上述功能相比,是否有更智能的方法来检测船舶之间的碰撞,或者我如何改进?
如果你需要更多代码我会编辑我的答案,但我希望我足够彻底。
答案 0 :(得分:1)
我建造一个Map
并将船只放在上面:
function Ship(size, direction) {
// Keep Ship simple
this.size = null;
this.direction = null;
this.coveredFields = null;
};
function BattleMap(boundaries) {
this.ships = [];
this.boundaries = boundaries;
};
BattleMap.prototype = {
createShipAtRandomPos: function() {
var ship = new Ship();
// check for collision here and set size+direction
this.ships.push(ship);
return ship;
}
};
var map = new BattleMap();
var ship1 = map.createShipAtRandomPos();