繁体   English   中英

如何使用 Math.random() 在 JavaScript Tic Tac Toe 中的人类玩家和 AI 之间切换?

[英]How do I switch between human player and ai in JavaScript Tic Tac Toe with Math.random()?

我正在构建人类与人工智能井字游戏,我正在寻找一种方法让人工智能在人类玩家之后随机放置一个符号。 我正在尝试使用 Math.random() 来实现这一点,并使用 for 循环为 AI 播放器生成一个 id。 什么是实现这一目标的好方法? 到目前为止,它一直适用于人类,直到应该为 AI 播放器调用 insertMarker 方法。

JS

$(document).ready(function() {
  let huPlayer, computer;
  let huPlayerArr = [], computerArr = [];
  let occupiedCells = [];
  let winningCombos = [
    [1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]
  ];

  $cell = $('.cell');

  $('#myModal').modal('show');

  $('.select').click(function() {
    let turnX = 'X';
    let turnO = 'O';
    $(this).attr("data-dismiss", "modal");
    huPlayer = $(this).text() 
    computer = huPlayer === turnX ? turnO: turnX; 
    $('.player').append(`<div class="alert-success">You chose to play as ${huPlayer}</div>`);
  });

  function resetGame() {
    huPlayer = undefined;
    computer = undefined;
    huPlayerArr = [];
    computerArr = [];
    occupiedCells = [];

  }

  function isEmpty(el) {
    if ($.trim($(el).html()) == '') {
      return true;
    };
  }

  function insertMarker(text, val, id) {
    occupiedCells.push(+id);
    text.html(val);
  }

  function isThereAWinner(arr) {
    for (let i = 0; i < winningCombos.length; i++) {
      let check = (arr.indexOf(winningCombos[i][0]) != '-1'
          && arr.indexOf(winningCombos[i][1]) != '-1'
          && arr.indexOf(winningCombos[i][2]) != '-1') 
      if (check) {
        return check;
      }
    }
  }

  $cell.click(function() {
    if (huPlayer === undefined && computer === undefined) {
      $('#myModal').modal('show');
    } 
    else {
      let id = $(this).attr("id");

      if (isEmpty(id)) {
        insertMarker($(this), huPlayer, +id);
        huPlayerArr.push(+id);
        console.log(huPlayerArr);

        if (isThereAWinner(huPlayerArr)) {
          console.log("There's a winner");
          resetGame();
        }
        else if (occupiedCells.length === 9) {
          console.log("Tie game");   
        }
        else {
          let rand = Math.floor(Math.random() * 9) + 1;

          for (let i = 0; i < rand; i++) {
            if (occupiedCells.indexOf(rand) != '-1' && occupiedCells.length != 9) {
              if (occupiedCells.length !== 9) {
                insertMarker($('#' + rand), computer, +rand);
                computerArr.push(rand);
                console.log(computerArr);
              }
            }
          }
        }
      }
    }
  });
});

HTML

      <table>
        <tr>
          <td class="cell" id="1"></td>
          <td class="cell" id="2"></td>
          <td class="cell" id="3"></td>
        </tr>
        <tr>
          <td class="cell" id="4"></td>
          <td class="cell" id="5"></td>
          <td class="cell" id="6"></td>
        </tr>
        <tr>
          <td class="cell" id="7"></td>
          <td class="cell" id="8"></td>
          <td class="cell" id="9"></td>
        </tr>
      </table>

``

function aiTurn() {


    // while it is the AI's turn
    while(!Turn) {  
        // randomly select from array // select Move
        tryMove = arr[Math.floor(Math.random()*arr.length)];
        console.log("tryMove " + String(tryMove));
        if(document.getElementById(tryMove).innerHTML == "o") {
            // remove from array
            arr.splice(arr.indexOf(tryMove),1);
            // select Ai's turn
            document.getElementById(tryMove).classList.toggle("fade");
             document.getElementById(tryMove).innerHTML = "O";
             document.getElementById(tryMove).style.color = "white";
             // change back to users turn
             Turn = !Turn;
             checkForWin();
         }

        }

我用 AI 制作了一款井字游戏,在用户移动后我将其命名为 function。 您可以在https://github.com/rileyworstell/UpdatedTicTac/blob/master/TicTacGame/javascript1.js查看我的存储库中的文件

暂无
暂无

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

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