As a beginner programmer, I have recently delved into learning JavaScript on my own. One of the projects I tackled was creating a simple battleship game. However, I encountered an issue where if the user hits the same location three times, the battleship sinks prematurely. To address this problem, I implemented an array called "userchoices" to store user inputs and added a for-loop to cross-check whether the user has already fired at a particular location. Unfortunately, the current implementation leads to the if statement being executed each time, which is not the intended behavior.
I would appreciate it if you could take a look at the code snippet below and provide suggestions for improvement. Thank you for your assistance.
var randomloc = Math.floor(Math.random() * 5);
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var userchoices = [];
var hits = 0;
var guesses = 0;
var issunk = false;
function battleship() {
while(issunk == false)
{
guess = prompt("Ready, Aim, Fire! (Enter a number 0-6):");
console.log("User's input = " + guess);
if (guess == null)
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. Number of guesses has been incremented.");
}
else{
guesses++;
userchoices[guesses] = guess;
console.log("User's choices = " + userchoices);
}
/* for(var i = 0; i <= guesses; i++)
{
if(userchoices[guesses] = guess)
console.log("You have already fired at this location");
} */
if (guess == location1 || guess == location2 || guess == location3){
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3){
issunk = true;
alert("Enemy battleship sunk");
}
}
else{
alert("You missed");
}
}
if (issunk){var stats = "You took " + guesses + " guesses to sink the battleship. Your accuracy was " + (3/guesses);alert(stats);}
else{alert("You Failed!"); issunk = false;}
}
This section appears to be causing the error:
for(var i = 0; i<=guesses; i++)
{
if (userchoices[guesses] = guess){
console.log("You have fired at this location already");
}}
The intention behind the above if statement is to notify the user only when they fire upon a grid number they've previously targeted, regardless of hitting or missing the battleship.