I am playing with ALLEGRO_EVENT_KEY_CHAR and having some success. However, When typing characters, it draws the character twice. Here is the code:
#SelectExpand
1#include "allegro5/allegro.h"
2#include "allegro5/allegro_image.h"
3#include "allegro5/allegro_primitives.h"
4#include <stdio.h>
5#include <allegro5/allegro_font.h>
6#include <allegro5/allegro_ttf.h>
7#define white al_map_rgb(255,255,255)
8#define black al_map_rgb(0,0,0)
9#define line_size 2
10bool done
= false;
11bool redraw
= false;
12
13int main
(int argc,
char **argv
){
14
15 ALLEGRO_DISPLAY *display
= NULL
;
16 ALLEGRO_EVENT_QUEUE *event_queue
= NULL
;
17 ALLEGRO_USTR *input
;
18 input
= al_ustr_new("");
19
20
21 if(!al_init()) {
22 fprintf(stderr,
"failed to initialize allegro!\n");
23 return -1;
24 }
25
26 display
= al_create_display(640,
480);
27 if(!display
) {
28 fprintf(stderr,
"failed to create display!\n");
29 return -1;
30 }
31
32 event_queue
= al_create_event_queue();
33 if(!event_queue
) {
34 fprintf(stderr,
"failed to create event_queue!\n");
35 al_destroy_display(display
);
36 return -1;
37 }
38
39 if(!al_install_keyboard()) {
40 fprintf(stderr,
"failed to initialize the keyboard!\n");
41 return -1;
42 }
43
44 ALLEGRO_FONT *font = al_create_builtin_font
();
45
46 if (!font){
47 fprintf(stderr,
"Could not create font.\n");
48 return -1;
49 }
50
51 al_register_event_source(event_queue,
al_get_display_event_source(display
));
52
53 al_register_event_source(event_queue,
al_get_keyboard_event_source());
54
55 al_clear_to_color(black
);
56
57 al_flip_display();
58
59 while(!done
)
60 {
61 ALLEGRO_EVENT ev
;
62 ALLEGRO_TIMEOUT timeout
;
63 al_init_timeout(&timeout,
0.
06);
64 int position
= 0;
65
66 bool get_event
= al_wait_for_event_until(event_queue,
&ev,
&timeout
);
67
68 if(get_event
&& ev.type
== ALLEGRO_EVENT_DISPLAY_CLOSE
) {
69 done
= true;
70 }
71
72 if(get_event
&& ev.keyboard.keycode
== ALLEGRO_KEY_ESCAPE
)
73 done
= true;
74
75 if(ev.type
== ALLEGRO_EVENT_KEY_CHAR
){
76 al_ustr_append_chr(input, ev.keyboard.unichar
);
77 redraw
= true;
78 }
79
80 if(!al_event_queue_is_empty
(&ev
) && redraw
){
81 redraw
= false;
82 al_draw_textf(font, white,
10,
30,
0,
"%s",
al_cstr(input
));
83 al_flip_display();}
84 }// end of while loop
85
86// fprintf(stderr, "You entered %u", al_cstr(input));
87
88 al_destroy_display(display
);
89 al_destroy_event_queue(event_queue
);
90
91 return 0;
92}
I suspect either my loop is faulty, or allegro_event_key_char reads pressing and releasing the key is read as two keystrokes. Which is the case?