예제 #1
0
파일: main.cpp 프로젝트: henriquesa/pong
int game() {
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_TIMER *timer = NULL;

	bool exit = false;

	if (!al_init()) {
		fprintf(stderr, "Allegro could not be initialized.");
		return -1;
	}

	if (!al_install_keyboard()) {
		fprintf(stderr, "Keyboard could not be initialized.");
		return -1;
	}

	if (!al_install_audio()){
		fprintf(stderr, "Audio could not be initialized.");
		return -1;
	}

	if (!al_reserve_samples(1)){
		fprintf(stderr, "Samples could not be reserved.");
		return -1;
	}
	if (!al_init_acodec_addon()) {
		fprintf(stderr, "Audio codecs could not be initialized.");
		return -1;
	}

	al_init_primitives_addon();
	al_init_image_addon();

	al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
	al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST);

	display = al_create_display(SCREEN_W, SCREEN_H);
	if (!display) {
		fprintf(stderr, "Display could not be created.");
		return -1;
	}

	timer = al_create_timer(1.0 / FPS);
	if (!timer) {
		fprintf(stderr, "Timer could not be created.");
		return -1;
	}

	al_set_target_bitmap(al_get_backbuffer(display));

	eventQueue = al_create_event_queue();
	if (!eventQueue) {
		fprintf(stderr, "Event queue could not be created.");
		return -1;
	}

	yaySound = al_load_sample("yay.wav");
	naySound = al_load_sample("nay.wav");
	hitSound = al_load_sample("hit.wav");


	al_register_event_source(eventQueue, al_get_display_event_source(display));
	al_register_event_source(eventQueue, al_get_timer_event_source(timer));
	al_register_event_source(eventQueue, al_get_keyboard_event_source());

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

	al_flip_display();

	al_start_timer(timer);

	// Open menu.
	titleScreen();

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

	return 0;
}
예제 #2
0
파일: main.cpp 프로젝트: khellwan/FINAL
int main(int argc, char *argv[])
{

// -------- VARIÁVEIS DO JOGO --------
ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;
ALLEGRO_TIMER *timer = NULL;
ALLEGRO_FONT *font20 = NULL;
ALLEGRO_SAMPLE *ataque = NULL;
ALLEGRO_SAMPLE *morte_inimigo = NULL;
ALLEGRO_SAMPLE *morte_personagem = NULL;
ALLEGRO_SAMPLE *hit = NULL;
ALLEGRO_SAMPLE *item = NULL;
ALLEGRO_AUDIO_STREAM *musica = NULL;
ALLEGRO_AUDIO_STREAM *track_menu = NULL;
ALLEGRO_BITMAP *start = NULL;

bool fim = false;
bool menu = true;
int flag = 0;
bool desenha = true;
bool game_over = false;
bool teclas[] = {false, false, false, false, false, false, false};
int i;
int dificuldade;


// ___________________________________


// -------- INICIALIZAÇÃO DE OBJETOS --------
dificuldade = 0;
Personagem personagem_principal;
Projetil* balas = new Projetil [NUM_BALAS];
Projetil* balas_2 = new Projetil [NUM_BALAS];
Inimigo* inimigos = new Inimigo[NUM_INIMIGOS];
Inimigo* inimigos2 = new Inimigo [NUM_INIMIGOS];
Coracao* coracoes = new Coracao[NUM_ITENS];
Speed* speed = new Speed[NUM_ITENS];
ItemPontos* pontos = new ItemPontos[NUM_ITENS];
Estrelas estrelas_pf[NUM_PLANOS][NUM_ESTRELAS];
Selecionar select;


// __________________________________________

// -------- INICIALIZAÇÃO DA ALLEGRO E DO DISPLAY --------
    ALLEGRO_DISPLAY *display = NULL;

    if (!al_init())
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO INICIALIZAR A ALLEGRO!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    display = al_create_display(LARGURA_T, ALTURA_T);

    if (!display)
    {
        al_show_native_message_box(NULL, "AVISO!", "ERRO!", "ERRO AO CRIAR O DISPLAY!", NULL, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    al_set_window_title(display, "Cosmos Guardian");


// ____________________________________________________

// -------- INICIALIZAÇÃO DE ADDONS E INSTALAÇÕES --------
    al_init_primitives_addon();
    al_install_keyboard();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    al_install_audio();
    al_init_acodec_addon();

    al_reserve_samples(100);

// _______________________________________________________

// -------- CRIAÇÃO DE FILAS E DEMAIS DISPOSITIVOS --------
    fila_eventos = al_create_event_queue();
    timer = al_create_timer(1.0 / FPS);
    font20 = al_load_font("BADABB__.ttf", 20, 0);


// ________________________________________________________

// -------- REGISTRO DE SOURCES --------
    al_register_event_source(fila_eventos, al_get_display_event_source(display));
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

// _____________________________________


// -------- FUNÇÕES INICIAIS --------
    srand(time(NULL));
    personagem_principal.InitPersonagem();

    select.InitSelecionar();

    //Inicialização de projeteis
    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].InitBalas();
        balas_2[i].InitBalas();
    }

    //Inicialização de inimigos
    for (i = 0; i < NUM_INIMIGOS; i++)
    {
        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
    }

    //Inicialização de itens
    for (i = 0; i < NUM_ITENS; i++)
    {
        coracoes[i].InitItem();
        speed[i].InitItem();
        pontos[i].InitItem();
    }

    //Inicialização do Plano de Fundo
    InitPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);

    //Setando Sons e Imagens
    select.bmp = al_load_bitmap("select.png");
    ataque = al_load_sample("laser.wav");
    morte_inimigo = al_load_sample("dead.wav");
    morte_personagem = al_load_sample("death.wav");
    hit = al_load_sample("hit.wav");
    item = al_load_sample("item.wav");
    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);
    track_menu = al_load_audio_stream("menu.ogg", 4, 1024);
    personagem_principal.bmp = al_load_bitmap("ship.png");


    for (i = 0; i < NUM_BALAS; i++)
    {
        balas[i].bmp = al_load_bitmap("bala.png");
        balas_2[i].bmp = al_load_bitmap("bala.png");
    }
    for (i = 0; i < NUM_INIMIGOS; i++){
        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
    }
    start = al_load_bitmap("start.jpg");

    for (i = 0; i < NUM_ITENS; i++){
        coracoes[i].imagem = al_load_bitmap("heart.png");
        speed[i].imagem = al_load_bitmap("speed.png");
        pontos[i].imagem = al_load_bitmap("pontos.png");
    }
// __________________________________

// ----------------- LOOP PRINCIPAL -----------------
    al_start_timer(timer);

    while(!fim)
    {
        ALLEGRO_EVENT ev;
        al_wait_for_event(fila_eventos, &ev);
        // -------- EVENTOS E LÓGICA DO JOGO --------
        if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            fim = true;
        }

        else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_ESCAPE:
                fim = true;
                break;
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = true;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = true;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = true;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = true;
                break;
            case ALLEGRO_KEY_SPACE:
                teclas[ESPACO] = true;
                AtiraBalas(balas, NUM_BALAS, personagem_principal, personagem_principal.y + 12);
                AtiraBalas(balas_2, NUM_BALAS, personagem_principal, personagem_principal.y + 70);
                al_play_sample(ataque, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = true;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = true;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_KEY_UP)
        {
            switch(ev.keyboard.keycode)
            {
            case ALLEGRO_KEY_UP:
                teclas[CIMA] = false;
                break;
            case ALLEGRO_KEY_DOWN:
                teclas[BAIXO] = false;
                break;
            case ALLEGRO_KEY_LEFT:
                teclas[ESQUERDA] = false;
                break;
            case ALLEGRO_KEY_RIGHT:
                teclas[DIREITA] = false;
                break;
            case ALLEGRO_KEY_ENTER:
                teclas[ENTER] = false;
                break;
            case ALLEGRO_KEY_BACKSPACE:
                teclas[BACKSPACE] = false;
                break;
            }
        }

        else if (ev.type == ALLEGRO_EVENT_TIMER)
        {
            desenha = true;

            if (teclas[CIMA])
                personagem_principal.MoveCima();
            if (teclas[BAIXO])
                personagem_principal.MoveBaixo(ALTURA_T);
            if (teclas[ESQUERDA])
                personagem_principal.MoveEsquerda();
            if (teclas[DIREITA])
                personagem_principal.MoveDireita(LARGURA_T);
            if (teclas[ESPACO])
            {
                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].AtualizaBalas(0);
                    balas_2[i].AtualizaBalas(0);
                }

            }

            // Movimentação no menu
            if(menu)
            {
                al_attach_audio_stream_to_mixer(track_menu, al_get_default_mixer());
                al_set_audio_stream_playing(track_menu, true);
                if (teclas[CIMA] && select.y!=235)
                    select.y -= 70;
                if (teclas[BAIXO] && select.y!=305)
                    select.y += 70;
                if (teclas[ENTER] && select.y==235)
                {
                    menu = false;
                    al_set_audio_stream_playing(track_menu, false);
                }

            }

            // Acontecimentos do Jogo
            if(!game_over && !menu)
            {
                al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
                al_set_audio_stream_playing(musica, true);

                AtualizaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                {
                    //Gera e atualiza inimigos
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].GeraInimigos();
                        inimigos2[i].GeraInimigos();
                        inimigos[i].AtualizaInimigos();
                        inimigos[i].InimigoColidido(personagem_principal, hit);
                        inimigos2[i].AtualizaInimigos();
                        inimigos2[i].InimigoColidido(personagem_principal, hit);
                    }
                }

                //Checa colisões de projeteis

                BalaColidida(balas, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                BalaColidida(balas, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);
                BalaColidida(balas_2, NUM_BALAS, inimigos2, NUM_INIMIGOS, personagem_principal, dificuldade, morte_inimigo);

                // Faz os testes relacionado aos itens
                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].GeraItens(inimigos[i]);
                    coracoes[i].AtualizaItens();
                    coracoes[i].ItemColidido(personagem_principal, item);

                    speed[i].GeraItens(inimigos[i]);
                    speed[i].AtualizaItens();
                    speed[i].ItemColidido(personagem_principal, item);

                    pontos[i].GeraItens(inimigos[i]);
                    pontos[i].AtualizaItens();
                    pontos[i].ItemColidido(personagem_principal, item);
                }


                if ((dificuldade+1)%16 == 0) // Dificuldade aumenta a cada 15 pontos.
                {
                    for (i = 0; i < NUM_INIMIGOS; i++){
                        inimigos[i].velocidade++;
                        inimigos2[i].velocidade++;
                    }

                    dificuldade = 0;
                }

                if (personagem_principal.vidas <= 0)
                {
                    al_play_sample(morte_personagem, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
                    game_over = true;
                }
            }

            // Reinicializa o jogo
            else if (!menu)
            {
                al_set_audio_stream_playing(musica, false);
                if (teclas[ENTER])
                {
                    al_destroy_audio_stream(musica);

                    personagem_principal.InitPersonagem();

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].InitBalas();
                        balas_2[i].InitBalas();
                    }


                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].InitInimigo(7, 46, 85, 1 , 0);
                        inimigos2[i].InitInimigo(3, 55, 94, 3, 0);
                    }

                    for (i = 0; i < NUM_ITENS; i++)
                    {
                        coracoes[i].InitItem();
                        speed[i].InitItem();
                        pontos[i].InitItem();
                    }


                    personagem_principal.bmp = al_load_bitmap("ship.png");
                    musica = al_load_audio_stream("trilha_sonora.ogg", 4, 1024);

                    for (i = 0; i < NUM_BALAS; i++)
                    {
                        balas[i].bmp = al_load_bitmap("bala.png");
                        balas_2[i].bmp = al_load_bitmap("bala.png");
                    }
                    for (i = 0; i < NUM_INIMIGOS; i++)
                    {
                        inimigos[i].bmp = al_load_bitmap("enemyRed.png");
                        inimigos2[i].bmp = al_load_bitmap("enemyWhite.png");
                        coracoes[i].imagem = al_load_bitmap("heart.png");
                        speed[i].imagem = al_load_bitmap("heart.png");
                    }

                    game_over = false;
                }
            }

        }


        // _________________________________________

        // ---------------- DESENHO ----------------

        if(desenha && al_is_event_queue_empty(fila_eventos))
        {
            desenha = false;
            // Desenhos da Tela do Menu
            if(menu)
            {
                al_draw_bitmap(start, 0, 0, 0);
                if (select.ativo)
                    al_draw_bitmap(select.bmp, select.x, select.y, 0);

                if (teclas[ENTER] && flag == 0)
                {
                    flag = 1;
                    teclas[BACKSPACE] = false;
                    select.ativo = false;
                    start = al_load_bitmap("como_jogar.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
                else if (teclas[BACKSPACE] && flag == 1)
                {
                    flag = 0;
                    select.ativo = true;
                    start = al_load_bitmap("start.jpg");
                    al_draw_bitmap(start, 0, 0, 0);
                }
            }
            // Jogo normal, desenho de todos os objetos
            if(!game_over && !menu)
            {
                DesenhaPlanoFundo(estrelas_pf, NUM_PLANOS, NUM_ESTRELAS);
                personagem_principal.DesenhaPersonagem();

                for (i = 0; i < NUM_BALAS; i++)
                {
                    balas[i].DesenhaBalas();
                    balas_2[i].DesenhaBalas();
                }

                for (i = 0; i < NUM_INIMIGOS; i++){
                    inimigos[i].DesenhaInimigos();
                    inimigos2[i].DesenhaInimigos();
                }

                for (i = 0; i < NUM_ITENS; i++)
                {
                    coracoes[i].DesenhaItens();
                    speed[i].DesenhaItens();
                    pontos[i].DesenhaItens();
                }


                al_draw_textf(font20, al_map_rgb(255, 255, 255), 0, 0, 0, "VIDAS: %d / PONTOS: %d", personagem_principal.vidas, personagem_principal.pontos);
            }

            //Tela de fim de jogo
            else if (!menu)
            {
                al_draw_textf(font20, al_map_rgb(255, 255, 255), LARGURA_T / 2, ALTURA_T / 2, ALLEGRO_ALIGN_CENTRE, "FIM DE JOGO. SEUS PONTOS FORAM: %d. TECLE ENTER PARA JOGAR NOVAMENTE OU ESC PARA SAIR DO JOGO.", personagem_principal.pontos);
            }

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


        // _________________________________________
    }

// _________________________________________________

// -------- FINALIZAÇÕES DO PROGRAMA --------
    delete[] inimigos;
    delete[] inimigos2;
    delete[] balas;
    delete[] balas_2;
    delete[] coracoes;
    delete[] speed;
    delete[] pontos;

    al_destroy_bitmap(start);

    al_destroy_sample(ataque);
    al_destroy_sample(morte_inimigo);
    al_destroy_sample(morte_personagem);
    al_destroy_sample(hit);
    al_destroy_sample(item);
    al_destroy_audio_stream(musica);
    al_destroy_audio_stream(track_menu);

    al_destroy_display(display);
    al_destroy_timer(timer);
    al_destroy_font(font20);
    al_destroy_event_queue(fila_eventos);

//___________________________________________
    return 0;
}
예제 #3
0
int main(int argc, char **argv)
{
    ALLEGRO_VOICE *voice;
    ALLEGRO_MIXER *mixer;
    ALLEGRO_MIXER *submixer[2];
    ALLEGRO_SAMPLE_INSTANCE *sample[2];
    ALLEGRO_SAMPLE *sample_data[2];
    float sample_time;
    float max_sample_time;
    int i;

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

    open_log();

    if (argc < 3) {
        log_printf("This example needs to be run from the command line.\nUsage: %s file1 file2\n", argv[0]);
        goto done;
    }

    al_init_acodec_addon();

    if (!al_install_audio()) {
        abort_example("Could not init sound!\n");
    }

    voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16,
                            ALLEGRO_CHANNEL_CONF_2);
    if (!voice) {
        abort_example("Could not create ALLEGRO_VOICE.\n");
    }

    mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
                            ALLEGRO_CHANNEL_CONF_2);
    submixer[0] = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
                                  ALLEGRO_CHANNEL_CONF_2);
    submixer[1] = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
                                  ALLEGRO_CHANNEL_CONF_2);
    if (!mixer || !submixer[0] || !submixer[1]) {
        abort_example("al_create_mixer failed.\n");
    }

    if (!al_attach_mixer_to_voice(mixer, voice)) {
        abort_example("al_attach_mixer_to_voice failed.\n");
    }

    for (i = 0; i < 2; i++) {
        const char *filename = argv[i + 1];
        sample_data[i] = al_load_sample(filename);
        if (!sample_data[i]) {
            abort_example("Could not load sample from '%s'!\n", filename);
        }
        sample[i] = al_create_sample_instance(NULL);
        if (!sample[i]) {
            abort_example("al_create_sample failed.\n");
        }
        if (!al_set_sample(sample[i], sample_data[i])) {
            abort_example("al_set_sample_ptr failed.\n");
        }
        if (!al_attach_sample_instance_to_mixer(sample[i], submixer[i])) {
            abort_example("al_attach_sample_instance_to_mixer failed.\n");
        }
        if (!al_attach_mixer_to_mixer(submixer[i], mixer)) {
            abort_example("al_attach_mixer_to_mixer failed.\n");
        }
    }

    /* Play sample in looping mode. */
    for (i = 0; i < 2; i++) {
        al_set_sample_instance_playmode(sample[i], ALLEGRO_PLAYMODE_LOOP);
        al_play_sample_instance(sample[i]);
    }

    max_sample_time = al_get_sample_instance_time(sample[0]);
    sample_time = al_get_sample_instance_time(sample[1]);
    if (sample_time > max_sample_time)
        max_sample_time = sample_time;

    log_printf("Playing...");

    al_rest(max_sample_time);

    al_set_sample_instance_gain(sample[0], 0.5);
    al_rest(max_sample_time);

    al_set_sample_instance_gain(sample[1], 0.25);
    al_rest(max_sample_time);

    al_stop_sample_instance(sample[0]);
    al_stop_sample_instance(sample[1]);
    log_printf("Done\n");

    /* Free the memory allocated. */
    for (i = 0; i < 2; i++) {
        al_set_sample(sample[i], NULL);
        al_destroy_sample(sample_data[i]);
        al_destroy_sample_instance(sample[i]);
        al_destroy_mixer(submixer[i]);
    }
    al_destroy_mixer(mixer);
    al_destroy_voice(voice);

    al_uninstall_audio();

done:
    close_log(true);

    return 0;
}
예제 #4
0
파일: game.c 프로젝트: davidgomes/gnumaku
static SCM
game_init (SCM game_smob, SCM s_width, SCM s_height, SCM s_fullscreen)
{
    Game *game = check_game(game_smob);
    int width = scm_to_int (s_width);
    int height = scm_to_int (s_height);
    bool fullscreen = scm_to_bool (s_fullscreen);

    /* Initialize Allegro things */
    /* TODO: Handle these errors in a proper way */
    if(!al_init ()) {
	fprintf (stderr, "failed to initialize allegro!\n");
        exit (-1);
    }

    if (!al_init_image_addon ()) {
	fprintf (stderr, "failed to initialize image addon!\n");
        exit (-1);
    }

    al_init_font_addon ();

    if(!al_init_ttf_addon ()) {
        fprintf (stderr, "failed to initialize ttf addon!\n");
        exit (-1);
    }

    if(!al_install_audio ()) {
        fprintf (stderr, "failed to initialize audio addon!\n");
        exit (-1);
    }
 
    if(!al_init_acodec_addon ()) {
        fprintf (stderr, "failed to initialize audio codecs addon!\n");
        exit (-1);
    }
 
    if (!al_reserve_samples (16)) {
        fprintf (stderr, "failed to reserve samples!\n");
        exit (-1);
    }

    if(!al_install_keyboard ()) {
	fprintf (stderr, "failed to initialize keyboard!\n");
        exit (-1);
    }
    
    if (fullscreen) {
        al_set_new_display_flags (ALLEGRO_FULLSCREEN);
    }

    game->display = al_create_display (width, height);
    if (!game->display) {
	fprintf (stderr, "failed to create display!\n");
    }

    game->timer = al_create_timer (game->timestep);
    game->event_queue = al_create_event_queue ();
    al_register_event_source (game->event_queue, al_get_display_event_source (game->display));
    al_register_event_source (game->event_queue, al_get_timer_event_source (game->timer));
    al_register_event_source (game->event_queue, al_get_keyboard_event_source ());

    return SCM_UNSPECIFIED;
}
예제 #5
0
int engine_init(struct Engine_Conf *conf)
{
  if (engine.initialized)
  {
    puts("WARNING: Calling game_init() more than once");
    return 1;
  }

  // Initialize Allegro and stuff
  al_init();

  if (!al_install_keyboard())
  {
    puts("ERROR: Could not initialize the keyboard...");
    return 0;
  }

  if (conf->audio)
  {
    if (!al_install_audio())
    {
      puts("ERROR: Could not initialize audio...");
      return 0;
    }

    if (!al_init_acodec_addon())
    {
      puts("ERROR: Could not initialize acodec addon...");
      return 0;
    }
  }

  // Add-ons
  if (!al_init_image_addon())
  {
    puts("ERROR: Could not initialize image addon...");
    return 0;
  }

  al_init_font_addon();
  al_init_primitives_addon();

  // Find how much the game will be scaled when conf->scale <= 0
  if (conf->scale <= 0)
  {
    ALLEGRO_MONITOR_INFO info;
    al_get_monitor_info(0, &info);

    int monitor_w = info.x2 - info.x1;
    int monitor_h = info.y2 - info.y1;

    float new_monitor_w = (monitor_w - (monitor_w * SCREEN_RES_OVERRIDE));
    float new_monitor_h = (monitor_h - (monitor_h * SCREEN_RES_OVERRIDE));

    conf->scale = 2;

    // Keep scaling until a suitable scale factor is found
    while (1)
    {
      int scale_w = conf->width * conf->scale;
      int scale_h = conf->height * conf->scale;

      if (scale_w > new_monitor_w || scale_h > new_monitor_h)
      {
        --conf->scale;
        break;
      }

      ++conf->scale;
    }
  }
  else if (conf->scale < 2)
  {
    conf->scale = 2;
  }

  engine.display = al_create_display(conf->width * conf->scale,
    conf->height * conf->scale);

  if (!engine.display)
  {
    puts("ERROR: Could not create a display window...");
    return 0;
  }

  al_set_window_title(engine.display, conf->title);

  font = al_create_builtin_font();

  engine.timer = al_create_timer(1.0 / conf->framerate);
  engine.event_queue = al_create_event_queue();

  mainconf = conf;
  set_bg_color(BG_COLOR_DEFAULT);

  ALLEGRO_TRANSFORM trans;
  al_identity_transform(&trans);
  al_scale_transform(&trans, conf->scale, conf->scale);
  al_use_transform(&trans);

  engine.initialized = TRUE;

  return 1;
}
예제 #6
0
void Engine::init(const char* title, int width, int height, bool fullscreen){

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

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

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

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

    al_reserve_samples(0);

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

    al_register_event_source(event_queue, al_get_keyboard_event_source());
    al_register_event_source(event_queue, al_get_mouse_event_source());
    al_register_event_source(event_queue, al_get_timer_event_source(timer));
    al_register_event_source(event_queue, al_get_display_event_source(display));

    al_hide_mouse_cursor(display);

	m_fullscreen = fullscreen;
    m_running = true;

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

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

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

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

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

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

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

    al_start_timer(timer);
}
예제 #7
0
파일: main.cpp 프로젝트: pmprog/ROTMenu
int main( int argc, char* argv[] )
{
	ALLEGRO_EVENT e;
	ALLEGRO_TIMER* t;
	int64_t framesToUpdate = 0;

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

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

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

#if EXIT_IF_NO_AUDIO != 0

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

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

#else

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

#endif // EXIT_IF_NO_AUDIO

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

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

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

	al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);

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

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

			if( foundMode )
				break;
		}
	}

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

	al_hide_mouse_cursor( Screen );

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

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

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

	al_set_blender( ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA );

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

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

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

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

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

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

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

	al_destroy_event_queue( EventQueue );
	al_destroy_display( Screen );

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

	return 0;
}
예제 #8
0
파일: game.cpp 프로젝트: kotori/alMonopoly
int MonopolyGame::init() {

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

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

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

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

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

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

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

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

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

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

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

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

    return 0;
}
int main(int argc, char **argv)
{
   const char *filename = "../demos/cosmic_protector/data/sfx/title_music.ogg";
   ALLEGRO_VOICE *voice;
   ALLEGRO_MIXER *mixer;
   ALLEGRO_AUDIO_STREAM *stream;

   if (argc > 1) {
      filename = argv[1];
   }

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

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

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Could not create display.\n");
      return 1;
   }

   dbuf = al_create_bitmap(640, 480);

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

   if (!al_install_audio()) {
      abort_example("Could not init sound.\n");
      return 1;
   }

   voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16,
      ALLEGRO_CHANNEL_CONF_2);
   if (!voice) {
      abort_example("Could not create voice.\n");
      return 1;
   }

   mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
      ALLEGRO_CHANNEL_CONF_2);
   if (!mixer) {
      abort_example("Could not create mixer.\n");
      return 1;
   }

   if (!al_attach_mixer_to_voice(mixer, voice)) {
      abort_example("al_attach_mixer_to_voice failed.\n");
      return 1;
   }

   stream = al_load_audio_stream(filename, 4, 2048);
   if (!stream) {
      abort_example("Could not load '%s'\n", filename);
      return 1;
   }

   al_set_audio_stream_playmode(stream, ALLEGRO_PLAYMODE_LOOP);
   al_attach_audio_stream_to_mixer(stream, mixer);

   al_set_mixer_postprocess_callback(mixer, update_meter, NULL);

   main_loop();

   al_destroy_audio_stream(stream);
   al_destroy_mixer(mixer);
   al_destroy_voice(voice);
   al_uninstall_audio();

   al_destroy_bitmap(dbuf);
   al_destroy_bitmap(bmp);

   return 0;
}
bool
initialize ()
{
  ALLEGRO_BITMAP *temp_color_bitmap;
  ALLEGRO_BITMAP *temp_mask_bitmap;

  global.quit = false;
  al_set_app_name ("Super Battle Thor II");
  if (!al_init ())
    {
      fputs ("Error: Could not start allegro.\n", stderr);
      return false;
    }

  al_set_new_display_option (ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST);
  al_set_new_display_flags (ALLEGRO_GENERATE_EXPOSE_EVENTS);
  global.display = al_create_display (256, 192);
  if (!global.display)
    {
      fputs ("Error: Allegro could not create a display of 256x192 pixels.\n",
             stderr);
      return false;
    }

  if (!al_install_keyboard ())
    {
      fputs ("Allegro could not initialize the keyboard system.\n", stderr);
      return false;
    }

  global.timer = al_create_timer (ALLEGRO_BPS_TO_SECS (60));
  if (!global.timer)
    {
      fputs ("Allegro could not create a 60hrz timer.\n", stderr);
      return false;
    }

  global.queue = al_create_event_queue ();
  if (!global.queue)
    {
      fputs ("Allegro could not create an event queue.\n", stderr);
      return false;
    }
  al_register_event_source (global.queue, al_get_keyboard_event_source ());
  al_register_event_source (global.queue,
                            al_get_display_event_source (global.display));
  al_register_event_source (global.queue,
                            al_get_timer_event_source (global.timer));

  if (!al_init_image_addon ())
    {
      fputs ("Allegro could not initialize the image loading system.\n",
             stderr);
      return false;
    }

  if (!al_install_audio ())
    {
      fputs ("Allegro could not initialize the audio system.\n", stderr);
      return false;
    }
  al_reserve_samples (16);

  if (!al_init_acodec_addon ())
    {
      fputs ("Allegro could not initialize the audio file loading system.\n",
             stderr);
      return false;
    }

  al_init_font_addon ();

  /* load files */
  global.path = al_get_standard_path (ALLEGRO_PROGRAM_PATH);
  al_append_path_component (global.path, "media");

  al_set_path_filename (global.path, "proggy_tiny.png");
  global.programing_font =
    al_load_bitmap_font (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.programing_font)
    {
      fputs ("Allegro could not load proggy_tiny.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "mjollnir.png");
  global.sprite_bitmap[SPRITE_THOR] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sprite_bitmap[SPRITE_THOR])
    {
      fputs ("Allegro could not load mjollnir.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "arrows.png");
  global.arrow_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.arrow_bitmap)
    {
      fputs ("Allegro could not load arrows.png.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_1_2_3_4.jpg");
  global.backgrounds[BACKGROUND_1] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_1])
    {
      fputs ("Allegro could not load background_1_2_3_4.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_5.jpg");
  global.backgrounds[BACKGROUND_5] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_5])
    {
      fputs ("Allegro could not load background_5.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "background_6.jpg");
  global.backgrounds[BACKGROUND_6] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_6])
    {
      fputs ("Allegro could not load background_6.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "title_screen.jpg");
  global.backgrounds[BACKGROUND_TITLE] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_TITLE])
    {
      fputs ("Allegro could not load title_screen.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "game_over.jpg");
  global.backgrounds[BACKGROUND_GAME_OVER] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_GAME_OVER])
    {
      fputs ("Allegro could not load game_over.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "you_win.jpg");
  global.backgrounds[BACKGROUND_YOU_WIN] =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.backgrounds[BACKGROUND_YOU_WIN])
    {
      fputs ("Allegro could not load you_win.jpg.\n", stderr);
      return false;
    }

  global.backgrounds[BACKGROUND_BLACK] = al_create_bitmap (256, 192);
  if (!global.backgrounds[BACKGROUND_BLACK])
    {
      fputs ("Allegro could not make a 256x192 bitmap :o", stderr);
      return false;
    }
  al_set_target_bitmap (global.backgrounds[BACKGROUND_BLACK]);
  al_clear_to_color (al_map_rgb (0, 0, 0));
  al_set_target_backbuffer (global.display);

/* start copy paste code here becasue I'm lazy */
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "0-thor.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 0-thor.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "0-thor_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 0-thor_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_THOR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "1-giant.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 1-giant.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "1-giant_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 1-giant_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_GIANT] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "2-nidhogg.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 2-nidhogg.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "2-nidhogg_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 2-nidhogg_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_NIDHOGG] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "3-ran.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 3-ran.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "3-ran_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 3-ran_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_RAN] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "4-grendel.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 4-grendel.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "4-grendel_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 4-grendel_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_GRENDEL] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "5-fafnir.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 5-fafnir.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "5-fafnir_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 5-fafnir_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FAFNIR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "6-loki.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 6-loki.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "6-loki_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 6-loki_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_LOKI] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "7-fenrir.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load 7-fenrir.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "7-fenrir_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load 7-fenrir_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FENRIR] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
  al_set_path_filename (global.path, "fight.jpg");
  temp_color_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_color_bitmap)
    {
      fputs ("Allegro could not load fight.jpg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "fight_mask.jpg");
  temp_mask_bitmap =
    al_load_bitmap (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!temp_mask_bitmap)
    {
      fputs ("Allegro could not load fight_mask.jpg.\n", stderr);
      return false;
    }

  global.sprite_bitmap[SPRITE_FIGHT] =
    make_from_mask (temp_color_bitmap, temp_mask_bitmap);
  al_destroy_bitmap (temp_color_bitmap);
  al_destroy_bitmap (temp_mask_bitmap);
/*------------------------------------------------------------------------*/
/* loading sounds here (still copy paste) */
  al_set_path_filename (global.path, "titlescreen_loop.ogg");
  global.sounds[SOUND_TITLESCREEN_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_TITLESCREEN_LOOP])
    {
      fputs ("Allegro could not load titlescreen_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "begin_battle.ogg");
  global.sounds[SOUND_BEGIN_BATTLE] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_BEGIN_BATTLE])
    {
      fputs ("Allegro could not load begin_battle.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "battle_loop.ogg");
  global.sounds[SOUND_BATTLE_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_BATTLE_LOOP])
    {
      fputs ("Allegro could not load battle_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "dragon_loop.ogg");
  global.sounds[SOUND_DRAGON_LOOP] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_DRAGON_LOOP])
    {
      fputs ("Allegro could not load dragon_loop.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "hit_1.ogg");
  global.sounds[SOUND_HIT_1] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_HIT_1])
    {
      fputs ("Allegro could not load hit_1.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "hit_2.ogg");
  global.sounds[SOUND_HIT_2] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_HIT_2])
    {
      fputs ("Allegro could not load hit_2.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_1.ogg");
  global.sounds[SOUND_LAUGH_1] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_1])
    {
      fputs ("Allegro could not load laugh_1.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_2.ogg");
  global.sounds[SOUND_LAUGH_2] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_2])
    {
      fputs ("Allegro could not load laugh_2.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_3.ogg");
  global.sounds[SOUND_LAUGH_3] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_3])
    {
      fputs ("Allegro could not load laugh_3.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_4.ogg");
  global.sounds[SOUND_LAUGH_4] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_4])
    {
      fputs ("Allegro could not load laugh_4.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_5.ogg");
  global.sounds[SOUND_LAUGH_5] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_5])
    {
      fputs ("Allegro could not load laugh_5.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "laugh_6.ogg");
  global.sounds[SOUND_LAUGH_6] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_LAUGH_6])
    {
      fputs ("Allegro could not load laugh_6.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "killed_baddie.ogg");
  global.sounds[SOUND_KILLED_BADDIE] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_KILLED_BADDIE])
    {
      fputs ("Allegro could not load killed_baddie.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "got_hit.ogg");
  global.sounds[SOUND_GOT_HIT] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_GOT_HIT])
    {
      fputs ("Allegro could not load got_hit.ogg.\n", stderr);
      return false;
    }

  al_set_path_filename (global.path, "you_are_dead.ogg");
  global.sounds[SOUND_YOU_ARE_DEAD] =
    al_load_sample (al_path_cstr (global.path, ALLEGRO_NATIVE_PATH_SEP));
  if (!global.sounds[SOUND_YOU_ARE_DEAD])
    {
      fputs ("Allegro could not you_are_dead.ogg.\n", stderr);
      return false;
    }

  global.music = NULL;

  al_destroy_path (global.path);

  return true;
}
예제 #11
0
파일: main.c 프로젝트: fspacheco/ProjetoC
int main()
{
    bool quit = false;
    int gamestate = 0;
    srand(time(NULL));

    int change_bkg = 0;
    int stopwatch = 120;
    bool iddle = false;

    int bulletID=0;
    int bulletCount=0;

    ALLEGRO_DISPLAY*            display;
    ALLEGRO_TIMER*              timer_0p2;
    ALLEGRO_TIMER*              timer_1;
    ALLEGRO_TIMER*              timer_60;
    ALLEGRO_EVENT_QUEUE*        event_queue;
    ALLEGRO_EVENT               ev;

    ALLEGRO_BITMAP*             img_home_screen;
    ALLEGRO_BITMAP*             img_dica_h1n1;
    ALLEGRO_BITMAP*             img_background0;
    ALLEGRO_BITMAP*             img_game_over;
    ALLEGRO_BITMAP*             img_you_win;

    ALLEGRO_BITMAP*             img_heart;
    ALLEGRO_BITMAP*             img_medal;
    ALLEGRO_BITMAP*             img_clock;
    ALLEGRO_BITMAP*             img_block1;
    ALLEGRO_BITMAP*             img_block2;

    ALLEGRO_BITMAP*             img_player_walking;
    ALLEGRO_BITMAP*             img_player_walking_shoot;
    ALLEGRO_BITMAP*             img_player_immobile;
    ALLEGRO_BITMAP*             img_player_immobile_shoot;
    ALLEGRO_BITMAP*             img_player_jump;
    ALLEGRO_BITMAP*             img_player_jump_shoot;
    ALLEGRO_BITMAP*             img_player_bullet;

    ALLEGRO_BITMAP*             img_enemy1;
    ALLEGRO_BITMAP*             img_boss1;
    ALLEGRO_BITMAP*             img_enemy_bullet;

    ALLEGRO_SAMPLE*             spl_theme;
    ALLEGRO_SAMPLE*             spl_playerShoot;
    ALLEGRO_SAMPLE*             spl_mlk;

    ALLEGRO_SAMPLE_INSTANCE*    instance_theme;
    ALLEGRO_SAMPLE_INSTANCE*    instance_playerShoot;
    ALLEGRO_SAMPLE_INSTANCE*    instance_mlk;

    ALLEGRO_FONT*           fonte16;

    /* Estruturas */
    s_object player;
    s_object block[LINHA_MAX][COLUNA_MAX];
    s_object enemy1[LINHA_MAX][COLUNA_MAX];

    for (i=0; i<LINHA_MAX; i++)
    {
        for(j=0; j<COLUNA_MAX; j++)
        {
            /* Cria o player */
            if(mapa[i][j] == 1)
            {
                player.y = i*16 - 24;
                player.x = j*64 + 24;
                player.speed = 3;
                player.direction = 1;

                player.live = true;
                player.life = 100;

                block[i][j].live = false;
            }
            /* Cria os Blocos */
            if(mapa[i][j] == 2)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 3)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 4)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = true;
            }
            if(mapa[i][j] == 5)
            {
                block[i][j].y = i*16;
                block[i][j].x = j*64;
                block[i][j].live = false;
            }
            /* Cria os Inimigos */
            if(mapa[i][j] == 6)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = -1;

                enemy1[i][j].life = 3;
                enemy1[i][j].live = true;

                block[i][j].live = false;
            }
            if(mapa[i][j] == 7 || mapa[i][j] == 8)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = 1;

                enemy1[i][j].life = 3;
                enemy1[i][j].live = false;

                block[i][j].live = false;
            }
            if(mapa[i][j] == 9)
            {
                enemy1[i][j].y = i*16 - 24;
                enemy1[i][j].x = j*64;
                enemy1[i][j].speed = 2;
                enemy1[i][j].direction = -1;

                enemy1[i][j].life = 25;
                enemy1[i][j].live = false;

                block[i][j].live = false;
            }
        }
    }

    s_bullet playerBullet[NUM_BULLET];
    s_bullet enemyBullet[NUM_BULLET];

    for(i=0; i<NUM_BULLET; i++)
    {
        playerBullet[i].x = 0;
        playerBullet[i].y = 0;
        playerBullet[i].speed = 5;
        playerBullet[i].direction = 1;
        playerBullet[i].live = false;

        enemyBullet[i].x = 0;
        enemyBullet[i].y = 0;
        enemyBullet[i].speed = 5;
        enemyBullet[i].direction = 0;
        enemyBullet[i].live = false;
    }
    s_animation walking;
    walking.maxFrame = 8;
    walking.frameDelay = 5;
    walking.frameCount = 0;
    walking.curFrame = 0;
    walking.frameHeight = 40;
    walking.frameWidth = 40;

    s_animation jumping;
    jumping.maxFrame = 7;
    jumping.frameDelay = 5;
    jumping.frameCount = 0;
    jumping.curFrame = 0;
    jumping.frameHeight = 52;
    jumping.frameWidth = 40;

    s_animation immobile;
    immobile.maxFrame = 7;
    immobile.frameDelay = 15;
    immobile.frameCount = 0;
    immobile.curFrame = 0;
    immobile.frameHeight = 40;
    immobile.frameWidth = 40;

    s_animation anim_enemy1;
    anim_enemy1.maxFrame = 3;
    anim_enemy1.frameDelay = 15;
    anim_enemy1.frameCount = 0;
    anim_enemy1.curFrame = 0;
    anim_enemy1.frameHeight = 40;
    anim_enemy1.frameWidth = 40;

    /* Faz com que as teclas comecem em false */
    for(i=0; i<KEY_MAX; i++)
    {
        keys[i] = false;
    }

    /* Carrega as configuracoes (teclado, audio, etc) */
    al_init();
    al_install_keyboard();
    al_init_image_addon();
    al_install_audio();
    al_init_acodec_addon();
    al_init_font_addon();
    al_init_ttf_addon();


    /* Erros ao criar algo */
    display = al_create_display(SCREEN_W, SCREEN_H);
    if(!display)
    {
        printf("Erro ao criar o display");
        exit(-1);
    }

    timer_0p2 = al_create_timer(5.0);
    timer_1 = al_create_timer(1.0);
    timer_60 = al_create_timer(1/60.0);

    if(!timer_0p2)
    {
        printf("Erro ao criar o timer de 0.2 FPS");
        exit(-1);
    }
    if(!timer_1)
    {
        printf("Erro ao criar o timer de 1 FPS");
        exit(-1);
    }
    if(!timer_60)
    {
        printf("Erro ao criar o timer de 60 FPS");
        exit(-1);
    }

    event_queue = al_create_event_queue();
    if(!event_queue)
    {
        printf("Erro ao criar o event_queue");
        exit(-1);
    }

    /* Carregando as Imagens */
    img_home_screen = al_load_bitmap("Sprites/Background/home_screen.png");
    img_dica_h1n1 = al_load_bitmap("Sprites/Background/dica_h1n1.png");
    img_background0 = al_load_bitmap("Sprites/Background/background_h1n1.png");
    img_you_win = al_load_bitmap("Sprites/Background/you_win.png");
    img_game_over = al_load_bitmap("Sprites/Background/game_over.png");

    img_heart = al_load_bitmap("Sprites/heart.png");
    img_medal = al_load_bitmap("Sprites/medal.png");
    img_clock = al_load_bitmap("Sprites/clock.png");
    img_block1 = al_load_bitmap("Sprites/block1.png");
    img_block2 = al_load_bitmap("Sprites/block2.png");

    img_player_walking = al_load_bitmap("Sprites/Player/player_walking.png");
    img_player_walking_shoot = al_load_bitmap("Sprites/Player/player_walking_shoot.png");
    img_player_immobile = al_load_bitmap("Sprites/Player/player_immobile.png");
    img_player_immobile_shoot = al_load_bitmap("Sprites/Player/player_immobile_shoot.png");
    img_player_jump = al_load_bitmap("Sprites/Player/player_jump.png");
    img_player_jump_shoot = al_load_bitmap("Sprites/Player/player_jump_shoot.png");
    img_player_bullet = al_load_bitmap("Sprites/Player/player_bullet.png");

    img_enemy1 = al_load_bitmap("Sprites/Enemies/enemy_h1n1.png");
    img_boss1 = al_load_bitmap("Sprites/Enemies/boss_h1n1.png");
    img_enemy_bullet = al_load_bitmap("Sprites/Enemies/enemy_bullet.png");

    /* Carregando os Samples */
    al_reserve_samples(10);
    spl_theme = al_load_sample("Sounds/theme.wav");
    spl_playerShoot = al_load_sample("Sounds/shoot.wav");
    spl_mlk = al_load_sample("Sounds/mlk.wav");

    instance_theme = al_create_sample_instance(spl_theme);
    instance_playerShoot = al_create_sample_instance(spl_playerShoot);
    instance_mlk = al_create_sample_instance(spl_mlk);

    al_set_sample_instance_gain(instance_playerShoot, 0.5);

    al_attach_sample_instance_to_mixer(instance_theme, al_get_default_mixer());
    al_attach_sample_instance_to_mixer(instance_playerShoot, al_get_default_mixer());
    al_attach_sample_instance_to_mixer(instance_mlk, al_get_default_mixer());

    /* Registra os Eventos */
    al_register_event_source(event_queue, al_get_display_event_source(display));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_0p2));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_1));
    al_register_event_source(event_queue, al_get_timer_event_source(timer_60));
    al_register_event_source(event_queue, al_get_keyboard_event_source());

    /* Carregando os timers */
    al_start_timer(timer_0p2);
    al_start_timer(timer_1);
    al_start_timer(timer_60);

    /* Carregando a fonte */
    fonte16 = al_load_ttf_font("Joystix.TTF", 16, 0);
    if (!fonte16) {
        printf("Erro ao carregar Joystix.TTF\n");
        exit(1);
    }

    while(!quit)
    {
        switch(gamestate)
        {
        case 0:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
                if(ev.keyboard.keycode == ALLEGRO_KEY_SPACE) /* Faz com que o jogo inicie ao pressionar space */
                {
                    change_bkg++;
                    if(change_bkg >= 2)
                    {
                        gamestate = 1;
                    }
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    if(change_bkg == 0)
                    {
                        al_draw_bitmap(img_home_screen, 0, 0, 0);
                    }
                    if(change_bkg == 1)
                    {
                        al_draw_bitmap(img_dica_h1n1, 0, 0, 0);

                        if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay)
                        {
                            if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame)
                            {
                                anim_enemy1.curFrame = 0;
                            }
                            anim_enemy1.frameCount = 0;
                        }

                        al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 330, 320, 0);
                        al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, 450, 320, 0);
                    }
                    al_flip_display();
                }
            }
            break;
        case 1:

            if(force>= -7.5)
            {
                force-=0.5; /* Queda */
            }

            /* Toca a música de fundo */
            if(!al_get_sample_instance_playing(instance_theme) && !al_get_sample_instance_playing(instance_mlk))
            {
                al_play_sample_instance(instance_theme);
            }

            /* Fechar o display */
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
            {
                quit = true;
            }

            /* Evento de quando a tecla eh pressionada */
            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_ESCAPE:
                    quit = true;
                    break;
                case ALLEGRO_KEY_SPACE:
                    keys[KEY_SPACE]=true;
                    break;
                case ALLEGRO_KEY_UP:
                    keys[KEY_UP] = true;
                    if(jump == false)
                    {
                        jump = true;
                        force = gravity;
                    }
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[KEY_RIGHT]=false;
                    keys[KEY_LEFT]=true;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[KEY_LEFT]=false;
                    keys[KEY_RIGHT]=true;
                    break;
                case ALLEGRO_KEY_F1:
                    if(!al_get_sample_instance_playing(instance_mlk))
                    {
                        al_play_sample_instance(instance_mlk);
                        al_stop_sample_instance(instance_theme);
                    }
                    break;
                case ALLEGRO_KEY_M:
                    if(al_get_sample_instance_playing(instance_mlk))
                    {
                        al_stop_sample_instance(instance_mlk);
                    }
                    break;
                }
            }

            /* Evento de quando a tecla eh solta */
            if(ev.type == ALLEGRO_EVENT_KEY_UP)
            {
                switch(ev.keyboard.keycode)
                {
                case ALLEGRO_KEY_SPACE:
                    keys[KEY_SPACE]=false;
                    break;
                case ALLEGRO_KEY_UP:
                    keys[KEY_UP] = false;
                    break;
                case ALLEGRO_KEY_LEFT:
                    keys[KEY_LEFT]=false;
                    break;
                case ALLEGRO_KEY_RIGHT:
                    keys[KEY_RIGHT]=false;
                    break;
                }
            }

            if(ev.type == ALLEGRO_EVENT_TIMER)
            {
                if(ev.timer.source == timer_0p2)
                {
                    if((iddle == false) && (keys[KEY_RIGHT] == false) && (keys[KEY_LEFT] == false) && (jump == false))
                    {
                        iddle = true;
                    }
                }
                if(ev.timer.source == timer_1)
                {
                    stopwatch--;
                }
                if(ev.timer.source == timer_60)
                {
                    /* Posicionamento do player*/
                    player.y-=force;

                    if(keys[KEY_RIGHT])
                    {
                        player.direction = 1;
                        player.x+=player.speed;
                    }
                    if(keys[KEY_LEFT])
                    {
                        player.direction = -1;
                        player.x-=player.speed;
                    }

                    if(keys[KEY_SPACE])
                    {
                        for(i=0; i<NUM_BULLET; i++)
                        {
                            if(!al_get_sample_instance_playing(instance_playerShoot))
                            {
                                playerShoot(&player, &playerBullet[i], instance_playerShoot);
                            }
                        }
                    }


                    /*Posicionamento do Inimigo */

                    for (i=0; i<LINHA_MAX; i++)
                    {
                        for(j=0; j<COLUNA_MAX; j++)
                        {
                            if(player.x > enemy1[i][j].x + 40)
                            {
                                enemy1[i][j].direction = 1;
                            }
                            else if(player.x + 40 <= enemy1[i][j].x)
                            {
                                enemy1[i][j].direction = -1;
                            }
                        }
                    }

                    /* ~~Posicionamento do projetil~~ */

                    /* Chance do Inimigo Atirar */
                    chance_enemy_shoot = rand() % 40;
                    for (i=0; i<LINHA_MAX; i++)
                    {
                        for(j=0; j<COLUNA_MAX; j++)
                        {
                            enemyShoot(&player, &enemy1[i][j], enemyBullet, &bulletID, &bulletCount);
                        }
                    }
                    for(i=0; i<NUM_BULLET; i++)
                    {
                        if(!playerBullet[i].live)
                        {
                            playerBullet[i].direction = player.direction;
                        }

                        if(playerBullet[i].live)
                        {
                            if(playerBullet[i].direction == -1)
                            {
                                playerBullet[i].x-=playerBullet[i].speed;
                            }
                            else if(playerBullet[i].direction == 1)
                            {
                                playerBullet[i].x+=playerBullet[i].speed;
                            }
                        }
                        if(enemyBullet[i].live)
                        {
                            if(enemyBullet[i].direction == -1)
                            {
                                enemyBullet[i].x-=enemyBullet[i].speed;
                            }
                            if(enemyBullet[i].direction == 1)
                            {
                                enemyBullet[i].x+=enemyBullet[i].speed;
                            }

                        }
                    }

                    /* Prende a Camera no Personagem */
                    cameraX = player.x-(SCREEN_W/2);
                    cameraY = player.y-(SCREEN_H/2);

                    /* Fazer com que a camera nao passe dos limites do mapa */
                    if (cameraX < 0) cameraX = 0;
                    if (cameraY < 0) cameraY = 0;
                    if (cameraX > WORLD_W - SCREEN_W) cameraX = WORLD_W - SCREEN_W;
                    if (cameraY > WORLD_H - SCREEN_H) cameraY = WORLD_H - SCREEN_H;

                    /* Colisoes + check trap */
                    for (i = 0; i<LINHA_MAX; i++)
                    {
                        for(j = 0; j<COLUNA_MAX; j++)
                        {
                            for(k=0; k<NUM_BULLET; k++)
                            {
                                collision_bullet_player(&player, &enemyBullet[k], img_enemy_bullet, &bulletCount, 40, 40);
                            }
                            if(block[i][j].live == true)
                            {
                                if(mapa[i][j] == 2)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 3)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 4)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 4);
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                if(mapa[i][j] == 5)
                                {
                                    collision_player_tiles(&player, &block[i][j], &jumping, img_block2);
                                }
                                for(k=0; k<NUM_BULLET; k++)
                                {
                                    collision_bullet_tiles(&playerBullet[k], &block[i][j], img_player_bullet, img_block2, 0, &bulletCount);
                                    collision_bullet_tiles(&enemyBullet[k], &block[i][j], img_player_bullet, img_block2, 1, &bulletCount);
                                }
                            }
                            if(block[i][j].live == false)
                            {
                                if(mapa[i][j] == 5)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 5);
                                }
                                if(mapa[i][j] == 6)
                                {
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 7)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 7);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 8)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 8);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                                if(mapa[i][j] == 9)
                                {
                                    check_trap(&player, &block[i][j], &enemy1[i][j], 9);
                                    collision_player_enemy(&player, &enemy1[i][j], 40, 40);

                                    for(k=0; k<NUM_BULLET; k++)
                                    {
                                        collision_bullet_enemy(&playerBullet[k], &enemy1[i][j], img_player_bullet, 40, 40);
                                    }
                                }
                            }
                        }
                    }

                    collision_player_wall(&player, &jumping, img_block1);

                    /* ~~Desenha o Background~~ */
                    al_draw_bitmap(img_background0, 0 - cameraX, 0 - cameraY, 0);

                    /* ~~Animação dos inimigos~~ */
                    if(++anim_enemy1.frameCount >= anim_enemy1.frameDelay)
                    {
                        if(++anim_enemy1.curFrame >= anim_enemy1.maxFrame)
                        {
                            anim_enemy1.curFrame = 0;
                        }
                        anim_enemy1.frameCount = 0;
                    }

                    /* ~~Desenha os Blocos/Inimigos~~ */
                    for (i = 0; i<LINHA_MAX; i++)
                    {
                        for(j = 0; j<COLUNA_MAX; j++)
                        {
                            if(mapa[i][j] == 2 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block1, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 3 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 4 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if(mapa[i][j] == 5 && block[i][j].live == true)
                            {
                                al_draw_bitmap(img_block2, block[i][j].x - cameraX, block[i][j].y - cameraY, 0);
                            }
                            if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == -1) && (enemy1[i][j].live == true))
                            {
                                al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0);
                            }
                            if((mapa[i][j] == 6 || mapa[i][j] == 7 || mapa[i][j] == 8) && (enemy1[i][j].direction == 1) && (enemy1[i][j].live == true))
                            {
                                al_draw_bitmap_region(img_enemy1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(mapa[i][j] == 9 && enemy1[i][j].live == true)
                            {
                                al_draw_bitmap_region(img_boss1, anim_enemy1.curFrame * anim_enemy1.frameWidth, 0, anim_enemy1.frameWidth, anim_enemy1.frameHeight, enemy1[i][j].x - cameraX, enemy1[i][j].y - cameraY, 0);
                            }
                        }
                    }

                    /* ~~Desenho do player~~ */

                    /* Player parado */
                    if(iddle == true)
                    {
                        if(++immobile.frameCount >= immobile.frameDelay)
                        {
                            if(++immobile.curFrame >= immobile.maxFrame)
                            {
                                immobile.curFrame = 0;
                                iddle = false;
                            }
                            immobile.frameCount = 0;
                        }
                    }
                    if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1) || player.x == 64))
                    {
                        al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                    }
                    if((keys[KEY_SPACE] == false) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1) || player.x == WORLD_W - (64-immobile.frameWidth)))
                    {
                        al_draw_bitmap_region(img_player_immobile, immobile.curFrame * immobile.frameWidth, 0, immobile.frameWidth, immobile.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                    }
                    if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_LEFT] && player.direction == -1)))
                    {
                        al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                    }
                    if((keys[KEY_SPACE] == true) && (jump == false) && ((!keys[KEY_RIGHT] && player.direction == 1)))
                    {
                        al_draw_bitmap(img_player_immobile_shoot, player.x - cameraX, player.y - cameraY, 0);
                    }

                    /* Player andando */
                    if(++walking.frameCount >= walking.frameDelay)
                    {
                        if(++walking.curFrame >= walking.maxFrame)
                        {
                            walking.curFrame = 0;
                        }
                        walking.frameCount = 0;
                    }

                    if(keys[KEY_SPACE] == false)
                    {
                        if(jump == false && keys[KEY_LEFT] && player.direction == -1)
                        {
                            al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                        }
                        if(jump == false && keys[KEY_RIGHT] && player.direction == 1)
                        {
                            al_draw_bitmap_region(img_player_walking, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                        }
                    }
                    if(keys[KEY_SPACE] == true)
                    {
                        if(jump == false && keys[KEY_LEFT] && player.direction == -1)
                        {
                            al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                        }
                        if(jump == false && keys[KEY_RIGHT] && player.direction == 1)
                        {
                            al_draw_bitmap_region(img_player_walking_shoot, walking.curFrame * walking.frameWidth, 0, walking.frameWidth, walking.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                        }
                    }

                    /* Player pulando */
                    if(jump == true)
                    {
                        if(++jumping.frameCount >= jumping.frameDelay)
                        {
                            if(++jumping.curFrame >= jumping.maxFrame)
                            {
                                jumping.curFrame = 0;
                            }
                            jumping.frameCount = 0;
                        }

                        if(keys[KEY_SPACE] == false)
                        {
                            if(player.direction == -1)
                            {
                                al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(player.direction == 1)
                            {
                                al_draw_bitmap_region(img_player_jump, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                            }
                        }
                        else if(keys[KEY_SPACE] == true)
                        {
                            if(player.direction == -1)
                            {
                                al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, ALLEGRO_FLIP_HORIZONTAL);
                            }
                            if(player.direction == 1)
                            {
                                al_draw_bitmap_region(img_player_jump_shoot, jumping.curFrame * jumping.frameWidth, 0, jumping.frameWidth, jumping.frameHeight, player.x - cameraX, player.y - cameraY, 0);
                            }
                        }

                    }

                    /* ~~Desenho dos projeteis~~ */
                    for(i=0; i<NUM_BULLET; i++)
                    {
                        if(playerBullet[i].live)
                        {
                            al_draw_bitmap(img_player_bullet, playerBullet[i].x - cameraX, playerBullet[i].y - cameraY, 0);
                        }
                        if(enemyBullet[i].live)
                        {
                            al_draw_bitmap(img_enemy_bullet, enemyBullet[i].x - cameraX, enemyBullet[i].y - cameraY, 0);
                        }
                    }

                    /* Pontuacao e Porcentagem de Vida */
                    al_draw_bitmap(img_heart, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 20, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), player.life);

                    al_draw_bitmap(img_medal, 64, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 80, 0, ALLEGRO_ALIGN_LEFT, ("%04d"), scores);

                    al_draw_bitmap(img_clock, 144, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 255, 255), 160, 0, ALLEGRO_ALIGN_LEFT, ("%03d"), stopwatch);
                }

                /* Termino da Fase */
                if(enemyKilled == ENEMY_MAX) /* You Win! */
                {
                    scores = scores + (25 * stopwatch) + (10*player.life);
                    gamestate = 2;
                }
                if(player.life <= 0 || stopwatch == 0) /* Game Over! */
                {
                    gamestate = 3;
                }

                /* Troca o display */
                al_flip_display();
            }
            break;
        case 2:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    al_draw_bitmap(img_you_win, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores);
                    al_draw_textf(fonte16, al_map_rgb(0, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair");
                    al_flip_display();
                }
            }
            break;

        case 3:
            al_wait_for_event(event_queue, &ev);

            if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE) /* Faz com que o jogo feche ao clicar no botao "X" do display */
            {
                quit = true;
            }

            if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                if(ev.keyboard.keycode == ALLEGRO_KEY_ESCAPE) /* Faz com que o jogo feche ao pressionar esc */
                {
                    quit = true;
                }
            }
            if(ev.type == ALLEGRO_EVENT_TIMER) /* Mostrar mensagens na tela */
            {
                if(ev.timer.source == timer_60)
                {
                    al_clear_to_color(al_map_rgb(0,0,0));
                    al_draw_bitmap(img_game_over, 0, 0, 0);
                    al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 48, ALLEGRO_ALIGN_CENTRE, "Seus pontos: %d", scores);
                    al_draw_textf(fonte16, al_map_rgb(255, 0, 0), SCREEN_W/2, SCREEN_H - 32, ALLEGRO_ALIGN_CENTRE, "Pressione Esc para sair");
                    al_flip_display();
                }
            }
            break;
        }
    }
    /* Destruindo as variaveis */
    al_destroy_display(display);
    al_destroy_event_queue(event_queue);
    al_destroy_timer(timer_0p2);
    al_destroy_timer(timer_1);
    al_destroy_timer(timer_60);

    al_destroy_bitmap(img_home_screen);
    al_destroy_bitmap(img_dica_h1n1);
    al_destroy_bitmap(img_background0);

    al_destroy_bitmap(img_heart);
    al_destroy_bitmap(img_medal);
    al_destroy_bitmap(img_clock);
    al_destroy_bitmap(img_block1);
    al_destroy_bitmap(img_block2);

    al_destroy_bitmap(img_player_walking);
    al_destroy_bitmap(img_player_walking_shoot);
    al_destroy_bitmap(img_player_immobile);
    al_destroy_bitmap(img_player_immobile_shoot);
    al_destroy_bitmap(img_player_jump);
    al_destroy_bitmap(img_player_jump_shoot);
    al_destroy_bitmap(img_player_bullet);

    al_destroy_bitmap(img_enemy1);
    al_destroy_bitmap(img_boss1);
    al_destroy_bitmap(img_enemy_bullet);

    al_destroy_sample(spl_theme);
    al_destroy_sample(spl_playerShoot);
    al_destroy_sample(spl_mlk);

    return 0;
}
예제 #12
0
int main(void)
{
   ALLEGRO_TRANSFORM trans;
   ALLEGRO_EVENT event;
   int bps = 4;
   bool redraw = false;
   unsigned int last_timer = 0;

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

   open_log();

   al_install_keyboard();

   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Could not create display\n");
   }

   font = al_create_builtin_font();
   if (!font) {
      abort_example("Could not create font\n");
   }

   if (!al_install_audio()) {
      abort_example("Could not init sound\n");
   }

   if (!al_reserve_samples(RESERVED_SAMPLES)) {
      abort_example("Could not set up voice and mixer\n");
   }

   ping = generate_ping();
   if (!ping) {
      abort_example("Could not generate sample\n");
   }

   timer = al_create_timer(1.0 / bps);
   al_set_timer_count(timer, -1);

   event_queue = al_create_event_queue();
   al_register_event_source(event_queue, al_get_keyboard_event_source());
   al_register_event_source(event_queue, al_get_timer_event_source(timer));

   al_identity_transform(&trans);
   al_scale_transform(&trans, 16.0, 16.0);
   al_use_transform(&trans);

   al_start_timer(timer);

   while (true) {
      al_wait_for_event(event_queue, &event);
      if (event.type == ALLEGRO_EVENT_TIMER) {
         const float speed = pow(21.0/20.0, (event.timer.count % PERIOD));
         if (!al_play_sample(ping, 1.0, 0.0, speed, ALLEGRO_PLAYMODE_ONCE, NULL)) {
            log_printf("Not enough reserved samples.\n");
         }
         redraw = true;
         last_timer = event.timer.count;
      }
      else if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
            break;
         }
         if (event.keyboard.unichar == '+' || event.keyboard.unichar == '=') {
            if (bps < 32) {
               bps++;
               al_set_timer_speed(timer, 1.0 / bps);
            }
         }
         else if (event.keyboard.unichar == '-') {
            if (bps > 1) {
               bps--;
               al_set_timer_speed(timer, 1.0 / bps);
            }
         }
      }

      if (redraw && al_is_event_queue_empty(event_queue)) {
         ALLEGRO_COLOR c;
         if (last_timer % PERIOD == 0)
            c = al_map_rgb_f(1, 1, 1);
         else
            c = al_map_rgb_f(0.5, 0.5, 1.0);

         al_clear_to_color(al_map_rgb(0, 0, 0));
         al_draw_textf(font, c, 640/32, 480/32 - 4, ALLEGRO_ALIGN_CENTRE,
            "%u", last_timer);
         al_flip_display();
      }
   }

   close_log(false);

   return 0;
}
예제 #13
0
파일: main.cpp 프로젝트: kruci/Juicy-Plebs
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;
}
예제 #14
0
파일: audio.c 프로젝트: Luiji/allua
/* Methods
 * */
static int allua_audio_install(lua_State * L)
{
   lua_pushboolean(L, al_install_audio());
   return 1;
}
예제 #15
0
void StateControl::Initialize()
{
	cout << endl;
	cout << "* * * * * * * * * * * * *" << endl;
	cout << "*                       *" << endl;
	cout << "*    STARTING RADIO     *" << endl;	
	cout << "*                       *" << endl;
	cout << "* * * * * * * * * * * * *" << endl;
	cout << endl;
	cout << "-------------" << endl;
	cout << "Activity Log:" << endl;
	cout << "-------------" << endl;

	cout << "Getting time seed for random numbers..." << endl;
	srand ((unsigned int) time(NULL));

	cout << "Starting Allegro 5..." << endl;
	if (!al_init())
	{
		al_show_native_message_box(NULL, NULL, "Could not initialize Allegro 5", NULL, NULL, NULL);
	}

	cout << "Initializing addons..." << endl;
	al_init_image_addon();
	al_init_primitives_addon();
	al_init_acodec_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	cout << "Installing devices..." << endl;
	al_install_mouse();
	al_install_keyboard();
	al_install_audio();

	cout << "Creating display..." << endl;
	CreateAllegroDisplay();	
	cout << "Loading fonts..." << endl;
	LoadFonts();

	cout << "Creating timers..." << endl;
	timer = al_create_timer(1.0 / FPS);

	cout << "Creating event queues..." << endl;
	event_queue = al_create_event_queue();

	cout << "Registring event sources..." << endl;
	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_register_event_source(event_queue, al_get_keyboard_event_source());	

	cout << "Initializing variables..." << endl;
	left_mouse_button_pressed = false;
	left_mouse_button_released = false;
	right_mouse_button_pressed = false;
	right_mouse_button_released = false;

	playing_music = false;

	possible_double_press = false;
	double_press_counter = 0;

	player_interface_y_coord = 380;
	music_time_counter = 0;

	cout << "Starting timers..." << endl;
	al_start_timer(timer);
}
예제 #16
0
int main(int argc, char *argv[])
{
   ALLEGRO_DISPLAY *display;
   ALLEGRO_FONT *font;
   ALLEGRO_AUDIO_RECORDER *recorder;
   ALLEGRO_EVENT_QUEUE *queue;
   ALLEGRO_TIMER *timer;
   int font_height;
   
   /* Frequency is the number of samples per second. */
   const int frequency = 44100;
   
   const int channels = 2;

   /* The latency is used to determine the size of the fragment buffer.
      More accurately, it represents approximately how many seconds will
      pass between fragment events. (There may be overhead latency from
      the OS or driver the adds a fixed amount of latency on top of 
      Allegro's.) 
      
      For this example, the latency should be kept relatively low since
      each fragment is processed in its entirety. Increasing the latency
      would increase the size of the fragment, which would decrease the
      accuracy of the code that processes the fragment.
      
      But if it's too low, then it will cut out too quickly. (If the
      example were more thoroughly written, the latency setting wouldn't
      actually change how the voice detection worked.)
    */
   const float latency = 0.10;

   const int max_seconds = 3; /* number of seconds of voice recording */
   
   int16_t *name_buffer;      /* stores up to max_seconds of audio */
   int16_t *name_buffer_pos;  /* points to the current recorded position */
   int16_t *name_buffer_end;  /* points to the end of the buffer */
   
   float gain = 0.0f;         /* 0.0 (quiet) - 1.0 (loud) */
   float begin_gain = 0.3f;   /* when to begin recording */
   
   bool is_recording = false;
   
   ALLEGRO_SAMPLE *spl = NULL;
   
   (void) argc;
   (void) argv;
   
   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   
   if (!al_install_audio()) {
      abort_example("Unable to initialize audio addon\n");
   }
   
   if (!al_init_acodec_addon()) {
      abort_example("Unable to initialize acoded addon\n");
   }
   
   if (!al_init_image_addon()) {
      abort_example("Unable to initialize image addon\n");
   }
   
   if (!al_init_primitives_addon()) {
      abort_example("Unable to initialize primitives addon\n");
   }
      
   al_init_font_addon();
   al_install_keyboard();
   
   font = al_load_bitmap_font("data/bmpfont.tga");
   if (!font) {
      abort_example("Unable to load data/a4_font.tga\n");
   }
   
   font_height = al_get_font_line_height(font);
   
   /* WARNING: This demo assumes an audio depth of INT16 and two channels.
      Changing those values will break the demo. Nothing here really needs to be
      changed. If you want to fiddle with things, adjust the constants at the
      beginning of the program.
    */
   
   recorder = al_create_audio_recorder(
      5 / latency,                 /* five seconds of buffer space */
      frequency * latency,         /* configure the fragment size to give us the given
                                        latency in seconds */
      frequency,                   /* samples per second (higher => better quality) */
      ALLEGRO_AUDIO_DEPTH_INT16,   /* 2-byte sample size */
      ALLEGRO_CHANNEL_CONF_2       /* stereo */
   );
   
   if (!recorder) {
      abort_example("Unable to create audio recorder\n");
   }
   
   display = al_create_display(640, 480);
   if (!display) {
      abort_example("Unable to create display\n");
   }
   
   /* Used to play back the voice recording. */
   al_reserve_samples(1);
   
   /* store up to three seconds */
   name_buffer = al_calloc(channels * frequency * max_seconds, sizeof(int16_t));
   name_buffer_pos = name_buffer;
   name_buffer_end = name_buffer + channels * frequency * max_seconds;
   
   queue = al_create_event_queue();
   timer = al_create_timer(1 / 60.0);
   
   al_register_event_source(queue, al_get_display_event_source(display));
   al_register_event_source(queue, al_get_audio_recorder_event_source(recorder));
   al_register_event_source(queue, al_get_timer_event_source(timer));
   al_register_event_source(queue, al_get_keyboard_event_source());
   
   al_start_timer(timer);
   al_start_audio_recorder(recorder);
   
   while (true) {
      ALLEGRO_EVENT event;
      bool do_draw = false;
      
      al_wait_for_event(queue, &event);
      
      if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE || 
         (event.type == ALLEGRO_EVENT_KEY_UP && event.keyboard.keycode == ALLEGRO_KEY_ESCAPE)) {
         break;
      }
      else if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
         if (spl && event.keyboard.unichar != 27) {
            al_play_sample(spl, 1.0, 0.0, 1.0, ALLEGRO_PLAYMODE_ONCE, NULL);
         }
      }
      else if (event.type == ALLEGRO_EVENT_TIMER) {
         do_draw = true;
      }
      else if (event.type == ALLEGRO_EVENT_AUDIO_RECORDER_FRAGMENT && recorder != NULL) {
         /* Because the recording happens in a different thread (and simply because we are
            queuing up events), it's quite possible to receive (process) a fragment event
            after the recorder has been stopped or destroyed. Thus, it is important to
            somehow check that the recorder is still valid, as we are doing above.
          */
         ALLEGRO_AUDIO_RECORDER_EVENT *re = al_get_audio_recorder_event(&event);
         int16_t *buffer = re->buffer;
         int16_t low = 0, high = 0;
         unsigned int i;
         
         /* Calculate the volume by comparing the highest and lowest points. This entire
            section assumes we are using fairly small fragment size (low latency). If a 
            large fragment size were used, then we'd have to inspect smaller portions 
            of it at a time to more accurately deterine when recording started and
            stopped. */
         for (i = 0; i < channels * re->samples; ++i) {
            if (buffer[i] < low)
               low = buffer[i];
            else if (buffer[i] > high)
               high = buffer[i];
         }
         
         gain = gain * 0.25 + ((float) (high - low) / 0xffff) * 0.75;
         
         /* Set arbitrary thresholds for beginning and stopping recording. This probably
            should be calibrated by determining how loud the ambient noise is.
          */
         if (!is_recording && gain >= begin_gain && name_buffer_pos == name_buffer)
            is_recording = true;
         else if (is_recording && gain <= 0.10)
            is_recording = false;
         
         if (is_recording) {
            /* Copy out of the fragment buffer into our own buffer that holds the
               name. */
            int samples_to_copy = channels * re->samples;
            
            /* Don't overfill up our name buffer... */
            if (samples_to_copy > name_buffer_end - name_buffer_pos)
               samples_to_copy = name_buffer_end - name_buffer_pos;
            
            if (samples_to_copy) {
               /* must multiply by two, since we are using 16-bit samples */
               memcpy(name_buffer_pos, re->buffer, samples_to_copy * 2);
            }
            
            name_buffer_pos += samples_to_copy;
            if (name_buffer_pos >= name_buffer_end) {
               is_recording = false;
            }
         }
         
         if (!is_recording && name_buffer_pos != name_buffer && !spl) {
            /* finished recording, but haven't created the sample yet */
            spl = al_create_sample(name_buffer, name_buffer_pos - name_buffer, frequency, 
               ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2, false);
            
            /* We no longer need the recorder. Destroying it is the only way to unlock the device. */
            al_destroy_audio_recorder(recorder);
            recorder = NULL;
         }
      }
      
      if (do_draw) {
         al_clear_to_color(al_map_rgb(0,0,0));
         if (!spl) {
            const char *msg = "Say Your Name";
            int width = al_get_text_width(font, msg);
            
            al_draw_text(font, al_map_rgb(255,255,255),
               320, 240 - font_height / 2, ALLEGRO_ALIGN_CENTRE, msg
            );
            
            /* draw volume meter */
            al_draw_filled_rectangle(320 - width / 2, 242 + font_height / 2,
               (320 - width / 2) + (gain * width), 242 + font_height, 
               al_map_rgb(0,255,0)
            );
            
            /* draw target line that triggers recording */
            al_draw_line((320 - width / 2) + (begin_gain * width), 242 + font_height / 2,
               (320 - width / 2) + (begin_gain * width), 242 + font_height,
               al_map_rgb(255,255,0), 1.0
            );
         }
         else {
            al_draw_text(font, al_map_rgb(255,255,255), 320, 240 - font_height / 2,
               ALLEGRO_ALIGN_CENTRE, "Press Any Key");
         }
         al_flip_display();
      }
   }
   
   if (recorder) {
      al_destroy_audio_recorder(recorder);
   }
   
   al_free(name_buffer);
   
   return 0;
}
예제 #17
0
bool GameLogic::InitializeAllegro() {
	if(!al_init()) {
        fprintf(stderr, "Failed to initialize allegro!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Allegro 5 initialized.\n"); }

	if(!al_install_keyboard()) {
      fprintf(stderr, "Failed to initialize the keyboard!\n");
      return false;
    }
    if(Debug) { fprintf(stderr, "Keyboard initialized.\n"); }

    if(!al_install_mouse()) {
        fprintf(stderr, "Failed to initialize the mouse!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Mouse initialized.\n"); }

    Timer = al_create_timer(TimerStep);
    if(!Timer) {
        fprintf(stderr, "Failed to create Timer!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Timer initialized.\n"); }

    if(!al_init_image_addon()) {
        fprintf(stderr, "Failed to initialize images loading!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Image loading initialized.\n"); }

	if(!al_init_primitives_addon()) {
        fprintf(stderr, "Failed to initialize primitives!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Primitives addon initialized.\n"); }

    al_init_font_addon();
	
    if(!al_init_ttf_addon()) {
        fprintf(stderr, "Failed to initialize TrueType!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "TTF font loading initialized.\n"); }
    
    if(!al_install_audio()) {
        fprintf(stderr, "Failed to initialize audio!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Audio initialized.\n"); }

    if(!al_init_acodec_addon()) {
        fprintf(stderr, "Failed to initialize audio codecs!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Ogg/FLAC initialized.\n"); }

    // create and confirm allegro Display
    Display = al_create_display(DisplayWidth, DisplayHeight);
    if(!Display) {
        fprintf(stderr, "Failed to create Display!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Display initialized.\n"); }

    // Make sure we are on the backbuffer
    al_set_target_bitmap(al_get_backbuffer(Display));
    
    Voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2);
    if (!Voice) {
        fprintf(stderr, "Could not create ALLEGRO_VOICE.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Voice created.\n"); }

    Mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,ALLEGRO_CHANNEL_CONF_2);
    if (!Mixer) {
        fprintf(stderr, "Could not create ALLEGRO_MIXER.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Mixer created.\n"); }

    if (!al_attach_mixer_to_voice(Mixer, Voice)) {
        fprintf(stderr, "Attaching Mixer to Voice failed.\n");
        return 1;
    }
    if(Debug) { fprintf(stderr, "Mixer attached to Voice.\n"); }
    
    // create and confirm event queue
    EventQueue = al_create_event_queue();
    if(!EventQueue) {
        fprintf(stderr, "Failed to create EventQueue!\n");
        return false;
    }
    if(Debug) { fprintf(stderr, "Event queue created successfully.\n"); }

    al_register_event_source(EventQueue, al_get_display_event_source(Display));
    al_register_event_source(EventQueue, al_get_timer_event_source(Timer));
    al_register_event_source(EventQueue, al_get_mouse_event_source());
    al_register_event_source(EventQueue, al_get_keyboard_event_source());

    // blank the Display
    al_clear_to_color(al_map_rgb(0,0,0));
    al_flip_display();

	// actually start our Timer
    al_start_timer(Timer);

	return true;
}
예제 #18
0
파일: x_init.c 프로젝트: Abstrusle/LCTourn
void init_sound(int camstate_rand_seed)
{

 settings.sound_on = 1;

//    al_init_acodec_addon(); - shouldn't need this


 if (!al_install_audio()
  || !al_init_acodec_addon())
 {
  fprintf(stdout, "\nAllegro audio installation failed. Starting without sound.");
  settings.sound_on = 0;
  return;
 }


 if (!al_reserve_samples(24))
 {
  fprintf(stdout, "\nCould not set up Allegro audio voice/mixer. Starting without sound.");
  settings.sound_on = 0;
  return;
 }

 if (settings.option [OPTION_VOL_MUSIC] == 0
		&& settings.option [OPTION_VOL_EFFECT] == 0)
	{
  settings.sound_on = 0;
  return;
	}


 load_in_sample(SAMPLE_BLIP1, "data/sound/blip.wav");
 load_in_sample(SAMPLE_BLIP2, "data/sound/blip2.wav");
 load_in_sample(SAMPLE_BLIP3, "data/sound/blip3.wav");
 load_in_sample(SAMPLE_BLIP4, "data/sound/blip4.wav");
 load_in_sample(SAMPLE_KILL, "data/sound/kill.wav");
 load_in_sample(SAMPLE_CHIRP, "data/sound/chirp.wav");
 load_in_sample(SAMPLE_OVER, "data/sound/over.wav");
 load_in_sample(SAMPLE_ALLOC, "data/sound/alloc.wav");
 load_in_sample(SAMPLE_NEW, "data/sound/new.wav");

 load_in_sample(SAMPLE_BANG, "data/sound/bang.wav");
 load_in_sample(SAMPLE_BANG2, "data/sound/bang2.wav");
 load_in_sample(SAMPLE_INT_UP, "data/sound/int_up.wav");
 load_in_sample(SAMPLE_INT_BREAK, "data/sound/int_break.wav");
 load_in_sample(SAMPLE_RESTORE, "data/sound/restore.wav");
 load_in_sample(SAMPLE_STREAM1, "data/sound/stream1.wav");
 load_in_sample(SAMPLE_STREAM2, "data/sound/stream2.wav");
 load_in_sample(SAMPLE_ZAP, "data/sound/zap.wav");
 load_in_sample(SAMPLE_SPIKE, "data/sound/spike.wav");
 load_in_sample(SAMPLE_SLICE, "data/sound/slice.wav");
 load_in_sample(SAMPLE_ULTRA, "data/sound/ultra.wav");
 load_in_sample(SAMPLE_BUBBLE, "data/sound/bubble.wav");

 load_in_sample(SAMPLE_DRUM1, "data/sound/music/drum1.wav");
 load_in_sample(SAMPLE_DRUM2, "data/sound/music/drum2.wav");
 load_in_sample(SAMPLE_DRUM3, "data/sound/music/drum3.wav");
 load_in_sample(SAMPLE_CLICK, "data/sound/music/click.wav");
 load_in_sample(SAMPLE_THUMP, "data/sound/music/thump.wav");

// load_in_msample(MSAMPLE_NOTE, "data/sound/amb/note.wav");
// load_in_msample(MSAMPLE_NOTE2, "data/sound/amb/note_harm.wav");
// load_in_msample(MSAMPLE_NOTE3, "data/sound/amb/note_sine.wav");
// load_in_msample(MSAMPLE_NOTE4, "data/sound/amb/note_sq.wav");

// load_in_amb_sample(AMB_WARBLE, "sound/amb/warble.wav");
// load_in_amb_sample(AMB_NOTE, "sound/amb/note.wav");



 //al_stop_samples();

 build_tone_array();

 sound_config.music_volume = settings.option [OPTION_VOL_MUSIC] * 0.01;
 sound_config.effect_volume = settings.option [OPTION_VOL_EFFECT] * 0.01;

 sound_timer = al_create_timer(0.22); // 0.20
 if (!sound_timer)
 {
    fprintf(stdout, "\nError: failed to create sound timer.");
    safe_exit(-1);
 }
 al_start_timer(sound_timer);
 al_init_user_event_source(&sound_event_source);

 sound_queue = al_create_event_queue();
 al_register_event_source(sound_queue, &sound_event_source);
 al_register_event_source(sound_queue, al_get_timer_event_source(sound_timer));

 sound_event.user.type = ALLEGRO_GET_EVENT_TYPE(1, 0, 4, 0);

 sthread_init_sample_pointers();

 if (settings.option [OPTION_VOL_MUSIC] != 0)
  init_camstate(-1, 1, 0, camstate_rand_seed); // this is usually only called from within the sound thread
   // but can be called here because the sound thread hasn't been started yet.
   // -1 means start new music
    else
     init_camstate(-2, 0, 0, 0); // -2 means turn the music off


 sound_thread = al_create_thread(thread_check_sound_queue, NULL);
 al_start_thread(sound_thread);

 started_sound_thread = 1;

}
예제 #19
0
파일: Main.cpp 프로젝트: kckrepo/kck-repo
int main(int argc, char **argv)
{
	bool done = false;
	bool render = false;

	float gameTime = 0;
	int frames = 0;
	int gameFPS = 0;

	float evTimer = 0;

	tractor = new Tractor();
	Xml = new xml();

	int state = -1;

	ALLEGRO_BITMAP *icon;
	ALLEGRO_BITMAP *map = NULL;
	ALLEGRO_BITMAP *panel = NULL;
	ALLEGRO_BITMAP *tractorImage = NULL;
	ALLEGRO_BITMAP *titleImage = NULL;
	ALLEGRO_BITMAP *lostImage = NULL;
	ALLEGRO_SAMPLE *titleSong = NULL;
	ALLEGRO_SAMPLE *gameSong = NULL;
	ALLEGRO_SAMPLE *lostSong = NULL;
	ALLEGRO_SAMPLE *cash = NULL;

	ALLEGRO_BITMAP *L1 = NULL;
	ALLEGRO_BITMAP *L2 = NULL;
	ALLEGRO_BITMAP *L3 = NULL;
	ALLEGRO_BITMAP *L4 = NULL;
	ALLEGRO_BITMAP *L5 = NULL;
	ALLEGRO_BITMAP *L6 = NULL;
	ALLEGRO_BITMAP *L7 = NULL;

	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_DISPLAY_MODE   disp_data;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer;
	ALLEGRO_FONT *font;
	ALLEGRO_FONT *score;

	if (!al_init())
		return -1;

	al_install_keyboard();
	al_install_mouse();
	al_init_image_addon();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_primitives_addon();
	al_install_audio();
	al_init_acodec_addon();

	al_get_display_mode(al_get_num_display_modes() - 1, &disp_data);

	//al_set_new_display_flags(ALLEGRO_FULLSCREEN);
	al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_REQUIRE);

	display = al_create_display(disp_data.width, disp_data.height);

	icon = al_load_bitmap("icon.png");
	al_set_display_icon(display, icon);

	float sx = (float)disp_data.width / WIDTH;
	float sy = (float)disp_data.height / HEIGHT;

	ALLEGRO_TRANSFORM trans;
	al_identity_transform(&trans);
	al_scale_transform(&trans, sx, sy);
	al_use_transform(&trans);

	if (!display)
		return -1;

	font = al_load_font("arial.ttf", 20, 0);
	score = al_load_font("score.ttf", 45, 0);
	al_reserve_samples(15);

	map = al_load_bitmap("map2.png");
	panel = al_load_bitmap("panel.png");

	L1 = al_load_bitmap("l1.png");
	L2 = al_load_bitmap("l2.png");
	L3 = al_load_bitmap("l3.png");
	L4 = al_load_bitmap("l4.png");
	L5 = al_load_bitmap("l5.png");
	L6 = al_load_bitmap("l6.png");
	L7 = al_load_bitmap("l7.png");

	Background *Map = new Background(map);
	objects.push_back(Map);

	TextBox *Task = new TextBox;

	Field *field1 = new Field(L1, L2, L3, L4, L5, L6, L7, 50, 50);
	objects.push_back(field1);
	Field *field2 = new Field(L1, L2, L3, L4, L5, L6, L7, 450, 50);
	objects.push_back(field2);
	Field *field3 = new Field(L1, L2, L3, L4, L5, L6, L7, 50, 450);
	objects.push_back(field3);
	Field *field4 = new Field(L1, L2, L3, L4, L5, L6, L7, 450, 450);
	objects.push_back(field4);

	tractorImage = al_load_bitmap("tractor.png");
	cash = al_load_sample("cash.ogg");
	tractor->Init(tractorImage, cash);
	objects.push_back(tractor);

	titleImage = al_load_bitmap("screen_Title.png");
	lostImage = al_load_bitmap("screen_Lost.png");

	titleScreen = new Background(titleImage);
	lostScreen = new Background(lostImage);

	titleSong = al_load_sample("title.ogg");
	gameSong = al_load_sample("game.ogg");
	lostSong = al_load_sample("lost.ogg");

	songInstance = al_create_sample_instance(titleSong);
	al_set_sample_instance_playmode(songInstance, ALLEGRO_PLAYMODE_LOOP);

	songInstance2 = al_create_sample_instance(gameSong);
	al_set_sample_instance_playmode(songInstance2, ALLEGRO_PLAYMODE_LOOP);

	songInstance3 = al_create_sample_instance(lostSong);
	al_set_sample_instance_playmode(songInstance3, ALLEGRO_PLAYMODE_LOOP);

	al_attach_sample_instance_to_mixer(songInstance, al_get_default_mixer());
	al_attach_sample_instance_to_mixer(songInstance2, al_get_default_mixer());
	al_attach_sample_instance_to_mixer(songInstance3, al_get_default_mixer());

	ChangeState(state, TITLE);

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

	al_register_event_source(event_queue, al_get_timer_event_source(timer));
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_mouse_event_source());

	al_start_timer(timer);
	gameTime = al_current_time();

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

		if (ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_ENTER:
				keys[ENTER] = true;
				if (state == TITLE)
					ChangeState(state, PLAYING);
				else if (state == PLAYING && Task->CheckText())
				{
					TextBox *text = new TextBox();
					text->SetText(Task->Send());
					history.push_back(text);

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 400)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}

					Xml->interpreter(Task->GetLast(), tractor);

					TextBox *txtxml = new TextBox();
					txtxml->SetText(Xml->wyslij());
					history.push_back(txtxml);

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 300)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}
				}
				else if (state == LOST)
					ChangeState(state, PLAYING);
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = true;
				if (state == PLAYING)
				{

					Task->SetStatus();
					if (Task->GetStatus())
					{
						TextBox *text = new TextBox();
						text->SetText("Konsola zostala wlaczona");
						history.push_back(text);
					}
					else
					{
						TextBox *text = new TextBox();
						text->SetText("Konsola zostala wylaczona");
						history.push_back(text);
					}

					for (iter2 = history.begin(); iter2 != history.end(); iter2++)
					{
						if ((*iter2)->GetY() < 300)
						{
							delete (*iter2);
							iter2 = history.erase(iter2);
						}
						(*iter2)->UpdateY();
					}

					setTimer(evTimer);
				}
				tractor->Sell();
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPC] = true;
				if (state == PLAYING)
					Task->Add(" ");
				break;
			case ALLEGRO_KEY_BACKSPACE:
				if (state == PLAYING && Task->CheckText())
					Task->Backspace();
				break;
			case ALLEGRO_KEY_COMMA:
				keys[COM] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add(",");
				break;
			case ALLEGRO_KEY_0:
				numb[N0] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("0");
				break;
			case ALLEGRO_KEY_1:
				numb[N1] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("1");
				break;
			case ALLEGRO_KEY_2:
				numb[N2] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("2");
				break;
			case ALLEGRO_KEY_3:
				numb[N3] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("3");
				break;
			case ALLEGRO_KEY_4:
				numb[N4] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("4");
				break;
			case ALLEGRO_KEY_5:
				numb[N5] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("5");
				break;
			case ALLEGRO_KEY_6:
				numb[N6] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("6");
				break;
			case ALLEGRO_KEY_7:
				numb[N7] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("7");
				break;
			case ALLEGRO_KEY_8:
				numb[N8] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("8");
				break;
			case ALLEGRO_KEY_9:
				numb[N9] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("9");
				break;
			case ALLEGRO_KEY_A:
				letters[A] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("a");
				break;
			case ALLEGRO_KEY_B:
				letters[B] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("b");
				break;
			case ALLEGRO_KEY_C:
				letters[C] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("c");
				break;
			case ALLEGRO_KEY_D:
				letters[D] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("d");
				break;
			case ALLEGRO_KEY_E:
				letters[E] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("e");
				break;
			case ALLEGRO_KEY_F:
				letters[F] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("f");
				break;
			case ALLEGRO_KEY_G:
				letters[G] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("g");
				break;
			case ALLEGRO_KEY_H:
				letters[H] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("h");
				break;
			case ALLEGRO_KEY_I:
				letters[I] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("i");
				break;
			case ALLEGRO_KEY_J:
				letters[J] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("j");
				break;
			case ALLEGRO_KEY_K:
				letters[K] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("k");
				break;
			case ALLEGRO_KEY_L:
				letters[L] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("l");
				break;
			case ALLEGRO_KEY_M:
				letters[M] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("m");
				break;
			case ALLEGRO_KEY_N:
				letters[N] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("n");
				break;
			case ALLEGRO_KEY_O:
				letters[O] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("o");
				break;
			case ALLEGRO_KEY_P:
				letters[P] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("p");
				break;
			case ALLEGRO_KEY_Q:
				letters[Q] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("q");
				break;
			case ALLEGRO_KEY_R:
				letters[R] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("r");
				break;
			case ALLEGRO_KEY_S:
				letters[S] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("s");
				break;
			case ALLEGRO_KEY_T:
				letters[T] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("t");
				break;
			case ALLEGRO_KEY_U:
				letters[U] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("u");
				break;
			case ALLEGRO_KEY_V:
				letters[V] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("v");
				break;
			case ALLEGRO_KEY_W:
				letters[W] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("w");
				break;
			case ALLEGRO_KEY_X:
				letters[X] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("x");
				break;
			case ALLEGRO_KEY_Y:
				letters[Y] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("y");
				break;
			case ALLEGRO_KEY_Z:
				letters[Z] = true;
				if (state == PLAYING && Task->GetStatus())
					Task->Add("z");
				break;
			}
		}
		else if (ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch (ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_ENTER:
				keys[ENTER] = false;
				break;
			case ALLEGRO_KEY_TAB:
				keys[TAB] = false;
				break;
			case ALLEGRO_KEY_BACKSPACE:
				keys[BSPC] = false;
				break;
			case ALLEGRO_KEY_COMMA:
				keys[COM] = false;
				break;
			case ALLEGRO_KEY_0:
				numb[N0] = false;
				break;
			case ALLEGRO_KEY_1:
				numb[N1] = false;
				break;
			case ALLEGRO_KEY_2:
				numb[N2] = false;
				break;
			case ALLEGRO_KEY_3:
				numb[N3] = false;
				break;
			case ALLEGRO_KEY_4:
				numb[N4] = false;
				break;
			case ALLEGRO_KEY_5:
				numb[N5] = false;
				break;
			case ALLEGRO_KEY_6:
				numb[N6] = false;
				break;
			case ALLEGRO_KEY_7:
				numb[N7] = false;
				break;
			case ALLEGRO_KEY_8:
				numb[N8] = false;
				break;
			case ALLEGRO_KEY_9:
				numb[N9] = false;
				break;
			case ALLEGRO_KEY_A:
				letters[A] = false;
				break;
			case ALLEGRO_KEY_B:
				letters[B] = false;
				break;
			case ALLEGRO_KEY_C:
				letters[C] = false;
				break;
			case ALLEGRO_KEY_D:
				letters[D] = false;
				break;
			case ALLEGRO_KEY_E:
				letters[E] = false;
				break;
			case ALLEGRO_KEY_F:
				letters[F] = false;
				break;
			case ALLEGRO_KEY_G:
				letters[G] = false;
				break;
			case ALLEGRO_KEY_H:
				letters[H] = false;
				break;
			case ALLEGRO_KEY_I:
				letters[I] = false;
				break;
			case ALLEGRO_KEY_J:
				letters[J] = false;
				break;
			case ALLEGRO_KEY_K:
				letters[K] = false;
				break;
			case ALLEGRO_KEY_L:
				letters[L] = false;
				break;
			case ALLEGRO_KEY_M:
				letters[M] = false;
				break;
			case ALLEGRO_KEY_N:
				letters[N] = false;
				break;
			case ALLEGRO_KEY_O:
				letters[O] = false;
				break;
			case ALLEGRO_KEY_P:
				letters[P] = false;
				break;
			case ALLEGRO_KEY_Q:
				letters[Q] = false;
				break;
			case ALLEGRO_KEY_R:
				letters[R] = false;
				break;
			case ALLEGRO_KEY_S:
				letters[S] = false;
				break;
			case ALLEGRO_KEY_T:
				letters[T] = false;
				break;
			case ALLEGRO_KEY_U:
				letters[U] = false;
				break;
			case ALLEGRO_KEY_V:
				letters[V] = false;
				break;
			case ALLEGRO_KEY_W:
				letters[W] = false;
				break;
			case ALLEGRO_KEY_X:
				letters[X] = false;
				break;
			case ALLEGRO_KEY_Y:
				letters[Y] = false;
				break;
			case ALLEGRO_KEY_Z:
				letters[Z] = false;
				break;
			}
		}

		else if (ev.type == ALLEGRO_EVENT_TIMER)
		{
			render = true;

			frames++;

			if (al_current_time() - gameTime >= 1)
			{
				gameTime = al_current_time();
				gameFPS = frames;
				frames = 0;
			}

			if (state == PLAYING)
			{
				if (keys[UP])
				{
					if (Map->GetY() + Map->frameHeight > disp_data.height)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetY((*iter)->GetY() - 10);
						}
						tractor->SetDistY((tractor->GetDistY() - 10));
					}
				}
				else if (keys[DOWN])
				{
					if (Map->GetY() < 0)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetY((*iter)->GetY() + 10);
						}
						tractor->SetDistY(tractor->GetDistY() + 10);
					}
				}

				if (keys[LEFT])
				{
					if (Map->GetWidth() > (disp_data.width - al_get_bitmap_width(panel)))
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetX((*iter)->GetX() - 10);
						}
						tractor->SetDistX(tractor->GetDistX() - 10);
					}
				}
				else if (keys[RIGHT])
				{
					if (Map->GetX() < 0)
					{
						for (iter = objects.begin(); iter != objects.end(); ++iter)
						{
							(*iter)->SetX((*iter)->GetX() + 10);
						}
						tractor->SetDistX(tractor->GetDistX() + 10);
					}
				}

				for (iter = objects.begin(); iter != objects.end(); ++iter)
					(*iter)->Update();

				if (tractor->GetStatus())
					tractor->Move();

				field1->Change_Field();
				field1->Grow_Field();
				field2->Change_Field();
				field2->Grow_Field();
				field3->Change_Field();
				field3->Grow_Field();
				field4->Change_Field();
				field4->Grow_Field();
				field1->Action_On_Field(tractor);
				field2->Action_On_Field(tractor);
				field3->Action_On_Field(tractor);
				field4->Action_On_Field(tractor);

				if (!tractor->Get_Iminwork()){
					Xml->ZKolejki(field1, field2, field3, field4, tractor);
					if (Xml->wyslij() != ""){
						TextBox *txtxml = new TextBox();
						txtxml->SetText(Xml->wyslij());
						history.push_back(txtxml);

						for (iter2 = history.begin(); iter2 != history.end(); iter2++)
						{
							if ((*iter2)->GetY() < 300)
							{
								delete (*iter2);
								iter2 = history.erase(iter2);
							}

							(*iter2)->UpdateY();
						}
					}
				}
				if (evTimer < 60)
				{
					evTimer += 0.1;
				}
				else
				{
					if (tractor->GetPodpowiedz() == 0)
					{
						Xml->podpowiedz(field1, field2, field3, field4, tractor);
						evTimer = 0;

						TextBox *txtxml = new TextBox();
						txtxml->SetText(Xml->wyslij());
						history.push_back(txtxml);

						for (iter2 = history.begin(); iter2 != history.end(); iter2++)
						{
							if ((*iter2)->GetY() < 300)
							{
								delete (*iter2);
								iter2 = history.erase(iter2);
							}

							(*iter2)->UpdateY();
						}
					}
					
				}
			}

			if (tractor->GetMoney() <= 0)
				ChangeState(state, LOST);
		}

		for (iter = objects.begin(); iter != objects.end();)
		{
			if (!(*iter)->GetAlive())
			{
				delete (*iter);
				iter = objects.erase(iter);
			}
			else
				iter++;
		}

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

			if (state == TITLE)
			{
				titleScreen->Render();
			}
			else if (state == PLAYING)
			{
				for (iter = objects.begin(); iter != objects.end(); ++iter)
					(*iter)->Render();

				al_draw_bitmap(panel, WIDTH - al_get_bitmap_width(panel), 0, 0);
				al_draw_textf(font, al_map_rgb(255, 255, 255), Task->GetX(), Task->GetY(), 0, Task->ShowText());

				for (iter2 = history.begin(); iter2 != history.end(); iter2++)
				{
					al_draw_textf(font, al_map_rgb(255, 255, 255), (*iter2)->GetX(), (*iter2)->GetY(), 0, (*iter2)->ShowText());
				}

				if (tractor->GetHealth() < 20)
					al_draw_textf(score, RED, WIDTH - 430, 15, 0, "%i", tractor->GetHealth());
				else
					al_draw_textf(score, BLACK, WIDTH - 430, 15, 0, "%i", tractor->GetHealth());
				
				if (tractor->GetFuel() < 20)
					al_draw_textf(score, RED, WIDTH - 260, 15, 0, "%i", tractor->GetFuel());
				else
					al_draw_textf(score, BLACK, WIDTH - 260, 15, 0, "%i", tractor->GetFuel());
				
				if (tractor->GetMoney() < 200)
					al_draw_textf(score, RED, WIDTH - 400, 100, 0, "%i", tractor->GetMoney());
				else
					al_draw_textf(score, BLACK, WIDTH - 400, 100, 0, "%i", tractor->GetMoney());

				al_draw_textf(score, BLACK, WIDTH - 70, 15, 0, "%i", tractor->GetWater());

				for (int j = 0; j < 5; j++)
				{
					al_draw_textf(font, BLACK, WIDTH - 170, 85 + j * 20, 0, "%i", tractor->GetSupply(0, j));
				}

				for (int j = 0; j < 5; j++)
				{
					al_draw_textf(font, BLACK, WIDTH - 150, 85 + j * 20, 0, "%i", tractor->GetSupply(1, j));
				}

				al_draw_textf(font, al_map_rgb(255, 0, 255), 5, 5, 0, "FPS: %i", WIDTH - al_get_bitmap_width(panel) /*gameFPS*/);
			}
			else if (state == LOST)
				lostScreen->Render();

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

	for (iter = objects.begin(); iter != objects.end();)
	{
		(*iter)->Destroy();
		delete (*iter);
		iter = objects.erase(iter);
	}

	for (iter2 = history.begin(); iter2 != history.end();)
	{
		(*iter2)->Destroy();
		delete (*iter2);
		iter2 = history.erase(iter2);
	}

	//tractor->Destroy();
	Task->Destroy();
	titleScreen->Destroy();
	lostScreen->Destroy();
	delete titleScreen;
	delete lostScreen;
	al_destroy_sample(cash);
	al_destroy_sample_instance(songInstance);
	al_destroy_sample_instance(songInstance2);
	al_destroy_sample_instance(songInstance3);

	al_destroy_font(score);
	al_destroy_font(font);
	al_destroy_timer(timer);
	al_destroy_event_queue(event_queue);
	al_destroy_display(display);
			
	return 0;
}
예제 #20
0
int main(int argc, 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;

   if (!al_init()) {
      abort_example("Could not init Allegro.\n");
   }
   
   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);
   if (!d) {
      abort_example("Error creating display\n");
   }
      
   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;
}
예제 #21
0
파일: engine.c 프로젝트: eliasYFGM/Luna2
int engine_init(struct Engine_Conf *conf)
{
  if (engine.initialized)
    {
      return 1;
    }

  // Initialize Allegro and stuff
  al_init();

  if (!al_install_keyboard())
    {
      puts("engine_init(): Failed to initialize the keyboard...");
      return 0;
    }

  if (!al_install_mouse())
    {
      puts("engine_init(): Failed to initialize the mouse...");
      return 0;
    }

  if (al_install_audio())
    {
      if (!al_init_acodec_addon())
        {
          puts("engine_init(): Failed to initialize codecs...");
        }

      al_reserve_samples(1);
    }
  else
    {
      puts("engine_init(): Failed to initialize audio...");
    }

  // Add-ons
  if (!al_init_image_addon())
    {
      puts("engine_init(): Failed to initialize image addon...");
      return 0;
    }

  al_init_font_addon();
  al_init_primitives_addon();

  if (conf->fullscreen)
    {
      al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);
    }

  // Initialize variables...
  engine.display = al_create_display(conf->width, conf->height);

  if (!engine.display)
    {
      puts("engine_init(): Failed to create a display window...");
      return 0;
    }

  al_set_window_title(engine.display, conf->title);

  MAINCONF = conf;
  aspect_ratio_transform();

  al_add_new_bitmap_flag(ALLEGRO_MAG_LINEAR);

  if (conf->buffer)
    {
      engine.buffer = al_create_bitmap(conf->width, conf->height);
      al_set_new_bitmap_flags(0);
    }

  font = al_create_builtin_font();

  engine.timer = al_create_timer(1.0 / conf->framerate);
  engine.event_queue = al_create_event_queue();

  engine.sm.change_state = change_state;
  engine.sm.push_state = push_state;
  engine.sm.pop_state = pop_state;

  set_bg_color(al_map_rgb(192, 192, 192));

  srand(time(NULL));

  engine.initialized = TRUE;

  return 1;
}
예제 #22
0
int main()
{
    ALLEGRO_DISPLAY *Screen = NULL;
    ALLEGRO_EVENT_QUEUE *EventQueue = NULL;
    ALLEGRO_EVENT Event;
    ALLEGRO_BITMAP *Background = NULL, *KeyDownImage = NULL;
    ALLEGRO_BITMAP *Image = NULL;
    ALLEGRO_SAMPLE *sample=NULL;
    bool Exit = false, KeyDown = false;

    if(!al_init())
    {
        al_show_native_message_box(NULL, "Error!", "Allegro has failed to initialize.", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    if(!al_init_image_addon())
    {
        al_show_native_message_box(NULL, "Error!", "Image addon has failed to initialize.", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

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

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

    if (!al_reserve_samples(1)){
        fprintf(stderr, "failed to reserve samples!\n");
        return -1;
    }

    sample = al_load_sample( "music.ogg" );

    if (!sample){
        printf( "Audio clip sample not loaded!\n" );
        return -1;
    }

    Screen = al_create_display(512, 512);
        if(Screen == NULL)
        {
            al_show_native_message_box(Screen, "Error!", "Failed to create the display.", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
            return -1;
        }

    EventQueue = al_create_event_queue();
        if(EventQueue == NULL)
        {
            al_show_native_message_box(Screen, "Error!", "Failed to create the event queue.", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
            return -1;
        }

    if(!al_install_keyboard())
    {
        al_show_native_message_box(NULL, "Error!", "Failed to install keyboard.", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
        return -1;
    }

    al_register_event_source(EventQueue, al_get_display_event_source(Screen));
    al_register_event_source(EventQueue, al_get_keyboard_event_source());

    Background = al_load_bitmap("Background.png");
        if(Background == NULL)
        {
            al_show_native_message_box(Screen, "Error!", "Failed to load -Background.png-", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
            return -1;
        }
    Image = al_load_bitmap("image.png");
         if(Image == NULL)
        {
            al_show_native_message_box(Screen, "Error!", "Failed to load -Image.png-", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
            return -1;
        }

    KeyDownImage = al_load_bitmap("Meteors.png");
        if(KeyDownImage == NULL)
        {
            al_show_native_message_box(Screen, "Error!", "Failed to load -KeyPressed.png-", 0, 0, ALLEGRO_MESSAGEBOX_ERROR);
            return -1;
        }

    al_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,NULL);

    while(Exit == false)
    {
        if(KeyDown == true)
        {
            al_draw_bitmap(KeyDownImage, 0, 0, 0);
        }

        else
        {
            al_draw_bitmap(Background, 0, 0, 0);
            al_draw_bitmap(Image, 100, 100, 0);
        }

        al_flip_display();

        al_wait_for_event(EventQueue, &Event);

        if(Event.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            if(Event.keyboard.keycode == ALLEGRO_KEY_SPACE)
            {
                KeyDown = true;
            }
        }

        if(Event.type == ALLEGRO_EVENT_KEY_UP)
        {
            KeyDown = false;
        }

        if(Event.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            Exit = true;
        }
    }

    al_destroy_bitmap(Background);
    al_destroy_bitmap(KeyDownImage);
    al_destroy_event_queue(EventQueue);
    al_destroy_display(Screen);

    return 0;
}
예제 #23
0
int main(int argc, const char *argv[])
{
    ALLEGRO_SAMPLE *sample_data[MAX_SAMPLE_DATA] = {NULL};
    ALLEGRO_DISPLAY *display;
    ALLEGRO_EVENT_QUEUE *event_queue;
    ALLEGRO_EVENT event;
    int i;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s {audio_files}\n", argv[0]);
        return 1;
    }
    argc--;
    argv++;

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

    al_install_keyboard();

    display = al_create_display(640, 480);
    if (!display) {
        abort_example("Could not create display\n");
    }

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

    al_init_acodec_addon();

Restart:

    if (!al_install_audio()) {
        fprintf(stderr, "Could not init sound!\n");
        return 1;
    }

    if (!al_reserve_samples(RESERVED_SAMPLES)) {
        fprintf(stderr, "Could not set up voice and mixer.\n");
        return 1;
    }

    memset(sample_data, 0, sizeof(sample_data));
    for (i = 0; i < argc && i < MAX_SAMPLE_DATA; i++) {
        const char *filename = argv[i];

        /* Load the entire sound file from disk. */
        sample_data[i] = al_load_sample(argv[i]);
        if (!sample_data[i]) {
            fprintf(stderr, "Could not load sample from '%s'!\n", filename);
            continue;
        }
    }

    printf("Press digits to play sounds, space to stop sounds, "
           "Escape to quit.\n");

    while (true) {
        al_wait_for_event(event_queue, &event);
        if (event.type == ALLEGRO_EVENT_KEY_CHAR) {
            if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) {
                break;
            }
            if (event.keyboard.unichar == ' ') {
                al_stop_samples();
            }

            if (event.keyboard.unichar >= '0' && event.keyboard.unichar <= '9') {
                i = (event.keyboard.unichar - '0' + 9) % 10;
                if (sample_data[i]) {
                    printf("Playing %d\n",i);
                    if (!al_play_sample(sample_data[i], 1.0, 0.5, 1.0, ALLEGRO_PLAYMODE_LOOP, NULL)) {
                        fprintf(stderr,
                                "al_play_sample_data failed, perhaps too many sounds\n");
                    }
                }
            }

            /* Hidden feature: restart audio subsystem.
             * For debugging race conditions on shutting down the audio.
             */
            if (event.keyboard.unichar == 'r') {
                al_uninstall_audio();
                goto Restart;
            }
        }
    }

    /* Sample data and other objects will be automatically freed. */
    al_uninstall_audio();

    return 0;
}
int main(int argc, char **argv)
{
   ALLEGRO_VOICE *voice;
   ALLEGRO_SAMPLE_INSTANCE *sample;
   int i;

   if (argc < 2) {
      fprintf(stderr, "Usage: %s {audio_files}\n", argv[0]);
      return 1;
   }

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

   al_init_acodec_addon();

   if (!al_install_audio()) {
      fprintf(stderr, "Could not init sound!\n");
      return 1;
   }

   for (i = 1; i < argc; ++i) {
      ALLEGRO_SAMPLE *sample_data = NULL;
      const char *filename = argv[i];
      ALLEGRO_CHANNEL_CONF chan;
      ALLEGRO_AUDIO_DEPTH depth;
      unsigned long freq;
      float sample_time = 0;

      /* Load the entire sound file from disk. */
      sample_data = al_load_sample(filename);
      if (!sample_data) {
         fprintf(stderr, "Could not load sample from '%s'!\n",
            filename);
         continue;
      }

      sample = al_create_sample_instance(NULL);
      if (!sample) {
         fprintf(stderr, "al_create_sample failed.\n");
        return 1;
      }

      if (!al_set_sample(sample, sample_data)) {
         fprintf(stderr, "al_set_sample failed.\n");
         continue;
      }

      depth = al_get_sample_instance_depth(sample);
      chan = al_get_sample_instance_channels(sample);
      freq = al_get_sample_instance_frequency(sample);
      fprintf(stderr, "Loaded sample: %i-bit depth, %i channels, %li Hz\n",
         (depth < 8) ? (8+depth*8) : 0, (chan>>4)+(chan%0xF), freq);
      fprintf(stderr, "Trying to create a voice with the same specs... ");
      voice = al_create_voice(freq, depth, chan);
      if (!voice) {
         fprintf(stderr, "Could not create ALLEGRO_VOICE.\n");
         return 1;
      }
      fprintf(stderr, "done.\n");

      if (!al_attach_sample_instance_to_voice(sample, voice)) {
         fprintf(stderr, "al_attach_sample_instance_to_voice failed.\n");
         return 1;
      }

      /* Play sample in looping mode. */
      al_set_sample_instance_playmode(sample, ALLEGRO_PLAYMODE_LOOP);
      al_play_sample_instance(sample);

      sample_time = al_get_sample_instance_time(sample);
      fprintf(stderr, "Playing '%s' (%.3f seconds) 3 times", filename,
         sample_time);

      al_rest(sample_time * 3);

      al_stop_sample_instance(sample);
      fprintf(stderr, "\n");

      /* Free the memory allocated. */
      al_set_sample(sample, NULL);
      al_destroy_sample(sample_data);
      al_destroy_sample_instance(sample);
      al_destroy_voice(voice);
   }

   al_uninstall_audio();

   return 0;
}
예제 #25
0
static bool
init(void)
{
  if(!al_init()) {
    fprintf(stderr, "failed to initialize allegro.\n");
    return false;
  }

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

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

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

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

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

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

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

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

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

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

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

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

  return true;
}
예제 #26
0
int main() {
  bool menu = true;
  char pontuacao[100];
  char vida[100];
  ALLEGRO_COLOR  font_color;
  ALLEGRO_FONT *font,*font2;
  ALLEGRO_AUDIO_STREAM *musica = NULL;
  
  camera *cam = camera_inicializa(0);
  if(!cam)
    erro("erro na inicializacao da camera\n");
  int x = 0, y =  0;
  int largura = cam->largura;
  int altura = cam->altura;
  int fps = 0,tempo = 5;
  int ndisco = 9;
 
  if(!al_init())
    erro("erro na inicializacao do allegro\n");

  if(!al_init_image_addon())
    erro("erro na inicializacao do adicional de imagem\n");

  al_init_font_addon();
  al_init_ttf_addon();

    font_color = al_map_rgb(0, 0, 0);
    
    font = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 20, 0);
    font2 = al_load_ttf_font("Fontes/Blokletters-Viltstift.ttf", 50, 0);
    


  if(!al_init_primitives_addon())
    erro("erro na inicializacao do adicional de primitivas\n");

  ALLEGRO_TIMER *timer = al_create_timer(1.0 / FPS);
  if(!timer)
    erro("erro na criacao do relogio\n");

  ALLEGRO_DISPLAY *display = al_create_display(2 * largura,altura);
  if(!display)
    erro("erro na criacao da janela\n");

  ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
  if(!queue)
    erro("erro na criacao da fila\n");

   if (!al_install_audio())
    {
        fprintf(stderr, "Falha ao inicializar áudio.\n");
        return false;
    }
 
    if (!al_init_acodec_addon())
    {
        fprintf(stderr, "Falha ao inicializar codecs de áudio.\n");
        return false;
    }
    if (!al_reserve_samples(1))
    {
        fprintf(stderr, "Falha ao alocar canais de áudio.\n");
        return false;
    }

  musica = al_load_audio_stream("Audio/elementary.ogg", 4, 1024);
  if(!musica)
        erro("Erro na alocação da musica de fundo\n");

  al_attach_audio_stream_to_mixer(musica, al_get_default_mixer());
  al_set_audio_stream_playing(musica, true);

  al_register_event_source(queue, al_get_timer_event_source(timer));
  al_register_event_source(queue, al_get_display_event_source(display));

  al_start_timer(timer);
  
  unsigned char ***matriz = camera_aloca_matriz(cam);
  ALLEGRO_BITMAP *buffer = al_get_backbuffer(display);
  ALLEGRO_BITMAP *fundo = al_load_bitmap("Imagens/Elementary2.png");

  if(!fundo)
    erro("erro ao carregar Elementary.png");

  ALLEGRO_BITMAP *esquerda = al_create_sub_bitmap(buffer, 0, 0, largura, altura);
  ALLEGRO_BITMAP *direita = al_create_sub_bitmap(buffer, largura, 0, largura, altura);

  /**********/
  Disco *discos[9];
  bool perdeu = false;
  carregarDiscos(discos);
  int pontos=0,velo = 1;
  int aux1 = 1;
  int vidas = 10;
  int ultimoDisco = 0;
  int distance = 0;
  int desenhar = 0;
  int terminar = 0;
  al_set_target_bitmap(esquerda);
  al_draw_bitmap(fundo,0,0,0);
  while(1) {

    ALLEGRO_EVENT event;

    al_wait_for_event(queue, &event);

    switch(event.type) {
    case ALLEGRO_EVENT_TIMER:
      desenhar = 1;
      break;
    case ALLEGRO_EVENT_DISPLAY_CLOSE:
      terminar = 1;
      break;
   
    }

    if(terminar)
      break;

    if(desenhar && al_is_event_queue_empty(queue)) {
      desenhar = 0;
      camera_atualiza(cam);
      mediana(cam);
      /**********/
      al_set_target_bitmap(esquerda);
      al_draw_bitmap(fundo,0,0,0);
      
      if(!menu){
        while(aux1 <= ndisco){
          if(discos[aux1]->status == false){
            if(distance > 50 || ultimoDisco==0  ){
              printf("%d\n",aux1 );
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
              discos[aux1]->status = true;
              distance = 0;
              ultimoDisco = aux1;
              break;
            }else
             aux1++;
          }else{
              discos[aux1]->pos_y+=(10+velo);
              al_draw_bitmap(discos[aux1]->elemento,discos[aux1]->pos_x,discos[aux1]->pos_y,0);
            aux1++;
              
            }
        }
        distance = discos[ultimoDisco]->pos_y;
        for(aux1 = 1;aux1<ndisco;aux1++){
          if(discos[aux1]->pos_x >= x-30 && discos[aux1]->pos_x <= x+30 && discos[aux1]->pos_y >= y-30 &&  discos[aux1]->pos_y <= y+30){
            if(discos[aux1]->tipo == 2){ // Tipo do fogo(Necessario para vencer o jogo)
            pontos +=10;
            velo += 1;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }else if(discos[aux1]->tipo == 1){ //Tipo da agua(Perde o jogo se destruir esse disco)
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else if(discos[aux1]->tipo == 3){//Tipo planta(Aumenta velocidade de queda das peças)
            velo *= 2;
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }

        }else if( discos[aux1]->pos_y > 480){
          if(discos[aux1]->tipo == 2){ //Tipo da agua e Planta(Não perde se deixar cair)
               discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
            al_flip_display();
            vidas--;
          }else{
            discos[aux1]->pos_x = rand()%9 * 55;
            discos[aux1]->pos_y = 0;
            discos[aux1]->status = false;
          }
        }
      }

        aux1 = 1;
      sprintf(pontuacao,"PONTUAÇÃO: %d",pontos);
      al_draw_text(font, al_map_rgb(255, 255, 255), 50, 5, 0,pontuacao);
       sprintf(vida,"VIDAS: %d",vidas);
      al_draw_text(font, al_map_rgb(255, 255, 255), 300, 5, 0,vida);
      al_flip_display();

      }
       if(perdeu){
        al_draw_text(font2, al_map_rgb(255, 0, 0), 50, 100, 0,"PONTUAÇÃO FINAL");
        sprintf(pontuacao,"%d",pontos);
        al_draw_text(font2, al_map_rgb(255, 0, 0), 250, 170, 0,pontuacao);
        al_flip_display();
        al_rest(3);
        break;
      }
       
      if(vidas == 0){
        perdeu = true;
      }

      if(menu){
        if(abrirJogo(x,y,&fps,&tempo,font,font2, font_color)){
          fundo = al_load_bitmap("Imagens/galaxia.png");
          menu = false;
        }
      }
      cameraRastreia(cam,&x,&y);
   

      al_set_target_bitmap(direita);
      camera_copia(cam, cam->quadro, direita);
      al_flip_display();
    }
  }
  al_destroy_bitmap(direita);
  al_destroy_bitmap(fundo);
  al_destroy_bitmap(esquerda);
  camera_libera_matriz(cam, matriz);
int fri = 9;
while(fri != 0){
  free(discos[fri]);
  fri--;

}


  al_stop_timer(timer);

  al_unregister_event_source(queue, al_get_display_event_source(display));
  al_unregister_event_source(queue, al_get_timer_event_source(timer));

  al_destroy_event_queue(queue);
  al_destroy_display(display);
  al_destroy_timer(timer);
  al_destroy_audio_stream(musica);
  al_shutdown_primitives_addon();
  al_shutdown_image_addon();
  al_uninstall_system();

  camera_finaliza(cam);

  return EXIT_SUCCESS;
}
예제 #27
0
파일: ex_acodec.c 프로젝트: gitustc/d2imdev
int main(int argc, char **argv)
{
   ALLEGRO_VOICE *voice;
   ALLEGRO_MIXER *mixer;
   ALLEGRO_SAMPLE_INSTANCE *sample;
   int i;
   char const **filenames;
   int n;

   if (argc < 2) {
      n = 1;
      filenames = malloc(sizeof *filenames);
      filenames[0] = "data/testing.ogg";
   }
   else {
      n = argc - 1;
      filenames = malloc(sizeof *filenames * n);
      for (i = 1; i < argc; ++i) {
         filenames[i - 1] = argv[i];
      }
   }

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

   open_log();

   al_init_acodec_addon();

   if (!al_install_audio()) {
      abort_example("Could not init sound!\n");
   }

   voice = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16,
      ALLEGRO_CHANNEL_CONF_2);
   if (!voice) {
      abort_example("Could not create ALLEGRO_VOICE.\n");
   }

   mixer = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32,
      ALLEGRO_CHANNEL_CONF_2);
   if (!mixer) {
      abort_example("al_create_mixer failed.\n");
   }

   if (!al_attach_mixer_to_voice(mixer, voice)) {
      abort_example("al_attach_mixer_to_voice failed.\n");
   }

   sample = al_create_sample_instance(NULL);
   if (!sample) {
      abort_example("al_create_sample failed.\n");
   }

   for (i = 0; i < n; ++i) {
      ALLEGRO_SAMPLE *sample_data = NULL;
      const char *filename = filenames[i];
      float sample_time = 0;

      /* Load the entire sound file from disk. */
      sample_data = al_load_sample(filename);
      if (!sample_data) {
         abort_example("Could not load sample from '%s'!\n",
            filename);
         continue;
      }

      if (!al_set_sample(sample, sample_data)) {
         abort_example("al_set_sample_instance_ptr failed.\n");
         continue;
      }

      if (!al_attach_sample_instance_to_mixer(sample, mixer)) {
         abort_example("al_attach_sample_instance_to_mixer failed.\n");
         goto done;
      }

      /* Play sample in looping mode. */
      al_set_sample_instance_playmode(sample, ALLEGRO_PLAYMODE_LOOP);
      al_play_sample_instance(sample);

      sample_time = al_get_sample_instance_time(sample);
      log_printf("Playing '%s' (%.3f seconds) 3 times", filename,
         sample_time);

      al_rest(sample_time);

      if (!al_set_sample_instance_gain(sample, 0.5)) {
         abort_example("Failed to set gain.\n");
      }
      al_rest(sample_time);

      if (!al_set_sample_instance_gain(sample, 0.25)) {
         abort_example("Failed to set gain.\n");
      }
      al_rest(sample_time);

      al_stop_sample_instance(sample);
      log_printf("\nDone playing '%s'\n", filename);

      /* Free the memory allocated. */
      al_set_sample(sample, NULL);
      al_destroy_sample(sample_data);
   }

   al_destroy_sample_instance(sample);
   al_destroy_mixer(mixer);
   al_destroy_voice(voice);

   al_uninstall_audio();

done:
   close_log(true);

   return 0;
}
예제 #28
0
int main(int argc, char *argv[])
{
   ALLEGRO_DISPLAY *display;
   (void)argc;
   (void)argv;

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

   open_log();

   al_install_keyboard();
   al_install_mouse();

   al_init_primitives_addon();
   al_init_font_addon();
   al_init_ttf_addon();

   al_set_new_display_flags(ALLEGRO_GENERATE_EXPOSE_EVENTS);
   display = al_create_display(800, 600);
   if (!display) {
      abort_example("Unable to create display\n");
   }
   al_set_window_title(display, "Synthesiser of sorts");

   font_gui = al_load_ttf_font("data/DejaVuSans.ttf", 12, 0);
   if (!font_gui) {
      abort_example("Failed to load data/fixed_font.tga\n");
   }

   if (!al_install_audio()) {
      abort_example("Could not init sound!\n");
   }

   if (!al_reserve_samples(0)) {
      abort_example("Could not set up voice and mixer.\n");
   }

   size_t buffers = 8;
   unsigned samples = SAMPLES_PER_BUFFER;
   unsigned freq = STREAM_FREQUENCY;
   ALLEGRO_AUDIO_DEPTH depth = ALLEGRO_AUDIO_DEPTH_FLOAT32;
   ALLEGRO_CHANNEL_CONF ch = ALLEGRO_CHANNEL_CONF_1;

   stream1 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream2 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream3 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream4 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   stream5 = al_create_audio_stream(buffers, samples, freq, depth, ch);
   if (!stream1 || !stream2 || !stream3 || !stream4 || !stream5) {
      abort_example("Could not create stream.\n");
   }

   ALLEGRO_MIXER *mixer = al_get_default_mixer();
   if (
      !al_attach_audio_stream_to_mixer(stream1, mixer) ||
      !al_attach_audio_stream_to_mixer(stream2, mixer) ||
      !al_attach_audio_stream_to_mixer(stream3, mixer) ||
      !al_attach_audio_stream_to_mixer(stream4, mixer) ||
      !al_attach_audio_stream_to_mixer(stream5, mixer)
   ) {
      abort_example("Could not attach stream to mixer.\n");
   }

   al_set_mixer_postprocess_callback(mixer, mixer_pp_callback, mixer);

   /* Prog is destroyed at the end of this scope. */
   {
      Theme theme(font_gui);
      Prog prog(theme, display);
      prog.run();
   }

   al_destroy_audio_stream(stream1);
   al_destroy_audio_stream(stream2);
   al_destroy_audio_stream(stream3);
   al_destroy_audio_stream(stream4);
   al_destroy_audio_stream(stream5);
   al_uninstall_audio();

   al_destroy_font(font_gui);

   al_fclose(save_fp);

   close_log(false);

   return 0;
}
예제 #29
0
파일: main.c 프로젝트: dradtke/battlechess
/* the main program body */
int main(int argc, char *argv[])
{
   ALLEGRO_PATH *font_path;
   int w = 0, h = 0;
   int www = FALSE;
   int i, n;
   int display_flags = ALLEGRO_GENERATE_EXPOSE_EVENTS;

   srand(time(NULL));
   
   al_set_org_name("liballeg.org");
   al_set_app_name("SPEED");

   if (!al_init()) {
      fprintf(stderr, "Could not initialise Allegro.\n");
      return 1;
   }
   al_init_primitives_addon();

   /* parse the commandline */
   for (i=1; i<argc; i++) {
      if (strcmp(argv[i], "-cheat") == 0) {
         cheat = TRUE;
      }
      else if (strcmp(argv[i], "-simple") == 0) {
         low_detail = TRUE;
      }
      else if (strcmp(argv[i], "-nogrid") == 0) {
         no_grid = TRUE;
      }
      else if (strcmp(argv[i], "-nomusic") == 0) {
         no_music = TRUE;
      }
      else if (strcmp(argv[i], "-www") == 0) {
         www = TRUE;
      }
      else if (strcmp(argv[i], "-fullscreen") == 0) {
         /* if no width is specified, assume fullscreen_window */
         display_flags |= w ? ALLEGRO_FULLSCREEN : ALLEGRO_FULLSCREEN_WINDOW;
      }
      else {
         n = atoi(argv[i]);

         if (!n) {
            usage();
            return 1;
         }

         if (!w) {
            w = n;
            if (display_flags & ALLEGRO_FULLSCREEN_WINDOW) {
               /* toggle from fullscreen_window to fullscreen */
               display_flags &= ~ALLEGRO_FULLSCREEN_WINDOW;
               display_flags |= ALLEGRO_FULLSCREEN;
            }
         }
         else if (!h) {
            h = n;
         }
         else {
            usage();
            return 1;
         }
      }
   }

   /* it's a real shame that I had to take this out! */
   if (www) {
      printf(
	 "\n"
	 "Unfortunately the built-in web browser feature had to be removed.\n"
	 "\n"
	 "I did get it more or less working as of Saturday evening (forms and\n"
	 "Java were unsupported, but tables and images were mostly rendering ok),\n"
	 "but the US Department of Justice felt that this was an unacceptable\n"
	 "monopolistic attempt to tie in web browsing functionality to an\n"
	 "unrelated product, so they threatened me with being sniped at from\n"
	 "the top of tall buildings by guys with high powered rifles unless I\n"
	 "agreed to disable this code.\n"
	 "\n"
	 "We apologise for any inconvenience that this may cause you.\n"
      );

      return 1;
   }
   
   if (!w || !h) {
      if (argc == 1 || (display_flags & ALLEGRO_FULLSCREEN_WINDOW)) {
         w = 640;
         h = 480;
      }
      else {
         usage();
         return 1;
      }
   }

   /* set the screen mode */
   al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST);
   al_set_new_display_option(ALLEGRO_SAMPLES, 4, ALLEGRO_SUGGEST);

   al_set_new_display_flags(display_flags);
   screen = al_create_display(w, h);
   if (!screen) {
      fprintf(stderr, "Error setting %dx%d display mode\n", w, h);
      return 1;
   }

   al_init_image_addon();

   /* The Allegro 5 port introduced an external data dependency, sorry.
    * To avoid performance problems on graphics drivers that don't support
    * drawing to textures, we build up transition screens on memory bitmaps.
    * We need a font loaded into a memory bitmap for those, then a font
    * loaded into a video bitmap for the game view. Blech!
    */
   font_path = get_resources_path();
   al_set_path_filename(font_path, "a4_font.tga");

   al_init_font_addon();
   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   font = al_load_bitmap_font(al_path_cstr(font_path, '/'));
   if (!font) {
      fprintf(stderr, "Error loading %s\n", al_path_cstr(font_path, '/'));
      return 1;
   }

   al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
   font_video = al_load_bitmap_font(al_path_cstr(font_path, '/'));
   if (!font_video) {
      fprintf(stderr, "Error loading %s\n", al_path_cstr(font_path, '/'));
      return 1;
   }
   
   al_destroy_path(font_path);

   /* set up everything else */
   al_install_keyboard();
   al_install_joystick();
   if (al_install_audio()) {
      if (!al_reserve_samples(8))
         al_uninstall_audio();
   }

   init_input();
   init_sound();
   init_hiscore();

   /* the main program body */
   while (title_screen()) {
      if (play_game()) {
	 show_results();
	 score_table();
      }
   }

   /* time to go away now */
   shutdown_hiscore();
   shutdown_sound();

   goodbye();

   shutdown_input();

   al_destroy_font(font);
   al_destroy_font(font_video);

   return 0;
}
int main(void)
{
	// don't forget to put allegro-5.0.10-monolith-md-debug.lib
	//primitive variable
	bool done = false;
	bool redraw = true;
	const int FPS = 60;
	bool isGameOver = false;

	//object variables
	spaceShip ship;
	Bullet bullets[NUM_BULLETS];
	Comet comets[NUM_COMETS];
	Explosion explosions[NUM_EXPLOSIONS];

	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;
	ALLEGRO_FONT *font18 = NULL;
	ALLEGRO_BITMAP *shipImage;
	ALLEGRO_BITMAP *cometImage;
	ALLEGRO_BITMAP *expImage;
	ALLEGRO_SAMPLE * sample = NULL;
	ALLEGRO_SAMPLE * sample2 = NULL;
	ALLEGRO_SAMPLE * sample3 = NULL;
	ALLEGRO_SAMPLE_INSTANCE * instance1 = NULL;
	ALLEGRO_SAMPLE_INSTANCE * instance2 = NULL;
	ALLEGRO_SAMPLE_INSTANCE * instance3 = NULL;

	//Initialization Functions
	if(!al_init())										//initialize Allegro
		return -1;

	display = al_create_display(WIDTH, HEIGHT);			//create our display object

	if(!display)										//test display object
		return -1;

	al_init_primitives_addon();
	al_install_keyboard();
	al_init_font_addon();
	al_init_ttf_addon();
	al_init_image_addon();
	al_install_audio(); // always initialize audio before the codecs
	al_init_acodec_addon();
	
	al_reserve_samples(10); // reserves numbers of samples/ channels or voices

	sample = al_load_sample("chirp.ogg");
	sample2 = al_load_sample("static.ogg");
	sample3 = al_load_sample("JSS - Our Song.ogg");

	instance1 = al_create_sample_instance(sample);
	instance2 = al_create_sample_instance(sample2);
	instance3 = al_create_sample_instance(sample3);	

	al_set_sample_instance_playmode(instance3, ALLEGRO_PLAYMODE_LOOP);

	al_attach_sample_instance_to_mixer(instance1, al_get_default_mixer());
    al_attach_sample_instance_to_mixer(instance2, al_get_default_mixer());
	al_attach_sample_instance_to_mixer(instance3, al_get_default_mixer());

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

	cometImage = al_load_bitmap("asteroid-1-96.png");
	//above does not need convert_mask_to_alpha because it is tranparent background in sprite sheet
	shipImage = al_load_bitmap("Spaceship_by_arboris.png");
	al_convert_mask_to_alpha(shipImage,al_map_rgb(255,0,255));

	expImage = al_load_bitmap("explosion_3_40_128.png");

	srand(time(NULL));
	InitShip(ship, shipImage);
	InitBullet(bullets, NUM_BULLETS);
	InitComet(comets, NUM_COMETS, cometImage);
	InitExplosions(explosions, NUM_EXPLOSIONS, expImage);

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

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

	al_play_sample_instance(instance3);

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

		if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			redraw = true;
			int soundX = ship.x;
			int soundY = ship.y;
			
			if(keys[UP])
				MoveShipUp(ship);
			else if(keys[DOWN])
				MoveShipDown(ship);
			else
				ResetShipAnimation(ship,1);
			if(keys[LEFT])
				MoveShipLeft(ship);
			else if(keys[RIGHT])
				MoveShipRight(ship);
			else
				ResetShipAnimation(ship, 2);
			
			if(soundX != ship.x || soundY != ship.y){
				//al_play_sample(sample, 1,0,1, ALLEGRO_PLAYMODE_ONCE, NULL);
				al_play_sample_instance(instance1);
			}
			if (ship.x -10 < 0 || ship.x + 10 > WIDTH || ship.y - 10 < 0 || ship.y + 10 > HEIGHT){
				al_play_sample_instance(instance2);
			}

			if(!isGameOver)
			{
				UpdateExplosions(explosions, NUM_EXPLOSIONS);
				UpdateBullet(bullets, NUM_BULLETS);
				StartComet(comets, NUM_COMETS);
				UpdateComet(comets, NUM_COMETS);
				CollideBullet(bullets, NUM_BULLETS, comets, NUM_COMETS, ship, explosions, NUM_EXPLOSIONS);
				CollideComet(comets, NUM_COMETS, ship, explosions, NUM_BULLETS);

				if(ship.lives <= 0)
					isGameOver = true;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = true;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = true;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = true;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = true;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = true;
				FireBullet(bullets, NUM_BULLETS, ship);
				break;
			}
		}
		else if(ev.type == ALLEGRO_EVENT_KEY_UP)
		{
			switch(ev.keyboard.keycode)
			{
			case ALLEGRO_KEY_ESCAPE:
				done = true;
				break;
			case ALLEGRO_KEY_UP:
				keys[UP] = false;
				break;
			case ALLEGRO_KEY_DOWN:
				keys[DOWN] = false;
				break;
			case ALLEGRO_KEY_LEFT:
				keys[LEFT] = false;
				break;
			case ALLEGRO_KEY_RIGHT:
				keys[RIGHT] = false;
				break;
			case ALLEGRO_KEY_SPACE:
				keys[SPACE] = false;
				break;
			}
		}

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

			if(!isGameOver)
			{
				DrawShip(ship);
				if(al_get_sample_instance_playing(instance1)){
					al_draw_text(font18, al_map_rgb(255,255,255),5,30,0, "Instance 1 is playing");
				}
				if(al_get_sample_instance_playing(instance2)){
					al_draw_text(font18, al_map_rgb(255,255,255),WIDTH - 5,30,ALLEGRO_ALIGN_RIGHT, "Instance 2 is playing");
				}
				if(al_get_sample_instance_playing(instance3)){
					al_draw_textf(font18, al_map_rgb(255,255,255),5,HEIGHT - 30,0, "Instance 3 is playing: %.1f %%", al_get_sample_instance_position(instance3) / (float)al_get_sample_instance_length(instance3) * 100);
				}

				DrawBullet(bullets, NUM_BULLETS);
				DrawComet(comets, NUM_COMETS);
				DrawExplosions(explosions, NUM_EXPLOSIONS);

				al_draw_textf(font18, al_map_rgb(255, 0, 255), 5, 5, 0, "Player has %i lives left. Player has destroyed %i objects", ship.lives, ship.score);
			}
			else
			{
				al_draw_textf(font18, al_map_rgb(0, 255, 255), WIDTH / 2, HEIGHT / 2, ALLEGRO_ALIGN_CENTRE, "Game Over. Final Score: %i", ship.score);
			}
		
			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0));
		}
	}

	al_destroy_sample_instance(instance1);
	al_destroy_sample_instance(instance2);
	al_destroy_sample_instance(instance3);
	al_destroy_sample(sample);
	al_destroy_sample(sample2);
	al_destroy_sample(sample3);
	al_destroy_bitmap(expImage);
	al_destroy_bitmap(shipImage);
	al_destroy_bitmap(cometImage);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	al_destroy_font(font18);
	al_destroy_display(display);						//destroy our display object

	return 0;
}