]> git.sommitrealweird.co.uk Git - advent-of-code-2019.git/blob - day13/run2.sh
And lo, we have completed day13 (it took a while for blockbuster to run - it did...
[advent-of-code-2019.git] / day13 / run2.sh
1 #!/bin/bash
2
3 exec 3<input.txt
4 OLDIFS=$IFS
5 IFS="," read -u 3 -a instructions
6 IFS=$OLDIFS
7 exec 4>output.txt
8
9 basedir=$(dirname $(readlink -f ${BASH_SOURCE}))
10
11 . $basedir/computer.sh
12 . $basedir/screen.sh
13
14 instructions[0]=2
15
16 coproc computer (run_program instructions 2>computer_output.txt)
17
18 comp_pid=${computer_PID}
19 comp_stdin=${computer[1]}
20 comp_stdout=${computer[0]}
21
22 paddle_x=0
23 paddle_y=0
24 ball_x=0
25 ball_y=0
26 ball_dir_left=-2
27 ball_dir_up=0
28 ball_started=-1
29 where_paddle_should_be_x=0
30
31 get_joystick_direction() {
32     if [ $ball_dir_left -eq -2 ]; then
33         echo "0"
34         return
35     fi
36
37     if   [ $paddle_x -lt $ball_x ]; then
38         paddle_dir=1
39     elif [ $paddle_x -gt $ball_x ]; then
40         paddle_dir=-1
41     elif [ $paddle_x -eq $ball_x ]; then
42         paddle_dir=0
43     fi
44
45     echo "Where we think the paddle should be: $where_ball_will_be_on_paddle_line" >&4
46     echo "Where we are: $paddle_x,$paddle_y" >&4
47     echo "Where the ball is: $ball_x, $ball_y" >&4
48     echo "Direction of ball: $ball_dir_left,$ball_dir_up" >&4
49     echo "Direction of paddle: $paddle_dir" >&4
50
51     echo "$paddle_dir"
52 }
53
54 update_paddle_pos() {
55     paddle_x=$1
56     paddle_y=$2
57 }
58
59 update_ball_pos() {
60     local x=$1
61     local y=$2
62
63     # work out if we're going up or down
64     # left or right
65     if [ $x -gt $ball_x ]; then
66         ball_dir_left=1
67     elif [ $x -lt $ball_x ]; then
68         ball_dir_left=-1
69     else
70         ball_dir_left=0
71     fi
72
73     if [ $y -gt $ball_y ]; then
74         ball_dir_up=1
75     elif [ $y -lt $ball_y ]; then
76         ball_dir_up=-1
77     else
78         ball_dir_up=0
79     fi
80
81     ball_x=$x
82     ball_y=$y
83 }
84
85 arcade_screen_init
86
87 while ps -p $comp_pid >/dev/null 2>/dev/null; do
88     read -u $comp_stdout x || break
89     if [ $x == "input:" ]; then
90         echo "$(get_joystick_direction)" >&$comp_stdin
91         continue # go back to main loop
92     fi
93     echo "x: '$x'" >&4
94     if [ "x$x" == "xinput: " ]; then
95         continue
96     fi
97     read -u $comp_stdout y || break
98     echo "y: '$y'" >&4
99     read -u $comp_stdout z || break
100     echo "z: '$z'" >&4
101
102     case $z in
103         3)
104             update_paddle_pos $x $y
105             ;;
106         4)
107             update_ball_pos $x $y
108             ;;
109     esac
110
111     if [ $x -eq -1 ]; then
112         update_score_board $z
113         continue
114     fi
115     arcade_screen_update $x $y $z
116 done
117
118 arcade_screen_finish