在JavaScript中重新启动方法

时间:2016-07-23 18:28:21

标签: javascript methods return

我在Javascript中制作战舰游戏。目前,我正在努力放置船只,并确保船只不会相互叠放。

要做到这一点,我使用三种方法,一种选择船只的位置,一种建造船只并在其周围形成边界,第三种方法执行这两种方法。当第二种方法在船周围形成边界时,它通过将属性boatHere设置为1来实现,然后在第三个函数中,它检查第一个函数是否选择了一个位置已经拥有属性boatHere = 1。我想检查那里是否有船,并重新启动第三个功能,以便将船放在其他地方。这是代码:

    placeBoat : function() { //chooses position, checks to see if eligible and builds boat
        for (boatNum = 1; boatNum < 4; boatNum++) {
            this.selectPos();
            if (document.getElementById(boatPos).boatHere == 1) {
                return;
            }
            else {
                this.buildBoat();               
            }
        }   
    }, 

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

    buildBoat : function() { //builds boat 3 tiles long and boundary 7 tiles long
        for (boatLen = 1; boatLen < 4; boatLen++) {
            xPos = xPos + 1;
            boatPos = "cell_" + xPos + "_" + yPos;
            document.getElementById(boatPos).hasBoat = 1;
            document.getElementById(boatPos).style.backgroundColor = "brown";
            console.log("placed one tile");
        }
        xPos = xPos - 6;
        for (boatBox = 1; boatBox < 8; boatBox++) {
            xPos++;
            boatPos = "cell_" + xPos + "_" + yPos;
            document.getElementById(boatPos).boatHere = 1;
            document.getElementById(boatPos).innerHTML = "  X";//visual reminder of where boundary is
        }

2 个答案:

答案 0 :(得分:2)

您可以使用单独的placeSingleBoat()功能放置一艘船,如果成功与否则返回。然后,placeBoat()函数可以根据需要经常调用placeSingleBoat(),直到成功为止:

placeSingleBoat: function(boatNum) {  //chooses position, checks to see if eligible and builds boat
    this.selectPos();
    if (document.getElementById(boatPos).boatHere == 1) {
        return false;
    }
    else {
        this.buildBoat();               
    }
    return true;       
},

placeBoat : function() {
    for (boatNum = 1; boatNum < 4; boatNum++) {
        var placed = false;
        while (!placed) {
            placed = this.placeSingleBoat(boatNum);
        }
    }
},

答案 1 :(得分:-1)

根据您的描述,您似乎想要这样:

    for (boatNum = 1; boatNum < 4; boatNum++) {
        do {
            this.selectPos();
        } while (document.getElementById(boatPos).boatHere == 1);
        this.buildBoat();               
    }   

即。继续选择新的位置,直到找到一个尚未被占用的位置,然后在那里建造一艘船。