JS: Snake
v1:
http://jsfiddle.net/ARTsinn/3cQvw/8/
more at:
http://trickkr.com/item/40/javascript-basic-html5-snake
http://aspektas.com/blog/canvas-snake-game/
http://lab.aspektas.com/canvas_snake.html
http://cssdeck.com/labs/classic-snake-game-with-html5-canvas
http://www.htmlstack.com/canvassnake/
HTML
<script src="https://wagenaartje.github.io/neataptic/cdn/1.4.7/neataptic.js"></script>
<script src="https://cdn.rawgit.com/cazala/synaptic/master/dist/synaptic.min.js"></script>
<span class="cont">
<button id="stepup">
Faster
</button>
<button id="stepdown">
Slower
</button>
<button id="reset">
Reset
</button>
<span id="generation">
Generation 0
</span>
<span id="step">
Speed 1
</span>
</span>
CSS
html,
body {
margin: 0;
padding: 0
}
canvas,
.cont {
display: inline-block;
vertical-align: top;
}
canvas {
width: auto;
max-width: 100%;
height: auto;
}
.cont > * {
display: block;
}
JavaScript
/**
* A lightweight game wrapper
*
* @constructor
*/
var colors = "#bf3030, #99574d, #f26d3d, #a65b29, #ffd9bf, #ffa640, #fff240, #b2ad59, #8fbf30, #b1d9a3, #00ff00, #ffffff, #f2f2f2, #00cc6d, #00d6e6, #b6eef2, #537fa6, #408cff, #bfd0ff, #263699, #4040ff, #c480ff, #8f0099, #f200e2, #997396, #ff80d5, #b2005f, #ff8091, #d9a3aa".split(",");
//var colors = ["#bf3030"];
var neat = window.neat = new neataptic.Neat(5, 3, null, {
mutation: neataptic.methods.mutation.ALL,
popsize: 20,
mutationRate: 0.3,
mutationAmount: 2,
elitism: 4,
network: new neataptic.architect.Perceptron(
5,
8,
3
)
});
function Game(canvas, options) {
this.canvas = canvas;
this.context = canvas.getContext('2d');
this.steps = 1;
this.score = 0;
this.entities = [];
this.options = {
fps: 15
};
if (options) {
for (var i in options) this.options[i] = options[i];
}
this.scale();
}
/**
* Start the game loop
*/
Game.prototype.start = function() {
var loop = () => {
for (var i = 0; i < this.steps; i++) {
this.gameLoop();
}
setTimeout(loop, 1000 / this.options.fps);
}
loop();
};
/**
* Stop the game loop
*/
Game.prototype.stop = function() {
this.pause = true;
};
/**
* Scale the canvas element
* in accordance with the correct ratio
*/
Game.prototype.scale = function() {
this.ratio = innerWidth < innerHeight ? innerWidth : innerHeight;
this.tile = (this.ratio / 20) | 0;
this.grid = this.ratio / this.tile;
this.canvas.width = this.canvas.height = this.ratio;
};
/**
* Adds an entity to the game
*
* @param {Function} entity
*/
Game.prototype.addEntity = function(entity) {
this.entities.push(entity);
};
Game.prototype.removeEntity = function(entity) {
var index = this.entities.indexOf(entity);
if (index > -1) {
this.entities.splice(index, 1);
if (this.entities.length == 0) {
init();
}
}
};
/**
* Determines if an entity collides with another
*
* @param {Object} a
*...