From 9f77fd526296f098bdfc4d3bfd811733961c187d Mon Sep 17 00:00:00 2001 From: Codinget Date: Mon, 6 Apr 2020 12:02:22 +0200 Subject: [PATCH] fixed duplicate games (closes #20) --- src/js/main.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/js/main.js b/src/js/main.js index 586ae53..bb4e758 100644 --- a/src/js/main.js +++ b/src/js/main.js @@ -25,7 +25,7 @@ let currentGame=null; // forward-declare functions - let resizeCanvas, getLevel, startGame, handleWin, handleDeath, menu, help, restart; + let resizeCanvas, getLevel, startGame, stopGame, handleWin, handleDeath, menu, help, settings, restart; // handle window resize and fullscreen resizeCanvas=() => { @@ -92,15 +92,31 @@ }); }); + // stop a running game + stopGame=() => { + if(currentGame) { + // stop the actual game + currentGame.playing=false; + + // setup the DOM + nav.classList.remove('hidden'); + canvas.classList.add('hidden'); + hud.classList.add('hidden'); + } + }; + // start a new game startGame=async (category, levelId, filename) => { // stop any running games - if(currentGame) currentGame.playing=false; + stopGame(); // load rules and level from cache or server const rules=levelList[category].rules || {}; const level=await levels.get(filename); + // stop any running games again + stopGame(); + // create the game and attach the callbacks and config const snek=currentGame=new SnekGame(level, canvas, rules); snek.callback=evt => { @@ -135,13 +151,7 @@ // return to the menu menu=() => { - // stop any running games - if(currentGame) currentGame.playing=false; - - // setup the DOM - nav.classList.remove('hidden'); - canvas.classList.add('hidden'); - hud.classList.add('hidden'); + stopGame(); }; // display the win popup @@ -238,6 +248,7 @@ if(hash=='' || hash=='menu') return menu(); else if(hash=='help') return help(); + else if(hash=='settings') return settings(); const [_, category, levelId, filename]=location.hash.match(/([a-zA-Z0-9_-]+?)\/([a-zA-Z0-9_-]+?)\/(.+)/); startGame(category, levelId, filename);