在 Tic Tac Toe 中清除棋盘

Clear the board in Tic Tac Toe

我正在用 Bash 制作井字棋。并且在每场比赛的最后,如果你想再玩一轮,你可以select。如果你想再玩一轮,整个脚本从头开始运行。

但是板子已经用完了,怎么清理板子呢?我还在学校学习编程,这是一个项目。

这是我的全部代码:

# 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=
    index2=
    index3=

    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

只需在每个(2 次)welcome_messageprint_board 之间添加对新 init_board 函数的新调用:

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

因此,您可以删除程序开头的初始化行。