Introduction
Tic tac toe is a well know game. Basically there is a 3x3 board and two players: one is X and the other is O, and there
are 8 probabilities for winning diagonals,
rows, and columns. In this proposal I’m going to explain how I implemented and designed this game as a computer program in two main parts.
- First part: Two humans play with each other.
- Second part: A human plays with the computer and the computer never loses.
UI design
I designed the user interface to be flexible in use and to meet the look and feel for users.
The game board consists of 9 buttons as in the following figure:
The UI gives the flexibility for users to choose between two options, either a
human and computer or two humans.
The UI shows the user who should play to manage the game and make it easier.
Design Architecture
I divided the solution to many parts so the development would be easier.
Two Humans design
Checkwin: Checks if either one of the players connected three blocks in row, column, or diagonal (8
possibilities).
Computer and human design
I designed an algorithm myself as I didn’t want to get it the easy way and search on the internet and get a
pre-written code.
The algorithm is designed for 3X3 and expected to be scalable and work for an odd number of blocks as 5x5.
As the following figure shows, there are eight probabilities for connecting three blocks with the same symbol.
First step: Fill the center block. By this way I forbid the opponent from
four opportunities and he still has another 4 as the following figure shows.
Second step: However the opponent plays, there is no danger till now and I have to decreased his number of opportunities.
The best location for playing now is the corners as it decreases his opportunities by two in one turn.
Third step: Check the two lines (1 and 2) as the previous
figure shows, and the one which contains two similar symbols; the computer should
set the third with the other opposite symbol so I don’t let the opponent win as the following figure shows.
Fourth step: Check the last available line for the opponent to win and check
if he has two blocks set with his symbol and then check the third.
Using the code
Fifth step: Check for the last empty place (and it should be one place at this step as the board has only 9 blocks) and set it.
In steps 3 and 4 in the above algorithm I first check If I can win and then implement the step.