Hi everyone,
I am sharing my code (I am not a developer and I am fully aware it is not the most optimised and the most elegant, still a lot to learn for sure):
function visualizeBoard(gameBoard){
let boardString=''
let gameBoardClone=[...gameBoard]
for (let index in gameBoardClone){
if (gameBoardClone[index]===null){
gameBoardClone[index]=parseInt(index)+1;
}
}
for (let i=0;i<=2;i+=1){
boardString=boardString+`${gameBoardClone[3*i]} ${gameBoardClone[3*i+1]} ${gameBoardClone[3*i+2]}` + '\n';
}
return boardString;
}
function getUserInput(gameBoard, nextPlayerSymbol){
let boardString=visualizeBoard(gameBoard);
let coordinates=prompt(`User ${nextPlayerSymbol}, make your pick\n ${boardString}`);
return coordinates;
}
function isMoveValid(coordinates, gameBoard){
if (gameBoard[coordinates-1] ===null)
{
return true
}
else
{
return false
}
}
function makeAMove(gameBoard, nextPlayerSymbol) {
newgameBoard=[...gameBoard];
let coordinates='';
do {
coordinates = getUserInput(gameBoard,nextPlayerSymbol);
} while ( isMoveValid(coordinates, gameBoard)===false );
newgameBoard[coordinates-1]=nextPlayerSymbol;
return newgameBoard;
}
function isGameOver(gameBoard, currentPlayerSymbol) {
// 1. check if there is a winner
if (hasLastMoverWon(currentPlayerSymbol, gameBoard) )
{
// Write a message that last mover has won the game
alert(`Congratulations, ${currentPlayerSymbol} has won the game`);
return true;
}
else
{
// Return: winner/draw OR game is still in progress
let indic=0;
for (let index in gameBoard)
{
if (gameBoard[index]===null)
{
//console.log(gameBoard[index]);
indic=indic+1;
}
}
if (indic===0)
{
alert('That is a draw');
return true;
}
else
{
return false;
}
}
}
function ticTacToe() {
let gameBoard = new Array(9).fill(null);
let players = ['X', 'O'];
let currentPlayerSymbol=null
do {
if (currentPlayerSymbol==='X'){
currentPlayerSymbol='O'}
else
{currentPlayerSymbol='X'}
gameBoard = makeAMove(gameBoard, currentPlayerSymbol);
} while ( !isGameOver(gameBoard, currentPlayerSymbol) );
}