Skip to content

Instantly share code, notes, and snippets.

@michalczaplinski
Created June 13, 2019 15:47
Show Gist options
  • Save michalczaplinski/aabbfe350fbe9a75bc0e6b7cae927bd7 to your computer and use it in GitHub Desktop.
Save michalczaplinski/aabbfe350fbe9a75bc0e6b7cae927bd7 to your computer and use it in GitHub Desktop.
Tic Tac Toe
let boardState = [0, 0, 0, 0, 0, 0, 0, 0, 0];
// 1 is X
// 2 is O
const winningIndices = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
function checkSolution() {
for (let i = 0; i < winningIndices.length; i++) {
const indices = winningIndices[i];
const mark = boardState[indices[0]];
const mark1 = boardState[indices[1]];
const mark2 = boardState[indices[2]];
if (mark === 1 && mark1 === 1 && mark2 === 1) {
return 1;
}
if (mark === 2 && mark1 === 2 && mark2 === 2) {
return 2;
}
}
}
const board = document.querySelector('.board');
board.addEventListener('click', (e) => {
const targetId = e.target.id;
let cell = document.getElementById(targetId);
cell.innerHTML = 'X';
turn++;
boardState[targetId] = 1;
checkSolution();
const result = checkSolution();
if (typeof result !== 'undefined') {
alert(`${result} won`);
boardState = [0,0,0,0,0,0,0,0,0];
const cells = board.querySelectorAll('.cell');
cells.forEach((cell) => {
cell.innerHTML = '';
});
}
})
function computerPlay(boardState) {
// if we already have 2 in same row / diagonal and the last one is empty
// then put the winning mark
for (let i = 0; i < winningIndices.length; i++) {
const indices = winningIndices[i];
const mark = boardState[indices[0]];
const mark1 = boardState[indices[1]];
const mark2 = boardState[indices[2]];
// for (let i 0 ;)
}
//
//
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment