1

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

我正在使用 javaScript 创建一个 Battleship 游戏来生成随机船舶放置。我为游戏板(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();

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

4

1 回答 1

0

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

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

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

顺便说一句,干得好!

更新

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

于 2013-04-19T00:14:38.457 回答