暂停/取消暂停Javascript俄罗斯方块游戏

Javascript: Pause/Unpause javascript Tetris game

本文关键字:暂停 方块 游戏 俄罗斯 Javascript 取消      更新时间:2023-09-26

我最近开始工作的javascript俄罗斯方块模板,我已经卡住了,试图实现暂停功能。我正在尝试创建一个窗口。Onkeydown功能,当一个按钮被点击,游戏将暂停,并切换到继续,一旦再次点击。

这是我的代码片段

function get(id) {
    return document.getElementById(id);
};
function hide(id) {
    get(id).style.visibility = 'hidden';
};
function show(id) {
    get(id).style.visibility = null;
};
function html(id, html) {
    get(id).innerHTML = html;
};
function timestamp() {
    return new Date().getTime();
};
function random(min, max) {
    return (min + (Math.random() * (max - min)));
};
function randomChoice(choices) {
    return choices[Math.round(random(0, choices.length - 1))];
};
if (!window.requestAnimationFrame) { // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback, element) {
            window.setTimeout(callback, 1000 / 60);
        }
}
var isPaused = true;
window.requestAnimFrame = (function () {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();
function Start() {
    if (isPaused) {
        Update();
    }
    requestAnimFrame(Start);
}
window.onkeydown = function () {
    isPaused = !isPaused; // flips the pause state
};
谁能给我指个正确的方向?

您必须在setTimeout上保留一个引用。如,

module.timeout = setTimeout(callback, 1000/60);

所以当你翻转isPaused时,清除两个超时并在你暂停它们的时候重新启动它们

clearTimeout(module.timeout)