Ti c -ta c - игра пальцами; JavaScript; код написан но не работает - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь создать игру 'ti c -ta c -toe' на JavaScript. На самом деле это моя домашняя работа, однако мой учитель отказывается давать мне какие-либо отзывы, хотя я полностью застрял. Так или иначе, моя задача - составить лог c игры, слушатели действий уже заданы задачей. Я провел исследование и написал код, но игра работает некорректно, а именно: программа не проверяет, была ли победа, и не отображает, кто победил. Кроме того, он не проверяет, была ли ничья. Вот мой код, с которым мне нужна помощь:

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('-')
}

Проблема в том, что для меня этот код имеет смысл. Мой учитель тоже не указал на серьезные ошибки. Однако я не могу найти причину, по которой игра не показывает, кто победил, или даже не останавливается на каком-то этапе. Код ниже: не обязательно читать, потому что это просто заданная задача, и если вы хотите увидеть, как игра выглядит вживую.

Вот что было дано задачей (также 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 Ответ

1 голос
/ 17 июня 2020

похоже, что ваши функции, которые проверяют результаты игры, например ifWon и ifDraw, пытаются проверить равенство массивов с помощью ===. Это не сработает, поскольку проверка равенства массивов требует проверки, соответствует ли каждый элемент в одном массиве соответствующему элементу (т. Е. Элементу с тем же индексом) во втором массиве. Один из быстрых способов проверить равенство массивов - использовать JSON.stringify:

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

надеюсь, что это поможет!

...