Skip to content
Advertisement

How to prevent players from updating their marker on Tic Tac Toe

I’m working on a Tic Tac Toe project and having trouble with a certain task.

Build the functions that allow players to add marks to a specific spot on the board, and then tie it to the DOM, letting players click on the gameboard to place their marker. Don’t forget the logic that keeps players from playing in spots that are already taken!

Specifically the “Don’t forget the logic that keeps players from playing in spots that are already taken!

I’m trying to see how to prevent the players from updating their marker from “X” to “O” and vice versa. I’d have to implement some sort of way to check if the cell is empty then don’t update the array/board any more, but I’m not sure how to go about it.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

With the code you already have in place, you can read a cell’s value with Gameboard.getBoard()[index]. If that is still the empty string (and thus not “X” or “O”), then it is OK to play at that index.

So you could add this statement:

JavaScript

Here is your updated snippet:

JavaScript
JavaScript
JavaScript

Not your question, but don’t forget to add logic that detects a win or a draw and act accordingly.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement