tableelement to represent the board.
- Write a victory Condition.
- Write the Computer AI function to play the best possible move.
In most games, the visuals you see are merely a representation of things and objects handled in the background. Even in this very simple game I decided to take the same approach.
This approach also allows us to test the game with different initial states when testing the AI function we are about to write.
The Victory Condition:
The Victory condition is very easy to write. You simply loop through rows and columns and see if any row or column have the same move. In this example I test the diagonals separately. Since I use the same loop for column and row test, I have maintain extra variables to save a victory state. The Victory condition function takes a board as input, instead of just using the present game state. This allows us to use this function later in AI.
The AI is by far the hardest to implement. We loop through each possible future move recursively and give ratings based on if the move leads to victory.
- Play all possible current moves for current Player
- Call the function recursively with board after playing each move (separately)
- Repeat this until a victory is detected
- Negative Rating if the victory belongs to enemy
This function basically iterates through all possible moves(of the computer and player) and decides the best one.
Putting it all together.
Explore the complete code on github at github.com/tinyjsgames/tictactoe/blob/master/js/tictactoe.js Play the game at tinyjs.games