Press the flag and watch. The pen size is set to the distance to the edge or the obstacle. If the ball gets stuck, press the R key or the reset button to reset it.
The ball moves randomly unless it is close to a wall. It then moves away from the wall. @onmax for the distance detection. Everything else by me.