3bc395625169bfcc23918a1888545f20525a6aa8
[advent-of-code-2019.git] / day13 / screen.sh
1 __arcade_score=0
2
3 clear_screen() {
4     echo -en '\033[2J'
5 }
6
7 move_cursor() {
8     local x=$1
9     local y=$2
10
11     # program assumes 0 based, we're 1 based, apparently
12     x=$((x+1))
13     y=$((y+1))
14
15     echo -en '\033['$y';'$x'f'
16 }
17
18 draw_tile() {
19     local tile_type=$1
20
21     case $tile_type in
22         0)
23             # blank
24             echo -n ' '
25             ;;
26         1)
27             # wall
28             echo -n '|'
29             ;;
30         2)
31             # block
32             echo -n '#'
33             ;;
34         3)
35             # horizontal paddle
36             echo -n '='
37             ;;
38         4)
39             # ball
40             echo -n 'o'
41             ;;
42     esac
43 }
44
45 hide_cursor() {
46     tput civis
47 }
48
49 show_cursor() {
50     tput cvvis
51 }
52
53 draw_score_board() {
54     local value=${1:-0}
55     local scoreboard_y=20
56     local scoreboard_width=43
57     move_cursor 0 $scoreboard_y
58     printf "+"
59     printf "%.0s-" {1..42}
60     printf "+\n"
61     printf "|"
62     printf "%.0s " {1..42}
63     printf "|\n"
64     printf "+"
65     printf "%.0s-" {1..42}
66     printf "+\n"
67     update_score_board
68 }
69
70 update_score_board() {
71     local value=${1:-$__arcade_score}
72     move_cursor 2 21
73     if [ $value -gt 0 ]; then
74         __arcade_score=$value
75     fi
76     printf '% 40d' $value
77 }
78
79 arcade_screen_init() {
80     clear_screen
81     hide_cursor
82     draw_score_board
83 }
84
85 arcade_screen_update() {
86     local x=$1
87     local y=$2
88     local tile=$3
89
90     move_cursor $x $y
91     draw_tile $tile
92 }
93
94 arcade_screen_finish() {
95     move_cursor 0 23
96     show_cursor
97     echo high score: $__arcade_score
98 }
99
100 arcade_screen() {
101     local max_y=0
102     local max_x=0
103     local -A blocks
104
105     # first, clear the screen and hide the cursor
106     clear_screen
107     hide_cursor
108
109     draw_score_board
110
111     while read x; do
112         read y
113         read tile
114         if [ $x -gt $max_x ]; then
115             max_x=$x
116         fi
117         if [ $y -gt $max_y ]; then
118             max_y=$y
119         fi
120         move_cursor $x $y
121         draw_tile $tile
122
123         case $tile in
124             0)
125                 if [ ${blocks[$x,$y]+a} ]; then
126                     unset blocks[$x,$y]
127                 fi
128                 ;;
129             2)
130                 blocks[$x,$y]=1
131                 ;;
132         esac
133     done
134
135     move_cursor 0 $((max_y+4))
136     echo "We have ${#blocks[@]} blocks on the screen"
137     echo "The maximum x was $max_x"
138     echo "The maximum y was $max_y"
139     show_cursor
140 }