Public
Edited
Apr 5, 2024
Insert cell
Insert cell
Insert cell
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
}
//// ADD INTERACTION
function keyDown(e) {
if(e.keyCode === 37) { player.left = 'on' } // left
else if(e.keyCode === 39) { player.right = 'on' } // right
}
function keyUp(e) {
if(e.keyCode === 37) { player.left = 'off' } // left
else if(e.keyCode === 39) { player.right = 'off' } // right
}
window.addEventListener('keyup', keyUp);
window.addEventListener('keydown', keyDown);

//// ANIMATION FRAME
let animationFrame;
function update() {
ctx.clearRect(0, 0, width, height);
//// PLAYER POS
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;
//// STAR POS
bonus = updatePos(bonus, player);
obs = updatePos(obs, player);
let score = bonus.score + obs.score;
//// DRAW
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;
}
Insert cell
function updatePos(el, player) {
if(el.y > height) {
el.x = width*.8 * Math.random() + width*.1;
el.y = -100 * Math.random();
el.speed = 3 * Math.random() + 5;
el.collision = false;
}
el.y = el.y + el.speed;
//// collision detection
let dx = Math.abs(player.x - el.x);
let dy = Math.abs(player.y - el.y);
if(dx < player.w && dy < player.w) {
if(el.collision == false) {
el.collision = true;
// if (audioOn == "true") { beepSound(el); }
if(el.name == 'bonus') { el.score++ }
else { el.score-- }
}
}
return el;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more