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

60 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-03-18 10:29:12 +01:00
import { Game } from "./Game.js"
2021-03-23 09:23:37 +01:00
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();
};
2021-03-11 09:39:52 +01:00
document.addEventListener('DOMContentLoaded', function() {
M.AutoInit();
2021-03-23 09:23:37 +01:00
canvas.width = gameZone.offsetWidth;
canvas.height = gameZone.offsetHeight;
2021-03-11 09:39:52 +01:00
});