This is an implementation of 'tic-tac-toe' game with javascript. Agent of the game play it's moves with minimax algorithm.
You can play it from here: Tic Tac Toe
Minimax is recusive algorithm which searches for best score for given game. In tic-tac-toe there are 3 position that ends the game: Win, Tie, Loss. In order to find best move, those 3 ending scenario should be mapped with numbers:
Win -> 1
Tie -> 0
Loss -> -1
Minimax keeps searching until one of the game ending scenario is found. After that it selects move option that maximize or minimaze it's score considering who has the turn. That is why algorithm is called 'minimax'.
- Algorithm finds all possible options. In each depth it eighter maximize(to select maximum score) or minimize(to select minimum score) the score. Because main pupouse of algorithm is finding best move, it starts with maximizing, and switches with minimazing, and again maximazing and so forth. In other words, if algorithm will move it maximize else it minimize. In scenario down below, since there are only one option in last depth, all the scores will directly pass to up.
- Algorithm will select worst option for itself in this depth so that maximize opponents moves.
- Finally, algorithm choose move which it will play. To do that, it just selects the best score that is available.
- If the restart button is pressed rapidly more than once, game plays more than one move.