single Keystroke issues ALLEGRO 5

Jan 11, 2014 at 5:30am
I'm making a menu screen and am having issues keeping my program from flickering to the active game and the menu screen. I'm using the M key to toggle between the game states and M is continuously active when I hold it down. How does one stop the program from reading the input if the key is being held down. I only want one iteration then the player must tap again. I tried a while loop and it created an infinite loop crashing the program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
			//key input
			else if((al_key_down(&keyState, ALLEGRO_KEY_M)))
			{
			// keyPress and prevKeyPress are being used in an attempt to cancel the ChangeState
			keyPress = ALLEGRO_KEY_M;
			if (state == PLAYING && keyPress != prevKeyPress )
				{ChangeState (state, MENU);
				std::cout << keyPress;
			keyPress = prevKeyPress;}
			else if (state == PLAYING && keyPress == prevKeyPress )
				{
			keyPress = prevKeyPress;}
			else if (state == MENU && keyPress != prevKeyPress )
				{ChangeState (state, PLAYING);
			keyPress = prevKeyPress;}
			else if (state == MENU && keyPress == prevKeyPress )
				{
			keyPress = prevKeyPress;}
			}
Jan 12, 2014 at 4:05am
I've never used Allegro. I glanced at the documentation, and I slapped this together. Sorry if there's anything that's wrong or missing - It's pseudo-code, and I'm also tired.

The idea is that in your allegro event loop, you set keys down if they're pressed, and set keys up when they're released. In the key_handler() function you lock the keys if they are pressed and haven't been locked, followed by whatever it is you want that key to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct Key {
	Key() {down = locked = false;}
	bool down, locked;

};

Key keys[ALLEGRO_KEY_MAX];

void key_handler() {
	for(unsigned short i=0; i<ALLEGRO_KEY_MAX; ++i) {
		if(keys[i].down == true && keys[i].locked == false) {
			keys[i].locked = true;
			//do something for that key
		}
	}
}

void allegro_event_handler() {

	while(true) {

		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {//if a key is pressed

			unsigned short index = ev.keyboard.keycode - 1;
			keys[index].down = true;

		}else if(ev.type == ALLEGRO_EVENT_KEY_UP) {//if a key is released

			unsigned short index = ev.keyboard.keycode - 1;
			keys[index].down = false;
			keys[index].locked = false;

		}
		key_handler();
	}
}


edit* you could optimize this by removing the for() loop in the key_handler() function, and passing the key index as a parameter.
Last edited on Jan 12, 2014 at 4:07am
Topic archived. No new replies allowed.