簡體   English   中英

當 Javascript memory 游戲結束時,如何停止計時器計數?

[英]How to stop a timer from counting when a Javascript memory game finishes?

我有一個關於如何在“找對”游戲中停止計時器的問題,該游戲內置於 javascript 用於學校項目。

在嘗試在線尋求幫助時,我注意到類似游戲的其他 javascript 項目。 但是,我發現的那些更多地使用了 CSS 功能,而我試圖完成的那個幾乎具有 javascript 中內置的所有功能。

為了給出描述,有一個帶有隨機徽標的板(6x8),我們稱它們為“卡片”。 游戲開始,所有卡片隨機排序,然后隱藏。

在玩家嘗試匹配它們時,所有卡片在 60 秒內保持在同一個 position 中。 在那之后,只有沒有配對的牌會重新排序,玩家將不得不再次嘗試配對。

代碼必須做的一件事是停止所有卡片正確配對的時間,即游戲結束時。

下面是用於結束游戲的代碼的最后一個版本。 function tempo() 應該定義時間。 temporizador 是時間進度條。 contador 是用於計算時間的變量。

function tempo(){       //function that controls our time progress bar, uses 60 seconds (maxCount) for its cycle
    let contador=0;     
    let maxCount=60;
     temporizador=null;
    if (temporizador != null) clearInterval(temporizador)   
    else 
    temporizador=setInterval(()=>{
        contador++;
        document.getElementById("time").value=contador;
        if(contador===maxCount-5)document.getElementById("time").classList.add("warning");  //when it takes 5 seconds to end the 60 seconds
        if(contador===maxCount) {                                                           //in the time bar, you can see the bar in red, blinking
            clearInterval(temporizador);                                                    
            document.getElementById("time").classList.remove("warning");                    //when cycle finished the red blinking stops
            scramblerEscondidas();                                                          //and the function scramblerEscondidas() to sort the unmatched pairs, is executed
        }                                                                                   
    },1000)
    for (let i=0; i<6; i++) {              //cycle to iterate the rows of the board
        for(let j=0; j<8; j++){            //cycle to iterate the columns of the board
            if (game.board[i][j].virada=true) tempo.stop();  //'virada' is a property of each card of the board, if true it displays the logo. defined in the 'const' for the card
                game.sounds.win.play();
        }

    }
    
}

在這個 function 中的最后一個循環應該檢查是否所有的牌都轉給了玩家,這意味着游戲結束了。 發生這種情況時應該停止時間(時間欄中的進度),但計時器不會停止。

對不起我的菜鳥。 任何人都可以就如何找到解決方案提供任何提示嗎? 我也嘗試了不同的方法,但我擔心它們都使用相同的邏輯,這可能是錯誤的。 任何簡單的提示都會有所幫助,因為我最近才開始使用 javascript。

我沒有看到你想用這些代碼做什么。 但我明白你的意思是停止計時器。

要使計時器停止,您只需將名為isHaveWinnerboolean變量設置為默認值。 然后用

 if (.isHaveWinner) {...your timer iteration }

在您的游戲邏輯中,如果游戲完成,請將isHaveWinner設置為true 所以你的計時器不會再運行了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM