示例#1
0
文件: pause.c 项目: dos1/SuperDerpy
int Pause_Keydown(struct Game *game, ALLEGRO_EVENT *ev) {
	if ((game->menu.menustate==MENUSTATE_OPTIONS) && ((ev->keyboard.keycode==ALLEGRO_KEY_ESCAPE) || ((ev->keyboard.keycode==ALLEGRO_KEY_ENTER) && (game->menu.selected==3)))) {
		al_play_sample_instance(game->menu.click);
		ChangeMenuState(game,MENUSTATE_PAUSE);
	} else if ((game->menu.menustate==MENUSTATE_VIDEO) && ((ev->keyboard.keycode==ALLEGRO_KEY_ESCAPE) || ((ev->keyboard.keycode==ALLEGRO_KEY_ENTER) && (game->menu.selected==3)))) {
		al_play_sample_instance(game->menu.click);
		ChangeMenuState(game,MENUSTATE_OPTIONS);
		if (game->menu.options.fullscreen!=game->fullscreen) {
			al_toggle_display_flag(game->display, ALLEGRO_FULLSCREEN_WINDOW, game->menu.options.fullscreen);
			al_clear_to_color(al_map_rgb(0,0,0));
			al_flip_display();
			game->fullscreen = game->menu.options.fullscreen;
			if (game->fullscreen) al_hide_mouse_cursor(game->display);
			else al_show_mouse_cursor(game->display);
			Shared_Unload(game);
			al_clear_to_color(al_map_rgb(0,0,0));
			al_flip_display();
			SetupViewport(game);
			Shared_Load(game);

#ifndef __clang__
			void Progress(struct Game *game, float p) {
				al_set_target_bitmap(al_get_backbuffer(game->display));
				al_clear_to_color(al_map_rgb(0,0,0));
				al_draw_text_with_shadow(game->font, al_map_rgb(255,255,255), game->viewportWidth*0.0234, game->viewportHeight*0.84, ALLEGRO_ALIGN_LEFT, "Loading...");
				al_draw_filled_rectangle(0, game->viewportHeight*0.985, game->viewportWidth, game->viewportHeight, al_map_rgba(128,128,128,128));
				al_draw_filled_rectangle(0, game->viewportHeight*0.985, p*game->viewportWidth, game->viewportHeight, al_map_rgba(255,255,255,255));
				al_flip_display();
			}
int menu_proc_play_normal(int i, void * p)
{
	al_hide_mouse_cursor(t3f_display);
	enemy_spawn_logic = enemy_spawn_logic_normal;
	game_init();
	return 1;
}
示例#3
0
void paddle_game_init(void)
{
	al_hide_mouse_cursor(t3f_display);
	
	/* place paddles */
	paddle[0].x = 32.0;
	paddle[0].y = 240.0 - 64.0 / 2.0;
	paddle[0].object = t3f_create_collision_object(0, 0, 16, 64, 32, 32, 0);
	t3f_move_collision_object_xy(paddle[0].object, paddle[0].x, paddle[0].y);
	paddle[0].active = true;
	paddle[1].x = 640.0 - 32.0 - 16.0;
	paddle[1].y = 240.0 - 64.0 / 2.0;
	paddle[1].object = t3f_create_collision_object(0, 0, 16, 64, 32, 32, 0);
	t3f_move_collision_object_xy(paddle[1].object, paddle[1].x, paddle[1].y);
	paddle[1].active = true;
	
	/* place ball */
	ball.object = t3f_create_collision_object(0, 0, 16, 16, 32, 32, 0);
	paddle_init_ball(1.0);
	
	/* reset scores */
	score[0] = 0;
	score[1] = 0;
	
	t3f_srand(&rng_state, time(0));
	
	paddle_state = EXAMPLE_STATE_GAME;
	t3f_play_music("data/music/game.xm");
}
示例#4
0
void
hide_mouse_cursor (void)
{
  if (! al_hide_mouse_cursor (display))
    error (0, 0, "%s (void): cannot hide mouse cursor",
           __func__);
}
示例#5
0
void Mouse::Update() {

    _prevState = _curState;
    al_get_mouse_state(&_curState);

    if(_cursor) {
        al_set_mouse_cursor(_parent_display, _cursor);
    } else {
        al_set_system_mouse_cursor(_parent_display, _cursor_id);
    }
    _isVisible ?  al_show_mouse_cursor(_parent_display) : al_hide_mouse_cursor(_parent_display);
}
示例#6
0
//----------------------------------------------------------------------------
bool AllegroRender::Init(bool openWindowed, const char *windowTitle, int windowLength, int windowHeight) {
	display = al_create_display(windowLength, windowHeight);
	if (!display) {
		return false;
	}

	if (!al_init_image_addon()) {
		return false;
	}

	al_set_window_title(display, windowTitle);
    al_hide_mouse_cursor(display);
	return true;
}
示例#7
0
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *cursor;
   ALLEGRO_MOUSE_STATE msestate;
   ALLEGRO_KEYBOARD_STATE kbdstate;
   int i;

   (void)argc;
   (void)argv;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }

   al_init_primitives_addon();
   al_install_mouse();
   al_install_keyboard();
   al_init_image_addon();
   init_platform_specific();

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Error creating display\n");
   }

   al_hide_mouse_cursor(display);

   cursor = al_load_bitmap("data/cursor.tga");
   if (!cursor) {
      abort_example("Error loading cursor.tga\n");
   }

   do {
      al_get_mouse_state(&msestate);
      al_get_keyboard_state(&kbdstate);

      al_clear_to_color(al_map_rgb(0xff, 0xff, 0xc0));
      for (i = 1; i <= NUM_BUTTONS; i++) {
         draw_mouse_button(i, al_mouse_button_down(&msestate, i));
      }
      al_draw_bitmap(cursor, msestate.x, msestate.y, 0);
      al_flip_display();

      al_rest(0.005);
   } while (!al_key_down(&kbdstate, ALLEGRO_KEY_ESCAPE));

   return 0;
}
示例#8
0
文件: main.c 项目: 0ctobyte/speedrun
// Initializes the the GDATA struct
_Bool data_init(void)
{
    // Create a window to display things on: 800x600 pixels
    al_set_new_display_flags(ALLEGRO_RESIZABLE | ALLEGRO_OPENGL);
    al_set_new_display_refresh_rate(60);
    data->display = al_create_display(res_width, res_height);
    if(data->display == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Display Error:", "Failed to create window!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Sets the physfs file interface to be used for loading files
    al_set_physfs_file_interface();
    PHYSFS_mount("images", NULL, 1);
    PHYSFS_mount("fonts", NULL, 1);
    PHYSFS_mount("buttons", NULL, 1);

    // Well, looks like we're gonna have to draw our own mouse *SIGH*
    al_hide_mouse_cursor(data->display);
    data->cursor = al_load_bitmap("cursor_darkgrey.png");
    if(data->cursor == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Cursor Error:", "Failed to locate cursor!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Set the title of the window
    al_set_window_title(data->display, "SpeedRun!");

    // Sets the window's icon
    data->icon = al_load_bitmap("speedrundisplayicon.png");
    if(data->icon == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Icon Error:", "Failed to locate icon!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }
    al_set_display_icon(data->display, data->icon);

    // Load a font
    data->font = al_load_ttf_font("times.ttf", 25, 0);
    data->b_font = al_load_ttf_font("impact.ttf", 25, 0);
    if(data->font == NULL || data->b_font == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Font Error:", "Failed to load font!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Make and set a color to draw with
    data->text_color = al_map_rgba(80, 112, 255, 255);

    // Set background color
    data->background_color = al_map_rgba(0, 0, 0, 0);

    // Install the keyboard handler
    if(!al_install_keyboard())
    {
        al_show_native_message_box(data->display, "Error!", "Keyboard Error:", "Failed to install keyboard handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Install the mouse handler
    if(!al_install_mouse())
    {
        al_show_native_message_box(data->display, "Error!", "Mouse Error:", "Failed to install mouse handler!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return false;
    }

    // Detect and set refresh rate
    int refresh_rate = al_get_display_refresh_rate(data->display);
    if(refresh_rate == 0)
    {
        refresh_rate = 60;
    }

    // Install timer with refresh rate
    data->timer = al_create_timer(1.0/refresh_rate);
    if(data->timer == NULL)
    {
        al_show_native_message_box(data->display, "Error!", "Timer Error:", "Failed to initialize timer!", NULL,
                                   ALLEGRO_MESSAGEBOX_ERROR);
        return 1;
    }
    al_start_timer(data->timer);


    // Start the event queues to handle keyboard input, mouse input, display input and timer input
    data->queue = al_create_event_queue();
    al_register_event_source(data->queue, (ALLEGRO_EVENT_SOURCE*)data->timer);
    data->queue2 = al_create_event_queue();
    al_register_event_source(data->queue2, al_get_keyboard_event_source());
    al_register_event_source(data->queue2, (ALLEGRO_EVENT_SOURCE*)data->display);
    al_register_event_source(data->queue2, al_get_mouse_event_source());

    // Set the quit and gamestarted flags to false initially
    data->exit = false;
    data->gamestarted = false;
    data->options = false;
    data->highscores = false;
    data->howtoplay = false;

    al_start_timer(data->timer);

    return true;
}
示例#9
0
static bool
init(void)
{
  if(!al_init()) {
    fprintf(stderr, "failed to initialize allegro.\n");
    return false;
  }

  if(!al_install_keyboard()) {
    fprintf(stderr, "failed to initialize keyboard.\n");
    return false;
  }

  if(!al_init_image_addon()) {
    fprintf(stderr, "failed to initialize image system.\n");
    return false;
  }

  al_init_font_addon();
  if(!al_init_ttf_addon()) {
    fprintf(stderr, "failed to initialize ttf system.\n");
    return false;
  }

  /* sound */
  if(!al_install_audio()) {
    fprintf(stderr, "failed to initialize audio system.\n");
    return false;
  }
  if(!al_init_acodec_addon()) {
    fprintf(stderr, "failed to initialize audio codecs.\n");
    return false;
  }
  if(!al_reserve_samples(10)) {
    fprintf(stderr, "failed to reserve audio samples.\n");
    return false;
  }

  /* fonts */
  asteroids.small_font = al_load_ttf_font("data/vectorb.ttf", 12, 0);
  asteroids.large_font = al_load_ttf_font("data/vectorb.ttf", 24, 0);

  /* lives sprite */
  asteroids.lives_sprite = al_load_bitmap("data/sprites/ship/ship.png");
  if(!asteroids.lives_sprite) {
    fprintf(stderr, "failed to load lives sprite.\n");
    return false;
  }

  /* sprite preloading */
  if(!level_init())
    return false;
  if(!ship_init())
    return false;
  if(!missile_init())
    return false;
  if(!saucer_init())
    return false;
  if(!asteroid_init())
    return false;
  if(!explosion_init())
    return false;

  asteroids.timer = al_create_timer(1.0 / FPS);
  if(!asteroids.timer) {
    fprintf(stderr, "failed to create timer.\n");
    return false;
  }

  asteroids.event_queue = al_create_event_queue();
  if(!asteroids.event_queue) {
    fprintf(stderr, "failed to create event queue.\n");
    return false;
  }

  if(FULLSCREEN)
    al_set_new_display_flags(ALLEGRO_FULLSCREEN);
  al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
  al_set_new_display_option(ALLEGRO_SAMPLES,        8, ALLEGRO_SUGGEST);
  asteroids.display = al_create_display(SCREEN_W, SCREEN_H);
  if(!asteroids.display) {
    fprintf(stderr, "failed to create display.\n");
    return false;
  }

  /* TODO: show on mouse movement */
  al_hide_mouse_cursor(asteroids.display);

  al_register_event_source(asteroids.event_queue, al_get_display_event_source(asteroids.display));
  al_register_event_source(asteroids.event_queue, al_get_timer_event_source(asteroids.timer));
  al_register_event_source(asteroids.event_queue, al_get_keyboard_event_source());

  return true;
}
int main(int argc, char const *argv[])
{
	const int FPS = 60;
	const int MAX_BULLETS = 10;
	const int MAX_ASTEROIDS = 10;
	const int MAX_EXPLOSIONS = 10;
	srand(time(NULL));
	int done = 0;
	int redraw = 1;

	if(!al_init())
	{
		al_show_native_message_box(NULL, "Error", "Error", 
			"Could not initialize Allegro 5.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_DISPLAY *display = al_create_display(screen_width, screen_height);
	if(!display)
	{
		al_show_native_message_box(NULL, "Error", "Error", 
			"Could not create display.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	if(!event_queue)
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not create event queue.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	ALLEGRO_TIMER *timer = al_create_timer(1.0/FPS);
	if(!timer)
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not create timer.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_install_keyboard())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not install keyboard.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_install_mouse())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not install mouse.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_init_image_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize image addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
		return -1;
	}

	if(!al_init_primitives_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize primitives addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
	}

	al_init_font_addon(); // for whatever reason this function is void returning

	if(!al_init_ttf_addon())
	{
		al_show_native_message_box(display, "Error", "Error", 
			"Could not initialize ttf addon.", 0, ALLEGRO_MESSAGEBOX_ERROR);
	}
	
	al_hide_mouse_cursor(display);

	al_register_event_source(event_queue, al_get_mouse_event_source());
	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));

	ALLEGRO_FONT *font18 = al_load_font("Arial.ttf", 18, 0);

	int prev_x = screen_width, prev_y = screen_height;
	int fps_counter = 0;
	int fps_counter2 = 0;
	int i, j, k;

	struct spaceship ship;
	init_ship(&ship);

	struct bullet bullets[MAX_BULLETS];
	for(i = 0; i < MAX_BULLETS; i++)
	{
		init_bullet(&bullets[i]);
	}

	struct asteroid asteroids[MAX_ASTEROIDS];
	for(i = 0; i < MAX_ASTEROIDS; i++)
	{
		init_asteroid(&asteroids[i]);
	}

	struct explosion explosions[MAX_EXPLOSIONS];
	for(i = 0; i < MAX_EXPLOSIONS; i++)
	{
		init_explosion(&explosions[i]);
	}

	al_start_timer(timer);

	while(!done)
	{
		ALLEGRO_EVENT event;
		al_wait_for_event(event_queue, &event);

		if(event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = 1;
		}
		if(event.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch(event.keyboard.keycode)
			{
				case ALLEGRO_KEY_Q: 
					done = 1;
					break;
				case ALLEGRO_KEY_ESCAPE:
					done = 1;
					break;
			}
		}
		if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
		{
			if(event.mouse.button & 1)
			{
				for(i = 0; i < MAX_BULLETS; i++)
				{
					if(!bullets[i].live)
					{
						fire_bullet(&bullets[i], ship);
						break;
					}
				}
			}
		}
		if(event.type == ALLEGRO_EVENT_MOUSE_AXES ||
              event.type == ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY)
		{
			set_ship_coordinates(&ship, event.mouse.x, event.mouse.y);
		}
		if(event.type == ALLEGRO_EVENT_TIMER)
		{	
			if(ship.x > prev_x)
			{	
				ship.sprite.dir_horizontal = RIGHT;
			}
			else if(ship.x == prev_x)
			{
				ship.sprite.dir_horizontal = CENTER;
			}
			else if(ship.x < prev_x) 
			{
				ship.sprite.dir_horizontal = LEFT;
			}

			if(ship.y > prev_y)
			{
				ship.sprite.dir_vertical = BACK;
			}
			else if(ship.y == prev_y)
			{
				ship.sprite.dir_vertical = NEUTRAL;
			}
			else if(ship.y < prev_y)
			{
				ship.sprite.dir_vertical = FORWARD;
			}

			if(++fps_counter >= FPS / 5)
			{
				fps_counter = 0;
				prev_x = ship.x;
				prev_y = ship.y;	
			}

			if(++fps_counter2 >= 2 * FPS)
			{
				for(i = 0; i < MAX_ASTEROIDS; i++)
				{
					if(!asteroids[i].live)
					{
						start_asteroid(&asteroids[i]);
						break;
					}
				}
				fps_counter2 = 0;
			}

			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					update_bullet(&bullets[i]);
				}
			}

			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					update_asteroid(&asteroids[i], &ship);
				}
			}

			for(i = 0; i < MAX_EXPLOSIONS; i++)
			{
				if(explosions[i].live)
				{
					update_explosion(&explosions[i]);
				}
			}

			update_ship_boundaries(&ship);

			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					for(j = 0; j < MAX_ASTEROIDS; j++)
					{
						if(asteroids[j].live)
						{
							if(bullet_and_asteroid_collision(bullets[i], asteroids[j]))
							{
								bullets[i].live = 0;
								asteroids[j].live = 0;
								ship.score += 20;
								for(k = 0; k < MAX_EXPLOSIONS; k++)
								{
									if(!explosions[k].live)
									{
										start_explosion(&explosions[k], bullets[i].x, bullets[i].y);
										break;
									}
								}
							}
						}
					}
				}
			}

			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					if(ship_and_asteroid_collision(ship, asteroids[i]))
					{
						asteroids[i].live = 0;
						for(k = 0; k < MAX_EXPLOSIONS; k++)
						{
							if(!explosions[k].live)
							{
								start_explosion(&explosions[k], ship.x, ship.y);
								break;
							}
						}
						
						ship.lives--;
					}
				}
			}

			if(!ship.lives)
			{
				done = true;
			}

			redraw = 1;
		}

		if(redraw)
		{
			redraw = 0;
			draw_ship_sprite(ship.sprite, ship.x, ship.y);
			for(i = 0; i < MAX_BULLETS; i++)
			{
				if(bullets[i].live)
				{
					draw_bullet(bullets[i]);
				}
			}
			for(i = 0; i < MAX_ASTEROIDS; i++)
			{
				if(asteroids[i].live)
				{
					draw_asteroid(asteroids[i]);
				}
			}
			for(i = 0; i < MAX_EXPLOSIONS; i++)
			{
				if(explosions[i].live)
				{
					draw_explosion(explosions[i]);
				}
			}
			al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 5, 0, 
				"Score: %d ", ship.score); // I have no idea why it doesn't print the S...
			al_draw_textf(font18, al_map_rgb(255, 255, 255), 50, 25, 0, 
				"Lives: %d", ship.lives);
			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
		}
	}

	for(i = 0; i < MAX_ASTEROIDS; i++)
	{
		destroy_asteroid(&asteroids[i]);
	}
	for(i = 0; i < MAX_EXPLOSIONS; i++)
	{
		destroy_explosion(&explosions[i]);
	}
	destroy_sprite(&ship.sprite);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font18);

	return 0;
}
示例#11
0
文件: main.cpp 项目: pmprog/ROTMenu
int main( int argc, char* argv[] )
{
	ALLEGRO_EVENT e;
	ALLEGRO_TIMER* t;
	int64_t framesToUpdate = 0;

	if( !al_init() )
	{
		return -1;
	}
	
	al_init_font_addon();
	if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
	{
		return -1;
	}

#if NETWORK_SUPPORT != 0
	if( !install_network() )
	{
		return -1;
	}
#endif

#if HTTP_SUPPORT
	if( !install_http() )
	{
		return -1;
	}
#ifdef PANDORA
	Downloads = new HttpManager(2);
#else
	Downloads = new HttpManager(6);
#endif
#endif

#if EXIT_IF_NO_AUDIO != 0

	if( !al_install_audio() || !al_init_acodec_addon() )
	{
		return -1;
	}

	voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
	if (!voice)
		return 1;
	mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
	if (!mixer)
		return 1;
	if (!al_attach_mixer_to_voice(mixer, voice))
		return 1;

#else

	if( al_install_audio() )
	{
		if( al_init_acodec_addon() )
		{
			voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
			if( voice != 0 )
			{
				mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2);
				if( mixer != 0 )
					al_attach_mixer_to_voice(mixer, voice);
			}
		}
	}

#endif // EXIT_IF_NO_AUDIO

	// Random number is guarenteed to be random
	srand( 5 );

	GameStack = new StageStack();
	CurrentConfiguration = new Configuration();

	if( CurrentConfiguration->FullScreen )
		al_set_new_display_flags( ALLEGRO_FULLSCREEN_WINDOW );

	al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);

	bool foundMode = false;
	int fallbackW = 640;
	int fallbackH = 480;

	if( CurrentConfiguration->ForceResolution )
	{
		foundMode = true;
	} else {
		for( int modeIdx = 0; modeIdx < al_get_num_display_modes(); modeIdx++ )
		{
			if( al_get_display_mode( modeIdx, &ScreenMode ) != NULL )
			{
				if( ScreenMode.width == CurrentConfiguration->ScreenWidth && ScreenMode.height == CurrentConfiguration->ScreenHeight )
				{
					foundMode = true;
				} else {
					fallbackW = ScreenMode.width;
					fallbackH = ScreenMode.height;
				}
			}

			if( foundMode )
				break;
		}
	}

	if( foundMode )
	{
		Screen = al_create_display( CurrentConfiguration->ScreenWidth, CurrentConfiguration->ScreenHeight );
	} else {
		Screen = al_create_display( fallbackW, fallbackH );
		CurrentConfiguration->ScreenWidth = fallbackW;
		CurrentConfiguration->ScreenHeight = fallbackH;
	}

	al_hide_mouse_cursor( Screen );

	t = al_create_timer( 1.0 / SCREEN_FPS );
  if( t == NULL )
    Quit = true;
  al_start_timer( t );

	EventQueue = al_create_event_queue();
	al_register_event_source( EventQueue, al_get_display_event_source( Screen ) );
	al_register_event_source( EventQueue, al_get_keyboard_event_source() );
	al_register_event_source( EventQueue, al_get_mouse_event_source() );
	al_register_event_source( EventQueue, al_get_timer_event_source( t ) );
#if NETWORK_SUPPORT != 0
	al_register_event_source( EventQueue, get_network_event_source() );
#endif
#if HTTP_SUPPORT
	Downloads->urlDownloads = CurrentConfiguration->MaxConcurrentDownloads;
	al_register_event_source( EventQueue, get_http_event_source() );
#endif

	Fonts = new FontManager();
	Images = new ImageManager();
	Audio = new SoundManager();

	al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA );

	GameStack->Push( (Stage*)new BootUp() );

	while( !Quit )
	{
		if( GameStack->IsEmpty() )
		{
			Quit = true;
		} else {
			while( al_get_next_event( EventQueue, &e ) )
			{
#if HTTP_SUPPORT
				Downloads->Event( &e );
#endif
				switch( e.type )
				{
					case ALLEGRO_EVENT_DISPLAY_CLOSE:
						Quit = true;
						break;
					case ALLEGRO_EVENT_JOYSTICK_CONFIGURATION:
						al_reconfigure_joysticks();
						break;
					case ALLEGRO_EVENT_TIMER:
						if( e.timer.source == t )
							framesToUpdate++;
						else if( !GameStack->IsEmpty() )
							GameStack->Current()->Event( &e );
						break;
					default:
						if( !GameStack->IsEmpty() )
							GameStack->Current()->Event( &e );
						switch( e.type )
						{
#if HTTP_SUPPORT
							case ALLEGRO_EVENT_HTTP:
#endif
#if NETWORK_SUPPORT
							case ALLEGRO_EVENT_NETWORK_CONNECTION:
							case ALLEGRO_EVENT_NETWORK_RECEIVEPACKET:
							case ALLEGRO_EVENT_NETWORK_DISCONNECTION:
#endif
							case ALLEGRO_EVENT_BUTTON_CLICK:
							case ALLEGRO_EVENT_MOUSEEX_MOVE:
							case ALLEGRO_EVENT_MOUSEEX_DOWN:
							case ALLEGRO_EVENT_MOUSEEX_UP:
							case ALLEGRO_EVENT_MOUSEEX_CLICK:
							case ALLEGRO_EVENT_MOUSEEX_DOUBLECLICK:
							case ALLEGRO_EVENT_MOUSEEX_BOXED:
							case ALLEGRO_EVENT_MOUSEEX_WHEEL:
								al_unref_user_event( &e.user );
								break;
						}
						break;
				}
			}

			if( framesToUpdate > 0 )
			{
				for( int frmUp = 0; frmUp < framesToUpdate; frmUp++ )
				{
					if( !GameStack->IsEmpty() )
						GameStack->Current()->Update();
				}
				framesToUpdate = 0;
			}

			al_clear_to_color( al_map_rgb( 128, 128, 128 ) );
			if( !GameStack->IsEmpty() )
				GameStack->Current()->Render();
			al_flip_display();

			Images->Tidy();
			Fonts->Tidy();
			Audio->Tidy();
		}
	}

	while( !GameStack->IsEmpty() )
	{
		GameStack->Pop();
	}

	delete Downloads;
	delete Fonts;
	delete Images;
	delete Audio;

	al_destroy_event_queue( EventQueue );
	al_destroy_display( Screen );

#if HTTP_SUPPORT
	uninstall_http();
#endif
#if NETWORK_SUPPORT != 0
	uninstall_network();
#endif
	al_uninstall_keyboard();
	al_uninstall_mouse();
	al_shutdown_primitives_addon();
	al_shutdown_ttf_addon();
	al_shutdown_image_addon();
	al_uninstall_audio();
	al_shutdown_font_addon();

	return 0;
}
示例#12
0
 //------------------------------------------------------------
 // La función principal main()
 //------------------------------------------------------------
 int main(int argc, char **argv)
 {
     // Iniciar Allegro (y añadidos)
     al_init();
     al_init_image_addon();
     al_init_primitives_addon();
  
     // Instalar el mouse, teclado, etc.
     al_install_keyboard();
     al_install_mouse();
  
     if (FULLSCREEN)
         al_set_new_display_flags(ALLEGRO_FULLSCREEN);
  
     // Crear el "display"
     display = al_create_display(SCREEN_W, SCREEN_H);
  
     if (!SHOW_CURSOR)
         al_hide_mouse_cursor(display);
  
     // Poner el título de la ventana
     al_set_window_title(display, WINDOW_TITLE);
  
     // Creamos el timer (controlador de FPS)
     timer = al_create_timer(1.0 / FRAMERATE);
  
     // Creamos la 'pila' de eventos
     event_queue = al_create_event_queue();
  
     // Preparamos el juego
     game_setup();
  
     // Los eventos que usaremos
     al_register_event_source(event_queue, al_get_keyboard_event_source());
     al_register_event_source(event_queue, al_get_mouse_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);
  
     // Si esta variable se pone a 0, el juego terminará de inmediato
     game_is_running = 1;
  
     ALLEGRO_EVENT event;
  
     // El 'loop' principal del juego
     while (game_is_running)
     {
         al_wait_for_event(event_queue, &event);
  
         // Si el botón para cerrar fue presionado...
         if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
             break;
  
         // Actualizamos las teclas
         if (event.type == ALLEGRO_EVENT_KEY_DOWN)
         {
             // Al presionar <Esc> el juego terminará
             if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
                 game_is_running = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
                 key[KEY_LEFT] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT)
                 key[KEY_RIGHT] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_UP)
                 key[KEY_UP] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_DOWN)
                 key[KEY_DOWN] = 1;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_X)
                 key[KEY_X] = 1;
         }
  
         // Actualizamos las teclas
         if (event.type == ALLEGRO_EVENT_KEY_UP)
         {
             if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
                 key[KEY_LEFT] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT)
                 key[KEY_RIGHT] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_UP)
                 key[KEY_UP] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_DOWN)
                 key[KEY_DOWN] = 0;
  
             if (event.keyboard.keycode == ALLEGRO_KEY_X)
                 key[KEY_X] = 0;
         }
  
         if (event.type == ALLEGRO_EVENT_TIMER)
         {
             game_update();
             redraw = 1;
         }
  
         if (redraw)
         {
             redraw = 0;
  
             al_clear_to_color(al_map_rgb(0, 0, 0));
  
             game_render();
  
             al_flip_display();
         }
     }
  
     al_destroy_display(display);
     al_destroy_timer(timer);
     al_destroy_event_queue(event_queue);
  
     game_shutdown();
  
     return 0;
 }
示例#13
0
void Engine::init(const char* title, int width, int height, bool fullscreen){

	// initialize ALLEGRO
	al_init();
    al_init_font_addon();
    al_init_ttf_addon();
    al_init_primitives_addon();
    al_init_image_addon();
    al_init_acodec_addon();
    al_install_keyboard();
    al_install_mouse();
    al_install_audio();

    if(fullscreen){
		al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
	}else{
        al_set_new_display_flags(ALLEGRO_WINDOWED);
	}
    display = al_create_display(screenWidth, screenHeight);
    al_set_window_title(display, title);

    bigFont = al_load_font("fonts/pixelFont.ttf", 48, 0);
    defaultFont = al_load_font("fonts/pixelFont.ttf", 24, 0);
    smallFont = al_load_font("fonts/pixelFont.ttf", 16, 0);

    cursorImage = al_load_bitmap("graphics/cursorImage.png");
    playerImage = al_load_bitmap("graphics/playerImage.png");
    groundImage1 = al_load_bitmap("graphics/groundImage1.png");
    groundImage2 = al_load_bitmap("graphics/groundImage2.png");
    brokenWallImage = al_load_bitmap("graphics/brokenWallImage.png");

    al_reserve_samples(0);

    event_queue = al_create_event_queue();
    timer = al_create_timer(1/FPS);

    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_mouse_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_hide_mouse_cursor(display);

	m_fullscreen = fullscreen;
    m_running = true;

    //Pointer Lists +
    networkList.clear();
    populationList.clear();
    //Pointer Lists -

    //Variables +
    versionNumber = "v1.0";

    fpsTimeNew = 0, fpsCounter = 0, fpsTimeOld = 0;

    drawScreen = false, timerEvent = false, done = false, mouseButtonLeft = false, mouseButtonLeftClick = false, mouseButtonRight = false, mouseButtonRightClick = false, updateTick = false, inGame = false;
    mouseX = 0, mouseY = 0;
    lastKeyPress = 0, mouseWheel = 0;

    score = 0, updateTickTime = 64, updateTickTimeHelper = 0;

    logicSpeed = 64, rockSpawnChance = 0, activationResponse = 0, neuronBias = 0, crossoverRate = 0, mutationRate = 0, maxPerturbation = 0;
    numHiddenLayers = 0, neuronsPerHiddenLayer = 0, numElite = 0, numCopiesElite = 0, populationSize = 0, currentNetwork = 0, currentGeneration = 0;

    for(int x = 0; x < mapArrayWidth; x++){
        for(int y = 0; y < mapArrayHeight; y++){
            mapArray[x][y] = 0;
            mapTileArray[x][y] = rand() % 8;
        }
    }

    al_start_timer(timer);
}
示例#14
0
文件: Game.cpp 项目: JackOfDawn/AI
bool Game::init()
{
	mShouldExit = false;

	//create Timers
	mpLoopTimer = new Timer;
	mpMasterTimer = new Timer;

	//startup allegro
	if(!al_init()) 
	{
		fprintf(stderr, "failed to initialize allegro!\n");
		return false;
	}

	//create and init GraphicsSystem
	mpGraphicsSystem = new GraphicsSystem();
	bool goodGraphics = mpGraphicsSystem->init( WIDTH, HEIGHT );
	if(!goodGraphics) 
	{
		fprintf(stderr, "failed to initialize GraphicsSystem object!\n");
		return false;
	}

	mpGraphicsBufferManager = new GraphicsBufferManager();
	mpSpriteManager = new SpriteManager();

	//startup a lot of allegro stuff

	//load image loader addon
	if( !al_init_image_addon() )
	{
		fprintf(stderr, "image addon failed to load!\n");
		return false;
	}

	//install audio stuff
	if( !al_install_audio() )
	{
		fprintf(stderr, "failed to initialize sound!\n");
		return false;
	}

	if(!al_init_acodec_addon())
	{
		fprintf(stderr, "failed to initialize audio codecs!\n");
		return false;
	}
 
	if (!al_reserve_samples(1))
	{
		fprintf(stderr, "failed to reserve samples!\n");
		return false;
	}

	//should probably be done in the InputSystem!
	if( !al_install_keyboard() )
	{
		printf( "Keyboard not installed!\n" ); 
		return false;
	}

	//should probably be done in the InputSystem!
	if( !al_install_mouse() )
	{
		printf( "Mouse not installed!\n" ); 
		return false;
	}

	//should be somewhere else!
	al_init_font_addon();
	if( !al_init_ttf_addon() )
	{
		printf( "ttf font addon not initted properly!\n" ); 
		return false;
	}

	//actually load the font
	mpFont = al_load_ttf_font( "cour.ttf", 20, 0 );
	if( mpFont == NULL )
	{
		printf( "ttf font file not loaded properly!\n" ); 
		return false;
	}

	//show the mouse
	if( !al_hide_mouse_cursor( mpGraphicsSystem->getDisplay() ) )
	{
		printf( "Mouse cursor not able to be hidden!\n" ); 
		return false;
	}

	if( !al_init_primitives_addon() )
	{
		printf( "Primitives addon not added!\n" ); 
		return false;
	}

	//load the sample
	mpSample = al_load_sample( "clapping.wav" );
	if (!mpSample)
	{
		printf( "Audio clip sample not loaded!\n" ); 
		return false;
	}

	mpMessageManager = new GameMessageManager();

	//load buffers
	mBackgroundBufferID = mpGraphicsBufferManager->loadBuffer("wallpaper.bmp");
	mPlayerIconBufferID = mpGraphicsBufferManager->loadBuffer("arrow.bmp");
	mEnemyIconBufferID = mpGraphicsBufferManager->loadBuffer("enemy-arrow.bmp");
	
	//setup sprites
	GraphicsBuffer* pBackGroundBuffer = mpGraphicsBufferManager->getBuffer( mBackgroundBufferID );
	if( pBackGroundBuffer != NULL )
	{
		mpSpriteManager->createAndManageSprite( BACKGROUND_SPRITE_ID, pBackGroundBuffer, 0, 0, pBackGroundBuffer->getWidth(), pBackGroundBuffer->getHeight() );
	}
	GraphicsBuffer* pPlayerBuffer = mpGraphicsBufferManager->getBuffer( mPlayerIconBufferID );
	Sprite* pArrowSprite = NULL;
	if( pPlayerBuffer != NULL )
	{
		pArrowSprite = mpSpriteManager->createAndManageSprite( PLAYER_ICON_SPRITE_ID, pPlayerBuffer, 0, 0, pPlayerBuffer->getWidth(), pPlayerBuffer->getHeight() );
	}
	GraphicsBuffer* pAIBuffer = mpGraphicsBufferManager->getBuffer( mEnemyIconBufferID );
	Sprite* pEnemyArrow = NULL;
	if( pAIBuffer != NULL )
	{
		pEnemyArrow = mpSpriteManager->createAndManageSprite( AI_ICON_SPRITE_ID, pAIBuffer, 0, 0, pAIBuffer->getWidth(), pAIBuffer->getHeight() );
	}

	//setup units
	Vector2D pos( 0.0f, 0.0f );
	Vector2D vel( 0.0f, 0.0f );
	mpUnit = new KinematicUnit( pArrowSprite, pos, 1, vel, 0.0f, 200.0f, 10.0f );
	
	Vector2D pos2( 1000.0f, 500.0f );
	Vector2D vel2( 0.0f, 0.0f );
	mpAIUnit = new KinematicUnit( pEnemyArrow, pos2, 1, vel2, 0.0f, 180.0f, 100.0f );
	//give steering behavior
	mpAIUnit->dynamicArrive( mpUnit ); 

	Vector2D pos3( 500.0f, 500.0f );
	mpAIUnit2 = new KinematicUnit( pEnemyArrow, pos3, 1, vel2, 0.0f, 180.0f, 100.0f );
	//give steering behavior
	mpAIUnit2->dynamicSeek( mpUnit );  

	return true;
}
示例#15
0
// Construct state
menu::menu(){
  // Init vars
  startMove = false;
  startClicked = false;
  mouse_rocket_up = false;

  // Screen on
  mini_screen = MINISTATE_MENU;

  // Buffer
  buffer = al_create_bitmap( SCREEN_W, SCREEN_H);

  // Load intro image
  // Random menu
  img_menu = load_bitmap_ex( "images/backgrounds/background_" + convertIntToString(random( 0, 3)) + ".png");
  start = load_bitmap_ex( "images/gui/start.png");
  highscores_button = load_bitmap_ex( "images/gui/highscores.png");
  mouse = load_bitmap_ex( "images/gui/mouse.png");
  mouse_rocket = load_bitmap_ex( "images/gui/mouse_rocket.png");
  title = load_bitmap_ex( "images/gui/title.png");
  options = load_bitmap_ex( "images/gui/options.png");

  ui_sound[1] = load_bitmap_ex( "images/gui/ui_sound_on.png");
  ui_sound[0] = load_bitmap_ex( "images/gui/ui_sound_off.png");

  ui_music[1] = load_bitmap_ex( "images/gui/ui_music_on.png");
  ui_music[0] = load_bitmap_ex( "images/gui/ui_music_off.png");

  ui_window[1] = load_bitmap_ex( "images/gui/ui_window_windowed.png");
  ui_window[0] = load_bitmap_ex( "images/gui/ui_window_fullscreen.png");

  ui_particle[0] = load_bitmap_ex("images/gui/ui_particle_circle.png");
  ui_particle[1] = load_bitmap_ex("images/gui/ui_particle_square.png");
  ui_particle[2] = load_bitmap_ex("images/gui/ui_particle_pixel.png");
  ui_particle[3] = load_bitmap_ex("images/gui/ui_particle_off.png");

  ui_control[0] = load_bitmap_ex("images/gui/ui_control_xbox.png");
  ui_control[1] = load_bitmap_ex("images/gui/ui_control_keyboard.png");
  ui_control[2] = load_bitmap_ex("images/gui/ui_control_auto.png");

  ui_screenshake[0] = load_bitmap_ex("images/gui/ui_screenshake_none.png");
  ui_screenshake[1] = load_bitmap_ex("images/gui/ui_screenshake_low.png");
  ui_screenshake[2] = load_bitmap_ex("images/gui/ui_screenshake_medium.png");
  ui_screenshake[3] = load_bitmap_ex("images/gui/ui_screenshake_high.png");

  ui_options = load_bitmap_ex( "images/gui/ui_options.png");
  ui_options_small = load_bitmap_ex( "images/gui/ui_options_small.png");
  ui_back = load_bitmap_ex( "images/gui/ui_back.png");
  credits = load_bitmap_ex("images/gui/credits.png");
  ui_credits = load_bitmap_ex("images/gui/ui_credits.png");
  highscores_table = load_bitmap_ex("images/gui/highscores_table.png");
  ui_help = load_bitmap_ex("images/gui/ui_help.png");
  helpScreen = load_bitmap_ex("images/gui/helpScreen.png");
  ui_exit = load_bitmap_ex("images/gui/ui_exit.png");
  xbox_start = load_bitmap_ex("images/gui/xbox_start.png");
  ui_screenshot_notification = load_bitmap_ex("images/gui/ui_screenshot_notification.png");
  ui_controls = load_bitmap_ex("images/gui/ui_controls.png");
  controls = load_bitmap_ex("images/gui/controls.png");

  // Load that menu music
  music_mainmenu = load_sample_ex("audio/music_mainmenu.ogg");

  // Read settings from file
  read_settings();

  // Init animation vars
  animation_pos = 0;

  // Hide mouse
  al_hide_mouse_cursor( display);

  // Load scores
  updateScores( scores);

  // Play music
  if( settings[SETTING_MUSIC] == 1)
    al_play_sample( music_mainmenu, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_LOOP, &currentMusic);
}
示例#16
0
/* 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);
	}
}
示例#17
0
文件: info.c 项目: dos1/mediator
void Gamestate_Start(struct Game *game, struct dosowiskoResources* data) {
    data->tick = 0;
    al_grab_mouse(game->display);
    al_hide_mouse_cursor(game->display);
    al_play_sample_instance(data->sound);
}
示例#18
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;
}
示例#19
0
Framework::Framework()
{
#ifdef WRITE_LOG
  printf( "Framework: Startup\n" );
#endif

  // Init Allegro
	if( !al_init() )
	{
		return;
	}
	al_init_font_addon();
	if( !al_install_keyboard() || !al_install_mouse() || !al_init_primitives_addon() || !al_init_ttf_addon() || !al_init_image_addon() )
	{
		return;
	}
	if( al_install_joystick() )
  {
    al_reconfigure_joysticks();
  }

  audioInitialised = false;
  InitialiseAudioSystem();

  std::string selectedLanguage;
  quitProgram = false;
  ProgramStages = new StageStack();
  framesToProcess = 0;
  Settings = new ConfigFile( "settings.cfg" );

  eventQueue = al_create_event_queue();

  InitialiseDisplay();

	al_register_event_source( eventQueue, al_get_keyboard_event_source() );
	al_register_event_source( eventQueue, al_get_mouse_event_source() );

	fpsTimer = al_create_timer( 1.0 / (float)FRAMES_PER_SECOND );
	al_register_event_source( eventQueue, al_get_timer_event_source( fpsTimer ) );
	al_start_timer( fpsTimer );

	al_hide_mouse_cursor( displaySurface );


  imageMgr = new ImageManager( this );
  fontMgr = new FontManager( this );
  audioMgr = new AudioManager( this );
  int maxDownloads = 4;
  if( Settings->KeyExists( "Downloads.MaxConcurrentDownloads" ) )
  {
    Settings->GetIntegerValue( "Downloads.MaxConcurrentDownloads", &maxDownloads );
  }
  downloadMgr = new DownloadManager( this, maxDownloads );
  networkMgr = new NetworkManager( this );
  languageMgr = new LanguageManager();
  if( Settings->KeyExists( "Application.Language" ) )
  {
    Settings->GetStringValue( "Application.Language", &selectedLanguage );
    languageMgr->SetActiveLanguage( selectedLanguage );
  }

  NativePlatform = new Platform();

  SystemFramework = this;

  extraEventsMutex = al_create_mutex();
}
示例#20
0
int MonopolyGame::init() {

    // Now begin initializing the Allegro library.
    if(!al_init()) {
        fprintf(stderr, "Failed to initialize Allegro.\n");
        return -1;
    }

    if(!al_install_keyboard()) {
        fprintf(stderr, "Failed to initialize the Keyboard!\n");
        return -1;
    }

    m_alTimer = al_create_timer(1.0 / MAX_FPS);
    if(!m_alTimer) {
        fprintf(stderr, "Failed to create Timer!\n");
        return -1;
    }

    m_alFrameTimer = al_create_timer(1.0 / MAX_FRAME_FPS);
    if(!m_alFrameTimer) {
        fprintf(stderr, "Failed to create Timer!\n");
        al_destroy_timer(m_alTimer);
        return -1;
    }

    al_init_image_addon(); // Initialize the image addon.
    al_install_audio();
    al_init_acodec_addon();

    al_init_font_addon(); // Initialize the font addon.
    al_init_ttf_addon(); // Initialize the ttf (True Type Font) addon.

    // Setup the display device in windowed mode.
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    m_alDisplayDevice = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
    if(!m_alDisplayDevice) {
        fprintf(stderr, "Failed to create Display: %i x %i\n", WINDOW_WIDTH, WINDOW_HEIGHT);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    // Create an event queue. This is where timed events, etc are pulled from.
    m_alEventQueue = al_create_event_queue();
    if(!m_alEventQueue) {
        fprintf(stderr, "Failed to create Event Queue!\n");
        al_destroy_display(m_alDisplayDevice);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    if( !al_reserve_samples( MAX_NUM_SAMPLES ) ) {
        fprintf(stderr, "Failed to reserve the required sound instances!\n");
        al_destroy_display(m_alDisplayDevice);
        al_destroy_timer(m_alTimer);
        al_destroy_timer(m_alFrameTimer);
        return -1;
    }

    // Register an event source per input.
    al_register_event_source(m_alEventQueue, al_get_display_event_source(m_alDisplayDevice));
    al_register_event_source(m_alEventQueue, al_get_timer_event_source(m_alTimer));
    al_register_event_source(m_alEventQueue, al_get_timer_event_source(m_alFrameTimer));
    al_register_event_source(m_alEventQueue, al_get_keyboard_event_source());

    // Ensure the mouse cursor is not visible.
    al_hide_mouse_cursor(m_alDisplayDevice);

    // Set some default values for the camera.
    m_alCamera.cameraPosition[Positions::X_POS] = 0;
    m_alCamera.cameraPosition[Positions::Y_POS] = 0;

    return 0;
}
示例#21
0
void Renderer::run()
{
	NBT_Debug("begin");

	al_hide_mouse_cursor(dpy_);

	al_identity_transform(&camera_transform_);

	float x = -camera_pos_.x, y = -camera_pos_.y, z = -camera_pos_.z;
	//x = -dim0_->spawnX();
	//z = -dim0_->spawnZ();

	al_translate_transform_3d(&camera_transform_, x, y, z);

	al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, DEG_TO_RAD(180));

	memset(key_state_, 0, sizeof(key_state_) * sizeof(key_state_[0]));

	al_start_timer(tmr_);

	NBT_Debug("run!");

	//al_use_shader(nullptr);

	/*ALLEGRO_TRANSFORM trans;
	al_identity_transform(&trans);
	al_orthographic_transform(&trans, 0, 0, -1, al_get_display_width(dpy_), al_get_display_height(dpy_), 1);
	al_set_projection_transform(dpy_, &trans);
	al_identity_transform(&trans);
	al_use_transform(&trans);

	if(!resManager_->getAtlas()->getSheet(0)->alBitmap())
		NBT_Debug("no sheet bitmap????");
	*/
	//al_draw_bitmap(resManager_->getAtlas()->getSheet(0)->alBitmap(), 0, 0, 0);

	//al_flip_display();
	//sleep(10);

	bool redraw = false;
	bool doUpdateLookPos = false;
	bool cleared = false;
	
	while(1)
	{
		ALLEGRO_EVENT ev;
      al_wait_for_event(queue_, &ev);

      if(ev.type == ALLEGRO_EVENT_TIMER)
		{
         redraw = true;
			//cam_.rx = 1.0;
			float x = 0.0, y = 0.0, z = 0.0;
			float translate_diff = 0.3;
			float ry = 0.0;
			float rotate_diff = 0.04;
			bool changeTranslation = false;
			bool changeRotation = false;

			if(key_state_[ALLEGRO_KEY_W])
			{
				z += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_S])
			{
				z -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_A])
			{
				x += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_D])
			{
				x -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_SPACE])
			{
				y -= translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_LSHIFT])
			{
				y += translate_diff;
				changeTranslation = true;
			}

			if(key_state_[ALLEGRO_KEY_LEFT])
			{
				ry += rotate_diff;
				changeRotation = true;
			}

			if(key_state_[ALLEGRO_KEY_RIGHT])
			{
				ry -= rotate_diff;
				changeRotation = true;
			}

			if(changeTranslation)
			{
				//camera_pos_.translate(x, y, z);
				al_translate_transform_3d(&camera_transform_, x, y, z);
				doUpdateLookPos = true;
			}

			if(changeRotation)
			{
				al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, ry);
				doUpdateLookPos = true;
			}

			if(doUpdateLookPos)
				updateLookPos();

      }
      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			NBT_Debug("display close");
         break;
      }
      else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			//NBT_Debug("key down");
			//NBT_Debug("pos: %fx%f", -camera_transform_.m[2][0], -camera_transform_.m[2][2]);
			key_state_[ev.keyboard.keycode] = true;

			if (ev.keyboard.keycode == ALLEGRO_KEY_Q)
			{
				break;
			}
			else if(ev.keyboard.keycode == ALLEGRO_KEY_C)
			{
				NBT_Debug("CLEAR CHUNKS");
				glBindVertexArray(vao_);
				for(auto ch: chunkData_)
				{
					delete ch.second;
				}
				glBindVertexArray(0);
				chunkData_.clear();

				glDeleteBuffers(1, &vao_);
				
				cleared = true;
			}
			else if (ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
			{
				grab_mouse_ = !grab_mouse_;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			//NBT_Debug("pos: %fx%f", -camera_transform_.m[2][0], -camera_transform_.m[2][2]);
			key_state_[ev.keyboard.keycode] = false;
		}
		else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
		{
				grab_mouse_ = true;
		}
		else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES && grab_mouse_)
		{
			float dx = ev.mouse.dx, dy = ev.mouse.dy;

			if(dy > 0 && dy < 1.5)
				dy = 0.0;

			if(dy < 0 && dy > -1.5)
				dy = 0.0;

			if(dx > 0 && dx < 1.5)
				dy = 0.0;

			if(dx < 0 && dx > -1.5)
				dx = 0.0;

			float ry = dx / al_get_display_width(dpy_), rx = dy / al_get_display_height(dpy_);

			rx_look += rx;
			al_rotate_transform_3d(&camera_transform_, 0.0, 1.0, 0.0, ry);
//			al_rotate_transform_3d(&camera_transform_, 1.0, 0.0, 0.0, rx);

			//cam_.rx += dy / al_get_display_height(dpy_);

			al_set_mouse_xy(dpy_, al_get_display_width(dpy_)/2.0, al_get_display_height(dpy_)/2.0);

			doUpdateLookPos = true;
		}

      if(redraw && al_is_event_queue_empty(queue_))
		{
			if(!loadChunkQueue.empty())
			{
				NBT_Debug("%i chunks to load", loadChunkQueue.size());

				std::pair<int32_t, int32_t> pos = loadChunkQueue.front();
				loadChunkQueue.pop();

				processChunk(pos.first, pos.second);
			}
			else
			{
				if(!cleared)
				{
					//NBT_Debug("pos: %fx%fx%f", camera_pos_.getX(), camera_pos_.getZ(), camera_pos_.getY());
					autoLoadChunks(camera_pos_.getX() / 16.0, camera_pos_.getZ() / 16.0);
				}
			}

			ALLEGRO_STATE state;
			al_store_state(&state, ALLEGRO_STATE_ALL);
			al_set_projection_transform(dpy_, &al_proj_transform_);

			glClear(GL_DEPTH_BUFFER_BIT);

         redraw = false;
			al_clear_to_color(al_map_rgb(255,255,255));
         draw();

			al_restore_state(&state);
			al_set_projection_transform(dpy_, &al_proj_transform_);

			drawHud();

			al_restore_state(&state);
         al_flip_display();
      }


	}

	NBT_Debug("stop timer");
	al_stop_timer(tmr_);

	NBT_Debug("end");


	NBT_Debug("sizeof GL_FLOAT: %i", sizeof(GLfloat));
}
示例#22
0
/* the main game logic function */
void dot_game_logic(void * data)
{
	APP_INSTANCE * app = (APP_INSTANCE *)data;

	int colored = 0;
	float rgb = 1.0;
	int i, m;

	/* handle level bg color transition */
	if(app->game.bg_color_fade < 1.0)
	{
		app->game.bg_color_fade += 1.0 / 60.0;
		if(app->game.bg_color_fade > 1.0)
		{
			app->game.bg_color_fade = 1.0;
		}
	}

	/* make level colors darker after every 10 levels */
	m = app->game.level / 10;
	for(i = 0; i < m; i++)
	{
		rgb *= 0.75;
	}
	app->game.bg_color = dot_darken_color(dot_transition_color(app->game.old_bg_color, app->level_color[app->game.level % 10], app->game.bg_color_fade), rgb);

	dot_game_emo_logic(data);
	dot_bg_objects_logic(data, app->game.speed);
	switch(app->game.state)
	{

		/* balls move slow for a few seconds so player can get ready */
		case DOT_GAME_STATE_START:
		{
			app->game.state_tick++;
			if(app->touch_id >= 0)
			{
				if(app->touch_x >= DOT_GAME_TOUCH_START_X && app->touch_x < DOT_GAME_TOUCH_END_X && app->touch_y >= DOT_GAME_TOUCH_START_Y && app->touch_y < DOT_GAME_TOUCH_END_Y)
				{
					t3f_play_sample(app->sample[DOT_SAMPLE_GO], 1.0, 0.0, 1.0);
					app->game.state = DOT_GAME_STATE_PLAY;
					app->game.state_tick = 0;
					app->game.player.lost_touch = false;
					app->game.player.ball.active = true;
					app->game.player.want_shield = true;
					app->game.player.touch_offset_x = 0;
					app->game.player.touch_offset_y = 0;
					app->game.level_start = false;
					al_hide_mouse_cursor(t3f_display);
				}
			}

			/* handle ball logic */
			colored = dot_game_move_balls(data);
			break;
		}

		case DOT_GAME_STATE_PAUSE:
		{
			if(app->touch_id >= 0 && t3f_distance(app->touch_x, app->touch_y, app->game.player.ball.x, app->game.player.ball.y) < DOT_GAME_GRAB_SPOT_SIZE)
			{
				app->game.player.touch_offset_x = app->game.player.ball.x - app->touch_x;
				app->game.player.touch_offset_y = app->game.player.ball.y - app->touch_y;
				app->game.state = DOT_GAME_STATE_PLAY;
				al_hide_mouse_cursor(t3f_display);
			}
			break;
		}

		case DOT_GAME_STATE_DONE:
		{
			for(i = 0; i < DOT_MAX_PARTICLES; i++)
			{
				if(app->particle[i].active)
				{
					break;
				}
			}
			if(i == DOT_MAX_PARTICLES)
			{
				dot_game_exit(data);
			}
			break;
		}

		/* normal game state */
		default:
		{
			/* handle shield logic */
			dot_game_shield_logic(data);

			/* move player */
			dot_game_move_player(data);

			/* handle ball logic */
			colored = dot_game_move_balls(data);

			dot_game_check_player_collisions(data);

			/* move on to next level */
			if(colored == 0)
			{
				dot_game_accumulate_score(data);
				for(i = 0; i < DOT_GAME_MAX_BALLS; i++)
				{
					if(app->game.ball[i].active && app->game.ball[i].type == 6)
					{
						dot_game_create_splash_effect(data, app->game.ball[i].x, app->game.ball[i].y, app->game.ball[i].r, app->dot_color[app->game.ball[i].type]);
					}
				}
				if(app->touch_id >= 0)
				{
					t3f_touch[app->touch_id].active = false;
				}
				al_show_mouse_cursor(t3f_display);
				app->game.old_bg_color = app->game.bg_color;
				dot_game_setup_level(data, app->game.level + 1);
				app->game.bg_color_fade = 0.0;
				app->game.combo = 0;
				app->game.shield.active = false;
			}
			break;
		}
	}
	if(t3f_key[ALLEGRO_KEY_ESCAPE] || t3f_key[ALLEGRO_KEY_BACK])
	{
		dot_intro_setup(data);
		app->state = DOT_STATE_INTRO;
		if(app->music_enabled)
		{
			t3f_play_music(DOT_MUSIC_TITLE);
		}
		t3f_key[ALLEGRO_KEY_ESCAPE] = 0;
		t3f_key[ALLEGRO_KEY_BACK] = 0;
	}
	app->game.tick++;
}
示例#23
0
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *cursor;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   ALLEGRO_FONT *font;
   int mx = 0;
   int my = 0;
   int mz = 0;
   int mw = 0;
   int mmx = 0;
   int mmy = 0;
   int mmz = 0;
   int mmw = 0;
   bool in = true;
   bool buttons[NUM_BUTTONS] = {false};
   int i;
   float p = 0.0;
   ALLEGRO_COLOR black;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }

   al_init_primitives_addon();
   al_install_mouse();
   al_install_keyboard();
   al_init_image_addon();
   al_init_font_addon();
   
   actual_buttons = al_get_mouse_num_buttons();
   if (actual_buttons > NUM_BUTTONS)
      actual_buttons = NUM_BUTTONS;

   al_set_new_display_flags(ALLEGRO_RESIZABLE);
   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Error creating display\n");
   }

   al_hide_mouse_cursor(display);

   cursor = al_load_bitmap("data/cursor.tga");
   if (!cursor) {
      abort_example("Error loading cursor.tga\n");
   }

   font = al_load_font("data/fixed_font.tga", 1, 0);
   if (!font) {
      abort_example("data/fixed_font.tga not found\n");
   }
   
   black = al_map_rgb_f(0, 0, 0);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));

   while (1) {
      if (al_is_event_queue_empty(queue)) {
         al_clear_to_color(al_map_rgb(0xff, 0xff, 0xc0));
         for (i = 0; i < actual_buttons; i++) {
            draw_mouse_button(i, buttons[i]);
         }
         al_draw_bitmap(cursor, mx, my, 0);
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
         al_draw_textf(font, black, 5, 5, 0, "dx %i, dy %i, dz %i, dw %i", mmx, mmy, mmz, mmw);
         al_draw_textf(font, black, 5, 25, 0, "x %i, y %i, z %i, w %i", mx, my, mz, mw);
         al_draw_textf(font, black, 5, 45, 0, "p = %g", p);
         al_draw_textf(font, black, 5, 65, 0, "%s", in ? "in" : "out");
         al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
         mmx = mmy = mmz = 0;
         al_flip_display();
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_MOUSE_AXES:
            mx = event.mouse.x;
            my = event.mouse.y;
            mz = event.mouse.z;
            mw = event.mouse.w;
            mmx = event.mouse.dx;
            mmy = event.mouse.dy;
            mmz = event.mouse.dz;
            mmw = event.mouse.dw;
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            if (event.mouse.button-1 < NUM_BUTTONS) {
               buttons[event.mouse.button-1] = true;
            }
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            if (event.mouse.button-1 < NUM_BUTTONS) {
               buttons[event.mouse.button-1] = false;
            }
            p = event.mouse.pressure;
            break;

         case ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY:
            in = true;
            break;

         case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
            in = false;
            break;

         case ALLEGRO_EVENT_KEY_DOWN:
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
               goto done;
            }
            break;

         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            goto done;
      }
   }

done:

   al_destroy_event_queue(queue);

   return 0;
}
示例#24
0
文件: mouse.c 项目: sanikoyes/tools
static int allua_mouse_hide_cursor(lua_State * L)
{
   ALLUA_display display = allua_check_display(L, 1);
   lua_pushboolean(L, al_hide_mouse_cursor(display));
   return 1;
}
示例#25
0
int main(void)
{
    bool done = false; // Variavel booleana para identificar se o programa terminou de ser executado
    bool redraw = true; // Enquanto essa variavel for verdadeira, ira ser desenhado algo na tela
    bool desenha = true;
    int draw[5]= {0, 0, 0, 0, 0};
    int pos_x = WIDTH / 2;
    int pos_y = HEIGHT / 2;
    int timer_tiros = 0;
    int timer_energy = 0;
    int timer_heats = 0;
    int timer_tamenho_heat = 0;
    int timer_componente = 0;
    int count = 0;


    Gamer(gamer);
    Zone zone[LINHAS][COLUNAS];
    Bullet bullets[NUM_BULLETS+1];
    Energy energy[NUM_ENERGYS+1];
    Heat heats[NUM_HEAT+1];
    Zombie zombie[NUM_ZOMBIES];
    Battery battery[NUM_BATTERY];


    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;
    ALLEGRO_FONT *font18 = NULL;
    ALLEGRO_FONT *font_maior = NULL;
    ALLEGRO_BITMAP *resistor = NULL;
    ALLEGRO_BITMAP *capacitor = NULL;
    ALLEGRO_BITMAP *indutor = NULL;
    ALLEGRO_BITMAP *diodo = NULL;
    ALLEGRO_BITMAP *bateria = NULL;
    ALLEGRO_BITMAP *protoboard = NULL;
    ALLEGRO_BITMAP *fogo = NULL;
    ALLEGRO_BITMAP *zombie_bitmap = NULL;
    ALLEGRO_BITMAP *ataque_eletromagnetico = NULL;
    ALLEGRO_BITMAP *energia_capacitor = NULL;
    ALLEGRO_BITMAP *logo = NULL;


    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();
    al_install_mouse();
    al_init_image_addon();

    resistor = al_load_bitmap("Resistor.png");
    capacitor = al_load_bitmap("Capacitor.png");
    indutor = al_load_bitmap("Indutor.png");
    diodo = al_load_bitmap("Diodo.png");
    bateria = al_load_bitmap("Bateria.png");
    protoboard = al_load_bitmap("Protoboard.png");
    fogo = al_load_bitmap("fogo_resistor/fire1.png");
    zombie_bitmap = al_load_bitmap("Zombie.png");
    ataque_eletromagnetico = al_load_bitmap("eletromagnetismo.jpg");
    energia_capacitor = al_load_bitmap("energia_capacitor.png");
    logo = al_load_bitmap("logo_EvsZ.jpg");

    al_convert_mask_to_alpha(resistor, al_map_rgb(255, 0, 255));
    al_convert_mask_to_alpha(capacitor, al_map_rgb(255, 0, 255));
    al_convert_mask_to_alpha(indutor, al_map_rgb(255, 0, 255));
    al_convert_mask_to_alpha(diodo, al_map_rgb(255, 0, 255));
    al_convert_mask_to_alpha(bateria, al_map_rgb(255, 0, 255));
    al_convert_mask_to_alpha(zombie_bitmap, al_map_rgb(255, 255, 255));
    al_convert_mask_to_alpha(ataque_eletromagnetico, al_map_rgb(255, 255, 255));


    event_queue = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);

    InitGamer(gamer);
    InitZone(zone, LINHAS, COLUNAS);
    InitBullet(bullets, NUM_BULLETS+1);
    InitHeat(heats, NUM_HEAT+1);
    InitZombie(zombie, NUM_ZOMBIES);
    InitEnergy(energy, NUM_ENERGYS+1);
    InitBattery(battery, NUM_BATTERY);

    font18 = al_load_font("arial.ttf", 18, 0);
    font_maior = al_load_font("arial.ttf", 24, 0);

    al_register_event_source(event_queue, al_get_mouse_event_source());
    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_hide_mouse_cursor(display);
    al_start_timer(timer);

    while(!done)
    {
        ALLEGRO_EVENT ev;
/*===============================================================================================================================================*/
        if(state == MENU)
        {
            al_wait_for_event(event_queue, &ev);

            al_draw_bitmap(logo, WIDTH / 2 - 145, HEIGHT - 500, 0);
            al_draw_text(font18, al_map_rgb(255, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Os Zombies querem roubar seu diploma, proteja-o");
            al_draw_text(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2 + 100, ALLEGRO_ALIGN_CENTRE, "Pressione Space para jogar");
            al_draw_text(font_maior, al_map_rgb(0, 255, 0), WIDTH / 2, HEIGHT / 2 + 150, ALLEGRO_ALIGN_CENTRE, "Tecla 1 = Resistor Tecla 2 = Capacitor  Tecla 3 = Indutor  Tecla 4 = Diodo");
            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
                if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE)
                    state = PLAYING;

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
                done = true;

            al_flip_display();

        }
/*===============================================================================================================================================*/
        if(state == PLAYING)
        {
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
                done = true;

            if(ev.type == ALLEGRO_EVENT_TIMER)
            {
                redraw = true;


                    for(int i = 0; i < LINHAS; i++)
                        for(int j=0; j<COLUNAS; j++)
                            if(zone[i][j].x < pos_x &&
                                    zone[i][j].x + ZONEX > pos_x &&
                                    zone[i][j].y < pos_y &&
                                    zone[i][j].y + ZONEY > pos_y)
                                if(desenha)
                                    if(zone[i][j].draw == 0)
                                    {
                                        if(keys[KEY_1] && gamer.energy >= 100)
                                        {
                                            zone[i][j].draw = draw[1];
                                            gamer.energy -=100;
                                            draw[1] = 0;
                                        }
                                        if(keys[KEY_2] && gamer.energy >= 50)
                                        {
                                            zone[i][j].draw = draw[2];
                                            gamer.energy -=50;
                                            draw[2] = 0;
                                        }
                                        if(keys[KEY_3] && gamer.energy >= 100)
                                        {
                                            zone[i][j].draw = draw[3];
                                            gamer.energy -=100;
                                            draw[3] = 0;
                                        }
                                        if(keys[KEY_4] && gamer.energy >= 100)
                                        {
                                            zone[i][j].draw = draw[4];
                                            gamer.energy -=100;
                                            draw[4] = 0;
                                        }
                                    }
                timer_battery_speed++;
                timer_battery_start++;
                if(timer_battery_start >= 360) // diminui a frequencia com que nasce uma bateria nova
                {
                    StartBattery(battery, NUM_BATTERY);
                    timer_battery_start = 0;
                }

                if(timer_battery_speed >= 2) // reduz um pouco a velocidade da bateria
                {
                    UpdateBattery(battery, NUM_BATTERY);
                    timer_battery_speed = 0;
                }


                timer_heats++;

                for(int i=0; i<LINHAS; i++)
                    for(int j=0; j<COLUNAS; j++)
                        if(zone[i][j].draw == 1)
                            if(timer_heats >= 200)
                            {
                                FireHeat(heats, NUM_HEAT+1, zone);
                                timer_heats = 0;
                            }

                timer_energy++;
                timer_energy_cap_death++;

                for(int i=0; i<LINHAS; i++)
                    for(int j=0; j<COLUNAS; j++)
                        if(zone[i][j].draw == 2)
                        {
                            if(timer_energy >= 420)
                            {
                                CreateEnergy(energy, NUM_ENERGYS+1, zone);
                                timer_energy = 0;
                            }

                        }

                timer_tiros++;

                for(int i=0; i<LINHAS; i++)
                    for(int j=0; j<COLUNAS; j++)
                        if(zone[i][j].draw == 3)
                            if(timer_tiros >= 200) // faz os Electronics atirarem numa velocidade constante
                            {
                                FireBullet(bullets, NUM_BULLETS+1, zone);
                                timer_tiros = 0;
                            }
                timer_zombie_start++;
                timer_zombie_speed++;
                timer_dificuldade++;
                if(timer_zombie_start >= 3)
                {
                    StartZombie(zombie, NUM_ZOMBIES);
                    timer_zombie_start = 0;
                }
                if(dificuldade >20 && dificuldade <=500)
                {
                if(timer_dificuldade >= 300)
                    {
                        dificuldade -= 30;
                        timer_dificuldade = 0;
                    }
                }
                if(timer_zombie_speed >= 3)
                {
                    UpdateZombie(zombie, NUM_ZOMBIES);
                    timer_zombie_speed = 0;
                }


                UpdateBullet(bullets, NUM_BULLETS+1);
                CollideBullet(bullets, NUM_BULLETS, zombie, NUM_ZOMBIES, gamer);
                CollideHeat(heats, NUM_HEAT, zombie, NUM_ZOMBIES, gamer, timer_tamenho_heat);
                CollideZone(zone, LINHAS, COLUNAS, zombie, NUM_ZOMBIES);
                CollideZoneDiodo(zone, LINHAS, COLUNAS, zombie, NUM_ZOMBIES);


                for(int i = 0; i < NUM_ENERGYS; i++)
                    if(energy[i].live)
                        if(energy[i].x - energy[i].boundx < pos_x &&
                                energy[i].x + energy[i].boundx > pos_x &&
                                energy[i].y - energy[i].boundy < pos_y &&
                                energy[i].y + energy[i].boundy > pos_y)
                        {
                            energy[i].live = false;
                            gamer.energy += 25;
                        }


            }
            else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_ESCAPE:
                    done = true;
                    break;
                case ALLEGRO_KEY_1:
                    keys[KEY_1] = true;
                    break;
                case ALLEGRO_KEY_2:
                    keys[KEY_2] = true;
                    break;
                case ALLEGRO_KEY_3:
                    keys[KEY_3] = true;
                    break;
                case ALLEGRO_KEY_4:
                    keys[KEY_4] = true;
                    break;
                }
            }
            else if(ev.type == ALLEGRO_EVENT_KEY_UP)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_ESCAPE:
                    done = true;
                    break;
                case ALLEGRO_KEY_1:
                    keys[KEY_1] = false;
                    break;
                case ALLEGRO_KEY_2:
                    keys[KEY_2] = false;
                    break;
                case ALLEGRO_KEY_3:
                    keys[KEY_3] = false;
                    break;
                case ALLEGRO_KEY_4:
                    keys[KEY_4] = false;
                    break;
                }
            }
            else if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
            {
                if (ev.mouse.button & 2)
                    done = true;
            }
            else if(ev.type == ALLEGRO_EVENT_MOUSE_AXES)
            {
                pos_x = ev.mouse.x;
                pos_y = ev.mouse.y;
                CaptureBattery(battery, NUM_BATTERY, ev.mouse.x, ev.mouse.y, gamer);
            }

            timer_componente++;

            if(timer_componente >= 10)
            {
                if(keys[KEY_1])
                    draw[1] = 1;
                if(keys[KEY_2])
                    draw[2] = 2;
                if(keys[KEY_3])
                    draw[3] = 3;
                if(keys[KEY_4])
                    draw[4] = 4;
            }

            if(redraw && al_is_event_queue_empty(event_queue))
            {
                redraw = false;


                DrawZone(zone, LINHAS, COLUNAS, resistor, capacitor, indutor, diodo);
                DrawBullet(bullets, NUM_BULLETS+1, ataque_eletromagnetico);
                DrawEnergy(energy, NUM_ENERGYS+1, energia_capacitor);
                DrawZombie(zombie, NUM_ZOMBIES, zombie_bitmap);
                DrawBattery(battery, NUM_BATTERY, bateria);
                timer_tamenho_heat++;
                DrawHeat(heats, NUM_HEAT+1, timer_tamenho_heat, fogo);
                if(timer_tamenho_heat > 80)
                    for(int i=0; i<NUM_HEAT; i++)
                    {
                        heats[i].live = false;
                        timer_tamenho_heat = 0;
                    }


                al_draw_filled_rectangle(pos_x, pos_y, pos_x + 10, pos_y + 10, al_map_rgb(0, 0, 0));
                count++;
                al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/16, 85, 0, "Time: %i", count/60);
                al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/300, 85, 0, "Energy: %i", gamer.energy);
                al_draw_textf(font18, al_map_rgb(255, 0, 0), WIDTH*13/25, 85, 0, "Score: %i", gamer.score);
                al_flip_display();
                al_draw_bitmap(protoboard, 0, 0, 0);
            }

        }
    /*================================================================================================================================================*/
        if(state == GAMEOVER)
        {
            al_wait_for_event(event_queue, &ev);
            al_clear_to_color(al_map_rgb(0,0,0));
            al_draw_text(font18, al_map_rgb(255, 168, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Os Zombies roubaram seu diploma");
            al_draw_text(font18, al_map_rgb(255, 255, 255), WIDTH / 2, HEIGHT / 2 +40, ALLEGRO_ALIGN_CENTRE, "Pressione Space para sair");
            al_draw_textf(font_maior, al_map_rgb(255, 0, 0), WIDTH*13/28, 85, 0, "Score: %i", gamer.score);
            al_flip_display();

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
                done = true;

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
                if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE)
            {
                al_destroy_event_queue(event_queue);
                al_destroy_timer(timer);
                al_destroy_font(font18);
                al_destroy_bitmap(resistor);
                al_destroy_bitmap(capacitor);
                al_destroy_bitmap(indutor);
                al_destroy_bitmap(diodo);
                al_destroy_bitmap(bateria);
                al_destroy_bitmap(protoboard);
                al_destroy_bitmap(zombie_bitmap);
                al_destroy_display(display);

            }




        }
    }


    return 0;
}
示例#26
0
 // API --------------------------------------------------------------------
 v8::Handle<v8::Value> hide(const v8::Arguments& args) {
     al_hide_mouse_cursor(Game::allegro.display);
     return v8::Undefined();
 }
/*
 * Open up the mouse device.
 */
static int mallegro_Open(MOUSEDEVICE *pmd)
{
  al_hide_mouse_cursor(display); //here, or two mouse cursors
      
  return 1; //return -2; //no mouse
}
示例#28
0
int main(void)
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *cursor;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   ALLEGRO_FONT *font;
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT touch_events[MAX_TOUCHES];
   int touch = 0;
   bool in = true;
   bool down = false;
   int i;
   
   memset(touch_events, 0, sizeof(touch_events));
   
   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
      return 1;
   }

   al_install_mouse();
   al_init_image_addon();
   al_init_font_addon();

   display = al_create_display(480, 320);
   if (!display) {
      abort_example("Error creating display\n");
      return 1;
   }

   al_hide_mouse_cursor();

   cursor = al_load_bitmap("data/cursor.tga");
   if (!cursor) {
      abort_example("Error loading cursor.tga\n");
      return 1;
   }

   font = al_load_font("data/fixed_font.tga", 1, 0);
   if (!font) {
      abort_example("data/fixed_font.tga not found\n");
      return 1;
   }

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));
   
   timer = al_install_timer(1/10.0);
   al_register_event_source(queue, al_get_timer_event_source(timer));
   al_start_timer(timer);

   while (1) {
      al_wait_for_event(queue, &event);
         switch (event.type) {
         case ALLEGRO_EVENT_MOUSE_AXES:
            touch_events[touch] = event;
            touch++;
            touch %= MAX_TOUCHES;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            down = true;
            break;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            down = false;
            break;

         case ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY:
            in = true;
            break;

         case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
            in = false;
            break;

         case ALLEGRO_EVENT_TIMER:
            al_clear_to_color(al_map_rgb(0xff, 0xff, 0xc0));
            if (down) {
               for (i = 0; i < MAX_TOUCHES; i++) {
                  al_draw_bitmap(cursor, touch_events[i].mouse.x, touch_events[i].mouse.y, 0);
               }
            }
            al_flip_display();
            break;
               
         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            goto done;
         }
   }

done:

   al_destroy_event_queue(queue);

   return 0;
}
int main(int argc, char **argv )
{
	//inits
    al_init();
    al_init_ttf_addon();
    al_install_keyboard();
    al_install_mouse();
    al_install_audio();
    al_init_acodec_addon();
    al_init_primitives_addon();
    al_reserve_samples(1000);
    al_init_image_addon();
    ALLEGRO_KEYBOARD_STATE key;
    ALLEGRO_MOUSE_STATE mouse;
    
    ALLEGRO_DISPLAY *display;
    al_set_new_display_flags(ALLEGRO_WINDOWED);
    
    display = al_create_display(1024, 768);
    
    al_hide_mouse_cursor(display);

	//
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer = NULL;
    bool redraw = true;
    timer = al_create_timer(1.0/fps);
    event_queue = al_create_event_queue();
    
    //SAMPLES
    
    
    ///OBJECTS
    cPlayer oPlayer;
    oPlayer.create();
    
    cLevel oLevel;
    oLevel.init();
    
    ////
    al_clear_to_color(al_map_rgb(0,0,0));
    al_flip_display();
    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);
    al_reserve_samples(1000);
    
    //RUN
    while(1<2)
    {  
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);
        al_get_keyboard_state(&key);
        al_get_mouse_state(&mouse);
        al_get_mouse_state_axis(&mouse,0);
        al_get_mouse_state_axis(&mouse,1);
        if(ev.type == ALLEGRO_EVENT_TIMER)
        {
			
			//Runny tunny
			{
				oLevel.createLevel();
				oPlayer.run(&key);
				//player collision check
				for(int i = 0;i<oLevel.blocknum;i++)
				{
					oPlayer.checkCollision(oLevel.oBlock[i].x,oLevel.oBlock[i].y,&key);
				}
				if(al_key_down(&key,ALLEGRO_KEY_ESCAPE))
				{
					return 0;
				}
			
			
			}
            redraw = true;
        }
        else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            break;   
        }
        if(redraw && al_is_event_queue_empty(event_queue))
        {
			//draw
			al_clear_to_color(al_map_rgb(0,0,0));
		
			oPlayer.draw();
			oLevel.draw();
			//////
		
            redraw = false;
            //
            al_flip_display();
        }
    }
    return 0;
};
示例#30
0
// Update loop
void menu::update(){
  //Menu animations
  if( animation_pos < 100 && !startClicked)
    animation_pos += 4;
  if( animation_pos > 0 && startClicked)
    animation_pos -= 4;

  // Start the game
  if( startClicked && animation_pos <= 0)
    set_next_state( STATE_GAME);

  // Open submenu or start game
  if( mini_screen == MINISTATE_MENU){
    // Start game with controller
    if( joystickListener::buttonPressed[JOY_XBOX_START] || joystickListener::buttonPressed[JOY_XBOX_A]){
      startClicked = true;
    }
    // Buttons
    if( mouseListener::mouse_pressed & 1){
      // Start game
      if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 40, 40 + al_get_bitmap_width(start), mouseListener::mouse_y, mouseListener::mouse_y, 410, 410 + al_get_bitmap_height(start))){
        startClicked = true;
      }
      // Scores
      else if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 660, 660 + al_get_bitmap_width(highscores_button), mouseListener::mouse_y, mouseListener::mouse_y, 30, 30 + al_get_bitmap_height(highscores_button))){
        updateScores( scores);
        mini_screen = MINISTATE_SCORES;
      }
      // Credits menu
      else if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 542, 644, mouseListener::mouse_y, mouseListener::mouse_y, 548, 600)){
        mini_screen = MINISTATE_CREDITS;
      }
      // Controls menu
      else if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 644, 696, mouseListener::mouse_y, mouseListener::mouse_y, 548 ,600)){
        mini_screen = MINISTATE_CONTROLS;
      }
      // Help screen
      else if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 696, 749, mouseListener::mouse_y, mouseListener::mouse_y, 548, 600)){
        mini_screen = MINISTATE_TUTORIAL;
      }
      // Options menu
      else if( collision( mouseListener::mouse_x, mouseListener::mouse_x, 749, 800, mouseListener::mouse_y, mouseListener::mouse_y, 548, 600)){
        mini_screen = MINISTATE_OPTIONS;
      }
    }
  }
  // Exit menus
  else if( mini_screen == MINISTATE_TUTORIAL || mini_screen == MINISTATE_CREDITS || mini_screen == MINISTATE_CONTROLS || mini_screen == MINISTATE_SCORES ){
    if( keyListener::lastKeyPressed != -1  || mouseListener::mouse_pressed & 1 || joystickListener::lastButtonPressed != -1){
			mini_screen = MINISTATE_MENU;
			draw();
    }
  }
  // Options
  else if( mini_screen == MINISTATE_OPTIONS && mouseListener::mouse_pressed & 1){
    // Particles toggle
    if( collision( 280, 360, mouseListener::mouse_x, mouseListener::mouse_x, 400, 480, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_PARTICLE_TYPE] = (settings[SETTING_PARTICLE_TYPE] + 1) % 4;
    }
    // Sound button toggle
    else if( collision( 120, 200, mouseListener::mouse_x, mouseListener::mouse_x, 180, 260, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_SOUND] = (settings[SETTING_SOUND] + 1) % 2;
    }
    // Music button toggle
    else if( collision( 280, 360, mouseListener::mouse_x, mouseListener::mouse_x, 180, 260, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_MUSIC] = (settings[SETTING_MUSIC] + 1) % 2;
      if( settings[SETTING_MUSIC] == 0)
        al_stop_sample( &currentMusic);
      else
        al_play_sample( music_mainmenu, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, &currentMusic);

    }
    // Fullscreen toggle
    else if( collision( 120, 200, mouseListener::mouse_x, mouseListener::mouse_x, 400, 480, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_FULLSCREEN] = (settings[SETTING_FULLSCREEN] + 1) % 2;

      if( settings[SETTING_FULLSCREEN]){
        // Fullscreen stuff
        al_destroy_display( display);
        al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
        display = al_create_display( SCREEN_W, SCREEN_H);

        ALLEGRO_DISPLAY_MODE disp_data;
        al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);
        float sx = disp_data.width / (float)SCREEN_W;
        float sy = disp_data.height / (float)SCREEN_H;

        ALLEGRO_TRANSFORM trans;
        al_identity_transform(&trans);
        al_scale_transform(&trans, sx, sy);
        al_use_transform(&trans);
        al_hide_mouse_cursor( display);
      }
      else{
        al_destroy_display( display);
        al_set_new_display_flags(ALLEGRO_WINDOWED);
        display = al_create_display( SCREEN_W, SCREEN_H);
        al_hide_mouse_cursor( display);
      }
    }
    //Screen shake
    else if( collision( 280, 360, mouseListener::mouse_x, mouseListener::mouse_x, 290, 370, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_SCREENSHAKE] = (settings[SETTING_SCREENSHAKE] + 1) % 4;
    }
    // Control Toggle
    else if( collision( 120, 200, mouseListener::mouse_x, mouseListener::mouse_x, 290, 370, mouseListener::mouse_y, mouseListener::mouse_y)){
      settings[SETTING_CONTROLMODE] = ((settings[SETTING_CONTROLMODE] + 1) % 3);
    }
    // Power off
    else if( collision( 540, 620, mouseListener::mouse_x, mouseListener::mouse_x, 180, 260, mouseListener::mouse_y, mouseListener::mouse_y)){
      write_settings();
      set_next_state( STATE_EXIT);
    }
    // Exit menu
    else if( collision( 540, 620, mouseListener::mouse_x, mouseListener::mouse_x, 407, 487, mouseListener::mouse_y, mouseListener::mouse_y)){
      mini_screen = MINISTATE_MENU;
      write_settings();
    }
  }

  // Update mouse particles
  if( settings[SETTING_PARTICLE_TYPE] != 3 && mouse_rocket_up){
    for( int i = 0; i < 500; i++){
      if( random( 1, 10) == 1){
        ALLEGRO_COLOR part_color = al_map_rgb( 255, random(0,255), 0);
        if( settings[SETTING_CHRISTMAS]){
          int red_or_green = random( 0, 1) * 255;
          part_color = al_map_rgb( red_or_green, 255 - red_or_green, 0);
        }
        particle newParticle( mouseListener::mouse_x, mouseListener::mouse_y + 16, part_color, random( -2, 2), random( 8, 20), 1, settings[SETTING_PARTICLE_TYPE]);
        mousePart.push_back( newParticle);
      }
    }
  }
  for( unsigned int i = 0; i < mousePart.size(); i++){
    mousePart.at(i).logic();
    if( random( 0, 10) == 0)
      mousePart.erase( mousePart.begin() + i);
  }

  // Close game
  if( keyListener::key[ALLEGRO_KEY_ESCAPE])
    set_next_state( STATE_EXIT);

  // Check if mouse is going up
  mouse_rocket_up = ( mouseListener::mouse_y < mouseMove);
  mouseMove = mouseListener::mouse_y;
}