Ti tac toe game logic help

So my next project is tic tac toe where the machine responds automatically to the user.What should be the computers move?Should it be random or use some algorithm.Google tells me to use min max algorithm.
What to do?

It’s totally up to you. I suggest you start with an AI that moves randomly. Then finish all the functionalities up to the point where you can play the game smoothly. Then go ahead and implement an AI that plays perfectly. It’s a good exercise on your algorithmic thinking that it’s worth pursuing even though it’s not required by the project specification.

1 Like

Thanku I thought the project demands using the min max algorithm…:relieved:

If you read the user stories: https://www.freecodecamp.com/challenges/build-a-tic-tac-toe-game, you will notice that there is no mention of min max – although I think min max is the most commonly used. I would first get the game functioning, and then work on refining how the computer moves.

On a side note, I didn’t used min max in my version. While I understand how min max works, I wasn’t able to translate that in to JS code. By knowing the patterns of play in tic tac toe, it wasn’t all too difficult to create an unbeatable computer player.

To build on what @sceadgugenga said, once you start looking into it, you’ll realize only the first 3 or 4 moves need specific logic (hint: play center first). After that, it’s just identifying where there are two of the same piece lined up and playing there. And you’ll need to figure that out anyway to make win/lose conditions, so there’s really not much to it. It seemed daunting to me at first as well, but once you get going you’ll realize it isn’t all that bad. Best of luck.

@sceadgugenga same here i too had difficulty to convert the min max algorithm into a JS code.
Currently I am making the computers move random.But will soon implement the algo as told by you…:slight_smile:

@gtrabbit Thanx!!enough hints to get me started!

can i say that the position where the user marks,accordingly the computer chooses a position around it means top ,bottom left or right.This minimizes the chance of win for the user.
And if the user has two marks in same row or column the computer takes that particular row/column.
Am i on the correct track?

Exactly. You just build on it from there. Here are a couple of places that talk about how to win at tic tac toe (they were literally the first ones to show up in a google search, so they may not be the best, but they should give a start). Basically you will check for these scenarios and take the appropriate action during the computer’s turn. https://www.quora.com/Is-there-a-way-to-never-lose-at-Tic-Tac-Toe, http://www.wikihow.com/Win-at-Tic-Tac-Toe.

I look forward to see your finished game…

@sceadgugenga thanx a lottt:)

will get back to u with the project!

@sceadgugenga Here goes the game:

Well done getting this working!

1 Like