Home > Software engineering >  Clear the board in Tic Tac Toe
Clear the board in Tic Tac Toe

Time:05-24

I am making a Tic Tac Toe with Bash. And in the end of every game, you can select if you want to play another round. If you want to play another round, the whole script runs from the beginning.

But with the already used board, so how do I clear the board? I am still learning to code at school and this is a project.

Here is my whole code:

# tic-tac-toe.sh

#!/usr/bin/bash

player_1="X"
player_2="O"
turn=1
moves=( - - - - - - - - - )

welcome_message() {
    clear
    echo "========================"
    echo "== TIC TAC TOE by Roni=="
    echo "========================"
    sleep 3
}

print_board () {
    clear
    echo " ${moves[0]} | ${moves[1]} | ${moves[2]} "
    echo "-----------"
    echo " ${moves[3]} | ${moves[4]} | ${moves[5]} "
    echo "-----------"
    echo " ${moves[6]} | ${moves[7]} | ${moves[8]} "
    echo "============="
}

player_pick(){
    if [[ $(( turn % 2 )) == 0 ]]
    then
        echo "Player 1 pick a square: "
        play=$player_2
    else
        play=$player_1
        echo "Player 2 pick a square: "
    fi

    read -r square

    if [[ ${moves[(square-1)]} == "-" ]] &&
       [[ $square == [1-9] ]]
    then
        moves[(square -1)]=$play
        (( turn  = 1 ))
    else
        echo "Not a valid square."
        player_pick
    fi
}

check_match() {
    index1=$1
    index2=$2
    index3=$3

    if  [[ ${moves[$index1]} == "${moves[$index2]}" ]] &&
        [[ ${moves[$index1]} == "${moves[$index3]}" ]] &&
        [[ ${moves[$index1]} != "-" ]]
    then
        if [[ ${moves[$index1]} == 'X' ]]
        then
            echo "Player one wins!"
            sleep 4
            new_game
        else
            echo "player two wins!"
            sleep 4
            new_game
        fi
    fi
}

check_winner(){
    if [[ $turn -gt 9 ]]
    then
        echo "Its a draw!"
        sleep 4
        new_game
    fi
    check_match 0 1 2
    check_match 3 4 5
    check_match 6 7 8
    check_match 0 4 8
    check_match 2 4 6
    check_match 0 3 6
    check_match 1 4 7
    check_match 2 5 8
}

new_game(){
    echo "Start a new Game? y/n"
    read input
      if [ "$input" = "y" ] 
      then
         clear
         welcome_message
         print_board
         while true
         do
         player_pick
         print_board
         check_winner
         done
     fi
     if [ "$input" = "n" ] 
     then
     exit
     fi
}


welcome_message
print_board
while true
do
    player_pick
    print_board
    check_winner
done

CodePudding user response:

Just add between each (2 times) welcome_message and print_board calls a new call for the new init_board function:

init_board () {
         turn=1
         moves=( - - - - - - - - - )
}

So, you can remove the init lines at the beginning of your program.

  • Related