Here's an animation that shows each square's index:
mousePressed function is called when the player clicks the mouse
In the snowflake game, we learned that
mouseY are inaccurate if the canvas is resized, which it often is so we have to adjust to the canvas resize ratio.
With the mouse location, we can now find the row and column the mouse is in with some division. We can then find the index of the grid square by using a formula:
numberOfColumns * rowNumber + columnNumber.
Then we simply check if the grid square is empty at the index. If not, then we assign it the letter X and redraw the game.
Here's an example of how to shorten code using the
The player's turn should now switch properly!
You should see a Game Over message once the grid is filled and the game will reset when the mouse is pressed.