This double for loop is supposed to loop over a Battleship board and add an event listener to each cell. The event listener is supposed to represent a cell in a Battleship board. When it is clicked and a ship is positioned on that cell, the cell's color will change to red, representing a hit, and w will increment by 2. If w reaches 24, the game will end and the winner's scores will be presented.
let table2 = document.getElementById("player2board");
let opptable2 = document.getElementById("player1opp");
for(var i = 1; i < table2.rows.length; i++){
for(var j = 1; j < table2.rows[i].cells.length; j++){
table2.rows[i].cells[j].innerHTML = p2Board[i - 1][j - 1];
if(p2Board[i - 1][j - 1] != ""){
let currcell = opptable2.rows[i].cells[j];
opptable2.rows[i].cells[j].addEventListener("click", () => {currcell.style.backgroundColor = "Red";
document.getElementById("player1table").hidden = true;
w += 2;
console.log(w);
if(w == 24){
let t = w;
w = w - w2;
w2 = w2 - t;
document.getElementById("p1score").innerText = p1Name + "'s score (winner): " + w;
document.getElementById("p2score").innerText = p2Name + "'s score: " + w2;
document.getElementById("scores").hidden = false;
}else{
document.getElementById("player2turn").hidden = false;
}});
}else{
let currcell = opptable2.rows[i].cells[j];
opptable2.rows[i].cells[j].addEventListener("click", () => {currcell.style.backgroundColor = "White";
document.getElementById("player1table").hidden = true; document.getElementById("player2turn").hidden = false;});
}
}
}
What's going wrong, though, is that the event listener is incrementing w for every hit that has been made. If I click on a cell and get a 2nd hit, w will increment by 4, if I get a 3rd hit w will increment by 8 etc. What did I do wrong and how do I fix it?