A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one, should change their color (toggle). The game continues until all cells turn red.
Now, there's a requirement to make certain cells default to red, not randomly. How can this be achieved? Additionally, any suggestions on optimizing the code for a more concise execution would be appreciated!
window.onload = function() {
document.getElementById("zero0").style.backgroundColor = "red";
document.getElementById("one3").style.backgroundColor = "red";
document.getElementById("three2").style.backgroundColor = "red";
}
function zero0() {
var cell00 = document.getElementById("zero0");
let cell01 = document.getElementById("zero1");
let cell10 = document.getElementById("one0");
if (cell00.style.backgroundColor == "red") {
cell00.style.backgroundColor = "white"
} else {
cell00.classList.toggle('reed')
}
if (cell01.style.backgroundColor == "red") {
cell01.style.backgroundColor = "white"
} else {
cell01.classList.toggle('reed')
}
if (cell10.style.backgroundColor == "red") {
cell10.style.backgroundColor = "white"
} else {
cell10.classList.toggle('reed')
}
}
...
// More functions here
body {
text-align: center;
display: flex;
justify-content: center;
}
table {
/*border-radius: 10px;*/
margin-top: 60px;
border: 1px solid;
background-color: lightcyan;
box-shadow: 5px 5px 40px royalblue;
}
td {
border: 1px solid;
width: 40px;
height: 40px;
}
p {
font-weight: bold;
font-size: 17px;
}
td {
background-color: white;
}
.reed {
background-color: red;
}
<div class="container">
<h2>Table game</h2>
<p>Try to color all of the cells to <b>red</b></p>
<table>
<tr>
<td id="zero0" onclick="zero0()"></td>
<td id="zero1" onclick="zero1()"></td>
<td id="zero2" onclick="zero2()"></td>
<td id="zero3" onclick="zero3()"></td>
<td id="zero4" onclick="zero4()"></td>
</tr>
... // More table rows
</table>
</div>