Skip to content

Instantly share code, notes, and snippets.

@leoshimo
Created July 20, 2023 03:20
Show Gist options
  • Save leoshimo/e41aa84fc1e3fb8a3ff36e835002a8c5 to your computer and use it in GitHub Desktop.
Save leoshimo/e41aa84fc1e3fb8a3ff36e835002a8c5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# tictactoe.sh - tictactoe in bash for fun
#
set -eu
board=" "
turn="X"
print_board() {
tput smul
echo "0|${board:0:1}|${board:1:1}|${board:2:1}"
echo "1|${board:3:1}|${board:4:1}|${board:5:1}"
echo "2|${board:6:1}|${board:7:1}|${board:8:1}"
tput rmul
echo " |0|1|2"
echo
}
read_digit() {
name="$1"
while true; do
printf '%s> ' "$name" >&2
read -r
if printf "%s" "$REPLY" | grep -qE "^[012]$"; then
break
else
echo "Invalid input" >&2
fi
done
echo "$REPLY"
}
updated_board() {
sym="$1"
pos="$2"
next=$((pos + 1))
echo "${board:0:$pos}${sym}${board:$next:9}"
}
check_win() {
s="$1" #symbol
# keep regex simpler - turn board into string of numbers for matching symbol
symstr=$(printf "%s" "$board" | fold -w1 | nl | grep "$s" | tr -d '\n')
printf "%s" "$symstr" | grep -q "1.*2.*3\|\
4.*5.*6\|\
7.*8.*9\|\
1.*4.*7\|\
2.*5.*8\|\
3.*6.*9\|\
1.*5.*9\|\
3.*5.*7"
}
while true; do
print_board
while true; do
echo "*** player $turn ***"
row=$(read_digit "row")
col=$(read_digit "col")
pos=$((row * 3 + col))
if [ "${board:pos:1}" != " " ]; then
echo "Position is not empty" >&2
else
break
fi
done
board=$(updated_board "$turn" "$pos")
echo
if check_win $turn; then
echo "*** player $turn wins ***"
break
fi
if [ $turn = "X" ]; then
turn="O"
else
turn="X"
fi
done
@leoshimo
Copy link
Author

Sample Run

sh-3.2$ ./tictactoe.sh
0| | |
1| | |
2| | |
 |0|1|2

*** player X ***
row> 2
col> 1

0| | |
1| | |
2| |X|
 |0|1|2

*** player O ***
row> 1
col> 1

0| | |
1| |O|
2| |X|
 |0|1|2

*** player X ***
row> 2
col>
Invalid input
col> 0

0| | |
1| |O|
2|X|X|
 |0|1|2

*** player O ***
row> 1
col> 0

0| | |
1|O|O|
2|X|X|
 |0|1|2

*** player X ***
row> 2
col> 2

*** player X wins ***

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment