ClearOut (Game)
by Dean Panayotov
HTML
<body>
<canvas id="canvas">g</canvas>
<br>
<input type="button" id="reset" value="reset">
<label>Score: </label><label id="score">0</label>
</body>
CSS
body {
background-color: #000000;
color: #FFFFFF;
text-align:center;
vertical-align: middle;
}
#canvas {
margin: 10px;
padding: 0px;
}
JavaScript
var canvas = document.getElementById('canvas');
canvas.addEventListener('click', click, false);
var c = canvas.getContext("2d");
var button = document.getElementById('reset');
button.addEventListener('click', init, false);
var scoreField = document.getElementById('score');
////CONSTANTS/////////////////////////////
var COLORS = [
"#660099", //0
"#330066", //1
"#99FF00", //2
"#FF9900", //3
"#FFFFFF", //4
"#FFCCFF", //5
"#FFD699", //6
"#D1B2E0", //7
"#800000", //8
"#FFFF99" //9
];
var HEIGHT = 16;
var WIDTH = 16;
var BLOCK_SIZE = 20;
/** 2-10 */
var NUMBER_OF_COLORS = 6;
var EMPTY = -1;
canvas.width = WIDTH * BLOCK_SIZE;
canvas.height = HEIGHT * BLOCK_SIZE;
var grid = [];
var valid = false;
var score = 0;
init();
//////////////////////////////////////////
function init(){
for(var i = 0; i < WIDTH; i ++){
grid[i] = [];
for(var j = 0; j < HEIGHT; j ++){
grid[i][j] = Math.floor(Math.random() * (NUMBER_OF_COLORS));
}
}
valid = true;
scoreField.innerHTML = score = 0;
draw();
}
/** TODO:this probably doesn't work in nested divs */
function getCursorPosition(event) {
var mouseX;
var mouseY;
if (event.pageX || event.pageY) {
mouseX = event.pageX;
mouseY = event.pageY;
} else {
mouseX = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
mouseY = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
mouseX -= canvas.offsetLeft;
mouseY -= canvas.offsetTop;
var x = Math.floor(mouseX / BLOCK_SIZE);
var y = Math.floor(mouseY / BLOCK_SIZE);
y = HEIGHT - y - 1; //reverse the y
return new Block(x, y);
}
/** @constructor */
function Block(x, y) {
this.x = x;
this.y = y;
}
function draw(){
c.fillStyle = "#000000";
c.fillRect(0,0,canvas.width,canvas.height);
for(var i = 0; i < WIDTH; i ++){
for(var j = grid[i].length-1; j >=...