Как сравнить массив с вложенным массивом? - PullRequest
0 голосов
/ 31 октября 2019

Это мой первый раз код с Javascript. Я пытаюсь сделать игру в крестики-нолики. Я сделал большую часть этого, но я застрял в последней части. Мне нужно иметь возможность зарегистрировать победителя. У меня есть вложенный массив, содержащий все 8 возможных сценариев выигрыша (например, [[1, 2, 3], [4, 5, 6], ... и т. Д.)). Мое событие щелчка для плиток - это сбор идентификаторов моих плиток и помещение их в отдельный массив. Как я могу создать функцию win с моим текущим кодом?

Уже пробовал разные методы массива / цикла (например, split, if / else, for / loops и т. Д.). Не могу понять.

Мой код в repl.it:

https://repl.it/@drmartirosian/TTT?language=html

Необходимо каким-то образом подключить массивы моих игроков к массиву условий победы.

1 Ответ

0 голосов
/ 31 октября 2019

Код ниже будет работать:

  1. Вам нужно вставить целочисленное значение id в массиве проигрывателя, чтобы вы могли сравнить эти целочисленные значения со значениями массива win
  2. Затем вы можете проверить выигрыш игрока, используя некоторые функции-прототипы Array, такие как some и every, как показано ниже.

// Display an empty tic-tac-toe board when the page is initially displayed.--CHECK

// A player can click on the nine cells to make a move.--CHECK

// Every click will alternate between marking an X and O.--CHECK

// Once occupied with an X or O, the cell cannot be played again. --CHECK

// Provide a Reset Game button that will clear the contents of the board.--CHECK





/*------------ constants --------------*/
const win = [ //possible win scenarios...
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],

  [1, 4, 7],
  [2, 5, 8],
  [7, 8, 9],

  [1, 5, 9],
  [3, 5, 7],
];



/*----- app's state (variables) -------*/
var turn = []; //number of turns in game...
var playerO = []; //
var playerX = []; //



/*----- cached element references -----*/
//TILE BUTTONS
const tileAll = document.querySelectorAll('.tiles');
const content = document.getElementById('message'); //for message...


/*------------ event listeners ---------*/
//LISTENER FOR CLICK
tileAll.forEach(element => {
  element.addEventListener('click', tileClick);
});



/*------------ functions ----------------*/
//STATES OF GAMEPLAY...
function tileClick(event) {
  turn.push(''); //+1 to turn array per click
  let tileLabeler = event.target;
  if (turn.length % 2 !== 0 && turn.length <= 9) { //PLAYER1
    message.textContent = "PLAYER2'S TURN!";
    tileLabeler.innerHTML = "X";
    playerX.push(parseInt(tileLabeler.id));
    playerX.sort();
    let win = checkWin(playerX);
    if (win) {
      console.log("PLAYER X WON!! " + playerX);
    }

  } else { //PLAYER2
    message.textContent = "PLAYER1'S TURN!";
    tileLabeler.innerHTML = "O";
    playerO.push(parseInt(tileLabeler.id));
    playerO.sort();
    let win = checkWin(playerO);
    if (win) {
      console.log("PLAYER O WON!! " + playerO);
    }
  }
  if (turn.length >= 9) {
    return message.textContent = "GAME OVER!"
  }
};

function checkWin(playerArray) {
  return win.some((winArray) => winArray.every((winNumber) => playerArray.includes(winNumber)));
}
console.log("WIN CONDITIONS: " + JSON.stringify(win));
body {
  background-color: lightgray;
}

header {
  font-size: 10px;
  text-align: center;
  color: black;
}

.message {
  display: grid;
  font-size: 10px;
  text-align: center;
  color: black;
}

button {
  display: grid;
  font-size: 30px;
  width: 10%;
  margin-left: 45%;
  margin-right: 35%;
  margin-top: 10px;
}

button:hover {
  background-color: lightblue;
}

.tiles {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 50px;
  background-color: white;
  border-radius: 10px;
  width: 100px;
  height: 100px;
}

.tiles:hover {
  background-color: lightblue;
}

.alltiles {
  display: grid;
  grid-template-columns: 90px 90px 90px;
  grid-template-rows: 90px 90px 90px;
  grid-gap: 18px;
  width: 320px;
  height: 20px;
  margin: auto;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <header>TIC-TAC-HERO!</header>
  <message class="message" id="message">START!</message>

  <div class="alltiles" id="tall">
    <button onclick="this.disabled=true" class="tiles" id="1"></button>
    <button onclick="this.disabled=true" class="tiles" id="2"></button>
    <button onclick="this.disabled=true" class="tiles" id="3"></button>
    <button onclick="this.disabled=true" class="tiles" id="4"></button>
    <button onclick="this.disabled=true" class="tiles" id="5"></button>
    <button onclick="this.disabled=true" class="tiles" id="6"></button>
    <button onclick="this.disabled=true" class="tiles" id="7"></button>
    <button onclick="this.disabled=true" class="tiles" id="8"></button>
    <button onclick="this.disabled=true" class="tiles" id="9"></button>
  </div>
</body>
<script defer src="script.js"></script>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...