#!/bin/bash

# Initialize the board
declare -a board=(" " " " " " " " " " " " " " " " " ")

# Current player (X or O)
current_player="O"

# Function to display the board
function display_board() {
    echo " ${board[0]} | ${board[1]} | ${board[2]} "
    echo "---+---+---"
    echo " ${board[3]} | ${board[4]} | ${board[5]} "
    echo "---+---+---"
    echo " ${board[6]} | ${board[7]} | ${board[8]} "
}

# Function to check if the game has been won
function check_win() {
    local win_combinations=(
        "0 1 2" "3 4 5" "6 7 8"  # Rows
        "0 3 6" "1 4 7" "2 5 8"  # Columns
        "0 4 8" "2 4 6"           # Diagonals
    )

    for combination in "${win_combinations[@]}"; do
        local positions=($combination)
        local p1=${board[${positions[0]}]}
        local p2=${board[${positions[1]}]}
        local p3=${board[${positions[2]}]}
        if [ "$p1" != " " ] && [ "$p1" == "$p2" ] && [ "$p2" == "$p3" ]; then
            return 0
        fi
    done

    return 1
}

# Function to check if the game has ended in a draw
function check_draw() {
    for cell in "${board[@]}"; do
        if [ "$cell" == " " ]; then
            return 1
        fi
    done

    return 0
}

# Function to switch players
function switch_player() {
    if [ "$current_player" == "X" ]; then
        current_player="O"
    else
        current_player="X"
    fi
}

# Function to handle player moves
function play_move() {
    local position=$1

    if [ "${board[$position]}" == " " ]; then
        board[$position]=$current_player
        switch_player
    else
        echo "Invalid move! Please try again."
    fi
}

# Main game loop
function main() {
    display_board

    while true; do
        echo "Player $current_player's turn"
        read -p "Enter the position (0-8): " position

        if [[ $position =~ ^[0-8]$ ]]; then
            play_move $position
            display_board

            if check_win; then
                echo "Player $current_player wins!"
                break
            fi

            if check_draw; then
                echo "The game ends in a draw!"
                break
            fi
        else
            echo "Invalid position! Please try again."
        fi
    done
}

# Start the game
main
