javascript
<!DOCTYPE html>
<html>
<head>
<style>
#grid{
width:316px;
height: 316px;
background-color: #00BFFF;
}
.cell {
width: 60px;
height: 60px;
border: 1px solid black;
float: left;
}
.red {
background-color: red;
}
.black {
background-color: black;
}
</style>
</head>
<body>
<div id="grid"></div>
<script>
var grid = [];
var size = 5;
var gridElement = document.getElementById('grid');
for (var i = 0; i < size; i++) {
var row = [];
for (var j = 0; j < size; j++) {
var cell = document.createElement('div');
cell.className = 'cell red';
cell.onclick = (function(i, j) {
return function() {
toggleColor(i, j);
}
})(i, j);
gridElement.appendChild(cell);
row.push(cell);
}
grid.push(row);
}
grid[2][2].className = 'cell black';
function toggleColor(i, j) {
var directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
for (var k = 0; k < directions.length; k++) {
var ni = i + directions[k][0];
var nj = j + directions[k][1];
if (ni >= 0 && ni < size && nj >= 0 && nj < size) {
var cell = grid[ni][nj];
cell.className = cell.className === 'cell red' ? 'cell black' : 'cell red';
}
}
}
</script>
</body>
</html>