0
\$\begingroup\$

I am currently programming a Tetris clone. In Tetris, there is a system being used called DAS, or Delayed Auto Shift. It works similarly to the keyboard auto-repeat used in Windows. For example, if you press left, the block immediately jumps one Column to the left. Then a certain amount of time goes by till it jumps a second time, and the following jumps move at a constant rate. I have this implemented as moveHorizontal(boolean moveRight), and can call it with a boolean that determines the direction the movement is going in.

However my main problem is handling the left and right direction buttons at the same time. More specifically, the state where you hold down one button, while pressing another button. The more recently pressed button should overwrite the old one, and the DAS should be reset once it switches directions. I feel like I can't really get a grasp on how to implement this kind of logic.

How do I logically change the state so as to correctly respond to the user input as I have described?

I hope I explained the problem in enough detail. If I didn't, please let me know, so I can provide more information.

\$\endgroup\$
1
\$\begingroup\$

Easiest solution is to act as if neither are pressed if both are pressed.

if(key_left && key_right){
  key_left = false;
  key_right = false;
}

For using the most recent instead:

if(key_left && !last_frame_key_left){
    // key pressed: start left and stop right
    go_left = true;
    go_right = false;
    ResetRepeatTimer();
} else if(!key_left && last_frame_key_left){
    // key released, stop
    go_left = false;
}
// save state for next game update
last_frame_key_left = key_left;

// same thing the other way
if(key_right && !last_frame_key_right){
    go_right = true;
    go_left = false;
    ResetRepeatTimer();
} else if(!key_right && last_frame_key_right){
    go_right = false;
}
last_frame_key_right = key_right;
\$\endgroup\$
  • \$\begingroup\$ First of all, thanks allot for the quick answer. I changed my moveHorizontal() method a bit, so that it now uses the go_right/go_left variables and it works. :) I modified it a bit so it doesn't completly stop when one button is held down, another is pressed and released. Gonna mark this as the answer. \$\endgroup\$ – The_Blog Sep 5 '16 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.