javascript 如何添加计时器到井字游戏

axr492tv  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(167)

我建立了一个井字游戏,我需要添加一个计时器,所以如果一个球员没有作出移动30秒,他失去了比赛,但我不知道如何在游戏中实现这一点。游戏语言是希伯来语,但这并不重要,我尝试添加一个计时器从一些代码,我发现在网上与setTimeout,但我不'我不知道如何设置计时器重置后,每一轮和结束游戏后,时间运行和打印其他对手赢了。谢谢帮助!

  1. const ALL_WIN_COMBINATION = [
  2. [0, 3, 6],
  3. [1, 4, 7],
  4. [2, 5, 8],
  5. [0, 4, 8],
  6. [6, 4, 2],
  7. [0, 1, 2],
  8. [3, 4, 5],
  9. [6, 7, 8]
  10. ];
  11. //Player 'X' plays first
  12. let xTurn = true;
  13. let count = 0;
  14. //Disable All Buttons
  15. const disableButtons = () => {
  16. document.querySelectorAll(".block").forEach((element) => (element.disabled = true));
  17. //enable popup
  18. document.querySelector(".message").classList.remove("hide");
  19. };
  20. //Enable all buttons (For New Game and Restart)
  21. const enableButtons = () => {
  22. document.querySelectorAll(".block").forEach((element) => {
  23. element.innerText = "";
  24. element.disabled = false;
  25. });
  26. //disable popup
  27. document.querySelector(".message").classList.add("hide");
  28. };
  29. //This function is executed when a player wins
  30. const winFunction = (letter) => {
  31. disableButtons();
  32. if (letter == "X") {
  33. document.getElementById("text").innerHTML = "&#x1F389; <br> 'X' Wins";
  34. } else {
  35. document.getElementById("text").innerHTML = "&#x1F389; <br> 'O' Wins";
  36. }
  37. };
  38. //Function for draw
  39. const drawFunction = () => {
  40. disableButtons();
  41. document.getElementById("text").innerHTML = "&#x1F60E; <br> It's a Draw";
  42. };
  43. //New Game
  44. document.getElementById("restart_button2").addEventListener("click", () => {
  45. count = 0;
  46. enableButtons();
  47. });
  48. document.getElementById("restart_button").addEventListener("click", () => {
  49. count = 0;
  50. enableButtons();
  51. });
  52. //Win Logic
  53. const winChecker = () => {
  54. //Loop through all win patterns
  55. for (let i of ALL_WIN_COMBINATION) {
  56. let [element1, element2, element3] = [
  57. document.querySelectorAll(".block")[i[0]].innerText,
  58. document.querySelectorAll(".block")[i[1]].innerText,
  59. document.querySelectorAll(".block")[i[2]].innerText,
  60. ];
  61. //Check if elements are filled
  62. //If 3 empty elements are same and would give win as would
  63. if (element1 != "" && (element2 != "") & (element3 != "")) {
  64. if (element1 == element2 && element2 == element3) {
  65. //If all 3 buttons have same values then pass the value to winFunction
  66. winFunction(element1);
  67. }
  68. }
  69. }
  70. };
  71. //Display X/O on click
  72. document.querySelectorAll(".block").forEach((element) => {
  73. element.addEventListener("click", () => {
  74. if (xTurn) {
  75. xTurn = false;
  76. //Display X
  77. element.innerText = "X";
  78. element.disabled = true;
  79. } else {
  80. xTurn = true;
  81. //Display Y
  82. element.innerText = "O";
  83. element.disabled = true;
  84. }
  85. //Increment count on each click
  86. count += 1;
  87. if (count == 9) {
  88. drawFunction();
  89. }
  90. //Check for win on every click
  91. winChecker();
  92. });
  93. });
  94. //Enable Buttons and disable popup on page load
  95. window.onload = enableButtons;
  1. * {
  2. padding: 0;
  3. margin: auto;
  4. box-sizing: border-box;
  5. }
  6. body {
  7. height: 70vh;
  8. background-image: red;
  9. }
  10. html {
  11. font-size: 22px;
  12. text-align: center;
  13. }
  14. #intro{
  15. text-shadow: -1px 1px 2px white,
  16. 11px 1px 2px white,
  17. 1px -1px 0px white,
  18. -1px -1px 0px white;
  19. }
  20. #case {
  21. position:absolute;
  22. transform: translate(-50%, -16%);
  23. top: 50%;
  24. left: 50%;
  25. }
  26. #game_board {
  27. width: 49vmin;
  28. height: 49vmin;
  29. display: flex;
  30. flex-wrap: wrap;
  31. }
  32. .block {
  33. background: #ffffff;
  34. height: 15vmin;
  35. width: 15vmin;
  36. border: none;
  37. border-radius: 30px;
  38. font-size: 14vmin;
  39. color: black;
  40. }
  41. #restart_button {
  42. font-size: 1em;
  43. padding: 1em;
  44. border-radius: 90px;
  45. background-color: black;
  46. color: #ffffff;
  47. position: relative;
  48. }
  49. .message {
  50. background: red;
  51. height: 100%;
  52. width: 100%;
  53. position:absolute;
  54. transform: translate(-50%, -50%);
  55. top: 50%;
  56. left: 50%;
  57. gap: 1em;
  58. font-size: 12vmin;
  59. }
  60. #restart_button2 {
  61. font-size: 1em;
  62. padding: 1em;
  63. border-radius: 90px;
  64. background-color: black;
  65. color: #ffffff;
  66. position: relative;
  67. }
  68. #text {
  69. color: black;
  70. text-shadow: -1px 1px 2px white,
  71. 11px 1px 2px white,
  72. 1px -1px 0px white,
  73. -1px -1px 0px white;
  74. text-align: center;
  75. font-size: 2em;
  76. }
  77. .message.hide {
  78. display: none;
  79. }
  1. <!DOCTYPE html>
  2. <html dir="rtl" lang="he">
  3. <head>
  4. <meta charset="UFT-8" content="width=device-width, initial-scale=1.0">
  5. <link rel="stylesheet" href="style.css">
  6. <title>איקס עיגול - מאור ישראלי</title>
  7. <div id="intro">
  8. <div id = "title">
  9. <u><h1>איקס עיגול</h1></u>
  10. </div>
  11. <div id ="target_header">
  12. <h2>מטרת המשחק:</h2>
  13. </div>
  14. <div id="target">
  15. <b>מטרת כל שחקן היא ליצור שלושה סימנים (איקס או עיגול) הנמצאים על שורה אחת, טור אחד או אלכסון אחד.</b>
  16. </div>
  17. <div id ="instruction_header">
  18. <h2>הוראות:</h2>
  19. </div>
  20. <div id ="instruction">
  21. <b>
  22. המשחק מתחיל בלחיצה על אחד התאים,<br>
  23. השחקן הראשון שלוחץ הוא ה-X והשחקן השני הוא ה-O.<br>
  24. אם לא מתבצע מהלך תוך 30 שניות השחקן מפסיד!<br>
  25. </b>
  26. </div>
  27. <div id="timer">
  28. <b><u>
  29. זמן שנותר: <span id="counter"></span>
  30. </u></b>
  31. </div>
  32. </div>
  33. </head>
  34. <body>
  35. </div>
  36. <div id ="case">
  37. <div id="game_board">
  38. <button class="block"></button>
  39. <button class="block"></button>
  40. <button class="block"></button>
  41. <button class="block"></button>
  42. <button class="block"></button>
  43. <button class="block"></button>
  44. <button class="block"></button>
  45. <button class="block"></button>
  46. <button class="block"></button>
  47. </div>
  48. <button id="restart_button">התחל מחדש</button>
  49. </div>
  50. <div class="message hide">
  51. <p id="text">דוגמא</p>
  52. <button id="restart_button2">התחל מחדש</button>
  53. </div>
  54. <script src="tictac.js"></script>
  55. </body>
  56. </html>
huwehgph

huwehgph1#

这是我尝试在一个非常基本的两人游戏中使用计时器策略。
本演示中使用的方法是在游戏等待玩家移动的任何时候调用setTimeout。当时间到期时,回调将运行并关闭游戏。如果玩家在时间到期前移动,则计时器将被清除,并为下一个玩家启动新的计时器。
我尽了最大的努力让它尽可能的简单,但是当我添加了一个全局计时器时,它变得更密集了。无论如何,它进一步展示了全局计时器如何独立于玩家的事件计时器,并以更小的时间粒度来增加时钟,就像我在这里所做的:

  1. document.getElementById('makemove')
  2. .addEventListener('click', waitForNextMove);
  3. function waitForNextMove(){
  4. resetTimer();
  5. currentPlayer = ++currentPlayer % 2;
  6. playerName = players[currentPlayer];
  7. console.log(`${playerName}, waiting for your next move...`);
  8. document.querySelector('.player').innerText = playerName;
  9. //here resets the previous timer
  10. clearInterval(currentTimer);
  11. //and starts the new one
  12. currentTimer = setTimeout(onTimeExpired, duration);
  13. }
  14. const onTimeExpired = () => {
  15. console.log("Time expired!");
  16. gameOver();
  17. stopTimer();
  18. }
  19. const gameOver = () => {
  20. console.log('The game is over.');
  21. document.getElementById('makemove').disabled = true;
  22. }
  23. const duration = 5000;
  24. const players = ['player1', 'player2'];
  25. let currentPlayer = -1;
  26. let currentTimer;
  27. let globalTimer;
  28. waitForNextMove();
  29. //----Global Timer
  30. startTimer();
  31. function startTimer(){
  32. globalTimer =
  33. setInterval(()=>{
  34. incrementTimer();
  35. }, 1000);
  36. }
  37. function stopTimer(){
  38. document.getElementById('timer').innerText = '5';
  39. clearInterval(globalTimer);
  40. }
  41. function resetTimer(){
  42. document.getElementById('timer').innerText = '0';
  43. }
  44. function incrementTimer(){
  45. const t = document.getElementById('timer');
  46. const i = parseInt(t.innerText) + 1;
  47. t.innerText = i;
  48. }
  1. :root{
  2. --padding: .2rem .6rem;
  3. }
  4. label{
  5. border: solid lightgray;
  6. padding: var(--padding);
  7. }
  8. button{
  9. padding: var(--padding);
  10. cursor: pointer;
  11. }
  12. #timer{
  13. display: inline-block;
  14. border: solid 2px;
  15. padding: var(--padding);
  16. background: red;
  17. color: white;
  18. font-weight: 600;
  19. }
  1. <label>PLAYER: <span class="player"></span></label>
  2. <button id="makemove">Make your move!</button>
  3. <div id="timer">1</div>
展开查看全部

相关问题