Writing small puzzle games is a nice way of improving your programming skills as those games tend to present you with challenge after challenge and force you to really put tremendous thought into writing your code.

One such game is the classic Tic-Tac-Toe.

In this little walk-through (read long and descriptive) about writing an unbeatable tic-tac-toe, I will be using Vanilla JavaScript for logic and HTML/CSS for UI. I won’t be concentrating much on UI part of it, because, duh!

Another little disclaimer — we will be concentrating on logic primarily and code will come second to that. Again, if you want to skip the “walk-through” and jump right to the code, I have a public repository on GitHub at https://github.com/FaisalST32/tic-tac-toe. I also have a live version of the game available at http://games.faisalrashid.xyz/tictactoe/

So, let’s dive in.

First of all you need to create the UI. Just use simple HTML to create 9 input boxes, or divs even to hold your X’s and O’s. The id’s of these input boxes are important as they will be our reference to the X’s and O’s. To keep it consistent with the positioning of our boxes, I have given the input boxes the id’s “0–0” to “2–2”. To visualize:

0–0 0–1 0–2

1–0 1–1 1–2

2–0 2–1 2–2

This will give us an easy to use 3x3 matrix. You can design your UI whatever way you want. It should simply employ this form of queryable HTML elements.

Here’s a screenshot of my UI. Simple boxes with a little gloss of CSS.

Now, the logic! First of all, whenever a user, or a participant in this case, clicks or taps an empty box, the value of that box should change to either an X or an O, depending upon whose turn it is.

Implementing that is simple. I use a global variable to hold the ‘currentPlayer’. This variable has a value of either X or O. Then I simply write a method to toggle current player, whenever a box is tapped. I call the method changePlayer.

All this is started by tapping a box. So, we need a function to get us started. We write a function that marks the box with X or O and changes player. We call the function onCheckBox. So far, the function checks a box and and then changes player.

#unbeatable-tic-tac-toe #vanilla-javascript #javascript-game #faisal-rashid #tic-tac-toe

How to Write an Unbeatable Tic-Tac-Toe in JavaScript
6.50 GEEK