/* starting game UI */ void start_game (bool Fullscreen) { /* creating display */ ALLEGRO_DISPLAY * display; if (Fullscreen) { /* creating disp_data struct to store supported resolutions */ ALLEGRO_DISPLAY_MODE disp_data; /* making it fullscreen */ al_set_new_display_flags(ALLEGRO_FULLSCREEN); /* storing info */ al_get_display_mode(al_get_num_display_modes() - 1, &disp_data); CurrentScreenWidth = disp_data.width; CurrentScreenHeight = disp_data.height; /* creating display with different resolutions for different screens */ display = al_create_display(CurrentScreenWidth, CurrentScreenHeight); } else { al_set_new_display_flags(ALLEGRO_WINDOWED); display = al_create_display(CurrentScreenWidth, CurrentScreenHeight); } if (!display) { al_show_native_message_box(display, "Error", "Display Settings", "Couldn't create a display.", NULL, ALLEGRO_MESSAGEBOX_ERROR); exit(-1); } /* setting new window title */ al_set_window_title(display, "Snake"); // ----------------------- /* creating fonts */ ALLEGRO_FONT * font = al_load_font(MainFont, 36, ALLEGRO_ALIGN_CENTER); ALLEGRO_FONT * credits_font = al_load_font(CreditsFont, 20, NULL); if (!font) { al_show_native_message_box(display, "Error", "Could not load font file.", "Have you included the resources in the same directory of the program?", NULL, ALLEGRO_MESSAGEBOX_ERROR); exit(-1); } /* loading audio samples */ ALLEGRO_SAMPLE * over_button_sound = al_load_sample(OverButton); ALLEGRO_SAMPLE * pressed_button_sound = al_load_sample(PressedButton); ALLEGRO_SAMPLE * eating_apple_sound = al_load_sample(EatApple); ALLEGRO_SAMPLE * game_over_sound = al_load_sample(GameOverSound); if (!over_button_sound || !pressed_button_sound) { al_show_native_message_box(display, "Error", "Could not load one or more sound files.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR); exit(-1); } al_reserve_samples(2); /* creating timer */ ALLEGRO_TIMER * timer = al_create_timer(1.0 / FPS); ALLEGRO_TIMER *frametimer = al_create_timer(1.0 / frameFPS); /* creating event queue */ ALLEGRO_EVENT_QUEUE * event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_timer_event_source(frametimer)); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); ALLEGRO_KEYBOARD_STATE keystate; /* loading BITMAPS */ ALLEGRO_BITMAP * SmallWallpaperBitmap = al_load_bitmap(SmallWallpaper); ALLEGRO_BITMAP * BigWallpaperBitmap = al_load_bitmap(BigWallpaper); ALLEGRO_BITMAP * mouse = al_load_bitmap(MouseCursor); ALLEGRO_BITMAP * applepng = al_load_bitmap(Apple_png); if (!mouse) { al_show_native_message_box(display, "Error", "Could not load one or more resource file.", "Your resources folder must be corrupt, please download it again.", NULL, ALLEGRO_MESSAGEBOX_ERROR); exit(-1); } al_hide_mouse_cursor(display); /* ---- VARIABLES ---- */ bool done = false, change_resolution = false, draw = true; int mouse_x = CurrentScreenWidth, mouse_y = CurrentScreenHeight; /* mouse */ bool left_mouse_button_down = false; bool left_mouse_button_up = false; /* MAIN MENU */ int button_displacement; if (!Fullscreen) { button_displacement = 20; } else { button_displacement = 15; } Button play_button(50, 20, Blue, 0, -button_displacement); Button options_button(40, 15, Blue); Button exit_button(40, 15, Blue, 0, button_displacement); /* PLAY */ string score; Direction new_direction; int speed_up, speed_up_anim_frame = 0; bool speed_up_anim = false; Snake snake; Apple apple; /* starting timers */ al_start_timer(timer); al_start_timer(frametimer); while (!done) { /* actually defining our events */ ALLEGRO_EVENT events; al_wait_for_event(event_queue, &events); al_get_keyboard_state(&keystate); switch (gameState) { case MainMenu: { /* WINDOW */ if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } /* MOUSE */ if (events.type == ALLEGRO_EVENT_MOUSE_AXES) { mouse_x = events.mouse.x; mouse_y = events.mouse.y; draw = true; } if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { /* left button */ if (events.mouse.button & 1) { left_mouse_button_down = true; draw = true; } } if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { /* left button */ if (events.mouse.button & 1) { left_mouse_button_down = false; left_mouse_button_up = true; draw = true; } } /* button conditions */ if (play_button.MouseOverButton(mouse_x, mouse_y) && !play_button.StillOverButton) { play_button.play_over_button_sound = true; } if (options_button.MouseOverButton(mouse_x, mouse_y) && !options_button.StillOverButton) { options_button.play_over_button_sound = true; } if (exit_button.MouseOverButton(mouse_x, mouse_y) && !exit_button.StillOverButton) { exit_button.play_over_button_sound = true; } /* KEYBOARD */ if (events.type == ALLEGRO_EVENT_KEY_UP) { switch (events.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: { done = true; break; } case ALLEGRO_KEY_SPACE: case ALLEGRO_KEY_ENTER: { /* STARTING GAME NOW */ new_direction = RIGHT; speed_up = 0; snake.ResetSnakeDetails(); apple.NewApple(snake.GetSnakeCells()); gameState = PlayGame; } } break; } /* ------------ NOW DRAWING ------------ */ if (draw) { /* drawing wallpaper */ if (Fullscreen) { al_draw_scaled_bitmap(BigWallpaperBitmap, 0, 0, al_get_bitmap_width(BigWallpaperBitmap), al_get_bitmap_height(BigWallpaperBitmap), 0, 0, CurrentScreenWidth, CurrentScreenHeight, NULL); } else { al_draw_bitmap(SmallWallpaperBitmap, 0, 0, 0); } /* -- play button -- */ if (play_button.MouseOverButton(mouse_x, mouse_y)) { play_button.SetButtonColor(LightBlue); /* button pressed */ if (left_mouse_button_down) { play_button.pressed_button = true; play_button.SetButtonColor(DarkBlue); } /* button released */ else if (left_mouse_button_up) { play_button.pressed_button = false; play_button.StillPressingButton = false; play_button.SetButtonColor(Blue); /* STARTING GAME NOW */ new_direction = RIGHT; speed_up = 0; snake.ResetSnakeDetails(); apple.NewApple(snake.GetSnakeCells()); gameState = PlayGame; } play_button.DisplayButton(); } else { play_button.pressed_button = false; play_button.StillPressingButton = false; play_button.StillOverButton = false; play_button.SetButtonColor(Blue); play_button.DisplayButton(); } /* -- options button -- */ if (options_button.MouseOverButton(mouse_x, mouse_y)) { options_button.SetButtonColor(LightBlue); /* button pressed */ if (left_mouse_button_down) { options_button.pressed_button = true; options_button.SetButtonColor(DarkBlue); } /* button released */ else if (left_mouse_button_up) { options_button.pressed_button = false; options_button.StillPressingButton = false; options_button.SetButtonColor(Blue); switch (Fullscreen) { case 0: { Fullscreen = 1; done = true; change_resolution = true; break; } case 1: { Fullscreen = 0; done = true; change_resolution = true; break; } } } options_button.DisplayButton(); } else { options_button.pressed_button = false; options_button.StillPressingButton = false; options_button.StillOverButton = false; options_button.SetButtonColor(Blue); options_button.DisplayButton(); } /* -- exit button -- */ if (exit_button.MouseOverButton(mouse_x, mouse_y)) { exit_button.SetButtonColor(LightBlue); /* button pressed */ if (left_mouse_button_down) { exit_button.pressed_button = true; exit_button.SetButtonColor(DarkBlue); } /* button released */ else if (left_mouse_button_up) { exit_button.pressed_button = false; exit_button.StillPressingButton = false; exit_button.SetButtonColor(Blue); done = true; } exit_button.DisplayButton(); } else { exit_button.pressed_button = false; exit_button.StillPressingButton = false; exit_button.StillOverButton = false; exit_button.SetButtonColor(Blue); exit_button.DisplayButton(); } /* -- sound -- */ /* mouse over button */ if (play_button.MouseOverButton(mouse_x, mouse_y) && !play_button.StillOverButton) { play_button.StillOverButton = true; al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } if (options_button.MouseOverButton(mouse_x, mouse_y) && !options_button.StillOverButton) { options_button.StillOverButton = true; al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } if (exit_button.MouseOverButton(mouse_x, mouse_y) && !exit_button.StillOverButton) { exit_button.StillOverButton = true; al_play_sample(over_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } /* button pressed */ if (play_button.pressed_button && !play_button.StillPressingButton) { play_button.StillPressingButton = true; al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } else if (options_button.pressed_button && !options_button.StillPressingButton) { options_button.StillPressingButton = true; al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } else if (exit_button.pressed_button && !exit_button.StillPressingButton) { exit_button.StillPressingButton = true; al_play_sample(pressed_button_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); } /* -- text -- */ string fullscreenmode_string; if (Fullscreen) { fullscreenmode_string = "Fullscreen: On"; } else { fullscreenmode_string = "Fullscreen: Off"; } al_draw_text(font, White, CurrentScreenWidth / 2, play_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, "New Game"); al_draw_text(font, White, CurrentScreenWidth / 2, options_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, fullscreenmode_string.c_str()); al_draw_text(font, White, CurrentScreenWidth / 2, exit_button.GetButtonHeightCenter() - 23, ALLEGRO_ALIGN_CENTER, "Exit"); al_draw_text(credits_font, White, 3, CurrentScreenHeight - 20, NULL, "FEUP 2013 - Henrique Ferrolho"); /* -- mouse cursor -- */ al_draw_bitmap(mouse, mouse_x, mouse_y, NULL); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); left_mouse_button_up = false; draw = false; } break; } case PlayGame: { if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } /* KEYBOARD */ if (events.type == ALLEGRO_EVENT_KEY_UP) { switch (events.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: { /* going back to MAIN MENU */ draw = true; gameState = MainMenu; break; } case ALLEGRO_KEY_ENTER: case ALLEGRO_KEY_SPACE: { /* pausing game */ draw = true; gameState = PauseGame; break; } } break; } if (events.type == ALLEGRO_EVENT_TIMER) { if (events.timer.source == timer) { draw = true; /* navigation keys */ if (al_key_down(&keystate, ALLEGRO_KEY_DOWN) || al_key_down(&keystate, ALLEGRO_KEY_S)) { new_direction = DOWN; } else if (al_key_down(&keystate, ALLEGRO_KEY_UP) || al_key_down(&keystate, ALLEGRO_KEY_W)) { new_direction = UP; } else if (al_key_down(&keystate, ALLEGRO_KEY_RIGHT) || al_key_down(&keystate, ALLEGRO_KEY_D)) { new_direction = RIGHT; } else if (al_key_down(&keystate, ALLEGRO_KEY_LEFT) || al_key_down(&keystate, ALLEGRO_KEY_A)) { new_direction = LEFT; } /* checking boundaries */ if (!snake.IsInScreenBoundaries() || snake.EatedItself()) { draw = true; al_play_sample(game_over_sound, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); gameState = GameOver; break; } } else if (events.timer.source == frametimer) { /* moving snake */ snake.SetSnakeDirection(new_direction); snake.MoveSnake(); if (snake.EatedApple(apple.GetAppleX(), apple.GetAppleY())) { al_play_sample(eating_apple_sound, 0.5, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, 0); apple.NewApple(snake.GetSnakeCells()); snake.IncreaseSnakeLength(); draw = true; } } } /* ------------ NOW DRAWING ------------ */ if (draw) { /* game frame */ if (Fullscreen) { al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20); //al_draw_rectangle(0, 0, 1360, 760, DarkRed, 20); } else { al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20); } apple.DrawApple(applepng); snake.DrawSnake(); /* increasing speed */ if (snake.GetSnakeCells().size() < 5) { al_set_timer_speed(frametimer, 1.0 / frameFPS); } else if (snake.GetSnakeCells().size() < 10) { if (speed_up == 0) { speed_up++; speed_up_anim = true; } al_set_timer_speed(frametimer, 1.0 / 14); } else if (snake.GetSnakeCells().size() < 20) { if (speed_up == 1) { snake.SetColor(LightBlue); speed_up++; speed_up_anim = true; } al_set_timer_speed(frametimer, 1.0 / 16); } else if (snake.GetSnakeCells().size() < 30) { if (speed_up == 2) { speed_up++; speed_up_anim = true; } al_set_timer_speed(frametimer, 1.0 / 18); } else if (snake.GetSnakeCells().size() < 40) { if (speed_up == 3) { snake.SetColor(DarkRed); speed_up++; speed_up_anim = true; } al_set_timer_speed(frametimer, 1.0 / 20); } /* speed up animation */ if (speed_up_anim) { if (speed_up_anim_frame < 10) { al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!"); speed_up_anim_frame++; } else if (speed_up_anim_frame < 20) { al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!"); speed_up_anim_frame++; } else if (speed_up_anim_frame < 30) { al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!"); speed_up_anim_frame++; } else if (speed_up_anim_frame < 40) { al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!"); speed_up_anim_frame++; } else if (speed_up_anim_frame < 50) { al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "SPEED UP!"); speed_up_anim_frame++; } else if (speed_up_anim_frame < 60) { speed_up_anim = false; speed_up_anim_frame = 0; } } /* printing score */ stringstream ss; ss << "Score: " << snake.GetSnakeCells().size(); score = ss.str(); al_draw_text(credits_font, Yellow, 60, 15, ALLEGRO_ALIGN_CENTER, score.c_str()); al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); draw = false; } break; } case PauseGame: { if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } if (events.type == ALLEGRO_EVENT_KEY_UP) { switch (events.keyboard.keycode) { case ALLEGRO_KEY_SPACE: case ALLEGRO_KEY_ENTER: { /* resume game */ draw = true; gameState = PlayGame; break; } } break; } /* ------------ NOW DRAWING ------------ */ if (draw) { /* game frame */ if (Fullscreen) { al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20); //al_draw_rectangle(0, 0, 1360, 760, DarkRed, 20); } else { al_draw_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed, 20); } apple.DrawApple(applepng); snake.DrawSnake(); /* printing score */ stringstream ss; ss << "Score: " << snake.GetSnakeCells().size(); score = ss.str(); al_draw_text(credits_font, Yellow, 60, 15, ALLEGRO_ALIGN_CENTER, score.c_str()); al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "GAME PAUSED"); al_flip_display(); draw = false; } break; } case GameOver: { if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } /* MOUSE */ if (events.type == ALLEGRO_EVENT_MOUSE_AXES) { mouse_x = events.mouse.x; mouse_y = events.mouse.y; draw = true; } if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { /* left button */ if (events.mouse.button & 1) { left_mouse_button_down = true; draw = true; } } if (events.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { /* left button */ if (events.mouse.button & 1) { left_mouse_button_down = false; left_mouse_button_up = true; draw = true; } } /* going to MAIN MENU */ if (events.type == ALLEGRO_EVENT_KEY_UP) { switch (events.keyboard.keycode) { case ALLEGRO_KEY_SPACE: case ALLEGRO_KEY_ENTER: { draw = true; gameState = MainMenu; break; } } break; } if (left_mouse_button_up) { left_mouse_button_up = false; draw = true; gameState = MainMenu; break; } if (draw) { al_draw_filled_rectangle(0, 0, CurrentScreenWidth, CurrentScreenHeight, DarkRed); /* printing score */ stringstream ss; ss << "Score: " << snake.GetSnakeCells().size(); score = ss.str(); al_draw_text(font, Yellow, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 80, ALLEGRO_ALIGN_CENTER, score.c_str()); al_draw_text(font, White, CurrentScreenWidth / 2, (CurrentScreenHeight / 2) - 30, ALLEGRO_ALIGN_CENTER, "Click to continue"); /* -- mouse cursor -- */ al_draw_bitmap(mouse, mouse_x, mouse_y, NULL); al_flip_display(); } break; } } } /* dealocating memory */ al_destroy_display(display); al_destroy_font(font); al_destroy_timer(timer); al_destroy_bitmap(mouse); al_destroy_sample(over_button_sound); al_destroy_sample(pressed_button_sound); al_destroy_event_queue(event_queue); if (change_resolution) { CurrentScreenWidth = DefaultScreenWidth; CurrentScreenHeight = DefaultScreenHeight; start_game(Fullscreen); } }
int main(int argc, char *argv[]) { int c; while((c = getopt(argc, argv, "hv")) != -1) { switch(c) { case 'h': puts(HELP); return 0; case 'v': printf("version %.1f\n", PROGRAM_VERSION); return 0; } } if(!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } if(argc == 2 && !strcmp(argv[1], "-v")) { printf("version %.1f\n", PROGRAM_VERSION); return 0; } bool key[5] = {false, false, false, false, false}; bool doexit = false; bool redraw = true; timer = al_create_timer(1.0 / FPS); if(!timer) { fprintf(stderr, "couldn't initialize timer.\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { fprintf(stderr, "failed to create the display.\n"); al_destroy_timer(timer); return -1; } al_set_window_title(display, "blasteroids"); al_init_primitives_addon(); if(!al_install_keyboard()) { fprintf(stderr, "failed to initialize keyboard.\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } /* Making the sky look like sky */ colors[0] = al_map_rgba(255, 100, 255, 128); colors[1] = al_map_rgba(255, 100, 100, 255); colors[2] = al_map_rgba(100, 100, 255, 255); for (layer = 0; layer < 3; layer++) { for (star = 0; star < NUM_STARS/3; star++) { Point *p = &stars[layer][star]; p->x = rand() % SCREEN_W; p->y = rand() % SCREEN_H; } } start = al_get_time() * 1000; now = start; elapsed = 0; frame_count = 0; program_start = al_get_time(); /* done with the sky. Now making the ship. */ Spaceship *ship = init_ship(); List *a = (List *)summon_asteroids(NUMBER_ASTEROIDS); ListElmt *astElmt = list_head(a); if(!ship) { fprintf(stderr, "couldn't create bitmap.\n"); al_destroy_timer(timer); al_destroy_display(display); return -1; } Blast *blast = init_blast(ship->sx, ship->sy, ship->heading); event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr, "failed to create event queue.\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_start_timer(timer); while(!doexit) { /* animate the sky, just sky, starts, but NOT objects. */ ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { if(key[UP]) ship->speed += 0.04; if(key[RIGHT]) ship->heading += 1.0f; if(key[DOWN]) if(ship->speed > 0.05) ship->speed -= 0.04; if(key[LEFT]) ship->heading -= 1.0f; fly_ship(ship); // fire ze missile if(key[SPACE]) { blast->sx = ship->sx; blast->sy = ship->sy; blast->heading = ship->heading; blast->gone = 0; } float theta = head2theta(blast->heading); blast->sx += blast->speed * cos(theta); if(blast->sx <= 0 || blast->sx >= SCREEN_W) { blast->gone = 1; } blast->sy += blast->speed * sin(theta); if(blast->sy <= 0 || blast->sy >= SCREEN_H) { blast->gone = 1; } /* loop through the list of asteroids */ astElmt = (astElmt->next)?astElmt->next : list_head(a); Asteroid *aster = astElmt->aster; /* asteroid eternity */ if(aster->sx < 0 || aster->sx > SCREEN_W - 33) aster->sx = 0; if(aster->sy < 0 || aster->sy > SCREEN_H) aster->sy = 0; aster->twist += aster->rot_velocity; /* Fuzzy movement */ if((int)aster->sx % 3 == 0) aster->sx += aster->speed; aster->sx += 0.9; if((int)aster->sy % 5 == 3) aster->sy += aster->speed; aster->sy += 0.9; aster->twist += 0.4; /* detect alteroid collision, but only if 5 seconds have passed since the last Death */ Box s = {{ship->sx, ship->sy}, 16.0f, 20.0f}; Box a = {{aster->sx, aster->sy}, 45.0f, 40.0f}; if(ship->heading != -90.0f) { if(!aster->gone && !ship->gone && is_collision(&s, &a)) { ship->color = al_map_rgb(0, 0, 255); } } /* detect asteroid being shot */ Box b = {{blast->sx, blast->sy}, 120.0f, 3.0f}; if(!(blast->gone) && !(aster->gone) && is_collision(&b, &a)) { aster->gone = 1; } redraw = true; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[UP] = true; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = true; break; case ALLEGRO_KEY_DOWN: key[DOWN] = true; break; case ALLEGRO_KEY_LEFT: key[LEFT] = true; break; case ALLEGRO_KEY_SPACE: key[SPACE] = true; break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[UP] = false; break; case ALLEGRO_KEY_RIGHT: key[RIGHT] = false; break; case ALLEGRO_KEY_DOWN: key[DOWN] = false; break; case ALLEGRO_KEY_LEFT: key[LEFT] = false; break; case ALLEGRO_KEY_SPACE: key[SPACE] = false; break; case ALLEGRO_KEY_Q: case ALLEGRO_KEY_ESCAPE: doexit = true; break; } } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; al_clear_to_color(al_map_rgb(0, 0, 0)); if (frame_count < (1000/TARGET_FPS)) { frame_count += elapsed; } else { int X, Y; frame_count -= (1000/TARGET_FPS); for (star = 0; star < NUM_STARS/3; star++) { Point *p = &stars[0][star]; al_draw_pixel(p->x, p->y, colors[0]); } /* al_lock_bitmap(al_get_backbuffer(display), ALLEGRO_PIXEL_FORMAT_ANY, 0); */ for (layer = 1; layer < 3; layer++) { for (star = 0; star < NUM_STARS/3; star++) { Point *p = &stars[layer][star]; // put_pixel ignores blending al_put_pixel(p->x, p->y, colors[layer]); } } /* Check that dots appear at the window extremes. */ X = SCREEN_W - 1; Y = SCREEN_H - 1; al_put_pixel(0, 0, al_map_rgb_f(1, 1, 1)); al_put_pixel(X, 0, al_map_rgb_f(1, 1, 1)); al_put_pixel(0, Y, al_map_rgb_f(1, 1, 1)); al_put_pixel(X, Y, al_map_rgb_f(1, 1, 1)); /* al_unlock_bitmap(al_get_backbuffer(display)); */ total_frames++; } now = al_get_time() * 1000; elapsed = now - start; start = now; for (layer = 0; layer < 3; layer++) { for (star = 0; star < NUM_STARS/3; star++) { Point *p = &stars[layer][star]; p->y -= speeds[layer] * elapsed; if (p->y < 0) { p->x = rand() % SCREEN_W; p->y = SCREEN_H; } } } draw_ship(ship); if(!blast->gone) { draw_blast(blast); } draw_asteroids(a); al_flip_display(); } } length = al_get_time() - program_start; /* printf("Length = %f\n", length); */ al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; }
int main() { bool quit = false; int gamestate = 0; srand(time(NULL)); int change_bkg = 0; int stopwatch = 120; bool iddle = false; int bulletID=0; int bulletCount=0; ALLEGRO_DISPLAY* display; ALLEGRO_TIMER* timer_0p2; ALLEGRO_TIMER* timer_1; ALLEGRO_TIMER* timer_60; ALLEGRO_EVENT_QUEUE* event_queue; ALLEGRO_EVENT ev; ALLEGRO_BITMAP* img_home_screen; ALLEGRO_BITMAP* img_dica_h1n1; ALLEGRO_BITMAP* img_background0; ALLEGRO_BITMAP* img_game_over; ALLEGRO_BITMAP* img_you_win; ALLEGRO_BITMAP* img_heart; ALLEGRO_BITMAP* img_medal; ALLEGRO_BITMAP* img_clock; ALLEGRO_BITMAP* img_block1; ALLEGRO_BITMAP* img_block2; ALLEGRO_BITMAP* img_player_walking; ALLEGRO_BITMAP* img_player_walking_shoot; ALLEGRO_BITMAP* img_player_immobile; ALLEGRO_BITMAP* img_player_immobile_shoot; ALLEGRO_BITMAP* img_player_jump; ALLEGRO_BITMAP* img_player_jump_shoot; ALLEGRO_BITMAP* img_player_bullet; ALLEGRO_BITMAP* img_enemy1; ALLEGRO_BITMAP* img_boss1; ALLEGRO_BITMAP* img_enemy_bullet; ALLEGRO_SAMPLE* spl_theme; ALLEGRO_SAMPLE* spl_playerShoot; ALLEGRO_SAMPLE* spl_mlk; ALLEGRO_SAMPLE_INSTANCE* instance_theme; ALLEGRO_SAMPLE_INSTANCE* instance_playerShoot; ALLEGRO_SAMPLE_INSTANCE* instance_mlk; ALLEGRO_FONT* fonte16; /* Estruturas */ s_object player; s_object block[LINHA_MAX][COLUNA_MAX]; s_object enemy1[LINHA_MAX][COLUNA_MAX]; for (i=0; i<LINHA_MAX; i++) { for(j=0; j<COLUNA_MAX; j++) { /* Cria o player */ if(mapa[i][j] == 1) { player.y = i*16 - 24; player.x = j*64 + 24; player.speed = 3; player.direction = 1; player.live = true; player.life = 100; block[i][j].live = false; } /* Cria os Blocos */ if(mapa[i][j] == 2) { block[i][j].y = i*16; block[i][j].x = j*64; block[i][j].live = true; } if(mapa[i][j] == 3) { block[i][j].y = i*16; block[i][j].x = j*64; block[i][j].live = true; } if(mapa[i][j] == 4) { block[i][j].y = i*16; block[i][j].x = j*64; block[i][j].live = true; } if(mapa[i][j] == 5) { block[i][j].y = i*16; block[i][j].x = j*64; block[i][j].live = false; } /* Cria os Inimigos */ if(mapa[i][j] == 6) { enemy1[i][j].y = i*16 - 24; enemy1[i][j].x = j*64; enemy1[i][j].speed = 2; enemy1[i][j].direction = -1; enemy1[i][j].life = 3; enemy1[i][j].live = true; block[i][j].live = false; } if(mapa[i][j] == 7 || mapa[i][j] == 8) { enemy1[i][j].y = i*16 - 24; enemy1[i][j].x = j*64; enemy1[i][j].speed = 2; enemy1[i][j].direction = 1; enemy1[i][j].life = 3; enemy1[i][j].live = false; block[i][j].live = false; } if(mapa[i][j] == 9) { enemy1[i][j].y = i*16 - 24; enemy1[i][j].x = j*64; enemy1[i][j].speed = 2; enemy1[i][j].direction = -1; enemy1[i][j].life = 25; enemy1[i][j].live = false; block[i][j].live = false; } } } s_bullet playerBullet[NUM_BULLET]; s_bullet enemyBullet[NUM_BULLET]; for(i=0; i<NUM_BULLET; i++) { playerBullet[i].x = 0; playerBullet[i].y = 0; playerBullet[i].speed = 5; playerBullet[i].direction = 1; playerBullet[i].live = false; enemyBullet[i].x = 0; enemyBullet[i].y = 0; enemyBullet[i].speed = 5; enemyBullet[i].direction = 0; enemyBullet[i].live = false; } s_animation walking; walking.maxFrame = 8; walking.frameDelay = 5; walking.frameCount = 0; walking.curFrame = 0; walking.frameHeight = 40; walking.frameWidth = 40; s_animation jumping; jumping.maxFrame = 7; jumping.frameDelay = 5; jumping.frameCount = 0; jumping.curFrame = 0; jumping.frameHeight = 52; jumping.frameWidth = 40; s_animation immobile; immobile.maxFrame = 7; immobile.frameDelay = 15; immobile.frameCount = 0; immobile.curFrame = 0; immobile.frameHeight = 40; immobile.frameWidth = 40; s_animation anim_enemy1; anim_enemy1.maxFrame = 3; anim_enemy1.frameDelay = 15; anim_enemy1.frameCount = 0; anim_enemy1.curFrame = 0; anim_enemy1.frameHeight = 40; anim_enemy1.frameWidth = 40; /* Faz com que as teclas comecem em false */ for(i=0; i<KEY_MAX; i++) { keys[i] = false; } /* Carrega as configuracoes (teclado, audio, etc) */ al_init(); al_install_keyboard(); al_init_image_addon(); al_install_audio(); al_init_acodec_addon(); al_init_font_addon(); al_init_ttf_addon(); /* Erros ao criar algo */ display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { printf("Erro ao criar o display"); exit(-1); } timer_0p2 = al_create_timer(5.0); timer_1 = al_create_timer(1.0); timer_60 = al_create_timer(1/60.0); if(!timer_0p2) { printf("Erro ao criar o timer de 0.2 FPS"); exit(-1); } if(!timer_1) { printf("Erro ao criar o timer de 1 FPS"); exit(-1); } if(!timer_60) { printf("Erro ao criar o timer de 60 FPS"); exit(-1); } event_queue = al_create_event_queue(); if(!event_queue) { printf("Erro ao criar o event_queue"); exit(-1); } /* Carregando as Imagens */ img_home_screen = al_load_bitmap("Sprites/Background/home_screen.png"); img_dica_h1n1 = al_load_bitmap("Sprites/Background/dica_h1n1.png"); img_background0 = al_load_bitmap("Sprites/Background/background_h1n1.png"); img_you_win = al_load_bitmap("Sprites/Background/you_win.png"); img_game_over = al_load_bitmap("Sprites/Background/game_over.png"); img_heart = al_load_bitmap("Sprites/heart.png"); img_medal = al_load_bitmap("Sprites/medal.png"); img_clock = al_load_bitmap("Sprites/clock.png"); img_block1 = al_load_bitmap("Sprites/block1.png"); img_block2 = al_load_bitmap("Sprites/block2.png"); img_player_walking = al_load_bitmap("Sprites/Player/player_walking.png"); img_player_walking_shoot = al_load_bitmap("Sprites/Player/player_walking_shoot.png"); img_player_immobile = al_load_bitmap("Sprites/Player/player_immobile.png"); img_player_immobile_shoot = al_load_bitmap("Sprites/Player/player_immobile_shoot.png"); img_player_jump = al_load_bitmap("Sprites/Player/player_jump.png"); img_player_jump_shoot = al_load_bitmap("Sprites/Player/player_jump_shoot.png"); img_player_bullet = al_load_bitmap("Sprites/Player/player_bullet.png"); img_enemy1 = al_load_bitmap("Sprites/Enemies/enemy_h1n1.png"); img_boss1 = al_load_bitmap("Sprites/Enemies/boss_h1n1.png"); img_enemy_bullet = al_load_bitmap("Sprites/Enemies/enemy_bullet.png"); /* Carregando os Samples */ al_reserve_samples(10); spl_theme = al_load_sample("Sounds/theme.wav"); spl_playerShoot = al_load_sample("Sounds/shoot.wav"); spl_mlk = al_load_sample("Sounds/mlk.wav"); instance_theme = al_create_sample_instance(spl_theme); instance_playerShoot = al_create_sample_instance(spl_playerShoot); instance_mlk = al_create_sample_instance(spl_mlk); al_set_sample_instance_gain(instance_playerShoot, 0.5); al_attach_sample_instance_to_mixer(instance_theme, al_get_default_mixer()); al_attach_sample_instance_to_mixer(instance_playerShoot, al_get_default_mixer()); al_attach_sample_instance_to_mixer(instance_mlk, al_get_default_mixer()); /* Registra os Eventos */ al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer_0p2)); al_register_event_source(event_queue, al_get_timer_event_source(timer_1)); al_register_event_source(event_queue, al_get_timer_event_source(timer_60)); al_register_event_source(event_queue, al_get_keyboard_event_source()); /* Carregando os timers */ al_start_timer(timer_0p2); al_start_timer(timer_1); al_start_timer(timer_60); /* Carregando a fonte */ fonte16 = al_load_ttf_font("Joystix.TTF", 16, 0); if (!fonte16) { printf("Erro ao carregar Joystix.TTF\n"); exit(1); } while(!quit) { switch(gamestate) { case 0: al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */ { quit = true; } if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */ { quit = true; } if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE) /* Faz com que o jogo inicie ao pressionar space */ { change_bkg++; if(change_bkg >= 2) { gamestate = 1; } } } if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */ { if(ev.timer.source == timer_60) { al_clear_to_color(al_map_rgb(0,0,0)); if(change_bkg == 0) { al_draw_bitmap(img_home_screen, 0, 0, 0); } if(change_bkg == 1) { al_draw_bitmap(img_dica_h1n1, 0, 0, 0); if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay) { if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame) { anim_enemy1.curFrame = 0; } anim_enemy1.frameCount = 0; } al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 330, 320, 0); al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 450, 320, 0); } al_flip_display(); } } break; case 1: if(force>= -7.5) { force-=0.5; /* Queda */ } /* Toca a música de fundo */ if(!al_get_sample_instance_playing(instance_theme) && !al_get_sample_instance_playing(instance_mlk)) { al_play_sample_instance(instance_theme); } /* Fechar o display */ al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { quit = true; } /* Evento de quando a tecla eh pressionada */ if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: quit = true; break; case ALLEGRO_KEY_SPACE: keys[KEY_SPACE]=true; break; case ALLEGRO_KEY_UP: keys[KEY_UP] = true; if(jump == false) { jump = true; force = gravity; } break; case ALLEGRO_KEY_LEFT: keys[KEY_RIGHT]=false; keys[KEY_LEFT]=true; break; case ALLEGRO_KEY_RIGHT: keys[KEY_LEFT]=false; keys[KEY_RIGHT]=true; break; case ALLEGRO_KEY_F1: if(!al_get_sample_instance_playing(instance_mlk)) { al_play_sample_instance(instance_mlk); al_stop_sample_instance(instance_theme); } break; case ALLEGRO_KEY_M: if(al_get_sample_instance_playing(instance_mlk)) { al_stop_sample_instance(instance_mlk); } break; } } /* Evento de quando a tecla eh solta */ if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_SPACE: keys[KEY_SPACE]=false; break; case ALLEGRO_KEY_UP: keys[KEY_UP] = false; break; case ALLEGRO_KEY_LEFT: keys[KEY_LEFT]=false; break; case ALLEGRO_KEY_RIGHT: keys[KEY_RIGHT]=false; break; } } if(ev.type == ALLEGRO_EVENT_TIMER) { if(ev.timer.source == timer_0p2) { if((iddle == false) && (keys[KEY_RIGHT] == false) && (keys[KEY_LEFT] == false) && (jump == false)) { iddle = true; } } if(ev.timer.source == timer_1) { stopwatch--; } if(ev.timer.source == timer_60) { /* Posicionamento do player*/ player.y-=force; if(keys[KEY_RIGHT]) { player.direction = 1; player.x+=player.speed; } if(keys[KEY_LEFT]) { player.direction = -1; player.x-=player.speed; } if(keys[KEY_SPACE]) { for(i=0; i<NUM_BULLET; i++) { if(!al_get_sample_instance_playing(instance_playerShoot)) { playerShoot(&player, &playerBullet[i], instance_playerShoot); } } } /*Posicionamento do Inimigo */ for (i=0; i<LINHA_MAX; i++) { for(j=0; j<COLUNA_MAX; j++) { if(player.x > enemy1[i][j].x + 40) { enemy1[i][j].direction = 1; } else if(player.x + 40 <= enemy1[i][j].x) { enemy1[i][j].direction = -1; } } } /* ~~Posicionamento do projetil~~ */ /* Chance do Inimigo Atirar */ chance_enemy_shoot = rand() % 40; for (i=0; i<LINHA_MAX; i++) { for(j=0; j<COLUNA_MAX; j++) { enemyShoot(&player, &enemy1[i][j], enemyBullet, &bulletID, &bulletCount); } } for(i=0; i<NUM_BULLET; i++) { if(!playerBullet[i].live) { playerBullet[i].direction = player.direction; } if(playerBullet[i].live) { if(playerBullet[i].direction == -1) { playerBullet[i].x-=playerBullet[i].speed; } else if(playerBullet[i].direction == 1) { playerBullet[i].x+=playerBullet[i].speed; } } if(enemyBullet[i].live) { if(enemyBullet[i].direction == -1) { enemyBullet[i].x-=enemyBullet[i].speed; } if(enemyBullet[i].direction == 1) { enemyBullet[i].x+=enemyBullet[i].speed; } } } /* Prende a Camera no Personagem */ cameraX = player.x-(SCREEN_W/2); cameraY = player.y-(SCREEN_H/2); /* Fazer com que a camera nao passe dos limites do mapa */ if (cameraX < 0) cameraX = 0; if (cameraY < 0) cameraY = 0; if (cameraX > WORLD_W - SCREEN_W) cameraX = WORLD_W - SCREEN_W; if (cameraY > WORLD_H - SCREEN_H) cameraY = WORLD_H - SCREEN_H; /* Colisoes + check trap */ for (i = 0; i<LINHA_MAX; i++) { for(j = 0; j<COLUNA_MAX; j++) { for(k=0; k<NUM_BULLET; k++) { collision_bullet_player(&player, &enemyBullet[k], img_enemy_bullet, &bulletCount, 40, 40); } if(block[i][j].live == true) { if(mapa[i][j] == 2) { collision_player_tiles(&player, &block[i][j], &jumping, img_block2); } if(mapa[i][j] == 3) { collision_player_tiles(&player, &block[i][j], &jumping, img_block2); } if(mapa[i][j] == 4) { check_trap(&player, &block[i][j], &enemy1[i][j], 4); collision_player_tiles(&player, &block[i][j], &jumping, img_block2); } if(mapa[i][j] == 5) { collision_player_tiles(&player, &block[i][j], &jumping, img_block2); } for(k=0; k<NUM_BULLET; k++) { collision_bullet_tiles(&playerBullet[k], &block[i][j], img_player_bullet, img_block2, 0, &bulletCount); collision_bullet_tiles(&enemyBullet[k], &block[i][j], img_player_bullet, img_block2, 1, &bulletCount); } } if(block[i][j].live == false) { if(mapa[i][j] == 5) { check_trap(&player, &block[i][j], &enemy1[i][j], 5); } if(mapa[i][j] == 6) { collision_player_enemy(&player, &enemy1[i][j], 40, 40); for(k=0; k<NUM_BULLET; k++) { collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40); } } if(mapa[i][j] == 7) { check_trap(&player, &block[i][j], &enemy1[i][j], 7); collision_player_enemy(&player, &enemy1[i][j], 40, 40); for(k=0; k<NUM_BULLET; k++) { collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40); } } if(mapa[i][j] == 8) { check_trap(&player, &block[i][j], &enemy1[i][j], 8); collision_player_enemy(&player, &enemy1[i][j], 40, 40); for(k=0; k<NUM_BULLET; k++) { collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40); } } if(mapa[i][j] == 9) { check_trap(&player, &block[i][j], &enemy1[i][j], 9); collision_player_enemy(&player, &enemy1[i][j], 40, 40); for(k=0; k<NUM_BULLET; k++) { collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40); } } } } } collision_player_wall(&player, &jumping, img_block1); /* ~~Desenha o Background~~ */ al_draw_bitmap(img_background0, 0 - cameraX, 0 - cameraY, 0); /* ~~Animação dos inimigos~~ */ if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay) { if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame) { anim_enemy1.curFrame = 0; } anim_enemy1.frameCount = 0; } /* ~~Desenha os Blocos/Inimigos~~ */ for (i = 0; i<LINHA_MAX; i++) { for(j = 0; j<COLUNA_MAX; j++) { if(mapa[i][j] == 2 && block[i][j].live == true) { al_draw_bitmap(img_block1, block[i][j].x - cameraX, block[i][j].y - cameraY, 0); } if(mapa[i][j] == 3 && block[i][j].live == true) { al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0); } if(mapa[i][j] == 4 && block[i][j].live == true) { al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0); } if(mapa[i][j] == 5 && block[i][j].live == true) { al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0); } if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == -1) && (enemy1[i][j].live == true)) { al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0); } if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == 1) && (enemy1[i][j].live == true)) { al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if(mapa[i][j] == 9 && enemy1[i][j].live == true) { al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0); } } } /* ~~Desenho do player~~ */ /* Player parado */ if(iddle == true) { if(++immobile.frameCount >= immobile.frameDelay) { if(++immobile.curFrame >= immobile.maxFrame) { immobile.curFrame = 0; iddle = false; } immobile.frameCount = 0; } } if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1) || player.x == 64)) { al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1) || player.x == WORLD_W - (64-immobile.frameWidth))) { al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, 0); } if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1))) { al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1))) { al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, 0); } /* Player andando */ if(++walking.frameCount >= walking.frameDelay) { if(++walking.curFrame >= walking.maxFrame) { walking.curFrame = 0; } walking.frameCount = 0; } if(keys[KEY_SPACE] == false) { if(jump == false && keys[KEY_LEFT] && player.direction == -1) { al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if(jump == false && keys[KEY_RIGHT] && player.direction == 1) { al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0); } } if(keys[KEY_SPACE] == true) { if(jump == false && keys[KEY_LEFT] && player.direction == -1) { al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if(jump == false && keys[KEY_RIGHT] && player.direction == 1) { al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0); } } /* Player pulando */ if(jump == true) { if(++jumping.frameCount >= jumping.frameDelay) { if(++jumping.curFrame >= jumping.maxFrame) { jumping.curFrame = 0; } jumping.frameCount = 0; } if(keys[KEY_SPACE] == false) { if(player.direction == -1) { al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if(player.direction == 1) { al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0); } } else if(keys[KEY_SPACE] == true) { if(player.direction == -1) { al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL); } if(player.direction == 1) { al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0); } } } /* ~~Desenho dos projeteis~~ */ for(i=0; i<NUM_BULLET; i++) { if(playerBullet[i].live) { al_draw_bitmap(img_player_bullet, playerBullet[i].x - cameraX, playerBullet[i].y - cameraY, 0); } if(enemyBullet[i].live) { al_draw_bitmap(img_enemy_bullet, enemyBullet[i].x - cameraX, enemyBullet[i].y - cameraY, 0); } } /* Pontuacao e Porcentagem de Vida */ al_draw_bitmap(img_heart, 0, 0, 0); al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 20, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), player.life); al_draw_bitmap(img_medal, 64, 0, 0); al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 80, 0, ALLEGRO_ALIGN_LEFT, ("%04d"), scores); al_draw_bitmap(img_clock, 144, 0, 0); al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 160, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), stopwatch); } /* Termino da Fase */ if(enemyKilled == ENEMY_MAX) /* You Win! */ { scores = scores + (25 * stopwatch) + (10*player.life); gamestate = 2; } if(player.life <= 0 || stopwatch == 0) /* Game Over! */ { gamestate = 3; } /* Troca o display */ al_flip_display(); } break; case 2: al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */ { quit = true; } if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */ { quit = true; } } if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */ { if(ev.timer.source == timer_60) { al_clear_to_color(al_map_rgb(0,0,0)); al_draw_bitmap(img_you_win, 0, 0, 0); al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores); al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair"); al_flip_display(); } } break; case 3: al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */ { quit = true; } if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */ { quit = true; } } if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */ { if(ev.timer.source == timer_60) { al_clear_to_color(al_map_rgb(0,0,0)); al_draw_bitmap(img_game_over, 0, 0, 0); al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores); al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair"); al_flip_display(); } } break; } } /* Destruindo as variaveis */ al_destroy_display(display); al_destroy_event_queue(event_queue); al_destroy_timer(timer_0p2); al_destroy_timer(timer_1); al_destroy_timer(timer_60); al_destroy_bitmap(img_home_screen); al_destroy_bitmap(img_dica_h1n1); al_destroy_bitmap(img_background0); al_destroy_bitmap(img_heart); al_destroy_bitmap(img_medal); al_destroy_bitmap(img_clock); al_destroy_bitmap(img_block1); al_destroy_bitmap(img_block2); al_destroy_bitmap(img_player_walking); al_destroy_bitmap(img_player_walking_shoot); al_destroy_bitmap(img_player_immobile); al_destroy_bitmap(img_player_immobile_shoot); al_destroy_bitmap(img_player_jump); al_destroy_bitmap(img_player_jump_shoot); al_destroy_bitmap(img_player_bullet); al_destroy_bitmap(img_enemy1); al_destroy_bitmap(img_boss1); al_destroy_bitmap(img_enemy_bullet); al_destroy_sample(spl_theme); al_destroy_sample(spl_playerShoot); al_destroy_sample(spl_mlk); return 0; }
ALLEGRO_EVENT EventHandler::waitForEvent() { al_wait_for_event(event_queue, &event); return (event); }
int main(int argc, char *argv[]) { ALLEGRO_CONFIG *config; ALLEGRO_EVENT event; unsigned buffer_count; unsigned samples; const char *s; ALLEGRO_PLAYMODE playmode = ALLEGRO_PLAYMODE_LOOP; initialize(); if (argc > 1) { stream_filename = argv[1]; } buffer_count = 0; samples = 0; config = al_load_config_file("ex_stream_seek.cfg"); if (config) { if ((s = al_get_config_value(config, "", "buffer_count"))) { buffer_count = atoi(s); } if ((s = al_get_config_value(config, "", "samples"))) { samples = atoi(s); } if ((s = al_get_config_value(config, "", "playmode"))) { if (!strcmp(s, "loop")) { playmode = ALLEGRO_PLAYMODE_LOOP; } else if (!strcmp(s, "once")) { playmode = ALLEGRO_PLAYMODE_ONCE; } } al_destroy_config(config); } if (buffer_count == 0) { buffer_count = 4; } if (samples == 0) { samples = 1024; } music_stream = al_load_audio_stream(stream_filename, buffer_count, samples); if (!music_stream) { abort_example("Stream error!\n"); } al_register_event_source(queue, al_get_audio_stream_event_source(music_stream)); loop_start = 0.0; loop_end = al_get_audio_stream_length_secs(music_stream); al_set_audio_stream_loop_secs(music_stream, loop_start, loop_end); al_set_audio_stream_playmode(music_stream, playmode); al_attach_audio_stream_to_mixer(music_stream, al_get_default_mixer()); al_start_timer(timer); while (!exiting) { al_wait_for_event(queue, &event); event_handler(&event); } myexit(); al_destroy_display(display); close_log(true); return 0; }
extern int main(int argc, char **argv) { ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_FONT *font; bool done = false; bool redraw = true; use_constraints = true; (void)argc; (void)argv; if (!al_init()) { abort_example("Failed to init Allegro.\n"); } if (!al_init_primitives_addon()) { abort_example("Failed to init primitives addon.\n"); } if (!al_init_image_addon()) { abort_example("Failed to init image addon.\n"); } if (!al_init_font_addon()) { abort_example("Failed to init font addon.\n"); } if (!al_init_native_dialog_addon()) { abort_example("Failed to init native dialog addon.\n"); } al_set_new_display_flags(ALLEGRO_WINDOWED #if defined(USE_GTK) && !defined(_WIN32) | ALLEGRO_GTK_TOPLEVEL #endif | ALLEGRO_RESIZABLE | ALLEGRO_MAXIMIZED | ALLEGRO_GENERATE_EXPOSE_EVENTS); /* creating really small display */ display = al_create_display(DISPLAY_W / 3, DISPLAY_H / 3); if (!display) { abort_example("Error creating display.\n"); } /* set lower limits for constraints only */ if(!al_set_window_constraints(display, DISPLAY_W / 2, DISPLAY_H / 2, 0, 0)) abort_example("Unable to set window constraints.\n"); al_apply_window_constraints(display, use_constraints); if (!al_install_keyboard()) { abort_example("Error installing keyboard.\n"); } queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); ALLEGRO_COLOR color_1 = al_map_rgb(255, 127, 0); ALLEGRO_COLOR color_2 = al_map_rgb(0, 255, 0); ALLEGRO_COLOR *color = &color_1; ALLEGRO_COLOR color_text = al_map_rgb(0, 0, 0); font = al_create_builtin_font(); while (!done) { ALLEGRO_EVENT event; if (redraw && al_is_event_queue_empty(queue)) { redraw = false; int x2 = al_get_display_width(display) - 10; int y2 = al_get_display_height(display) - 10; al_clear_to_color(al_map_rgb(0, 0, 0)); al_draw_filled_rectangle(10, 10, x2, y2, *color); draw_information(display, font, color_text); al_flip_display(); } al_wait_for_event(queue, &event); switch (event.type) { case ALLEGRO_EVENT_KEY_DOWN: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) done = true; break; case ALLEGRO_EVENT_KEY_UP: if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) { redraw = true; if (color == &color_1) { if (!al_set_window_constraints(display, 0, 0, DISPLAY_W, DISPLAY_H)) { abort_example("Unable to set window constraints.\n"); } color = &color_2; } else { if (!al_set_window_constraints(display, DISPLAY_W / 2, DISPLAY_H / 2, 0, 0)) { abort_example("Unable to set window constraints.\n"); } color = &color_1; } al_apply_window_constraints(display, use_constraints); } else if (event.keyboard.keycode == ALLEGRO_KEY_ENTER) { redraw = true; use_constraints = !use_constraints; al_apply_window_constraints(display, use_constraints); } break; case ALLEGRO_EVENT_DISPLAY_RESIZE: al_acknowledge_resize(event.display.source); redraw = true; break; case ALLEGRO_EVENT_DISPLAY_EXPOSE: redraw = true; break; case ALLEGRO_EVENT_DISPLAY_CLOSE: done = true; break; } /* switch (event.type) { */ } al_destroy_font(font); return 0; }
int main(int argc, char **argv){ ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_BITMAP *bouncer = NULL; float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE / 2.0; float bouncer_y = SCREEN_H / 2.0 - BOUNCER_SIZE / 2.0; float bouncer_dx = -4.0, bouncer_dy = 4.0; bool redraw = true; if(!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } timer = al_create_timer(1.0 / FPS); if(!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if(!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE); if(!bouncer) { fprintf(stderr, "failed to create bouncer bitmap!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_set_target_bitmap(bouncer); al_clear_to_color(al_map_rgb(255, 0, 255)); al_set_target_bitmap(al_get_backbuffer(display)); event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_bitmap(bouncer); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_clear_to_color(al_map_rgb(0,0,0)); al_flip_display(); al_start_timer(timer); while(1) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { if(bouncer_x < 0 || bouncer_x > SCREEN_W - BOUNCER_SIZE) { bouncer_dx = -bouncer_dx; } if(bouncer_y < 0 || bouncer_y > SCREEN_H - BOUNCER_SIZE) { bouncer_dy = -bouncer_dy; } bouncer_x += bouncer_dx; bouncer_y += bouncer_dy; redraw = true; } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; al_clear_to_color(al_map_rgb(0,0,0)); al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0); al_flip_display(); } } al_destroy_bitmap(bouncer); al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; }
int main(int argc, char **argv) { ALLEGRO_THREAD *thread[NUM_THREADS]; ALLEGRO_DISPLAY *display; ALLEGRO_TIMER *timer; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_EVENT event; bool need_draw; int i; (void)argc; (void)argv; for (i = 0; i < 256; i++) { sin_lut[i] = 128 + (int) (127.0 * sin(i / 8.0)); } if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_install_keyboard(); al_install_mouse(); display = al_create_display(W * IMAGES_PER_ROW, H * NUM_THREADS / IMAGES_PER_ROW); if (!display) { abort_example("Error creating display\n"); } timer = al_create_timer(1.0/3); if (!timer) { abort_example("Error creating timer\n"); } queue = al_create_event_queue(); if (!queue) { abort_example("Error creating event queue\n"); } al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); /* Note: * Right now, A5 video displays can only be accessed from the thread which * created them (at least for OpenGL). To lift this restriction, we could * keep track of the current OpenGL context for each thread and make all * functions accessing the display check for it.. not sure it's worth the * additional complexity though. */ al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_RGB_888); al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP); for (i = 0; i < NUM_THREADS; i++) { thread_info[i].bitmap = al_create_bitmap(W, H); if (!thread_info[i].bitmap) { goto Error; } thread_info[i].mutex = al_create_mutex(); if (!thread_info[i].mutex) { goto Error; } thread_info[i].cond = al_create_cond(); if (!thread_info[i].cond) { goto Error; } thread_info[i].is_paused = false; thread_info[i].random_seed = i; thread[i] = al_create_thread(thread_func, &thread_info[i]); if (!thread[i]) { goto Error; } } set_target(0, -0.56062033041600878303, -0.56064322926933807256); set_target(1, -0.57798076669230014080, -0.63449861991138123418); set_target(2, 0.36676836392830602929, -0.59081385302214906030); set_target(3, -1.48319283039401317303, -0.00000000200514696273); set_target(4, -0.74052910500707636032, 0.18340899525730713915); set_target(5, 0.25437906525768350097, -0.00046678223345789554); set_target(6, -0.56062033041600878303, 0.56064322926933807256); set_target(7, -0.57798076669230014080, 0.63449861991138123418); set_target(8, 0.36676836392830602929, 0.59081385302214906030); for (i = 0; i < NUM_THREADS; i++) { al_start_thread(thread[i]); } al_start_timer(timer); need_draw = true; while (true) { if (need_draw && al_is_event_queue_empty(queue)) { show_images(); need_draw = false; } al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_TIMER) { need_draw = true; } else if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { int n = (event.mouse.y / H) * IMAGES_PER_ROW + (event.mouse.x / W); if (n < NUM_THREADS) { double x = event.mouse.x - (event.mouse.x / W) * W; double y = event.mouse.y - (event.mouse.y / H) * H; /* Center to the mouse click position. */ if (thread_info[n].is_paused) { thread_info[n].target_x = x / W - 0.5; thread_info[n].target_y = y / H - 0.5; } toggle_pausedness(n); } } else if (event.type == ALLEGRO_EVENT_DISPLAY_EXPOSE) { need_draw = true; } else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (event.type == ALLEGRO_EVENT_KEY_DOWN) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } need_draw = true; } } for (i = 0; i < NUM_THREADS; i++) { /* Set the flag to stop the thread. The thread might be waiting on a * condition variable, so signal the condition to force it to wake up. */ al_set_thread_should_stop(thread[i]); al_lock_mutex(thread_info[i].mutex); al_broadcast_cond(thread_info[i].cond); al_unlock_mutex(thread_info[i].mutex); /* al_destroy_thread() implicitly joins the thread, so this call is not * strictly necessary. */ al_join_thread(thread[i], NULL); al_destroy_thread(thread[i]); } al_destroy_event_queue(queue); al_destroy_timer(timer); al_destroy_display(display); return 0; Error: return 1; }
int main(int argc, char *argv[]) { bool windowed = false; float rescale = 1.0f; std::string arg; if(argc > 1) { arg = argv[1]; if(arg == "--help") { std::cout << "-s {scale} for running in windowed mode and scaled (standart size is 1440*810)" << std::endl; return 0; } else if(arg == "-s") { if( argc > 2) { arg = argv[2]; rescale = atof(argv[2]); } windowed = true; } } /**initialize allegro*/ if(!al_init()){error_message("al_init()");return 33;} if(!al_init_primitives_addon()){error_message("al_init_primitives_addon()");return 33;} //if(!al_install_keyboard()){error_message("al_install_keyboard()");return 33;} //no use for keyboard in this game if(!al_install_mouse()){error_message("al_install_mouse()");return 33;} if(!al_init_image_addon()){error_message("al_init_image_addon()");return 33;} al_init_font_addon(); // returns void if(!al_init_ttf_addon()){error_message("al_init_ttf_addon()");return 33;} //audio if(al_install_audio() == true) { if(al_init_acodec_addon() == true){} else { error_message("al_init_acodec_addon() - cant initialize audio codec"); global::audio = false; global::sound_card = false; } } else { error_message("al_install_audio() - cant found sound device"); global::audio = false; global::sound_card = false; } /**Some allegro variables*/ ALLEGRO_DISPLAY *display = nullptr; ALLEGRO_EVENT_QUEUE *event_queue = nullptr; ALLEGRO_TIMER *timer = nullptr; ALLEGRO_BITMAP *logo = nullptr; /**Display preparation*/ bool supported_ratio = true; ALLEGRO_MONITOR_INFO mon_info; al_get_monitor_info(0, &mon_info); global::sHeight = mon_info.y2 - mon_info.y1; //gets monitor size in pixels global::sWidth = mon_info.x2 - mon_info.x1; global::aspectratio = round( ((float)global::sWidth / (float)global::sHeight) * 100.0f) / 100.0f; //gets aspectratio if(global::aspectratio == 1.78f){global::xratio = 16; global::yratio = 9;} // 16:9 screen ration else if(global::aspectratio == 1.6f){global::xratio = 16; global::yratio = 10;} // 16:10 else if(global::aspectratio == 1.33f){global::xratio = 4; global::yratio = 3;} // 4:3 else{supported_ratio = false;} global::dHeight = global::dWidth / global::xratio * global::yratio; global::xscale = (float)global::sWidth / (float)global::dWidth; global::yscale = (float)global::sHeight / (float)global::dHeight; /**display creation*/ al_set_new_bitmap_flags(ALLEGRO_MAG_LINEAR | ALLEGRO_MIN_LINEAR); // Thanks to this, magnified fonts dont look retarted, and game is fast (hopefully) :D if(windowed == true || supported_ratio == false) { supported_ratio = true; al_set_new_display_flags(ALLEGRO_WINDOWED | ALLEGRO_OPENGL); global::xscale = rescale; global::yscale = rescale; global::dWidth = 1440; global::dHeight = 810; display = al_create_display(global::dWidth*rescale, global::dHeight*rescale); } else { al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW | ALLEGRO_OPENGL); display = al_create_display(global::dWidth, global::dHeight); } if(display == nullptr){error_message("al_create_display()"); return 1;} al_set_window_title(display, "Este neviem meno, ale asi neco so zemiakom"); /**logo*/ logo = al_load_bitmap("resources/graphics/logo.png"); if(logo == nullptr){error_message("resources/graphics/logo.png not found");} else{ al_set_display_icon(display, logo);} /**Transformation*/ al_identity_transform(&global::trans); if(supported_ratio == true) { al_scale_transform(&global::trans, global::xscale, global::yscale); } else { error_message("Unsupported monitor type - upgrade you monitor pls"); float scale_backup_plan = (global::xscale > global::yscale ? global::yscale : global::xscale); global::xscale = scale_backup_plan; global::yscale = scale_backup_plan; al_scale_transform(&global::trans, global::xscale, global::yscale); } al_use_transform(&global::trans); /**timer*/ timer = al_create_timer(1.0f/global::FPS); if(timer == nullptr){error_message("al_create_timer()"); return 44;} bool redraw = true; /**even que*/ event_queue = al_create_event_queue(); if(event_queue == nullptr){error_message("al_create_event_queue()"); return 44;} /**registering event sources*/ al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_mouse_event_source()); al_start_timer(timer); rguil::mouse_state = &global::mouse_state; global::audio_player = new AudioHandler(10); #ifdef _SOUND_TEST ALLEGRO_SAMPLE *s = al_load_sample("resources/music/Fuck_This_Shit_Im_Out.wav"); ALLEGRO_SAMPLE_INSTANCE *si = al_create_sample_instance(s); global::audio_player->global_sounds.push_back(si); global::audio_player->Play_sample_instance(&si, ALLEGRO_PLAYMODE_LOOP); #endif // _SOUND_TEST #ifdef _FPS ALLEGRO_FONT *fps_font = nullptr; fps_font = al_load_font("resources/fonts/Asimov.otf", 12,0); int counter = 0; time_t tsttme2 = time(nullptr), tsttme = time(nullptr); int fps = 0; #endif // FPS global::save = new GameSave(); ScreenMain *SCMain = new ScreenMain(); global::audio_b = new Button("resources/fonts/Calibri.ttf", 1240, global::dHeight -65, 1240 + 40, global::dHeight - 25, "", al_map_rgba(0,0,0,0), ( global::audio == true ? MusicON : MusicOFF)); /**Main loop*/ //forced 30 FPS, drawing and computing in same thread while(global::loop == true) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); al_get_mouse_state(&global::mouse_state); if(ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } /**Take event input here*/ if(global::audio_b->Input(ev, global::xscale, global::yscale) == 2) { global::audio_b->unclick(); global::audio = (global::audio == true ? false : true); if(global::audio == true) { al_destroy_bitmap(global::audio_b->bmp); global::audio_b->bmp = al_load_bitmap(MusicON); global::audio_player->Mute_sample_instances(false); } else { al_destroy_bitmap(global::audio_b->bmp); global::audio_b->bmp = al_load_bitmap(MusicOFF); global::audio_player->Mute_sample_instances(true); } } SCMain->Input(ev, global::xscale, global::yscale); /**---------------------*/ #ifdef _FPS tsttme2 = time(&tsttme2); if(difftime(tsttme2,tsttme) >= 1.0f) { tsttme = time(&tsttme); fps = counter; counter = 0; } #endif // FPS if(redraw == true && al_is_event_queue_empty(event_queue)) { redraw = false; al_clear_to_color(al_map_rgb(0,0,0)); /**Draw and compute here*/ SCMain->Print(); global::audio_b->Print(); /**---------------------*/ #ifdef _FPS counter++; al_draw_text(fps_font, al_map_rgb(255,0,0), 0.0f,0.0f, 0, std::to_string(fps).c_str()); #endif // FPS al_flip_display(); } } #ifdef _SOUND_TEST global::audio_player->Stop_sample_instances(); global::audio_player->global_sounds.erase(global::audio_player->global_sounds.begin()); al_destroy_sample_instance(si); al_destroy_sample(s); #endif // _SOUND_TEST delete global::audio_b; delete SCMain; delete global::save; delete global::audio_player; al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); if(logo != nullptr) al_destroy_bitmap(logo); #ifdef _FPS al_destroy_font(fps_font); #endif // FPS return 0; }
int main() { ALLEGRO_DISPLAY* display = NULL; ALLEGRO_DISPLAY_MODE disp; ALLEGRO_EVENT_QUEUE* eq = NULL; ALLEGRO_TIMER* timer = NULL; ALLEGRO_TIMER* ball_timer = NULL; bool run = true; bool draw = false; if (!al_init()) { return -1; } al_get_display_mode(al_get_num_display_modes() - 1, &disp); std::cout << disp.height << " " << height << std::endl; std::cout << disp.width << " " << width << std::endl; height = disp.height / 3 * 2; width = height / 9 * 16; std::cout << disp.height << " " << height << std::endl; std::cout << disp.width << " " << width << std::endl; al_set_new_display_flags(ALLEGRO_FULLSCREEN); display = al_create_display(width, height); al_set_window_title(display, "PONG V2"); if (display == NULL) { return -1; } init(&player1, &player2, &ball); eq = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); ball_timer = al_create_timer(15.0); al_install_keyboard(); al_init_primitives_addon(); al_init_font_addon(); al_init_ttf_addon(); font = al_load_ttf_font("./arial.ttf", 18, 0); scorefont = al_load_ttf_font("./arial.ttf", (height * width) / 36000, 0); al_register_event_source(eq, al_get_keyboard_event_source()); al_register_event_source(eq, al_get_display_event_source(display)); al_register_event_source(eq, al_get_timer_event_source(timer)); al_hide_mouse_cursor(display); al_start_timer(timer); while (run) { ALLEGRO_EVENT ev; al_wait_for_event(eq, &ev); if (ev.type == ALLEGRO_EVENT_TIMER) { draw = true; } else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { run = false; } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_S: keys[P1][DOWN] = true; break; case ALLEGRO_KEY_W: keys[P1][UP] = true; break; case ALLEGRO_KEY_DOWN: keys[P2][DOWN] = true; break; case ALLEGRO_KEY_UP: keys[P2][UP] = true; break; case ALLEGRO_KEY_SPACE: start = true; firstGame = false; break; case ALLEGRO_KEY_ESCAPE: run = false; break; case ALLEGRO_KEY_P: if (pause == true) pause = false; else if (pause == false) pause = true; break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_S: keys[P1][DOWN] = false; break; case ALLEGRO_KEY_W: keys[P1][UP] = false; break; case ALLEGRO_KEY_DOWN: keys[P2][DOWN] = false; break; case ALLEGRO_KEY_UP: keys[P2][UP] = false; break; } } if (draw && al_event_queue_is_empty(eq)) { if (!pause) { if (keys[P1][UP])update(&player1, -1); if (keys[P1][DOWN])update(&player1, 1); if (keys[P2][UP])update(&player2, -1); if (keys[P2][DOWN])update(&player2, 1); update(&ball); updateGame(&player1, &player2, &ball); render(); draw = false; } } } al_destroy_display(display); al_destroy_event_queue(eq); return 0; }
int main(void) { ALLEGRO_VERTEX v[8]; ALLEGRO_DISPLAY * display; ALLEGRO_TRANSFORM perst; ALLEGRO_TRANSFORM camt; ALLEGRO_BITMAP * texture, * texture2; ALLEGRO_EVENT_QUEUE * queue; ALLEGRO_EVENT event; ALLEGRO_FONT * font; int busy = 1; float cx = 0; float cy = -2; // 128; float cz = 0; int face = 0; int hori = 0; float angle = 0; float theta = 0; float near = 2; float far = 8192; float zoom = 1; float scale = 1.0; float us = 20; float ratio = 480.0 / 640.0; al_init(); al_init_image_addon(); al_init_font_addon(); al_install_keyboard(); font = al_create_builtin_font(); queue = al_create_event_queue(); al_set_new_display_option(ALLEGRO_DEPTH_SIZE, 16, ALLEGRO_SUGGEST); display = al_create_display(640, 480); al_register_event_source(queue, al_get_keyboard_event_source()); texture = al_load_bitmap("tile_1.png"); texture2 = al_load_bitmap("tile_2.png"); /* Allegro coordinates: +Y is down, +X is to the right, * and +Z comes "out of" the screen. * */ while (busy) { init_vertex(v+0, 0, 0, 0, 0, 0, 1, 0, 0, 1); init_vertex(v+1, 0, 0, us, 0, 256, 0, 1, 0, 1); init_vertex(v+2, us, 0, us, 256, 256, 0, 0, 1, 1); init_vertex(v+3, us, 0, 0, 256, 0, 1, 1, 0, 1); init_vertex(v+4, us, -us, 0, 256, 256, 1, 0, 1, 1); init_vertex(v+5, 0, -us, 0, 256, 0, 0, 1, 1, 1); init_vertex(v+6, 0, -us, us, 256, 256, 0, 0, 0, 1); init_vertex(v+7, 0, 0, us, 0, 256, 1, 1, 1, 1); al_identity_transform(&camt); al_scale_transform_3d(&camt, scale, scale, scale); al_translate_transform_3d(&camt, cx, cy, cz); angle = face * 0.125 * ALLEGRO_PI; al_rotate_transform_3d(&camt, 0, -1, 0, angle); theta = hori * 0.125 * ALLEGRO_PI; al_rotate_transform_3d(&camt, -1, 0, 0, theta); al_use_transform(&camt); // al_set_projection_transform(display, &perst); al_clear_to_color(al_map_rgb_f(0.75, 0.75, 0.95)); al_set_render_state(ALLEGRO_DEPTH_TEST, 1); al_clear_depth_buffer(far); al_identity_transform(&perst); al_perspective_transform(&perst, -1, ratio, near, 1, -ratio, far); al_use_projection_transform(&perst); al_draw_filled_rectangle(0, 0, 4, 5, al_map_rgb_f(0, 0.25, 0.25)); al_draw_prim(v, NULL, texture, 0, 8, ALLEGRO_PRIM_TRIANGLE_FAN); draw_textured_colored_rectangle_3d(0 , -us, 0, us, us, 0, 1.0, 1.0, texture2, al_map_rgb_f(1,1,1)); draw_textured_colored_rectangle_3d(0 , -us, 0, 0, us, us, 1.0, 1.0, texture2, al_map_rgb_f(1,1,1)); draw_textured_colored_rectangle_3d(0 , 0, 0, us, 0, us, 1.0, 1.0, texture2, al_map_rgb_f(1,1,1)); al_identity_transform(&perst); al_orthographic_transform(&perst, 0, 0, -1.0, 640, 480, 1.0); al_identity_transform(&camt); al_use_projection_transform(&perst); al_use_transform(&camt); al_draw_filled_rectangle(111, 22, 133, 44, al_map_rgb_f(0.25, 0.25, 0)); al_draw_multiline_textf(font, al_map_rgb_f(1,1,1), 10, 10, 620, 0, 0, "Coords: (%f %f %f)\nAngle: (%f %f)\nView: [%f %f %f %f]\nScale: %f", cx, cy, cz, angle, theta, near, far, zoom, scale); al_flip_display(); al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_KEY_DOWN) { switch (event.keyboard.keycode) { case ALLEGRO_KEY_RIGHT: cx += 8; break; case ALLEGRO_KEY_LEFT: cx -= 8; break; case ALLEGRO_KEY_UP: cy += 8; break; case ALLEGRO_KEY_DOWN: cy -= 8; break; case ALLEGRO_KEY_HOME: cz += 8; break; case ALLEGRO_KEY_END: cz -= 8; break; case ALLEGRO_KEY_R: face++; break; case ALLEGRO_KEY_L: face--; break; case ALLEGRO_KEY_H: hori++; break; case ALLEGRO_KEY_G: hori--; break; case ALLEGRO_KEY_N: near *= 2.0; break; case ALLEGRO_KEY_M: near /= 2.0; break; case ALLEGRO_KEY_F: far += 64; break; case ALLEGRO_KEY_V: far -= 64; break; case ALLEGRO_KEY_Z: zoom *= 2.0f; break; case ALLEGRO_KEY_S: zoom /= 2.0f; break; case ALLEGRO_KEY_A: scale *= 2.0f; break; case ALLEGRO_KEY_Q: scale /= 2.0f; break; case ALLEGRO_KEY_ESCAPE: busy = 0 ; break; default: break; } } } al_destroy_bitmap(texture); al_destroy_bitmap(texture2); return 0; }
void game_loop(void) { //load font ALLEGRO_FONT *font = al_load_ttf_font("RobotoMono-Medium.ttf",10,0); //create floor array (will eventually make this a function) srand(time(NULL)); for (int x = 0; x < 16; x++) { //for each y value between 2 and 13 for (int y = 0; y < 16; y++) { randX = 6 + (rand() % (int)(12 - 6 + 1)); randY = 0 + (rand() % (int)(3 - 0 + 1)); //drawDungeonTile(randX, randY, x, y); floorArray [x] [y] [0] = randX; floorArray [x] [y] [1] = randY; } } Player p1; //(speed, friction, sprint accel, max speed) //default: p1.setMovement(1.4, .4, 1.8, 4); p1.setMovement(1.4, .4, 1.8, 3); p1.setPosition(tileSize * 7, tileSize * 12); p1.setCurrentRoom(112); p1.setInitial(tileSize,tileSize,240,240); p1.setH(tileSize); p1.setW(tileSize); p1.setAnimation(tileSize * 0, tileSize * 0,0,0,9,4,0); p1.canMove = true; p1.vincible = true; p1.blinking = false; p1.blinkTimer = 5; p1.setMaxHP(100); p1.setCurrentHP(100); int tempBlinkTimer = p1.blinkTimer; p1.knockback = 0; p1.knockbackTimer = 0; p1.setBound(19,27,7,3, 14,8,9,24); p1.canRotate = true; //p1.setX(240); //p1.setY(240); p1.leavingTransport = 0; //init player prototypes void movePlayerUp(Player &p); void movePlayerDown(Player &p); void movePlayerLeft(Player &p); void movePlayerRight(Player &p); void sprintPlayer(Player &p); void maxSpeedPlayer(Player &p); void maxWalkSpeedPlayer(Player &p); void updatePlayer(Player &p); void collidePlayerWallX(Player &p, int obstacles [16][16]); void collidePlayerWallY(Player &p, int obstacles [16][16]); void collidePlayerMonster(Player &p, Monster m[]); void drawPlayer(Player &p); void resetPlayerAnimation(Player &p); //load current room map Room currentRoom; currentRoom.getWalkRoom(p1.getCurrentRoom()); //currentRoom.getCollideRoom(p1.getCurrentRoom()); //load all objects objectArray currentArray; currentArray.getObjects(p1.getCurrentRoom()); //load current room transporters Transporter currentTrans; currentTrans.exitNumber = 0; //load current room buttons //void getButton (int array[][16]); void getButton (Button b[], int array[][16]); //void drawButtons (int buttonArray[][16]); void drawButtons (Button b[]); void collidePlayerButton(Player &p, Button b[]); Button currentButts[numButts]; getButton (currentButts, currentArray.buttsArray); void getDoor (Door d[], int array[][16]); void placeDoor (Door d[], Room &r); Door currentDoor[numDoors]; getDoor (currentDoor, currentArray.buttsArray); //currentDoor.getDoorState(); void getMonsters (Monster m[], int array[][16]); void drawMonsters (Monster m[]); void collideMonsterWallX(Monster m[], int obstacles [16][16]); void collideMonsterWallY(Monster m[], int obstacles [16][16]); void updateMonstersX (Monster currentMonsters[]); void updateMonstersY (Monster currentMonsters[]); //void seekMonsters (Monster m[], Player p); void seekMonsters (Monster &m, float x, float y); void seekPathMonsters (Monster &m, Player p); void pathfindMonsters (Monster &m, Player p, int obstacles [16][16], int mt); void newPathfindMonster (Monster &m, Player p, int obstacles [16][16]); int monsterDebug = 1; //init monsters prototypes Monster currentMonsters[numMonsters]; //load current room's monsters getMonsters(currentMonsters, currentArray.array); Weapon stick(15, 32, 4, 0, 20, bash, none); stick.setAnimation(tileSize * 0, tileSize * 0,0,0,2,3,0); void updateWeapon(Player &p, Weapon &w); void collideWeaponMonster(Weapon w, Monster m[], Player p); void resetAttack (Player p, Weapon &w); void attackWeapon(Player p, Weapon &w); void drawWeapon(Player p, Weapon &w); void drawCutscene(int num, int message); void closingSplash(void); Cutscene currentCutscene; currentCutscene.cutsceneFont = al_load_ttf_font("data/slkscr.ttf",32,0); int vincibleTimer = 0; int pathCounter = 0; bool showHitboxes = false; bool createCutscene = false; bool inCutscene = false; bool runSeekPath = false; al_start_timer(timer); while (!done) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_TIMER) { if(key[keyW]) { movePlayerUp(p1); } else if(key[keyS]) { movePlayerDown(p1); } if(key[keyA]) { movePlayerLeft(p1); } else if(key[keyD]) { movePlayerRight(p1); } if(!(key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) { resetPlayerAnimation(p1); } if(key[keyShift] && (key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) { sprintPlayer(p1); } else { maxWalkSpeedPlayer(p1); } maxSpeedPlayer(p1); if(key[keySpace]) { //printf("ATTACK!\n"); } //update player position p1.setX(p1.getX() + p1.getDx()); collidePlayerMonster(p1,currentMonsters); collidePlayerButton(p1,currentButts); //printf("player DX: %f\n",p1.getDx()); //printf("player DY: %f\n",p1.getDy()); //X axis //detect and respond to collision with obstacles collidePlayerWallX(p1,currentRoom.collideArray); if(p1.canMove) { p1.setDx(p1.getDx() * p1.getFriction()); } //knockback timer //Y axis p1.setY(p1.getY() + p1.getDy()); collidePlayerWallY(p1,currentRoom.collideArray); p1.setDy(p1.getDy() * p1.getFriction()); //Monster movement and wall collisions for (int i = 0; i < numMonsters; i++) { if (currentMonsters[i].isLive) { newPathfindMonster( currentMonsters[i], p1, currentRoom.collideArray); } } //seekMonsters(currentMonsters[1],p1.getX(), p1.getY()); for (int i = 0; i < numMonsters; i++) { if (currentMonsters[i].isLive) { //seekPathMonsters(currentMonsters[i],p1); //printf("Monster location: %.1f, %.1f\n",currentMonsters[1].getX(),currentMonsters[1].getY()); seekMonsters(currentMonsters[i],currentMonsters[i].destX, currentMonsters[i].destY); //seekMonsters(currentMonsters[i],64,64); } } //weapon updating updateWeapon(p1,stick); collideWeaponMonster(stick, currentMonsters, p1); updateMonstersX(currentMonsters); collideMonsterWallX(currentMonsters,currentRoom.collideArray); updateMonstersY(currentMonsters); collideMonsterWallY(currentMonsters,currentRoom.collideArray); //if able to transport if (p1.leavingTransport == 0) { //check for collisions with transporter currentTrans.exitNumber = currentTrans.playerTransCollision(p1.getX(), p1.getY(),currentArray.array); if (currentTrans.exitNumber) { currentTrans.fromNumber = p1.getCurrentRoom(); p1.leavingTransport = 1; } } //if transporting if ( p1.leavingTransport == 1) { //set room to move to p1.setCurrentRoom(currentTrans.exitNumber); currentRoom.getWalkRoom(p1.getCurrentRoom()); //currentRoom.getCollideRoom(p1.getCurrentRoom()); currentArray.getObjects(p1.getCurrentRoom()); getMonsters(currentMonsters, currentArray.array); getButton(currentButts, currentArray.buttsArray); getDoor(currentDoor, currentArray.buttsArray); placeDoor(currentDoor, currentRoom); //must set player's location to the location of the exit portal in the new room currentTrans.getDestination(currentArray.array); p1.setX(currentTrans.destination[0] + tileSize/2); p1.setY(currentTrans.destination[1] + tileSize/2); currentTrans.destination[0] = 0; currentTrans.destination[1] = 0; p1.leavingTransport = 0; } //functions for drawing the player (will need to go elsewhere eventually) //invincible timer if (p1.vincible == false) { vincibleTimer ++; tempBlinkTimer --; p1.blinking = true; //printf("p1 blinking? %d, %d\n",p1.blinking, tempBlinkTimer); if (tempBlinkTimer < 0) { p1.blinking = false; if ( tempBlinkTimer == p1.blinkTimer * (-3)) { tempBlinkTimer = p1.blinkTimer; } } if (vincibleTimer == invincibleTime) { p1.vincible = true; p1.blinking = false; vincibleTimer = 0; //printf ("vincible Again \n"); } } pathCounter ++; if (pathCounter == 90) {pathCounter = 0;} redraw = true; } //key pressed down else if (event.type == ALLEGRO_EVENT_KEY_DOWN) { switch (event.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; case ALLEGRO_KEY_W: key[keyW] = true; break; case ALLEGRO_KEY_A: key[keyA] = true; break; case ALLEGRO_KEY_S: key[keyS] = true; break; case ALLEGRO_KEY_D: key[keyD] = true; break; case ALLEGRO_KEY_C: key[keyC] = true; if (!inCutscene) { currentCutscene.openDialog ("data/cutscenes/1"); createCutscene = 1; } if (inCutscene) { currentCutscene.currentMessage ++; } while(1) break; case ALLEGRO_KEY_LSHIFT: key[keyShift] = true; break; case ALLEGRO_KEY_SPACE: key[keySpace] = true; runSeekPath = true; //pathfindMonsters( currentMonsters[1], p1, currentRoom.collideArray, pathCounter); newPathfindMonster( currentMonsters[1], p1, currentRoom.collideArray); attackWeapon(p1,stick); break; } } //key released else if (event.type == ALLEGRO_EVENT_KEY_UP) { switch (event.keyboard.keycode) { case ALLEGRO_KEY_W: key[keyW] = false; break; case ALLEGRO_KEY_A: key[keyA] = false; break; case ALLEGRO_KEY_S: key[keyS] = false; break; case ALLEGRO_KEY_D: key[keyD] = false; break; case ALLEGRO_KEY_C: key[keyC] = false; break; case ALLEGRO_KEY_LSHIFT: key[keyShift] = false; break; case ALLEGRO_KEY_SPACE: key[keySpace] = false; resetAttack(p1, stick); break; } } else if(event.type == ALLEGRO_EVENT_MOUSE_AXES || ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) { crosshair_x = event.mouse.x - crosshairSize/2; crosshair_y = event.mouse.y - crosshairSize/2; } if (redraw && al_is_event_queue_empty(event_queue)) { redraw = false; //Clear screen to black al_clear_to_color(al_map_rgb(0, 0, 0)); if (createCutscene == true) { al_set_target_bitmap(cutsceneBackdrop); al_clear_to_color(al_map_rgb(0, 0, 0)); } //update_graphics(); //graphics that will always be there if (!inCutscene) { //drawDoor(currentDoor,currentRoom); drawDungeon(floorArray,currentRoom.walkArray); drawDungeon(floorArray,currentRoom.collideArray); for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { al_draw_textf(font, al_map_rgb(255,255,255),j*tileSize,i*tileSize,ALLEGRO_ALIGN_LEFT,"%d,%d",j+1,i+1); } } if (transDebug) currentTrans.drawTransporters(currentArray.array); drawButtons(currentButts); drawMonsters(currentMonsters); if (p1.getDir() != UP && p1.getDir() != LEFT) { if (p1.blinking == false) { drawPlayer(p1); } } drawWeapon(p1,stick); if (p1.getDir() == UP || p1.getDir() == LEFT) { if (p1.blinking == false) { drawPlayer(p1); } } al_draw_textf(font, al_map_rgb(255,255,255),0,tileSize*0,ALLEGRO_ALIGN_LEFT,"playerHP: %d",p1.getCurrentHP()); for (int i = 1; i < numMonsters; i++) { if (currentMonsters[i].getCurrentHP() > -10000 && currentMonsters[i].getCurrentHP() <10000) { al_draw_textf(font, al_map_rgb(255,255,255),tileSize * 4 * i,tileSize*15,ALLEGRO_ALIGN_LEFT,"monster %d HP: %d",i,currentMonsters[i].getCurrentHP()); } } } if (inCutscene) { currentCutscene.drawCutscene(1, 1); } //al_draw_bitmap(crosshair, crosshair_x, crosshair_y, 0); if (createCutscene == true) { inCutscene = true; createCutscene = false; al_set_target_bitmap(al_get_backbuffer(display)); //al_lock_bitmap(cutsceneBackdrop); inCutscene = true; } al_flip_display(); } } }
int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_BITMAP *pared2 = NULL; ALLEGRO_BITMAP *carretera = NULL; ALLEGRO_BITMAP *fondo = NULL; ALLEGRO_BITMAP *tierra = NULL; ALLEGRO_BITMAP *coche = NULL; ALLEGRO_BITMAP *coche2 = NULL; ALLEGRO_BITMAP *otros = NULL; ALLEGRO_BITMAP *porche1 = NULL; ALLEGRO_BITMAP *porche2 = NULL; ALLEGRO_BITMAP *porche3 = NULL; ALLEGRO_BITMAP *porche4 = NULL; ALLEGRO_BITMAP *porche5 = NULL; ALLEGRO_BITMAP *porche6 = NULL; ALLEGRO_BITMAP *freno = NULL; ALLEGRO_BITMAP *ciudad = NULL; ALLEGRO_BITMAP *ganas = NULL; ALLEGRO_BITMAP *pierdes = NULL; ALLEGRO_FONT *font = NULL; int i = 3; int objetivo = 10000; int tiempo = 3600; float velocidad = 0; float carreteray = 0; float carreteray2 = 720; float bouncer_x = 360; float bouncer_y = (SCREEN_H / 10) * 9; int camaraX; float carreterax1; float carreterax2; float angulo = 1.571; float velocidadt = -10; float veltraficox, veltraficoy; float centro = 695; float ladoizq = 620; float ladoder = 790; float frenosi = 3; float hasganao = 5000; float hasperdio = 5000; bool key[5] = { false, false, false, false, false}; bool redraw = true; bool doexit = false; struct Trafico trafico1 = {1000, 300, 1000, 5, 1}; struct Trafico trafico2 = {850, 200, 850, 5 , 2}; struct Trafico trafico3 = {1170, 0, 1170, 5, 3}; struct Trafico trafico4 = {1000, 400, 1000, 5, 4}; struct Trafico trafico5 = {850, 100, 850, 5, 1}; struct Trafico trafico6 = {1170, 500, 1170, 5, 2}; if (!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } if (!al_init_image_addon()) { al_show_native_message_box(display, "Error", "Error", "No carga lo de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR); } if (!al_init_primitives_addon()) { al_show_native_message_box(display, "Error", "Error", "No carga lo de primitivos", NULL, ALLEGRO_MESSAGEBOX_ERROR); } if (!al_install_keyboard()) { fprintf(stderr, "failed to initialize the keyboard!\n"); return -1; } timer = al_create_timer(1.0 / FPS); if (!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if (!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } al_init_font_addon(); al_init_ttf_addon(); font = al_load_ttf_font("djc2.otf", 60, 0); pared2 = al_create_bitmap(PARED2_X, PARED2_Y); carretera = al_load_bitmap("road22.png"); if (!carretera) { fprintf(stderr, "failed to create bouncer bitmap!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } fondo = al_load_bitmap("cielo2.png"); tierra = al_load_bitmap("camino4.png"); coche = al_load_bitmap("outrun2.png"); otros = al_load_bitmap("outruntrprueba5.png"); ciudad = al_load_bitmap("ciudad3.png"); freno = al_load_bitmap("freno.png"); ganas = al_load_bitmap("youwin.png"); pierdes = al_load_bitmap("youlose.png"); al_convert_mask_to_alpha(coche, al_map_rgb(186, 254, 202)); al_convert_mask_to_alpha(otros, al_map_rgb(186, 254, 202)); if (!fondo) { al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_display(display); return 0; } if (!coche) { al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR); al_destroy_display(display); return 0; } al_set_target_bitmap(pared2); al_clear_to_color(al_map_rgb(150, 150, 150)); al_set_target_bitmap(al_get_backbuffer(display)); event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_bitmap(pared2); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_clear_to_color(al_map_rgb(0, 0, 0)); al_flip_display(); al_start_timer(timer); while (!doexit) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if (ev.type == ALLEGRO_EVENT_TIMER) { tiempo -= 1; /*Spawn del trafico*/ srand(time(NULL)); int distancia = rand() % (950 - 750) + 750; int distancia2 = rand() % (950 - 750) + 750; int distancia3 = rand() % (950 - 750) + 750; int distancia4 = rand() % (1201 - 1050) + 1050; int distancia5 = rand() % (1201 - 1050) + 1050; int distancia6 = rand() % (1201 - 1050) + 1050; /*Teclas, movimiento y cambio de sprites en coche principal*/ if (key[KEY_UP] && velocidad < 25) { velocidad += 0.5; velocidadt += 0.5; } else if (velocidad > 0) { velocidad -= 0.1; velocidadt -= 0.1; } if (key[KEY_DOWN]) { velocidad -= 0.3; velocidadt -= 0.3; frenosi = SCREEN_W / 2; } else{ frenosi = 3000; } if (key[KEY_LEFT] && velocidad > 0) { bouncer_x -= 4; frenosi = frenosi + 3; } if (key[KEY_LEFT] && i > 1 && velocidad > 0) { i -= 1; } else if (!key[KEY_LEFT] && i < 4) { i += 1; } if (key[KEY_RIGHT] && velocidad > 0) { bouncer_x += 4; frenosi = frenosi - 3; } if (key[KEY_RIGHT] && i < 5 && velocidad > 0) { i += 1; } else if (!key[KEY_RIGHT] && i > 3) { i -= 1; } objetivo -= velocidad / 10; /*Carretera*/ carreteray += velocidad; carreteray2 += velocidad; if (carreteray > 1080) { carreteray = carreteray2 - 720; } if (carreteray2 > 1080) { carreteray2 = carreteray -720; } /*Limites de sprite y velocidad segun posición*/ if (velocidad < 0){ velocidad = 0; i = 3; } if (bouncer_x < 140 && velocidad > 4) { velocidad -= 0.6; velocidadt -= 0.6; } if (bouncer_x > 590 && velocidad > 4) { velocidad -= 0.6; velocidadt -= 0.6; } /*Formulas para velocidad y posicion del trafico*/ veltraficox = (velocidadt / 5) * cos(angulo); veltraficoy = (velocidadt / 5) * sin(angulo); trafico1.traficox += veltraficox; trafico1.traficoy += veltraficoy; trafico2.traficox += veltraficox; trafico2.traficoy += veltraficoy - 1; trafico3.traficox += veltraficox; trafico3.traficoy += veltraficoy - 1; trafico4.traficox += veltraficox; trafico4.traficoy += veltraficoy; trafico5.traficox += veltraficox; trafico5.traficoy += veltraficoy - 1; trafico6.traficox += veltraficox; trafico6.traficoy += veltraficoy - 1; /*Reaparicion del trafico.*/ if (trafico1.traficoy > distancia) { trafico1.traficoy = 200; trafico1.traficox = trafico1.spawnp; trafico1.otrosi = 5; trafico1.otrosy = rand() % 4; } if (trafico2.traficoy > distancia2) { trafico2.otrosi = 5; trafico2.traficoy = 200; trafico2.traficox = trafico2.spawnp; trafico2.otrosy = rand() % 4; } if (trafico3.traficoy > distancia3) { trafico3.otrosi = 5; trafico3.traficoy = 200; trafico3.traficox = trafico3.spawnp; trafico3.otrosy = rand() % 4; } if (trafico4.traficoy > distancia4) { trafico4.otrosi = 5; trafico4.traficoy = 200; trafico4.traficox = trafico4.spawnp; trafico4.otrosy = rand() % 4; } if (trafico5.traficoy > distancia5) { trafico5.otrosi = 5; trafico5.traficoy = 200; trafico5.traficox = trafico5.spawnp; trafico5.otrosy = rand() % 4; } if (trafico6.traficoy > distancia6) { trafico6.otrosi = 5; trafico6.traficoy = 200; trafico6.traficox = trafico6.spawnp; trafico6.otrosy = rand() % 4; } /*Perspectiva - Falso 3D*/ camaraX = bouncer_x; carreterax1 = 650 - (camaraX / 2); carreterax2 = 1130 - (camaraX / 2); if (carreterax1 < 820 - camaraX){ carreterax1 = 820 - camaraX; } if (carreterax1 > 860 - camaraX) { carreterax1 = 860 - camaraX; } if (carreterax2 > 1320 - camaraX) { carreterax2 = 1320 - camaraX; } if (carreterax2 < 1280 - camaraX) { carreterax2 = 1280 - camaraX; } /*Creacion de sprites*/ coche2 = al_create_sub_bitmap(coche, i * 130, 0, 130, 74); porche1 = al_create_sub_bitmap(otros, trafico1.otrosi * 130, trafico1.otrosy * 62, 130, 62); porche2 = al_create_sub_bitmap(otros, trafico2.otrosi * 130, trafico2.otrosy * 62, 130, 62); porche3 = al_create_sub_bitmap(otros, trafico3.otrosi * 130, trafico3.otrosy * 62, 130, 62); porche4 = al_create_sub_bitmap(otros, trafico4.otrosi * 130, trafico4.otrosy * 62, 130, 62); porche5 = al_create_sub_bitmap(otros, trafico5.otrosi * 130, trafico5.otrosy * 62, 130, 62); porche6 = al_create_sub_bitmap(otros, trafico6.otrosi * 130, trafico6.otrosy * 62, 130, 62); /*Cambio de sprites en Trafico*/ /*porche1*/ if (trafico1.traficoy > 370) { if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 5; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 6; } } if (trafico1.traficoy > 420){ if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 4; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 7; } } if (trafico1.traficoy > 470) { if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 3; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 8; } } if (trafico1.traficoy > 520) { if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 2; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 9; } } if (trafico1.traficoy > 570) { if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 1; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 10; } } if (trafico1.traficoy > 620) { if (trafico1.traficox - camaraX < centro) { trafico1.otrosi = 0; } if (trafico1.traficox - camaraX > centro) { trafico1.otrosi = 11; } } /*porche2*/ if (trafico2.traficoy > 370) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 5; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 6; } } if (trafico2.traficoy > 420) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 4; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 7; } } if (trafico2.traficoy > 470) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 3; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 8; } } if (trafico2.traficoy > 520) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 2; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 9; } } if (trafico2.traficoy > 570) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 1; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 10; } } if (trafico2.traficoy > 620) { if (trafico2.traficox - camaraX < centro) { trafico2.otrosi = 0; } if (trafico2.traficox - camaraX > centro) { trafico2.otrosi = 11; } } /*porche3*/ if (trafico3.traficoy > 370) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 5; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 6; } } if (trafico3.traficoy > 420) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 4; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 7; } } if (trafico3.traficoy > 470) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 3; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 8; } } if (trafico3.traficoy > 520) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 2; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 9; } } if (trafico3.traficoy > 570) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 1; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 10; } } if (trafico3.traficoy > 620) { if (trafico3.traficox - camaraX < centro) { trafico3.otrosi = 0; } if (trafico3.traficox - camaraX > centro) { trafico3.otrosi = 11; } } /*porche4*/ if (trafico4.traficoy > 370) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 5; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 6; } } if (trafico4.traficoy > 420) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 4; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 7; } } if (trafico4.traficoy > 470) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 3; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 8; } } if (trafico4.traficoy > 520) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 2; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 9; } } if (trafico4.traficoy > 570) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 1; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 10; } } if (trafico4.traficoy > 620) { if (trafico4.traficox - camaraX < centro) { trafico4.otrosi = 0; } if (trafico4.traficox - camaraX > centro) { trafico4.otrosi = 11; } } /*porche5*/ if (trafico5.traficoy > 370) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 5; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 6; } } if (trafico5.traficoy > 420) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 4; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 7; } } if (trafico5.traficoy > 470) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 3; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 8; } } if (trafico5.traficoy > 520) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 2; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 9; } } if (trafico5.traficoy > 570) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 1; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 10; } } if (trafico5.traficoy > 620) { if (trafico5.traficox - camaraX < centro) { trafico5.otrosi = 0; } if (trafico5.traficox - camaraX > centro) { trafico5.otrosi = 11; } } /*porche6*/ if (trafico6.traficoy > 370) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 5; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 6; } } if (trafico6.traficoy > 420) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 4; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 7; } } if (trafico6.traficoy > 470) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 3; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 8; } } if (trafico6.traficoy > 520) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 2; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 9; } } if (trafico6.traficoy > 570) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 1; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 10; } } if (trafico6.traficoy > 620) { if (trafico6.traficox - camaraX < centro) { trafico6.otrosi = 0; } if (trafico6.traficox - camaraX > centro) { trafico6.otrosi = 11; } } /*Colisiones*/ if (ladoizq < trafico1.traficox + 65 - camaraX && trafico1.traficox + 65 - camaraX < ladoder && bouncer_y < trafico1.traficoy && trafico1.traficoy < 700) { velocidad = 0; velocidadt = -10; } if (ladoizq < trafico2.traficox + 65 - camaraX && trafico2.traficox + 65 - camaraX < ladoder && bouncer_y < trafico2.traficoy && trafico2.traficoy < 700) { velocidad = 0; velocidadt = -10; } if (ladoizq < trafico3.traficox + 65 - camaraX && trafico3.traficox + 65 - camaraX < ladoder && bouncer_y < trafico3.traficoy && trafico3.traficoy < 700) { velocidad = 0; velocidadt = -10; } if (ladoizq < trafico4.traficox + 65 - camaraX && trafico4.traficox + 65 - camaraX < ladoder && bouncer_y < trafico4.traficoy && trafico4.traficoy < 700) { velocidad = 0; velocidadt = -10; } if (ladoizq < trafico5.traficox + 65 - camaraX && trafico5.traficox + 65 - camaraX < ladoder && bouncer_y < trafico5.traficoy && trafico5.traficoy < 700) { velocidad = 0; velocidadt = -10; } if (ladoizq < trafico6.traficox + 65 - camaraX && trafico6.traficox + 65 - camaraX < ladoder && bouncer_y < trafico6.traficoy && trafico6.traficoy < 700) { velocidad = 0; velocidadt = -10; } /*Funcionamiento de la Camara*/ if (camaraX > mundoAncho - SCREEN_W) { camaraX = mundoAncho - SCREEN_W; } if (camaraX < 0) { camaraX = 0; } if (bouncer_x > mundoAncho - SCREEN_W) { bouncer_x = mundoAncho - SCREEN_W; } if (bouncer_x < 0) { bouncer_x = 0; } /*Fin de partida*/ if (tiempo < 0 & objetivo > 0){ al_stop_timer(timer); hasperdio = 292.5; } if (objetivo < 0 & tiempo > 0) { al_stop_timer(timer); hasganao = 292.5; } redraw = true; } else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[KEY_UP] = true; break; case ALLEGRO_KEY_DOWN: key[KEY_DOWN] = true; break; case ALLEGRO_KEY_LEFT: key[KEY_LEFT] = true; break; case ALLEGRO_KEY_RIGHT: key[KEY_RIGHT] = true; break; case ALLEGRO_KEY_SPACE: key[KEY_SPACE] = true; break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[KEY_UP] = false; break; case ALLEGRO_KEY_DOWN: key[KEY_DOWN] = false; break; case ALLEGRO_KEY_LEFT: key[KEY_LEFT] = false; break; case ALLEGRO_KEY_RIGHT: key[KEY_RIGHT] = false; break; case ALLEGRO_KEY_SPACE: key[KEY_SPACE] = false; break; case ALLEGRO_KEY_ESCAPE: doexit = true; break; } } if (redraw && al_is_event_queue_empty(event_queue)) { redraw = false; al_clear_to_color(al_map_rgb(10, 10, 10)); al_draw_bitmap(carretera, 640 - camaraX, carreteray, 0); al_draw_bitmap(carretera, 640 - camaraX, carreteray2, 0); al_draw_bitmap(tierra, 640 - camaraX, 0, 0); al_draw_filled_triangle(820 - camaraX, 720, 775 - camaraX, 400, carreterax1, 400, al_map_rgb(0, 0, 0)); al_draw_filled_triangle(1320 - camaraX, 720, 1365 - camaraX, 400, carreterax2, 400, al_map_rgb(0, 0, 0)); al_draw_line(820 - camaraX, 720, carreterax1, 400, al_map_rgb(0, 255, 255), 6); al_draw_line(1320 - camaraX, 720, carreterax2, 400, al_map_rgb(0, 255, 255), 6); al_draw_line(640 - camaraX, 425, carreterax1 - 4, 425, al_map_rgb(0, 255, 255), 10); al_draw_line(1485 - camaraX, 425, carreterax2 + 4, 425, al_map_rgb(0, 255, 255), 10); al_draw_bitmap(porche1, trafico1.traficox - camaraX, trafico1.traficoy, 0); al_draw_bitmap(porche2, trafico2.traficox - camaraX, trafico2.traficoy, 0); al_draw_bitmap(porche3, trafico3.traficox - camaraX, trafico3.traficoy, 0); al_draw_bitmap(porche4, trafico4.traficox - camaraX, trafico4.traficoy, 0); al_draw_bitmap(porche5, trafico5.traficox - camaraX, trafico5.traficoy, 0); al_draw_bitmap(porche6, trafico6.traficox - camaraX, trafico6.traficoy, 0); al_draw_bitmap(fondo, 640 - camaraX, 5, 0); al_draw_bitmap(ciudad, 640 - camaraX, 65, 0); al_draw_bitmap(pared2, 1485 - camaraX, 0, 0); al_draw_bitmap(pared2, 630 - camaraX, 0, 0); al_draw_bitmap(coche2, SCREEN_W / 2, bouncer_y - 10, 0); al_draw_bitmap(freno, frenosi, bouncer_y - 10, 0); al_draw_textf(font, al_map_rgb(255, 0, 0), SCREEN_W / 2 + 200, 50, 0, "%i", objetivo / 2); al_draw_textf(font, al_map_rgb(0, 255, 255), SCREEN_W / 2, 50, 0, "%i", tiempo / 60); al_draw_bitmap(ganas, hasganao, 200, 0); al_draw_bitmap(pierdes, hasperdio, 200, 0); al_flip_display(); } } al_destroy_bitmap(fondo); al_destroy_bitmap(coche); al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; }
int main(int argc, char **argv) { ALLEGRO_TIMER *timer; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_MONITOR_INFO info; const char* bitmap_filename; int w = 640, h = 480; bool done = false; bool need_redraw = true; bool background = false; example.show_help = true; example.hold_bitmap_drawing = false; if (argc > 1) { bitmap_filename = argv[1]; } else { bitmap_filename = "data/mysha256x256.png"; } if (!al_init()) { abort_example("Failed to init Allegro.\n"); } if (!al_init_image_addon()) { abort_example("Failed to init IIO addon.\n"); } al_init_font_addon(); init_platform_specific(); al_get_num_video_adapters(); al_get_monitor_info(0, &info); al_set_new_display_option(ALLEGRO_SUPPORTED_ORIENTATIONS, ALLEGRO_DISPLAY_ORIENTATION_ALL, ALLEGRO_SUGGEST); example.display = al_create_display(w, h); if (!example.display) { abort_example("Error creating display.\n"); } w = al_get_display_width(example.display); h = al_get_display_height(example.display); if (!al_install_keyboard()) { abort_example("Error installing keyboard.\n"); } if (!al_install_mouse()) { abort_example("Error installing mouse.\n"); } al_install_touch_input(); example.font = al_create_builtin_font(); if (!example.font) { abort_example("Error creating builtin font\n"); } example.mysha = al_load_bitmap(bitmap_filename); if (!example.mysha) { abort_example("Error loading %s\n", bitmap_filename); } example.white = al_map_rgb_f(1, 1, 1); example.half_white = al_map_rgba_f(1, 1, 1, 0.5); example.dark = al_map_rgb(15, 15, 15); example.red = al_map_rgb_f(1, 0.2, 0.1); change_size(256); add_sprite(); add_sprite(); timer = al_create_timer(1.0 / FPS); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); if (al_install_touch_input()) al_register_event_source(queue, al_get_touch_input_event_source()); al_register_event_source(queue, al_get_display_event_source(example.display)); al_start_timer(timer); while (!done) { float x, y; ALLEGRO_EVENT event; w = al_get_display_width(example.display); h = al_get_display_height(example.display); if (!background && need_redraw && al_is_event_queue_empty(queue)) { double t = -al_get_time(); add_time(); al_clear_to_color(al_map_rgb_f(0, 0, 0)); redraw(); t += al_get_time(); example.direct_speed_measure = t; al_flip_display(); need_redraw = false; } al_wait_for_event(queue, &event); switch (event.type) { case ALLEGRO_EVENT_KEY_CHAR: /* includes repeats */ if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) done = true; else if (event.keyboard.keycode == ALLEGRO_KEY_UP) { add_sprites(1); } else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) { remove_sprites(1); } else if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) { change_size(example.bitmap_size - 1); } else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) { change_size(example.bitmap_size + 1); } else if (event.keyboard.keycode == ALLEGRO_KEY_F1) { example.show_help ^= 1; } else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) { example.use_memory_bitmaps ^= 1; change_size(example.bitmap_size); } else if (event.keyboard.keycode == ALLEGRO_KEY_B) { example.blending++; if (example.blending == 5) example.blending = 0; } else if (event.keyboard.keycode == ALLEGRO_KEY_H) { example.hold_bitmap_drawing ^= 1; } break; case ALLEGRO_EVENT_DISPLAY_CLOSE: done = true; break; case ALLEGRO_EVENT_DISPLAY_HALT_DRAWING: background = true; al_acknowledge_drawing_halt(event.display.source); break; case ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING: background = false; al_acknowledge_drawing_resume(event.display.source); break; case ALLEGRO_EVENT_DISPLAY_RESIZE: al_acknowledge_resize(event.display.source); break; case ALLEGRO_EVENT_TIMER: update(); need_redraw = true; break; case ALLEGRO_EVENT_TOUCH_BEGIN: x = event.touch.x; y = event.touch.y; goto click; case ALLEGRO_EVENT_MOUSE_BUTTON_UP: x = event.mouse.x; y = event.mouse.y; goto click; click: { int fh = al_get_font_line_height(example.font); if (x < fh * 12 && y >= h - fh * 30) { int button = (y - (h - fh * 30)) / (fh * 6); if (button == 0) { example.use_memory_bitmaps ^= 1; change_size(example.bitmap_size); } if (button == 1) { example.blending++; if (example.blending == 5) example.blending = 0; } if (button == 3) { if (x < fh * 6) remove_sprites(example.sprite_count / 2); else add_sprites(example.sprite_count); } if (button == 2) { int s = example.bitmap_size * 2; if (x < fh * 6) s = example.bitmap_size / 2; change_size(s); } if (button == 4) { example.show_help ^= 1; } } break; } } } al_destroy_bitmap(example.bitmap); return 0; }
int main(void) { bool done =false; bool redraw = true; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_TIMER *timer =NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; SpaceShip ship; Bullet bullet[num_bullets]; Commet commet[num_commets]; if(!al_init()) { fprintf(stderr,"allegro is not intialized"); return -1; } display = al_create_display(SCREEN_W,SCREEN_H); if(!display) { fprintf(stderr,"failed to intialize the display"); return -1; } timer = al_create_timer(1.0/FPS); if(!timer) { fprintf(stderr,"failed to intialize timer"); al_destroy_display(display); return -1; } event_queue = al_create_event_queue(); if(!event_queue) { fprintf(stderr,"failed to create event queue"); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_install_keyboard(); al_register_event_source(event_queue,al_get_timer_event_source(timer)); al_register_event_source(event_queue,al_get_keyboard_event_source()); al_register_event_source(event_queue,al_get_display_event_source(display)); init_ship(&ship); init_bullet(&bullet); init_commet(&commet); al_start_timer(timer); while(!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue,&ev); if(ev.type == ALLEGRO_EVENT_TIMER) { if(keys[KEY_UP]) { move_ship_up(&ship); } if(keys[KEY_DOWN]) { move_ship_down(&ship); }if(keys[KEY_LEFT]) { move_ship_left(&ship); } if(keys[KEY_RIGHT]) { move_ship_right(&ship); } if(keys[KEY_SPACEBAR]) { fire_bullet(&bullet,&ship); } if(!GameOver) { update_bullet(&bullet); update_commet(&commet); bullet_collision(&bullet,&commet); } redraw = true; } else if(ev.type==ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: { keys[KEY_UP]=true; break; } case ALLEGRO_KEY_DOWN: { keys[KEY_DOWN]=true; break; } case ALLEGRO_KEY_LEFT: { keys[KEY_LEFT]=true; break; } case ALLEGRO_KEY_RIGHT : { keys[KEY_RIGHT]=true; break; } case ALLEGRO_KEY_SPACE: { keys[KEY_SPACEBAR] = true; break; } } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_UP: { keys[KEY_UP]=false; break; } case ALLEGRO_KEY_DOWN: { keys[KEY_DOWN]=false; break; } case ALLEGRO_KEY_LEFT: { keys[KEY_LEFT]=false; break; } case ALLEGRO_KEY_RIGHT : { keys[KEY_RIGHT]=false; break; } case ALLEGRO_KEY_SPACE: { keys[KEY_SPACEBAR]=false; break; } } } if(redraw && al_event_queue_is_empty(event_queue)) { redraw = false ; al_clear_to_color(al_map_rgb(255,100,100)); draw_ship(&ship); draw_bullet(bullet); draw_commet(commet); al_flip_display(); al_clear_to_color(al_map_rgb(255,100,100)); } } al_destroy_display(display); al_destroy_timer(timer); al_destroy_event_queue(event_queue); return 0; }
int main(int argc, char **argv) { ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; bool redraw = true; bool doexit = false; bool key[4] = { false, false, false, false }; if (!al_init()) { fprintf(stderr, "failed to initialize allegro!\n"); return -1; } if (!al_init_image_addon()) { al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!", NULL, ALLEGRO_MESSAGEBOX_ERROR); return 0; } if (!al_install_keyboard()) { fprintf(stderr, "failed to initialize the keyboard!\n"); return -1; } collider collide; std::vector<bouncer *> balls; std::vector<tile*> tiles; std::vector<move *> moveVector; ALLEGRO_BITMAP *image = NULL; image = al_load_bitmap("megamanss.png"); if (!image) { al_show_native_message_box(display, "Error", "Error", "Failed to load image!", NULL, NULL); al_destroy_display(display); return 0; } for (int i = 0; i < NUM_BALLS; i++) { bouncer* a; a = new bouncer(30 * i, 30 * i, 10, i / 5.0, i); balls.push_back(a); // collide.add(a); } for (int i = 0; i < NUM_TILES; i++) { tile * a; // std::cout << i%16 << "\t" << i/12 << "\n"; a = new tile(TILE_SIZE * (i % 16), TILE_SIZE * (i / 16), TILE_SIZE); tiles.push_back(a); // collide.add(a); } animator *anim = new animator("megamanss.png", "Source/megamanss.txt"); //ballGenerator *bg = new ballGenerator(100,100,&collide,&balls); //PokemonFactory pf; pokemon * p = new pokemon("treeko", 1, 2, 3, 4); MoveFactory *mf = new MoveFactory(); move *m = mf->Create(SWAG, "swag", p, p, 0, 400, 200); moveVector.push_back(m); collide.add(p); collide.add(m); // bouncer b(20,20,32,3,4); // bouncer c(30,30,32,4,4); timer = al_create_timer(1.0 / FPS); if (!timer) { fprintf(stderr, "failed to create timer!\n"); return -1; } display = al_create_display(SCREEN_W, SCREEN_H); if (!display) { fprintf(stderr, "failed to create display!\n"); al_destroy_timer(timer); return -1; } al_set_target_bitmap(al_get_backbuffer(display)); event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "failed to create event_queue!\n"); al_destroy_display(display); al_destroy_timer(timer); return -1; } al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_clear_to_color(al_map_rgb(0, 0, 0)); al_flip_display(); al_start_timer(timer); std::cout << "\nDONE WITH INIT\n"; while (!doexit) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if (ev.type == ALLEGRO_EVENT_TIMER) { collide.update(); anim->update(); for (int i = 0; i < moveVector.size(); i++) { std::cout << "moveVector.size()" << moveVector.size() << "\n"; if (moveVector[i]->markForDeath == true) { delete moveVector[i]; moveVector.erase(moveVector.begin() + i); i--; } else { moveVector[i]->update(); } } /* if (m != NULL && m->markForDeath == true) { std::cout << "deleting object"; delete m; m = NULL; } else if (m!= NULL) m->update(); */ for (int i = 0; i < balls.size(); i++) { if (balls[i]->markForDeath == true) { collide.remove(balls[i]); delete balls[i]; balls.erase(balls.begin() + i); i--; } else { balls[i]->update(); } } if (key[KEY_UP]) { anim->switchAnimations(1); } if (key[KEY_DOWN]) { anim->switchAnimations(2); } if (key[KEY_LEFT]) { anim->switchAnimations(3); } if (key[KEY_RIGHT]) { anim->switchAnimations(4); } // for (int i = 0; i < tiles.size(); i++) // tiles[i]->update(); p->update(); //bg->update(); redraw = true; } else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[KEY_UP] = true; break; case ALLEGRO_KEY_DOWN: key[KEY_DOWN] = true; break; case ALLEGRO_KEY_LEFT: key[KEY_LEFT] = true; break; case ALLEGRO_KEY_RIGHT: key[KEY_RIGHT] = true; break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) { switch (ev.keyboard.keycode) { case ALLEGRO_KEY_UP: key[KEY_UP] = false; break; case ALLEGRO_KEY_DOWN: key[KEY_DOWN] = false; break; case ALLEGRO_KEY_LEFT: key[KEY_LEFT] = false; break; case ALLEGRO_KEY_RIGHT: key[KEY_RIGHT] = false; break; case ALLEGRO_KEY_ESCAPE: doexit = true; break; } } if (redraw && al_is_event_queue_empty(event_queue)) { redraw = false; al_set_target_bitmap(al_get_backbuffer(display)); al_clear_to_color(al_map_rgb(0, 0, 0)); // al_draw_bitmap(image,200,200,0); for (int i = 0; i < moveVector.size(); i++) moveVector[i]->draw(); /* for (int i = 0; i < tiles.size(); i++) tiles[i]->draw(); for (int i = 0; i < balls.size(); i++) balls[i]->draw();*/ anim->draw(100, 100); p->draw(); al_flip_display(); } } for (int i = 0; i < tiles.size(); i++) delete tiles[i]; for (int i = 0; i < balls.size(); i++) delete balls[i]; al_destroy_timer(timer); al_destroy_display(display); al_destroy_event_queue(event_queue); return 0; }
int main(int argc, char **argv) { ALLEGRO_DISPLAY *display; ALLEGRO_BITMAP *bitmap; ALLEGRO_EVENT_QUEUE *events; ALLEGRO_EVENT event; bool down = false; int down_x = 0, down_y = 0; ALLEGRO_TIMER *timer; (void)argc; (void)argv; if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_install_mouse(); al_install_keyboard(); al_init_image_addon(); init_platform_specific(); al_set_new_display_flags(ALLEGRO_FRAMELESS); display = al_create_display(300, 200); if (!display) { abort_example("Error creating display\n"); } bitmap = al_load_bitmap("data/fakeamp.bmp"); if (!bitmap) { abort_example("Error loading fakeamp.bmp\n"); } timer = al_create_timer(1.0f/30.0f); events = al_create_event_queue(); al_register_event_source(events, al_get_mouse_event_source()); al_register_event_source(events, al_get_keyboard_event_source()); al_register_event_source(events, al_get_display_event_source(display)); al_register_event_source(events, al_get_timer_event_source(timer)); al_start_timer(timer); for (;;) { al_wait_for_event(events, &event); if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (event.mouse.button == 1 && event.mouse.x) { down = true; down_x = event.mouse.x; down_y = event.mouse.y; } if (event.mouse.button == 2) { al_set_display_flag(display, ALLEGRO_FRAMELESS, !(al_get_display_flags(display) & ALLEGRO_FRAMELESS)); } } else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { if (event.mouse.button == 1) { down = false; } } else if (event.type == ALLEGRO_EVENT_MOUSE_AXES) { if (down) { int cx, cy; if (al_get_mouse_cursor_position(&cx, &cy)) { al_set_window_position(display, cx - down_x, cy - down_y); } } } else if (event.type == ALLEGRO_EVENT_KEY_DOWN && event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } else if (event.type == ALLEGRO_EVENT_TIMER) { al_draw_bitmap(bitmap, 0, 0, 0); al_flip_display(); } } al_destroy_timer(timer); al_destroy_event_queue(events); al_destroy_display(display); return 0; }
int main(int argc, char **argv) { int num_touches = 0; TOUCH touches[MAX_TOUCHES]; ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_EVENT event; (void)argc; (void)argv; if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_init_primitives_addon(); if (!al_install_touch_input()) { abort_example("Could not init touch input.\n"); } display = al_create_display(800, 600); if (!display) { abort_example("Error creating display\n"); } queue = al_create_event_queue(); al_register_event_source(queue, al_get_touch_input_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); while (true) { if (al_is_event_queue_empty(queue)) { al_clear_to_color(al_map_rgb(255, 255, 255)); draw_touches(num_touches, touches); al_flip_display(); } al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (event.type == ALLEGRO_EVENT_TOUCH_BEGIN) { int i = num_touches; if (num_touches < MAX_TOUCHES) { touches[i].id = event.touch.id; touches[i].x = event.touch.x; touches[i].y = event.touch.y; num_touches++; } } else if (event.type == ALLEGRO_EVENT_TOUCH_END) { int i = find_index(event.touch.id, num_touches, touches); if (i >= 0 && i < num_touches) { touches[i] = touches[num_touches - 1]; num_touches--; } } else if (event.type == ALLEGRO_EVENT_TOUCH_MOVE) { int i = find_index(event.touch.id, num_touches, touches); if (i >= 0) { touches[i].x = event.touch.x; touches[i].y = event.touch.y; } } } return 0; }
void game_loop(void) { //load font ALLEGRO_FONT *font = al_load_ttf_font("RobotoMono-Medium.ttf",12,0); //create floor array (will eventually make this a function) srand(time(NULL)); for (int x = 0; x < 16; x++) { //for each y value between 2 and 13 for (int y = 0; y < 16; y++) { randX = 6 + (rand() % (int)(12 - 6 + 1)); randY = 0 + (rand() % (int)(3 - 0 + 1)); //drawDungeonTile(randX, randY, x, y); floorArray [x] [y] [0] = randX; floorArray [x] [y] [1] = randY; } } Player p1; //(speed, friction, sprint accel, max speed) //default: p1.setMovement(1.4, .4, 1.8, 4); p1.setMovement(1.4, .4, 1.8, 3); p1.setPosition(tileSize * 7, tileSize * 12); p1.setCurrentRoom(111); p1.setInitial(tileSize,tileSize,240,240); p1.setH(tileSize); p1.setW(tileSize); p1.setAnimation(tileSize * 0, tileSize * 0,0,0,9,4,0); p1.canMove = true; p1.vincible = true; p1.blinking = false; p1.blinkTimer = 5; int tempBlinkTimer = p1.blinkTimer; p1.knockback = 0; p1.knockbackTimer = 0; p1.setBound(19,27,7,3, 14,8,9,24); //p1.setX(240); //p1.setY(240); p1.leavingTransport = 0; //init player prototypes void movePlayerUp(Player &p); void movePlayerDown(Player &p); void movePlayerLeft(Player &p); void movePlayerRight(Player &p); void sprintPlayer(Player &p); void maxSpeedPlayer(Player &p); void maxWalkSpeedPlayer(Player &p); void updatePlayer(Player &p); void collidePlayerWallX(Player &p, int obstacles [16][16]); void collidePlayerWallY(Player &p, int obstacles [16][16]); void collidePlayerMonster(Player &p, Monster m[]); void drawPlayer(Player &p); void resetPlayerAnimation(Player &p); //load current room map Room currentRoom; currentRoom.getRoom(p1.getCurrentRoom()); //load all objects objectArray currentArray; currentArray.getObjects(p1.getCurrentRoom()); //load current room transporters Transporter currentTrans; currentTrans.exitNumber = 0; //init monsters prototypes Monster currentMonsters[numMonsters]; getMonsters(currentMonsters, currentArray.array); void getMonsters (Monster m[], int array[][16]); void drawMonsters (Monster m[]); void collideMonsterWallX(Monster m[], int obstacles [16][16]); void collideMonsterWallY(Monster m[], int obstacles [16][16]); void updateMonstersX (Monster currentMonsters[]); void updateMonstersY (Monster currentMonsters[]); void seekMonsters (Monster m[], Player p); int monsterDebug = 1; //load current room's monsters //currentMonsters.getObjects(p1.getCurrentRoom()); int vincibleTimer = 0; bool showHitboxes = false; al_start_timer(timer); while (!done) { ALLEGRO_EVENT event; al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_TIMER) { if(key[keyW]) { movePlayerUp(p1); } else if(key[keyS]) { movePlayerDown(p1); } if(key[keyA]) { movePlayerLeft(p1); } else if(key[keyD]) { movePlayerRight(p1); } if(!(key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) { resetPlayerAnimation(p1); } if(key[keyShift] && (key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) { sprintPlayer(p1); maxSpeedPlayer(p1); } else { maxWalkSpeedPlayer(p1); } //Monster movement and wall collisions seekMonsters(currentMonsters,p1); updateMonstersX(currentMonsters); collideMonsterWallX(currentMonsters,currentRoom.array); updateMonstersY(currentMonsters); collideMonsterWallY(currentMonsters,currentRoom.array); redraw = true; //update player position p1.setX(p1.getX() + p1.getDx()); collidePlayerMonster(p1,currentMonsters); //printf("player DX: %f\n",p1.getDx()); //printf("player DY: %f\n",p1.getDy()); //X axis //detect and respond to collision with obstacles collidePlayerWallX(p1,currentRoom.array); if(p1.canMove) { p1.setDx(p1.getDx() * p1.getFriction()); } //knockback timer //Y axis p1.setY(p1.getY() + p1.getDy()); collidePlayerWallY(p1,currentRoom.array); p1.setDy(p1.getDy() * p1.getFriction()); //if able to transport if (p1.leavingTransport == 0) { //check for collisions with transporter currentTrans.exitNumber = currentTrans.playerTransCollision(p1.getX(), p1.getY(),currentArray.array); if (currentTrans.exitNumber) { currentTrans.fromNumber = p1.getCurrentRoom(); p1.leavingTransport = 1; } } //if transporting if ( p1.leavingTransport == 1) { //set room to move to p1.setCurrentRoom(currentTrans.exitNumber); currentRoom.getRoom(p1.getCurrentRoom()); currentArray.getObjects(p1.getCurrentRoom()); getMonsters(currentMonsters, currentArray.array); //must set player's location to the location of the exit portal in the new room currentTrans.getDestination(currentArray.array); p1.setX(currentTrans.destination[0] + tileSize/2); p1.setY(currentTrans.destination[1] + tileSize/2); currentTrans.destination[0] = 0; currentTrans.destination[1] = 0; p1.leavingTransport = 0; } //functions for drawing the player (will need to go elsewhere eventually) //invincible timer if (p1.vincible == false) { vincibleTimer ++; tempBlinkTimer --; p1.blinking = true; //printf("p1 blinking? %d, %d\n",p1.blinking, tempBlinkTimer); if (tempBlinkTimer < 0) { p1.blinking = false; if ( tempBlinkTimer == p1.blinkTimer * (-3)) { tempBlinkTimer = p1.blinkTimer; } } if (vincibleTimer == invincibleTime) { p1.vincible = true; p1.blinking = false; vincibleTimer = 0; //printf ("vincible Again \n"); } } //animation frame counter redraw = true; } //key pressed down else if (event.type == ALLEGRO_EVENT_KEY_DOWN) { switch (event.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; case ALLEGRO_KEY_W: key[keyW] = true; break; case ALLEGRO_KEY_A: key[keyA] = true; break; case ALLEGRO_KEY_S: key[keyS] = true; break; case ALLEGRO_KEY_D: key[keyD] = true; break; case ALLEGRO_KEY_LSHIFT: key[keyShift] = true; break; } } //key released else if (event.type == ALLEGRO_EVENT_KEY_UP) { switch (event.keyboard.keycode) { case ALLEGRO_KEY_W: key[keyW] = false; break; case ALLEGRO_KEY_A: key[keyA] = false; break; case ALLEGRO_KEY_S: key[keyS] = false; break; case ALLEGRO_KEY_D: key[keyD] = false; break; case ALLEGRO_KEY_LSHIFT: key[keyShift] = false; break; } } else if(event.type == ALLEGRO_EVENT_MOUSE_AXES || ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY) { crosshair_x = event.mouse.x - crosshairSize/2; crosshair_y = event.mouse.y - crosshairSize/2; } if (redraw && al_is_event_queue_empty(event_queue)) { redraw = false; //Clear screen to green al_clear_to_color(al_map_rgb(0, 0, 0)); //update_graphics(); //graphics that will always be there drawDungeon(floorArray,currentRoom.array); if (transDebug) currentTrans.drawTransporters(currentArray.array); drawMonsters(currentMonsters); //Monster debug hitbox if (showHitboxes) { for (int i = 0; i < numMonsters; i ++) { if (currentMonsters[i].isLive == 1) { //al_draw_rectangle(BBBitmap, currentMonsters[i].getX() + currentMonsters[i].getBoundOffsetW(), currentMonsters[i].getY() + currentMonsters[i].getBoundOffsetH(), 0); al_draw_rectangle(currentMonsters[i].getX() + currentMonsters[i].getBoundOffsetW(), currentMonsters[i].getY() + currentMonsters[i].getBoundOffsetH(), currentMonsters[i].getX() + currentMonsters[i].getBoundOffsetW() + currentMonsters[i].getBoundW(), currentMonsters[i].getY() + currentMonsters[i].getBoundOffsetH() + currentMonsters[i].getBoundH(), al_map_rgb(255,0,0),1); al_draw_rectangle(currentMonsters[i].getX() + currentMonsters[i].getWallOffsetW(), currentMonsters[i].getY() + currentMonsters[i].getWallOffsetH(), currentMonsters[i].getX() + currentMonsters[i].getWallOffsetW() + currentMonsters[i].getWallW(), currentMonsters[i].getY() + currentMonsters[i].getWallOffsetH() + currentMonsters[i].getWallH(), al_map_rgb(0,255,0),1); } } } if (p1.blinking == false) { drawPlayer(p1); } //player debug hitbox if (showHitboxes) { al_draw_rectangle(p1.getX() + p1.getBoundOffsetW(), p1.getY() + p1.getBoundOffsetH(), p1.getX() + p1.getBoundOffsetW() + p1.getBoundW(), p1.getY() + p1.getBoundOffsetH() + p1.getBoundH(), al_map_rgb(255,0,0),1); al_draw_rectangle(p1.getX() + p1.getWallOffsetW(), p1.getY() + p1.getWallOffsetH(), p1.getX() + p1.getWallOffsetW() + p1.getWallW(), p1.getY() + p1.getWallOffsetH() + p1.getWallH(), al_map_rgb(0,255,0),1); } al_draw_text(font, al_map_rgb(255,255,255),0,tileSize*15,ALLEGRO_ALIGN_LEFT,"TEXT!"); //al_draw_bitmap(crosshair, crosshair_x, crosshair_y, 0); al_flip_display(); } } }
int main(int argc, const char *argv[]) { ALLEGRO_SAMPLE *sample_data[MAX_SAMPLE_DATA] = {NULL}; ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue; ALLEGRO_EVENT event; int i; if (!al_init()) { abort_example("Could not init Allegro.\n"); } open_log(); if (argc < 2) { log_printf("This example needs to be run from the command line.\nUsage: %s {audio_files}\n", argv[0]); goto done; } argc--; argv++; al_install_keyboard(); display = al_create_display(640, 480); if (!display) { abort_example("Could not create display\n"); } event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_init_acodec_addon(); Restart: if (!al_install_audio()) { abort_example("Could not init sound!\n"); } if (!al_reserve_samples(RESERVED_SAMPLES)) { abort_example("Could not set up voice and mixer.\n"); } memset(sample_data, 0, sizeof(sample_data)); for (i = 0; i < argc && i < MAX_SAMPLE_DATA; i++) { const char *filename = argv[i]; /* Load the entire sound file from disk. */ sample_data[i] = al_load_sample(argv[i]); if (!sample_data[i]) { log_printf("Could not load sample from '%s'!\n", filename); continue; } } log_printf("Press digits to play sounds, space to stop sounds, " "Escape to quit.\n"); while (true) { al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_KEY_CHAR) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } if (event.keyboard.unichar == ' ') { al_stop_samples(); } if (event.keyboard.unichar >= '0' && event.keyboard.unichar <= '9') { i = (event.keyboard.unichar - '0' + 9) % 10; if (sample_data[i]) { log_printf("Playing %d\n",i); if (!al_play_sample(sample_data[i], 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_LOOP, NULL)) { log_printf( "al_play_sample_data failed, perhaps too many sounds\n"); } } } /* Hidden feature: restart audio subsystem. * For debugging race conditions on shutting down the audio. */ if (event.keyboard.unichar == 'r') { al_uninstall_audio(); goto Restart; } } } /* Sample data and other objects will be automatically freed. */ al_uninstall_audio(); done: al_destroy_display(display); close_log(true); return 0; }
int main(void) { ALLEGRO_DISPLAY *display, *ms_display; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_TIMER *timer; ALLEGRO_BITMAP *memory; char title[1024]; bool quit = false; bool redraw = true; int wx, wy; if (!al_init()) { abort_example("Couldn't initialise Allegro.\n"); } al_init_primitives_addon(); al_install_keyboard(); al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP); memory = create_bitmap(); /* Create the normal display. */ al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 0, ALLEGRO_REQUIRE); al_set_new_display_option(ALLEGRO_SAMPLES, 0, ALLEGRO_SUGGEST); display = al_create_display(300, 450); if (!display) { abort_example("Error creating display\n"); } al_set_window_title(display, "Normal"); /* Create bitmaps for the normal display. */ al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); bitmap_filter = al_clone_bitmap(memory); al_set_new_bitmap_flags(0); bitmap_normal = al_clone_bitmap(memory); font = al_create_builtin_font(); al_get_window_position(display, &wx, &wy); if (wx < 160) wx = 160; /* Create the multi-sampling display. */ al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_REQUIRE); al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST); ms_display = al_create_display(300, 450); if (!ms_display) { abort_example("Multisampling not available.\n"); } sprintf(title, "Multisampling (%dx)", al_get_display_option( ms_display, ALLEGRO_SAMPLES)); al_set_window_title(ms_display, title); /* Create bitmaps for the multi-sampling display. */ al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR); bitmap_filter_ms = al_clone_bitmap(memory); al_set_new_bitmap_flags(0); bitmap_normal_ms = al_clone_bitmap(memory); font_ms = al_create_builtin_font(); /* Move the windows next to each other, because some window manager * would put them on top of each other otherwise. */ al_set_window_position(display, wx - 160, wy); al_set_window_position(ms_display, wx + 160, wy); timer = al_create_timer(1.0 / 30.0); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_display_event_source(ms_display)); al_register_event_source(queue, al_get_timer_event_source(timer)); al_start_timer(timer); while (!quit) { ALLEGRO_EVENT event; /* Check for ESC key or close button event and quit in either case. */ al_wait_for_event(queue, &event); switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: quit = true; break; case ALLEGRO_EVENT_KEY_DOWN: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) quit = true; break; case ALLEGRO_EVENT_TIMER: bitmap_move(); redraw = true; break; } if (redraw && al_is_event_queue_empty(queue)) { /* Draw the multi-sampled version into the first window. */ al_set_target_backbuffer(ms_display); al_clear_to_color(al_map_rgb_f(1, 1, 1)); draw(bitmap_filter_ms, 0, "filtered, multi-sample"); draw(bitmap_normal_ms, 250, "no filter, multi-sample"); al_flip_display(); /* Draw the normal version into the second window. */ al_set_target_backbuffer(display); al_clear_to_color(al_map_rgb_f(1, 1, 1)); draw(bitmap_filter, 0, "filtered"); draw(bitmap_normal, 250, "no filter"); al_flip_display(); redraw = false; } } return 0; }
void corrermusica(void){ const int CANTICANCIONES=5; ALLEGRO_TIMER *timer = NULL; ALLEGRO_EVENT_QUEUE *queue=NULL; ALLEGRO_BITMAP *icons[CANTICANCIONES]; boton items[CANTICANCIONES]; void (*p2buttonf[CANTICANCIONES])(void); ALLEGRO_FONT *font=NULL; queue = al_create_event_queue(); timer = al_create_timer(1.0/FPS); //genero un timer para trabajar en 60 fps bool redraw=false; //pajaros icons[0]=al_load_bitmap("pajaros.png"); botones(&items[0],30,70, 150, 200); p2buttonf[0]=pajaros; //clorofila icons[1]=al_load_bitmap("clorofila.png"); botones(&items[1],230,70, 150, 200); p2buttonf[1]=clorofila; //brisa icons[2]=al_load_bitmap("brisa.png"); botones(&items[2],30,330, 150, 200); p2buttonf[2]=brisa; //alfred icons[3]=al_load_bitmap("graciasalfred.png"); botones(&items[3],230,330, 150, 200); p2buttonf[3]=graciasalfred; //mute icons[4]=al_load_bitmap("mute.png"); botones(&items[4],340,OFFSETDOWN-70, 64, 64); p2buttonf[4]=mute; //font font=al_load_font("font.ttf",30,0); //register events al_register_event_source(queue, al_get_display_event_source(display)); al_register_event_source(queue, al_get_mouse_event_source()); al_register_event_source(queue, al_get_timer_event_source(timer)); //timer starts al_start_timer(timer); while(!doexit && !exitmenu) // loop { ALLEGRO_EVENT ev; al_wait_for_event(queue, &ev); // espero a timer, salida o keyboard if(ev.type == ALLEGRO_EVENT_TIMER) redraw = true; // si es el timer de refresco, redibujo salio(ev); inicio(ev); presionobotones(ev, items, p2buttonf,CANTICANCIONES); if(redraw && !exitmenu){ // si hay que redibujar drawfondo(); al_draw_text(font, al_map_rgb(171,130,255), 10, OFFSETDOWN-55, ALLEGRO_ALIGN_LEFT,"Musica por Motoneta"); drawbotones(items, icons,CANTICANCIONES); redraw=false; al_flip_display(); //flipeo } } al_destroy_event_queue(queue); al_destroy_timer(timer); al_destroy_bitmap(icons[0]); al_destroy_bitmap(icons[1]); al_destroy_bitmap(icons[2]); al_destroy_bitmap(icons[3]); exitmenu=false; }
int main(void) { //primitive variable bool done = false; bool redraw = true; const int FPS = 60; bool isGameOver = false; //object variables SpaceShip ship; Bullet bullets[NUM_BULLETS]; Comet comets[NUM_COMETS]; //Allegro variables ALLEGRO_DISPLAY *display = NULL; ALLEGRO_EVENT_QUEUE *event_queue = NULL; ALLEGRO_TIMER *timer = NULL; ALLEGRO_FONT *font18 = NULL; //Initialization Functions if(!al_init()) //initialize Allegro return -1; display = al_create_display(WIDTH, HEIGHT); //create our display object if(!display) //test display object return -1; al_init_primitives_addon(); al_install_keyboard(); al_init_font_addon(); al_init_ttf_addon(); event_queue = al_create_event_queue(); timer = al_create_timer(1.0 / FPS); srand(time(NULL)); InitShip(ship); InitBullet(bullets, NUM_BULLETS); InitComet(comets, NUM_COMETS); font18 = al_load_font("arial.ttf", 18, 0); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_display_event_source(display)); al_start_timer(timer); while(!done) { ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); if(ev.type == ALLEGRO_EVENT_TIMER) { redraw = true; if(keys[UP]) MoveShipUp(ship); if(keys[DOWN]) MoveShipDown(ship); if(keys[LEFT]) MoveShipLeft(ship); if(keys[RIGHT]) MoveShipRight(ship); if(!isGameOver) { UpdateBullet(bullets, NUM_BULLETS); StartComet(comets, NUM_COMETS); UpdateComet(comets, NUM_COMETS); CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship); CollideComet(comets, NUM_COMETS, ship); if(ship.lives <= 0) isGameOver = true; } } else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { done = true; } else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = true; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = true; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = true; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = true; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = true; FireBullet(bullets, NUM_BULLETS, ship); break; } } else if(ev.type == ALLEGRO_EVENT_KEY_UP) { switch(ev.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: done = true; break; case ALLEGRO_KEY_UP: keys[UP] = false; break; case ALLEGRO_KEY_DOWN: keys[DOWN] = false; break; case ALLEGRO_KEY_LEFT: keys[LEFT] = false; break; case ALLEGRO_KEY_RIGHT: keys[RIGHT] = false; break; case ALLEGRO_KEY_SPACE: keys[SPACE] = false; break; } } if(redraw && al_is_event_queue_empty(event_queue)) { redraw = false; if(!isGameOver) { DrawShip(ship); DrawBullet(bullets, NUM_BULLETS); DrawComet(comets, NUM_COMETS); al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score); } else { al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score); } al_flip_display(); al_clear_to_color(al_map_rgb(0,0,0)); } } al_destroy_event_queue(event_queue); al_destroy_timer(timer); al_destroy_font(font18); al_destroy_display(display); //destroy our display object return 0; }
int main(int argc, char** argv) { int defw = 640; int defh = 480; if (argc == 3) { /*the program was run using 3 arguments argv[0] = name of the executable file argv[1] = screen width (as a string) argv[2] = screen height (as a string) */ defw = atoi(argv[1]); defh = atoi(argv[2]); } if (!al_init()) return 1; //exit if can't initialize allegro //initialize most stuff al_install_keyboard(); al_init_primitives_addon(); //run in a window al_set_new_display_flags(ALLEGRO_WINDOWED); //initialize our display and event queue ALLEGRO_DISPLAY* display = al_create_display(defw, defh); ALLEGRO_EVENT_QUEUE* eventq = al_create_event_queue(); //this timer will tick once per frame ALLEGRO_TIMER* framet = al_create_timer(1.0 / 30.0); //30 frames per second al_start_timer(framet); //register the event sources so they send events to our queue al_register_event_source(eventq, al_get_display_event_source(display)); //display/window al_register_event_source(eventq, al_get_keyboard_event_source()); //keyboard al_register_event_source(eventq, al_get_timer_event_source(framet)); //fps timer //this box is our play field (covers the whole screen) CBox fieldbox(0, 0, defw, defh); //we setup the ball at the center of the screen with white color CBall ball(CBox(defw / 2 - 10, defh / 2 - 10, 20, 20), al_map_rgb(255, 255, 255)); //we tell it to move to the left ball.setXYMovement(-5.0, 0.0); //we initialize our both players in an array CPlayer players[2] = { //red player on the left CPlayer(CBox(10, defh / 2 - 80 / 2, 20, 80), al_map_rgb(255, 0, 0)), //blue player on the right CPlayer(CBox(defw - 10 - 20, defh / 2 - 80 / 2, 20, 80), al_map_rgb(0, 0, 255)), }; /*when this variable is set to true the program will quit the main loop and free the allocated resources before quitting */ bool exit = false; while (!exit) { al_wait_for_event(eventq, NULL); ALLEGRO_EVENT ev; while (al_get_next_event(eventq, &ev)) { if (ev.type == ALLEGRO_EVENT_TIMER) { if (ev.timer.source == framet) { //fill the screen with black al_clear_to_color(al_map_rgb(0, 0, 0)); //move and draw our two players for (int i = 0; i<2; i++) { players[i].move(fieldbox); players[i].draw(); } //move, collide and draw the ball switch (ball.move(fieldbox, players)) { case 0: break; case 1: players[0].setScore(players[0].getScore() + 1); ball.setXYMovement(5.0, 0.0); break; case 2: players[1].setScore(players[1].getScore() + 1); ball.setXYMovement(-5.0, 0.0); break; } ball.draw(); //show what we've drawn al_flip_display(); } } else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { //quit if the user tries to close the window if (ev.display.source == display) exit = true; } else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) { //handle key presses switch (ev.keyboard.keycode) { case ALLEGRO_KEY_W: players[0].setYMovement(-3.0); break; case ALLEGRO_KEY_S: players[0].setYMovement(3.0); break; case ALLEGRO_KEY_UP: players[1].setYMovement(-3.0); break; case ALLEGRO_KEY_DOWN: players[1].setYMovement(3.0); break; case ALLEGRO_KEY_ESCAPE: exit = true; break; case ALLEGRO_EVENT_DISPLAY_CLOSE: exit = true; break; } } else if (ev.type == ALLEGRO_EVENT_KEY_UP) { int code = ev.keyboard.keycode; /*avoid clumsy movement making sure the released key corresponds with the moving direction*/ if (code == ALLEGRO_KEY_W && players[0].getYMovement() < 0) players[0].setYMovement(0.0); else if (code == ALLEGRO_KEY_S && players[0].getYMovement() > 0) players[0].setYMovement(0.0); else if (code == ALLEGRO_KEY_UP && players[1].getYMovement() < 0) players[1].setYMovement(0.0); else if (code == ALLEGRO_KEY_DOWN && players[1].getYMovement() > 0) players[1].setYMovement(0.0); } } } al_destroy_event_queue(eventq); al_destroy_timer(framet); al_destroy_display(display); }
int main() { const float FPS = 60.0; if(!al_init()) { al_show_native_message_box(NULL, "Fatal Error", NULL, "No se pudo inicializar Allegro", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } al_set_new_display_flags(ALLEGRO_WINDOWED); // Pone la ventana en modo Windowed ALLEGRO_DISPLAY *display = al_create_display(ScreenWidth, ScreenHeight); // Pone la posición en la que debe salir la ventana //al_set_window_position(display, 0, 30); // Pone el título de la ventana al_set_window_title(display, "Rabbit Kills Robots"); if(!display) // Si no se pudo crear la ventana, entonces pone un mensaje de error { al_show_native_message_box(NULL, "Error", NULL, "No se pudo crear la pantalla", NULL, ALLEGRO_MESSAGEBOX_ERROR); return -1; } al_install_keyboard(); al_install_mouse(); al_init_image_addon(); al_init_font_addon(); al_init_ttf_addon(); al_init_primitives_addon(); // ----------------------------------------------------------------- ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue(); ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS); ALLEGRO_KEYBOARD_STATE keyState; // Utilizado para debugging ALLEGRO_FONT *font = al_load_font("sprites/DroidSans.ttf", 10, 0); ALLEGRO_BITMAP *fondo1 = al_load_bitmap("sprites/fondo1.png"); bool done = false; // ---------Estructuras del juego----------------------------------- //~ struct Player //~ { //~ ALLEGRO_BITMAP *image; //~ float x; //~ float y; //~ float moveSpeed; //~ float degrees; //~ int clip; //~ bool alive; //~ float xmouse; //~ float ymouse; //~ }player; struct Player player; player.image = al_load_bitmap("sprites/player.png"); al_convert_mask_to_alpha(player.image, al_map_rgb(255,255,255)); player.x = ScreenWidth / 2; player.y = ScreenHeight / 2; player.w = al_get_bitmap_width(player.image); player.h = al_get_bitmap_height(player.image); player.moveSpeed = 3; player.degrees = -ALLEGRO_PI/2; player.alive = true; player.clip = 6; //~ struct Bala //~ { //~ ALLEGRO_BITMAP *image; //~ float x; //~ float y; //~ float dx; //~ float dy; //~ bool shot; //~ void update(); //~ }bala; struct Bala bala; //~ void Bala::update() //~ { //~ bala.dx = cosf(player.xmouse - player.x); //~ bala.dy = senf(player.ymouse - player.y); //~ //~ if(bala.shot){ //~ //~ bala.x += bala.dx; //~ bala.y += bala.dy; //~ } //~ //~ } bala.image = al_load_bitmap("sprites/bullet.png"); bala.x = player.x+50; bala.y = player.y+25; bala.shot = false; //~ struct Enemigo //~ { //~ ALLEGRO_BITMAP *image; //~ float x; //~ float y; //~ float velocidad_x; //~ float velocidad_y; //~ //float degrees; //~ }robot; struct Enemigo robot; robot.image = al_load_bitmap("sprites/Robot_sprites.png"); //al_convert_mask_to_alpha(robot.image, al_map_rgb(255,255,255)); robot.x = 50; robot.y = 50; robot.w = al_get_bitmap_width(robot.image); robot.h = al_get_bitmap_height(robot.image); robot.velocidad_x = 0.23; robot.velocidad_y = 0.23; //~ void Weapon::recargar() //~ { //~ for(int i = 0; i < 6; i++) //~ { //~ bullets[i] = bala; //~ } //~ } //~ struct Weapon //~ { //~ struct Bala bullets[player.clip]; //~ void recargar(); //~ }arma; //~ //~ void Weapon::recargar() //~ { //~ for(int i = 0; i < player.clip; i++) //~ { //~ bullets[i] = bala; //~ } //~ } //~ // ----------------------------------------------------------------- // Esta variable guardará los eventos del mouse ALLEGRO_MOUSE_STATE mouseState; // Registro varias fuentes de eventos al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_register_event_source(event_queue, al_get_mouse_event_source()); // Inicializo el temporizador principal al_start_timer(timer); while(!done) { // La variable de los eventos ALLEGRO_EVENT ev; al_wait_for_event(event_queue, &ev); // Y aquí espero por los eventos if(ev.type == ALLEGRO_EVENT_TIMER) { // Dos funciones para pasar eventos del mouse y del teclado al_get_keyboard_state(&keyState); al_get_mouse_state(&mouseState); // Esto detecta la posición del mouse y lo guarda a un par de variables player.xmouse = al_get_mouse_state_axis(&mouseState, 0); player.ymouse = al_get_mouse_state_axis(&mouseState, 1); // Si presiono Esc entonces me saca del juego if(al_key_down(&keyState, ALLEGRO_KEY_ESCAPE)) { done = true; } // Si presiono A entonces el valor x se reduce, osea, se va a la izquierda if(al_key_down(&keyState, ALLEGRO_KEY_A)) { player.x -= player.moveSpeed; } // Si... meh, ya sabes lo que sigue if(al_key_down(&keyState, ALLEGRO_KEY_D)) { player.x += player.moveSpeed; } // ... if(al_key_down(&keyState, ALLEGRO_KEY_W)) { player.y -= player.moveSpeed; } // ... if(al_key_down(&keyState, ALLEGRO_KEY_S)) { player.y += player.moveSpeed; } } // Esto permite que el jugador se mueva con el mouse player.degrees = atan2((player.ymouse-player.y),(player.xmouse-player.x)); // La Inteligencia Artificial del enemigo if(robot.x < player.x-25) robot.x += robot.velocidad_x; if(robot.x > player.x-25) robot.x -= robot.velocidad_x; if(robot.y > player.y-25) robot.y -= robot.velocidad_y; if(robot.y < player.y-25) robot.y += robot.velocidad_y; // Uso de las funciones para las colisiones //if(Collision(player.x, player.y, 50, 50, robot.x, robot.y, 34, 34)) player.alive = false; if(PixelCol(player.image, robot.image, player.x-(player.w/2), player.y-(player.h/2), player.w, player.h, robot.x, robot.y, robot.w/7, robot.h)) player.alive = false; al_clear_to_color(al_map_rgb(255, 255, 255)); // Se pinta todo a negro al_draw_scaled_bitmap(fondo1,0, 0, 256, 256, 0, 0, ScreenWidth, ScreenHeight, 0); // Se dibuja el fondo if(player.alive){ // Si el jugador está vivo al_draw_rotated_bitmap(player.image, 25, 25, player.x, player.y, player.degrees, 0); // Dibujo el jugador al_draw_rotated_bitmap(bala.image, 0, 0, player.x+5, player.y+5, player.degrees, 0); // Dibujo la bala (esto hay que quitarlo) } al_draw_bitmap_region(robot.image, 0, 0, 60, 52, robot.x, robot.y, 0); // Dibujo el robot // Esto es para el debugging // Dibujo rectángulos para las colisiones al_draw_rectangle(player.x-(player.w/2), player.y-(player.h/2), (player.x+player.w)-(player.w/2), (player.y+player.h)-(player.h/2), al_map_rgb(0, 255, 0), 1.0); al_draw_rectangle(robot.x, robot.y, robot.x+(robot.w/7), robot.y+robot.h, al_map_rgb(0, 255, 0), 1.0); // Escribo en una esquina de la pantalla, información respecto al personaje al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 2, ALLEGRO_ALIGN_RIGHT, "Player x, y : %.1f %.1f", player.x, player.y); al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 12, ALLEGRO_ALIGN_RIGHT, "Rotation (rad): %.5f", player.degrees); al_draw_textf(font, al_map_rgb(255,255,255), ScreenWidth-10, 22, ALLEGRO_ALIGN_RIGHT, "Rotation (degrees): %.2f", (player.degrees*180)/ALLEGRO_PI); // Actualizo la pantalla (flip) al_flip_display(); } //-----After party (hay que limpiar)-------------------------------- // A destruirlo todo!! BAM BAM BAM, KABOOM!! al_destroy_font(font); al_destroy_bitmap(fondo1); al_destroy_bitmap(robot.image); al_destroy_display(display); al_destroy_event_queue(event_queue); al_destroy_bitmap(player.image); al_destroy_timer(timer); return 0; }
int main(void) { ALLEGRO_TRANSFORM trans; ALLEGRO_EVENT event; int bps = 4; bool redraw = false; unsigned int last_timer = 0; if (!al_init()) { abort_example("Could not init Allegro.\n"); } open_log(); al_install_keyboard(); display = al_create_display(640, 480); if (!display) { abort_example("Could not create display\n"); } font = al_create_builtin_font(); if (!font) { abort_example("Could not create font\n"); } if (!al_install_audio()) { abort_example("Could not init sound\n"); } if (!al_reserve_samples(RESERVED_SAMPLES)) { abort_example("Could not set up voice and mixer\n"); } ping = generate_ping(); if (!ping) { abort_example("Could not generate sample\n"); } timer = al_create_timer(1.0 / bps); al_set_timer_count(timer, -1); event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_keyboard_event_source()); al_register_event_source(event_queue, al_get_timer_event_source(timer)); al_identity_transform(&trans); al_scale_transform(&trans, 16.0, 16.0); al_use_transform(&trans); al_start_timer(timer); while (true) { al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_TIMER) { const float speed = pow(21.0/20.0, (event.timer.count % PERIOD)); if (!al_play_sample(ping, 1.0, 0.0, speed, ALLEGRO_PLAYMODE_ONCE, NULL)) { log_printf("Not enough reserved samples.\n"); } redraw = true; last_timer = event.timer.count; } else if (event.type == ALLEGRO_EVENT_KEY_CHAR) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } if (event.keyboard.unichar == '+' || event.keyboard.unichar == '=') { if (bps < 32) { bps++; al_set_timer_speed(timer, 1.0 / bps); } } else if (event.keyboard.unichar == '-') { if (bps > 1) { bps--; al_set_timer_speed(timer, 1.0 / bps); } } } if (redraw && al_is_event_queue_empty(event_queue)) { ALLEGRO_COLOR c; if (last_timer % PERIOD == 0) c = al_map_rgb_f(1, 1, 1); else c = al_map_rgb_f(0.5, 0.5, 1.0); al_clear_to_color(al_map_rgb(0, 0, 0)); al_draw_textf(font, c, 640/32, 480/32 - 4, ALLEGRO_ALIGN_CENTRE, "%u", last_timer); al_flip_display(); } } close_log(false); return 0; }
int main(int argc, char **argv) { int num_joysticks; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_JOYSTICK *curr_joy; ALLEGRO_DISPLAY *display; (void)argc; (void)argv; if (!al_init()) { abort_example("Could not init Allegro.\n"); } if (!al_install_joystick()) { abort_example("Could not init joysticks.\n"); } al_install_keyboard(); al_init_primitives_addon(); open_log(); display = al_create_display(640, 480); if (!display) { abort_example("Could not create display.\n"); } queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_register_event_source(queue, al_get_joystick_event_source()); al_register_event_source(queue, al_get_display_event_source(display)); num_joysticks = al_get_num_joysticks(); log_printf("Num joysticks: %d\n", num_joysticks); if (num_joysticks > 0) { curr_joy = al_get_joystick(0); print_joystick_info(curr_joy); } else { curr_joy = NULL; } draw(curr_joy); while (1) { ALLEGRO_EVENT event; al_wait_for_event(queue, &event); if (event.type == ALLEGRO_EVENT_KEY_DOWN && event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { break; } else if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } else if (event.type == ALLEGRO_EVENT_KEY_CHAR) { int n = event.keyboard.unichar - '0'; if (n >= 0 && n < num_joysticks) { curr_joy = al_get_joystick(n); log_printf("switching to joystick %d\n", n); print_joystick_info(curr_joy); } } else if (event.type == ALLEGRO_EVENT_JOYSTICK_CONFIGURATION) { al_reconfigure_joysticks(); num_joysticks = al_get_num_joysticks(); log_printf("after reconfiguration num joysticks = %d\n", num_joysticks); if (curr_joy) { log_printf("current joystick is: %s\n", al_get_joystick_active(curr_joy) ? "active" : "inactive"); } curr_joy = al_get_joystick(0); } else if (event.type == ALLEGRO_EVENT_JOYSTICK_AXIS) { log_printf("axis event from %p, stick %d, axis %d\n", event.joystick.id, event.joystick.stick, event.joystick.axis); } else if (event.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN) { log_printf("button down event %d from %p\n", event.joystick.button, event.joystick.id); } else if (event.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_UP) { log_printf("button up event %d from %p\n", event.joystick.button, event.joystick.id); } draw(curr_joy); } close_log(false); return 0; }
void Game::run () { bool to_paint; ALLEGRO_EVENT event; while (1) { do { al_wait_for_event(global.queue, &event); switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: Utils::terminate(); break; case ALLEGRO_EVENT_TIMER: to_paint = true; if (!paused) time_walk (); break; case ALLEGRO_EVENT_KEY_DOWN: case ALLEGRO_EVENT_KEY_REPEAT: if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) paused = !paused; }; } while (!al_event_queue_is_empty(global.queue)); if (to_paint) { al_clear_to_color(global.color_black); al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba_f(1.0, 1.0, 1.0, 0.3)); al_draw_bitmap(global.bitmap_bga[0], GAME_X1, n_frame - al_get_bitmap_height(global.bitmap_bgd[0]) - al_get_bitmap_height(global.bitmap_bgc[0]) - al_get_bitmap_height(global.bitmap_bgb[0]) - al_get_bitmap_height(global.bitmap_bga[0]) + GAME_H, 0); al_draw_bitmap(global.bitmap_bgb[0], GAME_X1, n_frame - al_get_bitmap_height(global.bitmap_bgd[0]) - al_get_bitmap_height(global.bitmap_bgc[0]) - al_get_bitmap_height(global.bitmap_bgb[0]) + GAME_H, 0); al_draw_bitmap(global.bitmap_bgc[0], GAME_X1, n_frame - al_get_bitmap_height(global.bitmap_bgd[0]) - al_get_bitmap_height(global.bitmap_bgc[0]) + GAME_H, 0); al_draw_bitmap(global.bitmap_bgd[0], GAME_X1, n_frame - al_get_bitmap_height(global.bitmap_bgd[0]) + GAME_H, 0); if (gamedata.fl_invincible && n_frame % 6 < 3) { al_set_blender(ALLEGRO_ALPHA, ALLEGRO_ONE, al_map_rgba_f(0.0, 0.0, 1.0, 1.0)); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); } else { /* if (gamedata.character == CHAR_SILK) { al_set_blender(ALLEGRO_ALPHA, ALLEGRO_ONE, al_map_rgba_f(1.0, 1.0, 1.0, 1.0)); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); } else */ { al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba_f(1.0, 1.0, 1.0, 1.0)); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_char[gamedata.character]), 0); } } al_set_blender(ALLEGRO_ALPHA, ALLEGRO_ONE, al_map_rgba_f(1.0, 1.0, 1.0, 1.0)); al_draw_bitmap(GAME_POS_C(gamedata.cur_pos, global.bitmap_crd[gamedata.character]), 0); al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba_f(1.0, 1.0, 1.0, 1.0)); for (int i = 0; i < gamedata.n_pbullet; i ++) gamedata.pbullet[i] -> draw (); for (int i = 0; i < gamedata.n_ebullet; i ++) gamedata.ebullet[i] -> draw (); for (int i = 0; i < gamedata.n_enemy; i ++) gamedata.enemy[i] -> draw (); al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba_f(1.0, 1.0, 1.0, 1.0)); al_draw_bitmap(global.bitmap_game, 1, 1, 0); al_set_blender(ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, al_map_rgba_f(0.7, 0.7, 1.0, 0.9)); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 50, ALLEGRO_ALIGN_LEFT, "HISCORE"); al_draw_textf(global.font_game_score, SCREEN_W - 20, GAME_Y1 + 50, ALLEGRO_ALIGN_RIGHT, "0"); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 75, ALLEGRO_ALIGN_LEFT, "SCORE"); al_draw_textf(global.font_game_score, SCREEN_W - 20, GAME_Y1 + 75, ALLEGRO_ALIGN_RIGHT, "0"); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 110, ALLEGRO_ALIGN_LEFT, "Life"); { char buf[128]; int tmp = 0, bp = 0; while (tmp + HP_PER_LIFE <= gamedata.hp) { buf[bp ++] = '@'; tmp += HP_PER_LIFE; } while (tmp + 1 <= gamedata.hp) { buf[bp ++] = '.'; tmp += HP_PER_LIFE; } buf[bp] = 0; al_draw_textf(global.font_game_score, GAME_X2 + 90, GAME_Y1 + 110, ALLEGRO_ALIGN_LEFT, buf); } al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 135, ALLEGRO_ALIGN_LEFT, "Power"); al_draw_textf(global.font_game_score, GAME_X2 + 90, GAME_Y1 + 135, ALLEGRO_ALIGN_LEFT, "%d.%02d \\ 5.00", gamedata.power / 100, gamedata.power % 100); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 160, ALLEGRO_ALIGN_LEFT, "Skill"); al_draw_textf(global.font_game_score, GAME_X2 + 90, GAME_Y1 + 160, ALLEGRO_ALIGN_LEFT, "17234 \\ 1500"); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 195, ALLEGRO_ALIGN_LEFT, "Point"); al_draw_textf(global.font_game_score, GAME_X2 + 90, GAME_Y1 + 195, ALLEGRO_ALIGN_LEFT, "20000"); al_draw_textf(global.font_game, GAME_X2 + 20, GAME_Y1 + 220, ALLEGRO_ALIGN_LEFT, "Graze"); al_draw_textf(global.font_game_score, GAME_X2 + 90, GAME_Y1 + 220, ALLEGRO_ALIGN_LEFT, "%d", gamedata.graze); { char buf[128]; sprintf(buf, "%2.2lf", global.calculated_fps); al_draw_textf(global.font_game_score, SCREEN_W, SCREEN_H - 20, ALLEGRO_ALIGN_RIGHT, buf); } { double cur_time = al_current_time (); global.calculated_fps = FPS / (cur_time - global.time_previous[d_frame % FPS]); global.time_previous[d_frame % FPS] = cur_time; d_frame ++; } al_flip_display(); to_paint = false; } } }
int main(void) { ALLEGRO_FONT *font; ALLEGRO_DISPLAY *display; ALLEGRO_EVENT_QUEUE *event_queue; ALLEGRO_EVENT event; bool right_button_down = false; bool redraw = true; int fake_x = 0, fake_y = 0; ALLEGRO_COLOR white; if (!al_init()) { abort_example("Could not init Allegro.\n"); } al_init_primitives_addon(); al_init_font_addon(); al_init_image_addon(); al_install_mouse(); al_install_keyboard(); al_set_new_display_flags(ALLEGRO_WINDOWED); display = al_create_display(width, height); if (!display) { abort_example("Could not create display.\n"); return 1; } memset(&event, 0, sizeof(event)); event_queue = al_create_event_queue(); al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_mouse_event_source()); al_register_event_source(event_queue, al_get_keyboard_event_source()); font = al_load_font("data/fixed_font.tga", 0, 0); white = al_map_rgb_f(1, 1, 1); while (1) { if (redraw && al_is_event_queue_empty(event_queue)) { int th = al_get_font_line_height(font); al_clear_to_color(al_map_rgb_f(0, 0, 0)); if (right_button_down) { al_draw_line(width / 2, height / 2, fake_x, fake_y, al_map_rgb_f(1, 0, 0), 1); al_draw_line(fake_x - 5, fake_y, fake_x + 5, fake_y, al_map_rgb_f(1, 1, 1), 2); al_draw_line(fake_x, fake_y - 5, fake_x, fake_y + 5, al_map_rgb_f(1, 1, 1), 2); } al_draw_textf(font, white, 0, 0, 0, "x: %i y: %i dx: %i dy %i", event.mouse.x, event.mouse.y, event.mouse.dx, event.mouse.dy); al_draw_textf(font, white, width / 2, height / 2 - th, ALLEGRO_ALIGN_CENTRE, "Left-Click to warp pointer to the middle once."); al_draw_textf(font, white, width / 2, height / 2, ALLEGRO_ALIGN_CENTRE, "Hold right mouse button to constantly move pointer to the middle."); al_flip_display(); redraw = false; } al_wait_for_event(event_queue, &event); if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { break; } if (event.type == ALLEGRO_EVENT_KEY_DOWN) { if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) break; } if (event.type == ALLEGRO_EVENT_MOUSE_WARPED) { printf("Warp\n"); } if (event.type == ALLEGRO_EVENT_MOUSE_AXES) { if (right_button_down) { al_set_mouse_xy(display, width / 2, height / 2); fake_x += event.mouse.dx; fake_y += event.mouse.dy; } redraw = true; } if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) { if (event.mouse.button == 1) al_set_mouse_xy(display, width / 2, height / 2); if (event.mouse.button == 2) { right_button_down = true; fake_x = width / 2; fake_y = height / 2; } } if (event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) { if (event.mouse.button == 2) { right_button_down = false; } } } al_destroy_event_queue(event_queue); al_destroy_display(display); return 0; }
int main(int argc, char **argv) { int i, j, k, l, m; ALLEGRO_COLOR src_colors[2]; ALLEGRO_COLOR dst_colors[2]; ALLEGRO_COLOR blend_colors[2]; int src_formats[2] = { ALLEGRO_PIXEL_FORMAT_ABGR_8888, ALLEGRO_PIXEL_FORMAT_BGR_888 }; int dst_formats[2] = { ALLEGRO_PIXEL_FORMAT_ABGR_8888, ALLEGRO_PIXEL_FORMAT_BGR_888 }; src_colors[0] = C(0, 0, 0, 1); src_colors[1] = C(1, 1, 1, 1); dst_colors[0] = C(1, 1, 1, 1); dst_colors[1] = C(0, 0, 0, 0); blend_colors[0] = C(1, 1, 1, 0.5); blend_colors[1] = C(1, 1, 1, 1); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-d")) test_display = 1; else test_only_index = strtol(argv[i], NULL, 10); } al_init(); if (test_display) al_create_display(100, 100); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { for (k = 0; k < 2; k++) { for (l = 0; l < 2; l++) { for (m = 0; m < 2; m++) { do_test1( src_colors[i], dst_colors[j], blend_colors[k], src_formats[l], dst_formats[m]); } } } } } printf("\n"); if (test_only_index && test_display) { ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_EVENT event; al_flip_display(); al_install_keyboard(); queue = al_create_event_queue(); al_register_event_source(queue, al_get_keyboard_event_source()); al_wait_for_event(queue, &event); } return 0; }