Created
September 24, 2019 16:09
-
-
Save letroot/9d3d26c83ba1a95f44b22c133fe7ee2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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