Tic Tac Toe in terminal using Python
Tags: python, tutorial
Published: 2022-11-22 19:53:31

## introduction
Welcome to this tutorial on how to create a tic-tac-toe game using Python. In this guide, we will go through all the steps necessary to build a functional tic-tac-toe game, including creating the grid, initializing the game, handling user input, and checking for a winner. By the end of this tutorial, you will have a fully-functional tic-tac-toe game that you can play with a friend or family member.

## the Game
Tic-tac-toe is a paper-and-pencil game for two players who take turns marking the spaces in a three-by-three grid with X or O. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner.

## Gameplay
Tic-tac-toe is played on a three-by-three grid by two players, alternately placing the marks X and O in one of the nine spaces in the grid.

In the following example, the first player (X) wins the Game in seven steps:

Game of Tic-tac-toe, won by X
There is no universally-agreed rule as to who plays first, but in this article, the convention that X plays first is used.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5vrty146roiy13c9tsw.png)

##Setting up the game in Python
To begin building our tic-tac-toe game in Python, we will first need to create the grid. We can represent the grid as a 3x3 matrix of integers, with each element representing a space on the grid. For example:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ul5mh1p9xq3p910cyu0i.jpg)

```
#        row_1   row_2   row_3
grid = [[0,0,0],[0,0,0],[0,0,0]]`
```
In this representation, each 0 represents an empty space. Later, these zeros will be replaced by 1 for player One and 2 for player Two.


##Displaying the grid

To display the grid to the user, we can define a function that takes the grid as an argument and prints it to the console. To give the grid a more visually appealing look, we can create a dictionary of symbols to use for each element in the grid. For example:

```
grid_symbols = {
    0: ' ',
    1: 'X',
    2: 'O'
}

def display_grid(grid):
    row_1 = [grid_symbols[i] for i in grid[0]]
    row_2 = [grid_symbols[i] for i in grid[1]]
    row_3 = [grid_symbols[i] for i in grid[2]]
    print(f'      1   2   3  columns \n1  r {row_1}\n2  o {row_2}\n3  w {row_3}')

grid = [[1, 0, 0],
        [0, 2, 0],
        [0, 0, 0]]
display_grid(grid)

# Output:
#       1   2   3  columns
# 1  r ['X', ' ', ' ']
# 2  o [' ', 'O', ' ']
# 3  w [' ', ' ', ' ']
```


##Handling user input
To allow the players to make a move, we can define a function that prompts the user for a row and column and marks the chosen space with the current player's symbol. The function should take the player as a parameter, which will be used to display which player's turn it is. The function should also check that the input is valid (i.e., a number between 1 and 3). For example:

```
def user_input(player):
    row_valid = False
    column_valid = False
    player = player
    While not row_valid:
        row = input(f"{player} please Choose a row: ")
        if row.isnumeric() and int(row) < 4 and int(row) >=1:
            row_valid = True
        else:print("Input invalid please choose a number from 1 to 3")
    While not column_valid:
        column = input(f"{player} please Choose a column: ")
        if column.isnumeric() and int(column) < 4 and int(column) >=1:
            column_valid = True
        else:print("Input invalid please choose a number from 1 to 3")
    return (int(row),int(column))
```
`output:
Player One, please Choose a row: 
or
Player Two, please Choose a row: 
`


#step Three
create a function to check whether a position in the grid is already taken.

```
def check_grid(row,column):
    if grid[row][column] == 1 or grid[row][column] == 2:
        return False
    else: return True
```

#step four
let's create the main loop where we can actually play the Game.

```
def start_game():
    player_one_choose = True
    while True:
        print_grid()
        if player_one_choose:
            player_row,player_column = user_input("Player One")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 1
                clear()
                player_one_choose = False
            else:
                player_one_choose = True
                clear()
                print("The position is already taken")
        else:
            player_row,player_column = user_input("Player Two")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 2
                clear()
                player_one_choose = True
            else:
                player_one_choose = False
                clear()
                print("The position is already taken")
```
The Game is now playable, but there's one final step. The last function is to determine who will be the winner of the Game.

#step five
create a function to check the winner. Then implement the function inside the main loop of the Game.

```
def checkWinner(grid):
    for i in range(0,3):
        if grid[i][0] == grid[i][1] == grid[i][2] != 0:
            return grid[i][0]
        elif grid[0][i] == grid[1][i] == grid[2][i] != 0:
            return grid[0][i]
            
    if grid[0][0] == grid[1][1] == grid[2][2] != 0:
        return grid[0][0]
    elif grid[0][2] == grid[1][1] == grid[2][0] != 0:
        return grid[0][0]

    elif 0 not in grid[0] and 0 not in grid[1] and 0 not in grid[2]:
        return 0
    else:
        return -1

def start_game():
    player_one_choose = True
    while True:
        print_grid()
        if player_one_choose:
            player_row,player_column = user_input("Player One")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 1
                clear()
                player_one_choose = False
            else:
                player_one_choose = True
                clear()
                print("The position is already taken")
        else:
            player_row,player_column = user_input("Player Two")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 2
                clear()
                player_one_choose = True
            else:
                player_one_choose = False
                clear()
                print("The position is already taken")
        if checkWinner(grid) == 1:
            print("X WON!")
            print_grid()
            break
        if checkWinner(grid) == 2:
            print("O WON!")
            print_grid()
            break

```

Now that we have all the necessary functions, we can put them together to create a complete tic-tac-toe game. First, we will define a function to initialize the game, which will create an empty grid and set the current player to "X". Then, we will create a loop that will continue until the game is over (either because a player has won or the grid is full). Within the loop, we will call the display_grid and get_move functions to allow the players to make their moves and update the grid accordingly. Finally, we will call the check_winner function to see if the game is over and display the result.

Here is an example of what the complete code might look like:

## full code

```
grid = [[0,0,0],[0,0,0],[0,0,0]]
import os
clear = lambda: os.system('cls')
clear()
grid_simbols = {
    0:'',
    1:'X',
    2:"O"
}

def start_game():
    player_one_choose = True
    while True:
        print_grid()
        if player_one_choose:
            player_row,player_column = user_input("Player One")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 1
                clear()
                player_one_choose = False
            else:
                player_one_choose = True
                clear()
                print("The position is already taken")
        else:
            player_row,player_column = user_input("Player Two")
            if check_grid(player_row - 1,player_column - 1):
                grid[player_row - 1][player_column - 1] = 2
                clear()
                player_one_choose = True
            else:
                player_one_choose = False
                clear()
                print("The position is already taken")
        if checkWinner(grid) == 1:
            print("X WON!")
            print_grid()
            break
        if checkWinner(grid) == 2:
            print("O WON!")
            print_grid()
            break
        
def user_input(player):
    row_valid = False
    column_valid = False
    player = player
    while not row_valid:
        row = input(f"{player} please Choose a row: ")
        if row.isnumeric() and int(row) < 4 and int(row) >=1:
            row_valid = True
        else:print("Input invalid please choose a number from 1 to 3")
    while not column_valid:
        column = input(f"{player} please Choose a column: ")
        if column.isnumeric() and int(column) < 4 and int(column) >=1:
            column_valid = True
        else:print("Input invalid please choose a number from 1 to 3")
    return (int(row),int(column))

def print_grid():
    row_1 = [grid_simbols[i] for i in grid[0]]
    row_2 = [grid_simbols[i] for i in grid[1]]
    row_3 = [grid_simbols[i] for i in grid[2]]
    print(f'      1   2   3  columns \n1  r {row_1}\n2  o {row_2}\n3  w {row_3}')



def check_grid(row,column):
    if grid[row][column] == 1 or grid[row][column] == 2:
        return False
    else: return True

def checkWinner(grid):
    for i in range(0,3):
        if grid[i][0] == grid[i][1] == grid[i][2] != 0:
            return grid[i][0]
        elif grid[0][i] == grid[1][i] == grid[2][i] != 0:
            return grid[0][i]
            
    if grid[0][0] == grid[1][1] == grid[2][2] != 0:
        return grid[0][0]
    elif grid[0][2] == grid[1][1] == grid[2][0] != 0:
        return grid[0][0]

    elif 0 not in grid[0] and 0 not in grid[1] and 0 not in grid[2]:
        return 0
    else:
        return -1
                
start_game()
```
## Conclusion
Congratulations! You have now created a fully-functional tic-tac-toe game using Python. You can try running the code and playing the game with a friend or family member to see how it works. You can also try adding additional features, such as a scoreboard to keep track of wins and losses, or the ability to play against the computer. I hope you have enjoyed this tutorial and learned something new about Python programming.