segunda-feira, 6 de março de 2017

Dev Log 3 # Tic Tac Toe SP - AI of Game [English]

Today we are going to talk about Artificial Intelligence (AI).

The prototype and the first version of the game.

First was made a paper prototype with some powers, with this test the game worked, but still depended on two people;
In the first digital version in Unity of the game, still, there was a version of the implemented one of AI. It was a two-player version. Depending on the cleverness of the players.


Prototype



The initial concept of AI.

First we thought of plays used more in the prototypes in paper and in the digital version. We also thought of a hierarchy of actions. Then the team drew a few more recurring moves and were placed in the AI code. However, this mapping is still insufficient. With this we are using an algorithm to map the moves and improve AI.


The technical functioning of the AI.

To decide which one to play the AI, Tic Tac Toe SP analyzes the board for each situation, and assigns points to each house according to the situations, if found. The house with the most points is the one in which the AI must play.

During the analysis of the board, each house is assigned two values: priority (number of points) and type of action: none, basic, prevent and destroy (this list is subject to change).

None: AI can not play in that house.
Basic: The AI must play its basic piece (X or O) in that house.
Prevent: AI must play a part (ice, plan, its normal part even) to disrupt an opponent's move. The difference to basic is that it can use ice and plant as well.
Destroy: The AI must destroy the piece that is in the house, with a blowtorch or a bomb.

If the AI can not perform the action with more points (for not having a blowtorch or bomb to destroy, for example), this is discarded and the next one with more points is attempted.


At each function, the AI looks for a specific situation on the board. In the above example, you would find two loose pieces of the opponent and two of their boards. He does not currently look for an isolated block of ice, as it does not matter - if he were to be together with other pieces of that might matter.


The situations that the program looks for are the following:


Glossary:
Basic piece of the player: The basic piece of the player (in the case of AI) - X or O 
Basic piece of the opponent: The opponent's basic piece - X or O 
Priority: number of points, in the end the house with the highest priority is the one chosen to be played.
Empty house: house without any part placed



CheckPlayerOneBasicPiece ();

Priority: 50
Action: Basic

Look for the basic pieces of the player, regardless of whether they are together or not. Then assign points to all houses around these that are empty.




CheckPlayerTwoBasicPieces ();

Priority: 75
Action: Basic

Look for basic player pieces that are adjacent to each other. If he finds one piece adjacent to another, he assigns the points to the houses that allow him to complete three pieces (two at most) - those that are empty, obviously.



CheckEnemyTwoBasicPieces ();

Priority: 74
Action: Prevent

Like the previous one, but look for the opponent's pieces. If he finds one piece adjacent to another, assign the points to the houses that the opponent could use to complete three pieces (two at the most) - those that are obviously empty.

Obs: In the current state of the game, it seems that the houses assigned by this function have not been chosen: there is always another house with more points.
  



CheckPlayerThreeBasicPieces ();

Priority: 100
Action: Basic


Look for three basic pieces of the player that are adjacent, and you only need to put one more piece to win the game. The priority is maximum, and at most two houses will be assigned points (those that are empty).



CheckEnemyThreeBasicPieces ();

Priority: 95
Action: Prevent

Like the previous one, but look for the opponent's pieces. It is very important to prevent his victory, only the AI victory on this turn is a better move than this.



CheckEnemyTwoAndAFourthBasicPieces ();
CheckEnemyOneAndThirdFourthBasicPieces ();

Priority: 95
Action: Prevent

Look for cases where the opponent has two pieces together, an empty house, and another piece, and playing in the void would give him a victory. Assign the points to this empty house, and have the same priority of three pieces of it together.



CheckEnemyOneAndThirdFourthBasicPiecesAndAnIceBetween ();
CheckEnemyTwoAndAFourthBasicPiecesAndAnIceBetween ();

Priority: 90
Action: Destroy

Here we look for the situation of having two pieces, one ice, and another piece aligned. Destroy one of the pieces.

Note: In fact, this is the only case currently in which the AI is requested to use the blowtorch or pump.



ResetActionsBoard ();

Priority: 0
Action: Basic or None

Ensures that all boxes in the chessboard have assigned values. It assigns zero priority to each house, and if it is occupied it is assigned a none action, prohibiting action on it.

Note: The assigned values can be replaced later by another of the above functions, including occupied houses, in which a destroy: action can be assigned to destroy the part.




Note 2: The order in which the functions are executed does not matter, because only higher priority values can replace others. If a function tries to assign values with lower priority, it is prevented to do that.

Dev Log3 # Tic Tac Toe SP - IA do jogo. [Português]

Hoje vamos falar sobre a Inteligência Artificial(IA).

O protótipo e a primeira versão do jogo.

Primeiro foi feito um protótipo em papel com alguns poderes, com esse teste o jogo funcionou, mas dependia ainda de duas pessoas. Na primeira versão digital em unity do jogo, ainda, não havia uma IA implementada. Era uma versão para dois jogadores. Dependendo da esperteza dos jogadores.

Primeiro protótipo



O conceito inicial da IA.

Primeiro se pensou em jogadas mais usadas nos protótipos em papel e na versão digital. Também se pensou em uma hierarquia de ações. Depois a equipe traçou algumas jogadas mais recorrentes e foram colocadas no código da IA. No entanto, esse mapeamento ainda é insuficiente. Com isso estamos usando um algoritmo para mapear as jogadas e aprimorar a IA.


O funcionamento técnico da IA.

Para decidir qual a jogada da IA, o Tic Tac Toe SP analisa o tabuleiro por cada situação, e atribui pontos a cada casa de acordo com as situações, se encontradas. A casa com mais pontos é aquela na qual a IA deve jogar.

Durante a análise do tabuleiro, a cada casa é atribuído dois valores: prioridade (o número de pontos) e o tipo de ação: none, basic, prevent e destroy (esta lista está sujeita a mudanças).

None: a IA não pode jogar naquela casa.
Basic: a IA deve jogar a sua peça básica (X ou O) naquela casa.
Prevent: a IA deve jogar uma peça (gelo, planta, sua peça normal mesmo) para atrapalhar uma jogada do adversário. A diferença para basic é que ele pode usar gelo e planta também.
Destroy: a IA deve destruir a peça que está na casa, com maçarico ou bomba.

Se a IA não conseguir realizar a ação com mais pontos (por não ter maçarico ou bomba para destruir, por exemplo), esta é descartada e a próxima com mais pontos é tentada.



A cada função a IA procura uma situação específica no tabuleiro. No exemplo acima, encontraria duas peças do adversário soltas e duas suas juntas. Atualmente, ele não procura um bloco de gelo isolado, pois ele não tem importância – se ele estivesse junto com outras peças daí poderia ter importância.



As situações que o programa procura são as seguintes:

Legenda:
Peça básica do jogador: A peça básica do jogador (no caso da IA) – X ou O
Peça básica do adversário: A peça básica do adversário – X ou O
Prioridade: número de pontos, no fim a casa com a maior prioridade é a escolhida para ser jogada.
Casa vazia: casa sem qualquer peça colocada

checkPlayerOneBasicPiece ();

Prioridade: 50
Ação: Basic

Procura pelas peças básicas do jogador, independente de estarem juntas de outras ou não. Então atribui pontos a todas as casas ao redor destas que estejam vazias.




checkPlayerTwoBasicPieces ();

Prioridade: 75
Ação: Basic

Procura pelas peças básicas do jogador que estejam um adjacente do outro. Se ele encontrar uma peça adjacente a outra, atribui os pontos para as casas que permitem completar três peças (duas no máximo) – as que estiverem vazias, obviamente.




checkEnemyTwoBasicPieces ();

Prioridade: 74
Ação: Prevent

Como o anterior, mas procura pelas peças do adversário. Se ele encontrar uma peça adjacente a outra, atribui os pontos para as casas que o adversário poderia usar para completar três peças (duas no máximo) – as que estiverem vazias, obviamente.

Obs: No estado atual do jogo, parece que as casas atribuídas por esta função não têm sido escolhidas: sempre tem outra casa com mais pontos.




checkPlayerThreeBasicPieces ();

Prioridade: 100
Ação: Basic

Procura por três peças básicas do jogador que estejam adjacentes, sendo que só precisa colocar mais uma peça para vencer o jogo. A prioridade é máxima, e no máximo a duas casas serão atribuídas pontos (as que estiverem vazias).




checkEnemyThreeBasicPieces ();

Prioridade: 95
Ação: Prevent

Como o anterior, mas procura pelas peças do adversário. É muito importante prevenir a vitória dele, só não mais do que garantir a própria vitória neste turno.




checkEnemyTwoAndAFourthBasicPieces ();
checkEnemyOneAndThirdFourthBasicPieces ();

Prioridade: 95

Ação: Prevent

Procura os casos em que o adversário tem duas peças juntas, uma casa vazia, e outra peça, sendo que jogar na vazia daria a ele uma vitória. Atribui os pontos a esta casa vazia, e têm a mesma prioridade de três peças dele juntas.



checkEnemyOneAndThirdFourthBasicPiecesAndAnIceBetween ();
checkEnemyTwoAndAFourthBasicPiecesAndAnIceBetween ();

Prioridade: 90
Ação: Destroy

Aqui se procura a situação de haver duas peças, um gelo, e outra peça alinhados. Destrói uma das peças.

Obs.: De fato, este é o único caso atualmente em que a IA é solicitada a usar o maçarico ou bomba.



resetActionsBoard ();

Prioridade: 0
Ação: Basic ou None

Garante que todas as casas do tabuleiro tenham valores atribuídos. Atribui prioridade zero a cada casa, e se ela estiver ocupada é atribuída ação none, proibindo ação sobre ela.

Obs.: Os valores atribuídos podem ser substituídos posteriormente por outra das funções acima, inclusive das casas ocupadas, nas quais podem ser atribuídas uma ação destroy: de destruir a peça.




Obs. 2: A ordem em que as funções são executadas não importa, pois somente valores com prioridade maior podem substituir outros. Se uma função tentar atribuir valores com prioridade menor, é impedido.