I am reading "Head First: Javascript" currently, and there's a task to create "battleship". I followed each step and my code looks exactly, the one from the book, but my code always generates the same number, which should get added by 1, each time. This means, if it generates the number 2, the following 2 numbers should be 3 and 4 (3 locations = 1 ship). I want it to be between 0 and 4 (because if it's 4, the 5 and 6 are also on the raster.) The user should pick a number between 0 and 6.
The random numbers are ALWAYS: 0, 1 and 1.. Here's the code:
var randomLoc = Math.floor(Math.random()) * 5;
var location1 = randomLoc;
var location2 = location1++;
var location3 = location2++;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
alert(location1 + " " + location2 + " " + location3); //To show the numbers for debugging.
while (isSunk == false) {
guess = prompt("Anlegen, Zielen Feuer! (Geben Sie eine Zahl zwischen 0 und 6 ein) :");
if (guess < 0 || guess > 6) {
alert("Diese Zahl (sofern es eine war) liegt nicht auf dem Raster")
} else {
guesses += 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("Treffer!")
hits += 1;
if (hits == 3) {
isSunk = true;
alert("Schiff versenkt!");
}
} else {
alert("Daneben!");
}
}
}
var stats = "Sie haben " + guesses + " Versuche gebraucht, um das Schiff zu versenken. " +
"Das entspricht einer Genauigkeit von " + (3 / guesses) * 100 + "%";
alert(stats);