0

In the code block below I am trying to move a rectangle once for every key-press but the rectangle moves as long as I hold down a key.

    ALLEGRO_EVENT ev;

    while(!done)
    {
        al_wait_for_event(event_queue, &ev);

        if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
                case ALLEGRO_KEY_UP:
                    pos_y -= 10;
                    break;
                case ALLEGRO_KEY_DOWN:
                    pos_y += 10;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    pos_x += 10;
                    break;
                case ALLEGRO_KEY_LEFT:
                    pos_x -= 10;
                    break;
            }
        }
        else if(ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
                done = true;
        }

        al_draw_filled_rectangle(pos_x, pos_y, pos_x + 30, pos_y + 30, al_map_rgb(255,0,255));
        al_flip_display();
        al_clear_to_color(al_map_rgb(0,0,0));
    }

Also I noticed that al_wait_for_event is not waiting for a new event in case of holding down a key but is in fact making the event of type ALLEGRO_EVENT_KEY_CHAR . Although this should not pose any problem , I wanted to know a bit more about it.

Also, the above code is taken from a tutorial. It worked fine over there.

pavel
  • 26,538
  • 10
  • 45
  • 61
nevermore
  • 1
  • 5
  • Does the tutorial happen to have a call to `void set_keyboard_rate(int delay, int repeat);` with the delay and repeat set to zero? Ref: [Keyboard routines](http://alleg.sourceforge.net/stabledocs/en/alleg006.html). – Andrew Morton Oct 07 '14 at 10:12
  • No. Here is the url for the entire code- http://fixbyproximity.com/public_files/TextInput1.cpp – nevermore Oct 07 '14 at 11:13
  • I believe `set_keyboard_rate` is not in the 5.0/5.1 API - it is up to the user to set the repeat rate through their system. – rcorre Oct 07 '14 at 11:13
  • Which OS? `ALLEGRO_EVENT_KEY_DOWN` should only trigger once per physical key press. `ALLEGRO_EVENT_KEY_CHAR`, however, will be triggered whenever the OS reports a character, which includes repeats. i.e., Shift-E is two down events + one char event (capital E). – Matthew Oct 07 '14 at 23:13

1 Answers1

0

To make sure your app doesn't apply the key press more than once per Key_Down event define a Boolean initialized to false. Place everything in your Key_Down events in an If statement triggering only if Boolean == false and in its block immediately set Boolean = true followed by the things you want the event to do only once per event. Then, in the corresponding Key_Up event set Boolean = false and you should be golden.

I haven't tested this, but it should work, and it serves towards compating your app to any client computer, no matter if they have funky key press settings on their device.

Element420
  • 16
  • 2