0

I have been working on a little typing game that creates a random string, explodes that string, and watches for input to match the displayed characters. Thanks to all the help i've received here on SO i'm sooo close... but. I am totally stumped. My question: The best way to implement a walking "^" under each character such that

3 x P ! 0 D 3 D 5 T r ! n G
^

is first set to a var i can check against, then moves with correct input

3 x P ! 0 D 3 D 5 T r ! n G
  ^

I don't want to paste a ton of code in here so Checkout my github https://github.com/archae0pteryx/chuppy for reference. Thanks!

Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57
rimraf
  • 3,925
  • 3
  • 25
  • 55
  • 3
    You can look into [tput](http://linux.die.net/man/1/tput), which allows for erasing lines and moving to various points on the screen. [terminfo (5)](http://linux.die.net/man/5/terminfo) has the information on the various commands. – fmt Sep 04 '16 at 16:18
  • wow. tput looks awesome! thanks. I'll need to really wrap my head around that one though. =) I was thinking of something dumb like adding " " two spaces before the carrot each keypress... i'll need to keep reading. thanks again. – rimraf Sep 04 '16 at 16:31

2 Answers2

1

Here's my quick attempt to do this

#!/bin/bash

len=14
pos=0
str="$(tr -Cd 'A-Za-z0-9' < /dev/urandom | head -c "$len" | sed -e 's/./& /g')"

show_caret() {
    tput el1
    head -c $((2*pos)) /dev/zero | tr '\0' ' '
    echo '^'
}

echo "${str}"
show_caret

while (( $pos < $len )); do
    read -rsN1 ch
    if [[ $ch ==  "${str:$((2*pos)):1}" ]]; then
        ((pos++))
        tput cuu1
        show_caret
    fi
done

I hope you can learn something from it.

redneb
  • 21,794
  • 6
  • 42
  • 54
0

A naive approach would be to use read -n1 combined with printf. \r will move the cursor to the beginning of the line, and read -n1 will read one character as input:

$ cat walk.bash
#!/bin/bash

echo "3 x P ! 0 D 3 D 5 T r ! n G"
i=1
answer=""
while [ "${#answer}" -lt 14 ]; do
  printf "\r%$((i * 2 - 1))s" "^"
  read -rn1 -s ans
  answer+="$ans"
  ((i++))
done
printf '\n'
echo "$answer"
$ ./walk.bash
3 x P ! 0 D 3 D 5 T r ! n G
^
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123