add wpm-game
[small-misc-bash] / wpm-game
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 wpm-game() {
17 local help="Usage: wpm-game [--help]
18 Typing speed game
19
20 Starts counting when you type a non-space.
21 Starts over and prints the scrore when you press enter."
22 if [[ $1 == --help ]]; then
23 echo "$help"
24 return 0
25 fi
26 local x line chars seconds
27 local TIMEFORMAT=%R
28 while true
29 do
30 line=()
31 while ! [[ $line ]] || [[ $line == [[:space:]] ]] ; do
32 read -n 1 line
33 done
34 x=$( { time read line; echo "$line"; } 2>&1 )
35 seconds=${x%%[[:space:]]*}
36 x="${x#$seconds}"
37 chars=$(( ${#x} + 1 )) # +1 for the first char we don't have
38 # this formual is the same as typeracer.com's 5 keys / word
39 # wikipedia says 6 is more accurate, I like typeracers flattery.
40 # chars / 5 and seconds/60 simplifies to * 12
41 echo -ne "$(echo "12 * $chars / $seconds" | bc)\t"
42 done
43 }
44 wpm-game "$@"