Racing game
HTML
<canvas id="game"></canvas>
<script></script>
JavaScript
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
/*
Game class
*/
function Game(id) {
this.WIDTH = 200;
this.HEIGHT = 400;
this.STEP = 1;
this.distance = 0;
this.clearColor = "#000";
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext("2d");
this.running = false;
this.state = null;
this.canvas.width = this.WIDTH;
this.canvas.height = this.HEIGHT;
}
Game.prototype.update = function() {
this.distance += this.STEP;
this.state.update(this.STEP);
if (this.distance % 100 == 0 && this.STEP < 10) {
this.STEP++
}
};
Game.prototype.draw = function() {
this.context.fillStyle = this.clearColor;
this.context.fillRect(0, 0, this.WIDTH, this.HEIGHT);
this.state.draw(this.context);
};
Game.prototype.loop = function() {
if (this.running) {
this.draw();
this.update();
window.requestAnimationFrame(this.loop.bind(this))
}
};
Game.prototype.run = function() {
this.running = true;
this.loop();
};
/*
State class
*/
function State() {
this.draw;
this.update;
}
/*
Road Class
*/
function Road(width, height) {
this.currentStep = 0;
this.bgColor = "#666";
this.line = {
color: "#fff",
width: Math.PI/3
};
this.width = width;
this.height = height;
this.offset = this.width * 1 / 4;
}
Road.prototype.draw = function(context) {
context.fillStyle = this.bgColor;
context.fillRect(this.offset, 0, this.width, this.height);
// long
context.fillStyle = this.line.color;
context.fillRect(this.offset, 0, this.line.width, this.height);
context.fillRect(this.width + this.offset - this.line.width, 0, this.line.width, this.height);
// short
for (var i = -1; i < 10; i += 2) {
context.fillRect(
this.offset + this.width / 3 + this.line.width / 2,
this.currentStep...