简体   繁体   中英

Restart button for snake game

I started studying JS from a couple of weeks. I was trying to do this guided exercise, adding functions like the restart button. I know I'm doing something wrong, can someone help me understand?

here is my code: https://github.com/StefaniaGalazzo/snake-game

Your code looks good so far. From your JS file, it seems like the problem is with this function:

function main() {

    if (has_game_ended()) return;

    changing_direction = false;
    setTimeout(function onTick() {
    clear_board();
    drawFood();
    move_snake();
    drawSnake();
    // Call main again
    main();
    }, 100)
    
}

Specifically this line:

if (has_game_ended()) return;

If you want the restartButton:

restartBtn.addEventListener("click", () => {
  return main();  
});

To reset the board when you press it, you should remove that if statement. Or, you can change add a ! to it

if (!has_game_ended()) return;

So, if has_game_ended is true, then that line will be skipped and your reset game functions below that in your main() function will actually be executed. At the moment, you return (exit) out of the function if your game has ended which is not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM