Tic Tac Toe in Python
Published: 2023-02-28 09:35:40

The start of my coding journey needs to start simple and the best way to learn is to code small and move from there. Part of my Codecademy CS course, I had to build a terminal game so I chose to go with the classic game of Tic Tac Toe.

## What's the Goal?
Build a two player game that, on each turn, they would need to the place their symbol in an empty box on the board and who ever gets three in a row (up, down, across, or diagonally) wins the game. However, If the squares are full, the game is tie.

## Coding breakdown
Here is the functions needed to build the game

First would need to print the rules of how to play the game. Then Create the board which was a 2d list which contained a symbol to represent an empty box such as '-'. Also have the ability to print the board 

```python
def print_board(board):

    for row in board:
        print_row = ""
        for index in range(len(row)):
            if index < (len(row) -1):
                print_row = print_row + row[index].replace ('-',' ') + " | "
            else:
                print_row = print_row + row[index].replace ('-',' ') + " "
        print(print_row)
        print("- | - | - ")
```
* Check if the there any empty boxes.
* Check if the a player won
```python
def check_if_player_won(board, player):
    combination =[
        ["0,0","0,1","0,2"],
        ["1,0","1,1","1,2"],
        ["2,0","2,1","2,2"],
        ["0,0","1,0","2,0"],
        ["0,1","1,1","2,1"],
        ["0,2","1,2","2,2"],
        ["0,0","1,1","2,2"],
        ["0,2","1,1","2,0"]
        ]
    for rows in combination:
        for item in rows: 
            current_check = board[int(item.split(",")[0])][int(item.split(",")[1])]
            if current_check != player:
                win = False
                break
            else: 
                win = True
        if win:
            return win
    return win
```
This will have two parameters which is the 2d list board and the current player's symbol. There is a 2d list of all the possible winning combinations where each item in the row is the index of the board. Each row in the list represent a winning combination as index position of the 2d board list. On every row iteration, each item in the row is then used as an index in the board. If the symbol in the board does not match the current player's symbol, then this is not a winning combination and exits that row's iteration. This will continue until there is a winning combination, or goes through all of the possible combination.

The final function will run through every step for each players turn. 

```python
def run_turn(player):
    print("Player {player} turn".format(player=player))
    correct = False
    while not correct:
        coord = input("Enter the row and column, Must be comma seperated and no spaces eg[1,2]:")
        check_coordinates = re.search('[1-3],[1-3]',coord)
        if check_coordinates:
            if board[int(coord.split(",")[0])-1][int(coord.split(",")[1])-1] != "-":
                print("Space already taken, Please try again")
            else:
                board[int(coord.split(",")[0])-1][int(coord.split(",")[1])-1] = player
                correct = True
            
        else:
            print("Coordinates are NOT correct, please try again")
```

This will ask the player to enter the row and column of where they want to place their symbol in the board. With using regex, it will check if the input is correct. If not, the player would need to enter the position again. This will also check if the position is already been filled. If so, the player would need to find a different position.

After is just running the game where on each players turn, it will ask to place the symbol in an empty square, print the board and check if the player has won or if its a tie. If there is no winner or a tie, it the next players turn.

## Thoughts
This project was a good start with how to create a program from scratch. It helped with creating the initial structure and trying to find a simple way to create this program.
Here's my [github](https://github.com/larsche/tic-tac-toe/blob/39f94f0191a09a0c79c13e362b182668cf55e0bf/main.py) 

Full Code

```python
import re

def entry_rules():
    print("Welcome to tic-tac-toe game")
    print("This is a two player game where Player 1 is 0 and Player 2 is X")
    print("On each player's turn, enter the row and column ")
    print("There are 3 rows and 3 colunms")
    print("Exaple if I want to enter top left I'll enter 1,1")
    print("Lets start")
    print()


def create_board():
    tic_tac_toe_board = [
        ["-","-","-"],
        ["-","-","-"],
        ["-","-","-"]
    ]
    return tic_tac_toe_board

def check_empty_boxes(board):
    for row in board:
        if "-" in row:
            return True
    return False


def print_board(board):
    
    for row in board:
        print_row = ""
        for index in range(len(row)):
            if index < (len(row) -1):
                print_row = print_row + row[index].replace ('-',' ') + " | "
            else:
                print_row = print_row + row[index].replace ('-',' ') + " "
        print(print_row)
        print("- | - | - ")

def check_if_player_won(board, player):
    combination =[
        ["0,0","0,1","0,2"],
        ["1,0","1,1","1,2"],
        ["2,0","2,1","2,2"],
        ["0,0","1,0","2,0"],
        ["0,1","1,1","2,1"],
        ["0,2","1,2","2,2"],
        ["0,0","1,1","2,2"],
        ["0,2","1,1","2,0"]
        ]
    for rows in combination:
        for item in rows: 
            current_check = board[int(item.split(",")[0])][int(item.split(",")[1])]
            if current_check != player:
                win = False
                break
            else: 
                win = True
        if win:
            return win
    return win

    
def run_turn(player):
    print("Player {player} turn".format(player=player))
    correct = False
    while not correct:
        coord = input("Enter the row and column, Must be comma seperated and no spaces eg[1,2]:")
        check_coordinates = re.search('[1-3],[1-3]',coord)
        if check_coordinates:
            if board[int(coord.split(",")[0])-1][int(coord.split(",")[1])-1] != "-":
                print("Space already taken, Please try again")
            else:
                board[int(coord.split(",")[0])-1][int(coord.split(",")[1])-1] = player
                correct = True
            
        else:
            print("Coordinates are NOT correct, please try again")


entry_rules()
board = create_board()
finished = False
player_turn = 'o' 
while not finished:
    run_turn(player_turn)
    print_board(board)
    if check_if_player_won(board, player_turn):
        print("Player {player_turn} is the Winner".format(player_turn=player_turn))
        finished = True
    elif not check_empty_boxes(board):
        print("It's a Tie")
        finished = True
    else:
        player_turn = "o" if player_turn == "x" else "x"
      
```