1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
Snake/sources/js/index.js
2021-03-23 09:29:52 +01:00

59 lines
1.6 KiB
JavaScript

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");
let game;
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();
function loadLevels(levels) {
if (!levels) {
menuLevel.innerHTML = "";
menuLevel.insertAdjacentHTML("beforeend", "<button class=\"col s8 offset-s2\" disabled>Fail to load levels :/</button>")
} 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))
}
}
}
const loadGame = data => {
game = new Game(canvas, data);
game.onStart = () => {
menu.classList.add("invisible");
canvas.classList.remove("invisible");
};
game.onStop = () => {
menu.classList.remove("invisible");
canvas.classList.add("invisible");
};
game.start();
};
document.addEventListener('DOMContentLoaded', function() {
M.AutoInit();
canvas.width = gameZone.offsetWidth;
canvas.height = gameZone.offsetHeight;
});