I created a basic battleship game using javascript, but unfortunately it's not working properly. I stored the ship locations in an array and attempted to remove guessed locations by using the splice method. However, it keeps displaying "MISS!" when numbers between 0 and 6 are entered.
Edit: I managed to fix the issue by utilizing the parseInt method for the prompt.
var location1 = Math.floor(Math.random() * 5);
var location2 = location1 + 1;
var location3 = location2 + 1;
var locations = [];
locations.push([location1, location2, location3]);
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Enter your guess(0 - 6)");
if (guess < 0 || guess > 6) {
alert("Please enter a valid number!");
} else {
guesses++;
if (locations.indexOf(guess) > 0) {
locations.splice(locations.indexOf(guess), 1);
hits++;
alert("HIT!");
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, which
means your shooting accuracy was " + (3 / guesses);
alert(stats);