比较多个数组的各个值

时间:2013-04-18 23:26:11

标签: javascript arrays object comparison

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

我正在使用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();

如何检查船舶阵列的每个值以检查重叠? 我已经尝试了多种方法,但是无论是挑出元素还是找到一种方法来轻松交叉引用它们都遇到了麻烦。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

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

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

顺便说一句好工作!

更新

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