#!/bin/bash

# Tic-tac-toe game by J. Ellis 2020

# A little proof-of-concept that I probobly won't polish

arr=(" " " " " " " " " " " " " " " " " " " ")   # Initialize game board array
turn=X
win=false
round=0

while true   # Game loop
do

# Draws the board:

clear
echo "Player $turn's turn:"
echo -e " ${arr[1]} | ${arr[2]} | ${arr[3]}  \n___|___|___\n ${arr[4]} | ${arr[5]} | ${arr[6]}  \n___|___|___\n ${arr[7]} | ${arr[8]} | ${arr[9]}  \n   |   |   "

# Gets input from the player:

echo -n "Row: "
read row
echo -n "Column: "
read column

# Converts coordinates into a single integer (1-9) stored in $num:

num=`expr $row - 1`
row=`expr $num \* 3`
num=`expr $row + $column`

# Checks to see if move is valid. $move = false if not:

move="true"
test "${arr[$num]}" != " " && move="false"
test $num -gt 9 && move="false"
test $num -lt 1 && move="false"

# Cancels move or continues with game loop depending on $move:

if [ "$move" = "false" ]
then
echo -e "\nInvalid  Move!"
read -n 1 -s
else

arr[$num]=$turn

# Checks win condition and stalemate:

round=`expr $round + 1`    # $round only increases if the move was valid

test "${arr[1]}" = "$turn" && test "${arr[1]}" = "${arr[2]}" && test "${arr[2]}" = "${arr[3]}" && win=true
test "${arr[4]}" = "$turn" && test "${arr[4]}" = "${arr[5]}" && test "${arr[5]}" = "${arr[6]}" && win=true
test "${arr[7]}" = "$turn" && test "${arr[7]}" = "${arr[8]}" && test "${arr[8]}" = "${arr[9]}" && win=true
test "${arr[1]}" = "$turn" && test "${arr[1]}" = "${arr[4]}" && test "${arr[4]}" = "${arr[7]}" && win=true
test "${arr[2]}" = "$turn" && test "${arr[2]}" = "${arr[5]}" && test "${arr[5]}" = "${arr[8]}" && win=true
test "${arr[3]}" = "$turn" && test "${arr[3]}" = "${arr[6]}" && test "${arr[6]}" = "${arr[9]}" && win=true
test "${arr[1]}" = "$turn" && test "${arr[1]}" = "${arr[5]}" && test "${arr[5]}" = "${arr[9]}" && win=true
test "${arr[3]}" = "$turn" && test "${arr[3]}" = "${arr[5]}" && test "${arr[5]}" = "${arr[7]}" && win=true

if [ $win = true ]
then
clear
echo "Player $turn's turn:"
echo -e " ${arr[1]} | ${arr[2]} | ${arr[3]}  \n___|___|___\n ${arr[4]} | ${arr[5]} | ${arr[6]}  \n___|___|___\n ${arr[7]} | ${arr[8]} | ${arr[9]}  \n   |   |   "
echo "Player $turn wins!"
read -n 1 -s
clear
exit
fi

if [ $round = 9 ]   # If $round is 9, than there has been 9 valid moves and therefore all spaces are filled
then
clear
echo "Player $turn's turn:"
echo -e " ${arr[1]} | ${arr[2]} | ${arr[3]}  \n___|___|___\n ${arr[4]} | ${arr[5]} | ${arr[6]}  \n___|___|___\n ${arr[7]} | ${arr[8]} | ${arr[9]}  \n   |   |   "
echo "Stalemate! No winners!"
read -n 1 -s
clear
exit
fi

fi

# Updates the current player:

test "$turn" = "X" && turn="O" || turn="X"

done # End of game loop
exit
