Created
October 5, 2016 20:01
-
-
Save kbdkode/c74f71624d697efff2fb25f55ba70084 to your computer and use it in GitHub Desktop.
bash chess (partial)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
trap restore_cursor_exit INT | |
function restore_cursor_exit { | |
printf '\e[?25h\n' | |
exit 0 | |
} | |
printf '\e[?25l' | |
color_clear=$'\e[0m' | |
color_rev=$'\e[7m' | |
color1=$'\e[33m' | |
color2=$'\e[34m' | |
posx='3' | |
posy='1' | |
declare -a space_chars=( ' ' "${color1}K" "${color1}Q" "${color1}R" "${color1}B" "${color1}N" "${color1}P" "${color2}K" "${color2}Q" "${color2}R" "${color2}B" "${color2}N" "${color2}P" ) | |
declare -a row7=( '9' '11' '10' '8' '7' '10' '11' '9' ) | |
declare -a row6=( '12' '12' '12' '12' '12' '12' '12' '12' ) | |
declare -a row5=( '0' '0' '0' '0' '0' '0' '0' '0' ) | |
declare -a row4=( '0' '0' '0' '0' '0' '0' '0' '0' ) | |
declare -a row3=( '0' '0' '0' '0' '0' '0' '0' '0' ) | |
declare -a row2=( '0' '0' '0' '0' '0' '0' '0' '0' ) | |
declare -a row1=( '6' '6' '6' '6' '6' '6' '6' '6' ) | |
declare -a row0=( '3' '5' '4' '2' '1' '4' '5' '3' ) | |
key='' | |
function get_space_char { | |
piece="space_chars["${1}"]" | |
printf "${!piece}" | |
} | |
function print_board { | |
printf '\e[1;1H+-----------------+ \e[E' | |
for ((row = 7; row >= 0; row--)); do | |
printf '|' | |
for ((col = 0; col <= 7; col++)); do | |
space="row"$row"["$col"]" | |
printf ' ' | |
(( "$col" == "$posx" && "$row" == "$posy" )) && printf "${color_rev}" | |
printf "$(get_space_char "${!space}")"${color_clear}"" | |
done | |
printf ' | \e[E' | |
done | |
printf '+-----------------+ ' | |
} | |
function handle_inp { | |
if [[ "$1" == $'\033[A' ]]; then | |
key='k' | |
elif [[ "$1" == $'\033[B' ]]; then | |
key='j' | |
elif [[ "$1" == $'\033[C' ]]; then | |
key='l' | |
elif [[ "$1" == $'\033[D' ]]; then | |
key='h' | |
else | |
key="$1" | |
fi | |
case "$key" in | |
h) | |
if (( "$posx" == 0 )); then | |
posx=7 | |
else | |
(( posx-- )) >/dev/null 2>&1 | |
fi | |
;; | |
j) | |
if (( "$posy" == 0 )); then | |
posy=7 | |
else | |
(( posy-- )) >/dev/null 2>&1 | |
fi | |
;; | |
k) | |
if (( "$posy" == 7 )); then | |
posy=0 | |
else | |
(( posy++ )) >/dev/null 2>&1 | |
fi | |
;; | |
l) | |
if (( "$posx" == 7 )); then | |
posx=0 | |
else | |
(( posx++ )) >/dev/null 2>&1 | |
fi | |
;; | |
q) | |
restore_cursor_exit | |
esac | |
} | |
printf '\e[1;1H\e[2J' | |
while :; do | |
print_board | |
read -sn1 inp >/dev/null 2>&1 | |
if [[ "$inp" == $'\033' ]]; then | |
new_inp='_' | |
while [[ "$new_inp" =~ [^A-Za-z] ]]; do | |
read -sn1 new_inp >/dev/null 2>&1 | |
inp="${inp}${new_inp}" | |
done | |
fi | |
handle_inp "$inp" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment