ゲームエンジン Allegro バージョン 5.0 でキーボードイベント処理
 Allegro サンプルプログラムです。
以下のように作成
#define ALLEGRO_STATICLINK
#include<stdio.h>
#include<allegro.h>
#include<allegro_ttf.h>
#include<allegro_primitives.h>
static ALLEGRO_FONT *font24;
int doit(ALLEGRO_EVENT Event)
{
static int x = 0;
static int y = 0;
static int c = 0;
if (Event.keyboard.keycode == ALLEGRO_KEY_LEFT) x--;
if (Event.keyboard.keycode == ALLEGRO_KEY_RIGHT) x++;
if (Event.keyboard.keycode == ALLEGRO_KEY_UP) y--;
if (Event.keyboard.keycode == ALLEGRO_KEY_DOWN) y++;
if (Event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
c = 100;
}
if (Event.keyboard.keycode == ALLEGRO_KEY_1) {
c = 1;
}
if (Event.keyboard.keycode == ALLEGRO_KEY_2) {
c = 2;
}
if (Event.keyboard.keycode == ALLEGRO_KEY_3) {
c = 3;
}
al_clear_to_color(al_map_rgb(0,0,0)); // clears the screen to the selected color
al_draw_textf(font24, /* color */ al_map_rgb(128, 128, 128), /* x */ 10, /* y */ 10, ALLEGRO_ALIGN_LEFT, "x : %d", x );
al_draw_textf(font24, /* color */ al_map_rgb(128, 128, 128), /* x */ 80, /* y */ 10, ALLEGRO_ALIGN_LEFT, "y : %d", y );
al_draw_textf(font24, /* color */ al_map_rgb(128, 128, 128), /* x */ 150, /* y */ 10, ALLEGRO_ALIGN_LEFT, "c : %d", c );
fprintf(stderr, "%d %d %d\n", x, y, c);
return 0;
}
int main()
{
/* you should always do this at the start of Allegro programs */
if(!al_init()) {
return -1;
}
/* set up the keyboard handler */
al_install_keyboard();
/* set up the mouse handler */
al_install_mouse();
/* set up fonts */
al_init_font_addon();
al_init_ttf_addon();
/* set a graphics mode sized 800x640 */
ALLEGRO_DISPLAY *display = NULL;
display = al_create_display(800, 640);
if(!display) {
return -1;
}
/* load font */
font24 = al_load_font("/usr/share/fonts/truetype/freefont/FreeSans.ttf",24,0);
al_clear_to_color(al_map_rgb(0,0,0)); // clears the screen to the selected color
ALLEGRO_EVENT_QUEUE *EventQueue;
ALLEGRO_EVENT Event;
bool Exit = false;
EventQueue = al_create_event_queue();
al_register_event_source(EventQueue, al_get_display_event_source(display));
al_register_event_source(EventQueue, al_get_keyboard_event_source());
al_register_event_source(EventQueue, al_get_mouse_event_source());
while(Exit == false) {
al_flip_display();
al_wait_for_event(EventQueue, &Event);
if(Event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
Exit = true;
}
if(Event.type == ALLEGRO_EVENT_KEY_DOWN) {
doit(Event);
}
}
al_destroy_display(display);
return 0;
}
次の手順でコンパイル
g++ hoge.cc -I/usr/local/include/allegro5 -L/usr/local/lib -lallegro -lallegro_font -lallegro_ttf -lm
次の手順で実行
./a.out
