简体   繁体   English

蛇游戏的重启按钮

[英]Restart button for snake game

I started studying JS from a couple of weeks.我从几周开始学习 JS。 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这是我的代码: 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:从您的 JS 文件来看,问题似乎出在这个函数上:

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.要在按下时重置电路板,您应该删除该 if 语句。 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.因此,如果 has_game_ended 为真,则该行将被跳过,并且您的 main() 函数中低于该行的重置游戏函数将实际执行。 At the moment, you return (exit) out of the function if your game has ended which is not what you want.目前,如果您的游戏已经结束,这不是您想要的,则您返回(退出)该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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