FYI, the final code example is wrong. If
dt is larger the frame it escapes the window than the next frame, weird things happen. To fix this, you need to make a distinction between the two situations:
X < 0 and
X > width. Make the speed positive in the first situation, negative in the second.
On another note, please use