/** * Game config */ const number_levels = 2; const cell_width = 10; const cell_height = 10; function byId(el) { return document.getElementById(el); } // Get elements const startScreen = byId("startScreen") const gameScreen = byId("gameScreen") const levelChoicesTarget = byId("levelChoice") const startGameBtn = byId("startGameBtn") const stopGameBtn = byId("stopGameBtn") const canvasTarget = byId("canvasTarget") /** * Show main screen */ function showMainScreen() { startScreen.style.display = "unset"; gameScreen.style.display = "none"; } /** * Start a new game */ async function startGame(gameID) { startScreen.style.display = "none"; gameScreen.style.display = "unset"; // Fetch level information let level; try { level = await (await fetch("levels/"+gameID+".json")).json(); } catch(e) { console.error(e); alert("Could not load game level!"); return; } // Create & apply the canvas const canvas = document.createElement("canvas"); canvas.width = cell_width * level.dimensions[0]; canvas.height = cell_height * level.dimensions[1]; canvasTarget.appendChild(canvas); } /** * Change the currently active window */ function changeWindow() { // Try to get game ID const gameID = Number(window.location.hash.substr(1)); if(gameID > 0) startGame(gameID); else showMainScreen(); } // Initialize page /// Listen to events window.addEventListener("hashchange", (e) => changeWindow()) // Make game levels form lives for (let index = 1; index < number_levels + 1; index++) { levelChoicesTarget.innerHTML += "
  • " + "" + " Level " + index + "
  • "; } startGameBtn.addEventListener("click", (ev) => { ev.preventDefault(); const gameID = document.querySelector("input[name='level']:checked").value location.href = "#" + gameID; }) // Stop game stopGameBtn.addEventListener("click", () => { location.href = "#"; }) // Refresh current window changeWindow();