Example #1
0
void StartMenu::draw(){
	al_draw_bitmap(background, 0, 0, 0);
	al_draw_rectangle(mouseX-5, mouseY-5, mouseX+5, mouseY+5, al_map_rgb(255,0,0), 5);	//testing purposes
	al_draw_text(font36, al_map_rgb(100,0,100), 25,25,0, "Press Space to make game Lobby");
	al_draw_textf(font36, al_map_rgb(100,0,100), 25,60,0, "This is the START MENU.");
	
	int tempY = windowHeight/2 - (fontHeight * 2);
	if(selected == START_GAME_HOST)
		al_draw_text(font36, al_map_rgb(0,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Host game");
	else 
		al_draw_text(font36, al_map_rgb(255,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Host game");
	tempY += fontHeight;
	
	if(selected == START_GAME_CLIENT)
		al_draw_text(font36, al_map_rgb(0,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Connect to game");
	else 
		al_draw_text(font36, al_map_rgb(255,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Connect to game");
	tempY += fontHeight;
	
	if(selected == HELP)
		al_draw_text(font36, al_map_rgb(0,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Help");
	else 
		al_draw_text(font36, al_map_rgb(255,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Help");
	tempY += fontHeight;
	
	if(selected == EXIT)
		al_draw_text(font36, al_map_rgb(0,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Exit");
	else 
		al_draw_text(font36, al_map_rgb(255,0,255), windowWidth/2, tempY, ALLEGRO_ALIGN_CENTRE, "Exit");
}
void GameOverScreen::start(Engine * engine) {
    jumpToGame = false;                 
    entryTransition = new Fadein(al_map_rgb(0, 0, 0), 1.0);
    exitTransition = new Fadeout(al_map_rgb(0, 0, 0), 1.0);
    curTransition = entryTransition;    
}
Example #3
0
static void print(ALLEGRO_FONT *myfont, char *message, int x, int y)
{
   al_draw_text(myfont, al_map_rgb(0, 0, 0), x+2, y+2, 0, message);
   al_draw_text(myfont, al_map_rgb(255, 255, 255), x, y, 0, message);
}
Example #4
0
void game_loop(void)
{
    //load font
    ALLEGRO_FONT *font = al_load_ttf_font("RobotoMono-Medium.ttf",10,0);
    //create floor array (will eventually make this a function)
    srand(time(NULL));
    for (int x = 0; x < 16; x++)
            {
                //for each y value between 2 and 13
                for (int y = 0; y < 16; y++)
                {
                    randX = 6 + (rand() % (int)(12 - 6 + 1));
                    randY = 0 + (rand() % (int)(3 - 0 + 1));
                    //drawDungeonTile(randX, randY, x, y);
                    floorArray [x] [y] [0] = randX;
                    floorArray [x] [y] [1] = randY;
                }
            }

    Player p1;
    //(speed, friction, sprint accel, max speed)
    //default: p1.setMovement(1.4, .4, 1.8, 4);
    p1.setMovement(1.4, .4, 1.8, 3);
    p1.setPosition(tileSize * 7, tileSize * 12);
    p1.setCurrentRoom(112);
    p1.setInitial(tileSize,tileSize,240,240);
    p1.setH(tileSize);
    p1.setW(tileSize);
    p1.setAnimation(tileSize * 0, tileSize * 0,0,0,9,4,0);
    p1.canMove = true;
    p1.vincible = true;
    p1.blinking = false;
    p1.blinkTimer = 5;
    p1.setMaxHP(100);
    p1.setCurrentHP(100);
    int tempBlinkTimer = p1.blinkTimer;
    p1.knockback = 0;
    p1.knockbackTimer = 0;
    p1.setBound(19,27,7,3, 14,8,9,24);
    p1.canRotate = true;
    //p1.setX(240);
    //p1.setY(240);
    p1.leavingTransport = 0;
    //init player prototypes
    void movePlayerUp(Player &p);
    void movePlayerDown(Player &p);
    void movePlayerLeft(Player &p);
    void movePlayerRight(Player &p);
    void sprintPlayer(Player &p);
    void maxSpeedPlayer(Player &p);
    void maxWalkSpeedPlayer(Player &p);
    void updatePlayer(Player &p);
    void collidePlayerWallX(Player &p, int obstacles [16][16]);
    void collidePlayerWallY(Player &p, int obstacles [16][16]);
    void collidePlayerMonster(Player &p, Monster m[]);
    void drawPlayer(Player &p);
    void resetPlayerAnimation(Player &p);

    //load current room map
    Room currentRoom;
    currentRoom.getWalkRoom(p1.getCurrentRoom());
    //currentRoom.getCollideRoom(p1.getCurrentRoom());

    //load all objects
    objectArray currentArray;
    currentArray.getObjects(p1.getCurrentRoom());

    //load current room transporters
    Transporter currentTrans;
    currentTrans.exitNumber = 0;

    //load current room buttons
    //void getButton (int array[][16]);
    void getButton (Button b[], int array[][16]);
    //void drawButtons (int buttonArray[][16]);
    void drawButtons (Button b[]);
    void collidePlayerButton(Player &p, Button b[]);

    Button currentButts[numButts];
    getButton (currentButts, currentArray.buttsArray);

    void getDoor (Door d[], int array[][16]);
    void placeDoor (Door d[], Room &r);

    Door currentDoor[numDoors];
    getDoor (currentDoor, currentArray.buttsArray);
    //currentDoor.getDoorState();

    void getMonsters (Monster m[], int array[][16]);
    void drawMonsters (Monster m[]);
    void collideMonsterWallX(Monster m[], int obstacles [16][16]);
    void collideMonsterWallY(Monster m[], int obstacles [16][16]);
    void updateMonstersX (Monster currentMonsters[]);
    void updateMonstersY (Monster currentMonsters[]);
    //void seekMonsters (Monster m[], Player p);
    void seekMonsters (Monster &m, float x, float y);
    void seekPathMonsters (Monster &m, Player p);
    void pathfindMonsters (Monster &m, Player p, int obstacles [16][16], int mt);
    void newPathfindMonster (Monster &m, Player p, int obstacles [16][16]);
    int monsterDebug = 1;


    //init monsters prototypes
    Monster currentMonsters[numMonsters];
    //load current room's monsters
    getMonsters(currentMonsters, currentArray.array);

    Weapon stick(15, 32, 4, 0, 20, bash, none);
    stick.setAnimation(tileSize * 0, tileSize * 0,0,0,2,3,0);
    void updateWeapon(Player &p, Weapon &w);
    void collideWeaponMonster(Weapon w, Monster m[], Player p);
    void resetAttack (Player p, Weapon &w);
    void attackWeapon(Player p, Weapon &w);
    void drawWeapon(Player p, Weapon &w);

    void drawCutscene(int num, int message);
    void closingSplash(void);
    Cutscene currentCutscene;
    currentCutscene.cutsceneFont = al_load_ttf_font("data/slkscr.ttf",32,0);

    int vincibleTimer = 0;
    int pathCounter = 0;
    bool showHitboxes = false;
    bool createCutscene = false;
    bool inCutscene = false;
    bool runSeekPath = false;
    al_start_timer(timer);
 
    while (!done) {
        ALLEGRO_EVENT event;
        al_wait_for_event(event_queue, &event);
 
        if (event.type == ALLEGRO_EVENT_TIMER) 
        {
            if(key[keyW])
            {
                movePlayerUp(p1);
            }
            else if(key[keyS])
            {
                movePlayerDown(p1);
            }

            if(key[keyA])
            {
                movePlayerLeft(p1);
            }
            else if(key[keyD])
            {
                movePlayerRight(p1);
            }

            if(!(key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) 
            {
                resetPlayerAnimation(p1);
            }

            if(key[keyShift] && (key[keyW] || key[keyA] ||key[keyS] ||key[keyD])) 
            {
                sprintPlayer(p1);
            }
            else
            {
                maxWalkSpeedPlayer(p1);
            }
                maxSpeedPlayer(p1);
            if(key[keySpace])
            {
                //printf("ATTACK!\n");
            }
            
            //update player position
            p1.setX(p1.getX() + p1.getDx());
            collidePlayerMonster(p1,currentMonsters);
            collidePlayerButton(p1,currentButts);
            //printf("player DX: %f\n",p1.getDx());
            //printf("player DY: %f\n",p1.getDy());
            //X axis
            //detect and respond to collision with obstacles
            collidePlayerWallX(p1,currentRoom.collideArray);
            if(p1.canMove)
            {
                p1.setDx(p1.getDx() * p1.getFriction());
            }
            //knockback timer

            //Y axis
            p1.setY(p1.getY() + p1.getDy());
            collidePlayerWallY(p1,currentRoom.collideArray);
            p1.setDy(p1.getDy() * p1.getFriction());

            //Monster movement and wall collisions
                for (int i = 0; i < numMonsters; i++)
                {
                    if (currentMonsters[i].isLive)
                    {
                        newPathfindMonster( currentMonsters[i], p1, currentRoom.collideArray);
                    }
                }
            //seekMonsters(currentMonsters[1],p1.getX(), p1.getY());
            for (int i = 0; i < numMonsters; i++)
            {
                if (currentMonsters[i].isLive)
                {
                    //seekPathMonsters(currentMonsters[i],p1);
                    //printf("Monster location: %.1f, %.1f\n",currentMonsters[1].getX(),currentMonsters[1].getY());
                    seekMonsters(currentMonsters[i],currentMonsters[i].destX, currentMonsters[i].destY);
                    //seekMonsters(currentMonsters[i],64,64);
                }
            }
            //weapon updating
            updateWeapon(p1,stick);
            collideWeaponMonster(stick, currentMonsters, p1);
            updateMonstersX(currentMonsters);
            collideMonsterWallX(currentMonsters,currentRoom.collideArray);
            updateMonstersY(currentMonsters);
            collideMonsterWallY(currentMonsters,currentRoom.collideArray);

            //if able to transport
            if (p1.leavingTransport == 0)
            {
                //check for collisions with transporter
                currentTrans.exitNumber = currentTrans.playerTransCollision(p1.getX(), p1.getY(),currentArray.array);
                if (currentTrans.exitNumber)
                {
                    currentTrans.fromNumber = p1.getCurrentRoom();
                    p1.leavingTransport = 1;
                }
            }

            //if transporting
            if ( p1.leavingTransport == 1)
            {
                //set room to move to
                p1.setCurrentRoom(currentTrans.exitNumber);
                currentRoom.getWalkRoom(p1.getCurrentRoom());
                //currentRoom.getCollideRoom(p1.getCurrentRoom());
                currentArray.getObjects(p1.getCurrentRoom());
                getMonsters(currentMonsters, currentArray.array);
                getButton(currentButts, currentArray.buttsArray);
                getDoor(currentDoor, currentArray.buttsArray);
                placeDoor(currentDoor, currentRoom);
                //must set player's location to the location of the exit portal in the new room
                currentTrans.getDestination(currentArray.array);
                p1.setX(currentTrans.destination[0] + tileSize/2);
                p1.setY(currentTrans.destination[1] + tileSize/2);
                currentTrans.destination[0] = 0;
                currentTrans.destination[1] = 0;
                p1.leavingTransport = 0;
            }

            //functions for drawing the player (will need to go elsewhere eventually)
            //invincible timer
            if (p1.vincible == false)
            {
                vincibleTimer ++;
                tempBlinkTimer --;

                p1.blinking = true;
                //printf("p1 blinking? %d, %d\n",p1.blinking, tempBlinkTimer);
                if (tempBlinkTimer < 0)
                {
                    p1.blinking = false;
                    if ( tempBlinkTimer == p1.blinkTimer * (-3))
                    {
                        tempBlinkTimer = p1.blinkTimer;
                    }
                }
                if (vincibleTimer == invincibleTime)
                {
                    p1.vincible = true;
                    p1.blinking = false;
                    vincibleTimer = 0;
                    //printf ("vincible Again \n");
                }
            }
            pathCounter ++;
            if (pathCounter == 90) {pathCounter = 0;}

            redraw = true;
         }

        //key pressed down
        else if (event.type == ALLEGRO_EVENT_KEY_DOWN) 
        {
            switch (event.keyboard.keycode)
            {
                case ALLEGRO_KEY_ESCAPE:
                done = true;

                case ALLEGRO_KEY_W:
                key[keyW] = true;
                break;

                case ALLEGRO_KEY_A:
                key[keyA] = true;
                break;

                case ALLEGRO_KEY_S:
                key[keyS] = true;
                break;

                case ALLEGRO_KEY_D:
                key[keyD] = true;
                break;

                case ALLEGRO_KEY_C:
                key[keyC] = true;
                if (!inCutscene)
                {
                    currentCutscene.openDialog ("data/cutscenes/1");
                    createCutscene = 1;
                }
                if (inCutscene)
                {
                    currentCutscene.currentMessage ++;
                }
                while(1)
                break;

                case ALLEGRO_KEY_LSHIFT:
                key[keyShift] = true;
                break;

                case ALLEGRO_KEY_SPACE:
                key[keySpace] = true;
                runSeekPath = true;
                //pathfindMonsters( currentMonsters[1], p1, currentRoom.collideArray, pathCounter);
                newPathfindMonster( currentMonsters[1], p1, currentRoom.collideArray);
                attackWeapon(p1,stick);
                break;
            }
        }

        //key released
        else if (event.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch (event.keyboard.keycode)
            {
                case ALLEGRO_KEY_W:
                key[keyW] = false;
                break;

                case ALLEGRO_KEY_A:
                key[keyA] = false;
                break;

                case ALLEGRO_KEY_S:
                key[keyS] = false;
                break;

                case ALLEGRO_KEY_D:
                key[keyD] = false;
                break;

                case ALLEGRO_KEY_C:
                key[keyC] = false;
                break;

                case ALLEGRO_KEY_LSHIFT:
                key[keyShift] = false;
                break;

                case ALLEGRO_KEY_SPACE:
                key[keySpace] = false;
                resetAttack(p1, stick);
                break;
            }
        }
        
        else if(event.type == ALLEGRO_EVENT_MOUSE_AXES || ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY)
        {
           crosshair_x = event.mouse.x - crosshairSize/2;
           crosshair_y = event.mouse.y - crosshairSize/2;
        }
        
        if (redraw && al_is_event_queue_empty(event_queue)) {
            redraw = false;
            //Clear screen to black
            al_clear_to_color(al_map_rgb(0, 0, 0));

            if (createCutscene == true)
            {
                al_set_target_bitmap(cutsceneBackdrop);
                al_clear_to_color(al_map_rgb(0, 0, 0));
            }

            //update_graphics();
            //graphics that will always be there
            if (!inCutscene)
            {
                //drawDoor(currentDoor,currentRoom);
                drawDungeon(floorArray,currentRoom.walkArray);
                drawDungeon(floorArray,currentRoom.collideArray);
                for (int i = 0; i < 16; i++)
                {
                    for (int j = 0; j < 16; j++)
                    {
                        al_draw_textf(font, al_map_rgb(255,255,255),j*tileSize,i*tileSize,ALLEGRO_ALIGN_LEFT,"%d,%d",j+1,i+1);
                    }
                }

                if (transDebug) currentTrans.drawTransporters(currentArray.array);
                drawButtons(currentButts);
                drawMonsters(currentMonsters);
                
                if (p1.getDir() != UP && p1.getDir() != LEFT)
                {
                    if (p1.blinking == false)
                    {
                        drawPlayer(p1);
                    }
                }
                drawWeapon(p1,stick);

                if (p1.getDir() == UP || p1.getDir() == LEFT)
                {
                    if (p1.blinking == false)
                    {
                        drawPlayer(p1);
                    }
                }

                al_draw_textf(font, al_map_rgb(255,255,255),0,tileSize*0,ALLEGRO_ALIGN_LEFT,"playerHP: %d",p1.getCurrentHP());
                for (int i = 1; i < numMonsters; i++)
                {
                    if (currentMonsters[i].getCurrentHP() > -10000 && currentMonsters[i].getCurrentHP() <10000)
                    {
                        al_draw_textf(font, al_map_rgb(255,255,255),tileSize * 4 * i,tileSize*15,ALLEGRO_ALIGN_LEFT,"monster %d HP: %d",i,currentMonsters[i].getCurrentHP());
                    }
                }
            }
            if (inCutscene)
            {
                currentCutscene.drawCutscene(1, 1);
            }
            //al_draw_bitmap(crosshair, crosshair_x, crosshair_y, 0);

            if (createCutscene == true)
            {
                inCutscene = true;
                createCutscene = false;
                al_set_target_bitmap(al_get_backbuffer(display));
                //al_lock_bitmap(cutsceneBackdrop);
                inCutscene = true;
            }
            al_flip_display();
        }
    }
}
int main(int argc, char **argv) {
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	bool redraw = true;
	bool doexit = false;
	bool key[4] = { false, false, false, false };

	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}
	if (!al_init_image_addon()) {
		al_show_native_message_box(display, "Error", "Error", "Failed to initialize al_init_image_addon!",
			NULL, ALLEGRO_MESSAGEBOX_ERROR);
		return 0;
	}
	if (!al_install_keyboard()) {
		fprintf(stderr, "failed to initialize the keyboard!\n");
		return -1;
	}

	collider collide;
	std::vector<bouncer *> balls;
	std::vector<tile*> tiles;
	std::vector<move *> moveVector;
	ALLEGRO_BITMAP *image = NULL;
	image = al_load_bitmap("megamanss.png");
	
	if (!image) {
		al_show_native_message_box(display, "Error", "Error", "Failed to load image!",
			NULL, NULL);
		al_destroy_display(display);
		return 0;
	}
	
	for (int i = 0; i < NUM_BALLS; i++)
	{
		bouncer* a;
		a = new bouncer(30 * i, 30 * i, 10, i / 5.0, i);

		balls.push_back(a);
		//  collide.add(a);
	}
	for (int i = 0; i < NUM_TILES; i++)
	{
		tile * a;
		//     std::cout << i%16 << "\t" << i/12 << "\n";
		a = new tile(TILE_SIZE * (i % 16), TILE_SIZE * (i / 16), TILE_SIZE);
		tiles.push_back(a);
		//  collide.add(a);
	}
	animator *anim = new animator("megamanss.png", "Source/megamanss.txt");
	//ballGenerator *bg = new ballGenerator(100,100,&collide,&balls);
	//PokemonFactory pf;

	pokemon * p = new pokemon("treeko", 1, 2, 3, 4);
	MoveFactory *mf = new MoveFactory();
	move *m = mf->Create(SWAG, "swag", p, p, 0, 400, 200);
	moveVector.push_back(m);
	collide.add(p);
	collide.add(m);
	//    bouncer b(20,20,32,3,4);
	//   bouncer c(30,30,32,4,4);
	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "failed to create timer!\n");
		return -1;
	}

	display = al_create_display(SCREEN_W, SCREEN_H);
	if (!display) {
		fprintf(stderr, "failed to create display!\n");
		al_destroy_timer(timer);
		return -1;
	}
	

	al_set_target_bitmap(al_get_backbuffer(display));

	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event_queue!\n");

		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_register_event_source(event_queue, al_get_keyboard_event_source());

	al_clear_to_color(al_map_rgb(0, 0, 0));

	al_flip_display();

	al_start_timer(timer);



	std::cout << "\nDONE WITH INIT\n";
	while (!doexit)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_TIMER) {
			collide.update();
			anim->update();
			for (int i = 0; i < moveVector.size(); i++)
			{
				std::cout << "moveVector.size()" << moveVector.size() << "\n";
				if (moveVector[i]->markForDeath == true)
				{

					delete moveVector[i];
					moveVector.erase(moveVector.begin() + i);
					i--;

				}
				else
				{
					moveVector[i]->update();
				}
			}
			/*
			if (m != NULL && m->markForDeath == true)
			{
			std::cout << "deleting object";
			delete m;
			m = NULL;
			}
			else if (m!= NULL)

			m->update();
			*/
			for (int i = 0; i < balls.size(); i++)
			{
				if (balls[i]->markForDeath == true)
				{
					collide.remove(balls[i]);
					delete balls[i];
					balls.erase(balls.begin() + i);
					i--;
				}
				else
				{
					balls[i]->update();
				}

			}
			
			if (key[KEY_UP]) {
				anim->switchAnimations(1);
			}

			if (key[KEY_DOWN]) {
				anim->switchAnimations(2);
			}

			if (key[KEY_LEFT]) {
				anim->switchAnimations(3);
			}

			if (key[KEY_RIGHT]) {
				anim->switchAnimations(4);
			}
			
			// for (int i = 0; i < tiles.size(); i++)
			//   tiles[i]->update();

			p->update();
			//bg->update();
			redraw = true;
		}



		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = true;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = true;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = true;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = true;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = false;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = false;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = false;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = false;
				break;

			case ALLEGRO_KEY_ESCAPE:
				doexit = true;
				break;
			}
		}
		if (redraw && al_is_event_queue_empty(event_queue)) {
			redraw = false;
			al_set_target_bitmap(al_get_backbuffer(display));
			al_clear_to_color(al_map_rgb(0, 0, 0));
			// al_draw_bitmap(image,200,200,0);

			for (int i = 0; i < moveVector.size(); i++)
				moveVector[i]->draw();
			/*
			for (int i = 0; i < tiles.size(); i++)
			tiles[i]->draw();
			for (int i = 0; i < balls.size(); i++)
			balls[i]->draw();*/
			anim->draw(100, 100);
			p->draw();

			
		
			al_flip_display();
		}
	}
	for (int i = 0; i < tiles.size(); i++)
		delete tiles[i];
	for (int i = 0; i < balls.size(); i++)
		delete balls[i];


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

	return 0;
}
Example #6
0
int main(int argc, char **argv)
{
   ALLEGRO_TIMER *timer;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_MONITOR_INFO info;
   const char* bitmap_filename;
   int w = 640, h = 480;
   bool done = false;
   bool need_redraw = true;
   bool background = false;
   example.show_help = true;
   example.hold_bitmap_drawing = false;

   if (argc > 1) {
      bitmap_filename = argv[1];
   }
   else {
      bitmap_filename = "data/mysha256x256.png";
   }

   if (!al_init()) {
      abort_example("Failed to init Allegro.\n");
   }

   if (!al_init_image_addon()) {
      abort_example("Failed to init IIO addon.\n");
   }

   al_init_font_addon();
   init_platform_specific();

   al_get_num_video_adapters();
   
   al_get_monitor_info(0, &info);

   al_set_new_display_option(ALLEGRO_SUPPORTED_ORIENTATIONS,
                             ALLEGRO_DISPLAY_ORIENTATION_ALL, ALLEGRO_SUGGEST);
   example.display = al_create_display(w, h);
   if (!example.display) {
      abort_example("Error creating display.\n");
   }

   w = al_get_display_width(example.display);
   h = al_get_display_height(example.display);

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

   al_install_touch_input();

   example.font = al_create_builtin_font();
   if (!example.font) {
      abort_example("Error creating builtin font\n");
   }

   example.mysha = al_load_bitmap(bitmap_filename);
   if (!example.mysha) {
      abort_example("Error loading %s\n", bitmap_filename);
   }

   example.white = al_map_rgb_f(1, 1, 1);
   example.half_white = al_map_rgba_f(1, 1, 1, 0.5);
   example.dark = al_map_rgb(15, 15, 15);
   example.red = al_map_rgb_f(1, 0.2, 0.1);
   change_size(256);
   add_sprite();
   add_sprite();

   timer = al_create_timer(1.0 / FPS);

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());
   al_register_event_source(queue, al_get_mouse_event_source());
   al_register_event_source(queue, al_get_timer_event_source(timer));
   
   if (al_install_touch_input())
      al_register_event_source(queue, al_get_touch_input_event_source());
   al_register_event_source(queue, al_get_display_event_source(example.display));

   al_start_timer(timer);

   while (!done) {
      float x, y;
      ALLEGRO_EVENT event;
      w = al_get_display_width(example.display);
      h = al_get_display_height(example.display);

      if (!background && need_redraw && al_is_event_queue_empty(queue)) {
         double t = -al_get_time();
         add_time();
         al_clear_to_color(al_map_rgb_f(0, 0, 0));
         redraw();
         t += al_get_time();
         example.direct_speed_measure  = t;
         al_flip_display();
         need_redraw = false;
      }

      al_wait_for_event(queue, &event);
      switch (event.type) {
         case ALLEGRO_EVENT_KEY_CHAR: /* includes repeats */
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)
               done = true;
            else if (event.keyboard.keycode == ALLEGRO_KEY_UP) {
               add_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_DOWN) {
               remove_sprites(1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_LEFT) {
               change_size(example.bitmap_size - 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT) {
               change_size(example.bitmap_size + 1);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_F1) {
               example.show_help ^= 1;
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               example.use_memory_bitmaps ^= 1;
               change_size(example.bitmap_size);
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_B) {
               example.blending++;
               if (example.blending == 5)
                  example.blending = 0;
            }
            else if (event.keyboard.keycode == ALLEGRO_KEY_H) {
               example.hold_bitmap_drawing ^= 1;
            }
            break;

         case ALLEGRO_EVENT_DISPLAY_CLOSE:
            done = true;
            break;

         case ALLEGRO_EVENT_DISPLAY_HALT_DRAWING:

            background = true;
            al_acknowledge_drawing_halt(event.display.source);

            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESUME_DRAWING:
            background = false;
            al_acknowledge_drawing_resume(event.display.source);
            break;
         
         case ALLEGRO_EVENT_DISPLAY_RESIZE:
            al_acknowledge_resize(event.display.source);
            break;
              
         case ALLEGRO_EVENT_TIMER:
            update();
            need_redraw = true;
            break;
         
         case ALLEGRO_EVENT_TOUCH_BEGIN:
            x = event.touch.x;
            y = event.touch.y;
            goto click;

         case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
            x = event.mouse.x;
            y = event.mouse.y;
            goto click;
            
         click:
         {
            int fh = al_get_font_line_height(example.font);
            
            if (x < fh * 12 && y >= h - fh * 30) {
               int button = (y - (h - fh * 30)) / (fh * 6);
               if (button == 0) {
                  example.use_memory_bitmaps ^= 1;
                  change_size(example.bitmap_size);
               }
               if (button == 1) {
                  example.blending++;
                  if (example.blending == 5)
                     example.blending = 0;
               }
               if (button == 3) {
                  if (x < fh * 6)
                     remove_sprites(example.sprite_count / 2);
                  else
                     add_sprites(example.sprite_count);
               }
               if (button == 2) {
                  int s = example.bitmap_size * 2;
                  if (x < fh * 6)
                     s = example.bitmap_size / 2;
                  change_size(s);
               }
               if (button == 4) {
                  example.show_help ^= 1;
               }
                
            }
            break;
         }
      }
   }

   al_destroy_bitmap(example.bitmap);

   return 0;
}
Example #7
0
int main(int argc, char **argv)

{
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_BITMAP *pared2 = NULL;
	ALLEGRO_BITMAP *carretera = NULL;
	ALLEGRO_BITMAP *fondo = NULL;
	ALLEGRO_BITMAP *tierra = NULL;
	ALLEGRO_BITMAP *coche = NULL;
	ALLEGRO_BITMAP *coche2 = NULL;
	ALLEGRO_BITMAP *otros = NULL;
	ALLEGRO_BITMAP *porche1 = NULL;
	ALLEGRO_BITMAP *porche2 = NULL;
	ALLEGRO_BITMAP *porche3 = NULL;
	ALLEGRO_BITMAP *porche4 = NULL;
	ALLEGRO_BITMAP *porche5 = NULL;
	ALLEGRO_BITMAP *porche6 = NULL;
	ALLEGRO_BITMAP *freno = NULL;
	ALLEGRO_BITMAP *ciudad = NULL;
	ALLEGRO_BITMAP *ganas = NULL;
	ALLEGRO_BITMAP *pierdes = NULL;
	ALLEGRO_FONT *font = NULL;
	int i = 3;
	int objetivo = 10000;
	int tiempo = 3600;
	float velocidad = 0;
	float carreteray = 0;
	float carreteray2 = 720;
	float bouncer_x = 360;
	float bouncer_y = (SCREEN_H / 10) * 9;
	int camaraX;
	float carreterax1;
	float carreterax2;
	float angulo = 1.571;
	float velocidadt = -10;
	float veltraficox, veltraficoy;
	float centro = 695;
	float ladoizq = 620;
	float ladoder = 790;
	float frenosi = 3;
	float hasganao = 5000;
	float hasperdio = 5000;
	bool key[5] = { false, false, false, false, false};
	bool redraw = true;
	bool doexit = false;

	struct Trafico trafico1 = {1000, 300, 1000, 5, 1};
	struct Trafico trafico2 = {850, 200, 850, 5 , 2};
	struct Trafico trafico3 = {1170, 0, 1170, 5, 3};
	struct Trafico trafico4 = {1000, 400, 1000, 5, 4};
	struct Trafico trafico5 = {850, 100, 850, 5, 1};
	struct Trafico trafico6 = {1170, 500, 1170, 5, 2};


	if (!al_init()) {
		fprintf(stderr, "failed to initialize allegro!\n");
		return -1;
	}

	if (!al_init_image_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

	if (!al_init_primitives_addon()) {
		al_show_native_message_box(display, "Error", "Error", "No carga lo de primitivos", NULL, ALLEGRO_MESSAGEBOX_ERROR);

	}

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

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

	display = al_create_display(SCREEN_W, SCREEN_H);
	if (!display) {
		fprintf(stderr, "failed to create display!\n");
		al_destroy_timer(timer);
		return -1;
	}

	al_init_font_addon();
	al_init_ttf_addon();

	font = al_load_ttf_font("djc2.otf", 60, 0);

	pared2 = al_create_bitmap(PARED2_X, PARED2_Y);

	carretera = al_load_bitmap("road22.png");

	if (!carretera) {
		fprintf(stderr, "failed to create bouncer bitmap!\n");
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	fondo = al_load_bitmap("cielo2.png");
	tierra = al_load_bitmap("camino4.png");
	coche = al_load_bitmap("outrun2.png");
	otros = al_load_bitmap("outruntrprueba5.png");
	ciudad = al_load_bitmap("ciudad3.png");
	freno = al_load_bitmap("freno.png");

	ganas = al_load_bitmap("youwin.png");
	pierdes = al_load_bitmap("youlose.png");
	
	al_convert_mask_to_alpha(coche, al_map_rgb(186, 254, 202));
	al_convert_mask_to_alpha(otros, al_map_rgb(186, 254, 202));

	
	if (!fondo) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	if (!coche) {
		al_show_native_message_box(display, "Error", "Error", "Falla la carga de imagen", NULL, ALLEGRO_MESSAGEBOX_ERROR);
		al_destroy_display(display);
		return 0;
	}

	al_set_target_bitmap(pared2);

	al_clear_to_color(al_map_rgb(150, 150, 150));

	al_set_target_bitmap(al_get_backbuffer(display));

	event_queue = al_create_event_queue();
	if (!event_queue) {
		fprintf(stderr, "failed to create event_queue!\n");
		al_destroy_bitmap(pared2);
		al_destroy_display(display);
		al_destroy_timer(timer);
		return -1;
	}

	al_register_event_source(event_queue, al_get_display_event_source(display));

	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_register_event_source(event_queue, al_get_keyboard_event_source());

	al_clear_to_color(al_map_rgb(0, 0, 0));

	al_flip_display();

	al_start_timer(timer);

	while (!doexit)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_TIMER) {

			tiempo -= 1;

			/*Spawn del trafico*/

			srand(time(NULL));
			int distancia = rand() % (950 - 750) + 750;
			int distancia2 = rand() % (950 - 750) + 750;
			int distancia3 = rand() % (950 - 750) + 750;
			int distancia4 = rand() % (1201 - 1050) + 1050;
			int distancia5 = rand() % (1201 - 1050) + 1050;
			int distancia6 = rand() % (1201 - 1050) + 1050;

			/*Teclas, movimiento y cambio de sprites en coche principal*/

			if (key[KEY_UP] && velocidad < 25) {
				velocidad += 0.5;
				velocidadt += 0.5;
			}
			else if (velocidad > 0) {
				velocidad -= 0.1;
				velocidadt -= 0.1;
			}

			if (key[KEY_DOWN]) {
				velocidad -= 0.3;
				velocidadt -= 0.3;
				frenosi = SCREEN_W / 2;
			}
			else{
				frenosi = 3000;
			}

			if (key[KEY_LEFT] && velocidad > 0) {
				bouncer_x -= 4;
				frenosi = frenosi + 3;
			}
			if (key[KEY_LEFT] && i > 1 && velocidad > 0) {
				i -= 1;
			}
			else if (!key[KEY_LEFT] && i < 4) {
				i += 1;
			}

			if (key[KEY_RIGHT] && velocidad > 0) {
				bouncer_x += 4;
				frenosi = frenosi - 3;
			}
			if (key[KEY_RIGHT] && i < 5 && velocidad > 0) {
				i += 1;
			}
			else if (!key[KEY_RIGHT] && i > 3) {
				i -= 1;
			}

			objetivo -= velocidad / 10;

			/*Carretera*/

			carreteray += velocidad;
			carreteray2 += velocidad;

			if (carreteray > 1080) {
				carreteray = carreteray2 - 720;
			}
			if (carreteray2 > 1080) {
				carreteray2 = carreteray -720;
			}
			
			/*Limites de sprite y velocidad segun posición*/

			if (velocidad < 0){
				velocidad = 0;
				i = 3;
			}

			if (bouncer_x < 140 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			if (bouncer_x > 590 && velocidad > 4) {
				velocidad -= 0.6;
				velocidadt -= 0.6;
			}

			/*Formulas para velocidad y posicion del trafico*/

			veltraficox = (velocidadt / 5) * cos(angulo);
			veltraficoy = (velocidadt / 5) * sin(angulo);
			trafico1.traficox += veltraficox;
			trafico1.traficoy += veltraficoy;
			trafico2.traficox += veltraficox;
			trafico2.traficoy += veltraficoy - 1;
			trafico3.traficox += veltraficox;
			trafico3.traficoy += veltraficoy - 1;
			trafico4.traficox += veltraficox;
			trafico4.traficoy += veltraficoy;
			trafico5.traficox += veltraficox;
			trafico5.traficoy += veltraficoy - 1;
			trafico6.traficox += veltraficox;
			trafico6.traficoy += veltraficoy - 1;

			/*Reaparicion del trafico.*/

			if (trafico1.traficoy > distancia) {
				trafico1.traficoy = 200;
				trafico1.traficox = trafico1.spawnp;
				trafico1.otrosi = 5;
				trafico1.otrosy = rand() % 4;
			}
			if (trafico2.traficoy > distancia2) {
				trafico2.otrosi = 5;
				trafico2.traficoy = 200;
				trafico2.traficox = trafico2.spawnp;
				trafico2.otrosy = rand() % 4;
			}

			if (trafico3.traficoy > distancia3) {
				trafico3.otrosi = 5;
				trafico3.traficoy = 200;
				trafico3.traficox = trafico3.spawnp;
				trafico3.otrosy = rand() % 4;
			}

			if (trafico4.traficoy > distancia4) {
				trafico4.otrosi = 5;
				trafico4.traficoy = 200;
				trafico4.traficox = trafico4.spawnp;
				trafico4.otrosy = rand() % 4;
			}
			if (trafico5.traficoy > distancia5) {
				trafico5.otrosi = 5;
				trafico5.traficoy = 200;
				trafico5.traficox = trafico5.spawnp;
				trafico5.otrosy = rand() % 4;
			}

			if (trafico6.traficoy > distancia6) {
				trafico6.otrosi = 5;
				trafico6.traficoy = 200;
				trafico6.traficox = trafico6.spawnp;
				trafico6.otrosy = rand() % 4;
			}


			/*Perspectiva - Falso 3D*/

			camaraX = bouncer_x;

			carreterax1 = 650 - (camaraX / 2);
			carreterax2 = 1130 - (camaraX / 2);

			if (carreterax1 < 820 - camaraX){
				carreterax1 = 820 - camaraX;
			}

			if (carreterax1 > 860 - camaraX) {
				carreterax1 = 860 - camaraX;
			}

			if (carreterax2 > 1320 - camaraX) {
				carreterax2 = 1320 - camaraX;
			}

			if (carreterax2 < 1280 - camaraX) {
				carreterax2 = 1280 - camaraX;
			}

			/*Creacion de sprites*/

			coche2 = al_create_sub_bitmap(coche, i * 130, 0, 130, 74);
			porche1 = al_create_sub_bitmap(otros, trafico1.otrosi * 130, trafico1.otrosy * 62, 130, 62);
			porche2 = al_create_sub_bitmap(otros, trafico2.otrosi * 130, trafico2.otrosy * 62, 130, 62);
			porche3 = al_create_sub_bitmap(otros, trafico3.otrosi * 130, trafico3.otrosy * 62, 130, 62);
			porche4 = al_create_sub_bitmap(otros, trafico4.otrosi * 130, trafico4.otrosy * 62, 130, 62);
			porche5 = al_create_sub_bitmap(otros, trafico5.otrosi * 130, trafico5.otrosy * 62, 130, 62);
			porche6 = al_create_sub_bitmap(otros, trafico6.otrosi * 130, trafico6.otrosy * 62, 130, 62);

			/*Cambio de sprites en Trafico*/

			/*porche1*/
			if (trafico1.traficoy > 370) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 5;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 6;
				}
			}

			if (trafico1.traficoy > 420){
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 4;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 7;
				}
			}

			if (trafico1.traficoy > 470) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 3;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 8;
				}
			}

			if (trafico1.traficoy > 520) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 2;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 9;
				}
			}

			if (trafico1.traficoy > 570) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 1;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 10;
				}

			}
			if (trafico1.traficoy > 620) {
				if (trafico1.traficox - camaraX < centro) {
					trafico1.otrosi = 0;
				}

				if (trafico1.traficox - camaraX > centro) {
					trafico1.otrosi = 11;
				}

			}

			/*porche2*/
			if (trafico2.traficoy > 370) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 5;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 6;
				}
			}

			if (trafico2.traficoy > 420) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 4;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 7;
				}
			}

			if (trafico2.traficoy > 470) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 3;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 8;
				}
			}

			if (trafico2.traficoy > 520) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 2;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 9;
				}
			}

			if (trafico2.traficoy > 570) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 1;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 10;
				}

			}
			if (trafico2.traficoy > 620) {
				if (trafico2.traficox - camaraX < centro) {
					trafico2.otrosi = 0;
				}

				if (trafico2.traficox - camaraX > centro) {
					trafico2.otrosi = 11;
				}

			}

			/*porche3*/
			if (trafico3.traficoy > 370) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 5;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 6;
				}
			}

			if (trafico3.traficoy > 420) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 4;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 7;
				}
			}

			if (trafico3.traficoy > 470) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 3;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 8;
				}
			}

			if (trafico3.traficoy > 520) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 2;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 9;
				}
			}

			if (trafico3.traficoy > 570) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 1;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 10;
				}

			}
			if (trafico3.traficoy > 620) {
				if (trafico3.traficox - camaraX < centro) {
					trafico3.otrosi = 0;
				}

				if (trafico3.traficox - camaraX > centro) {
					trafico3.otrosi = 11;
				}

			}

			/*porche4*/
			if (trafico4.traficoy > 370) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 5;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 6;
				}
			}

			if (trafico4.traficoy > 420) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 4;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 7;
				}
			}

			if (trafico4.traficoy > 470) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 3;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 8;
				}
			}

			if (trafico4.traficoy > 520) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 2;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 9;
				}
			}

			if (trafico4.traficoy > 570) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 1;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 10;
				}

			}
			if (trafico4.traficoy > 620) {
				if (trafico4.traficox - camaraX < centro) {
					trafico4.otrosi = 0;
				}

				if (trafico4.traficox - camaraX > centro) {
					trafico4.otrosi = 11;
				}

			}

			/*porche5*/
			if (trafico5.traficoy > 370) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 5;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 6;
				}
			}

			if (trafico5.traficoy > 420) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 4;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 7;
				}
			}

			if (trafico5.traficoy > 470) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 3;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 8;
				}
			}

			if (trafico5.traficoy > 520) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 2;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 9;
				}
			}

			if (trafico5.traficoy > 570) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 1;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 10;
				}

			}
			if (trafico5.traficoy > 620) {
				if (trafico5.traficox - camaraX < centro) {
					trafico5.otrosi = 0;
				}

				if (trafico5.traficox - camaraX > centro) {
					trafico5.otrosi = 11;
				}

			}

			/*porche6*/
			if (trafico6.traficoy > 370) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 5;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 6;
				}
			}

			if (trafico6.traficoy > 420) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 4;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 7;
				}
			}

			if (trafico6.traficoy > 470) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 3;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 8;
				}
			}

			if (trafico6.traficoy > 520) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 2;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 9;
				}
			}

			if (trafico6.traficoy > 570) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 1;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 10;
				}

			}
			if (trafico6.traficoy > 620) {
				if (trafico6.traficox - camaraX < centro) {
					trafico6.otrosi = 0;
				}

				if (trafico6.traficox - camaraX > centro) {
					trafico6.otrosi = 11;
				}

			}

			/*Colisiones*/

			if (ladoizq < trafico1.traficox + 65 - camaraX && trafico1.traficox + 65 - camaraX < ladoder && bouncer_y < trafico1.traficoy && trafico1.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			if (ladoizq < trafico2.traficox + 65 - camaraX && trafico2.traficox + 65 - camaraX < ladoder && bouncer_y < trafico2.traficoy && trafico2.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico3.traficox + 65 - camaraX && trafico3.traficox + 65 - camaraX < ladoder && bouncer_y < trafico3.traficoy && trafico3.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico4.traficox + 65 - camaraX && trafico4.traficox + 65 - camaraX < ladoder && bouncer_y < trafico4.traficoy && trafico4.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico5.traficox + 65 - camaraX && trafico5.traficox + 65 - camaraX < ladoder && bouncer_y < trafico5.traficoy && trafico5.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}
			if (ladoizq < trafico6.traficox + 65 - camaraX && trafico6.traficox + 65 - camaraX < ladoder && bouncer_y < trafico6.traficoy && trafico6.traficoy < 700) {
				velocidad = 0;
				velocidadt = -10;
			}

			/*Funcionamiento de la Camara*/

			if (camaraX > mundoAncho - SCREEN_W) {
				camaraX = mundoAncho - SCREEN_W;
			}

			if (camaraX < 0) {
				camaraX = 0;
			}

			if (bouncer_x > mundoAncho - SCREEN_W) {
				bouncer_x = mundoAncho - SCREEN_W;
			}

			if (bouncer_x < 0) {
				bouncer_x = 0;
			}

			/*Fin de partida*/

			if (tiempo < 0 & objetivo > 0){
				al_stop_timer(timer);
				hasperdio = 292.5;
			}

			if (objetivo < 0 & tiempo > 0) {
				al_stop_timer(timer);
				hasganao = 292.5;
			}

			redraw = true;
		}


		else if (ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
			break;
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_DOWN) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = true;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = true;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = true;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				key[KEY_SPACE] = true;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP) {
			switch (ev.keyboard.keycode) {
			case ALLEGRO_KEY_UP:
				key[KEY_UP] = false;
				break;

			case ALLEGRO_KEY_DOWN:
				key[KEY_DOWN] = false;
				break;

			case ALLEGRO_KEY_LEFT:
				key[KEY_LEFT] = false;
				break;

			case ALLEGRO_KEY_RIGHT:
				key[KEY_RIGHT] = false;
				break;

			case ALLEGRO_KEY_SPACE:
				key[KEY_SPACE] = false;
				break;

			case ALLEGRO_KEY_ESCAPE:
				doexit = true;
				break;
			}
		}

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

			al_clear_to_color(al_map_rgb(10, 10, 10));

			al_draw_bitmap(carretera, 640 - camaraX, carreteray, 0);
			al_draw_bitmap(carretera, 640 - camaraX, carreteray2, 0);

			al_draw_bitmap(tierra, 640 - camaraX, 0, 0);

			al_draw_filled_triangle(820 - camaraX, 720, 775 - camaraX, 400, carreterax1, 400, al_map_rgb(0, 0, 0));
			al_draw_filled_triangle(1320 - camaraX, 720, 1365 - camaraX, 400, carreterax2, 400, al_map_rgb(0, 0, 0));

			al_draw_line(820 - camaraX, 720, carreterax1, 400, al_map_rgb(0, 255, 255), 6);
			al_draw_line(1320 - camaraX, 720, carreterax2, 400, al_map_rgb(0, 255, 255), 6);

			al_draw_line(640 - camaraX, 425, carreterax1 - 4, 425, al_map_rgb(0, 255, 255), 10);
			al_draw_line(1485 - camaraX, 425, carreterax2 + 4, 425, al_map_rgb(0, 255, 255), 10);

			al_draw_bitmap(porche1, trafico1.traficox - camaraX, trafico1.traficoy, 0);
			al_draw_bitmap(porche2, trafico2.traficox - camaraX, trafico2.traficoy, 0);
			al_draw_bitmap(porche3, trafico3.traficox - camaraX, trafico3.traficoy, 0);
			al_draw_bitmap(porche4, trafico4.traficox - camaraX, trafico4.traficoy, 0);
			al_draw_bitmap(porche5, trafico5.traficox - camaraX, trafico5.traficoy, 0);
			al_draw_bitmap(porche6, trafico6.traficox - camaraX, trafico6.traficoy, 0);

			al_draw_bitmap(fondo, 640 - camaraX, 5, 0);

			al_draw_bitmap(ciudad, 640 - camaraX, 65, 0);

			al_draw_bitmap(pared2, 1485 - camaraX, 0, 0);
			al_draw_bitmap(pared2, 630 - camaraX, 0, 0);

			al_draw_bitmap(coche2, SCREEN_W / 2, bouncer_y - 10, 0);
			al_draw_bitmap(freno, frenosi, bouncer_y - 10, 0);

			al_draw_textf(font, al_map_rgb(255, 0, 0), SCREEN_W / 2 + 200, 50, 0, "%i", objetivo / 2);
			al_draw_textf(font, al_map_rgb(0, 255, 255), SCREEN_W / 2, 50, 0, "%i", tiempo / 60);

			al_draw_bitmap(ganas, hasganao, 200, 0);
			al_draw_bitmap(pierdes, hasperdio, 200, 0);

			al_flip_display();
		}
	}

	al_destroy_bitmap(fondo);
	al_destroy_bitmap(coche);
	al_destroy_timer(timer);
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);

	return 0;
}
Example #8
0
void MatchOver::DrawDropShadowText( ALLEGRO_FONT* Font, ALLEGRO_COLOR Colour, float X, float Y, int Flags, const char* Text )
{
	al_draw_text( Font, al_map_rgb( 0, 0, 0 ), X + 3, Y + 3, Flags, Text );
	al_draw_text( Font, Colour, X, Y, Flags, Text );
}
Example #9
0
Bot::Bot(slm::vec2 p):position(p) {
  color = al_map_rgb(255, 0, 0);
  AI = true;
  init();
}
Example #10
0
int main(int argc, char **argv)
{
   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_EVENT_QUEUE *event_queue = NULL;
   ALLEGRO_TIMER *timer = NULL;
   ALLEGRO_BITMAP *bouncer = NULL;
   ALLEGRO_BITMAP *pared = NULL;
   ALLEGRO_BITMAP *pared2 = NULL;
   ALLEGRO_BITMAP *cuentakm = NULL;
   ALLEGRO_FONT *font = NULL;
   int gear = 0;
   float RPM = 0;
   float KMH = 0;
   float angle = 0;
   float length = 0;
   float vel_x, vel_y;
   float bouncer_x = mundoLargo / 2;
   float bouncer_y = mundoAncho / 2;
   int camaraX = bouncer_x - SCREEN_W / 2;
   int camaraY = bouncer_y - SCREEN_H / 2;
   bool key[7] = { false, false, false, false, false, false, false };
   bool redraw = true;
   bool doexit = false;



 
   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;
   }
 
   timer = al_create_timer(1.0 / FPS);
   if(!timer) {
      fprintf(stderr, "failed to create timer!\n");
      return -1;
   }
 
   display = al_create_display(SCREEN_W, SCREEN_H);
   if(!display) {
      fprintf(stderr, "failed to create display!\n");
      al_destroy_timer(timer);
      return -1;
   }

   al_init_font_addon();
   al_init_ttf_addon();

   font = al_load_ttf_font("DTM-Sans.otf",72,0);
 
   bouncer = al_create_bitmap(BOUNCER_SIZE_X,BOUNCER_SIZE_Y);
   pared = al_create_bitmap(PARED_X,PARED_Y);
   pared2 = al_create_bitmap(PARED2_X, PARED2_Y);
   cuentakm = al_create_bitmap(CKM_X, CKM_Y);
 
   if(!bouncer) {
      fprintf(stderr, "failed to create bouncer bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }
 
   al_set_target_bitmap(bouncer);
 
   al_clear_to_color(al_map_rgb(0, 0, 0));
 
   al_set_target_bitmap(al_get_backbuffer(display));

   al_set_target_bitmap(pared);
 
   al_clear_to_color(al_map_rgb(150, 150, 150));
 
   al_set_target_bitmap(al_get_backbuffer(display));

   al_set_target_bitmap(pared2);
 
   al_clear_to_color(al_map_rgb(150, 150, 150));
 
   al_set_target_bitmap(al_get_backbuffer(display));

   al_set_target_bitmap(cuentakm);
 
   al_clear_to_color(al_map_rgb(255, 0, 0));
 
   al_set_target_bitmap(al_get_backbuffer(display));
 
   event_queue = al_create_event_queue();
   if(!event_queue) {
      fprintf(stderr, "failed to create event_queue!\n");
      al_destroy_bitmap(bouncer);
      al_destroy_bitmap(pared);
      al_destroy_bitmap(pared2);
      al_destroy_bitmap(cuentakm);
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }
 
   al_register_event_source(event_queue, al_get_display_event_source(display));
 
   al_register_event_source(event_queue, al_get_timer_event_source(timer));
 
   al_register_event_source(event_queue, al_get_keyboard_event_source());
 
   al_clear_to_color(al_map_rgb(0,0,0));
 
   al_flip_display();
 
   al_start_timer(timer);
 
   while(!doexit)
   {
      ALLEGRO_EVENT ev;
      al_wait_for_event(event_queue, &ev);
 
      if(ev.type == ALLEGRO_EVENT_TIMER) {
         
         if(key[KEY_UP] &&  RPM < 10 && gear == 0) {
            RPM += 0.4;
         }

         if(key[KEY_UP] &&  RPM < 10 && gear == 1) {
            RPM += 0.2;
         }

         if(key[KEY_UP] &&  RPM < 10 && gear == 2) {
            RPM += 0.1;
         }

         if(key[KEY_UP] &&  RPM < 10 && gear == 3) {
            RPM += 0.08;
         }

         if(key[KEY_UP] &&  RPM < 10 && gear == 4) {
            RPM += 0.05;
         }

         else if(RPM > 0) {
            RPM -= 0.04;
         }

         if(key[KEY_UP] && length < 5 && gear == 1) {
            length += 0.5;
         }

         if(key[KEY_UP] && length < 10 && gear == 2) {
            length += 0.25;
         }

         if(key[KEY_UP] && length < 20 && gear == 3) {
            length += 0.125;
         }

         if(key[KEY_UP] && length < 30 && gear == 4) {
            length += 0.0625;
         }

         else if(length > 0) {
            length -= 0.06;
         }
 
         if(key[KEY_DOWN] && length > 0) {
            length -= 0.5;
         }

         if(key[KEY_DOWN] && RPM > 0) {
            RPM -= 0.2;
         }
 
         if(key[KEY_LEFT] && length > 0) {
            angle = (angle - 0.1);
         }
 
         if(key[KEY_RIGHT] && length > 0) {
            angle = (angle + 0.1);
         }
 
         if(key[KEY_SPACE]) {
         }

         if(key[KEY_SHIFT] && gear < 4) {
            gear += 1;
            RPM -= RPM;
            key[KEY_SHIFT] = false;
            }

         if(key[KEY_CONTROL] && gear >= 1) {
            gear -= 1;
            RPM -= RPM / 2;
            key[KEY_CONTROL] = false;
         }

            vel_x = length * cos(angle);
            vel_y = length * sin(angle);
            bouncer_x += vel_x;
            bouncer_y += vel_y;


         if (camaraX < 0){
            camaraX = 0;
         }

         if (camaraY < 0) {
            camaraY = 0;
         }

         if (camaraX > mundoAncho - SCREEN_W) {
            camaraX = mundoAncho - SCREEN_W;
         }

         if (camaraY > mundoLargo - SCREEN_H) {
            camaraY = mundoLargo - SCREEN_H;
         }
 
         redraw = true;
      }


      else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
         switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_UP:
               key[KEY_UP] = true;
               break;
 
            case ALLEGRO_KEY_DOWN:
               key[KEY_DOWN] = true;
               break;
 
            case ALLEGRO_KEY_LEFT: 
               key[KEY_LEFT] = true;
               break;
 
            case ALLEGRO_KEY_RIGHT:
               key[KEY_RIGHT] = true;
               break;
            case ALLEGRO_KEY_SPACE:
               key[KEY_SPACE] = true;
               break;
            case ALLEGRO_KEY_LSHIFT:
               key[KEY_SHIFT] = true;
               break;
            case ALLEGRO_KEY_LCTRL:
               key[KEY_CONTROL] = true;
               break;
         }
      }
      else if(ev.type == ALLEGRO_EVENT_KEY_UP) {
         switch(ev.keyboard.keycode) {
            case ALLEGRO_KEY_UP:
               key[KEY_UP] = false;
               break;
 
            case ALLEGRO_KEY_DOWN:
               key[KEY_DOWN] = false;
               break;
 
            case ALLEGRO_KEY_LEFT: 
               key[KEY_LEFT] = false;
               break;
 
            case ALLEGRO_KEY_RIGHT:
               key[KEY_RIGHT] = false;
               break;

            case ALLEGRO_KEY_SPACE:
               key[KEY_SPACE] = false;
               break;

            case ALLEGRO_KEY_LSHIFT:
               key[KEY_SHIFT] = false;
               break;
            
            case ALLEGRO_KEY_LCTRL:
               key[KEY_CONTROL] = false;
               break;
 
            case ALLEGRO_KEY_ESCAPE:
               doexit = true;
               break;
         }
      }
 
      if(redraw && al_is_event_queue_empty(event_queue)) {
         redraw = false;
 
         al_clear_to_color(al_map_rgb(240,240,240));


         al_draw_bitmap(pared, 100 - camaraX, 600 - camaraY, 0);
         al_draw_bitmap(pared, 600 - camaraX, 600 - camaraY, 0);
         al_draw_bitmap(pared, 100 - camaraX, 50 - camaraY, 0);
         al_draw_bitmap(pared, 600 - camaraX, 50 - camaraY, 0);
         al_draw_bitmap(pared2, 100 - camaraX, 400 - camaraY, 0);
         al_draw_bitmap(pared2, 100 - camaraX, 100 - camaraY, 0);

         al_draw_textf(font, al_map_rgb(255,0,0), 660, 360, 0, "%i", gear);
         al_draw_textf(font, al_map_rgb(255,0,0), 660, 420, 0, "%.0f", length * 3);

         al_draw_rotated_bitmap(cuentakm, 90, CKM_Y / 2, 700, 360, RPM / 3, 0);
 
         al_draw_rotated_bitmap(bouncer, BOUNCER_SIZE_X / 3, BOUNCER_SIZE_Y / 2, bouncer_x, bouncer_y, angle, angle);

        
         al_flip_display();
      }
   }
 
   al_destroy_bitmap(bouncer);
   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);
 
   return 0;
}
Example #11
0
	draw_text("creatures may try to stop you. Don't let them!");
	draw_text("");
	x = 0.23;
	draw_text("Last but not least - You should be able to see the");
	draw_text("constellation Orion in the sky tonight. Be sure to");
	draw_text("take a moment to look for it if you have one to");
	draw_text("spare. It's beautiful!");
	draw_text("");
	x = 0.25;
	draw_text("The fate of Equestria rests in your hooves.");
	draw_text("Be safe and good luck!");
	draw_text("");
	x = 0.26;
	draw_text("Yours,");
	draw_text("Twilight Sparkle");
	al_draw_text_with_shadow(game->menu.font, al_map_rgb(255,255,255), al_get_bitmap_width(game->level.letter)*0.5, al_get_bitmap_height(game->level.letter)*0.8, ALLEGRO_ALIGN_CENTRE, "Press enter to continue...");
	al_set_target_bitmap(al_get_backbuffer(game->display));
	PROGRESS;

	al_set_target_bitmap(game->level.welcome);
	al_clear_to_color(al_map_rgba(0,0,0,0));
	al_draw_text_with_shadow(game->menu.font_title, al_map_rgb(255,255,255), game->viewportWidth*0.5, game->viewportHeight*0.1, ALLEGRO_ALIGN_CENTRE, "Level 1");
	al_draw_text_with_shadow(game->menu.font_subtitle, al_map_rgb(255,255,255), game->viewportWidth*0.5, game->viewportHeight*0.275, ALLEGRO_ALIGN_CENTRE, "Fluttershy");
	PROGRESS;
	al_set_target_bitmap(al_get_backbuffer(game->display));

	Dodger_PreloadBitmaps(game, progress);
}

void Level1_Draw(struct Game *game) {
	Dodger_Draw(game);
Example #12
0
int main(int argc, char **argv){
   ALLEGRO_DISPLAY *display = NULL;
   ALLEGRO_EVENT_QUEUE *event_queue = NULL;
   ALLEGRO_TIMER *timer = NULL;
   ALLEGRO_BITMAP *bouncer = NULL;
   ALLEGRO_BITMAP *buses[NUM_RUAS];
   int playing = 1;
   int collision = 0;
   
   //posicoes x e y iniciais do frog
   float bouncer_x = SCREEN_W / 2.0 - BOUNCER_SIZE / 2.0;
   float bouncer_y = SCREEN_H - BOUNCER_SIZE;
   //o quanto as posicoes x e y vao variar ao longo do tempo. No t=1, se x do bouncer eh 40, no t=2, x do bouncer eh 40 + bouncer_dx = 36
   float bouncer_dx = SCREEN_W /20.0, bouncer_dy = (float)SCREEN_H / NUM_RUAS;
   
   float TAM_RUA = (float) SCREEN_H / NUM_RUAS;
   float LARGURA_BUS = TAM_RUA * 0.8;
   
   //automoveis
   float buses_x[NUM_RUAS];
   float buses_y[NUM_RUAS];
   float buses_comp[NUM_RUAS];
   float buses_dx[NUM_RUAS];
   
	int i;
	int j;

	

	//----------------------- rotinas de inicializacao ---------------------------------------
   if(!al_init()) {
      fprintf(stderr, "failed to initialize allegro!\n");
      return -1;
   }
 
   timer = al_create_timer(1.0 / FPS);
   if(!timer) {
      fprintf(stderr, "failed to create timer!\n");
      return -1;
   }
 
   display = al_create_display(SCREEN_W, SCREEN_H);
   if(!display) {
      fprintf(stderr, "failed to create display!\n");
      al_destroy_timer(timer);
      return -1;
   }
 
	//cria um bitmap quadrangular de tamanho BOUNCER_SIZE (variavel global declarada acima)
   bouncer = al_create_bitmap(BOUNCER_SIZE, BOUNCER_SIZE);
   if(!bouncer) {
      fprintf(stderr, "failed to create bouncer bitmap!\n");
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }
   
   //buses
   	for(i=0; i<NUM_RUAS; i++) {
		buses_y[i] = i*TAM_RUA + 0.1*TAM_RUA;
		buses_x[i] = 0;
		buses_comp[i] = rand()%(SCREEN_W/4) + 10;
		buses_dx[i] = 3*(float)rand()/(float)RAND_MAX;
		buses[i] = al_create_bitmap(buses_comp[i], LARGURA_BUS);
		al_set_target_bitmap(buses[i]);
		al_clear_to_color(al_map_rgb(rand()%256, rand()%256, rand()%256));
	}
   
   al_install_keyboard();
 
	//avisa o allegro que eu quero modificar as propriedades do bouncer
   al_set_target_bitmap(bouncer);
 
	//altera a cor do bouncer para rgb(255,0,255)
   al_clear_to_color(al_map_rgb(0, 255, 0));
 
	//avisa o allegro que agora eu quero modificar as propriedades da tela
   al_set_target_bitmap(al_get_backbuffer(display));
	//colore a tela de preto (rgb(0,0,0))
   al_clear_to_color(al_map_rgb(0,0,0));   
 
	//cria a fila de eventos
   event_queue = al_create_event_queue();
   if(!event_queue) {
      fprintf(stderr, "failed to create event_queue!\n");
      al_destroy_bitmap(bouncer);
      al_destroy_display(display);
      al_destroy_timer(timer);
      return -1;
   }
 
	//registra na fila de eventos que eu quero identificar quando a tela foi alterada
   al_register_event_source(event_queue, al_get_display_event_source(display));
	//registra na fila de eventos que eu quero identificar quando o tempo alterou de t para t+1
   al_register_event_source(event_queue, al_get_timer_event_source(timer));
   //registra que a fila de eventos deve detectar quando uma tecla for pressionada no teclado
   al_register_event_source(event_queue, al_get_keyboard_event_source());   
 

	//reinicializa a tela
   al_flip_display();
	//inicia o temporizador
   al_start_timer(timer);
 
	//enquanto playing for verdadeiro, faca:
   while(playing) {
      ALLEGRO_EVENT ev;
	  //espera por um evento e o armazena na variavel de evento ev
      al_wait_for_event(event_queue, &ev);
	  
	//se o tipo do evento for uma tecla pressionada
	if(ev.type == ALLEGRO_EVENT_KEY_DOWN) {
		//verifica qual tecla foi
		switch(ev.keyboard.keycode) {
			//se a tecla for o W
			case ALLEGRO_KEY_W:
				bouncer_y -= bouncer_dy;
				if(bouncer_y < 0) 
					playing = 0;					
			break;
			//se a tecla for o S
			case ALLEGRO_KEY_S:
				if(bouncer_y < SCREEN_H - BOUNCER_SIZE)			
				bouncer_y += bouncer_dy;
			break;

			case ALLEGRO_KEY_A:
				if(bouncer_x > 0) 
					bouncer_x -= bouncer_dx;
			break;

			case ALLEGRO_KEY_D:
				if(bouncer_x < SCREEN_W - BOUNCER_SIZE) 
					bouncer_x += bouncer_dx;
			break;

			case ALLEGRO_KEY_ESCAPE:
				playing = 0;
			break;
			}

		}	  
 
		//se o tipo de evento for um evento do temporizador, ou seja, se o tempo passou de t para t+1
    if(ev.type == ALLEGRO_EVENT_TIMER) {
		//limpo a tela
		 al_clear_to_color(al_map_rgb(0,0,0));
		//desenho o bouncer nas novas posicoes x e y
		 al_draw_bitmap(bouncer, bouncer_x, bouncer_y, 0);
		 
		for(i=0; i<NUM_RUAS; i++) {
			buses_x[i] += buses_dx[i];
			if(buses_x[i] > SCREEN_W)
				buses_x[i] = 0;
			al_draw_bitmap(buses[i], buses_x[i], buses_y[i], 0);
			
			if( (bouncer_x + BOUNCER_SIZE > buses_x[i] && bouncer_x < buses_x[i] + buses_comp[i]) && (bouncer_y < buses_y[i] + LARGURA_BUS && bouncer_y > buses_y[i]) ) {
				playing = 0;
				collision = 1;
			}
			
		}		 
		//reinicializo a tela
		 al_flip_display();
    }
	//se o tipo de evento for o fechamento da tela (clique no x da janela)
	else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
		//interrompe o while(1)
		break;
	}
 
  } //fim do while
  
	//inicializa o modulo allegro que carrega as fontes
    al_init_font_addon();
	//inicializa o modulo allegro que entende arquivos tff de fontes
    al_init_ttf_addon();
	//carrega o arquivo arial.ttf da fonte Arial e define que sera usado o tamanho 32 (segundo parametro)
    ALLEGRO_FONT *size_32 = al_load_font("arial.ttf", 32, 1);	
	
	char my_text[20];	
		
	//colore toda a tela de preto
	al_clear_to_color(al_map_rgb(0,0,0));
	//imprime o texto armazenado em my_text na posicao x=10,y=10 e com a cor rgb(128,200,30)
	if(collision)
		al_draw_text(size_32, al_map_rgb(200, 0, 30), SCREEN_W/3, SCREEN_H/2, 0, "Perdeu :(");
	else {
		sprintf(my_text, "Ganhou: %.2f segundos", al_get_timer_count(timer)/FPS);	
		al_draw_text(size_32, al_map_rgb(0, 200, 30), SCREEN_W/3, SCREEN_H/2, 0, my_text);
	}
	
	//reinicializa a tela
	al_flip_display();	
    al_rest(3);		
   
	//procedimentos de fim de jogo (fecha a tela, limpa a memoria, etc)
	
	for(i=0; i<NUM_RUAS; i++) 
		al_destroy_bitmap(buses[i]);
   al_destroy_bitmap(bouncer);
   al_destroy_timer(timer);
   al_destroy_display(display);
   al_destroy_event_queue(event_queue);
 
   return 0;
}
Example #13
0
int main(int argc, const char **argv)
{
   ALLEGRO_AUDIO_RECORDER *r;
   ALLEGRO_AUDIO_STREAM *s;
   
   ALLEGRO_EVENT_QUEUE *q;
   ALLEGRO_DISPLAY *d;
   ALLEGRO_FILE *fp = NULL;
   ALLEGRO_PATH *tmp_path = NULL;
      
   int prev = 0;
   bool is_recording = false;
   
   int n = 0; /* number of samples written to disk */
   
   (void) argc;
   (void) argv;

   al_init();   
   
   if (!al_init_primitives_addon()) {
      abort_example("Unable to initialize primitives addon");
   }
      
   if (!al_install_keyboard()) {
      abort_example("Unable to install keyboard");
   }
      
   if (!al_install_audio()) {
      abort_example("Unable to initialize audio addon");
   }
   
   if (!al_init_acodec_addon()) {
      abort_example("Unable to initialize acodec addon");
   }
   
   /* Note: increasing the number of channels will break this demo. Other
    * settings can be changed by modifying the constants at the top of the
    * file.
    */
   r = al_create_audio_recorder(1000, samples_per_fragment, frequency,
      audio_depth, ALLEGRO_CHANNEL_CONF_1);
   if (!r) {
      abort_example("Unable to create audio recorder");
   }
   
   s = al_create_audio_stream(playback_fragment_count,
      playback_samples_per_fragment, frequency, audio_depth,
      ALLEGRO_CHANNEL_CONF_1);      
   if (!s) {
      abort_example("Unable to create audio stream");
   }
      
   al_reserve_samples(0);
   al_set_audio_stream_playing(s, false);
   al_attach_audio_stream_to_mixer(s, al_get_default_mixer());
      
   q = al_create_event_queue();
   
   /* Note: the following two options are referring to pixel samples, and have
    * nothing to do with audio samples. */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
   al_set_new_display_option(ALLEGRO_SAMPLES, 8, ALLEGRO_SUGGEST);
   
   d = al_create_display(320, 256);
      
   al_set_window_title(d, "SPACE to record. P to playback.");
   
   al_register_event_source(q, al_get_audio_recorder_event_source(r));
   al_register_event_source(q, al_get_audio_stream_event_source(s));
   al_register_event_source(q, al_get_display_event_source(d));
   al_register_event_source(q, al_get_keyboard_event_source());
   
   al_start_audio_recorder(r);
   
   while (true) {
      ALLEGRO_EVENT e;

      al_wait_for_event(q, &e);
       
      if (e.type == ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT) {
         /* We received an incoming fragment from the microphone. In this
          * example, the recorder is constantly recording even when we aren't
          * saving to disk. The display is updated every time a new fragment
          * comes in, because it makes things more simple. If the fragments
          * are coming in faster than we can update the screen, then it will be
          * a problem.
          */          
         ALLEGRO_AUDIO_RECORDER_EVENT *re = al_get_audio_recorder_event(&e);
         audio_buffer_t input = (audio_buffer_t) re->buffer;
         int sample_count = re->samples; 
         const int R = sample_count / 320;
         int i, gain = 0;
         
         /* Calculate the volume, and display it regardless if we are actively
          * recording to disk. */
         for (i = 0; i < sample_count; ++i) {
            if (gain < abs(input[i] - sample_center))
               gain = abs(input[i] - sample_center);
         }
        
         al_clear_to_color(al_map_rgb(0,0,0));
        
         if (is_recording) {
            /* Save raw bytes to disk. Assumes everything is written
             * succesfully. */
            if (fp && n < frequency / (float) samples_per_fragment * 
               max_seconds_to_record) {
               al_fwrite(fp, input, sample_count * sample_size);
               ++n;
            }

            /* Draw a pathetic visualization. It draws exactly one fragment
             * per frame. This means the visualization is dependent on the 
             * various parameters. A more thorough implementation would use this
             * event to copy the new data into a circular buffer that holds a
             * few seconds of audio. The graphics routine could then always
             * draw that last second of audio, which would cause the
             * visualization to appear constant across all different settings.
             */
            for (i = 0; i < 320; ++i) {
               int j, c = 0;
               
               /* Take the average of R samples so it fits on the screen */
               for (j = i * R; j < i * R + R && j < sample_count; ++j) {
                  c += input[j] - sample_center;
               }
               c /= R;
               
               /* Draws a line from the previous sample point to the next */
               al_draw_line(i - 1, 128 + ((prev - min_sample_val) /
                  (float) sample_range) * 256 - 128, i, 128 +
                  ((c - min_sample_val) / (float) sample_range) * 256 - 128,
                  al_map_rgb(255,255,255), 1.2);
               
               prev = c;
            }
         }
         
         /* draw volume bar */
         al_draw_filled_rectangle((gain / (float) max_sample_val) * 320, 251,
            0, 256, al_map_rgba(0, 255, 0, 128));
            
         al_flip_display();
      }
      else if (e.type == ALLEGRO_EVENT_AUDIO_STREAM_FRAGMENT) {
         /* This event is received when we are playing back the audio clip.
          * See ex_saw.c for an example dedicated to playing streams.
          */
         if (fp) {
            audio_buffer_t output = al_get_audio_stream_fragment(s);
            if (output) {
               /* Fill the buffer from the data we have recorded into the file.
                * If an error occurs (or end of file) then silence out the
                * remainder of the buffer and stop the playback.
                */
               const size_t bytes_to_read =
                  playback_samples_per_fragment * sample_size;
               size_t bytes_read = 0, i;
               
               do {
                  bytes_read += al_fread(fp, (uint8_t *)output + bytes_read,
                     bytes_to_read - bytes_read);                  
               } while (bytes_read < bytes_to_read && !al_feof(fp) &&
                  !al_ferror(fp));
               
               /* silence out unused part of buffer (end of file) */
               for (i = bytes_read / sample_size;
                  i < bytes_to_read / sample_size; ++i) {
                     output[i] = sample_center;
               }
               
               al_set_audio_stream_fragment(s, output);
               
               if (al_ferror(fp) || al_feof(fp)) {
                  al_drain_audio_stream(s);
                  al_fclose(fp);
                  fp = NULL;
               }
            }
         }
      }      
      else if (e.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (e.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (e.keyboard.unichar == 27) {
            /* pressed ESC */
            break;
         }
         else if (e.keyboard.unichar == ' ') {
            if (!is_recording) {
               /* Start the recording */
               is_recording = true;
               
               if (al_get_audio_stream_playing(s)) {
                  al_drain_audio_stream(s);
               }
               
               /* Reuse the same temp file for all recordings */
               if (!tmp_path) {
                  fp = al_make_temp_file("alrecXXX.raw", &tmp_path);
               }
               else {
                  if (fp) al_fclose(fp);
                  fp = al_fopen(al_path_cstr(tmp_path, '/'), "w");
               }
               
               n = 0;
            }
            else {
               is_recording = false;
               if (fp) {
                  al_fclose(fp);
                  fp = NULL;
               }
            }
         }
         else if (e.keyboard.unichar == 'p') {
            /* Play the previously recorded wav file */
            if (!is_recording) {
               if (tmp_path) {
                  fp = al_fopen(al_path_cstr(tmp_path, '/'), "r");
                  if (fp) {
                     al_set_audio_stream_playing(s, true);
                  }
               }
            }
         }
      }
   }
   
   /* clean up */
   al_destroy_audio_recorder(r);
   al_destroy_audio_stream(s);
      
   if (fp)
      al_fclose(fp);
      
   if (tmp_path) {
      al_remove_filename(al_path_cstr(tmp_path, '/'));
      al_destroy_path(tmp_path);
   }
   
   return 0;
}
Example #14
0
int main(){

    ALLEGRO_DISPLAY *display = NULL;
    ALLEGRO_EVENT_QUEUE *event_queue = NULL;
    ALLEGRO_TIMER *timer =NULL;	
    bool redraw = true;
    /*Se inicia el display y allegro ↑*/
    /*Se crean las variables ↑*/

    if(!al_init()){
	fprintf(stderr,"Fallo al iniciar display\n");
	return -1;
    }

    timer = al_create_timer(1.0/FPS);//Se crea el timer

    if(!timer){
	fprintf(stderr, "Fallo al crear timer\n");
	return -1;
    }

    display = al_create_display(640, 480);
    
    if(!display){
	fprintf(stderr, "Fallo al crear el display\n");
	al_destroy_timer(timer);
	return -1;
    }

    event_queue = al_create_event_queue();

    if(!event_queue){
	fprintf(stderr, "Fallo al crear event_queue");
	al_destroy_display(display);
	al_destroy_timer(timer);
    }

    /*Y registrar eventos: */

    al_register_event_source(event_queue, al_get_display_event_source(display));

    al_register_event_source(event_queue, al_get_timer_event_source(timer));

    al_clear_to_color(al_map_rgb(0,0,0));

    al_flip_display();

    al_start_timer(timer);

    while(1){
	ALLEGRO_EVENT ev;
	al_wait_for_event(event_queue, &ev);

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

	else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE){
	    break;
	}
	if(redraw && al_is_event_queue_empty(event_queue)){
	    redraw = false;
	    al_clear_to_color(al_map_rgb(0,0,0));
            al_flip_display();

	}

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


    return EXIT_SUCCESS;
}
Example #15
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);
	}
}
int main(void)
{


    int vMapa = 0;
    int vMatriz_Mapa[20][25],i=0,j=0;
    FILE *fMapa = fopen("salas.txt", "r"); // Carrega o arquivo de texto da fase em questão;

    char vLe_Char;

    while((vLe_Char = getc(fMapa) ) != EOF )    // Grava Caracter enquanto não chegar ao final do arquivo;
    {
        if ( i < 25 ) // Enquanto estivar na linha;
        {
            vMatriz_Mapa[j][i] = atoi(&vLe_Char); // Carrega a matriz com os caracteres que representam as imagens;
            i++;
        }
        else // senao passa para a proxima linha;
        {
            j++;
            i=0;
        }

    }
    int merda=0,chatisse=0;
    fclose(fMapa);
    for (j=0;j<600;j+=32){
    for (i=0;i<800;i+=32){

    if(vMatriz_Mapa[j/32][i/32]==2){
        printf("%d %d\n",j, i);
    }

    }
    printf("\n");
    }
    bool sair = false;
    int tecla = 0,top = 0, left = 0, right = 0, down=0;
    int x=192,y=64;

    if (!al_init())
    {
        fprintf(stderr, "Falha ao inicializar a Allegro.\n");
        return false;
    }

    al_init_font_addon();

    if (!al_init_ttf_addon())
    {
        fprintf(stderr, "Falha ao inicializar add-on allegro_ttf.\n");
        return false;
    }

    if (!al_init_image_addon())
    {
        fprintf(stderr, "Falha ao inicializar add-on allegro_image.\n");
        return false;
    }

    if (!al_install_keyboard())
    {
        fprintf(stderr, "Falha ao inicializar o teclado.\n");
        return false;
    }

    janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
    if (!janela)
    {
        fprintf(stderr, "Falha ao criar janela.\n");
        return false;
    }

    al_set_window_title(janela, "Utilizando o Teclado");


    fila_eventos = al_create_event_queue();
    if (!fila_eventos)
    {
        fprintf(stderr, "Falha ao criar fila de eventos.\n");
        al_destroy_display(janela);
        return false;
    }

    fundo = al_load_bitmap("salas.jpg");
    if (!fundo)
    {
        fprintf(stderr, "Falha ao carregar imagem de fundo.\n");
        al_destroy_display(janela);
        al_destroy_event_queue(fila_eventos);
        return false;
    }

    timer = al_create_timer(7.5/60.0);
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_display_event_source(janela));
    al_draw_bitmap(fundo, 0, 0, 0);
    ALLEGRO_BITMAP *peterSET = al_load_bitmap("sabrina3.bmp");
    al_convert_mask_to_alpha(peterSET,al_map_rgb(255,0,255));
    ALLEGRO_BITMAP *peterCHAR[12];

peterCHAR[0] = al_create_bitmap(32,32);
peterCHAR[0] = al_create_sub_bitmap(peterSET,  0, 0, 32, 32);
peterCHAR[1] = al_create_bitmap(32,32);
peterCHAR[1] = al_create_sub_bitmap(peterSET,  32, 0, 32, 32);
peterCHAR[2] = al_create_bitmap(32,32);
peterCHAR[2] = al_create_sub_bitmap(peterSET,  64, 0, 32, 32);
peterCHAR[3] = al_create_bitmap(32,32);
peterCHAR[3] = al_create_sub_bitmap(peterSET,  0, 32, 32, 32);
peterCHAR[4] = al_create_bitmap(32,32);
peterCHAR[4] = al_create_sub_bitmap(peterSET,  32, 32, 32, 32);
peterCHAR[5] = al_create_bitmap(32,32);
peterCHAR[5] = al_create_sub_bitmap(peterSET,  64, 32, 32, 32);
peterCHAR[6] = al_create_bitmap(32,32);
peterCHAR[6] = al_create_sub_bitmap(peterSET,  0, 64, 32, 32);
peterCHAR[7] = al_create_bitmap(32,32);
peterCHAR[7] = al_create_sub_bitmap(peterSET,  32, 64, 32, 32);
peterCHAR[8] = al_create_bitmap(32,32);
peterCHAR[8] = al_create_sub_bitmap(peterSET,  64, 64, 32, 32);
peterCHAR[9] = al_create_bitmap(32,32);
peterCHAR[9] = al_create_sub_bitmap(peterSET,  0, 96, 32, 32);
peterCHAR[10] = al_create_bitmap(32,32);
peterCHAR[10] = al_create_sub_bitmap(peterSET,  32, 96, 32, 32);
peterCHAR[11] = al_create_bitmap(32,32);
peterCHAR[11] = al_create_sub_bitmap(peterSET,  64, 96, 32, 32);
al_draw_bitmap(fundo, 0, 0, 0);
al_draw_bitmap(peterCHAR[10],x,y,0);
al_flip_display();
    al_start_timer(timer);
    while (!sair)
    {
        while(!al_is_event_queue_empty(fila_eventos))
        {
            ALLEGRO_EVENT evento;
            al_wait_for_event(fila_eventos, &evento);

            if (evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_ESCAPE:
                    sair = true;
                    break;
                case ALLEGRO_KEY_UP:
                    keys[UP] = true;
                    break;
                case ALLEGRO_KEY_DOWN:
                   keys[DOWN] = true;
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[LEFT] = true;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[RIGHT] = true;
                    break;
                case ALLEGRO_KEY_SPACE:
                    keys[SELECT]=true;
                    break;
                }
            }else if (evento.type == ALLEGRO_EVENT_KEY_UP)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_UP:
                    keys[UP] = false;
                    break;
                case ALLEGRO_KEY_DOWN:
                   keys[DOWN] = false;
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[LEFT] = false;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[RIGHT] = false;
                    break;
                case ALLEGRO_KEY_SPACE:
                    keys[SELECT]=false;
                    break;
                }
            }
            else if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            {
                sair = true;
            }
            else if (evento.type == ALLEGRO_EVENT_TIMER){

  if(keys[SELECT]){
    if(vMatriz_Mapa[y/32][(x+32)/32]==2){
            return 0;
    }
  }
  if (keys[UP]){

if(vMatriz_Mapa[(y-32)/32][x/32]==0){
                al_draw_bitmap(fundo, 0, 0, 0);
                if(top == 0)
                {   y=y-32;
                    al_draw_bitmap(peterCHAR[10],x,y,0);
                    top = 1;
                }
                else if(top == 1)
                {
                    y=y-32;
                    al_draw_bitmap(peterCHAR[9],x,y,0);
                    top=2;
                }
                else if (top == 2)
                {
                    y=y-32;
                    al_draw_bitmap(peterCHAR[11],x,y,0);
                    top =0;
                }

printf("x = %d e y = %d\n",x,y);
                al_flip_display();
  }
  }


  if (keys[DOWN]){
if(vMatriz_Mapa[(y+32)/32][x/32]==0){
                al_draw_bitmap(fundo, 0, 0, 0);
                if(down == 0)
                {   y=y+32;
                    al_draw_bitmap(peterCHAR[1],x,y,0);
                    down = 1;
                }
                else if(down == 1)
                {
                    y=y+32;
                    al_draw_bitmap(peterCHAR[0],x,y,0);
                    down = 2;
                }
                else if (down == 2)
                {
                    y=y+32;
                    al_draw_bitmap(peterCHAR[2],x,y,0);
                    down = 0;
                }
  }
  }

printf("x = %d e y = %d\n",x,y);
                al_flip_display();

                }


            if (keys[LEFT]){

if(vMatriz_Mapa[y/32][(x-32)/32]==0){
                al_draw_bitmap(fundo, 0, 0, 0);
                if(left == 0)
                {   x=x-32;
                    al_draw_bitmap(peterCHAR[4],x,y,0);
                    left = 1;
                }
                else if(left == 1)
                {
                    x=x-32;
                    al_draw_bitmap(peterCHAR[3],x,y,0);
                    left=2;
                }
                else if (left == 2)
                {
                    x=x-32;
                    al_draw_bitmap(peterCHAR[5],x,y,0);
                    left =0;
                }
                al_flip_display();
printf("x = %d e y = %d\n",x,y);
                }
            }


        if (keys[RIGHT]){

if(vMatriz_Mapa[y/32][(x+32)/32]==0){
al_draw_bitmap(fundo, 0, 0, 0);
                if(right == 0)
                {   x=x+32;
                    al_draw_bitmap(peterCHAR[7],x,y,0);
                    right = 1;
                }
                else if(right == 1)
                {
                    x=x+32;
                    al_draw_bitmap(peterCHAR[6],x,y,0);
                    right=2;
                }
                else if (right == 2)
                {
                    x=x+32;
                    al_draw_bitmap(peterCHAR[8],x,y,0);
                    right =0;
                }

printf("x = %d e y = %d\n",x,y);
                al_flip_display();
                }

        }

        }
    }

    al_destroy_display(janela);
    al_destroy_event_queue(fila_eventos);

    return 0;
}
Example #17
0
void Bar::render()
{
    al_draw_filled_rectangle(pos->x, pos->y, pos->x + width, pos->y + height, al_map_rgb(255, 255, 255));
}
Example #18
0
//Draws the table dependant on what state the table is in
void Table::Render()
{
	al_draw_bitmap(m_bgImage, 0, 0, NULL);

	//Always draws dealer and all players - if they have no hand then no hand is drawn
	m_dealer.Render(m_cardIMGs);

	for(int i = 0; i < m_numPlayers; i++)
	{
		m_players.at(i).Render(m_cardIMGs, i);
	}

	switch( m_state)
	{
		case State::GET_PLAYERS:
			{
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 43, NULL, "Enter Number");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 68, NULL, "of Players");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 103, NULL, "1 = 1 players");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 128, NULL, "2 = 2 players");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 153, NULL, "3 = 3 players");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 178, NULL, "4 = 4 players");
			}
			break;
		case State::GET_BETS:
			{
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 43, NULL, "Player %i", m_activePlayer + 1);
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 68, NULL, "enter your bet");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 103, NULL, "1 = 100 chips");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 128, NULL, "2 = 200 chips");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 153, NULL, "3 = 300 chips");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 178, NULL, "4 = 400 chips");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 203, NULL, "5 = 500 chips");
			}
			break;
		case State::START_HAND:
			break;
			//Draws options available to the player e.g. Hit, Double etc
		case State::PLAYING_HAND:
			{
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 43, NULL, "Player %i", m_activePlayer + 1);
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 68, NULL, "choose an option");
				
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 103, NULL, "H = Hit");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 128, NULL, "S = Stand");
				if(m_players.at(m_activePlayer).CanDouble())
					al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 153, NULL, "D = Double");
				if(m_players.at(m_activePlayer).CanSplit())
					al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 178, NULL, "P = Split");	
				if(m_players.at(m_activePlayer).CanSurrender())
					al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 203, NULL, "G = Surrender");

				al_draw_filled_rectangle(495 + (m_players[m_activePlayer].GetActiveHand() * 165), 198 + (m_activePlayer * 189),
					495 + (m_players[m_activePlayer].GetActiveHand() * 165) + 136, 200 + (m_activePlayer * 192) + 8, al_map_rgb(255,0,0));
			}
			break;
		case State::DISPLAY_RESULTS:
			{
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 43, NULL, "Press Enter to");
				al_draw_textf(m_font, al_map_rgb(255, 255, 255), 46, 68, NULL, "start next hand");
			}
		case State::END_HAND:
			{

			}
			break;
		case State::EXIT:
			{
				al_draw_scaled_bitmap(m_exitButton, 0, 0, 633, 471, 300, 250, 400, 299, NULL);
			}
			break;
	}
}
Example #19
0
void AIMap::drawObstacle(AIGameClient_Obstacle obstacle) {
/*
 float v[obstacle.vertex.size()*2];
 for(int i = 0; i < obstacle.vertex.size(); i++) {
   v[2*i] = obstacle.vertex[i].first;
   v[2*i+1] = obstacle.vertex[i].second;
 }
 al_draw_filled_polygon(v, obstacle.vertex.size(), al_map_rgb(50, 50, 50));
*/
  ALLEGRO_VERTEX v[obstacle.vertex.size()];
  for(int i = 0; i < obstacle.vertex.size(); i++) {
    ALLEGRO_VERTEX tmp = {obstacle.vertex[i].first, obstacle.vertex[i].second, 0, 0, 0, al_map_rgb(0,0,0)};
    v[i] = tmp;
  }
  al_draw_prim(v, NULL, 0, 0, obstacle.vertex.size(), ALLEGRO_PRIM_LINE_LOOP);
};
Example #20
0
int
main (int argc, char **argv)
{
  gtk_init( &argc, &argv );

  g_type_init ();

  gfx_lib_setup ();

  g_testtex = cogl_texture_new_from_file ("testtex_sr.bmp", COGL_TEXTURE_NONE, COGL_PIXEL_FORMAT_ANY, NULL);
  g_xassert (g_testtex != COGL_INVALID_HANDLE);

  //cogl_ortho (-1.0f, 1.0f, -1.0f, 1.0f, -5.0f, 100.0f);
  cogl_perspective (45.0f, 1.0f, 0.1f, 100.0f);
  cogl_set_source_texture (g_testtex);

  /**
   * WHY IS THIS NOT ENABLED BY DEFAULT
   */
  cogl_set_depth_test_enabled (TRUE);

  /**
   * Enabling this shows polygons actually missing not just culled out?
   * cogl_set_backface_culling_enabled (TRUE);
   */

  /**
   * Initialize g_state
   */
  struct NxState state = {0};
  g_state = g_new0 (struct NxState, 1);
  *g_state = state;

  g_state->dr_n = 1.0f;
  g_state->dr_f = 100.0f;
  g_state->vp_w = 100.0f;
  g_state->vp_h = 100.0f;
  g_state->vp_x = 0.0f;
  g_state->vp_y = 0.0f;

  NxMat z_mat;
  nx_mat_init_identity (&z_mat);
  nx_mat_translate (&z_mat, 0.0f, 0.0f, -30.0f);

  g_state->p_mat = z_mat;
  g_state->w_mat = z_mat;

  MaiModel *model;
  struct aiScene *scene;
  model = mai_model_new_from_file ("../misc/mtest1.dae", &scene);
  aiReleaseImport (scene);

  MaiAnimInstance *mai;
  g_xassert (model->anims->len > 0);
  mai = mai_anim_instance_new_from_anim (
                                         g_mai_anim_ptr_array_index (model->anims, 0),
                                         model->name_node_map,
                                         model->nodes);

  struct SrNodeGraph *sr_model;
  sr_node_graph_from_model (model, &sr_model);

  MaiInfoWin *iw;
  iw = MAI_INFO_WIN (mai_info_win_new ());

  mai_info_win_clear_model (iw);
  mai_info_win_fill_model_from_node_graph (iw, sr_model);
  mai_info_win_fill_model_from_model (iw, model);

  mai_info_win_show (iw);

  int frame;
  for (frame=0; frame<600; ++frame)
    {
      ALLEGRO_KEYBOARD_STATE aks;

      gfx_display_clear ();

      context_switch_allegro ();
      al_get_keyboard_state (&aks);
      sr_update_global_ypr (&aks);
      al_clear_to_color (al_map_rgb (0, 0, 0));

      mai_info_win_iteration (iw, FALSE);

      /**
       * Allegro drawing origin top left.
       * Compensate (Want positive x/y go northwest).
       */
      NxMat comp;
      comp = g_state->w_mat;
      nx_mat_scale (&comp, -1.0f, 1.0f, -1.0f);

      struct SrNodeGraph *sr_model_aux;
      GHashTable *ht;

      sr_node_graph_copy (&sr_model_aux, sr_model);

      sr_skeletal_anim_node_graph (mai, sr_model_aux);
      sr_skeletal_anim_verts (model, mai, sr_model_aux, &ht);

      GList *model_keys;
      model_keys = g_hash_table_get_keys (ht);

      for (GList *k = model_keys; k != NULL; k = k->next)
        {
          char *name;
          GArray *vts_a;
          MaiNode *mn_a;

          name = k->data;

          vts_a = g_hash_table_lookup (ht, name);
          g_xassert (vts_a);
          g_array_ref (vts_a);

          mn_a = g_object_ref (MAI_NODE (
              g_hash_table_lookup (model->name_node_map, name)));
          g_xassert (mn_a);

          sr_skeletal_draw_node_trans (&comp, sr_model_aux,
                                       mn_a, vts_a);

          g_object_unref (mn_a);
          g_array_unref (vts_a);
        }

      g_list_free (model_keys);

      g_hash_table_unref (ht);

      sr_node_graph_free (sr_model_aux);

      mai->current_frame += mai->current_frame == 29 ? -29 : 1;

      gfx_display_transfer ();

      al_rest (0.05f);
    }

  return EXIT_SUCCESS;
}
Example #21
0
	void Canvas::fill(Rectangle* rect, byte r, byte g, byte b)
	{
		if(al_get_target_bitmap() != this->buffer)
			al_set_target_bitmap(this->buffer);

		al_draw_filled_rectangle(rect->x, rect->y, rect->x + rect->width, rect->y + rect->height, al_map_rgb(r,g,b) );

		TF::engine->resetRenderingBuffer();
	}
Example #22
0
int main() 
{
	int state = MENU;

	float TimeGame = 0;
	int frame = 0;
	int GameFPS = 0;
	

	//=========== INFO ACHIEVEMENTS

	int Points = 0;
	int Golds = 0;
	int TimeInGame = 0;

	//=========== Allegro variable
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_BITMAP *background = NULL;
	ALLEGRO_BITMAP *background_game = NULL;
	ALLEGRO_BITMAP *wall1 = NULL;
	ALLEGRO_BITMAP *wall = NULL;
	ALLEGRO_TIMER *timer = NULL;

	//=========== Program init
	if (!al_init())
		return -1;
	
	//=========== FullScreen
	al_set_new_display_flags(ALLEGRO_FULLSCREEN);

	//=========== Create our display object
	display = al_create_display(Width, Height);

	if (!display)
		return -1;

	//=========== Addon init
	al_init_font_addon();
	al_init_ttf_addon();
	al_install_keyboard();
	al_init_primitives_addon();
	al_create_display;
	al_init_image_addon();

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

	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 *subtitles = al_load_font("BuxtonSketch.ttf", 40, NULL);
  	ALLEGRO_FONT *titles = al_load_font("BuxtonSketch.ttf", 100, NULL);
	ALLEGRO_FONT *setting_titles = al_load_font("BuxtonSketch.ttf", 55, NULL);
	ALLEGRO_FONT *options_titles = al_load_font("BuxtonSketch.ttf", 10, NULL);
	ALLEGRO_FONT *fps = al_load_font("arial.ttf", 18, NULL);

	al_set_window_position(display, 200, 200);

	background = al_load_bitmap("tlo1.bmp");
	background_game = al_load_bitmap("tlo_gry.png");
	wall1 = al_load_bitmap("wall1.bmp");

	int x = 0;
	int y = 0;

	//=========== MENU
	al_draw_bitmap(background, x, y, 0);
	al_draw_textf(titles, al_map_rgb(0, 0, 0), Width/2, Height/4.5, ALLEGRO_ALIGN_CENTRE, "SNAKE !");
	al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 50, ALLEGRO_ALIGN_CENTRE, "Nowa gra");
	al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 70, ALLEGRO_ALIGN_CENTRE, "[ENTER]");
	al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 120, ALLEGRO_ALIGN_CENTRE, "[TAB]");
	al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 170, ALLEGRO_ALIGN_CENTRE, "[ESC]");
	al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 100, ALLEGRO_ALIGN_CENTRE, "Ustawienia");
	al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 150, ALLEGRO_ALIGN_CENTRE, "Zamknij gre");

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

	TimeGame = al_current_time();
	al_start_timer(timer);

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

		//=========== INPUT
		if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				keys[ESCAPE] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = true;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				keys[ESCAPE] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = false;
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			Return = true;

			frame++;
			if (al_current_time() - GameFPS >= 1)
			{
				TimeGame = al_current_time();
				GameFPS = frame;
				frame = 0;
			}

			if (state == MENU)
			{
				if (keys[ESCAPE])
				{
					done = true;
				}
				al_draw_bitmap(background, x, y, 0);
				al_draw_textf(titles, al_map_rgb(0, 0, 0), Width / 2, Height / 4.5, ALLEGRO_ALIGN_CENTRE, "SNAKE !");
				al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 50, ALLEGRO_ALIGN_CENTRE, "Nowa gra");
				al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 100, ALLEGRO_ALIGN_CENTRE, "Ustawienia");
				al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 400, Height / 2 + 150, ALLEGRO_ALIGN_CENTRE, "Zamknij gre");
				al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 70, ALLEGRO_ALIGN_CENTRE, "[ENTER]");
				al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 120, ALLEGRO_ALIGN_CENTRE, "[TAB]");
				al_draw_textf(options_titles, al_map_rgb(0, 0, 0), 495, Height / 2 + 170, ALLEGRO_ALIGN_CENTRE, "[ESC]");
			}

			else if (state == PLAY)
			{
				al_clear_to_color(al_map_rgb(0, 0, 0));
				al_draw_bitmap(background_game, x, y, 0);
				//WallFunction(wall1, 0, 0, );
				al_flip_display();
			}

			else if (state == GAMEOVER)
			{
				al_clear_to_color(al_map_rgb(0, 0, 0));

			}

			else if (state = SETTING)
			{
				al_clear_to_color(al_map_rgb(0, 0, 0));
				al_draw_bitmap(background, x, y, 0);
				al_draw_textf(setting_titles, al_map_rgb(0, 0, 0), Width / 2, Height / 4.5, ALLEGRO_ALIGN_CENTRE, "Ustawienia");
				al_draw_textf(subtitles, al_map_rgb(0, 0, 0), 250, Height / 2 + 50, ALLEGRO_ALIGN_CENTRE, "Dzwiek: ");

				al_flip_display();
			}
		}

		if (Return && al_is_event_queue_empty(event_queue))
		{
			Return = false;
			al_draw_textf(fps, al_map_rgb(255, 0, 255), 5, 5, 0, "FPS: %d", GameFPS);

			{
				if (state == MENU)
				{
					if (keys[ENTER])
					{
						state = PLAY;
					}
				}
				else if (state == MENU)
				{
					if (keys[TAB])
					{
						state = SETTING;
					}
				}
				else if (state == PLAY)
				{
					if (keys[ESCAPE])
					{
						state = MENU;
					}
				}
				else if (state == SETTING)
				{
					if (keys[ESCAPE])
					{
						state = MENU;
					}
				}
				else if (state == GAMEOVER)
				{
					if (keys[ESCAPE])
					{
						state = MENU;
					}
				}
				else if (state = MENU)
				{
					if (keys[ESCAPE])
					{
						done = true;
					}
				}
			}

			al_flip_display();
			al_clear_to_color(al_map_rgb(0, 0, 0));
		}
	}
	al_destroy_font(fps);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);

	return 0;
}
Example #23
0
int main(int argc, char *argv[])
{
    bool windowed = false;
    float rescale = 1.0f;
    std::string arg;
    if(argc > 1)
    {
        arg = argv[1];
        if(arg == "--help")
        {
            std::cout << "-s {scale} for running in windowed mode and scaled (standart size is 1440*810)" << std::endl;
            return 0;
        }
        else if(arg == "-s")
        {
            if( argc > 2)
            {
                arg = argv[2];
                rescale = atof(argv[2]);
            }
            windowed = true;
        }
    }


    /**initialize allegro*/
    if(!al_init()){error_message("al_init()");return 33;}
    if(!al_init_primitives_addon()){error_message("al_init_primitives_addon()");return 33;}
    //if(!al_install_keyboard()){error_message("al_install_keyboard()");return 33;} //no use for keyboard in this game
    if(!al_install_mouse()){error_message("al_install_mouse()");return 33;}
    if(!al_init_image_addon()){error_message("al_init_image_addon()");return 33;}
    al_init_font_addon(); // returns void
    if(!al_init_ttf_addon()){error_message("al_init_ttf_addon()");return 33;}
    //audio
    if(al_install_audio() == true)
    {
        if(al_init_acodec_addon() == true){}
        else
        {
            error_message("al_init_acodec_addon() - cant initialize audio codec");
            global::audio = false;
            global::sound_card = false;
        }
    }
    else
    {
        error_message("al_install_audio() - cant found sound device");
        global::audio = false;
        global::sound_card = false;
    }

    /**Some allegro variables*/
    ALLEGRO_DISPLAY *display = nullptr;
    ALLEGRO_EVENT_QUEUE *event_queue = nullptr;
    ALLEGRO_TIMER *timer = nullptr;
    ALLEGRO_BITMAP *logo = nullptr;

    /**Display preparation*/
    bool supported_ratio = true;
    ALLEGRO_MONITOR_INFO mon_info;
    al_get_monitor_info(0, &mon_info);
    global::sHeight = mon_info.y2 - mon_info.y1; //gets monitor size in pixels
    global::sWidth = mon_info.x2 - mon_info.x1;
    global::aspectratio = round( ((float)global::sWidth / (float)global::sHeight) * 100.0f) / 100.0f; //gets aspectratio
    if(global::aspectratio == 1.78f){global::xratio = 16; global::yratio = 9;}      // 16:9 screen ration
    else if(global::aspectratio == 1.6f){global::xratio = 16; global::yratio = 10;} // 16:10
    else if(global::aspectratio == 1.33f){global::xratio = 4; global::yratio = 3;}  // 4:3
    else{supported_ratio = false;}
    global::dHeight = global::dWidth  / global::xratio * global::yratio;
    global::xscale = (float)global::sWidth / (float)global::dWidth;
    global::yscale = (float)global::sHeight / (float)global::dHeight;

    /**display creation*/
    al_set_new_bitmap_flags(ALLEGRO_MAG_LINEAR | ALLEGRO_MIN_LINEAR); // Thanks to this, magnified fonts dont look retarted, and game is fast (hopefully) :D
    if(windowed == true || supported_ratio == false)
    {
        supported_ratio = true;
        al_set_new_display_flags(ALLEGRO_WINDOWED | ALLEGRO_OPENGL);
        global::xscale = rescale;
        global::yscale = rescale;
        global::dWidth = 1440;
        global::dHeight = 810;
        display = al_create_display(global::dWidth*rescale, global::dHeight*rescale);
    }
    else
    {
        al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW | ALLEGRO_OPENGL);
        display = al_create_display(global::dWidth, global::dHeight);
    }
    if(display == nullptr){error_message("al_create_display()"); return 1;}
    al_set_window_title(display, "Este neviem meno, ale asi neco so zemiakom");

    /**logo*/
    logo = al_load_bitmap("resources/graphics/logo.png");
    if(logo == nullptr){error_message("resources/graphics/logo.png not found");}
    else{ al_set_display_icon(display, logo);}


    /**Transformation*/
    al_identity_transform(&global::trans);
    if(supported_ratio == true)
    {
        al_scale_transform(&global::trans, global::xscale, global::yscale);
    }
    else
    {
        error_message("Unsupported monitor type - upgrade you monitor pls");
        float scale_backup_plan = (global::xscale > global::yscale ? global::yscale : global::xscale);
        global::xscale = scale_backup_plan;
        global::yscale = scale_backup_plan;
        al_scale_transform(&global::trans, global::xscale, global::yscale);
    }
    al_use_transform(&global::trans);

    /**timer*/
    timer = al_create_timer(1.0f/global::FPS);
    if(timer == nullptr){error_message("al_create_timer()"); return 44;}
    bool redraw = true;

    /**even que*/
    event_queue = al_create_event_queue();
    if(event_queue == nullptr){error_message("al_create_event_queue()"); return 44;}

    /**registering event sources*/
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    al_register_event_source(event_queue, al_get_mouse_event_source());

    al_start_timer(timer);

    rguil::mouse_state = &global::mouse_state;

    global::audio_player = new AudioHandler(10);

    #ifdef _SOUND_TEST
    ALLEGRO_SAMPLE *s = al_load_sample("resources/music/Fuck_This_Shit_Im_Out.wav");
    ALLEGRO_SAMPLE_INSTANCE *si = al_create_sample_instance(s);
    global::audio_player->global_sounds.push_back(si);
    global::audio_player->Play_sample_instance(&si, ALLEGRO_PLAYMODE_LOOP);
    #endif // _SOUND_TEST

    #ifdef _FPS
    ALLEGRO_FONT *fps_font = nullptr;
    fps_font = al_load_font("resources/fonts/Asimov.otf", 12,0);
    int counter = 0;
    time_t tsttme2 = time(nullptr), tsttme = time(nullptr);
    int fps = 0;
    #endif // FPS

    global::save = new GameSave();
    ScreenMain *SCMain = new ScreenMain();
    global::audio_b = new Button("resources/fonts/Calibri.ttf", 1240, global::dHeight -65, 1240 + 40, global::dHeight - 25,
                                 "", al_map_rgba(0,0,0,0),
                                 ( global::audio == true ? MusicON : MusicOFF));

    /**Main loop*/ //forced 30 FPS, drawing and computing in same thread
    while(global::loop == true)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(event_queue, &ev);

        al_get_mouse_state(&global::mouse_state);

        if(ev.type == ALLEGRO_EVENT_TIMER)
        {
            redraw = true;
        }
        else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            break;
        }

        /**Take event input here*/
        if(global::audio_b->Input(ev, global::xscale, global::yscale) == 2)
        {
            global::audio_b->unclick();
            global::audio = (global::audio == true ? false : true);

            if(global::audio == true)
            {
                al_destroy_bitmap(global::audio_b->bmp);
                global::audio_b->bmp = al_load_bitmap(MusicON);
                global::audio_player->Mute_sample_instances(false);
            }
            else
            {
                al_destroy_bitmap(global::audio_b->bmp);
                global::audio_b->bmp = al_load_bitmap(MusicOFF);
                global::audio_player->Mute_sample_instances(true);
            }
        }

        SCMain->Input(ev, global::xscale, global::yscale);
        /**---------------------*/

        #ifdef _FPS
        tsttme2 = time(&tsttme2);
        if(difftime(tsttme2,tsttme) >= 1.0f)
        {
            tsttme = time(&tsttme);
            fps = counter;
            counter = 0;
        }
        #endif // FPS


        if(redraw == true && al_is_event_queue_empty(event_queue))
        {
            redraw = false;
            al_clear_to_color(al_map_rgb(0,0,0));


            /**Draw and compute here*/
            SCMain->Print();
            global::audio_b->Print();
            /**---------------------*/

            #ifdef _FPS
            counter++;
            al_draw_text(fps_font, al_map_rgb(255,0,0), 0.0f,0.0f, 0, std::to_string(fps).c_str());
            #endif // FPS
            al_flip_display();
        }
    }
    #ifdef _SOUND_TEST
    global::audio_player->Stop_sample_instances();
    global::audio_player->global_sounds.erase(global::audio_player->global_sounds.begin());
    al_destroy_sample_instance(si);
    al_destroy_sample(s);
    #endif // _SOUND_TEST

    delete global::audio_b;
    delete SCMain;
    delete global::save;
    delete global::audio_player;

    al_destroy_timer(timer);
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);
    if(logo != nullptr)
        al_destroy_bitmap(logo);
    #ifdef _FPS
    al_destroy_font(fps_font);
    #endif // FPS

    return 0;
}
int main(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_example("Could not init Allegro.\n");
      return 1;
   }

   al_install_keyboard();
   
   display = al_create_display(WIDTH, HEIGHT);
   if (!display) {
      abort_example("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)
{
   int num_touches = 0;
   TOUCH touches[MAX_TOUCHES];
   ALLEGRO_DISPLAY *display;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;

   (void)argc;
   (void)argv;

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

   display = al_create_display(800, 600);
   if (!display) {
       abort_example("Error creating display\n");
   }
   queue = al_create_event_queue();

   al_register_event_source(queue, al_get_touch_input_event_source());
   al_register_event_source(queue, al_get_display_event_source(display));

   while (true) {
      if (al_is_event_queue_empty(queue)) {
         al_clear_to_color(al_map_rgb(255, 255, 255));
         draw_touches(num_touches, touches);
         al_flip_display();
      }

      al_wait_for_event(queue, &event);

      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_BEGIN) {
         int i = num_touches;
         if (num_touches < MAX_TOUCHES) {
            touches[i].id = event.touch.id;
            touches[i].x = event.touch.x;
            touches[i].y = event.touch.y;
            num_touches++;
         }
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_END) {
         int i = find_index(event.touch.id, num_touches, touches);
         if (i >= 0 && i < num_touches) {
            touches[i] = touches[num_touches - 1];
            num_touches--;
         }
      }
      else if (event.type == ALLEGRO_EVENT_TOUCH_MOVE) {
         int i = find_index(event.touch.id, num_touches, touches);
         if (i >= 0) {
            touches[i].x = event.touch.x;
            touches[i].y = event.touch.y;
         }
      }
   }

   return 0;
}
Example #26
0
void Tela::inicia(int larg, int alt, const char *nome) {
    /* inicializa dados sobre o mouse */
    _rato.x = 0;
    _rato.y = 0;
    _botao = false;
    _tecla = 0;
    _modif = 0;

    /* inicializa o allegro */
    if (!al_init()) {
        std::cerr << "falha na inicializacao do allegro" << std::endl;
        std::abort();
    }

    /* conecta com tela X */
    display = al_create_display(larg, alt);
    if (display == NULL) {
        std::cerr << "falha ao criar display do allegro" << std::endl;
        std::abort();
    }

    janela.pos.x = 0;
    janela.pos.y = 0;
    tam.larg = larg;
    tam.alt = alt;
    janela.tam.larg = XX2U(tam.larg);
    janela.tam.alt = YX2U(tam.alt);
    tam = tam;

    /* Titulo da tela */
    al_set_window_title(display, nome);

    /* cria contextos grafico */
    ac_fundo = al_map_rgb(255, 255, 255);
    ac_cor = al_map_rgb(0, 0, 0);

    /* instala o driver de mouse e teclado */
    al_install_mouse();
    al_install_keyboard();
    al_init_primitives_addon();

    /* configura fonte */
    al_init_font_addon();
    al_init_image_addon();
    // fonte = al_load_bitmap_font("data/a4_font.tga");
    fonte = al_load_font("data/fixed_font.tga", 0, 0);
    if (!fonte) {
        std::cerr << "falha ao carregar fonte do allegro" << std::endl;
        std::abort();
    }

    /* inicia o timer */
    /* timer = al_create_timer(1.000 / FPS); */

    /* fila para eventos */
    queue = al_create_event_queue();
    if (queue == NULL) {
        std::cerr << "falha ao buscar eventos do allegro" << std::endl;
        std::abort();
    }

    /* registra para receber eventos de tela/teclado/mouse */
    al_register_event_source(queue, al_get_keyboard_event_source());
    al_register_event_source(queue, al_get_display_event_source(display));
    al_register_event_source(queue, al_get_mouse_event_source());
    // al_register_event_source(queue,
    // al_get_timer_event_source(timer));
}
Example #27
0
static bool test(ALLEGRO_BITMAP *bitmap, ALLEGRO_FONT *font, char *message)
{
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_EVENT event;
   double start_time;
   long frames = 0;
   double fps = 0;
   char second_line[100];
   bool quit = false;

   queue = al_create_event_queue();
   al_register_event_source(queue, al_get_keyboard_event_source());

   start_time = al_get_time();

   for (;;) {
      if (al_get_next_event(queue, &event)) {
         if (event.type == ALLEGRO_EVENT_KEY_DOWN) {
            if (event.keyboard.keycode == ALLEGRO_KEY_SPACE) {
               break;
            }
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
               quit = true;
               break;
            }
         }
      }

      al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);

      /* Clear the backbuffer with red so we can tell if the bitmap does not
       * cover the entire backbuffer.
       */
      al_clear_to_color(al_map_rgb(255, 0, 0));

      al_draw_scaled_bitmap(bitmap, 0, 0,
         al_get_bitmap_width(bitmap),
         al_get_bitmap_height(bitmap),
         0, 0,
         al_get_bitmap_width(al_get_target_bitmap()),
         al_get_bitmap_height(al_get_target_bitmap()),
         0);
      
      al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);

      /* Note this makes the memory buffer case much slower due to repeated
       * locking of the backbuffer.  Officially you can't use al_lock_bitmap
       * to solve the problem either.
       */
      print(font, message, 0, 0);
      sprintf(second_line, "%.1f FPS", fps);
      print(font, second_line, 0, al_get_font_line_height(font)+5);

      al_flip_display();

      frames++;
      fps = (double)frames / (al_get_time() - start_time);
   }

   al_destroy_event_queue(queue);

   return quit;
}
Example #28
0
int main(int argc, char **argv)
{
	InitAllegro();

	ALLEGRO_KEYBOARD_STATE klawiatura;
	ALLEGRO_MOUSE_STATE mysz;
	ALLEGRO_EVENT_QUEUE* event_queue = al_create_event_queue();
	ALLEGRO_EVENT_QUEUE* key_queue = al_create_event_queue();
	ALLEGRO_DISPLAY* okno = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);
	ALLEGRO_FONT* defaultFont = al_create_builtin_font();
	ALLEGRO_TIMER* timer = al_create_timer(1.0 / 60.0);

	al_register_event_source(key_queue, al_get_display_event_source(okno));
	al_register_event_source(event_queue, al_get_display_event_source(okno));
	al_register_event_source(key_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_set_window_title(okno, "Fraktale");
	al_set_target_bitmap(al_get_backbuffer(okno));
	
	Menu* menu = new Menu(WINDOW_WIDTH, WINDOW_HEIGHT);
	Mandelbrot* mandelbrot = new Mandelbrot(WINDOW_WIDTH, WINDOW_HEIGHT, defaultFont);
	Julia* julia = new Julia(WINDOW_WIDTH, WINDOW_HEIGHT, defaultFont);
	Window* window = new Window(menu, mandelbrot, julia);
	menu->SetWindow(window);
	mandelbrot->SetWindow(window);
	julia->SetWindow(window);

	const ALLEGRO_COLOR backgroundColor = al_map_rgb(255, 255, 255);
	const ALLEGRO_COLOR frameColor = al_map_rgb(255, 255, 255);
	const int frameThickness = 2;

	ALLEGRO_USTR* str = al_ustr_new("");
	int pos = (int)al_ustr_size(str);

	ALLEGRO_EVENT ev;

	double blokadaKlikniecia = al_get_time();
	
	int poczX = -1, poczY = -1, poprzedniStan = window->stanOkna;
	bool petla = true, klikniecieMyszy = false, klawiszWcisniety = false, wpisywanieIteracji = false;

	double screenRatio = static_cast<double>(WINDOW_HEIGHT) / static_cast<double>(WINDOW_WIDTH);

	while (petla)
	{
		if (poprzedniStan != window->stanOkna)
		{
			blokadaKlikniecia = al_get_time();
		}

		poprzedniStan = window->stanOkna;

		al_get_next_event(event_queue, &ev);
		al_get_mouse_state(&mysz);

		int mx = mysz.x;
		int my = mysz.y;

		bool koniecKlikniecia = false;

		if (mysz.buttons & 1 && klikniecieMyszy == false && al_get_time() > blokadaKlikniecia + 0.3)
		{
			klikniecieMyszy = true;

			if (window->CzyFraktal())
			{
				poczX = mx;
				poczY = my;
			}
		}
		else if (!(mysz.buttons & 1) && klikniecieMyszy == true && al_get_time() > blokadaKlikniecia + 0.3)
		{
			klikniecieMyszy = false;

			int pp = window->stanOkna;

			int respond = window->Click(mx, my);
			if (respond == Responds_t::RESPOND_CLOSE_WINDOW)
				petla = false;

			if (window->CzyFraktal() && (pp == WINDOWSTATE_MANDELBROT || pp == WINDOWSTATE_JULIA))
			{
				koniecKlikniecia = true;
			}

			if (pp == WINDOWSTATE_MENU && window->CzyFraktal())
			{
				window->ZaladujFraktal();
			}
		}

		if (koniecKlikniecia)
		{
			if (window->CzyFraktal())
			{
				Fraktal* fraktal = window->AktualnyFraktal();
				fraktal->Powieksz(poczX, mx, poczY, SkalujY(poczY, screenRatio, poczX, mx));
			}
			poczX = -1, poczY = -1;
		}

		al_get_next_event(key_queue, &ev);

		if (ev.type == ALLEGRO_EVENT_KEY_DOWN && klawiszWcisniety == false && window->CzyFraktal())
		{
			int kod = ev.keyboard.keycode;
			klawiszWcisniety = true;

			if (kod == 9)
			{
				wpisywanieIteracji = true;
			}
			else if (kod == 10)
			{
				Fraktal* fraktal = window->AktualnyFraktal();
				fraktal->Resetuj();
			}
			else if (kod >= 27 && kod <= 36 && wpisywanieIteracji)
			{
				pos += al_ustr_append_chr(str, kod + 21);
			}
			else if (kod == ALLEGRO_KEY_ENTER)
			{
				if (wpisywanieIteracji == true)
					wpisywanieIteracji = false;
				unsigned char* tmp = str->data;
				int t = atoi((const char*)tmp);
				window->SetIteracje(t);
			}
			else if (kod == ALLEGRO_KEY_BACKSPACE)
			{
				if (al_ustr_prev(str, &pos))
					al_ustr_truncate(str, pos);
			}
			else if (kod == ALLEGRO_KEY_ESCAPE)
			{
				window->stanOkna = WINDOWSTATE_MENU;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			klawiszWcisniety = false;
		}

		al_clear_to_color(backgroundColor);

		if (wpisywanieIteracji)
			window->Draw(str);
		else
			window->Draw(NULL);

		if(poczX != -1)
			al_draw_rectangle(poczX, poczY, mx, SkalujY(poczY, screenRatio, poczX, mx), frameColor, frameThickness);
		al_flip_display();
	}
	al_destroy_display(okno);
	return 0;
}
Example #29
0
void fireball::draw(){
   al_draw_filled_circle(circle->x,circle->y, circle->r, al_map_rgb(54,184,153));
};
Example #30
0
void Bullet::draw(){
    if(!this->playerShot){
        al_draw_filled_rectangle(this->posX, this->posY, this->posX + this->width, this->posY + this->height, al_map_rgb(255, 50, 50));
    }else{
        al_draw_filled_rectangle(this->posX, this->posY, this->posX + this->width, this->posY + this->height, al_map_rgb(50, 50, 255));
    }
}