Phase 1: Simple Two-Player Game
Phase 1 of the Game
The following example implements a simple two-player game but only permits legal moves in the required “row, col
” format. It re-prompts as necessary and re-prints the board after each move. The program terminates automatically when all nine squares have been filled in or if the user enters 0 to exit immediately.
How It Works
This is the simplest form of the Tic-Tac-Toe game. All it does is alternately asks two different human players for moves. Yet there still is a good deal to do on the housekeeping side. First, it’s necessary to create a true three-by-three matrix. The first two lines of code do that by creating a 2-dimensional list.
n = 3
mat = [['.'] * n for i in range(n)]
Let's understand more how 2D lists are created in Python. Let's start with creating a 1(single)-dimensional list and initialize all the elements in the list to integer 0.
n = 5
arr = [0 for i in range(n)]
print(arr)
Output:
[0, 0, 0, 0, 0]
To modify the value of an element in the list we can do the following:
arr[0] = 10
print(arr)
Output:
[10, 0, 0, 0, 0]
Extending the above we can define 2-dimensional lists in the following ways.
#Method 2a to create a 2D list
rows, cols = (5, 5)
arr = [[0]*cols]*rows
print(arr)
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Another way to create a 2D list would as follows:
#Method 2b to create a 2D list
rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]
print(arr)
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
So what's the difference between method 2a and method 2b for creating 2D lists?
To find the answer, let's change the value of the first element (row = 0, column = 0) to the value 10.
What is the resulting list in both cases? Why does both lists behave differently?
Now back to the tic-tac-toe code. Which method of creating the 2D matrix should we use for the purposes of this game?
Go back to the first 2 lines of the code, you'll see we've used method 2b in creating the 2D lists, this is because when a player changes the value of a row, we don't want that change to propagate to all other rows.
In the 2D game matrix, instead of initializing our 2D list to the integer value zero, each element in the list has the starting value of a string containing a dot (.), which indicates a blank space.
Last updated
Was this helpful?