Introduction
It’s been sometime I’ve been here. So, I will just get started off. Today, I’m going to write about how to develop tic-tac-toe using AngularJS. The demo is more to understand the possibilities and simplicity of the framework.
What’s needed in the UI
9 boxes arranged in a 3×3 fashion like below:
Each of these boxes are divs and each div is binded to the data behind as usual
Template:
<div ng-repeat="row in rows"> <div id="{{column.id}}" ng-repeat="column in row"> <div ng-click="markUserClick(column)"> </div> </div> </div> |
Data:
$scope.rows = [ [ {'id' : 'A11','letter': '','class': 'box'}, {'id' : 'A12','letter': '','class': 'box'}, {'id' : 'A13','letter': '','class': 'box'} ], [ {'id' : 'B11','letter': '','class': 'box'}, {'id' : 'B12','letter': '','class': 'box'}, {'id' : 'B13','letter': '','class': 'box'} ], [ {'id' : 'C11','letter': '','class': 'box'}, {'id' : 'C12','letter': '','class': 'box'}, {'id' : 'C13','letter': '','class': 'box'} ] ]; |
Now, the logic is to make the JS think engine. It’s easy when you follow the strategy mentioned in wiki.
AI Algorithm:
- Win: If the AI has two in a row, it will place a third to get three in a row.
- Block: If the [opponent] has two in a row, the AI will play the third to block the opponent.
- Fork: Creation of an opportunity where the AI has two threats to win (two non-blocked lines of 2).
- Blocking an opponent’s fork:
- The AI will create two in a row to force the opponent into defending, as long as it doesn’t result in them creating a fork. For example, if “X” has a corner, “O” has the center, and “X” has the opposite corner as well, “O” must not play a corner in order to win. (Playing a corner in this scenario creates a fork for “X” to win.)
- If there is a configuration where the opponent can fork, the player should block that fork.
- Center: AI marks the center. (If it is the first move of the game, playing on a corner gives “O” more opportunities to make a mistake and may therefore be the better choice; however, it makes no difference between perfect players.)
- Opposite corner: If the opponent is in the corner, the AI plays the opposite corner.
- Empty corner: The AI plays in a corner square.
- Empty side: The AI plays in a middle square on any of the 4 sides.
For TicTacToe DEMO : Click Here.
That’s it folks. Enjoy playing.
That is very fascinating, You are an overly skilled blogger. I have joined your rss feed and look ahead to searching for more of your wonderful post. Additionally, I’ve shared your web site in my social networks
Hello:
I’ve been referencing this building my own version. I realized I could beat your algo with the following and thought you may want to know.
Me: Top Left
CPU: Middle
Me: Bottom Right
CPU: Top Right
Me: Bottom Left (At this point I have a ‘fork’)
CPU: Middle Left (Block)
Me: Middle Bottom (FTW)
Just wanted to give you a heads up. I’ll be fixing this logic in my version and would be happy to share the end result.
Awesome, please do.