Angrynoid
Javascript version of the popular Arkanoid game.
by mlison
HTML
<body>
<div class="wrapper">
<h1>Angrynoid</h1>
<canvas id="game" width="830" height="500"></canvas>
<div class="actions">
<button id="new">New game</button>
</div>
<div class="lives"></div>
<p class="status">Ohai!<br />Use arrows to control the paddle.</p>
</div>
</body>
CSS
body {
font-family: arial;
}
.wrapper {
margin: 0 auto;
position: relative;
width: 830px;
}
h1 {
text-align: center;
}
#game {
background-color: #181818;
display: block;
margin: 0 auto;
}
.actions {
float: left;
padding-top: 5px;
}
.lives span {
background: url('https://raw.github.com/mlison/arkanoid/master/images/bird.png') no-repeat;
height: 20px;
float: right;
font-weight: bold;
margin: 0.5em;
width: 20px;
}
.hide {
display: none;
}
.status {
clear: both;
padding-top: 1em;
text-align: center;
}
JavaScript
function Game(options) {
"use strict";
var game = this,
canvas = (options.canvas) ? options.canvas : document.querySelector('#game'),
status = (options.status) ? options.status : document.querySelectorAll(".status")[0],
ctx = canvas.getContext("2d"),
speed = (options.speed) ? options.speed : 5;
game.isRunning = false;
game.isWon = false;
/*
* Public .init() initiates the game with 'saved' game data if available, or start a new game
*/
this.init = function () {
var done = false,
gamestate = null;
images.init();
if (window.localStorage) {
gamestate = JSON.parse(window.localStorage.getItem('gamestate'));
// if gamestate is present from previous session use stored values to initiate the game
if (gamestate !== null && !gamestate.isWon && gamestate.lives > 0) {
if (gamestate.isRunning) {
// if the game was running use stored values
ball.init(gamestate.ball.x, gamestate.ball.y, gamestate.ball.dx, gamestate.ball.dy);
bat.init(gamestate.bat.pos);
} else {
// otherwise reset ball and bat
ball.init();
bat.init();
}
bricks.init(gamestate.bricks.currentMap.clone(), gamestate.bricks.remaining);
lives.init(gamestate.lives);
done = true;
}
}
// otherwise just start the game with default values
if (!done) {
ball.init();
bat.init();
bricks.init();
lives.init();
}
addKeyHandlers();
game.isRunning = true;
game.isWon = false;
tick();
};
/*
* Public .reset() will restart the ball and bat from their default position
*/
this.reset = function () {
ball.init();
bat.init();
game.isRunning = true;
status.innerHTML = "";
reqAnimationFrame(tick);
};
/*
* Private lives object, implements life tracking from init() till die()
* .init initializes lives object
* .container element where lives live
* .count keeps track of how many lives are left
* .draw() draws available lives to .container
* .die() removes a life
*/
var...