Light Field Canvas Game
HTML
<canvas id="lightpanel" width="500" height="500"></canvas>
JavaScript
// light field
var lightField =
[
[ 'o', 'o', 'o', 'o', 'o' ],
];
var canvas = document.getElementById('lightpanel'),
ctx = canvas.getContext('2d');
canvas.onclick = function(e) {
// Get the click position
var ox = e.pageX,
oy = e.pageY,
yField = Math.floor(oy / 100),
xField = Math.floor(ox / 100);
// toggle the clicked field
lightField[yField][xField] = toggleField(yField, xField);
// toogle neighboring fields
if (yField-1 >= 0) {
lightField[yField-1][xField] = toggleField(yField-1, xField);
}
if (yField+1 < 5) {
lightField[yField+1][xField] = toggleField(yField+1, xField);
}
if (xField-1 >= 0) {
lightField[yField][xField-1] = toggleField(yField, xField-1);
}
if (xField+1 < 5) {
lightField[yField][xField+1] = toggleField(yField, xField+1);
}
// (re)draw results
repaintPanel();
};
function repaintPanel() {
// clear the frame before drawing
clear();
var cleared = true;
for(var i = 0, rlen = lightField.length; i < rlen; i++) { // rows
for(var j = 0, clen = lightField[i].length; j < clen; j++) { // columns
ctx.lineWidth = 3;
ctx.strokeStyle = '#999';
// draw!
ctx.beginPath();
// arc( x, y, radius, startAngle, endAngle, anticlockwise)
ctx.arc(j * 100 + 50, i * 100 + 50, 40, 0, Math.PI*2, true);
ctx.stroke();
if (lightField[i][j] == 'x') {
ctx.fillStyle = '#fff000';
ctx.beginPath();
ctx.arc(j * 100 + 50, i * 100 + 50, 38, 0, Math.PI*2, true);
ctx.fill();
cleared = false;
}
} // end col loop
} // end row loop
if (cleared) {
alert('All the lights are off, you finished the game!');
n = i;
randomize();
}
}
randomize();
function clear() {
ctx.clearRect(0, 0, 500,...