Move a square with the keyboard

Task 19 polled once a frame for the four arrow keys, a direction kept in memory, and a square that keeps going until you steer it somewhere else.

A square you steer. The arrow keys set which way it is going and it keeps going that way on its own, coming back in at the opposite edge when it leaves the screen. Click the Screen panel first: the screen only gets the keyboard when it has the focus, and a ring around it says so while it does.

A bouncing ball drew a picture that changed on its own. This one asks the keyboard, once per frame, what is being held down right now, and the answer changes what the next frame will look like.

You need to know: the "A bouncing ball" Example and the "The screen, keyboard and mouse through traps" lecture. What is new here is task 19, which takes four key codes packed into d1.l and answers with four bytes saying which of them are down at this instant.

move.l #$25262728, d1 is four key codes in one long, $25 for the left arrow, $26 up, $27 right and $28 down, and the answer comes back in d1 with one byte per key in the same places: $FF where the key is held and $00 where it is not. btst #24, d1 tests the lowest bit of the highest byte, which is the byte that belongs to $25, and a $FF has that bit set. The four bit numbers to test are 24, 16, 8 and 0, one per byte, in the order you packed the codes.

The keys do not move the square, they write dx and dy in memory, and the code under them moves it. That separation is what makes the square keep going after you let go, and it is how anything that moves in a game is written: the input decides the velocity, the frame applies it.

clr.w dy next to move.w #-STEP, dx is what keeps the movement to four directions. Take the four clr.w lines out and holding right and then up leaves both steps set, and the square goes diagonally.

Polling every frame is enough for keys held down: task 19 reports a key that was pressed and let go between two polls, so a tap is not missed. What it does not tell you is that a key was pressed again, which is why a game that wants one action per press keeps the last answer and compares.

Try changing the clr.w d5 under cmp.w #RIGHT, d5 to move.w #RIGHT, d5. The square stops against the right edge instead of coming back in at the left, which is the same two instructions doing clamping instead of wrapping.