Find the pairs
Simple "find the pairs" game made with canvas.
by Karl Tayfer
HTML
<canvas id="canvas" style="background:#ccc"></canvas>
JavaScript
(function () {
'use strict';
window.addEventListener('load', init, false);
var CARDBACK = 1;
var STATE_HOME = 0;
var STATE_PLAY = 1;
var STATE_GAMEOVER = 2;
var canvas = null;
var ctx = null;
var lastUpdate = 0;
var lastPress = null;
var mouse = {
x: 0,
y: 0
};
var state = STATE_HOME;
var card1 = null;
var card2 = null;
var timer = 0;
var cards = [];
var spritesheet = new Image();
spritesheet.src = 'http://jugaa.me/game/pairs/cards.png';
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width = 480;
canvas.height = 320;
enableInputs();
run();
}
function random(max) {
return ~~(Math.random() * max);
}
function run() {
requestAnimationFrame(run);
var now = Date.now();
var deltaTime = (now - lastUpdate) / 1000;
if (deltaTime > 1) deltaTime = 0;
lastUpdate = now;
act(deltaTime);
paint(ctx);
}
function reset() {
cards.length = 0;
// Randomize cards order
var temp = [];
for (var i = 0; i < 12; i++) {
if (random(2) % 2 == 0) {
temp.push(i % 6);
} else {
temp.unshift(i % 6);
}
}
// Add cards
for (var i = 0; i < 12; i++) {
var c = new Rectangle(64 + (i % 4) * 2 * 48, 32 + ~~ (i / 4) * 2 * 48, 64);
c.type = temp.shift();
cards.push(c);
}
}
function act(deltaTime) {
// Home
if (state == STATE_HOME) {
if (lastPress == 1) {
reset();
state = STATE_PLAY;
}
}
// Game Over
else if (state == STATE_GAMEOVER) {
if (lastPress == 1) {
reset();
state = STATE_PLAY;
}
}
...