0
我正在做一個戰艦遊戲。我想要放置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()函數不得不從內部回想自己是一個問題,但我不知道如何解決這個問題。所有幫助讚賞。
我不認爲在這樣的對象定義中聲明一個變量是合法的。你的意思是讓它成爲一個財產嗎? – Andbdrew
@Andbdrew是的,我有點快。我編輯了答案以匹配代碼。 – falkodev
boatPos被定義在對象之外,無論如何,爲什麼會讓它運行兩次buildBoat()函數? –