//Set player and AI characters
const hooman = "x";
const ai = "o";
var game = $('#gameBoard');
var board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
//set cells
var cell = $('#gameBoard .cell');
jQuery(document).ready(function() {
// add player character on click then fill next empty with AI character
$('#gameBoard .cell').on('click', function() {
// to check empty cell we add a value attribute. Empty cells do not have value attr.
if (!$(this).attr('value')) {
//fill clicked cell with X
$(this).text(hooman).attr('value', '1');
var row = $(this).attr('data-row');
var col = $(this).attr('data-col');
board[row][col] = 1;
// empty msg area, if any
$('#msg').text('');
if (checkWin()) {
//call AI turn function
aiTurn();
}
} else {
//if cell is not empty, as it has value attr. show err msg
$('#msg').text('Wrong move. Pick another cell!');
//pe care il scot dupa cateva secunde
setTimeout(function() {
$('#msg').text('');
}, 3000);
}
});
$('.restart').on('click', function() {
restart();
});
});
//restart game
function restart() {
cell.text('').removeAttr('value');
$('#msg').text('');
game.removeClass('ended');
$('td').removeClass('red green grey');
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
}
function aiTurn() {
//select random empty cell
var random;
do {
random = Math.floor(Math.random() * ($('#gameBoard td').length-1));
} while ($("#" + random).text() != "");
//check if selected cell has val
$("#" + random).text(ai).attr('value', '-1');
var row = $("#" + random).attr('data-row');
var col = $("#" + random).attr('data-col');
board[row][col] = -1;
checkWin();
//exit from each function, if a cell without val attr has been found
return false;
}
function checkWin() {
var rowSum = [0, 0, 0];
var colSum = [0, 0, 0];
var diagSum = [0, 0];
var draw = 1;
for (var i = 0; i <=...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.