import RetroSprite from "./retro/RetroSprite.js"; import Key from "./Key.js"; import MrCroc from "./MrCroc.js"; const MEDIA_READY_EVENT = 'mediaready'; const IMAGE_READY_EVENT = 'imgready'; class ImageLoader { images = []; numberImagesLoaded = 0; update() { this.numberImagesLoaded++; if (this.numberImagesLoaded === this.images.length) { window.dispatchEvent(new Event('imagesloaded')); } } getCurrentProgress() { return this.numberImagesLoaded / this.images.length; } addImage(image) { image.addEventListener( 'load', () => { this.update();1 } ); this.images.push(image); } } function MainLoop(timestamp) { if (lastRendered === undefined && lastTimestamp === undefined) { lastRendered = timestamp; lastTimestamp = timestamp; } let delta = (timestamp - lastTimestamp) / (10 / GAME_SPEED); if (KeyLeft.isPressed()) { mrCroc.moveLeft(timestamp, delta); } else if (KeyRight.isPressed()) { mrCroc.moveRight(timestamp, delta); } if (lastRendered >= FRAME_DURATION) { context.clearRect(0, 0, window.innerWidth, window.innerHeight); ground.draw(context); mrCroc.draw(context); lastRendered = timestamp; } lastTimestamp = timestamp; window.requestAnimationFrame(MainLoop); } const FPS = 60; const FRAME_DURATION = 1000 / FPS; const GAME_SPEED = 1; let lastRendered = undefined; let lastTimestamp = undefined; let context; let ground, mrCroc; let KeyLeft = new Key('ArrowLeft'); let KeyRight = new Key('ArrowRight'); let loader = new ImageLoader(); let image = new Image(); image.src = 'graphics/mr-croc-stand.png'; loader.addImage(image); let imgAnimation = new Image(); imgAnimation.src = 'graphics/mr-croc-walk-right.png'; loader.addImage(imgAnimation); let imgAnimationB = new Image(); imgAnimationB.src = 'graphics/mr-croc-walk-left.png'; loader.addImage(imgAnimationB); let imgBackground = new Image(); imgBackground.src = 'graphics/ground.jpg'; loader.addImage(imgBackground); window.addEventListener( 'imagesloaded', () => { console.log('Loaded'); ground = new RetroSprite('graphics/ground.jpg', 4); ground.position.y = window.innerHeight - ground.getRect().height; let canvas = document.getElementById('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; context = canvas.getContext('2d'); mrCroc = new MrCroc(); mrCroc.position.x = 100; mrCroc.position.y = window.innerHeight - ground.getHeight(); ground.draw(context); window.requestAnimationFrame(MainLoop); } );