game = {
const canvas = DOM.canvas(width, height);
const ctx = canvas.getContext('2d');
let player = {
x: 300,
y: height - 90,
w: 72,
left: 'off',
right: 'off',
name: 'player'
}
let bonus = {
x: 300,
y: 0,
w: 40,
speed: 6,
collision: false,
name: 'bonus',
score: 0
}
let obs = {
x: 100,
y: -200,
w: 43,
speed: 4.5,
collision: false,
name: 'obs',
score: 0
}
function keyDown(e) {
if(e.keyCode === 37) { player.left = 'on' }
else if(e.keyCode === 39) { player.right = 'on' }
}
function keyUp(e) {
if(e.keyCode === 37) { player.left = 'off' }
else if(e.keyCode === 39) { player.right = 'off' }
}
window.addEventListener('keyup', keyUp);
window.addEventListener('keydown', keyDown);
let animationFrame;
function update() {
ctx.clearRect(0, 0, width, height);
if(player.left === 'on') { player.x -= speed; }
if(player.right === 'on') { player.x += speed; }
player.x = player.x < 0 ? 0 : player.x;
player.x = player.x > width - 75 ? width - 75 : player.x;
bonus = updatePos(bonus, player);
obs = updatePos(obs, player);
let score = bonus.score + obs.score;
if(!bonus.collision) { ctx.drawImage(bonus_img, bonus.x, bonus.y, bonus.w, bonus.w) }
if(!obs.collision) { ctx.drawImage(mushroom, obs.x, obs.y, obs.w, obs.w) }
ctx.drawImage(player_img, player.x, player.y, player.w, player.w);
ctx.font = "16px Verdana";
ctx.textAlign = "center";
ctx.fillText("SCORE: " + score, width/2, 50);
animationFrame = requestAnimationFrame(update);
}
update();
return canvas;
}