JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://rawgit.com/sapienlab/lang-def/master/def.js"></script>
<canvas width="360" height="360"></canvas>
<span class="left">
<button id="play_btn">Play</button>
<p>Move the blue pressing <b>A</b>, <b>D</b>, <b>W</b> or <b>S</b></p>
<p>You're vegetarian, so eating greens and runs away from reds!</p>
<span>
CSS
canvas { border: 1px solid blue; float: left; }
.left { float: left; width: 60px; }
JavaScript
var Point = def({
x: 0,
y: 0,
distance: function (p) {
return Math.sqrt(
Math.pow(p.x - this.x, 2) +
Math.pow(p.y - this.y, 2)
);
}
});
// GameEntity have all members of Point
var GameEntity = def([Point], {
r: 5,
color: 'grey',
onCollision: function(entity) { },
onUpdate: function(deltaTime) { },
onRender: function (ctx) {
if(this.r > 0) {
ctx.save();
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, 7);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
}
}
});
// Player inherits from GameEntity
var Player = def(GameEntity, {
velocity: 0.5,
controls: null,
color: 'blue',
x: 100,
y: 100,
onCollision: function(entity) {
if(entity.r <= 0) { return; }
if(entity instanceof Mushroom) {
entity.r--;
this.r++;
} else if(entity instanceof Enemy) {
entity.r++;
this.r--;
}
},
onUpdate: function(deltaTime) {
if(this.game.isPress.D) {
this.x += this.velocity * deltaTime;
}
if(this.game.isPress.A) {
this.x -= this.velocity * deltaTime;
}
if(this.game.isPress.W) {
this.y -= this.velocity * deltaTime;
}
if(this.game.isPress.S) {
this.y += this.velocity * deltaTime;
}
}
});
var Randomize = def({
game: null,
randomize: function() {
this.x = Math.random() * this.game.width;
this.y = 0;
return this;
},
onUpdate: function(deltaTime) {
this.x += (Math.random() > 0.5 ? 2 : -2) * Math.random();
this.y += Math.random();
}
});
var Enemy = def(GameEntity, [Randomize], { color: 'red' });
var Mushroom = def(GameEntity, [Randomize], { color: 'green' });
// define a Game
var Game = def({
width: null,
height: null,
player: null,
canvas: null,
ctx: null,
entities:...