import { Game } from "./Game.js" const req = new XMLHttpRequest(); const canvas = document.getElementById("canvas"); const menu = document.getElementById("menu"); const menuLevel = document.querySelector(".menu-level"); const gameZone = document.getElementById("game"); const score = document.getElementById("score"); const lives = document.getElementById("lives"); const audio = new Audio("sources/sound/main.mp3"); const startSound = new Audio("sources/sound/onStart.mp3"); const eatSound = new Audio("sources/sound/onEat.mp3"); const dieSound = new Audio("sources/sound/onDie.mp3"); const gameOverSound = new Audio("sources/sound/onGameOver.mp3"); const game = new Game(canvas); startSound.volume = "0.2"; req.open("GET", "sources/levels.json"); req.onerror = () => console.error("Fail to load XML request"); req.onload = () => { let levels; if (req.status === 200) levels = JSON.parse(req.responseText); else levels = null; loadLevels(levels); }; req.send(); game.onStart = () => { updateLives(game.lives); updateScore(game.score); menu.classList.add("invisible"); canvas.classList.remove("invisible"); }; game.onStop = () => { menu.classList.remove("invisible"); canvas.classList.add("invisible"); }; game.onEat = (score) => { eatSound.play(); updateScore(score); }; game.onDie = lives => { dieSound.play(); updateLives(lives); }; game.onGameOver = (score) => { gameOverSound.play(); alert(`Game over !\nYour score is: ${score}`); }; function loadLevels(levels) { if (!levels) { menuLevel.innerHTML = ""; menuLevel.insertAdjacentHTML("beforeend", "") } else { for (const [name, level] of Object.entries(levels)) { const b = document.createElement("button"); b.classList.add("col", "s8", "offset-s2"); b.innerText = name; menuLevel.insertAdjacentElement("beforeend", b); b.addEventListener("click", () => loadGame(level)) } } } function loadGame(data) { game.load(data); game.start(); startSound.play(); }; function updateScore(s) { score.innerText = s; } function updateLives(l) { lives.innerText = l; } document.addEventListener('DOMContentLoaded', function() { M.AutoInit(); canvas.width = gameZone.clientWidth; canvas.height = gameZone.clientHeight; }); audio.addEventListener("canplaythrough", () => { audio.volume = 0.1; audio.play(); });