我正在用Javascript製作戰艦遊戲。目前,我正在着手放置船隻,並確保船隻不會彼此重疊。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
}
提防,未聲明的全局變量everywere! –