JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5 lightcycles</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>lightcycles</h1>
<p>Use WASD or arrow keys control cycle.</p>
<p>Click inside canvas to play game.</p>
<canvas id="the-game" width="640" height="480">
</body>
</html>
CSS
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
background-color: #333;
}
h1 {
font-size: 32px;
}
h1, p {
color: #FFF;
text-align: center;
}
canvas {
display: block;
margin: 10px auto;
background-color: #666;
}
JavaScript
/*
* HTML5 lightcycles
* copyright (c) 2013 Jason Straughan - JDStraughan.com
* MIT License - http://opensource.org/licenses/MIT
*/
canvas = document.getElementById("the-game");
context = canvas.getContext("2d");
enemy = {
type: 'program',
width: 8,
height: 8,
color: '#92F15F',
history: [],
current_direction: null
};
player = {
type: 'user',
width: 8,
height: 8,
color: '#58BEFF',
history: [],
current_direction: null
};
keys = {
up: [38, 87],
down: [40, 83],
left: [37, 65],
right: [39, 68],
start_game: [13, 32]
};
lastKey = null;
game = {
over: false,
start: function() {
cycle.resetPlayer();
cycle.resetEnemy();
game.over = false;
player.current_direction = "left";
game.resetCanvas();
},
stop: function(cycle) {
game.over = true;
context.fillStyle = '#FFF';
context.font = (canvas.height / 15) + 'px sans-serif';
context.textAlign = 'center';
winner = cycle.type == 'program' ? 'USER' : 'PROGRAM';
context.fillText('GAME OVER - ' + winner + ' WINS', canvas.width/2, canvas.height/2);
context.fillText('press spacebar to contine', canvas.width/2, canvas.height/2 + (cycle.height * 3));
cycle.color = "#F00";
},
newLevel: function() {
cycle.resetPlayer();
cycle.resetEnemy();
this.resetCanvas();
},
resetCanvas: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
};
cycle = {
resetPlayer: function() {
player.x = canvas.width - (canvas.width / (player.width / 2) + 4);
player.y = (canvas.height / 2) + (player.height / 2);
player.color = '#58BEFF';
player.history = [];
player.current_direction = "left";
},
resetEnemy: function() {
enemy.x = (canvas.width / (enemy.width / 2) - 4);
enemy.y = (canvas.height / 2) + (enemy.height / 2);
enemy.color = '#92F15F';
enemy.history = [];
enemy.current_direction = "right";
},
move: function(cycle, opponent) {
...