Day 13 2019
[advent-of-code-2019.git] / day13 / run2.sh
diff --git a/day13/run2.sh b/day13/run2.sh
new file mode 100755 (executable)
index 0000000..daccab3
--- /dev/null
@@ -0,0 +1,118 @@
+#!/bin/bash
+
+exec 3<input.txt
+OLDIFS=$IFS
+IFS="," read -u 3 -a instructions
+IFS=$OLDIFS
+exec 4>output.txt
+
+basedir=$(dirname $(readlink -f ${BASH_SOURCE}))
+
+. $basedir/computer.sh
+. $basedir/screen.sh
+
+instructions[0]=2
+
+coproc computer (run_program instructions 2>computer_output.txt)
+
+comp_pid=${computer_PID}
+comp_stdin=${computer[1]}
+comp_stdout=${computer[0]}
+
+paddle_x=0
+paddle_y=0
+ball_x=0
+ball_y=0
+ball_dir_left=-2
+ball_dir_up=0
+ball_started=-1
+where_paddle_should_be_x=0
+
+get_joystick_direction() {
+    if [ $ball_dir_left -eq -2 ]; then
+        echo "0"
+        return
+    fi
+
+    if   [ $paddle_x -lt $ball_x ]; then
+        paddle_dir=1
+    elif [ $paddle_x -gt $ball_x ]; then
+        paddle_dir=-1
+    elif [ $paddle_x -eq $ball_x ]; then
+        paddle_dir=0
+    fi
+
+    echo "Where we think the paddle should be: $where_ball_will_be_on_paddle_line" >&4
+    echo "Where we are: $paddle_x,$paddle_y" >&4
+    echo "Where the ball is: $ball_x, $ball_y" >&4
+    echo "Direction of ball: $ball_dir_left,$ball_dir_up" >&4
+    echo "Direction of paddle: $paddle_dir" >&4
+
+    echo "$paddle_dir"
+}
+
+update_paddle_pos() {
+    paddle_x=$1
+    paddle_y=$2
+}
+
+update_ball_pos() {
+    local x=$1
+    local y=$2
+
+    # work out if we're going up or down
+    # left or right
+    if [ $x -gt $ball_x ]; then
+        ball_dir_left=1
+    elif [ $x -lt $ball_x ]; then
+        ball_dir_left=-1
+    else
+        ball_dir_left=0
+    fi
+
+    if [ $y -gt $ball_y ]; then
+        ball_dir_up=1
+    elif [ $y -lt $ball_y ]; then
+        ball_dir_up=-1
+    else
+        ball_dir_up=0
+    fi
+
+    ball_x=$x
+    ball_y=$y
+}
+
+arcade_screen_init
+
+while ps -p $comp_pid >/dev/null 2>/dev/null; do
+    read -u $comp_stdout x || break
+    if [ $x == "input:" ]; then
+        echo "$(get_joystick_direction)" >&$comp_stdin
+        continue # go back to main loop
+    fi
+    echo "x: '$x'" >&4
+    if [ "x$x" == "xinput: " ]; then
+        continue
+    fi
+    read -u $comp_stdout y || break
+    echo "y: '$y'" >&4
+    read -u $comp_stdout z || break
+    echo "z: '$z'" >&4
+
+    case $z in
+        3)
+            update_paddle_pos $x $y
+            ;;
+        4)
+            update_ball_pos $x $y
+            ;;
+    esac
+
+    if [ $x -eq -1 ]; then
+        update_score_board $z
+        continue
+    fi
+    arcade_screen_update $x $y $z
+done
+
+arcade_screen_finish