井字游戏; JavaScript;代码已编写但不起作用

时间:2020-06-17 14:38:20

标签: javascript arrays tic-tac-toe

我正在尝试在 JavaScript 上创建“井字游戏”。这实际上是我的作业,但是,即使我完全陷入困境,我的老师也拒绝给我任何反馈。无论如何,我的任务是组成游戏的逻辑,任务已经给出了动作监听器。我进行了研究,并编写了代码,但是游戏无法正常运行,即程序不检查是否赢得了比赛,也不显示谁是赢家。此外,它不会检查是否有平局。这是我的代码,需要我的帮助:

let players = ['x', 'o'];
let activePlayer = 0;

const winningCombos = [
  ['0', '0', '1', '1', '2', '2'],
  ['0', '2', '1', '1', '2', '0'],
  ['0', '0', '0', '1', '0', '2'],
  ['1', '0', '1', '1', '1', '2'],
  ['2', '0', '2', '1', '2', '2'],
  ['0', '0', '1', '0', '2', '0'],
  ['0', '1', '1', '1', '2', '1'],
  ['0', '2', '1', '2', '2', '2'],
]

let board = [
  ['', '', ''],
  ['', '', ''],
  ['', '', '']
];

function switchPlayer() {
  if (activePlayer == players[0]) {
    activePlayer = players[1]
  } else if (activePlayer == players[1]) {
    activePlayer = players[0]
  } else {
    console.log('Error')
  }
}

function startGame() {
  activePlayer = players[Math.floor(players.length * Math.random())]; // Random selection of the first active player
  alert ('Active player is: ' + activePlayer);
  renderBoard(board);
}

let oResult = []; // an Arry for storing the rows and columns of the 'o' 
let xResult = []; // an Arry for storing the rows and columns of the 'x' 


//This is the function that is supposed to check whether there is a draw, but does not do that. My idea was that it should check, if the 'oResult' and the 'xResult' arrays have reached their maximum (so they are completely filled) and if yes, they should display into the console the phrae "it's a draw"
function ifDraw() {
  if (((oResult.length === 7) && (xResult.length === 9)) || ((oResult.length === 9) && (xResult.length === 7))) {
    console.log('its a draw')
  } 
}
//This function does not work as well, if I understand correctly. I thought, that the FOR cycle would go through each array in the 'winningCombos' array and compare it with the oResult and the 'xResult' arrays. When one of these two arrays matches one of the arrays from 'winningCombos', then the function 'showWinner' is called (the 'showWinner' function is already given by the task)
function ifWon() {
  for (let i = 0; i < winningCombos.length; i++) {
    if ((oResult === winningCombos[i]) || (xResult === winningCombos[i])) {
      showWinner(activePlayer)
    } 
  }
}

function click(row, column) {
  board[row][column] = activePlayer;
  switchPlayer();
  renderBoard(board);

  //Even though it was stated clearly, that the values of 'x' have to be written into the 'xResult' and the values of 'o' - into the 'oResult', the program sometimes mixes it up and the values of 'x' sometimes go to the 'oResult'. Why?
  if (activePlayer === 'x') {
    xResult.push(row);
    xResult.push(column);
  } else if (activePlayer === 'o') {
    oResult.push(row);
    oResult.push(column);
  }

  //These don't work
  ifDraw();
  ifWon();

  // Here I display what has been assignet to what in the console so that I can check the process
  console.log(xResult)
  console.log(oResult)
  console.log('-')
}

问题在于,对我而言,代码有意义。我的老师也没有指出任何重大错误。但是,我找不到游戏为什么不显示谁赢了,甚至停在a点上的原因。 下面的代码不是必需的,因为它只是给定的任务,如果您想查看游戏的直播效果,则无需阅读。

以下是任务给出的内容( JS 也位于另一个文件中):

window.addEventListener('load', startGame);

let boardEl = document.getElementById('board');
let modalEl = document.getElementById('modal');
let resetButtons = document.getElementsByClassName('reset');

for (let btn of resetButtons) {
  btn.addEventListener('click', function () {
    if (!modalEl.classList.contains('hidden')) {
      modalEl.classList.add('hidden');
    }
    startGame();
  });
}

boardEl.addEventListener('click', function (event) {
  let targetClasses = event.target.classList;
  let targetData = event.target.dataset;
  if (targetClasses.contains('field') && !targetClasses.contains('busy')) {
    click(targetData.row, targetData.col);
  }
});

function showWinner(winner) {
  let header = modalEl.getElementsByTagName('h2')[0];
  header.textContent = `? Won the player №${winner + 1}! ?`;
  modalEl.classList.remove('hidden');
}

function renderBoard(board) {
  const fields = [];
  for (let [i, row] of board.entries()) {
    for (let [j, value] of row.entries()) {
      fields.push(`
        <div class="field ${value ? 'busy' : 'free'}" 
            data-row="${i}" 
            data-col="${j}"
            style="grid-row:${i + 1};grid-column:${j + 1};"
        >
          ${value || ''}
        </div>
      `);
    }
  }
  boardEl.innerHTML = fields.join('');
}

下面是构成外观的HTML和CSS文件(任务也提供了这些文件)。如果您想看到我所看到的内容,我将使用Repl.it平台进行写作。 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tic-tac-toe</title>
    <link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>

<div id="board"></div>

<div id="modal" class="hidden">
    <div id="modal__window">
        <h2></h2>
        <div id="modal__buttons">
            <button class="reset">Play again</button>
        </div>
    </div>
</div>
<div class="panel">
    <button class="reset">From the beginning</button>
</div>

<script src="logic.js"></script>
<script src="ui.js"></script>
</body>
</html>

CSS:

* {
    box-sizing: border-box;
}
.panel {
    text-align: center;
}



#board {
    position: relative;
    height: 450px;
    width: 450px;
    margin: 50px auto 30px auto;
    overflow: hidden;
    display: grid;
    grid-auto-columns: 1fr;
    grid-auto-rows: 1fr;
    grid-gap: 10px;
}

.field {
    background-color: #78bec5;
    border-radius: 14px;
    cursor: pointer;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 5em;
    font-family: 'Arial', sans-serif;
}

.free:hover {
    background-color: #3d4250;
}

#modal {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
}

#modal__window {
    position: relative;
    top: 30%;
    width: 30%;
    margin: 0 auto;
    padding: 5px 20px 20px;
    background-color: #f8f6f6;
    text-align: center;
}

button {
    min-width: 100px;
    border: 1px solid lightgray;
    padding: 15px;
    background-color: #fff;
    font-size: 20pt;
    border-radius: 15px;
    opacity: 0.7;
}

button:hover {
    box-shadow: 2px 1px 0 rgb(0, 0, 0);
}

button:active {
    box-shadow: inset 2px 1px 0;
}

.hidden {
    display: none;
}

如果有任何帮助或指示,我将非常感谢,我不知道我在做什么错,哪里出了错。预先谢谢你!

1 个答案:

答案 0 :(得分:1)

看起来您的函数正在检查游戏的结果,例如ifWonifDraw试图使用===检查数组的相等性。这将不起作用,因为检查数组的相等性需要检查一个数组中的每个元素是否与第二个数组中的相应元素(即,具有相同索引的元素)相匹配。一种测试数组相等性的快速方法是使用JSON.stringify

if (JSON.stringify(arr1) === JSON.stringify(arr2)) {...your code here}

希望有帮助!