tic-tac-toe-minimax icon indicating copy to clipboard operation
tic-tac-toe-minimax copied to clipboard

Wrong move by computer

Open ariforu opened this issue 3 years ago • 2 comments

Start with this board position. board = [ [1, 1, -1], [ -1, 1, 0], [ -1, 0, 0], ]

Choose X or O
Chosen: O
First to start?[y/n]: n
Computer turn [X]

---------------
| X || X || O |
---------------
| O || X ||   |
---------------
| O ||   ||   |
---------------

Human turn [O]

---------------
| X || X || O |
---------------
| O || X || X | <--------- Wrong move by computer
---------------
| O ||   ||   |
---------------
Use numpad (1..9): 

ariforu avatar Dec 23 '20 17:12 ariforu

X starts with a winning board state. Any move by X will result in win. The algorithm just marks the first available position (6 in this case) instead of the positions that will bring the quickest win.

ariforu avatar Dec 23 '20 18:12 ariforu

To solve this problem we can say that if computer is winning in the current move then computer will not check further and it should consider this move as the best move . If there are many move in which computer can win in current move then computer can select any one of them. To do this , In Minimax function when we are iterating over all empty cells we should check if this move will lead to immediate victory, if yes then this move is optimal otherwise check further. In C++ :

	if (wins(state , COMP)) {
		state[x][y] = 0;
		best[0] = x;
		best[1] = y;
		best[2] = inf;
		return best;

	}

I have a opened a pull request for C++ implementation which also deals with this situation.

If there is anything mistake in this logic please correct me.

Cybertron3 avatar Dec 27 '20 10:12 Cybertron3