Ich mache ein Schlachtschiff Spiel in Javascript. Momentan arbeite ich daran, die Boote zu platzieren und sicherzustellen, dass die Boote nicht übereinander liegen.Neustart Methoden in JavaScript
Um dies zu tun, verwende ich drei Methoden, eine, die eine Position für das Boot wählt, eine, die das Boot baut und eine Grenze um es macht, und eine dritte, die diese beiden Methoden ausführt. Wenn die zweite Methode eine Grenze um das Boot legt, geschieht dies durch Setzen einer Eigenschaft boatHere
auf 1
, und dann in der dritten Funktion überprüft es, ob die erste Funktion eine Position ausgewählt hat, die bereits die Eigenschaft boatHere = 1
hat. Ich möchte prüfen, ob dort schon ein Boot ist, und die dritte Funktion neu starten, um ein Boot woanders zu platzieren. Hier ist der Code:
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
}
Vorsicht, nicht deklarierte globale Variablen every !! –