JSFiddle - React, Tailwind, and code Playground
by AndrewKuk
HTML
<div class="field" id="field">
</div>
JavaScript
//"use strict";
console.clear();
const CELL_SIZE = 50;
const CELL_STYLES = {
width : CELL_SIZE + "px",
height : CELL_SIZE + "px",
position : "absolute",
textAlign : "center",
fontSize : "15px"
};
const SIZE = 3;
let positions = [];
let cells = [];
createField(SIZE);
function createField(size) {
let fieldContainer = document.getElementById("field");
fieldContainer.style.position = "relative";
let counter = 0;
for (let i = 0; i < size; i++) {
positions[i] = [];
for (let j = 0; j < size; j++){
positions[i][j] = -1;
counter++;
cells.push(cell(fieldContainer, i, j, counter));
}
}
return cells;
}
function cell(parent, i, j, counter) {
let top = i;
let left = j;
let cell = document.createElement("BUTTON");
setStyle(cell, CELL_STYLES);
cell.style.top = top * CELL_SIZE + "px";
cell.style.left = left * CELL_SIZE + "px";
cell.textContent = "";
cell.addEventListener("click", function(event) {
listener(event, i, j, cell);
});
parent.appendChild(cell);
return cell;
}
function setStyle(obj, styles){
for(let style in styles){
obj.style[style] = styles[style];
}
}
let firstStep = (function() {
let step = Math.floor(Math.random() * 10) + 1;
if (step <= 5) {
return console.log("the first move of the player");
} return computerStep() + console.log("the first move of the computer");
})();
function listener(event, i, j, cell) {
if (positions[i][j] == -1 && checkField(1) == false && checkField(0) == false) {
cell.textContent = "X";
} else if (checkField(1) == true || checkField(0) == true) {
console.log("Game over");
return;
} else {
console.log("This cell is already taken");
return;
}
positions[i][j] = 1;
checkWinForPlayer();
}
function checkWinForPlayer() {
let win = checkField(1);
return win ? console.log("player WIN") : computerStep();
}
function computerStep() {
let pos = checkFree();
if(pos) {
cells[pos[0] * SIZE + pos[1]].textContent = "O"
} else {
...