Beispiel #1
0
void doMouse()
{
    al_get_mouse_state(&mouse);
    al_get_keyboard_state(&keyboard);
    int32_t keymod = getKeyMods(&keyboard);

    Interface::get().readMouse(mouse);

    char stepsize = ((keymod&ALLEGRO_KEYMOD_SHIFT) ? MAPNAVIGATIONSTEPBIG : MAPNAVIGATIONSTEP);
    //mouse_callback = mouseProc;
    static int last_mouse_z;
    if(mouse.z < last_mouse_z) {
        action_decrZ(keymod);
        last_mouse_z = mouse.z;
    }
    if(mouse.z > last_mouse_z) {
        action_incrZ(keymod);
        last_mouse_z = mouse.z;
    }
    if( mouse.buttons & 2 ) {
        ssConfig.follow_DFscreen = false;
        int x, y;
        x = mouse.x;
        y = mouse.y;
        int tilex,tiley,tilez;
        ScreenToPoint(x,y,tilex,tiley,tilez);
        int diffx = tilex - ssState.SegmentSize.x/2;
        int diffy = tiley - ssState.SegmentSize.y/2;
        /*we use changeRelativeToRotation directly, and not through moveViewRelativeToRotation
        because we don't want to move the offset with the mouse. It just feels weird. */
        // changing to +1,+1 which moves the clicked point to one of the 4 surrounding the center of rotation
        changeRelativeToRotation(ssState.DisplayedSegment.x, ssState.DisplayedSegment.y, diffx+1, diffy+1 );
        //moveViewRelativeToRotation(diffx+1, diffy+1);
        timeToReloadSegment = true;
        //rest(50);
    }
    if( mouse.buttons & 1 ) {
        ssConfig.follow_DFcursor = false;
        int x, y;
        x = mouse.x;//pos >> 16;
        y = mouse.y; //pos & 0x0000ffff;
        if(x >= MiniMapTopLeftX && x <= MiniMapBottomRightX && y >= MiniMapTopLeftY && y <= MiniMapBottomRightY) { // in minimap
            ssState.DisplayedSegment.x = (x-MiniMapTopLeftX-MiniMapSegmentWidth/2)/oneTileInPixels;
            ssState.DisplayedSegment.y = (y-MiniMapTopLeftY-MiniMapSegmentHeight/2)/oneTileInPixels;
        } else {
            int tilex,tiley,tilez;
            ScreenToPoint(x,y,tilex,tiley,tilez);
            int diffx = tilex - ssState.SegmentSize.x/2;
            int diffy = tiley - ssState.SegmentSize.y/2;
            debugCursor.x = tilex;
            debugCursor.y = tiley;
        }
        timeToReloadSegment = true;
    }
}
void AllegroShell::run(){
// run the loop
	unsigned num = 0;
	ALLEGRO_EVENT ev;
	al_start_timer(timer);

	unsigned keyboard_count = 0;
	unsigned mouse_count = 0;
	unsigned timer_count = 0;
	
	while( run_flag ){
		al_wait_for_event(queue,&ev);
		num++;
		printf("\r%d",num);

		if( ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE){
			run_flag = false;
		}else if( isKeyboardEvent(&ev)){
			// handle keyboard input
			++keyboard_count;
			al_get_keyboard_state(&(keyboard));
			handle_keyboard(&ev);
		}else if( isMouseEvent(&ev) ){
			// handle mouse input
			++mouse_count;
			mouse->update(&ev);
			handle_mouse(&ev);
		}else if( ev.type  == ALLEGRO_EVENT_TIMER){
			++timer_count;
			// Update the model only if we haven't drawn the scene
			if(draw_flag == false){
				if(step_once_flag){
					// always step once if the user requests it
					model->step();
					step_once_flag = false;
				}else if(step_flag) {
					model->step();
				}
			}
			draw_flag = true;
		}else if (ev.type == USER_VIEW_EVENT){
			// handling user events
			al_unref_user_event(&ev.user);
		}

		if( draw_flag && al_event_queue_is_empty(queue)){
			draw();
			draw_flag = false;
		}
	} // end while(run_flag)

	Textlog::get().log("\nkeyboard_count = %u\n",keyboard_count);
	Textlog::get().log("mouse_count = %u\n",mouse_count);
	Textlog::get().log("timer_count = %u\n",timer_count);
}
Beispiel #3
0
void doRepeatActions()
{
    al_get_keyboard_state(&keyboard);
    int32_t keymod = getKeyMods(&keyboard);

    for(int keycode=0; keycode<ALLEGRO_KEY_UNKNOWN; keycode++) {
        if(isRepeatable(keycode) && al_key_down(&keyboard,keycode)) {
            doKey(keycode, keymod);
        }
    }
}
Beispiel #4
0
/*
 * This reads one keystroke from the keyboard, and the current state of
 * the modifier keys (ALT, SHIFT, etc).  Returns -1 on error, 0 if no data
 * is ready, 1 on a keypress, and 2 on keyrelease.
 * This is a non-blocking call.
 */
static int
allegro_Read(MWKEY *kbuf, MWKEYMOD *modifiers, MWSCANCODE *scancode)
{

  int newkey;
  static int mwkey,scanvalue;

  if (closedown == 1) return -2; /* special case ESC - terminate application*/

  if (!al_is_keyboard_installed()) return 0;

  if (al_get_next_event(a_event_queue_k, &a_event)){
     /* there are further key events */
	 if (a_event.type == ALLEGRO_EVENT_KEY_CHAR) {
	  newkey = a_event.keyboard.unichar;  
	  al_get_keyboard_state(&kbdstate);
	  char ASCII = newkey & 0xff;  
	  mwkey = ASCII;
	  //fprintf(stderr,"key char:%d,%c\n",ASCII,ASCII);  fflush(stderr);
	  scanvalue = a_event.keyboard.keycode; 
     } else {
         if (a_event.type == ALLEGRO_EVENT_KEY_UP) {
            *kbuf = mwkey;		
            *scancode = scanvalue;
            return 2; //key released    
	    } else {
	        //fprintf(stderr,"NO key\n");  fflush(stderr);
	        return 0;
        }
	}

   *modifiers = 0;
   if (al_key_down(&kbdstate, ALLEGRO_KEY_ESCAPE)) return -2; /* special case ESC - terminate application*/

   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_SHIFT)) *modifiers |= MWKMOD_SHIFT;
   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_CTRL))  *modifiers |= MWKMOD_CTRL;
   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_ALT))   *modifiers |= MWKMOD_ALT;
   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_ALTGR)) *modifiers |= MWKMOD_ALTGR;
   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_LWIN))  *modifiers |= MWKMOD_LMETA; *modifiers |= MWKMOD_META;
   if (al_key_down(&kbdstate, ALLEGRO_KEYMOD_RWIN))  *modifiers |= MWKMOD_RMETA; *modifiers |= MWKMOD_META;
   save_modifiers=*modifiers;
   
    *kbuf = mwkey;		
    *scancode = scanvalue;

    return 1;		/* keypress received*/
  } 
return 0; //if no event received

}
Beispiel #5
0
void MenuState::update(Engine* engine){

    if(timerEvent){

        al_get_mouse_state(&mouseState);

        al_get_keyboard_state(&keyState);

        //Input +
        if(al_key_down(&keyState, ALLEGRO_KEY_ESCAPE)){
            if(lastKeyPress != ALLEGRO_KEY_ESCAPE){
                if(inGame){
                    engine->popState();
                }else{
                    engine->quit();
                }
                lastKeyPress = ALLEGRO_KEY_ESCAPE;
            }
         }
        //Input -

        //Update Entities +
        for(int i = 0; i < MAX_BUTTONS; i++){
            if(buttonList[i] != NULL && buttonList[i]->checkActive()){
                buttonList[i]->update();
                if(buttonList[i]->clicked){
                    switch(buttonList[i]->buttonId){
                        case 0:
                            engine->popState();
                            break;

                        case 1:
                            engine->changeState(PlayState::instance());
                            break;

                        case 2:
                            engine->quit();
                            break;
                    }
                }
            }
        }
        //Update Entities -

        //Rest +

        //Rest -
        engine->draw();
    }
}
Beispiel #6
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;
}
Beispiel #7
0
BaseGame::BaseGame(Vector2 windowSize, ScreenType screenType, string screenTitle, double fps) : fps(fps),
                   windowSize(windowSize), running(true)
{
	initScreen(screenType, screenTitle);
	initModules();

	al_get_keyboard_state(&keyState);
	al_get_mouse_state(&mouseState);

	eventQueue = al_create_event_queue();
	timer = al_create_timer(1/this->fps);

	//Events to read
	al_register_event_source(eventQueue, al_get_keyboard_event_source());
	al_register_event_source(eventQueue, al_get_timer_event_source(timer));
	al_register_event_source(eventQueue, al_get_display_event_source(display));
	al_register_event_source(eventQueue, al_get_mouse_event_source());
}
Beispiel #8
0
int main(void)
{
   ALLEGRO_COLOR black;
   ALLEGRO_COLOR red;
   ALLEGRO_KEYBOARD_STATE kbdstate;

   if (!al_init()) {
      abort_example("Error initialising Allegro.\n");
   }

   if (!al_install_keyboard()) {
      abort_example("Error installing keyboard.\n");
   }

   display1 = al_create_display(300, 300);
   display2 = al_create_display(300, 300);
   if (!display1 || !display2) {
      abort_example("Error creating displays.\n");
   }

   black = al_map_rgb(0, 0, 0);
   red = al_map_rgb(255, 0, 0);

   while (1) {
      al_get_keyboard_state(&kbdstate);
      if (al_key_down(&kbdstate, ALLEGRO_KEY_ESCAPE)) {
         break;
      }

      if (kbdstate.display == display1) {
         redraw(red, black);
      }
      else if (kbdstate.display == display2) {
         redraw(black, red);
      }
      else {
         redraw(black, black);
      }

      al_rest(0.1);
   }

   return 0;
}
Beispiel #9
0
bool Letter(struct Game *game, struct TM_Action *action, enum TM_ActionState state) {
	if (state == TM_ACTIONSTATE_INIT) {
		float* f = (float*)malloc(sizeof(float));
		*f = 0;
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)malloc(sizeof(ALLEGRO_AUDIO_STREAM*));
		*stream = al_load_audio_stream(GetDataFilePath(GetLevelFilename(game, "levels/?/letter.flac")), 4, 1024);
		al_attach_audio_stream_to_mixer(*stream, game->audio.voice);
		al_set_audio_stream_playing(*stream, false);
		al_set_audio_stream_gain(*stream, 2.00);
		action->arguments = TM_AddToArgs(action->arguments, (void*)f);
		action->arguments = TM_AddToArgs(action->arguments, (void*)stream);
		action->arguments->next->next = NULL;
	} else if (state == TM_ACTIONSTATE_DESTROY) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
		al_destroy_audio_stream(*stream);
		free(action->arguments->next->value);
		free(action->arguments->value);
		TM_DestroyArgs(action->arguments);
	} else if (state == TM_ACTIONSTATE_DRAW) {
		float* f = (float*)action->arguments->value;
		al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
		return false;
	} else if (state == TM_ACTIONSTATE_PAUSE) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, false);
	}	else if ((state == TM_ACTIONSTATE_RESUME) || (state == TM_ACTIONSTATE_START)) {
		ALLEGRO_AUDIO_STREAM** stream = (ALLEGRO_AUDIO_STREAM**)action->arguments->next->value;
		al_set_audio_stream_playing(*stream, true);
	}
	if (state != TM_ACTIONSTATE_RUNNING) return false;

	float* f = (float*)action->arguments->value;
	*f+=5;
	if (*f>255) *f=255;
	al_draw_tinted_bitmap(game->level.letter, al_map_rgba(*f,*f,*f,*f), (game->viewportWidth-al_get_bitmap_width(game->level.letter))/2.0, al_get_bitmap_height(game->level.letter)*-0.05, 0);
	struct ALLEGRO_KEYBOARD_STATE keyboard;
	al_get_keyboard_state(&keyboard);
	// FIXME: do it the proper way
	if (al_key_down(&keyboard, ALLEGRO_KEY_ENTER)) {
		return true;
	}
	return false;
}
Beispiel #10
0
  inline void				inputBehavior(float time, const ALLEGRO_EVENT &ev)
  {
    static float			lastTime = -1;
    ALLEGRO_KEYBOARD_STATE		k;

    al_get_keyboard_state(&k);

    if (lastTime == -1)
      lastTime = al_get_time();
    float speed = (time - lastTime) * this->speed_;

    if (al_key_down(&k, ALLEGRO_KEY_W))
      {
	this->position_ += this->forward_ * glm::vec3(speed, speed, speed);
      }
    if (al_key_down(&k, ALLEGRO_KEY_S))
      {
	this->position_ -= this->forward_ * glm::vec3(speed, speed, speed);
      }
    if (al_key_down(&k, ALLEGRO_KEY_A))
      {
	glm::vec3 up(0.0f, 1.0f, 0.0f);
	glm::vec3 left = glm::cross(up, forward_);
	this->position_ += glm::normalize(left);
      }
    if (al_key_down(&k, ALLEGRO_KEY_D))
      {
	glm::vec3 up(0.0f, 1.0f, 0.0f);
	glm::vec3 left = glm::cross(up, forward_);
	this->position_ -= glm::normalize(left);
      }
    if (al_key_down(&k, ALLEGRO_KEY_Q))
      {
	this->position_ += glm::vec3(0.0f, speed / 20.0f, 0.0f);
      }
    if (al_key_down(&k, ALLEGRO_KEY_E))
      {
	this->position_ -= glm::vec3(0.0f, speed / 20.0f, 0.0f);
      }

    lastTime = time;
    (void)ev;
    (void)time;
  }
Beispiel #11
0
int main(void)
{
	gpPerformanceTracker = new PerformanceTracker();

	gpGame = new GameApp();

	gpGame->init();

	GraphicsBuffer* pWallpaper = new GraphicsBuffer( "wallpaper.bmp" );//should "live" someplace else


	bool shouldExit = false;

	while( !shouldExit )
	{
		//get current keyboard state
		ALLEGRO_KEYBOARD_STATE keyState;
		al_get_keyboard_state( &keyState );

		//if escape key was down then exit the loop
		if( al_key_down( &keyState, ALLEGRO_KEY_ESCAPE ) )
		{
			gpGame->markForExit();
		}

		gpGame->beginLoop();
		gpGame->processLoop();
		shouldExit = gpGame->endLoop();
	}

	//cleanup
	delete pWallpaper;
	gpGame->cleanup();
	delete gpGame;
	delete gpPerformanceTracker;

	gMemoryTracker.reportAllocations( std::cout );

	system("pause");

	return 0;
}
Beispiel #12
0
void error_call(void)
{

 ALLEGRO_EVENT ev;

 ALLEGRO_KEYBOARD_STATE error_key_State;

 fprintf(stdout, "\n\r\n\rPress space to exit (with game window as focus)");

 while(TRUE)
 {
  al_wait_for_event(event_queue, &ev);
  al_get_keyboard_state(&error_key_State);

  if(al_key_down(&error_key_State, ALLEGRO_KEY_ESCAPE)
  || al_key_down(&error_key_State, ALLEGRO_KEY_SPACE))
   safe_exit(1);
 };

}
Beispiel #13
0
void update_keystate_table()
{
   al_get_keyboard_state(&keyboard);

   reset_keystate_table(keystate);

   if (al_key_down(&keyboard, ALLEGRO_KEY_UP))
      keystate[KEY_UP] = 1;

   if (al_key_down(&keyboard, ALLEGRO_KEY_DOWN))
      keystate[KEY_DOWN] = 1;

   if (al_key_down(&keyboard, ALLEGRO_KEY_LEFT))
      keystate[KEY_LEFT] = 1;

   if (al_key_down(&keyboard, ALLEGRO_KEY_RIGHT))
      keystate[KEY_RIGHT] = 1;

   if (al_key_down(&keyboard, ALLEGRO_KEY_ESCAPE))
      keystate[KEY_ESCAPE] = 1;
}
void SpaceSim::TakeInput()
{
	al_get_keyboard_state(&new_keyboard_state);

	//ESCAPE
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_ESCAPE))
	{
		done = true;
	}
	Entity* spaceship_body =  spaceship->getEntity("body");
	PositionComp* spaceship_body_pos = (PositionComp*) spaceship_body->getComponent("Position");
	PhysicsComp* spaceship_body_physiscs = (PhysicsComp*)spaceship_body->getComponent("Physics");

	//WASD
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_W))
	{
		Entity* thruster_main_entity = spaceship->getEntity("thruster_main");
		PositionComp* thruster_main_pos = (PositionComp*) thruster_main_entity->getComponent("Position");
		ThrusterComp* thruster_main = (ThrusterComp*)thruster_main_entity->getComponent("Thruster");
		ConnectedComp* thruster_main_connected = (ConnectedComp*)thruster_main_entity->getComponent("Connected");

		spaceship_body_physiscs->addForce(Force(thruster_main_connected->getRadianFromSocket()+spaceship_body_pos->getRotation(),
			thruster_main_pos->getRotation(),
			thruster_main->getForceExerted()));
	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_D))
	{
		Entity* thruster_east_entity = spaceship->getEntity("thruster_east");
		PositionComp* thruster_east_pos = (PositionComp*) thruster_east_entity->getComponent("Position");
		ThrusterComp* thruster_east = (ThrusterComp*)thruster_east_entity->getComponent("Thruster");
		ConnectedComp* thruster_east_connected = (ConnectedComp*)thruster_east_entity->getComponent("Connected");

		spaceship_body_physiscs->addForce(Force(thruster_east_connected->getRadianFromSocket()+spaceship_body_pos->getRotation(),
			thruster_east_pos->getRotation(),
			thruster_east->getForceExerted()));

	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_S))
	{

	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_A))
	{
		Entity* thruster_west_entity = spaceship->getEntity("thruster_west");
		PositionComp* thruster_west_pos = (PositionComp*) thruster_west_entity->getComponent("Position");
		ThrusterComp* thruster_west = (ThrusterComp*)thruster_west_entity->getComponent("Thruster");
		ConnectedComp* thruster_west_connected = (ConnectedComp*)thruster_west_entity->getComponent("Connected");

		spaceship_body_physiscs->addForce(Force(thruster_west_connected->getRadianFromSocket()+spaceship_body_pos->getRotation(),
			thruster_west_pos->getRotation(),
			thruster_west->getForceExerted()));
	}

	//ARROW KEYS
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_UP))
	{
		if(!al_key_down(&old_keyboard_state,ALLEGRO_KEY_UP))
		{
			Entity* north_turret_entity = spaceship->getEntity("turret_north");
			PositionComp* north_turret_pos = (PositionComp*) north_turret_entity->getComponent("Position");
			TurretComp* north_turret = (TurretComp*) north_turret_entity->getComponent("Turret");

			Entity* bullet = new Entity();
			physics_entities.push_back(bullet);
			entities.push_back(bullet);

			//We need to allow space betweent he turret and the bullet so they dont collide
			double x_position = (15.0*cos(north_turret_pos->getRotation())) + north_turret_pos->getPosition().x;
			double y_position = (15.0*sin(north_turret_pos->getRotation())) + north_turret_pos->getPosition().y;

			PositionComp* bullet_pos = new PositionComp(Vector3(x_position,y_position,16));
			bullet->addComponent(bullet_pos);
			bullet->addComponent(new SpriteComp(bullet_bitmap,bullet_pos));
			bullet->addComponent(new BulletComp(north_turret->getBulletArmorPiercing()));
			//bullet->addComponent(new RemovalComp(3,false,bullet));

			PhysicsComp* bullet_phys =new PhysicsComp(north_turret->getBulletWeight(),al_get_bitmap_width(bullet_bitmap)/2,.1,bullet_pos);
			double bullet_direction = north_turret_pos->getRotation();
			double bullet_degrees = bullet_direction*57.2957795;
			bullet_phys->addForce(Force(bullet_direction+PI,bullet_direction, north_turret->getBulletForce()));
			bullet->addComponent(bullet_phys);

		}
	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_RIGHT))
	{
		if(!al_key_down(&old_keyboard_state,ALLEGRO_KEY_RIGHT))
		{

		}
	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_DOWN))
	{

	}
	if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_LEFT))
	{
		if(!al_key_down(&old_keyboard_state,ALLEGRO_KEY_LEFT))
		{

		}
	}


	////Q
	//if(al_key_down(&new_keyboard_state,ALLEGRO_KEY_Q))
	//{
	//	if(!al_key_down(&old_keyboard_state,ALLEGRO_KEY_Q))
	//	{
	//		player_sprite->setBitmap(dead_bitmap);
	//	}
	//}

	////Player fuel stats

	//double fuel_cost =player_astronaut->getFuelCost();
	//double current_co2 = player_astronaut->getCurrentCO2();

	////W
	//current_co2 = player_astronaut->getCurrentCO2();
	//if(current_co2 > fuel_cost*1000*dt && al_key_down(&new_keyboard_state,ALLEGRO_KEY_W))
	//{
	//	thrust_animated->setToVisible();
	//	player_physics->addForce(Force(player_position->getRotation()+PI,player_position->getRotation(),1000));
	//	if(!al_get_sample_instance_playing(co2_sample_instance))
	//	{
	//		al_play_sample_instance(co2_sample_instance);
	//	}		

	//	player_astronaut->setCurrentCO2(current_co2 - (fuel_cost*1000)*dt );
	//}
	//else
	//{
	//	thrust_animated->setToInvisible();
	//	al_stop_sample_instance(co2_sample_instance);
	//}

	////S
	//current_co2 = player_astronaut->getCurrentCO2();
	//if(current_co2 > fuel_cost*1000*dt && al_key_down(&new_keyboard_state,ALLEGRO_KEY_S))
	//{
	//	double current_co2 = player_astronaut->getCurrentCO2();

	//	thrust_back_animated->setToVisible();
	//	player_physics->addForce(Force(player_position->getRotation(),player_position->getRotation()+PI,1000));

	//	if(!al_get_sample_instance_playing(co2_sample_instance))
	//	{
	//		al_play_sample_instance(co2_back_sample_instance);
	//	}	
	//	player_astronaut->setCurrentCO2(current_co2 - (fuel_cost*1000)*dt );
	//}
	//else
	//{
	//	thrust_back_animated->setToInvisible();
	//	al_stop_sample_instance(co2_back_sample_instance);
	//}

	////D
	//current_co2 = player_astronaut->getCurrentCO2();
	//if(current_co2 > fuel_cost*500*dt && al_key_down(&new_keyboard_state,ALLEGRO_KEY_D))
	//{

	//	thrust_right_animated->setToVisible();
	//	player_physics->addForce(Force(player_position->getRotation()-(PI/2.0),player_position->getRotation(),500));
	//	if(!al_get_sample_instance_playing(co2_right_sample_instance))
	//	{
	//		al_play_sample_instance(co2_right_sample_instance);
	//	}	
	//	player_astronaut->setCurrentCO2(current_co2 - (fuel_cost*500)*dt );
	//}
	//else
	//{
	//	thrust_right_animated->setToInvisible();
	//	al_stop_sample_instance(co2_right_sample_instance);
	//}

	////A
	//current_co2 = player_astronaut->getCurrentCO2();
	//if(current_co2 > fuel_cost*500*dt && al_key_down(&new_keyboard_state,ALLEGRO_KEY_A))
	//{
	//	thrust_left_animated->setToVisible();
	//	player_physics->addForce(Force(player_position->getRotation()+(PI/2.0),player_position->getRotation(),500));
	//	if(!al_get_sample_instance_playing(co2_sample_instance))
	//	{
	//		al_play_sample_instance(co2_left_sample_instance);
	//	}	
	//	player_astronaut->setCurrentCO2(current_co2 - (fuel_cost*500)*dt );	
	//}
	//else
	//{
	//	thrust_left_animated->setToInvisible();
	//	al_stop_sample_instance(co2_left_sample_instance);
	//}


	old_keyboard_state = new_keyboard_state;
}
Beispiel #15
0
void main_loop(ALLEGRO_EVENT_QUEUE *event_queue) {
  int color = 0, c2 = 0, c3 = 0;
  bool stlacene_tlacitka[ALLEGRO_KEY_MAX];
  memset(stlacene_tlacitka, 0, sizeof(stlacene_tlacitka));

  struct Player *player;
  player = player_new();

  struct Objekt * obj = malloc(sizeof(struct Objekt));

  list_add(&scena, obj);
  obj->objekt = player;
  obj->draw = player_draw;
  obj->destroy = player_destroy;
  obj->copy = player_copy;

  mutex = al_create_mutex();
  ALLEGRO_THREAD *thread = al_create_thread(kresliace_vlakno, event_queue);
  al_start_thread(thread);

  for (;;) {
    ALLEGRO_EVENT event;
    al_wait_for_event(event_queue, &event);

    if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
      break;
    }

    if (event.type == ALLEGRO_EVENT_TIMER) {
      al_lock_mutex(mutex);

      if (stlacene_tlacitka[ALLEGRO_KEY_LEFT]) {
        player->x = player->x - 10;
        if (player->x < 0) player->x = 0;
      }
      if (stlacene_tlacitka[ALLEGRO_KEY_RIGHT]) {
        player->x = player->x + 10;
        if (player->x > SCREEN_W - 64) player->x = SCREEN_W - 64;
      }

      al_unlock_mutex(mutex);

    }

    if (event.type == ALLEGRO_EVENT_KEY_DOWN
      ||event.type == ALLEGRO_EVENT_KEY_UP) {

      ALLEGRO_KEYBOARD_STATE stav_klavesnice;
      al_get_keyboard_state(&stav_klavesnice);

      if (al_key_down(&stav_klavesnice, ALLEGRO_KEY_ESCAPE)) {
        break;
      }

      if (al_key_down(&stav_klavesnice, ALLEGRO_KEY_LEFT)) {
        stlacene_tlacitka[ALLEGRO_KEY_LEFT] = true;
      } else {
        stlacene_tlacitka[ALLEGRO_KEY_LEFT] = false;
      }
      if (al_key_down(&stav_klavesnice, ALLEGRO_KEY_RIGHT)) {
        stlacene_tlacitka[ALLEGRO_KEY_RIGHT] = true;
      } else {
        stlacene_tlacitka[ALLEGRO_KEY_RIGHT] = false;
      }
      if (al_key_down(&stav_klavesnice, ALLEGRO_KEY_UP)) {
        stlacene_tlacitka[ALLEGRO_KEY_UP] = true;
      } else {
        stlacene_tlacitka[ALLEGRO_KEY_UP] = false;
      }
      if (al_key_down(&stav_klavesnice, ALLEGRO_KEY_DOWN)) {
        stlacene_tlacitka[ALLEGRO_KEY_DOWN] = true;
      } else {
        stlacene_tlacitka[ALLEGRO_KEY_DOWN] = false;
      }
    }
  }

  al_destroy_thread(thread);


}
void AllegroInput5::Update( int dt )
{
	if ( m_doubleClickTimer > 0 )
		m_doubleClickTimer -= dt;
	if ( m_repeatTimer > 0 )
		m_repeatTimer -= dt;

	  // Get current transformation, to tranform reported scaled/shifted mouse coordinates into something the game can use
	const ALLEGRO_TRANSFORM *pTransform = al_get_current_inverse_transform();

	const JoystickMapping & mapping = GetJoystickMapping(0);

	ALLEGRO_EVENT ev;
	while( al_get_next_event( m_queue, &ev ) )
	{
		if ( m_hasKeyboard )
		{
			if ( ev.any.type == ALLEGRO_EVENT_KEY_DOWN )
				AddEvent( InputEvent::KeyboardEvent( KeyboardEvent::KBD_KEY_DOWN, ev.keyboard.keycode, ev.keyboard.unichar, ev.keyboard.modifiers ) );
			else if ( ev.any.type == ALLEGRO_EVENT_KEY_UP )
				AddEvent( InputEvent::KeyboardEvent( KeyboardEvent::KBD_KEY_UP, ev.keyboard.keycode, ev.keyboard.unichar, ev.keyboard.modifiers ) );
			else if ( ev.any.type == ALLEGRO_EVENT_KEY_CHAR && m_repeatTimer <= 0 )
			{
				  // Please note that some event params (like modifiers) are ONLY accessible in KEY_CHAR event!
				AddEvent( InputEvent::KeyboardEvent( KeyboardEvent::KBD_KEY_REPEAT, ev.keyboard.keycode, ev.keyboard.unichar, ev.keyboard.modifiers ) );
				m_repeatTimer = 100;
			}
		}

		if ( m_hasMouse )
		{
			float exf = ev.mouse.x;
			float eyf = ev.mouse.y;
			float edxf = ev.mouse.dx;
			float edyf = ev.mouse.dy;

			al_transform_coordinates( pTransform, &exf, &eyf );
			al_transform_coordinates( pTransform, &edxf, &edyf );

			int ex = (int)floorf( exf );
			int ey = (int)floorf( eyf );
			int edx = (int)floorf( edxf );
			int edy = (int)floorf( edyf );

			if ( ev.any.type == ALLEGRO_EVENT_MOUSE_AXES )
			{
				if ( edx != 0 || edy != 0 )
					AddEvent( InputEvent::MouseEvent( MouseEvent::MOUSE_MOVE, ex, ey, ev.mouse.dw ) );
				if ( ev.mouse.dw != 0 )
					AddEvent( InputEvent::MouseEvent( MouseEvent::MOUSE_WHEEL, ex, ey, ev.mouse.dw ) );
			}
			else if ( ev.any.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN )
			{
				MouseEvent::EType type = MouseEvent::MOUSE_B1_DOWN;
				if ( ev.mouse.button == 1 )
				{
					if ( m_doubleClickTimer > 0 )
					{
						m_doubleClickTimer = 0;
						type = MouseEvent::MOUSE_B1_DOUBLECLICK;
					}
					else
						type = MouseEvent::MOUSE_B1_DOWN;
				}
				else if ( ev.mouse.button == 2 )
					type = MouseEvent::MOUSE_B2_DOWN;
				else if ( ev.mouse.button == 3 )
					type = MouseEvent::MOUSE_B3_DOWN;
				AddEvent( InputEvent::MouseEvent( type, ex, ey, 0 ) );
			}
			else if ( ev.any.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP )
			{
				MouseEvent::EType type = MouseEvent::MOUSE_B1_UP;
				if ( ev.mouse.button == 1 )
				{
					m_doubleClickTimer = 250;
					type = MouseEvent::MOUSE_B1_UP;
				}
				else if ( ev.mouse.button == 2 )
					type = MouseEvent::MOUSE_B2_UP;
				else if ( ev.mouse.button == 3 )
					type = MouseEvent::MOUSE_B3_UP;
				AddEvent( InputEvent::MouseEvent( type, ex, ey, 0 ) );
			}
		}

		if ( m_hasGamepad )
		{
			if ( ev.any.type == ALLEGRO_EVENT_JOYSTICK_AXIS )
			{
				const int stick = ev.joystick.stick;
				const int axis  = ev.joystick.axis;
			
				if ( stick >= (int)m_gamepadSticks.size() )
					m_gamepadSticks.resize( stick + 1 );

				GamepadStick & s = m_gamepadSticks[ stick ];
				if ( axis >= (int)s.m_axis.size() )
					s.m_axis.resize( axis + 1 );

				GamepadAxis & a = s.m_axis[ axis ];

				  // Some axes on some systems has their neutral position at -1 instead of 0, so we have to adjust for it
				const float adjPos = ev.joystick.pos - mapping.GetAxisBase( ev.joystick.stick, ev.joystick.axis );
				const bool nearZero = fabs(adjPos) < 0.01f;
				
				  // We only want to send GP_AXIS event once for each direction change, like it was a digital axis or a keyboard key
				if ( nearZero )
				{
					  // If the stick is back to its neutral position, and wasn't there before, send an event about it
					if ( !a.m_unlocked )
						AddEvent( InputEvent::GamepadEvent( GamepadEvent::GP_AXIS, ev.joystick.stick, ev.joystick.axis, 0 ) );
					a.m_unlocked = true;
				}
				else
				{
					  // If the stick is outside its neutral position, and this wasn't reported before, send an event about it
					if ( a.m_unlocked )
						AddEvent( InputEvent::GamepadEvent( GamepadEvent::GP_AXIS, ev.joystick.stick, ev.joystick.axis, adjPos ) );
					a.m_unlocked = false;
				}
			}
			else if ( ev.any.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_DOWN )
			{
				AddEvent( InputEvent::GamepadEvent( GamepadEvent::GP_BUTTON_DOWN, ev.joystick.button ) );
			}
			else if ( ev.any.type == ALLEGRO_EVENT_JOYSTICK_BUTTON_UP )
			{
				AddEvent( InputEvent::GamepadEvent( GamepadEvent::GP_BUTTON_UP, ev.joystick.button ) );
			}
		}

		if ( m_hasTouch )
		{
			float exf = ev.touch.x;
			float eyf = ev.touch.y;
			float edxf = ev.touch.dx;
			float edyf = ev.touch.dy;

			al_transform_coordinates( pTransform, &exf, &eyf );
            edxf *= pTransform->m[0][0];
            edyf *= pTransform->m[0][0];

			int ex = (int)floorf( exf );
			int ey = (int)floorf( eyf );
			int edx = (int)floorf( edxf );
			int edy = (int)floorf( edyf );

			if ( ev.any.type == ALLEGRO_EVENT_TOUCH_BEGIN )
				AddEvent( InputEvent::TouchEvent( TouchEvent::TOUCH_BEGIN, ev.touch.id, ev.touch.primary, ev.touch.timestamp, ex, ey, edx, edy ) );
			else if ( ev.any.type == ALLEGRO_EVENT_TOUCH_MOVE )
				AddEvent( InputEvent::TouchEvent( TouchEvent::TOUCH_MOVE, ev.touch.id, ev.touch.primary, ev.touch.timestamp, ex, ey, edx, edy ) );
			else if ( ev.any.type == ALLEGRO_EVENT_TOUCH_END )
				AddEvent( InputEvent::TouchEvent( TouchEvent::TOUCH_END, ev.touch.id, ev.touch.primary, ev.touch.timestamp, ex, ey, edx, edy ) );
			else if ( ev.any.type == ALLEGRO_EVENT_TOUCH_CANCEL )
				AddEvent( InputEvent::TouchEvent( TouchEvent::TOUCH_CANCEL, ev.touch.id, ev.touch.primary, ev.touch.timestamp, ex, ey, edx, edy ) );

			//GetLog().Log( CommonLog(), LL_CRITICAL, "AllegroInput: event=%i id=%i x=%f y=%f", ev.any.type, ev.touch.id, ev.touch.x, ev.touch.y );
		}
	}

	if ( m_hasKeyboard )
	{
		  // Since Allegro events don't have KEY_PRESSED, we do it other way.
		ALLEGRO_KEYBOARD_STATE state;
		al_get_keyboard_state( &state );

		for ( int i = 0; i < ALLEGRO_KEY_MAX; ++i )
		{
			  // We don't know key code for state :(
			if ( al_key_down( &state, i ) && m_keyStates[ i ] )
				AddEvent( InputEvent::KeyboardEvent( KeyboardEvent::KBD_KEY_PRESSED, i, 0, 0 ) );

			m_keyStates[ i ] = al_key_down( &state, i )  != 0;
		}
	}
}
Beispiel #17
0
int main( void ) {

   ALLEGRO_DISPLAY *display;
   ALLEGRO_KEYBOARD_STATE key_state;
   Point stars[3][NUM_STARS/3];
   float speeds[3] = { 0.0001f, 0.05f, 0.15f };
   ALLEGRO_COLOR colors[3];
   long start, now, elapsed, frame_count;
   int total_frames = 0;
   double program_start;
   double length;
   int layer, star;

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

   al_install_keyboard();
   
   display = al_create_display(WIDTH, HEIGHT);
   if (!display) {
      abort_app("Could not create display.\n");
      return 1;
   }

   colors[0] = al_map_rgba(255, 100, 255, 128);
   colors[1] = al_map_rgba(255, 100, 100, 255);
   colors[2] = al_map_rgba(100, 100, 255, 255);
         
   for (layer = 0; layer < 3; layer++) {
      for (star = 0; star < NUM_STARS/3; star++) {
         Point *p = &stars[layer][star];
         p->x = rand() % WIDTH;
         p->y = rand() % HEIGHT;
      }
   }


   start = al_get_time() * 1000;
   now = start;
   elapsed = 0;
   frame_count = 0;
   program_start = al_get_time();


   while (1) {
      if (frame_count < (1000/TARGET_FPS)) {
         frame_count += elapsed;
      }
      else {
         int X, Y;

         frame_count -= (1000/TARGET_FPS);
         al_clear_to_color(al_map_rgb(0, 0, 0));
         for (star = 0; star < NUM_STARS/3; star++) {
            Point *p = &stars[0][star];
            al_draw_pixel(p->x, p->y, colors[0]);
         }
         al_lock_bitmap(al_get_backbuffer(display), ALLEGRO_PIXEL_FORMAT_ANY, 0);

         for (layer = 1; layer < 3; layer++) {
            for (star = 0; star < NUM_STARS/3; star++) {
               Point *p = &stars[layer][star];
               // put_pixel ignores blending
               al_put_pixel(p->x, p->y, colors[layer]);
            }
         }

         /* Check that dots appear at the window extremes. */
         X = WIDTH - 1;
         Y = HEIGHT - 1;
         al_put_pixel(0, 0, al_map_rgb_f(1, 1, 1));
         al_put_pixel(X, 0, al_map_rgb_f(1, 1, 1));
         al_put_pixel(0, Y, al_map_rgb_f(1, 1, 1));
         al_put_pixel(X, Y, al_map_rgb_f(1, 1, 1));

         al_unlock_bitmap(al_get_backbuffer(display));
         al_flip_display();
         total_frames++;
      }

      now = al_get_time() * 1000;
      elapsed = now - start;
      start = now;

      for (layer = 0; layer < 3; layer++) {
         for (star = 0; star < NUM_STARS/3; star++) {
            Point *p = &stars[layer][star];
            p->y -= speeds[layer] * elapsed;
            if (p->y < 0) {
               p->x = rand() % WIDTH;
               p->y = HEIGHT;
            }
         }
      }

      al_rest(0.001);

      al_get_keyboard_state(&key_state);
      if (al_key_down(&key_state, ALLEGRO_KEY_ESCAPE))
         break;
   }

   length = al_get_time() - program_start;

   if (length != 0) {
      printf("%d FPS\n", (int)(total_frames / length));
   }

   al_destroy_display(display);

   return 0;
}
int main(int argc, char **argv)
{
   float r = 0.5, g = 0.5, b = 1, ratio = 0;
   int dir = 1;
   ALLEGRO_DISPLAY *display;
   ALLEGRO_BITMAP *mysha;
   ALLEGRO_BITMAP *buffer;

   const char *tinter_shader_src[] = {
      "uniform sampler2D backBuffer;",
      "uniform float r;",
      "uniform float g;",
      "uniform float b;",
      "uniform float ratio;",
      "void main() {",
      "	vec4 color;",
      "	float avg, dr, dg, db;",
      "	color = texture2D(backBuffer, gl_TexCoord[0].st);",
      "	avg = (color.r + color.g + color.b) / 3.0;",
      "	dr = avg * r;",
      "	dg = avg * g;",
      "	db = avg * b;",
      "	color.r = color.r - (ratio * (color.r - dr));",
      "	color.g = color.g - (ratio * (color.g - dg));",
      "	color.b = color.b - (ratio * (color.b - db));",
      "	gl_FragColor = color;",
      "}"
   };
   const int TINTER_LEN = 18;
   double start;
   GLint loc;

   (void)argc;
   (void)argv;

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

   al_install_keyboard();
   al_init_image_addon();

   al_set_new_display_flags(ALLEGRO_OPENGL);
   display = al_create_display(320, 200);
   if (!display) {
      abort_example("Error creating display\n");
   }

   mysha = al_load_bitmap("data/mysha.pcx");
   if (!mysha) {
      abort_example("Could not load image.\n");
   }

   buffer = al_create_bitmap(320, 200);

   if (!al_have_opengl_extension("GL_EXT_framebuffer_object")
      && !al_have_opengl_extension("GL_ARB_fragment_shader")) {
      abort_example("Fragment shaders not supported.\n");
   }

   tinter_shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);

   glShaderSourceARB(tinter_shader, TINTER_LEN, tinter_shader_src, NULL);
   glCompileShaderARB(tinter_shader);
   tinter = glCreateProgramObjectARB();
   glAttachObjectARB(tinter, tinter_shader);
   glLinkProgramARB(tinter);
   loc = glGetUniformLocationARB(tinter, "backBuffer");
   glUniform1iARB(loc, al_get_opengl_texture(buffer));

   start = al_get_time();

   while (1) {
      double now, diff;
      ALLEGRO_KEYBOARD_STATE state;
      al_get_keyboard_state(&state);
      if (al_key_down(&state, ALLEGRO_KEY_ESCAPE)) {
         break;
      }
      now = al_get_time();
      diff = now - start;
      start = now;
      ratio += diff * 0.5 * dir;
      if (dir < 0 && ratio < 0) {
         ratio = 0;
         dir = -dir;
      }
      else if (dir > 0 && ratio > 1) {
         ratio = 1;
         dir = -dir;
      }

      al_set_target_bitmap(buffer);

      glUseProgramObjectARB(tinter);
      loc = glGetUniformLocationARB(tinter, "ratio");
      glUniform1fARB(loc, ratio);
      loc = glGetUniformLocationARB(tinter, "r");
      glUniform1fARB(loc, r);
      loc = glGetUniformLocationARB(tinter, "g");
      glUniform1fARB(loc, g);
      loc = glGetUniformLocationARB(tinter, "b");
      glUniform1fARB(loc, b);
      al_draw_bitmap(mysha, 0, 0, 0);
      glUseProgramObjectARB(0);

      al_set_target_backbuffer(display);
      al_draw_bitmap(buffer, 0, 0, 0);
      al_flip_display();
      al_rest(0.001);
   }

   glDetachObjectARB(tinter, tinter_shader);
   glDeleteObjectARB(tinter_shader);

   al_uninstall_system();

   return 0;
}
Beispiel #19
0
void Widget_editor::Event(const ALLEGRO_EVENT &event)
{
	if(ALLEGRO_EVENT_MOUSE_BUTTON_DOWN == event.type)
	{
		if(event.mouse.button == 1)
		{
			Rect brect = Get_bounding_rect();
			if(brect.Contains_point(event.mouse.x, event.mouse.y))
			{
				pressed = true;
				if(event.mouse.x < brect.Topleft().x+5)
				{
					pos.x = brect.Topleft().x;
					left = true;
				}
				else if(event.mouse.x > brect.Bottomright().x-5)
				{
					pos.x = brect.Bottomright().x;
					right = true;
				}
				if(event.mouse.y < brect.Topleft().y+5)
				{
					pos.y = brect.Topleft().y;
					top = true;
				}
				else if(event.mouse.y > brect.Bottomright().y-5)
				{
					pos.y = brect.Bottomright().y;
					bottom = true;
				}
				if(!(left || right || top || bottom))
				{
					move = true;
					pos = brect.Topleft();
				}
				if(!selected)
				{
					selected = true;
					Set_dirty(true);
				}
			}
			else if(selected)
			{
				selected = false;
				Set_dirty(true);
			}
		}
	}
	if(ALLEGRO_EVENT_MOUSE_BUTTON_UP == event.type)
	{
		if(event.mouse.button == 1)
		{
			pressed = false;
			left = false;
			right = false;
			top = false;
			bottom = false;
			move = false;

			Rect brect = Get_bounding_rect();
			if(selected && !brect.Contains_point(event.mouse.x, event.mouse.y))
			{
				selected = false;
				Set_dirty(true);
			}
		}
		if(event.mouse.button == 2)
		{
			Rect brect = Get_bounding_rect();
			if(brect.Contains_point(event.mouse.x, event.mouse.y))
			{
				editing_attributes = true;
				attribute_group->Move_to(event.mouse.x, event.mouse.y);
				for(Attribute_groups::iterator i = attribute_groups.begin(); i != attribute_groups.end(); ++i)
				{
					(*i)->Move_to(event.mouse.x, event.mouse.y+attributes_height);
				}
				w_top.Set_value(brect.Topleft().y);
				w_left.Set_value(brect.Topleft().x);
				w_width.Set_value(brect.Size().x);
				w_height.Set_value(brect.Size().y);
			}
		}
	}
	if(ALLEGRO_EVENT_MOUSE_AXES == event.type)
	{
		if(pressed)
		{
			pos += Vector2(event.mouse.dx, event.mouse.dy);
			Vector2 curpos(pos);
			ALLEGRO_KEYBOARD_STATE keyboard_state;
			al_get_keyboard_state(&keyboard_state);
			if(al_key_down(&keyboard_state, ALLEGRO_KEY_LCTRL))
			{
				curpos.x = int(pos.x/10)*10;
				curpos.y = int(pos.y/10)*10;
			}
			if(move)
			{
				Rect n = widget->Get_bounding_rect();
				n.Move_to(curpos.x, curpos.y);
				widget->Set_bounding_rect(n);
				Set_bounding_rect(n);
			}

			Vector2 topleft = Get_bounding_rect().Topleft();
			Vector2 bottomright = Get_bounding_rect().Bottomright();
			if(left && curpos.x < bottomright.x-15)
				topleft.x = curpos.x;
			if(right && curpos.x > topleft.x+15)
				bottomright.x = curpos.x;
			if(top && curpos.y < bottomright.y-15)
				topleft.y = curpos.y;
			if(bottom && curpos.y > topleft.y+15)
				bottomright.y = curpos.y;
			
			Rect n(topleft, bottomright);
			widget->Set_bounding_rect(n);
			Set_bounding_rect(n);

			w_top.Set_value(n.Topleft().y);
			w_left.Set_value(n.Topleft().x);
			w_width.Set_value(n.Size().x);
			w_height.Set_value(n.Size().y);

			Set_dirty(true);
		}
	}
	if (ALLEGRO_EVENT_KEY_DOWN == event.type)
	{
		if (ALLEGRO_KEY_ESCAPE == event.keyboard.keycode)
		{
			editing_attributes = false;
		}
	}
	if(editing_attributes)
	{
		attribute_group->Event(event);
		float top = w_top.Get_value();
		float left = w_left.Get_value();
		float width = w_width.Get_value();
		float height = w_height.Get_value();
		Rect n(left, top, width, height);
		widget->Set_bounding_rect(n);
		Set_bounding_rect(n);
		
		for(Attribute_groups::iterator i = attribute_groups.begin(); i != attribute_groups.end(); ++i)
		{
			(*i)->Set_widget(widget);
			(*i)->Event(event);
		}
	}
}
Beispiel #20
0
int main() {

	ALLEGRO_DISPLAY *display;

	const float FPS = 60.0;
	const float frameFPS = 15.0;

	float degrees = 0.0f;

	if (!al_init())
		al_show_native_message_box(NULL, "Error", NULL, "Could not Initialize Allegro", NULL, NULL); 

	display = al_create_display(ScreenWidth, ScreenHeight);

	if (!display)
		al_show_native_message_box(NULL, "Error", NULL, "Could not create Allegro Display", NULL, NULL);

	al_set_window_position(display, 200, 200);

	bool done = false, draw = true, active = false;
	float moveSpeed = 5;
	int dir = NONE;

	al_install_keyboard();
	al_init_image_addon();
	al_init_primitives_addon();

	SpriteSeq iory1SpriteSeq = SpriteUtil::process("iory-yagami.png", al_map_rgba(255, 0, 0, 255));
	SpriteSeq iory2SpriteSeq = SpriteUtil::process("iory-yagami.png", al_map_rgba(255, 0, 0, 255));
	
	iory1SpriteSeq.setX(200);
	iory2SpriteSeq.setX(200);

	iory1SpriteSeq.setY(200);
	iory2SpriteSeq.setY(200);

	ALLEGRO_KEYBOARD_STATE keyState;

	ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
	ALLEGRO_TIMER *frameTimer = al_create_timer(1.0 / frameFPS);

	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	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_display_event_source(display));
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	al_start_timer(timer);
	al_start_timer(frameTimer);

	while(!done)
	{
		ALLEGRO_EVENT events; 
		al_wait_for_event(event_queue, &events);
		al_get_keyboard_state(&keyState);

		if (events.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if (events.type == ALLEGRO_EVENT_TIMER)
		{
			if (events.timer.source == timer)
			{
				dir = NONE;
				active = true;
				
				if (al_key_down(&keyState, ALLEGRO_KEY_DOWN)) {
				
					iory1SpriteSeq.incY(moveSpeed);
					
					if (al_key_down(&keyState, ALLEGRO_KEY_RIGHT))
					{
						iory1SpriteSeq.incX(moveSpeed);
						dir = DOWN_RIGHT;
						
					} else if (al_key_down(&keyState, ALLEGRO_KEY_LEFT)) {
					
						iory1SpriteSeq.decX(moveSpeed);
						dir = DOWN_LEFT;
					}
					
				} else if (al_key_down(&keyState, ALLEGRO_KEY_UP)) {
				
					iory1SpriteSeq.decY(moveSpeed);
					
					if (al_key_down(&keyState, ALLEGRO_KEY_RIGHT)) {
					
						iory1SpriteSeq.incX(moveSpeed);
						dir = UP_RIGHT;

					} else if (al_key_down(&keyState, ALLEGRO_KEY_LEFT)) {

						iory1SpriteSeq.decX(moveSpeed);
						dir = UP_LEFT;
					}
				
				} else if (al_key_down(&keyState, ALLEGRO_KEY_RIGHT)) {
				
					iory1SpriteSeq.incX(moveSpeed);
					dir = RIGHT;
					
				} else if (al_key_down(&keyState, ALLEGRO_KEY_LEFT)) {
				
					iory1SpriteSeq.decX(moveSpeed);
					dir = LEFT;
					
				} else {
				
					active = false;
				}

				if (al_key_down(&keyState, ALLEGRO_KEY_W))
					degrees++; 
				else if (al_key_down(&keyState, ALLEGRO_KEY_S))
					degrees--;

				if (degrees >= 360 || degrees <= -360)
					degrees = 0;
					
			} else if (events.timer.source == frameTimer) {
			
				iory1SpriteSeq.next();

				if (!iory1SpriteSeq.hasNext())
					iory1SpriteSeq.reset();
					
				iory2SpriteSeq.next();

				if (!iory2SpriteSeq.hasNext())
					iory2SpriteSeq.reset();

			}

			draw = true;
		}

		if (draw) {
		
			Sprite sprite1 = iory1SpriteSeq.current();
			Sprite sprite2 = iory2SpriteSeq.current();
			
			iory1SpriteSeq.setInFrontOf(&iory2SpriteSeq);
			iory2SpriteSeq.setInFrontOf(&iory1SpriteSeq);
			
			al_draw_bitmap(iory2SpriteSeq.getSubBitmap(), iory2SpriteSeq.getX(), iory2SpriteSeq.getY(), iory2SpriteSeq.getDrawFlags());
			al_draw_bitmap(iory1SpriteSeq.getSubBitmap(), iory1SpriteSeq.getX(), iory1SpriteSeq.getY(), iory1SpriteSeq.getDrawFlags());
			
			//al_draw_rotated_bitmap(iory1SpriteSeq.getSubBitmap(), sprite1.width/2, sprite1.height/2, iory1SpriteSeq.getX(), iory1SpriteSeq.getY(), 
			//						degrees * 3.1415 / 180, iory1SpriteSeq.getDrawFlags());
			
			//al_draw_tinted_bitmap(sprite.bitmap, al_map_rgb(255, 0, 0), x, y, NULL);
			
			//al_draw_scaled_bitmap(subBitmap, 16, 16, 16, 16, x, y, 32 * degrees, 32 * degrees, NULL);
			
			ALLEGRO_COLOR red = al_map_rgb(255,0,0);
			ALLEGRO_COLOR blue = al_map_rgb(0,0,255);

			al_draw_line(
				(float) iory1SpriteSeq.getX(), 
				(float) iory1SpriteSeq.getY() - 10.10, 
				(float) iory1SpriteSeq.getX(), 
				(float) iory1SpriteSeq.getY() - 20.0, 
				red, 
				1.0);

			al_draw_line(
				(float) iory1SpriteSeq.getCenterX(), 
				(float) iory1SpriteSeq.getY() - 30.0, 
				(float) iory1SpriteSeq.getCenterX(), 
				(float) iory1SpriteSeq.getY() - 40.0, 
				blue, 
				1.0);

			al_draw_line(
				(float) iory2SpriteSeq.getX(), 
				(float) iory2SpriteSeq.getY() - 10.10, 
				(float) iory2SpriteSeq.getX(), 
				(float) iory2SpriteSeq.getY() - 20.0, 
				red, 
				1.0);

			al_draw_line(
				(float) iory2SpriteSeq.getCenterX(), 
				(float) iory2SpriteSeq.getY() - 30.0, 
				(float) iory2SpriteSeq.getCenterX(), 
				(float) iory2SpriteSeq.getY() - 40.0, 
				blue, 
				1.0);
			
			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
		}
	}
	
	al_destroy_display(display);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);

	return 0;
}
Beispiel #21
0
int main()
{
	// don't forget to put allegro-5.0.10-monolith-md-debug.lib
	const float FPS = 60.0f;

	ALLEGRO_DISPLAY *display;

	if(!al_init())
	{
		al_show_native_message_box(NULL,"Error","Error",
									"Cannot initialize Allegro", NULL, NULL);
		return -1;
	}

	display = al_create_display(ScreenWidth, ScreenHeight);

	if(!display)
	{
		al_show_native_message_box(NULL,"Error","Error",
									"Cannot create dsiplay", NULL, NULL);
		return -1;
	}

	al_set_window_position(display, 100, 100);

	al_install_keyboard();
	al_install_mouse();

	al_init_image_addon();
	//al_init_acodec_addon();

	al_init_font_addon();
	al_init_ttf_addon();

	ALLEGRO_TIMER *timer  = al_create_timer(1.0f / FPS);
	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	ALLEGRO_KEYBOARD_STATE keyState;

	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));

	bool done = false;

	InputManager input;
	ScreenManager::GetInstance().Initialize();
	ScreenManager::GetInstance().LoadContent();



	std::vector<int> keys;

	//these two below plus the IsKeyReleased are example how to use simultaneous keys
	keys.push_back(ALLEGRO_KEY_DOWN);
	keys.push_back(ALLEGRO_KEY_ESCAPE);

	float fade = 0.0f;

	al_start_timer(timer);

	while (!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);
		al_get_keyboard_state(&keyState);

		if(input.IsKeyReleased(ev,keys))
			done=true; //closes the game
		//barnhen to check begin
		if(input.IsKeyPressed(ev, ALLEGRO_KEY_RIGHT))
			fade++;
		else if(input.IsKeyPressed(ev, ALLEGRO_KEY_LEFT))
			fade--;
		//barnhen to check end

		ScreenManager::GetInstance().Update(ev);
		ScreenManager::GetInstance().Draw(display);

		al_flip_display();
		al_clear_to_color(al_map_rgb(0,0,0));
	}

	ScreenManager::GetInstance().UnloadContent();

	//Destroyers
	al_destroy_display(display);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);

	//std::cin.get();
	return 0;
}
int main()
{
	const float FPS = 60.0f;

	ALLEGRO_DISPLAY *display;

	if(!al_init())
	{
		al_show_native_message_box(NULL,"Error","Error",
			"Cannot initialize Allegro",NULL,NULL);
		return -1;
	}

	display = al_create_display(ScreenWidth, ScreenHeight);

	if(!display)
	{
		al_show_native_message_box(NULL,"Error","Error",
			"Cannot create display",NULL,NULL);
		return -1;
	}

	al_install_keyboard();
	al_install_mouse();

	al_init_font_addon();
	al_init_ttf_addon();
	al_init_image_addon();
	//al_init_acodec_addon();
	
	ALLEGRO_TIMER *timer = al_create_timer(1.0f / FPS);
	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();
	ALLEGRO_KEYBOARD_STATE keystate;

	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));

	InputManager input;
	ScreenManager::GetInstance().Initialize();
	ScreenManager::GetInstance().LoadContent();

	bool done = false;

	al_set_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA);

	al_start_timer(timer);

	while(!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);
		al_get_keyboard_state(&keystate);

		if(input.IsKeyPressed(ev, ALLEGRO_KEY_ESCAPE))
			done = true;
		else if(input.IsKeyReleased(ev, ALLEGRO_KEY_SPACE))
			done = true;

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

		ScreenManager::GetInstance().Update(ev);
		ScreenManager::GetInstance().Draw(display);
		
		al_flip_display();
		al_clear_to_color(al_map_rgb(0,0,0));
	}

	ScreenManager::GetInstance().UnloadContent();

	al_destroy_display(display);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);

	return 0;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *evqueue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_KEYBOARD_STATE keyboard_state;
    ALLEGRO_EVENT event;
    ALLEGRO_FONT *font;
    ALLEGRO_BITMAP *clock_hand, *clock_quadrant, *bow, *sword;
    float clock_ray = 0, clock_angle = 0;
    int clock_ray_alpha;
    float soul_interval = SOUL_TIME_INTERVAL;
    FuzzyPlayer *player, *cpu;
    FuzzyGame * game;

	bool running = true;
	bool redraw = true;

	int map_x = 13*16, map_y = 5*16;
	int screen_width = WINDOW_WIDTH;
	int screen_height = WINDOW_HEIGHT;
    double curtime;

	/* Initialization */
    fuzzy_iz_error(al_init(), "Failed to initialize allegro");
    fuzzy_load_addon("image", al_init_image_addon());
    fuzzy_load_addon("primitives", al_init_primitives_addon());
    fuzzy_load_addon("keyboard", al_install_keyboard());
    fuzzy_load_addon("mouse", al_install_mouse());
    al_init_font_addon();

	fuzzy_iz_error(timer = al_create_timer(1.0 / FPS), "Cannot create FPS timer");
    fuzzy_iz_error(evqueue = al_create_event_queue(), "Cannot create event queue");
	fuzzy_iz_error(display = al_create_display(screen_width, screen_height),
      "Cannot initialize display");
    al_set_window_title(display, WINDOW_TITLE);
    fuzzy_iz_error(font = al_load_font(fuzzy_res(FONT_FOLDER, "fixed_font.tga"), 0, 0), "Cannot load 'fixed_font.tga'");
    clock_hand = al_load_bitmap(fuzzy_res(PICTURE_FOLDER, "clock_hand.png"));
    fuzzy_iz_error(clock_hand, "Cannot load clock handle");
    clock_quadrant = al_load_bitmap(fuzzy_res(PICTURE_FOLDER, "clock_quadrant.png"));
    fuzzy_iz_error(clock_hand, "Cannot load clock quadrant");
    bow = al_load_bitmap(fuzzy_res(PICTURE_FOLDER, "bow.png"));
    fuzzy_iz_error(clock_hand, "Cannot load bow image");
    sword = al_load_bitmap(fuzzy_res(PICTURE_FOLDER, "sword.png"));
    fuzzy_iz_error(clock_hand, "Cannot load sword image");

	/* Queue setup */
	al_register_event_source(evqueue, al_get_display_event_source(display));
	al_register_event_source(evqueue, al_get_timer_event_source(timer));
	al_register_event_source(evqueue, al_get_keyboard_event_source());
    al_register_event_source(evqueue, al_get_mouse_event_source());

    /* Game setup */
    game = fuzzy_game_new("level000.tmx");
    player = fuzzy_player_new(game, FUZZY_PLAYER_LOCAL, "Dolly");
    cpu = fuzzy_player_new(game, FUZZY_PLAYER_CPU, "CPU_0");

    fuzzy_chess_add(game, player, FUZZY_FOO_LINK, 34, 30);
    fuzzy_chess_add(game, player, FUZZY_FOO_LINK, 33, 30);
    fuzzy_chess_add(game, cpu, FUZZY_FOO_LINK, 40, 30);
    bool showing_area = false;
    FuzzyChess *chess, *focus = NULL;

	al_clear_to_color(al_map_rgb(0, 0, 0));
    al_draw_bitmap(game->map->bitmap, -map_x, -map_y, 0);
	al_flip_display();

#if DEBUG
	ALLEGRO_BITMAP *icon;
    int fps, fps_accum;
    double fps_time;

    icon = al_load_bitmap(fuzzy_res(PICTURE_FOLDER, "icon.tga"));
    if (icon)
        al_set_display_icon(display, icon);
    fps_accum = fps_time = 0;
    fps = FPS;
#endif
    /* Server connection */
    int svsock;
    //~ FuzzyMessage * sendmsg = fuzzy_message_new();
    svsock = fuzzy_server_connect(FUZZY_DEFAULT_SERVER_ADDRESS, FUZZY_DEFAULT_SERVER_PORT);

    _aaa_menu(game, svsock);

	/* MAIN loop */
    player->soul_time = al_get_time();
    al_start_timer(timer);
	while (running) {
        /* wait until an event happens */
		al_wait_for_event(evqueue, &event);

        switch (event.type) {
        case ALLEGRO_EVENT_TIMER:
            /* check soul ticks */
            curtime = al_get_time();
            while (curtime - player->soul_time >= soul_interval) {
                //~ fuzzy_debug("Soul tick!");
                player->soul_time += soul_interval;
                player->soul_points += SOUL_POINTS_BOOST;

                clock_ray = 1;
            }
            clock_angle = (curtime - player->soul_time)/soul_interval * FUZZY_2PI;
            if (clock_ray) {
                clock_ray = (curtime - player->soul_time)/RAY_TIME_INTERVAL * 50 + 40;
                clock_ray_alpha = (curtime - player->soul_time)/RAY_TIME_INTERVAL*(55) + 200;
                if (clock_ray >= 90)
                    clock_ray = 0;
            }

            al_get_keyboard_state(&keyboard_state);
            if (al_key_down(&keyboard_state, ALLEGRO_KEY_RIGHT)) {
                map_x += 5;
                if (map_x > (game->map->tot_width - screen_width))
                    map_x = game->map->tot_width - screen_width;
            }
            else if (al_key_down(&keyboard_state, ALLEGRO_KEY_LEFT)) {
                map_x -= 5;
                if (map_x < 0)
                    map_x = 0;
            }
            else if (al_key_down(&keyboard_state, ALLEGRO_KEY_UP)) {
                map_y -= 5;
                if (map_y < 0)
                    map_y = 0;
            }
            else if (al_key_down(&keyboard_state, ALLEGRO_KEY_DOWN)) {
                map_y += 5;
                if (map_y > (game->map->tot_height - screen_height))
                    map_y = game->map->tot_height - screen_height;
            } else if (al_key_down(&keyboard_state, ALLEGRO_KEY_O)) {
                soul_interval = fuzzy_max(0.1, soul_interval - 0.05);
            } else if (al_key_down(&keyboard_state, ALLEGRO_KEY_P)) {
                soul_interval += 0.05;
            }
            redraw = true;
            break;
        case ALLEGRO_EVENT_KEY_DOWN:
            if(! focus)
                break;

            _attack_area_off();

            switch(event.keyboard.keycode) {
                case ALLEGRO_KEY_W:
                    _chess_move(game, player, focus, focus->x, focus->y-1);
                    break;
                case ALLEGRO_KEY_A:
                    _chess_move(game, player, focus, focus->x-1, focus->y);
                    break;
                case ALLEGRO_KEY_S:
                    _chess_move(game, player, focus, focus->x, focus->y+1);
                    break;
                case ALLEGRO_KEY_D:
                    _chess_move(game, player, focus, focus->x+1, focus->y);
                    break;

                case ALLEGRO_KEY_K:
                    _attack_area_on();
                    break;
                case ALLEGRO_KEY_SPACE:
                    /* switch attack type */
                    if (! focus)
                        break;
                    if (focus->atkarea == &FuzzyMeleeMan)
                        focus->atkarea = &FuzzyRangedMan;
                    else
                        focus->atkarea = &FuzzyMeleeMan;
                    break;
            }
            break;
        case ALLEGRO_EVENT_DISPLAY_CLOSE:
            running = false;
            break;
        case ALLEGRO_EVENT_KEY_UP:
            break;
        case ALLEGRO_EVENT_KEY_CHAR:
            break;
        case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
            if(event.mouse.button == RIGHT_BUTTON) {
                _attack_area_on();
            } else if(event.mouse.button == LEFT_BUTTON) {
                /* world to tile coords */
                int tx = (event.mouse.x+map_x) / game->map->tile_width;
                int ty = (event.mouse.y+map_y) / game->map->tile_height;
#ifdef DEBUG
                printf("SELECT %d %d\n", tx, ty);
#endif
                if(showing_area && fuzzy_chess_inside_target_area(game, focus, tx, ty)) {
                    /* select attack target */
                    if (fuzzy_map_spy(game->map, FUZZY_LAYER_SPRITES, tx, ty) == FUZZY_CELL_SPRITE) {
                        if (fuzzy_chess_local_attack(game, player, focus, tx, ty))
                            _attack_area_off();
                    }
                } else {
                    /* select chess */
                    chess = fuzzy_chess_at(game, player, tx, ty);
                    if (chess && focus != chess) {
                        _attack_area_off();

                        if (focus != NULL) {
                            // already has a focus effect, just move it
                            fuzzy_sprite_move(game->map, FUZZY_LAYER_BELOW, focus->x, focus->y, tx, ty);
                        } else {
                            fuzzy_sprite_create(game->map, FUZZY_LAYER_BELOW, GID_TARGET, tx, ty);
                        }
                        focus = chess;
                    } else if (! chess) {
                        if (showing_area) {
                            // just hide the attack area
                            _attack_area_off();
                        } else if(focus) {
                            // remove the focus
                            fuzzy_sprite_destroy(game->map, FUZZY_LAYER_BELOW, focus->x, focus->y);
                            focus = NULL;
                        }
                    }
                }
            }
            break;
        default:
#ifdef DEBUG
            //~ fprintf(stderr, "Unknown event received: %d\n", event.type);
#endif
            break;
        }

        if (redraw && al_is_event_queue_empty(evqueue)) {
            curtime = al_get_time();
            fuzzy_map_update(game->map, curtime);

            // Clear the screen
            al_clear_to_color(al_map_rgb(0, 0, 0));
            al_draw_bitmap(game->map->bitmap, -map_x, -map_y, 0);

#ifdef GRID_ON
            /* Draw the grid */
            int tw = game->map->tile_width;
            int ty = game->map->tile_height;
            int x, y;
            for (x=(tw-map_x)%tw; x<screen_width; x+=tw)
                al_draw_line(x, 0, x, screen_height, al_map_rgba(7,7,7,100), 1);
            for (y=(ty-map_y)%ty; y<screen_height; y+=ty)
                al_draw_line(0, y, screen_width, y, al_map_rgba(7,7,7,100), 1);
#endif
#if DEBUG
            al_draw_filled_rounded_rectangle(screen_width-100, 4, screen_width, 30,
                8, 8, al_map_rgba(0, 0, 0, 200));
            al_draw_textf(font, al_map_rgb(255, 255, 255),
                screen_width-50, 8, ALLEGRO_ALIGN_CENTRE, "FPS: %d", fps);
#endif
            /* draw SP count */
            al_draw_filled_rounded_rectangle(4, screen_height-170, 175, screen_height-4,
                8, 8, al_map_rgba(0, 0, 0, 200));
            al_draw_textf(font, al_map_rgb(255, 255, 255),
                15, screen_height-163, ALLEGRO_ALIGN_LEFT, "SP: %d", player->soul_points);

            /* draw Soul Clock */
            al_draw_scaled_bitmap(clock_quadrant, 0, 0, 301, 301, 20, screen_height-80-139/2, 139, 139, 0);
            al_draw_scaled_rotated_bitmap(clock_hand, 160, 607, 90, screen_height-80, 0.11, 0.11, clock_angle, 0);
            al_draw_circle(90, screen_height-80, clock_ray, al_map_rgb(80, clock_ray_alpha, 80), 2.0);

            /* draw weapon */
            if (focus) {
                ALLEGRO_BITMAP * weapon;

                if (focus->atkarea == &FuzzyMeleeMan)
                    weapon = sword;
                else
                    weapon = bow;
                al_draw_scaled_bitmap(weapon, 0, 0, 90, 90, 20, 20, 60, 60, 0);
            }

            al_flip_display();
#if DEBUG
            fps_accum++;
            if (curtime - fps_time >= 1) {
                fps = fps_accum;
                fps_accum = 0;
                fps_time = curtime;
            }
#endif
            redraw = false;
        }
    }

	/* Cleanup */
    //~ void * retval;
    //~ char srvkey[FUZZY_SERVERKEY_LEN];
    //~ fuzzy_protocol_server_shutdown(svsock, sendmsg, srvkey);
    //~ fuzzy_message_del(sendmsg);
    fuzzy_game_free(game);

    al_destroy_event_queue(evqueue);
	al_destroy_display(display);
    al_destroy_timer(timer);
	return 0;
}
void personagem_update(personagem * p){
    ALLEGRO_KEYBOARD_STATE state;
    al_get_keyboard_state(&state);

    if (al_key_down(&state, ALLEGRO_KEY_LEFT) && p->x+8 > 32){
        p->x -= 1; // se quiser aumentar a velocidade, mudar este 1
        p->direcao = 'e';
    }
    if (al_key_down(&state, ALLEGRO_KEY_RIGHT) && p->x+16 < 240-32){
        p->x += 1;
        p->direcao = 'd';
    }
    if (al_key_down(&state, ALLEGRO_KEY_UP) && p->y+16 > 32){
        p->y -= 1;
        p->direcao = 'c';
    }
    if (al_key_down(&state, ALLEGRO_KEY_DOWN) && p->y+28 < 160-32){
        p->y += 1;
        p->direcao = 'b';
    }

    //Atirar
    if (al_key_down(&state, ALLEGRO_KEY_SPACE) && p->f.viva == false){
        flecha_init(&p->f, p->x+4, p->y, p->direcao);
        al_play_sample(p->som_flecha, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
    }

    //Esta apertando alguma direcao
    if(al_key_down(&state, ALLEGRO_KEY_LEFT) || al_key_down(&state, ALLEGRO_KEY_RIGHT) || al_key_down(&state, ALLEGRO_KEY_UP) || al_key_down(&state, ALLEGRO_KEY_DOWN)){
        if(p->direcao == 'c'){
            p->animacao_atual = &p->anda_c;
        }
        if(p->direcao == 'b'){
            p->animacao_atual = &p->anda_b;
        }
        if(p->direcao == 'e'){
            p->animacao_atual = &p->anda_e;
        }
        if(p->direcao == 'd'){
            p->animacao_atual = &p->anda_d;
        }
    }
    else{
        if(p->direcao == 'c'){
            p->animacao_atual = &p->parada_c;
        }
        if(p->direcao == 'b'){
            p->animacao_atual = &p->parada_b;
        }
        if(p->direcao == 'e'){
            p->animacao_atual = &p->parada_e;
        }
        if(p->direcao == 'd'){
            p->animacao_atual = &p->parada_d;
        }
    }

    animation_update(p->animacao_atual);

    flecha_update(&p->f);
}
Beispiel #25
0
int main(){
   ALLEGRO_DISPLAY *display;

	const float FPS = 60.0;
	//const float frameFPS = 15.0;
	const int largura = 800;
	const int altura = 600;
     Game *g = new Game();


	enum Direction { UP, DOWN, RIGHT, LEFT };

	if (!al_init()) {
		al_show_native_message_box(NULL, NULL, NULL, "Não pode iniciar o Allegro", NULL, 0);

		return -1;
	}

	// Setando tipo de janela a ser criada
	//al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
	//al_set_new_display_flags(ALLEGRO_OPENGL);
	//al_set_new_display_flags(ALLEGRO_OPENGL);
	al_set_new_display_flags(ALLEGRO_WINDOWED);

	display = al_create_display(largura, altura);

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_image_addon();



	ALLEGRO_KEYBOARD_STATE keyState;
	ALLEGRO_BITMAP *player = NULL;
	al_set_window_position(display,200,100);


	if (!display) {
		al_show_native_message_box(display, "Olá", "Opções do display", "Mensage,", NULL, 0);
	}


	// Mostra na tela o que está no buffer do display
	al_flip_display();

	// ***** RECEBENDO EVENTOS *****


	ALLEGRO_EVENT_QUEUE *event_queue = al_create_event_queue();

	// registrando o teclado na fila de eventos
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	// timer event
	ALLEGRO_TIMER *timer = al_create_timer( 1.0 / FPS );
	//ALLEGRO_TIMER *frametimer = al_create_timer( 1.0 / frameFPS );
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	//al_register_event_source(event_queue, al_get_timer_event_source(frametimer));


	// Game loop
	bool finalizar = false;
	bool draw = false;
	bool comer = false;
	int x = 10, y = 10;
	float velocidade = 3;
	Direction direcao = DOWN;

	srand(time(NULL)*rand());

	x = rand() % largura;
	y = rand() % altura;

    int comida_x = rand() % largura;
    int comida_y = rand() % altura;
    int cont=0;




	al_start_timer(timer);
	//al_start_timer(frametimer);

	ALLEGRO_COLOR azul = al_map_rgb(0, 0, 255);
	ALLEGRO_COLOR vermelho = al_map_rgb(255, 0, 0);

	while (!finalizar) {


		ALLEGRO_EVENT events;
		al_wait_for_event(event_queue, &events);
		al_get_keyboard_state(&keyState);


		if (events.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (events.keyboard.keycode) {
				case ALLEGRO_KEY_DOWN:
					direcao = DOWN;
					break;
				case ALLEGRO_KEY_UP:
					direcao = UP;
					break;
				case ALLEGRO_KEY_RIGHT:
					direcao = RIGHT;
					break;
				case ALLEGRO_KEY_LEFT:
					direcao = LEFT;
					break;
				case ALLEGRO_KEY_ESCAPE:
					finalizar = true;
					break;


			}
		}

		if (events.type == ALLEGRO_EVENT_TIMER) {
			switch (direcao) {
				case DOWN:
					y += velocidade;
					if(y>altura-20){
                        y =altura-20;
                        finalizar = true;
                    }

					break;
				case UP:
					y -= velocidade;
					if(y<0){
                        y=0;
                    finalizar = true;
                    }
					break;
				case RIGHT:
					x += velocidade;
					if(x > largura-20){
                        x=largura-20;
                        finalizar = true;
                    }
					break;
				case LEFT:
					x -= velocidade;
					if(x<0){
                        x=0;
                    finalizar = true;
                    }
					break;
			}

			draw = true;

		}if(Colisao(comida_x, comida_y, x, y, 20, 20)){
                    cont++;
                    if(direcao == DOWN)
                        comer = true;
                        //y -= velocidade;
                    else if(direcao == LEFT)
                        //x += velocidade;
                        comer = true;
                    else if(direcao == RIGHT)
                        //x -= velocidade;
                        comer = true;
                    else if(direcao ==UP)
                        //y +=velocidade;
                        comer = true;

                 }

		if (draw) {
            draw = false;
			// desenha retanguo 20x20 na posicao x,y nova
			//g->draw();



			if(comer){
			comer = false;
			al_draw_filled_rectangle(x, y, x+20, y+20, azul);
			al_draw_filled_circle(comida_x,comida_y, 5, vermelho);
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));

            comida_x = rand() % largura;
            comida_y = rand() % altura;
			al_draw_filled_circle(comida_x,comida_y, 5, vermelho);
            al_clear_to_color(al_map_rgb(0,0,0));
            if(cont>=3){
                velocidade++;
                cont=0;
            }
			//al_flip_display();
			//al_clear_to_color(al_map_rgb(0,0,0));

            }else{
            al_draw_filled_circle(comida_x,comida_y, 5, vermelho);
            al_draw_filled_rectangle(x, y, x+20, y+20, azul);
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));
            }// Mostra na tela o que está no buffer do display

			// preenche o buffer com preto
			al_clear_to_color(al_map_rgb(0,0,0));
		}

	}


	al_destroy_display(display);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);
	return  0;
}
Beispiel #26
0
int real_main() {
    srand48(time(NULL));

    if (!al_init()) {
        puts("Could not initialise allegro");
        return 1;
    }
    if (!al_install_keyboard()) {
        puts("Could not initialise allegro keyboard subsystem");
        return 1;
    }
    keys = malloc(sizeof(ALLEGRO_KEYBOARD_STATE));
    if (!init_font()) {
        puts("Could not initialise allegro font subsystem");
        return 1;
    }

    al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);

    ALLEGRO_DISPLAY* display = al_create_display(1, 1);
    if (!display) {
        puts("Could not initialise allegro display");
        return 1;
    }

    Vector size = new_vector();
    size.x = al_get_display_width(display);
    size.y = al_get_display_height(display);

    Game* game = new_game(size);
    int i;
    for (i = 0; i < ASTEROIDN; i++)
        spawn_asteroid(game);

    ALLEGRO_TIMER* timer = al_create_timer(1.0/FPS);

    ALLEGRO_EVENT_QUEUE *timereq = al_create_event_queue();
    ALLEGRO_EVENT_QUEUE *genericeq = al_create_event_queue();
    if (!timereq || !genericeq) {
        puts("Could not create allegro event queue");
        return 1;
    }
    al_register_event_source(timereq, al_get_timer_event_source(timer));

    al_register_event_source(genericeq, al_get_keyboard_event_source());
    al_register_event_source(genericeq, al_get_display_event_source(display));

    al_start_timer(timer); // Start generating timer events
    ALLEGRO_EVENT *timerevent = malloc(sizeof(ALLEGRO_EVENT));
    ALLEGRO_EVENT *genericevent = malloc(sizeof(ALLEGRO_EVENT));

    float last_drawn, now;
    last_drawn = now = al_get_time();
    while (game->status != Quit) {
        al_get_keyboard_state(keys);

        al_wait_for_event(timereq, NULL);
        al_get_next_event(timereq, timerevent);
        // No need to fill up the queue if we are late drawing frames
        al_flush_event_queue(timereq);

        handle_key_status(game, keys);

        while(al_get_next_event(genericeq, genericevent))
            switch(genericevent->type) {
            case ALLEGRO_EVENT_KEY_DOWN:
                handle_key_event(game, genericevent->keyboard.keycode);
                break;

            case ALLEGRO_EVENT_DISPLAY_RESIZE:
                game->size.x = genericevent->display.x;
                game->size.y = genericevent->display.y;
                al_acknowledge_resize(display);
                break;

            case ALLEGRO_EVENT_DISPLAY_CLOSE:
                game->status = Quit;
                break;
            }

        now = al_get_time();
        update_game(game, now - last_drawn);
        last_drawn = now;

        draw_game(game, game->status == Playing ? 1 : 0.2);
        switch(game->status) {
        case Playing:
            break;
        case Paused:
            draw_paused(game);
            break;
        case Won:
            draw_won(game);
            break;
        case Lost:
            draw_lost(game);
            break;
        default:
            break;
        }

        al_flip_display();
    }

    free(timerevent);
    free(genericevent);
    delete_game(game);
    return 0;
}
void ImGui_ImplA5_NewFrame()
{
    if (!g_Texture) 
        Imgui_ImplA5_CreateDeviceObjects();

    ImGuiIO &io = ImGui::GetIO();

    // Setup display size (every frame to accommodate for window resizing)
    int w, h;
    w = al_get_display_width(g_Display);
    h = al_get_display_height(g_Display);
    io.DisplaySize = ImVec2((float)w, (float)h);

    // Setup time step
    double current_time = al_get_time();
    io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f);
    g_Time = current_time;

    // Setup inputs
    ALLEGRO_KEYBOARD_STATE keys;
    al_get_keyboard_state(&keys);
    io.KeyCtrl = al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL);
    io.KeyShift = al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT);
    io.KeyAlt = al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR);

    ALLEGRO_MOUSE_STATE mouse;
    if (keys.display == g_Display) 
    {
        al_get_mouse_state(&mouse);
        io.MousePos = ImVec2((float)mouse.x, (float)mouse.y);
    }
    else 
    {
        io.MousePos = ImVec2(-1, -1);
    }

    al_get_mouse_state(&mouse);
    io.MouseDown[0] = mouse.buttons & (1 << 0);
    io.MouseDown[1] = mouse.buttons & (1 << 1);
    io.MouseDown[2] = mouse.buttons & (1 << 2);

    // Hide OS mouse cursor if ImGui is drawing it
    if (io.MouseDrawCursor)
    {
        al_set_mouse_cursor(g_Display, g_MouseCursorInvisible);
    }
    else
    {
        ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
        switch (ImGui::GetMouseCursor())
        {
        case ImGuiMouseCursor_TextInput:    cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
        case ImGuiMouseCursor_Move:         cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
        case ImGuiMouseCursor_ResizeNS:     cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
        case ImGuiMouseCursor_ResizeEW:     cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
        case ImGuiMouseCursor_ResizeNESW:   cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
        case ImGuiMouseCursor_ResizeNWSE:   cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
        }
        al_set_system_mouse_cursor(g_Display, cursor_id);
    }

    // Start the frame
    ImGui::NewFrame();
}
Beispiel #28
0
void Root::start()
{
    al_init();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();
    al_init_primitives_addon();
    al_install_keyboard();
    al_install_mouse();

    m_windowWidth = 1024;
    m_windowHeight = 768;
    m_display = al_create_display(m_windowWidth, m_windowHeight);
    m_drawTimer = al_create_timer(1.0 / FPS);
    m_tickTimer = al_create_timer(1.0 / TPS);
    m_fpsLimit = false;
    /* Initializing assets */
    m_assets = new Assets();

    /* Initializing spritesheets */
    m_spritesheetDatabase = new SpritesheetDatabase();
    m_spritesheetDatabase->load(m_assets);

    /* Initializing tiles */
    m_tileDatabase = new TileDatabase();
    addBaseTilesToDatabase();
    m_tileDatabase->load(m_assets);

    /* World generator */
    //temporarly it will be hardcoded world generator path/handle/id
    std::vector<std::string> generators = m_assets->worldGenerators();
    if(generators.empty())
    {
        std::cout << "No world generators found. Exiting.";
        return;
    }
    Configuration worldGeneratorConfig = Configuration(generators[0]);
    m_worldGenerator = new WorldGenerator(worldGeneratorConfig);

    /* Creating world */
    m_world = new World(m_worldGenerator);

    al_start_timer(m_tickTimer);
    al_start_timer(m_drawTimer);
    int framesThisSecond = 0;
    int ticksThisSecond = 0;
    int lastTicks = al_get_timer_count(m_tickTimer);
    int lastFPSTicks = al_get_timer_count(m_drawTimer);
    for(;;)
    {
        ALLEGRO_KEYBOARD_STATE currentKeyboardState;
        al_get_keyboard_state(&currentKeyboardState);
        int nowTicks = al_get_timer_count(m_tickTimer);
        int nowDrawTicks = al_get_timer_count(m_drawTimer);

        if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_ESCAPE))
        {
            return;
        }

        if(nowTicks != lastTicks && !(nowTicks % TPS))
        {
            m_currentFps = framesThisSecond;
            framesThisSecond = 0;
            m_currentTps = ticksThisSecond;
            ticksThisSecond = 0;

            std::cout << "FPS: " << m_currentFps << "\nTPS: " << m_currentTps << "\n\n";
        }

        if(nowTicks != lastTicks)
        {
            lastTicks = nowTicks;
            ++m_ticks;
            ++ticksThisSecond;

#define HIGH_SPEED_CAMERA

#ifndef HIGH_SPEED_CAMERA
            /* low camera speed */

            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_LEFT))
            {
                m_world->moveCamera(Vec2D(-3, 0));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_RIGHT))
            {
                m_world->moveCamera(Vec2D(3, 0));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_UP))
            {
                m_world->moveCamera(Vec2D(0, -3));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_DOWN))
            {
                m_world->moveCamera(Vec2D(0, 3));
            }
#else
            /* high camera speed */
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_LEFT))
            {
                m_world->moveCamera(Vec2F(-20.3, 0));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_RIGHT))
            {
                m_world->moveCamera(Vec2F(20.3, 0));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_UP))
            {
                m_world->moveCamera(Vec2F(0, -20.3));
            }
            if(al_key_down(&currentKeyboardState, ALLEGRO_KEY_DOWN))
            {
                m_world->moveCamera(Vec2F(0, 20.3));
            }

#endif // HIGH_SPEED_CAMERA
            m_world->update();
        }
        if(nowDrawTicks != lastFPSTicks || !m_fpsLimit)
        {
            lastFPSTicks = nowDrawTicks;
            ++framesThisSecond;
            al_clear_to_color(al_map_rgb(64, 128, 255));
            m_world->draw();
            al_flip_display();
        }
    }
}
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;
};
Beispiel #30
0
/*
 * Application entry point
 */
int main(int argc, char *argv[])
{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_KEYBOARD_STATE keyboard_state;
	ALLEGRO_MAP *map;
	Avatar *tar;

	bool running = true;
	bool redraw = true;

	int map_x = 0, map_y = 0;
	int screen_width = 640;
	int screen_height = 480;

	//{{{ initialization
	
	// Initialize allegro
	if (!al_init()) {
		fprintf(stderr, "Failed to initialize allegro.\n");
		return 1;
	}

	// Initialize allegro_image addon
	if (!al_init_image_addon()) {
		fprintf(stderr, "Failed to initialize image addon.\n");
		return 1;
	}

	// Initialize the timer
	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "Failed to create timer.\n");
		return 1;
	}

	// Install the keyboard
	if (!al_install_keyboard()) {
		fprintf(stderr, "Failed to install keyboard.\n");
		return 1;
	}

	// Create the display
	display = al_create_display(screen_width, screen_height);
	if (!display) {
		fprintf(stderr, "Failed to create display.\n");
		return 1;
	} else {
		al_set_window_title(display, "Hello Tiled!");
	}

	// Create the event queue
	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "Failed to create event queue.\n");
		return 1;
	}

	// Register event sources
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	//}}}
	
	// Start the timer
	al_start_timer(timer);

	// Parse the map
	map = al_open_map(MAP_FOLDER, "level1.tmx");

    // Create avatar
    tar = create_avatar(0, 0, "data/avatar.png");

	// Draw the map
	al_clear_to_color(al_map_rgb(0, 0, 0));
	al_draw_map_region(map, map_x, map_y, screen_width, screen_height, 0, 0, 0);
	al_flip_display();
	
#if DEBUG
	// FPS counter
	double old_time = al_get_time(), fps = 0;
	int frames_done = 0;
#endif

	// Main loop
	while (running) {
		ALLEGRO_EVENT event;
		ALLEGRO_TIMEOUT	timeout;

		// Initialize the timeout (not the game's clock)
		al_init_timeout(&timeout, 0.06);

		// Fetch the event (if one exists)
		bool get_event = al_wait_for_event_until(event_queue, &event, &timeout);

		// Handle the event
		if (get_event) {
			switch (event.type) {
				case ALLEGRO_EVENT_TIMER:
					// is an arrow key being held?
					al_get_keyboard_state(&keyboard_state);
					
					int x_move = 0;
					int y_move = 0;
					
					if (al_key_down(&keyboard_state, ALLEGRO_KEY_RIGHT)) {
					    x_move += 2;
					}
					if (al_key_down(&keyboard_state, ALLEGRO_KEY_LEFT)) {
						x_move -= 2;
					}
					if (al_key_down(&keyboard_state, ALLEGRO_KEY_UP)) {
						y_move -= 2;
					}
					if (al_key_down(&keyboard_state, ALLEGRO_KEY_DOWN)) {
						y_move += 2;
					}
					
					walk(tar, x_move, y_move);
					//gravity(tar, 
					
					center_viewport(tar, screen_width, screen_height, map, &map_x, &map_y);

					redraw = true;
					break;
				case ALLEGRO_EVENT_DISPLAY_CLOSE:
					running = false;
					break;
				case ALLEGRO_EVENT_KEY_DOWN:
					// ignore
					break;
				case ALLEGRO_EVENT_KEY_UP:
					// ignore
					break;
				case ALLEGRO_EVENT_KEY_CHAR:
					if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
						ALLEGRO_MAP_LAYER *collide_layer = al_get_map_layer(map, "Blocks 1");
						ALLEGRO_MAP_TILE **tiles = get_occupied_tile_ids(tar, collide_layer, map);
						fprintf(stdout, "Avatar on tiles: {%s, %s, %s, %s}\n", 
								al_get_tile_property(tiles[0], "collide", "null"), 
								al_get_tile_property(tiles[1], "collide", "null"), 
								al_get_tile_property(tiles[2], "collide", "null"), 
								al_get_tile_property(tiles[3], "collide", "null"));
						free(tiles);
						tiles = NULL;
					}
					break;
				default:
					fprintf(stderr, "Unsupported event received: %d\n", event.type);
					break;
			}
		}

		if (redraw && al_is_event_queue_empty(event_queue)) {
			// Clear the screen
			al_clear_to_color(al_map_rgb(0, 0, 0));
			
#if DEBUG
		    double game_time = al_get_time();
			if(game_time - old_time >= 1.0) {
				fps = frames_done / (game_time - old_time);

				frames_done = 0;
				old_time = game_time;
				fprintf(stderr, "FPS:%f\n", fps);
			}
			frames_done++;
#endif
			
			al_draw_map_region(map, map_x, map_y, screen_width, screen_height, 0, 0, 0);
			draw_avatar(tar, map, map_x, map_y);

			al_flip_display();
			redraw = false;
		}
	}

	// Clean up and return
	free_avatar(tar);
	al_free_map(map);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	return 0;
}