我正在用 Javascript 制作战舰游戏。目前,我正在努力放置船只,并确保船只不会放置在彼此之上。
为此,我使用三种方法,一种为船选择位置,一种 build 船并在其周围划定边界,第三种方法执行这两种方法。当第二个方法在船周围建立边界时,它通过将属性 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
}
最佳答案
您可以使用单独的 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);
}
}
},
关于javascript - 重新启动 JavaScript 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545169/