I’m currently working on a Tic-Tac-Toe game for the odin project. The requirement for now is to get the game running purely on the console. Here’s the code I’ve written so far:
const board = {
a:[ "", "", ""],
b:[ "", "", ""],
c: [ "", "", ""]
}
function gameBoard() {
const getBoard = () => board;
const putToken = (gridItem) => {
if (gridItem === "") {
gridItem = game.getActivePlayer().token;
}
}
const printBoard = () => console.log(board);
return {
getBoard, printBoard, putToken
}
}
function gameController(playerOneName = "Player One", playerTwoName = "Player Two") {
const boards = gameBoard();
const players = [
{
name: playerOneName,
token: "O"
},
{
name: playerTwoName,
token: "X"
}
];
let activePlayer = players[0];
const switchPlayerTurn = () => {
activePlayer = activePlayer === players[0] ? players[1] : players[0]
}
const getActivePlayer = () => activePlayer;
const printNewRound = () => {
boards.printBoard();
console.log(`${getActivePlayer().name}'s turn.`)
}
const playRound = (gridItem) => {
boards.putToken(gridItem);
switchPlayerTurn();
printNewRound();
}
printNewRound();
return {
playRound, getActivePlayer
}
}
const game = gameController();
I’m currently having trouble trying to execute a player’s turn to input his mark ‘O’ ‘X’ onto the gameboard.
I tried running
game.playRound(board.a[1])
, which will run gameBoard().putToken(board.a[1])
,
which i had hoped to change board.a[1] into the active player’s token which is ‘O’. However, when i tried logging the supposedly updated gameboard, nothing has changed. I’m not sure what went wrong because I tried manually running board.a[1] = game.getActivePlayer().token
in the console and it worked fine. Can anyone tell me where I went wrong ? Thank you !