# Tic Tac Toe small game in JavaScript

This is a post about the small game “Tic-Tac-Toe,” which was written in order to replenish the programming experience in JS. Canvas and DojoBase are used here. The library is used to work with events and to find elements by id (this is very convenient). Canvas is used to draw the playing field.
Game itself

The rules of the “Tic-Tac-Toe” from this implementation are simple: you need to collect a series of five elements (in any direction) before the enemy. The number of moves is the same, that is, if the zeros (they go first) collected a row, and the crosses have a line of four elements, then the round does not end. Yes, in this implementation, one game consists of several rounds. The game ends when there are no free cells left on the field. The winner is the one who won more rounds. Cells that were used in past rounds are poured and become inactive. The resolution of the field itself is set depending on the resolution of the browser window.

###### Creation of AI (hereinafter, under AI, a set of search algorithms is parsed)

The most interesting thing here, of course, is AI. I “taught” him to walk more or less correctly in several stages ... At first, AI put his badge on the first free cell that I found. Having tested a little, it became clear to me that this is not interesting. It works, but something is wrong here. After thinking that a better case than this, I screwed up rand. After that, it became a little more fun, but still - not interesting.
So, okay, first let him find all the cells that you can (and should) go to. That is, something like that (highlighted in blue).

These "necessary" cells are determined by such an algorithm "
Here all the information about the playing field (what is happening on it) is contained in a two-dimensional global array, the values ​​of the elements of which indicate the state of the cells. A complete set of directions is used, that is, all neighboring cells with this one are checked. The array_2 records the results of the search for the “necessary” cells.

So, determined and what to do next with them? You can put a random element in any of these cells. And it is possible to assign an assessment to each cell and, based on them, choose the best option, and then use it. It sounds good. But, first you need to solve another question.
During the course of AI for zero, a situation may arise that there simply will not be “necessary” cells. For example, in the first turn of the round. Now we need to come up with an algorithm to find the best option in this situation (or when there are no free cells in crosses or zeros). And I think it's good to go where the most spacious.
Therefore, such an algorithm is implemented here
Intermediate data, that is, rows of free cells (vertical and horizontal) in a specific format, is recorded in m_sections. The result of this function will be written to the o_coordinate object. If the segment is the diameter of the "empty" square, then this means that its center point (cell) is the center of the square of free cells, and its sides are equal to this segment.

And the time has come for an algorithm that chooses a move based on ratings.
Here he is

На вход этого алгоритма подается массив с «нужными» точками. Массив м_оценок, вспомогательный и суда записываются оценки клеток. Здесь, как и в предыдущем примере, используется полный перебор всех направлений вокруг клетки. Оценка осуществляется по двум параметрам: тип хода(блокирование или дополнение своего ряда) и длина линии элементов(1, 2, 3 или 4 клетки). Назначение происходит специальной функцией, где можно менять критерии. Эти оценки(критерии) суммируются по всем направлениям для данной клетки.

###### Conclusion

Well, in the end, I got a small game with AI, which can beat beginners. I easily win it, not “dry”, of course, but still. It is worth noting that when you play for “crosses”, it’s as if the difficulty level is lower, but for “tokens” it’s a little more difficult to play.
The multi-round mode made the task more interesting. For example, here AI must find the optimal cell for the first move. There was still a problem with the fact that single empty cells (in which it makes no sense to walk), it was also necessary to “shade” somehow. But in the end I did it.