Categories
Coding

Tic Tac Toe GPN

Use this code to create your very own tic tac toe game to play with friends!

I did this project at my fifth Girls Programming Network (GPN) where I got to meet new friends and also run into some familiar faces. It was fun as always to hang out the entire day just coding and having fun.

I used EdStem to write and run my code.

# Created by Ahla, Anas 16/07/2025
# v1.1 Multiple gameplay implemented
# v1.0 Board cleaned up; commented the code; f string used; cleaned up inputs and logic
# v0.9 Initial release

# Declare an empty array of 9 elements
board = [" "," "," "," "," "," "," "," "," "]
game_continue=""

# Function to draw the canvas on screen
def print_board(board):
    print(" ")
    print(" ", board[0], "|", board[1], "|", board[2], " ")
    print("-------------")
    print(" ", board[3], "|", board[4], "|", board[5], " ")
    print("-------------")
    print(" ", board[6], "|", board[7], "|", board[8], " ")
    print(" ")

# Define winning logic
def check_winner(board):
    # First row is filled with the same symbol (O or X), so game over!
    if board[0] == board[1] == board[2] != " ":
        return True
    # Second row is filled with the same symbol (O or X), so game over!
    elif board[3] == board[4] == board[5] != " ":
        return True
    # Third row is filled with the same symbol (O or X), so game over!
    elif board[6] == board[7] == board[8] != " ":
        return True
    # First column is filled with the same symbol (O or X), so game over!
    if board[0] == board[3] == board[6] != " ":
        return True
    # Second column is filled with the same symbol (O or X), so game over!
    elif board[1] == board[4] == board[7] != " ":
        return True
    # Third column is filled with the same symbol (O or X), so game over!
    elif board[2] == board[5] == board[8] != " ":
        return True
    # Diagonal (left to right) is filled with the same symbol (O or X), so game over!
    if board[0] == board[4] == board[8] != " ":
        return True
    # Diagonal (right to left) is filled with the same symbol (O or X), so game over!
    elif board[2] == board[4] == board[6] != " ":
        return True
    # No one has won so far, continue the game
    else:
        return False
    
# Gameplay begins
# Welcome message and get player names
print("Welcome to Tic-Tac-Toe")
player_O = input("Who is playing naughts [O]? ")
player_X = input("Who is playing crosses [X]? ")
print(f"Welcome {player_O}, your symbol is O")
print(f"Welcome {player_X}, your symbol is X")
    
# Define Game loop
def game_loop():
    # Define variables
    game_over = False
    symbol = "O"
    current_player = player_O
    # Declare an empty array of 9 elements
    board = [" "," "," "," "," "," "," "," "," "]

    # Draw the canvas on screen
    print_board(board)
    
    # Game loop
    while game_over == False:
        # Info about the current player
        print(f"The current player is {current_player} playing {symbol}")

        # Take input from the player with validation
        while True:
            try:
                square_input = input("Which square do you want to place your symbol in (1 to 9)? ")
                # Since our board array has 9 elements from 0 to 8, "1" is subtracted from the input
                square_index = int(square_input)-1
                
                # Check if input is within valid range of 0 to 8 (for the user: 1 to 9)
                if square_index < 0 or square_index > 8:
                    print("Invalid input. Please enter a number between 1 and 9.")
                # Check if square is already occupied
                elif board[square_index] != " ":
                    print("That square is already occupied. Please choose another.")
                else:
                    break  # Input is valid, exit the validation loop
                    
            # Input might be string
            except ValueError:
                print("Invalid input. Please enter a number between 1 and 9.")


        # Assign the player's symbol to the board array
        board[square_index] = symbol

        print_board(board)
        game_over = check_winner(board)
        
        if game_over == True:
            print("=======================")
            print(f"{current_player} [{symbol}] won! Congratulations!")
            print("=======================")
            break  # Exit the game loop if there's a winner
            
        # Check for a tie (board is full)
        # No space on the board
        if " " not in board:
            print("=======================")
            print("It's a tie!")
            print("=======================")
            # Let's exit the game
            game_over = True
            break
        
    ##    # Alternate logic
    ##    # Take the count of spaces on the board. If no space, let's exit the game
    ##    if board.count(" ") == 0:
    ##        print("It's a tie!")
    ##        game_over = True
    ##        break
            
        # Change the current player and symbol to the next
        if symbol == "O":
            current_player = player_X
            symbol = "X"
        else:
            current_player = player_O
            symbol = "O"

# Game loop
game_loop()

# Ask to play again
# Infinite loop
while True:
    # Get input to the variable and strip any spaces before valid input
    game_continue = input("\nWould you like to play one more game? Yes [Y] or No [N]: ").strip()
    # Captures input and looks for yes "Y"
    if game_continue and game_continue[0].upper() == "Y":
        game_loop()
    # Exits the game if any other input comes
    else:
        print("=======================")
        print("GAME OVER!")
        print("=======================")
        # Exit the infinite while loop
        break

I would like to also like to implement a computer vs user version of tic tac toe in the future. I think it will also be fun to make the game graphical with a board in which players can play. This will make it more interactive and hands on to play.

Look forward to that blog coming soon!

One reply on “Tic Tac Toe GPN”

Leave a Reply

Your email address will not be published. Required fields are marked *