#!/bin/ksh
# Script demonstrating terminal control - like "minesweeper"
# Well, the rudiments of minesweeper anyway - draws a grid, and
# uses vi-like cursor commands to control the cursor:
#
# Key Action
# --- ------
# h left
# j down
# k up
# l right
# m mark "cell" with an "x"
# u unmark current "cell"
# ? tentatively mark a cell with a "?"
# x exit
#
# As of yet, has no "gameplay" but controls the cursor reliably and
# provides the framework
# Reset terminal at exit
trap "stty echo icanon; tput clear" 0
trap "stty echo icanon; tput clear; exit 1" 1 2 3 15
# use -icanon to process each char in turn - no need to press return
stty -echo -icanon # will be restored at exit
tput clear
row=1
col=1
# "constants"
max_columns=17
max_lines=19
# Draw the main grid
i=1
while [ "$i" -le $(( $max_lines + 2 )) ]
do
if [ $(( $i % 2 )) -eq "0" ]; then
echo "| | | | | | | | | |"
else
echo "-------------------"
fi
(( i = i + 1 ))
done
tput cup $row $col
# infinite while - key handlers are in here!
while :
do
# read one char from stdin
key=$( dd bs=1 count=1 2> /dev/null )
case "$key" in
h) #left
if [ "$col" -le "1" ]; then
col=1
tput cup $row $col
else
(( col = col - 2 ))
tput cup $row $col
fi
;;
l) #right
if [ "$col" -ge "$max_columns" ]; then
col=$max_columns
tput cup $row $col
else
(( col = col + 2 ))
tput cup $row $col
fi
;;
k) #up
if [ "$row" -le "1" ]; then
row=1
tput cup $row $col
else
(( row = row - 2 ))
tput cup $row $col
fi
;;
j) #down
if [ "$row" -ge "$max_lines" ]; then
row=$max_lines
tput cup $row $col
else
(( row = row + 2 ))
tput cup $row $col
fi
;;
m) #mark
echo -e "x\c\b" ;;
u) #unmark
echo -e " \c\b" ;;
\?) #tentative
echo -e "?\c\b" ;;
x) #exit
tput cup 21 1
echo -e "Do you want to quit $(basename $0)? [y|n] \c"
stty echo icanon # user must press return here
read response
case $response in
y|Y|[yY][eE][sS])
exit 0 ;;
*)
tput cup 21 1
# overwrite previous output
echo " "
tput cup $row $col
stty -echo -icanon #back to it
;;
esac
esac
done
exit 99 # should never get here