hp
toc

T-3PO — Tic-Tac-Toe Played Optimally

2017-04-08, post № 166

games, HTML, JavaScript, mathematics, programming, Python, #computer player, #game ai, #perfect, #perfect play, #three in a row, #three to win, #three

Tic-Tac-Toe, noughts and crosses, Xs and Os, three in a row or whatever you want to call it may be the simplest perfect information game that is enjoyable by humans. Two players set their pieces (X or O) on an 𝟥 ⨉ 𝟥 grid, alternating their turns. The first player to get three of their pieces in a line, wins. If no player succeeds to get a line, the game ends in a draw.

Tic-Tac-Toe’s simplicity may become clear, if you consider that skilled players — people who have played a few rounds — can reliably achieve a draw, thereby playing perfectly. Two perfect players playing Tic-Tac-Toe will — whoever starts — always tie, so one may call the game virtually pointless, due to there practically never being a winner.
Because of its simple rules and short maximal number of turns (nine) it is also a game that can be solved by a computer using brute-force and trees.

The first Tic-Tac-Toe-playing program I wrote is a Python shell script. It lets you, the human player, make the first move and then calculates the best possible move for itself, leading to it never loosing. On its way it has a little chat whilst pretending to think about its next move. The Python source code can be seen below or downloaded here.

The second Tic-Tac-Toe-playing program I wrote uses the exact same method of optimizing its play, though it lets you decide who should begin and is entirely written in JavaScript. You can play against it by following this link.

Both programs look at the entire space of possible games based on the current board’s status, assumes you want to win and randomly picks between the moves that either lead to a win for the computer or to a draw. I did not include random mistakes to give the human player any chance of winning against the computer. Other Tic-Tac-Toe-playing computers, such as Google’s (just google the game [1]), have this functionality.

Source code: t-3po.py

Footnotes

  1. [2020-07-29] Please only use Google if you feel comfortable with the implications of their service.
Jonathan Frech's blog; built 2024/08/31 22:59:44 CEST