@@ -188,6 +188,9 @@ const CONFIG_DIFFICULTY = {
188188} ;
189189
190190function main ( ctime ) {
191+ const canvas = document . getElementById ( 'snakeCanvas' ) ;
192+ if ( ! canvas ) return ; // Exit loop if the game modal has been closed
193+
191194 window . requestAnimationFrame ( main ) ;
192195 if ( ( ctime - lastPaintTime ) / 1000 < 1 / speed ) {
193196 return ;
@@ -285,6 +288,18 @@ function gameEngine() {
285288 ctx . fillRect ( food . x * 20 , food . y * 20 , 18 , 18 ) ;
286289}
287290
291+ function restartGame ( ) {
292+ const selector = document . getElementById ( 'difficultySelect' ) ;
293+ applyDifficultySettings ( ) ;
294+ if ( selector ) selector . disabled = true ;
295+ document . getElementById ( 'game-over-overlay' ) . classList . add ( 'hidden' ) ;
296+ direction = { x : 1 , y : 0 } ;
297+ snakeArr = [ { x : 13 , y : 10 } ] ;
298+ score = 0 ;
299+ document . getElementById ( 'score' ) . innerHTML = score ;
300+ food = { x : 6 , y : 7 } ;
301+ }
302+
288303// Initialize execution listeners
289304function initSnakeGame ( ) {
290305 window . requestAnimationFrame ( main ) ;
@@ -304,21 +319,13 @@ function initSnakeGame() {
304319 applyDifficultySettings ( ) ;
305320 // Prevent changing parameter matrices on an active engine run
306321 if ( selector ) selector . disabled = true ;
322+ document . getElementById ( 'game-over-overlay' ) . classList . add ( 'hidden' ) ;
307323 direction = { x : 1 , y : 0 } ; // Start moving right
308324 } ) ;
309325
310- document . getElementById ( 'restartSnakeBtn' ) . addEventListener ( 'click' , ( ) => {
311- location . reload ( ) ;
312- } ) ;
326+ document . getElementById ( 'restartSnakeBtn' ) . addEventListener ( 'click' , restartGame ) ;
313327
314- document . getElementById ( 'overlayRestartBtn' ) . addEventListener ( 'click' , ( ) => {
315- document . getElementById ( 'game-over-overlay' ) . classList . add ( 'hidden' ) ;
316- if ( selector ) selector . disabled = false ;
317- direction = { x : 0 , y : 0 } ;
318- snakeArr = [ { x : 13 , y : 10 } ] ;
319- score = 0 ;
320- document . getElementById ( 'score' ) . innerHTML = score ;
321- } ) ;
328+ document . getElementById ( 'overlayRestartBtn' ) . addEventListener ( 'click' , restartGame ) ;
322329
323330 window . addEventListener ( 'keydown' , e => {
324331 // Change difficulty selection dynamic evaluations if arrow key registers
0 commit comments