const canvas = document.getElementById("lienzo"); const ctx = canvas.getContext("2d"); const width = (canvas.width = 288); const height = (canvas.height = 512); const sprites = []; const background = new Image(); background.src = "./assets/bg.png"; class Suelo { constructor(ctx) { this.ctx = ctx; this.sueloImg = new Image(); this.sueloImg.src = "./assets/suelo.png"; this.posX = 0; this.posY = height - this.sueloImg.height; } update() { this.posX--; if (this.posX + this.sueloImg.width === 0) this.posX = 0; } draw() { ctx.drawImage(this.sueloImg, this.posX, this.posY); ctx.drawImage(this.sueloImg, this.posX + width, this.posY); } } class Tuberia { constructor(ctx, posX, tipo) { this.ctx = ctx; this.tuberiaImg = new Image(); this.tuberiaImg.src = "./assets/tuberias.png"; this.tipo = tipo; this.width = 52; this.height = 320; this.separacion = 60; //min 60 max 120 this.posX = posX; this.posY = Math.floor(Math.random() * (300 - 100 + 1)) + 100 - Math.floor(this.height * 2 + this.separacion) / 2; } generaPos() { this.posX = width; this.posY = Math.floor(Math.random() * (300 - 100 + 1)) + 100 - Math.floor(this.height * 2 + this.separacion) / 2; } update() { this.posX--; if (this.posX <= 0 - this.width) { this.generaPos(); } } draw() { this.ctx.drawImage( this.tuberiaImg, 1 * this.width, this.tipo * this.height, this.width, this.height, this.posX, this.posY, this.width, this.height ); this.ctx.drawImage( this.tuberiaImg, 0 * this.width, this.tipo * this.height, this.width, this.height, this.posX, this.posY + this.height + this.separacion, this.width, this.height ); } } class Bird { nFramesAnim = 3; animFrame = 0; gameFrame = 0; constructor(ctx) { this.gravedad = 0; this.ctx = ctx; this.birdImg = new Image(); this.birdImg.src = "./assets/flappybird.png"; this.posY = height / 2; this.posX = width / 8; this.width = 34; this.height = 24; } update() { this.posY += this.gravedad; this.animFrame = Math.floor(this.gameFrame / 10) % this.nFramesAnim; this.gameFrame++; } draw() { this.ctx.drawImage( this.birdImg, this.animFrame * this.width, 0, this.width, this.height, this.posX, this.posY, this.width, this.height ); } } function gameLoop(timeStamp) { ctx.clearRect(0, 0, width, height); ctx.drawImage(background, 0, 0, width, height); sprites.forEach((sprite) => { sprite.update(); sprite.draw(); }); requestAnimationFrame(gameLoop); // Llamar a gameLoop de nuevo en el siguiente fotograma } sprites.push( new Bird(ctx), new Tuberia(ctx, width * 2, 1), new Tuberia(ctx, width * 2 + width * 0.5 + 25, 0), new Suelo(ctx) ); window.onload = () => { gameLoop(); };