2020-03-23 13:16:25 +00:00
|
|
|
/**
|
|
|
|
* Game config
|
|
|
|
*/
|
2020-03-23 13:09:28 +00:00
|
|
|
const number_levels = 2;
|
2020-03-23 13:16:25 +00:00
|
|
|
const cell_width = 10;
|
|
|
|
const cell_height = 10;
|
2020-03-23 13:09:28 +00:00
|
|
|
|
|
|
|
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")
|
2020-03-23 13:16:25 +00:00
|
|
|
const canvasTarget = byId("canvasTarget")
|
2020-03-23 13:09:28 +00:00
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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";
|
2020-03-23 13:16:25 +00:00
|
|
|
|
|
|
|
// 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);
|
2020-03-23 13:09:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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 += "<li>" +
|
|
|
|
"<input type='radio' name='level' value='"+index+"' "+(index == 1 ? "checked" : "")+" />" +
|
|
|
|
" Level " + index + "</li>";
|
|
|
|
}
|
|
|
|
|
|
|
|
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();
|