Note: While putting together this post, I found the minimax algorithm. This solution to the tic-tac-toe app is not an explanation of it, it is my logic. A result of the light bulb going off in my head. 🙂
The main idea here is to use the grid system that comes with bootstrap to put together a set of boxes to serve as your nine position board.
In order to later access each of the boxes in the grid, I gave each spot their corresponding position as the “ID” name, allowing me to use JQuery to get the element id an parse out the the numbers for use with later logic.
00 , 01 , 02
10 , 11 , 12
20 , 21 , 22
When a user clicks a location on the board, they are choosing that location as their move. Then, it is up to my logic to work its magic.
A two dimensional array with the value of five in all locations is initialized when the game starts. Anytime a location is chosen, the corresponding array location is updated with a boolean value, True or False.
Here, the script checks if the user’s move was a win. This is done after every move, user and pc. If, the move is not a win, the pc chooses its next move.
Next, the logic scores all combinations and stores the results in an array. In Tic-Tac-Toe, there are eight sub arrays that are possible wins, three horizontal lines, three vertical lines, and two diagonals.
Score = 15 sub-array has combination of 5 , 5 , 5
Score = 10 sub-array has combination of 5 , 5 , False
Score = 5 sub-array has combination of 5 , False , False
Score = 11 sub-array has combination of 5 , 5 , True
Score = 7 sub-array has combination of 5 , True , True
Score = 6 sub-array has combination of 5 , True , false
Teach your app to beat you at Tic-Tac-Toe
The numbers to look for for are five and seven because they represent sub-arrays that are one play away from a win. The logic loops through an array that has the scores called arrsums. If the array has a score of five or seven, the pc plays the location that has the open spot, or the location with the value of five. The logic also checks if the play is a win for itself and that play is obviously given preference.
Again, this is not using the MIniMax algorithm. I’ll try to build the next version using that algorithm. Also, I am always open to suggestions.
Play my finished product here:
check out the code here: