JSFiddle - React, Tailwind, and code Playground
by Raynos
HTML
<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
JavaScript
// canvas height
var HEIGHT = 400;
// canvas with
var WIDTH = 640;
// Critter amount
var COUNT = 5;
// base speed of critter
var SPEED = 15;
// Size of critters
var SIZE = 20;
// Time per round
var TIMEOUT = 3000;
// paper object
var paper = Raphael(10, 50, WIDTH, HEIGHT);
// collision algorithm. It's really naive. only checks if mybox is inside box
Raphael.el.collision = function(box) {
var mybox = this.getBBox();
var points = [
[mybox.x, mybox.y],
[mybox.x + mybox.width, mybox.y],
[mybox.x, mybox.y + mybox.height],
[mybox.x + mybox.width, mybox.y + mybox.height]
];
return _.any(points, function(point) {
if (box.x < point[0] && point[0] < box.x + box.width &&
box.y < point[1] && point[1] < box.y + box.height) {
return true;
} else {
return false;
}
});
};
// BBox Mock object for the screen to test for out of bounds
var screen = {
x: 0,
y: 0,
width: WIDTH,
height: HEIGHT
};
var Critter = function() {
// default the speed to something random.
this.speed = SPEED + Math.random()*SPEED;
var loop;
// logic module
var logic = function(food) {
// move yourself randomly
this.el.translate(
-Math.random()*this.speed + Math.random()*this.speed,
-Math.random()*this.speed + Math.random()*this.speed);
// if you hit food you win
if (this.el.collision(food)) {
this.win();
}
// if your not in the screen then your out of bounds
if (!this.el.collision(screen)) {
this.out_of_bounds();
}
}
// start round
this.start = function(food, out_of_bounds) {
// store that out_of_bounds function so you can tell the game that you
// are out of bounds
this.notifyGame = out_of_bounds;
// create a player (circle);
this.el = paper.circle(Math.random()*WIDTH,...