Skip to content

Instantly share code, notes, and snippets.

@letroot
Created Sep 24, 2019
Embed
What would you like to do?
const X_IMAGE_URL = "res/x.png";
const O_IMAGE_URL = "res/circle.png";
const SYMBOLS = {
'x': X_IMAGE_URL,
'o': O_IMAGE_URL
};
function playGame() {
const freeBoxes = [];
const takenBoxes = {};
for (box of document.querySelectorAll('#grid div')) {
box.addEventListener('click', function playX(event) {
playXHandler(event, freeBoxes, takenBoxes);
box.removeEventListener('click', playX);
});
freeBoxes.push(box);
}
}
function deleteFromArray(element, array) {
let index = array.indexOf(element);
array.splice(index, 1);
}
function assignToBox(box, player, freeBoxes, takenBoxes) {
/*
`box` is a div element
`player` is a single character string
representing the respective symbols
of both player
*/
const image = document.createElement('img');
image.src = SYMBOLS[player];
box.appendChild(image);
deleteFromArray(box, freeBoxes);
takenBoxes[box.dataset.index] = player;
}
function playXHandler(event, freeBoxes, takenBoxes) {
assignToBox(event.currentTarget, 'x', freeBoxes, takenBoxes);
checkForWinner(takenBoxes);
computerPlayO(freeboxes, takenBoxes);
}
function checkForWinner(takenBoxes) {
console.log(takenBoxes);
}
function computerPlayO(freeBoxes, takenBoxes) {
let index = Math.random() * freeBoxes.length;
let box = freeBoxes[index];
assignToBox(box, 'o', freeBoxes, takenBoxes);
}
playGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment