召回方法问题

时间:2016-09-17 22:10:14

标签: javascript methods properties

我正在制作战舰游戏。我想放置3条长3片的小船而不重叠。我写了以下代码:

var boatGrid = {

    placeBoat : function() {
        for (boatNum = 1; boatNum < 4; boatNum++) {
            console.log("boat placed now");
            this.selectPos();
            document.getElementById("boattest").innerHTML = boatPos;
            if (document.getElementById(boatPos).hasBoat == 1) {
                this.placeBoat();
                document.getElementById("boattest").innerHTML = "failed";
            }
            else {
                this.buildBoat();           
            }
        }
    },

    selectPos : function() { 
            xPos = Math.floor(Math.random() * 8 + 1);
            yPos = Math.floor(Math.random() * 10 + 1);
            boatPos = "cell_" + xPos + "_" + yPos;
    },

    buildBoat : function() {
        for (boatLen = 1; boatLen < 4; boatLen++) {
            boatPos = "cell_" + xPos + "_" + yPos;
            xPos = xPos + 1;
            document.getElementById(boatPos).hasBoat = 1;
            document.getElementById(boatPos).style.backgroundColor = "brown";
            console.log("placed one tile");
        }

    },

    clearTable : function() {
        for (y = 1; y < 11; y++) {
            for (x = 1; x < 11; x++) {
                boatPos = "cell_" + x + "_" + y;
                document.getElementById(boatPos).hasBoat = 0;
                document.getElementById(boatPos).boatHere = 0;
                document.getElementById(boatPos).style.backgroundColor = "#34B0D9"
                document.getElementById(boatPos).innerHTML = "<pre>     </pre>";
                boatGrid.hasChecked = 0;
            }
        }
    },
}

当选择一个坐标两次(变量boatPos存储坐标)时,函数placeBoat()应该自行调用。但是,实际发生的是buildBoat()函数被调用两次。你们有没有人看到这个问题?我目前认为让placeBoat()函数不得不从内部回忆自己是一个问题,但我不知道如何解决这个问题。所有帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我会将boatPos作为全局变量存储在boatGrid中,就像那样:

var boatGrid = {
    boatPos: 0,

     placeBoat : function() {
        for (boatNum = 1; boatNum < 4; boatNum++) {
            //same code as before
            if (this.boatPos == 1) {
                this.placeBoat();
            // same code as before
        }
    },

    buildBoat : function() {
        for (boatLen = 1; boatLen < 4; boatLen++) {
            //same code as before
            this.boatPos = 1;
            // same code as before
        }
    },
}

如果您需要在boatPos中存储更多属性(看起来如此),请使用对象:

boatPos = {
   hasBoat: 0,
},

然后,在函数中:

if (this.boatPos.hasBoat == 1)

this.boatPos.hasBoat = 1;