void PlayEffect(Mix_Music* effect) { Mix_PlayMusic(effect,1); }
int main() { bool running; int fps; Mix_Music *music; snake s(840,640,20); Uint32 start; while(1) { s.Init(); fps=6; //Intro Mix_OpenAudio(22050,AUDIO_S16SYS,2,128); music=Mix_LoadMUS("Music/stronger.mp3"); Mix_PlayMusic(music,-1); music=Mix_LoadMUS("Music/snake.wav"); s.Draw_Bg(); s.WaitKey(); Mix_PlayMusic(music,-1); s.Draw_Bg(); s.Ready(); s.Fill_Screen(); SDL_Delay(2000); running=true; while(running) { start=SDL_GetTicks(); running=s.Go_To(); s.Draw_Bg(); s.Draw_Border(); s.Draw_Score(); s.Draw_Food(&fps); s.Draw_Node(); s.Fill_Screen(); if(1000/fps>(int)(SDL_GetTicks()-start)) SDL_Delay(1000/fps -SDL_GetTicks() +start); } Mix_FreeMusic(music); music=Mix_LoadMUS("Music/game_over.wav"); Mix_PlayMusic(music,-1); SDL_Delay(800); s.Draw_Bg(); s.Game_Over(); s.Fill_Screen(); SDL_Delay(4000); Mix_FreeMusic(music); Mix_CloseAudio(); } }
int main(int argc, char *args[]) { SDL_Init(SDL_INIT_EVERYTHING); //Init SDL Mix_Init(MIX_INIT_FLAC | MIX_INIT_MOD | MIX_INIT_MP3 | MIX_INIT_OGG); //Init SDL Mixer Mix_OpenAudio(22050, AUDIO_S16SYS, 2, 4096); //Open audiostream int temp = officalDelay; //The delay it will play int holder = -1; //Hold which sound it played before int counter = 0; //How many soundclips have been played //Create window and check if it's loaded SDL_Window *win = SDL_CreateWindow("Omvand Synestesi", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 800, SDL_WINDOW_SHOWN); if (win == NULL) { std::cout << "Couldn't create window, unkown error." << std::endl; } //Make a renderer SDL_Renderer *renderer = SDL_CreateRenderer(win, 0, SDL_RENDERER_ACCELERATED); //Create a texture, load it. Check if it's loaded SDL_Texture *texture = load_texture("get.bmp", renderer); if(texture == NULL) { std::cout << "Couldn't load picture, check so it's named get.bmp" << std::endl; } //Loads a surface, this is the picture it will take and make sound of. SDL_Surface *image = SDL_LoadBMP("get.bmp"); if (image == NULL) { std::cout << "Couldn't load picture until surface. Check the name so it is get.bmp" << std::endl; } //Load soundfiles Mix_Music *sound[15]; for (int i = 1; i < 16; i++) { std::string path = "sound/get" + convertInt(i) + ".wav"; sound[i] = Mix_LoadMUS(path.c_str()); std::cout << "Loaded soundfile: " << path << std::endl; if (sound[i] == NULL) { std::cout << "Couldn't load soundfile " << path << ". Check so the name is get" << i << ".wav" << std::endl; } } //Loop through the whole picture for (int y = 0; y < size_h; y++) { for (int x = 0; x < size_w; x++) { Uint32 pix = getPixel(image, x, y); SDL_RenderClear(renderer); //Clear the screen SDL_RenderCopy(renderer, texture, NULL, NULL); //Print out the picture SDL_RenderPresent(renderer); //Actually render the picture int npix = pix % 16 + 1; //Get's a value from the pixel and makes it so it's just 1 to 16 std::cout << "!-- " << pix << " --! " << npix << " | " << counter << "/1296" << std::endl; //Prints out some stuff so you can see for debugging mostly //If the same value is again, make a longer delay before playing next song, and if not, go back to standard delay if (npix == holder) { temp = temp + 120; } else { temp = officalDelay; } //Play right soundfile from value of pixel for (int i = 1; i < 15; i++) { int newi = i + 1; if (i == npix) { Mix_PlayMusic(sound[newi], 0); SDL_Delay(temp); holder = i; } } //If value is 16, don't play a sound and make a 3sec long delay. if (npix == 16) { std::cout << std::endl << "-----" << std::endl << std::endl; SDL_Delay(3000); } counter++; } } SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyTexture(texture); SDL_DestroyWindow(win); for (int i = 1; i < 16; i++) { Mix_FreeMusic(sound[i]); } Mix_Quit(); SDL_Quit(); return 0; }
//colocar um vetor de opções com o seguinte padrão {1, 1}; int TelaInicial(SDL_Surface *screen, int EstadoOpcoes[3]) // -1 = SAIR DO JOGO; 1 = ENTRAR NOVO JOGO; { //Controles[0] = Cima; Controles[1] = Baixo; Controles[2] = Direita; Controles[3] = Esquerda; Controles[4] = Bomba; /*Menu: 1-Iniciar; 2-High Score; 3-Opções; 4- Sobre; 5- Sair; 1.1-Continuar 2.1-Limpar 3.1-SFX(on/off) 4.1- Voltar *Sim 1.2-Novo Jogo 2.2- Voltar 3.2- Musica(on/off) *Não 1.3- Voltar 3.3-Auto save(on/off) 3.4-Save 3.5-Controles 3.6 Voltar */ int MenuSelecionado = 0, SubMenuSelecionado = -1, Pagina = 0; int Retorno = -2; int HaSave = 0; int MostrarSimNao = 0, SimOuNaoSelecionado = 0, ApagaRecordes = 0; int ControladorMorcego = 0, ControladorDeTempo = 0; // vai fazer a animação entre a imagem 1 e 2 int Sair = 0; //EstadoOpcoes[3]; opção[0] = SFX; opção[1] = Music; opção[2] = AutoSave //====================================================== TTF_Font* fonte; fonte = TTF_OpenFont("japonese.ttf",FONTSIZE * 2); //===================================================== //========================================================= /*Variáveis que serão usadas para carregar as músicas Mix_Chunk ------> mais usado para carregar arquivos de sons pequenos(tipo o efeito de seleção); Mix_Music -------> usado para carregar os arquivos de música; */ Mix_Music * musica_fundo = Mix_LoadMUS("SonsJogo/menu.mp3"); Mix_Chunk * som_selecao_enter = Mix_LoadWAV("SonsJogo/button16.wav"); Mix_Chunk * som_selecao_movimento = Mix_LoadWAV("SonsJogo/button15.wav"); //=========================================================== //====================================== SDL_Surface *FundoControles = IMG_Load("Imagens/fundoHS.png"); //====================================== SDL_Surface *Fundo = IMG_Load("Imagens/Background.jpg"); //botões da tela principal SDL_Surface *surBotoesIniciais[5][2]; surBotoesIniciais[0][0] = IMG_Load("Imagens/Menu/BotaoIniciar.png"); surBotoesIniciais[1][0] = IMG_Load("Imagens/Menu/BotaoRecordes.png"); surBotoesIniciais[2][0] = IMG_Load("Imagens/Menu/BotaoOpcoes.png"); surBotoesIniciais[3][0] = IMG_Load("Imagens/Menu/BotaoSobre.png"); surBotoesIniciais[4][0] = IMG_Load("Imagens/Menu/BotaoSair.png"); //botões da tela incial selecionados surBotoesIniciais[0][1] = IMG_Load("Imagens/Menu/BotaoIniciar_Selecionado.png"); surBotoesIniciais[1][1] = IMG_Load("Imagens/Menu/BotaoRecordes_Selecionado.png"); surBotoesIniciais[2][1] = IMG_Load("Imagens/Menu/BotaoOpcoes_Selecionado.png"); surBotoesIniciais[3][1] = IMG_Load("Imagens/Menu/BotaoSobre_Selecionado.png"); surBotoesIniciais[4][1] = IMG_Load("Imagens/Menu/BotaoSair_Selecionado.png"); //botões dentro da tag INICIAR SDL_Surface *surBotoesSubMenuIniciar[2][2]; surBotoesSubMenuIniciar[0][0] = IMG_Load("Imagens/Menu/SubMenuIniciar/BotaoContinuar.png"); surBotoesSubMenuIniciar[1][0] = IMG_Load("Imagens/Menu/SubMenuIniciar/BotaoNovoJogo.png"); //botões selecionados surBotoesSubMenuIniciar[0][1] = IMG_Load("Imagens/Menu/SubMenuIniciar/BotaoContinuar_Selecionado.png"); surBotoesSubMenuIniciar[1][1] = IMG_Load("Imagens/Menu/SubMenuIniciar/BotaoNovoJogo_Selecionado.png"); //botões dentro da tag de OPÇÕES SDL_Surface *surBotoesSubMenuOpcoes[3][2]; SDL_Surface *surBotaoOnOff[2][2]; //auxiliar que vai mostrar o estado da opção pro jogador surBotoesSubMenuOpcoes[0][0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoSFX.png"); surBotoesSubMenuOpcoes[1][0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoMusica.png"); surBotoesSubMenuOpcoes[2][0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoControles.png"); //botões selecionados surBotoesSubMenuOpcoes[0][1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoSFX_Selecionado.png"); surBotoesSubMenuOpcoes[1][1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoMusica_Selecionado.png"); surBotoesSubMenuOpcoes[2][1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/BotaoControles_Selecionado.png"); //auxiliares on/off surBotaoOnOff[0][0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/OnOff_Off.png"); surBotaoOnOff[1][0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/OnOff_On.png"); //botões selecionados surBotaoOnOff[0][1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/OnOff_Off_Selecionado.png"); surBotaoOnOff[1][1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/OnOff_On_Selecionado.png"); //Rect dos botões SDL_Rect rectBotoes[5]; //posicao dos botoes rectBotoes[0].x = OxPrimeiroBotao; rectBotoes[0].y = OyPrimeiroBotao; rectBotoes[1].x = OxSegundoBotao; rectBotoes[1].y = OySegundoBotao; rectBotoes[2].x = OxTerceiroBotao; rectBotoes[2].y = OyTerceiroBotao; rectBotoes[3].x = OxQuartoBotao; rectBotoes[3].y = OyQuartoBotao; rectBotoes[4].x = OxQuintoBotao; rectBotoes[4].y = OyQuintoBotao; //posição do botão On/off SDL_Rect rectBotoesOnOff[3]; int i; for(i=0;i<3;i++) { rectBotoesOnOff[i].x = rectBotoes[i].x + AcrescimoDeXemOnOff; rectBotoesOnOff[i].y = rectBotoes[i].y; } //botões que aparecem ao lado do botão sair para escolher sim ou não SDL_Surface *surBotaoSimNao[2][2]; surBotaoSimNao[0][0] = IMG_Load("Imagens/Menu/SubMenuSair/BotaoNao.png"); surBotaoSimNao[1][0] = IMG_Load("Imagens/Menu/SubMenuSair/BotaoSim.png"); //botões selecionados surBotaoSimNao[0][1] = IMG_Load("Imagens/Menu/SubMenuSair/BotaoNao_Selecionado.png"); surBotaoSimNao[1][1] = IMG_Load("Imagens/Menu/SubMenuSair/BotaoSim_Selecionado.png"); //rect dos botões sim/não SDL_Rect rectBotaoSimNao[2]; //posição botão não rectBotaoSimNao[0].x = OxQuintoBotao + AcrescimoEmX_Nao; rectBotaoSimNao[0].y = OyQuintoBotao - 4; //posição botão sim rectBotaoSimNao[1].x = OxQuintoBotao + AcrescimoEmX_Sim; rectBotaoSimNao[1].y = OyQuintoBotao + 2; //o que terá na tela de sobre SDL_Surface *surMenuSobre = IMG_Load("Imagens/Menu/MenuSobre/menu_sobre.png"); SDL_Rect rectMenuSobre; rectMenuSobre.x = 30; rectMenuSobre.y = 30; //botão padrão de subtela... voltar SDL_Surface *surBotaoVoltar[2]; surBotaoVoltar[0] = IMG_Load("Imagens/Menu/BotaoVoltar.png"); surBotaoVoltar[1] = IMG_Load("Imagens/Menu/BotaoVoltar_Selecionado.png"); //rect do botão voltar SDL_Rect rectBotaoVoltar; //posição do botão será definida em relação ao ultimo botão da tela //botão dentro da tag HIGH SCORE SDL_Surface *surBotaoLimpar[2]; surBotaoLimpar[0] = IMG_Load("Imagens/Menu/SubMenuRecordes/BotaoLimparRecordes.png"); surBotaoLimpar[1] = IMG_Load("Imagens/Menu/SubMenuRecordes/BotaoLimparRecordes_Selecionado.png"); //rect do botão limpar SDL_Rect rectBotaoLimpar; rectBotaoLimpar.x = OxBotaoLimpar; rectBotaoLimpar.y = OyBotaoLimpar; //imagens para as setas nos controles SDL_Surface *surMostrarControles[5]; surMostrarControles[0] = IMG_Load("Imagens/Menu/SubMenuOpcoes/Controles/Cima.png"); surMostrarControles[1] = IMG_Load("Imagens/Menu/SubMenuOpcoes/Controles/Direita.png"); surMostrarControles[2] = IMG_Load("Imagens/Menu/SubMenuOpcoes/Controles/Baixo.png"); surMostrarControles[3] = IMG_Load("Imagens/Menu/SubMenuOpcoes/Controles/Esquerda.png"); surMostrarControles[4] = IMG_Load("Imagens/Menu/SubMenuOpcoes/Controles/Bomba.png"); //botoes para as setas nos controles SDL_Rect rectMostraControles[5]; rectMostraControles[0].x = OxMostrarControles; rectMostraControles[0].y = OyPrimeiroBotao; rectMostraControles[1].x = OxMostrarControles; rectMostraControles[1].y = OySegundoBotao; rectMostraControles[2].x = OxMostrarControles; rectMostraControles[2].y = OyTerceiroBotao; rectMostraControles[3].x = OxMostrarControles; rectMostraControles[3].y = OyQuartoBotao; rectMostraControles[4].x = OxMostrarControles - (surMostrarControles[4]->w/2); rectMostraControles[4].y = OyQuintoBotao; //a ideia aqui é criar um pequeno morcego que ficará "voando" ao lado do menu selecionado ... SDL_Surface *surMorcegoSelect[2]; surMorcegoSelect[0] = IMG_Load("Imagens/Menu/Selecao/MorcegoSelect0.png"); surMorcegoSelect[1] = IMG_Load("Imagens/Menu/Selecao/MorcegoSelect1.png"); SDL_Rect rectMorcegoSelect; //a posição do morcego será definida a partir do botão que for selecionado, ou seja, só na hora de blitar na tela //....porém, devido a problemas com a primeira blitagem ele será definido como no 1º botão aqui rectMorcegoSelect.x = OxPrimeiroBotao + 70 + IncrementoDeSelecaoX + AcrescimoEmXMorcego; rectMorcegoSelect.y = OyPrimeiroBotao; //----------------------------INICIANDO TELA-------------------------------------------------- SDL_BlitSurface(Fundo, NULL, screen, NULL); for(i=0;i<5;i++) { if(i!=MenuSelecionado) SDL_BlitSurface(surBotoesIniciais[i][0], NULL, screen, &rectBotoes[i]); else { BlitarBotaoSelecionado(surBotoesIniciais[i][1], rectBotoes[i], screen); SDL_BlitSurface(surMorcegoSelect[i], NULL, screen, &rectMorcegoSelect); } } SDL_Flip(screen); //----------------------------- EVENTOS E CONTROLE INTERNO DO MENU----------------------------- SDL_Event evento; int quit = 0; //================================== /*Serve para começar a tocar a musica desejada Obs: O parâmetro "-1" na função indica que a musica irá ser repetida infinitamente ou até fechar o programa.*/ Mix_PlayMusic(musica_fundo, -1); //=================================== while (!quit) { if(ControladorDeTempo >= 5) { if(ControladorMorcego == 1) ControladorMorcego = 0; else ControladorMorcego = 1; ControladorDeTempo = 0; } else ControladorDeTempo++; while(SDL_PollEvent(&evento)) { //============================================= /*Como existe a opção de desligar os sons e a música do jogo, foi necessária a criação dessas condições: Mix_Volume-------->Meche com o volume dos sons(parametro -1 utilizado para indicar que isso servirá para todos os tipos de Mix_Chunk que vc esta utilizando. Mix_PauseMusic(pausar a musica) e Mix_ResumeMusic(voltar a tocar a musica)-------> Creio que não seja necessário explicar... pois a propria função diz o que ela faz.*/ if(EstadoOpcoes[0] == 0) Mix_Volume(-1, 0); else Mix_Volume(-1, 128); if(EstadoOpcoes[1] == 0) Mix_PauseMusic(); else Mix_ResumeMusic(); //============================================== if(evento.type == SDL_KEYDOWN) { switch(evento.key.keysym.sym) { case SDLK_DOWN: //se apertar a tecla pra baixo desce, mas depende da página que esta e do indice { //=========================================== //Tocará o som indicado quando ocorrer o evento de movimentar as opções. Mix_PlayChannel(-1,som_selecao_movimento,0); //=========================================== switch (Pagina) //PAGINA { case 0: //PAGINA PRINCIPAL { if( (MenuSelecionado==4) && (MostrarSimNao == 1) ) { MostrarSimNao = 0; SimOuNaoSelecionado = 0; } MenuSelecionado ++; //AUMENTA O MENU if(MenuSelecionado == 5) //IMPEDE QUE PASSE DO LIMITE MenuSelecionado = 0; break; //SAI DO SWITCH PÁGINA } case 1: //PAGINA 1 (QUALQUER SUBMENU) { switch (MenuSelecionado) { case 2: //OPÇÕES { SubMenuSelecionado++; //AUMENTA O SUBMENU if(SubMenuSelecionado == 4) //IMPEDE QUE PASSE DO LIMITE SubMenuSelecionado = 0; break;//SAI DO SWITCH DE ESCOLHER MENU } } break; } } break; } case SDLK_UP: // se apertar a tecla pra cima sobe { //========================================== Mix_PlayChannel(-1,som_selecao_movimento,0); //========================================== switch (Pagina) { case 0: { if( (MenuSelecionado==4) && (MostrarSimNao == 1) ) { MostrarSimNao = 0; SimOuNaoSelecionado = 0; } MenuSelecionado--; //DIMINUI O MENU if(MenuSelecionado == -1) //IMPEDE QUE PASSE DO LIMITE MenuSelecionado = 4; break; } case 1: { switch(MenuSelecionado) { case 2: { SubMenuSelecionado--; //AUMENTA O SUBMENU if(SubMenuSelecionado == -1)//IMPEDE QUE PASSE DO LIMITE SubMenuSelecionado = 3; break; } } } } break; } case SDLK_RIGHT: //FALTANDO HS //apertar para direita só irá acontecer na high score e nas opções { //============================================ Mix_PlayChannel(-1,som_selecao_movimento,0); //============================================ if( (Pagina == 0) && (MenuSelecionado == 4) && (MostrarSimNao == 1)) { SimOuNaoSelecionado++; if(SimOuNaoSelecionado > 1) SimOuNaoSelecionado--; } if((Pagina == 1) && (MenuSelecionado == 1)) { SubMenuSelecionado++; if (SubMenuSelecionado==1) SubMenuSelecionado--; } //talvez precise criar algo pra confirmação do apagar recordes if( (Pagina == 1) && (MenuSelecionado == 2) ) { switch (SubMenuSelecionado) { case 0: { EstadoOpcoes[0] = 0; break; } case 1: { EstadoOpcoes[1] = 0; break; } } } break; } case SDLK_LEFT: //FALTANDO HS //apertar para esquerda só irá acontecer na high score e nas opções { //========================================= Mix_PlayChannel(-1,som_selecao_movimento,0); //========================================= if( (Pagina == 0) && (MenuSelecionado == 4) && (MostrarSimNao == 1) ) { SimOuNaoSelecionado--; if(SimOuNaoSelecionado < 0) SimOuNaoSelecionado++; } if((Pagina == 1) && (MenuSelecionado == 1)) { SubMenuSelecionado--; if (SubMenuSelecionado == -1) SubMenuSelecionado++; } if( (Pagina == 1) && (MenuSelecionado == 2) ) { switch (SubMenuSelecionado) { case 0: { EstadoOpcoes[0] = 1; break; } case 1: { EstadoOpcoes[1] = 1; break; } } } break; } case SDLK_RETURN: // se apertar enter seleciona e entra na proxima tela ****DESENVOLVER UM MECANISMO PARA FINALIZAR**** { //===================================== Mix_PlayChannel(-1,som_selecao_enter,0); //====================================== switch (Pagina) { case 0: { if(MenuSelecionado == 4)//MENU SAIR { if(MostrarSimNao == 1)//ESTÁ MOSTRANDO SIM/NÃO { if(SimOuNaoSelecionado == 1)//SE SIM PG++ E SAI DA TELA { Pagina++; Sair = 1; } else MostrarSimNao = 0; //PARA DE MOSTRAR O SIM/NÃO } else { MostrarSimNao = 1;// SE NÃO ESTÁ MOSTRANDO, MOSTRA SimOuNaoSelecionado = 1;//SELECIONA O SIM } } else { Pagina++; // QUALQUER OUTRO MENU AUMENTA A PÁGINA if(MenuSelecionado == 0) Sair = 1; else SubMenuSelecionado = 0;//E COMEÇA NO INICIO DA TELA } break; } case 1: { switch(MenuSelecionado) { case 1://SUBMENU HIGHSCORES { //================================================= //SNK //==================================================== //==================================== mostra_recorde(screen); //===================================== Pagina = 0; MenuSelecionado = 0; switch (SubMenuSelecionado) { case 0: { if(MostrarSimNao == 0) MostrarSimNao == 1; else { if(SimOuNaoSelecionado == 1) { //FALTANDO //código pra zerar o HS } else MostrarSimNao = 0; } break; } case 1: { Pagina--; if(Pagina == -1) Pagina++; SubMenuSelecionado = 0; break; } } break; } case 2://SUBMENU OPÇÕES { if(SubMenuSelecionado == 2) { //FALTANDO Pagina++;//TELA QUE MOSTRA CONTROLES PG 2, MENU 2, SUB MENU 2 } if(SubMenuSelecionado == 3) Pagina --; break; } case 3: { if(SubMenuSelecionado == 0) { Pagina--; } break; } } break; } case 2: { switch(MenuSelecionado) { case 2: { if(SubMenuSelecionado == 2) Pagina--; break; } } break; } } break; } case SDLK_ESCAPE: { //======================================= Mix_PlayChannel(-1,som_selecao_enter,0); //====================================== if(Pagina > 0) { Pagina--; if(Pagina == 0) SubMenuSelecionado = -1; else SubMenuSelecionado = 0; break; } if(Pagina==0) { if( (MenuSelecionado == 4) && (MostrarSimNao == 1) ) MostrarSimNao = 0; else { MostrarSimNao = 1; SimOuNaoSelecionado = 1; MenuSelecionado = 4; } } break; } default: break; } } } //----------------------------------------------VISUALIZAÇÃO DO MENU BASEADA NOS EVENTOS----------------- SDL_BlitSurface(Fundo, NULL, screen, NULL); switch (Pagina) { case 0: //TELA INICIAL { for(i=0; i<5; i++) { if(i != MenuSelecionado) SDL_BlitSurface(surBotoesIniciais[i][0], NULL, screen, &rectBotoes[i]); else { BlitarBotaoSelecionado(surBotoesIniciais[i][1], rectBotoes[i], screen); rectMorcegoSelect.x = rectBotoes[i].x + surBotoesIniciais[i][1]->w + IncrementoDeSelecaoX + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotoes[i].y; } } if(MostrarSimNao == 1) { if(SimOuNaoSelecionado == 1) { SDL_BlitSurface(surBotaoSimNao[1][1], NULL, screen, &rectBotaoSimNao[1]); rectMorcegoSelect.x = rectBotaoSimNao[1].x + surBotaoSimNao[1][1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoSimNao[1].y; SDL_BlitSurface(surBotaoSimNao[0][0], NULL, screen, &rectBotaoSimNao[0]); } else { SDL_BlitSurface(surBotaoSimNao[1][0], NULL, screen, &rectBotaoSimNao[1]); SDL_BlitSurface(surBotaoSimNao[0][1], NULL, screen, &rectBotaoSimNao[0]); rectMorcegoSelect.x = rectBotaoSimNao[0].x + surBotaoSimNao[0][1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoSimNao[0].y; } } break; } case 1: //ALGUM SUBMENU { switch (MenuSelecionado) // VER QUAL É O SUBMENU EM RELAÇÃO À OPÇÃO ESCOLHIDA { case 0: //MENU INICIAR { if(Sair == 1) return 1; break; } case 1: // MENU HIGH SCORE { //****função que coloca o highscore na tela**** mostra_recorde(screen); Pagina = 0; /*rectBotaoVoltar.x = rectBotaoLimpar.x + AcrescimoXnoBotaoVoltar; rectBotaoVoltar.y = rectBotaoLimpar.y; if(SubMenuSelecionado == 0) { BlitarBotaoSelecionado(surBotaoLimpar[1], rectBotaoLimpar, screen); rectMorcegoSelect.x = rectBotaoLimpar.x + surBotaoLimpar[1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoLimpar.y; SDL_BlitSurface(surBotaoVoltar[0], NULL, screen, &rectBotaoVoltar); } if(SubMenuSelecionado == 1) { SDL_BlitSurface(surBotaoLimpar[0], NULL, screen, &rectBotaoLimpar); //rectSelecao.y = rectBotaoVoltar.y BlitarBotaoSelecionado(surBotaoVoltar[1], rectBotaoVoltar, screen); rectMorcegoSelect.x = rectBotaoVoltar.x + surBotaoVoltar[1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoVoltar.y; } if(MostrarSimNao == 1) { //FALTANDO //definir uma posição pro sim/não e blitar na tela }*/ break; } case 2: //OPÇÕES { for(i=0;i<3;i++) { if(i!=SubMenuSelecionado) { SDL_BlitSurface(surBotoesSubMenuOpcoes[i][0], NULL, screen, &rectBotoes[i]); } else { //rectSelecao.y = rectBotoes[i].y SDL_BlitSurface(surBotoesSubMenuOpcoes[i][1], NULL, screen, &rectBotoes[i]); rectMorcegoSelect.x = rectBotoes[i].x + surBotoesSubMenuOpcoes[i][1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotoes[i].y; } } rectBotaoVoltar.x = rectBotoes[2].x; rectBotaoVoltar.y = rectBotoes[2].y + AcrescimoYnoBotaoVoltar; if(SubMenuSelecionado != 3) { SDL_BlitSurface(surBotaoVoltar[0], NULL, screen, &rectBotaoVoltar); } else { SDL_BlitSurface(surBotaoVoltar[1], NULL, screen, &rectBotaoVoltar); rectMorcegoSelect.x = rectBotaoVoltar.x + surBotaoVoltar[1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoVoltar.y; } for(i=0;i<2;i++) { if(EstadoOpcoes[i] == 0) { if(i!=SubMenuSelecionado) SDL_BlitSurface(surBotaoOnOff[0][0], NULL, screen, &rectBotoesOnOff[i]); else { SDL_BlitSurface(surBotaoOnOff[0][1], NULL, screen, &rectBotoesOnOff[i]); } } else { if(i!=SubMenuSelecionado) SDL_BlitSurface(surBotaoOnOff[1][0], NULL, screen, &rectBotoesOnOff[i]); else { SDL_BlitSurface(surBotaoOnOff[1][1], NULL, screen, &rectBotoesOnOff[i]); } } } break; } case 3: //MENU SOBRE { SDL_BlitSurface(surMenuSobre, NULL, screen, &rectMenuSobre); rectBotaoVoltar.x = rectMenuSobre.x + ((surMenuSobre->w)/2); rectBotaoVoltar.y = rectMenuSobre.y + surMenuSobre->h + 50; rectMorcegoSelect.x = rectBotaoVoltar.x + surBotaoVoltar[1]->w -60; rectMorcegoSelect.y = rectBotaoVoltar.y; BlitarBotaoSelecionado(surBotaoVoltar[1], rectBotaoVoltar, screen); ControladorDeTempo++; break;//SAI DO SWITCH DE ESCOLHER MENU } case 4: { if(Sair == 1) { return -1; } } } break; } case 2: { switch (MenuSelecionado) { case 0: { if(SubMenuSelecionado == 0) { //programar para mostrar a tela de escolha de saves... } if(SubMenuSelecionado == 1) { //programar para mostrar a tela de escolha de personagens... } break; } case 2: { if(SubMenuSelecionado == 2) { //================================================== SDL_BlitSurface(FundoControles,NULL,screen,NULL); //================================================= for(i=0;i<5;i++) { SDL_BlitSurface(surMostrarControles[i], NULL, screen, &rectMostraControles[i]); } //================================================================================ TTF_SetFontStyle(fonte, TTF_STYLE_ITALIC); desenha_texto("Movimento para cima", screen, 220,100,fonte); TTF_SetFontStyle(fonte, TTF_STYLE_ITALIC); desenha_texto("Movimento para direita", screen, 220,180,fonte); TTF_SetFontStyle(fonte, TTF_STYLE_ITALIC); desenha_texto("Movimento para baixo", screen, 220,260,fonte); TTF_SetFontStyle(fonte, TTF_STYLE_ITALIC); desenha_texto("Movimento para esquerda", screen, 220, 340,fonte); TTF_SetFontStyle(fonte, TTF_STYLE_ITALIC); desenha_texto("Colocar bomba", screen, 230,410,fonte); //================================================================================ rectBotaoVoltar.x = rectMenuSobre.x + ((surMenuSobre->w)/2); rectBotaoVoltar.y = OySextoBotao; rectMorcegoSelect.x = rectBotaoVoltar.x + surBotaoVoltar[1]->w + AcrescimoEmXMorcego; rectMorcegoSelect.y = rectBotaoVoltar.y; SDL_BlitSurface(surBotaoVoltar[1], NULL, screen, &rectBotaoVoltar); ControladorDeTempo++; } } case 4: { if(MostrarSimNao == 1) { if(SimOuNaoSelecionado == 1) return -1; else { Pagina = 0; SimOuNaoSelecionado = 0; MostrarSimNao = 0; } } break; } } // e a de escolha de controles... break; } case 3: { //*PROGRAMAR AS AÇÕES BASEADO QUE PAGINA 3 SIGNIFICA QUE APERTOU O ENTER E VAI SAIR PARA DA FUNCAO if( (MenuSelecionado == 0) && (SubMenuSelecionado == 0) ) //DEFINE QUE VAI CONTINUAR DE ALGUM JOGO SALVO { quit = 1; /*switch () <<< vai definir qual é o continuar que vai ser acessado { case : { return 1; } case : { return 2; } }*/ } if( (MenuSelecionado == 0) && (SubMenuSelecionado == 1) ) //DEFINE QUE VAI COMEÇAR UM NOVO JOGO { //return 0; } if( (MenuSelecionado == 2) && (SubMenuSelecionado == 2) ) // TALVEZ ISSO SUMA, MAS É PARA SALVAR AS CONFIGURAÇÕES DE CONTROLE { } break; } } SDL_BlitSurface(surMorcegoSelect[ControladorMorcego], NULL, screen, &rectMorcegoSelect); SDL_Flip(screen); } //===================================== //Serve para liberar os sons(melhor dizendo, "descartá-los"...) Mix_FreeChunk(som_selecao_enter); Mix_FreeChunk(som_selecao_movimento); Mix_FreeMusic(musica_fundo); //====================================== }
int main(void) { // int good = 0; // int numeroMap = 0; // do{ // printf("Quelle map?\n"); // printf("1 - Original\n"); // printf("2 - Hard\n"); // printf("3 - Lol\n"); // printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n"); // scanf("%d", &numeroMap); // switch(numeroMap){ // case 1: // loadMap("../projec/map/original.map"); // good = 1; // break; // case 2: // loadMap("../projec/map/hard.map"); // good = 1; // break; // case 3: // loadMap("../projec/map/maplol.map"); // good = 1; // break; // case 4: // loadMap("../projec/map/rdastn.map"); // good = 1; // break; // case 42: // loadMap("../projec/map/rdastn.map"); // good = 1; // setQ(); // break; // } // }while(!good); //Create SDL objects SDL_Window *window = 0; SDL_Event event; SDL_Renderer *renderer = 0; int terminate = 0; //Initialise SDL if(SDL_Init(SDL_INIT_VIDEO) < 0){ printf("Error with SDL : %s\n", SDL_GetError()); SDL_Quit(); return EXIT_FAILURE; } window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN); terminate = 0; renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg"); SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu); SDL_FreeSurface(menu); SDL_RenderClear(renderer); int x, y; while(!terminate){ SDL_Rect dest = {0, 0, 544, 344}; SDL_RenderCopy(renderer, menuTexture, NULL, &dest); SDL_RenderPresent(renderer); SDL_WaitEvent(&event); switch(event.type){ case SDL_MOUSEBUTTONDOWN: x = event.motion.x; y = event.motion.y; if(x >= 57 && x <= (57+54) && y >= 94 && y <= (94 + 74)){ loadMap("../projec/map/original.map"); terminate = 1; } if(x >= 124 && x <= (124+53) && y >= 208 && y <= (208 + 73)){ loadMap("../projec/map/hard.map"); terminate = 1; } if(x >= 221 && x <= (221+59) && y >= 95 && y <= (95 + 80)){ loadMap("../projec/map/maplol.map"); terminate = 1; } if(x >= 311 && x <= (311+63) && y >= 208 && y <= (208 + 76)){ loadMap("../projec/map/rdastn.map"); terminate = 1; } if(x >= 350 && x <= (350+124) && y >= 73 && y <= (73 + 109)){ loadMap("../projec/map/rdastn.map"); terminate = 1; setQ(); } break; } SDL_Delay(1000 / FPS); } SDL_DestroyTexture(menuTexture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); //Search the pacman on the map and create him Pacman *pacman = getPacmanInstance(); unsigned int initialX = pacman->x; unsigned int initialY = pacman->y; Map *map = getMapInstance(); //If the pacman is not found if(!pacman){ printf("Pacman not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Pacman found !\n"); Ghost *clyde = searchAndCreateGhost(CLYDE); if(!clyde){ printf("Clyde not found on map\n"); freeMap(map); exit(EXIT_FAILURE); } printf("Clyde found !\n"); Ghost *blinky = searchAndCreateGhost(BLINKY); if(!blinky){ printf("Blinky not found on map\n"); freeMap(map); freeGhost(clyde); exit(EXIT_FAILURE); } printf("Blinky found !\n"); Ghost *inky = searchAndCreateGhost(INKY); if(!inky){ printf("Inky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); exit(EXIT_FAILURE); } printf("Inky found !\n"); Ghost *pinky = searchAndCreateGhost(PINKY); if(!pinky){ printf("Pinky not found on map\n"); freeMap(map); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); exit(EXIT_FAILURE); } printf("Pinky found !\n"); printf("SDL initialisation\n"); if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){ printf("%s", Mix_GetError()); } Mix_Music *music = NULL; music = Mix_LoadMUS("../projec/pacman.wav"); if(!music){ printf("Erreur de chargement de la musique %s \n", Mix_GetError()); }else{ Mix_VolumeMusic(MIX_MAX_VOLUME); Mix_PlayMusic(music, -1); } if(TTF_Init() == -1){ printf("Error during TTF initialization : %s\n", TTF_GetError()); } TTF_Font *police = NULL; police = TTF_OpenFont("../projec/monof.ttf", 65); if(!police){ printf("Error during font load : %s\n", TTF_GetError()); } SDL_Color color = { 255, 255, 255, 255}; //Create the window window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN); //If there is an error if(window == 0){ printf("Error during window creation : %s \n", SDL_GetError()); SDL_Quit(); freeMap(map); return EXIT_FAILURE; } int j; printf("SDL init success\n"); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //NEED gerer erreurs loadTextures(renderer); SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color); SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score); SDL_FreeSurface(score); char scoreString[15]; SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_Surface *scoreN; SDL_Texture *scoreTN; int open = 0; int konami[10] = {0,0,0,0,0,0,0,0,0,0}; //Infinite loop until we want to stop the game terminate = 0; while(!terminate){ SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20}; sprintf(scoreString, "%d", pacman->point); scoreN = TTF_RenderText_Solid(police, scoreString, color); scoreTN = SDL_CreateTextureFromSurface(renderer, score); renderMap(renderer); open = renderPacman(open, renderer); renderClyde(clyde, renderer); renderBlinky(blinky, renderer); renderPinky(pinky, renderer); renderInky(inky, renderer); changeDirectionGhost(blinky); changeDirectionGhost(clyde); changeDirectionGhost(inky); changeDirectionGhost(pinky); SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20}; SDL_RenderCopy(renderer, scoreT, NULL, &dest); SDL_RenderCopy(renderer, scoreTN, NULL, &dest2); SDL_RenderPresent(renderer); //Event handling SDL_PollEvent(&event); switch(event.type){ case SDL_KEYDOWN: switch(event.key.keysym.scancode){ case SDL_SCANCODE_UP: setPacmanDirection(NORTH); if(konami[0]){ if(konami[1]){ for(j = 0 ; j < 10 ; j++){ konami[j] = 0; } // printf("Déjà deux\n"); }else{ konami[1] = 1; } }else{ konami[0] = 1; } break; case SDL_SCANCODE_DOWN: setPacmanDirection(SOUTH); break; case SDL_SCANCODE_RIGHT: setPacmanDirection(EAST); break; case SDL_SCANCODE_LEFT: setPacmanDirection(WEST); break; default: break; } break; } terminate = update(clyde, blinky, inky, pinky); if(terminate){ if(pacman->life > 0 ){ pacman->life--; terminate = 0; pacman->x = initialX; pacman->y = initialY; } } if(event.window.event == SDL_WINDOWEVENT_CLOSE){ terminate = 1; } SDL_Delay(1000 / FPS); SDL_DestroyTexture(scoreTN); SDL_FreeSurface(scoreN); } printf("Score final : %d\n", pacman->point); Mix_FreeMusic(music); Mix_CloseAudio(); freeTextures(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); SDL_DestroyTexture(scoreT); freePacman(); freeGhost(clyde); freeGhost(blinky); freeGhost(inky); freeGhost(pinky); freeMap(); TTF_CloseFont(police); TTF_Quit(); return EXIT_SUCCESS; }
int menu(SDL_Renderer* Renderer){ SDL_Event event; SDL_Texture* cursor_texture = getTextureFromPath("BMPimages/Cursor/1.bmp", Renderer); ButtonMenu* startButton = malloc(sizeof(ButtonMenu)); ButtonMenu* exitButton = malloc(sizeof(ButtonMenu)); VolumeMenu* volumeButton = malloc(sizeof(VolumeMenu)); TTF_Font* Font = TTF_OpenFont("TTFtext/GOST-type-B-Standard.ttf", 1000); Mix_Music* musicMenu = Mix_LoadMUS("MIXmusic/space.flac"); GameStates state = IN_MENU; int x, y; int volumeOn = 1; SDL_Rect menuRect = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT}; SDL_Texture* array_menu_bg[BG_SPRITES]; size_t displace_menu_bg_2 = 0; size_t displace_menu_bg_3 = 0; size_t displace_menu_bg_4 = 0; Mix_PlayMusic(musicMenu, -1); initButtons(Renderer, Font, startButton, exitButton, volumeButton); initMenuBgSprites(Renderer, array_menu_bg); while(state == IN_MENU){ while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT){ state = EXIT; } if (event.type == SDL_MOUSEMOTION){ SDL_GetMouseState(&x, &y); if (isInsideRect(x, y, startButton->Rect)) startButton->cur_texture = startButton->mouseInside; else startButton->cur_texture = startButton->mouseOutside; if (isInsideRect(x, y, exitButton->Rect)) exitButton->cur_texture = exitButton->mouseInside; else exitButton->cur_texture = exitButton->mouseOutside; if (isInsideRect(x, y, volumeButton->Rect)){ if (volumeOn) volumeButton->cur_texture = volumeButton->mouseInside_volOn; else volumeButton->cur_texture = volumeButton->mouseInside_volOff; } else{ if (volumeOn) volumeButton->cur_texture = volumeButton->mouseOutside_volOn; else volumeButton->cur_texture = volumeButton->mouseOutside_volOff; } } if (event.type == SDL_MOUSEBUTTONDOWN){ SDL_GetMouseState(&x, &y); if (isInsideRect(x, y, startButton->Rect)) state = START; if (isInsideRect(x, y, exitButton->Rect)) state = EXIT; if (isInsideRect(x, y, volumeButton->Rect)){ if (volumeOn){ volumeOn = 0; Mix_PauseMusic(); volumeButton->cur_texture = volumeButton->mouseInside_volOff; } else{ volumeOn = 1; Mix_ResumeMusic(); volumeButton->cur_texture = volumeButton->mouseInside_volOn; } } } } SDL_SetRenderDrawColor(Renderer, 0xFF, 0xFF, 0xFF, 0xFF); SDL_RenderClear(Renderer); SDL_RenderCopy(Renderer, array_menu_bg[0], NULL, &menuRect); renderInfinityText(Renderer, array_menu_bg[1], &displace_menu_bg_2, 544, 2, 1); renderInfinityText(Renderer, array_menu_bg[2], &displace_menu_bg_3, 544, 2, 2); renderInfinityText(Renderer, array_menu_bg[3], &displace_menu_bg_4, 544, 2, 3); SDL_RenderCopy(Renderer, startButton->cur_texture, NULL, &startButton->Rect); SDL_RenderCopy(Renderer, volumeButton->cur_texture, NULL, &volumeButton->Rect); SDL_RenderCopy(Renderer, exitButton->cur_texture, NULL, &exitButton->Rect); showCursor(Renderer, cursor_texture); SDL_RenderPresent(Renderer); getFps(); waitForFps(35); } return state; }
void GameplayScreen::HandleCollisions() { // Check which node the player/AI occupies for (std::vector<Node*>::iterator iter = levelManager->GetLegalNodes().begin(); iter != levelManager->GetLegalNodes().end(); ++iter) { // Check if player is inside a node if (Utils::CollisionChecker(levelManager->GetPlayer()->GetBoundingRect(), (*iter)->GetBoundingRect())) { levelManager->GetPlayer()->UpdateNodes(*iter); if (levelManager->GetPlayer()->GetCurrentNode() != levelManager->GetPlayer()->GetPreviousNode()) { // Print the node ID that the player enters printf("Player is in node ID : %d\n", (*iter)->GetNodeId()); levelManager->GetPlayer()->SetPreviousDirection(levelManager->GetPlayer()->GetDirection()); } } // Iterate over each ghost for (std::vector<Ghost*>::iterator aiIter = levelManager->GetGhosts().begin(); aiIter != levelManager->GetGhosts().end(); ++aiIter) { // Check if a ghost is inside a node if (Utils::CollisionChecker((*aiIter)->GetBoundingRect(), (*iter)->GetBoundingRect())) { (*aiIter)->UpdateNodes(*iter); if ((*aiIter)->GetCurrentNode() != (*aiIter)->GetPreviousNode()) { // Print the node ID that the player enters //printf("blinky is in node ID : %d\n", (*iter)->GetNodeId()); (*aiIter)->SetPreviousDirection((*aiIter)->GetDirection()); } } } } // Check for collisions between the player/AI and the wall for (std::vector<Sprite*>::iterator iter = levelManager->GetWalls().begin(); iter != levelManager->GetWalls().end(); ++iter) { // Check if the player collides with a wall if (Utils::CollisionChecker(levelManager->GetPlayer()->GetSpriteRect(), (*iter)->GetBoundingRect())) { if (((levelManager->GetPlayer()->GetDirection() == DirectionEnum::Up) || (levelManager->GetPlayer()->GetDirection() == DirectionEnum::Down)) && ((levelManager->GetPlayer()->GetPreviousDirection() == DirectionEnum::Left) || (levelManager->GetPlayer()->GetPreviousDirection() == DirectionEnum::Right))) { levelManager->GetPlayer()->SetDirection(levelManager->GetPlayer()->GetPreviousDirection()); } else if (((levelManager->GetPlayer()->GetDirection() == DirectionEnum::Left) || (levelManager->GetPlayer()->GetDirection() == DirectionEnum::Right)) && ((levelManager->GetPlayer()->GetPreviousDirection() == DirectionEnum::Up) || (levelManager->GetPlayer()->GetPreviousDirection() == DirectionEnum::Down))) { levelManager->GetPlayer()->SetDirection(levelManager->GetPlayer()->GetPreviousDirection()); } else { levelManager->GetPlayer()->SetDirection(DirectionEnum::None); } levelManager->GetPlayer()->SetPosition(levelManager->GetPlayer()->GetCurrentNode()); } // Check if each ghost collides with a wall /*for (std::vector<Ghost*>::iterator aiIter = levelManager->GetGhosts().begin(); aiIter != levelManager->GetGhosts().end(); ++aiIter) { if (Utils::CollisionChecker((*aiIter)->GetBoundingRect(), (*iter)->GetBoundingRect())) { //printf("A collision has occured between the AI and a wall!\n"); int randVal = std::rand() % 4; // 4 is the number of moving states (*aiIter)->SetPosition((*aiIter)->GetCurrentNode()); (*aiIter)->SetDirection((DirectionEnum)randVal); } }*/ } // Check for collisions between player and consumable // NOTE: we must use iter++ instead of ++iter for (std::vector<Pellet*>::iterator iter = levelManager->GetPellets().begin(); iter != levelManager->GetPellets().end(); iter++) { if (Utils::CollisionChecker(levelManager->GetPlayer()->GetBoundingRect(), (*iter)->GetBoundingRect())) { if ((*iter)->GetType() == NodeTypeEnum::PowerPelletNode) { // Reverse the ghosts directions for (std::vector<Ghost*>::iterator iter = levelManager->GetGhosts().begin(); iter != levelManager->GetGhosts().end(); ++iter) { (*iter)->ReverseDirection(); (*iter)->EnterFrightenedState(0.55f); Ghost::ChangeState(GhostStateEnum::Frightened); Mix_PlayMusic(backgroundPower, -1); isPowerUpState = true; } } // Increment the score score += (*iter)->GetValue(); // Play the appropriate sound clip if ((*iter)->GetType() == PelletNode) { Mix_PlayChannel(-1, pop, 0); } else if ((*iter)->GetType() == PowerPelletNode) { Mix_PlayChannel(-1, powerUp, 0); } // Free memory, cleat the list, and break delete (*iter); levelManager->GetPellets().erase(iter); // The break is necessary for two reasons // 1) we stop checking for nodes once we found we collided with one // 2) if we allow iter to increment we will crash because we are erasing elements break; } } // Check player collision against the AI if (levelManager->GetPlayer()->IsAlive()) { for (std::vector<Ghost*>::iterator iter = levelManager->GetGhosts().begin(); iter != levelManager->GetGhosts().end(); ++iter) { if (Utils::CollisionChecker(levelManager->GetPlayer()->GetBoundingRect(), (*iter)->GetBoundingRect())) { if ((*iter)->IsFrightened()) { // Eat the ghost (*iter)->Respawn(); score += 500; // TODO adjust this Mix_PlayChannel(-1, eatEnemy, 0); } else { PlayerDeath(); } } } } }
/*! * Plays the music a number of times. * \param loops The number of times music is played. */ void SdlMixerMusic::play(int loops) const { Mix_PlayMusic(music_data_, loops); }
// メインループ void Game::MainLoop(void) { // 音楽再生 Mix_PlayMusic(music_main,-1); // イベント SDL_Event event; double next_frame = SDL_GetTicks(); double wait = 1000.0 / 60; // TOP画面 Top top; // PLAY画面 Play play; // ゲーム設定 Config config; // パズルの区画やブロックを並べる PuzzleManager puzzle_manager; // ブロックの集合 Block blocks[BLOCK_MAX] = {}; // 区画の集合 Section sections[SECTION_MAX] = {}; // ストップウォッチ boost::timer t; for (;;) { // すべてのイベントを処理する while (SDL_PollEvent(&event)) { // 終了 (QUIT イベントが発生するか、ESC キーが押されたら) if ((event.type == SDL_QUIT) || (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE)) return; // TOP画面 if (view_type == VIEW_TOP){ // イベント処理 int result = top.Event(&event, &config, &puzzle_manager, sections, blocks); if (result == ON){ view_type = VIEW_PLAY; } } // PLAY画面 if (view_type == VIEW_PLAY){ // イベント処理 play.Event(&event, &config, &puzzle_manager, sections, blocks, &t); } // 全画面共通 // キーボード操作 if (event.type == SDL_KEYDOWN){ // 右Shift if (event.key.keysym.sym == SDLK_RSHIFT){ // 設定初期化 config.Reset(); // ブロック未操作 play.SetFlagOperated(OFF); // 得点リセット puzzle_manager.ResetScore(); // 操作回数リセット play.SetNumberOfOperations(OFF); // クリア状況リセット play.SetPlayResult(OFF); // プレイ状況リセット play.Reset(); // TOP画面へ遷移 view_type = VIEW_TOP; } } } // 1秒間に60回Updateされるようにする if (SDL_GetTicks() >= next_frame) { Update(&config, &puzzle_manager, sections, &top, &play, blocks); // 描画 Draw(&config, sections, &top, &play, &puzzle_manager, blocks, &t); next_frame += wait; // CPU休ませる。どれくらいの数値がベスト…? SDL_Delay(3); } } }
// // StartSong // static void StartSong(bool loop) { if(music) Mix_PlayMusic(music, loop ? -1 : 0); }
void Music::Play(int times){ Mix_PlayMusic (music, times); }
void startscreen(SDL_Window *screen,uint *state,uint *grapset,uint *fullscreen) { /* Renderer (with VSync, nice !) */ SDL_Renderer *renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_PRESENTVSYNC|SDL_RENDERER_ACCELERATED); SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "0"); SDL_RenderSetLogicalSize(renderer, 256, 192); uint exit = 0; uint musicplay = 0; SDL_Rect srcintro = {0,0,256,192}; SDL_Rect desintro = {0,0,256,192}; SDL_Event keyp; /* Loading PNG */ SDL_Texture *intro = IMG_LoadTexture(renderer, DATADIR "/graphics/intro.png"); SDL_Texture *intromd = IMG_LoadTexture(renderer, DATADIR "/graphics/intromd.png"); /* Load audio */ Mix_Music *music = Mix_LoadMUS(DATADIR "/sounds/MainTitleN.ogg"); while (exit != 1) { /* Cleaning the renderer */ SDL_RenderClear(renderer); /* Put image on renderer */ if (*grapset == 0) SDL_RenderCopy(renderer, intro, &srcintro, &desintro); else SDL_RenderCopy(renderer, intromd, &srcintro, &desintro); /* Flip ! */ SDL_RenderPresent(renderer); /* Play music if required */ if (musicplay == 0) { musicplay = 1; Mix_PlayMusic(music, 0); } /* Check keyboard */ if ( SDL_PollEvent(&keyp) ) { if (keyp.type == SDL_KEYDOWN) { /* Key pressed */ if (keyp.key.keysym.sym == SDLK_c) { /* Change graphic set */ if (*grapset == 0) *grapset = 1; else *grapset = 0; } if (keyp.key.keysym.sym == SDLK_i) { /* Show instructions */ if (srcintro.y == 0) srcintro.y = 192; else { srcintro.y = 0; musicplay = 0; } } if (keyp.key.keysym.sym == SDLK_f) { /* Switch fullscreen/windowed */ if (*fullscreen == 0) { SDL_SetWindowFullscreen(screen,SDL_WINDOW_FULLSCREEN_DESKTOP); *fullscreen = 1; } else { SDL_SetWindowFullscreen(screen,0); *fullscreen = 0; } } if (keyp.key.keysym.sym == SDLK_SPACE) { /* Start game */ *state = 1; exit = 1; } if (keyp.key.keysym.sym == SDLK_ESCAPE) { /* Exit game */ exit = 1; *state = 6; } } } } /* Cleaning */ SDL_DestroyTexture(intro); SDL_DestroyTexture(intromd); SDL_DestroyRenderer(renderer); }
int main(void) { if(SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "SDL_Init( Error : %s\n", SDL_GetError()); exit(1); } SDL_Window *win = SDL_CreateWindow("Hello World !", 100, 100, 700, 700, SDL_WINDOW_SHOWN); if(win == NULL) { fprintf(stderr, "SDL_CreateWindow Error : %s\n", SDL_GetError()); exit(1); } SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(ren == NULL) { SDL_DestroyWindow(win); fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } SDL_Surface *bmp = SDL_LoadBMP("../media/wtf.bmp"); if(bmp == NULL) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); fprintf(stderr, "SDL_LoadBMP Error: %s \n", SDL_GetError()); SDL_Quit(); exit(1); } SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp); SDL_FreeSurface(bmp); if(tex == NULL) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); fprintf(stderr, "SDL_CreateTextureFromSurface Error :%s \n", SDL_GetError()); SDL_Quit(); exit(1); } if(Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) return false; SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); Mix_Music *music = NULL; SDL_Event event; bool running = false; int x = 0, y = 0; bool re = true; while(!running) { if(!re) exit(0); // execl("finalProject", NULL); if(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) running = true; if(event.type == SDL_MOUSEMOTION) { SDL_GetMouseState(&x, &y); if((x >= 66) && (x <= 550) && (y >= 638) && (y <= 700)) { re = true; } /*first sqr x - 66 y - 638 x - 550 y 638 x - 66 y - 700 x - 550 y - 700 */ else if((x >= 550) && (x <= 582) && (y >= 536) && (y <= 800)) { re = true; } /*second x - 550 y - 536 x 582 y 536 x - 550 y - 700 x 582 y 700 */ else if((x >= 66) && (x <= 550) && (y >= 536) && (y <= 590)) { re = true; } /* next x - 66 y - 536 x - 550 y - 536 x - 66 y - 590 x - 550 y - 590 */ else if((x >= 66) && (x <= 105) && (y >= 300) && (y <= 536)) { re = true; } /* next x - 66 y - 300 x - 105 y - 300 x - 66 y - 536 x - 105 y - 536 */ else if((x >= 105) && (x <= 335) && (y >= 300) && (y <= 342)) { re = true; } /* next x - 105 y - 300 x - 335 y - 300 x - 105 y - 342 x - 335 y - 342 */ else if((x >= 335) && (x <= 354) && (y >= 300) && (y <= 311)) { re = true; } /* next x - 335 y - 300 x - 354 y - 300 x - 335 y - 311 x - 354 y - 311 */ else if((x >= 346) && (x <= 354) && (y >= 237) && (y <= 300)) { re = true; } /* next x - 346 y - 237 x - 354 y - 237 x - 346 y - 300 x - 354 y - 300 */ else if((x >= 322) && (x <= 346) && (y >= 237) && (y <= 243)) { re = true; } /* next x - 322 y - 237 x - 346 y - 237 x - 322 y - 243 x - 346 y - 243 */ else if((x >= 322) && (x <= 330) && (y >= 200) && (y <= 237)) { re = true; } /* next x - 322 y - 200 x - 330 y - 200 x - 322 y - 237 x - 330 y - 237 */ else if((x >= 330) && (x <= 355) && (y >= 200) && (y <= 214)) { re = true; } /* next x - 330 y - 200 x - 355 y - 200 x - 330 y - 214 x - 355 y - 214 */ else if((x >= 346) && (x <= 355) && (y >= 180) && (y <= 200)) { re = true; } /* next x - 346 y - 180 x - 355 y - 180 x - 346 y - 200 x - 355 y - 200 */ else if((x >= 328) && (x <= 370) && (y >= 100) && (y <= 180)) { music = Mix_LoadMUS("../media/0111.wav"); if(music == NULL) { return false; } if(Mix_PlayMusic(music, -1) == -1) { return 1; } bmp = SDL_LoadBMP("../media/nice.bmp"); if(bmp == NULL) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); fprintf(stderr, "SDL_LoadBMP Error: %s \n", SDL_GetError()); SDL_Quit(); exit(1); } tex = SDL_CreateTextureFromSurface(ren, bmp); SDL_FreeSurface(bmp); if(tex == NULL) { SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); fprintf(stderr, "SDL_CreateTextureFromSurface Error :%s \n", SDL_GetError()); SDL_Quit(); exit(1); } //Mix_FreeMusic(music); SDL_RenderClear(ren); SDL_RenderCopy(ren, tex, NULL, NULL); SDL_RenderPresent(ren); SDL_Delay(10000); running = true; } else re = false; /* topchik x - 328 y - 100 x - 370 y - 100 x - 328 y - 178 x - 370 y - 178*/ } } } SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return 0; }
void Music::play(int loops) { Mix_PlayMusic((Mix_Music*)music_handle, loops); }
void Audio::PlayMusic(const int& music_id, const bool& loop) { assert(IsMusic(music_id)); Mix_PlayMusic(music[music_id], loop ? -1 : 1); }
void Music::play(int loops) { if (Mix_PlayMusic(m_music, loops) == -1) { fatalError("Mix_PlayChannel error:" + std::string(Mix_GetError())); } }
int main( int argc, char* args[] ) { quit = 0; Tile *tiles[ TOTAL_TILES ]; Timer fps; levelwon = 0; //Initialize if( init() == false ) { return 1; } if( TTF_Init() == -1 ) { return false; } //Initialize SDL_mixer if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 ) { return false; } //Load the files if( load_files() == false ) { return 1; } //Clip the tile sheeti if( Mix_PlayMusic( music, -1 ) == -1 ) { return 1; } clip_tiles(); if(!welcome)return 1; SDL_BlitSurface(welcome, NULL, screen, NULL ); SDL_Flip( screen ); SDL_Delay(6000); robin robinp; while(quit ==false) { if(level!= 1) { SDL_BlitSurface( prepare, NULL, screen, NULL ); SDL_Flip(screen); SDL_Delay(3000); } robinp.reset(); //Set the tiles if( set_tiles( tiles ) == false ) { return 1; } // SDL_Delay(3000); first=1; ///////////////////////////////////////////////////////////////////////////////////// while( quit == false && levelwon == 0)/////////////////////////////////// { //Start the frame timer fps.start(); //While there's events to handle while( SDL_PollEvent( &event ) ) { robinp.handle_events(); //If the user has Xed out the window if( event.type == SDL_QUIT ) { //Quit the program quit = true; } } SDL_BlitSurface( background, NULL, screen, NULL ); robinp.move(tiles); robinp.set_camera(); for( int t = 0; t < TOTAL_TILES; t++ ) { tiles[ t ]->show(); } for(int i=0;i< en_num;i++) { enemys[en_num]->show(); //robinp.reset(); } robinp.show(); showscore(); //Update the screen if( SDL_Flip( screen ) == -1 ) { return 1; } //Cap the frame rate if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND ) { SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() ); } } clean_up(tiles); level++; levelwon = 0; ///////////////////////////////////////////////////////////////////////////////////// //cout<<"out of level"; } SDL_FreeSurface( background ); SDL_FreeSurface( gameover ); SDL_FreeSurface( tileSheet ); //Free the music Mix_FreeMusic( music ); Mix_FreeChunk( jumpsou ); Mix_FreeChunk( coinsou ); Mix_FreeChunk( hitsou ); Mix_FreeChunk( diamoundsou ); //Close the font TTF_CloseFont( font ); //Quit SDL_mixer Mix_CloseAudio(); SDL_Quit(); //Quit SDL_ttf TTF_Quit(); return 0; }
int main(int, char**) { //initialise SDL system and the video subsystem if (SDL_Init(SDL_INIT_VIDEO) != 0) { QuitWithError("SDL_Init Error: "); } //Create a Window SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (win == nullptr) { QuitWithError("SDL_CreateWindow Error: "); } //SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN); Mix_Music *music = NULL; Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1; std::string basepath(SDL_GetBasePath()); music = Mix_LoadMUS((basepath + "background.wav").c_str()); Mix_PlayMusic(music, -1); Render* renderer = new Render(win); //Main loop flag bool quit = false; b2Vec2 Gravity(0.f, 0.0098f); b2World World(Gravity); string bgPath = basepath + "background22.bmp"; SDL_Surface* back = SDL_LoadBMP(bgPath.c_str()); SDL_Rect* backGroundRect = renderer->AddSurfaceToRenderer(back, 0, -600, 1.0f); Button button = Button(-200, -50, World, renderer); Door door = Door(600, -100, renderer); Level level = Level(World, renderer); Player player = Player(100, 500, World, renderer); vector<Cannon*> cannons; cannons.push_back(new Cannon(170, 350, World, renderer, 1)); cannons.push_back(new Cannon(1010, 50, World, renderer, 2)); cannons.push_back(new Cannon(170, 450, World, renderer, 1)); cannons.push_back(new Cannon(1010, 150, World, renderer, 2)); cannons.push_back(new Cannon(170, 550, World, renderer, 1)); cannons.push_back(new Cannon(1010, 250, World, renderer, 2)); MenuScene* menu = new MenuScene(1200, 100, renderer); SDL_Event e; //thread t1(&Process::run, Process((*(game)))); //Passing references //t1.detach(); //detaches from SDL mainline float prevTicks = SDL_GetTicks(); float currentTicks = SDL_GetTicks(); float FPS = 0; int fpsTimer = 0; SDL_Init(0); //game loop while (!quit) { World.Step(1 / 60.f, 6, 2); while (SDL_PollEvent(&e) != 0) { if (inputHandler.CheckInput(SDLK_ESCAPE, e)) { quit = true; } } if (menu->playBool == false && menu->quitBool == false) { renderer->DrawMenuScene(); menu->Update(renderer); } if (menu->playBool == true) { //PLAY GAME STATE int dir = player.Move(inputHandler, e); for (int i = 0; i < cannons.size(); i++) { cannons.at(i)->Update(); } SDL_Rect rec(player.spriteRect); rec.y = player.GetY(); for (int j = 0; j < cannons.size(); j++) { for (int i = 0; i < cannons.at(j)->fireballs.size(); i++) { if (cannons.at(j)->fireballs.at(i)->CheckCollision(&rec) == true) { std::cout << "Collision Detected!" << std::endl; player.Respawn(); button.setOnce(false); button.buttonBody->SetTransform(b2Vec2(880 / SCALE, 39 / SCALE), 0); door.spriteRect->x = -1000; door.spriteRect->y = -1000; player.prevPosX.clear(); player.prevPosY.clear(); player.count = 0; } } } button.Update(); if (button.CheckCollision(&rec) == true) { std::cout << "Collision Detected!" << std::endl; button.collision = true; button.spriteRect->x = -2000; button.spriteRect->y = -2000; button.buttonBody->SetTransform(b2Vec2(-2000, -2000), 0); //door.Draw(renderer); } if (door.CheckCollision(&rec) == true) { button.buttonBody->SetTransform(b2Vec2(880 / SCALE, 39/ SCALE), 0); std::cout << "Collision Detected!" << std::endl; player.Respawn(); button.setOnce(false); door.spriteRect->x = -1000; door.spriteRect->y = -1000; player.prevPosX.clear(); player.prevPosY.clear(); player.count = 0; player.Respawn(); menu->playBool = false; menu->quitBool = false; menu->backGroundRect->x = 0; menu->current = 0; button.collision = false; } if (button.collision == false) { door.DrawCage(renderer); } if (button.collision == true) { door.DrawNoCage(renderer); } int ticks = SDL_GetTicks(); int seconds = ticks / 50; int sprite = seconds % 8; renderer->Update(player.srcRect, player.dstRect, *player.LeftTexture, *player.RightTexture, *player.StandTexture, sprite, dir, player.moving, player.GetY()); player.dstRect.w = player.spriteRect.w; player.dstRect.h = player.spriteRect.h; player.dstRect.x = player.spriteRect.x; player.dstRect.y = player.spriteRect.y + 5; } if (menu->quitBool == true) { quit = true; } fpsthink(); if (fpsTimer == 60) { printf("%f\n", framespersecond); fpsTimer = 0; } fpsTimer++; } SDL_DestroyRenderer(renderer->ren); SDL_DestroyWindow(win); SDL_DestroyMutex(mutex); SDL_Quit(); return 0; }
void GameplayScreen::Initialize(Game* game) { // Load all content first LoadContent(game->renderer); arialFont = TTF_OpenFont("Resources/Fonts/ARIAL.TTF", Config::gridSize); SDL_SetTextureColorMod(TextureManager::GetTexture("wall"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_top_left"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_top_right"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_bottom_left"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_bottom_right"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_horizontal"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); SDL_SetTextureColorMod(TextureManager::GetTexture("wall_vertical"), Config::boardColor.r, Config::boardColor.g, Config::boardColor.b); nodeDisplayFlags[ID] = false; nodeDisplayFlags[G] = false; nodeDisplayFlags[H] = false; nodeDisplayFlags[F] = false; // Initialize variables score = 0; scoreTextRect.w = Config::gridSize * 6; scoreTextRect.h = Config::gridSize * 1.5; scoreTextRect.x = 4 * Config::gridSize; scoreTextRect.y = 32 * Config::gridSize; endGameMessage = "Game Over!"; isLevelOver = false; isDebugging = false; isPaused = false; isGameOver = false; isPowerUpState = false; livesTexture = TextureManager::GetTexture("playerLives"); livesRemaining = 2; // livesLeftRect.x intentionally not set here livesLeftRect.y = Config::gridSize * 32; // 32 is the vertical node offset livesLeftRect.w = Config::gridSize; livesLeftRect.h = Config::gridSize; SDL_Surface* pauseSurface = TTF_RenderText_Solid(arialFont, "PAUSED", SDL_Color{ 255, 255, 255 }); pauseTexture = SDL_CreateTextureFromSurface(game->renderer, pauseSurface); SDL_FreeSurface(pauseSurface); pauseSurface = NULL; // Create an instance of a level manager levelManager = LevelManager::Instance(); // Construct the level list std::vector<std::string> levelList; levelList.push_back("Level1-New.txt"); levelList.push_back("Level1Quick.txt"); levelList.push_back("Level1.txt"); levelList.push_back("PowerPelletLevel.txt"); levelList.push_back("Level0.txt"); levelManager->CreateLevelList("Resources/LevelData", levelList); // Initialize the level manager with the level list levelManager->InitializeLevel(); // Initialize the pathfinder with the legal playing nodes //pathfinder = new Pathfinder(levelManager->GetLegalNodes()); // Adjust the sound based on settings Mix_VolumeMusic(MIX_MAX_VOLUME * Config::musicVol); Mix_VolumeChunk(eatEnemy, MIX_MAX_VOLUME * Config::sfxVol); Mix_VolumeChunk(pop, MIX_MAX_VOLUME * Config::sfxVol); Mix_VolumeChunk(powerUp, MIX_MAX_VOLUME * Config::sfxVol); Mix_VolumeChunk(death, MIX_MAX_VOLUME * Config::sfxVol); // Play the background music Mix_PlayMusic(background, -1); // -1 means loop until stopped }
int main( int argc, char* args[] ) { SDL_Init(SDL_INIT_EVERYTHING); Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 1, 4096 ); //screen=SDL_SetVideoMode((LIN_MAX+1)*40,(COL_MAX+1)*40,32,SDL_FULLSCREEN/*SDL_SWSURFACE*/); screen=SDL_SetVideoMode(0,0,32,SDL_FULLSCREEN); TTF_Init(); font=TTF_OpenFont("font2.ttf",40); music=Mix_LoadMUS("bck.wav"); clear=SDL_LoadBMP("wooden_background.bmp"); apply_surface(0,0,clear,screen); if(mute==0) Mix_PlayMusic(music, -1 ); load_level("a"); print_level(); //welcome_message(); clear=SDL_LoadBMP("clear.bmp"); print_background(); burn=SDL_LoadBMP("fire.bmp"); background=SDL_LoadBMP("name_background.bmp"); message=TTF_RenderText_Solid(font,"Player 2",color1); apply_surface((COL_MAX+COL_START+2)*40,0,background,screen); apply_surface((COL_MAX+COL_START+2)*40+5,0,message,screen); SDL_Flip(screen); message=TTF_RenderText_Solid(font,"Player 1",color1); apply_surface((0)*40,0,background,screen); apply_surface((0)*40+5,0,message,screen); SDL_Flip(screen); player=SDL_LoadBMP("warrior_on_grass.bmp"); player1=SDL_LoadBMP("warrior1_on_grass.bmp"); obs[player2.lin][player2.col]=2; obs[player1.lin][player1.col]=3; print_hp(player2.hp,1,COL_MAX+COL_START+2); print_hp(player1.hp,1,0); print_mana(player2.mana,2,COL_MAX+COL_START+2); print_mana(player2.mana,2,0); time_ex=0; if(mute<=1) sound=Mix_LoadWAV("hit.wav"); print_level(); int start_t=0; put_arena_wall(); player1_load_save("player1"); player2_load_save("player2"); while(keystates[SDLK_ESCAPE]==NULL && player1.hp>0 && player2.hp>0) {flag_player=0; t=time(NULL); if(t-t1>=2) { start_t++; if(start_t>=4) { clear_arena_wall(); } t1=t; if(player2.mana<=99) { player2.mana++; print_mana(player2.mana,2,COL_MAX+COL_START+2); } if(player1.mana<=99) { player1.mana++; print_mana(player1.mana,2,0); } //load_level("a"); print_level(); player2.permission=player1.permission=0; } if(t-t2>=1) { t2=t; player2.permission_basic=player1.permission_basic=0; } up=keystates[SDLK_UP]; down=keystates[SDLK_DOWN]; right=keystates[SDLK_RIGHT]; left=keystates[SDLK_LEFT]; atack_left=keystates[SDLK_RCTRL]; atack_right=keystates[SDLK_RCTRL]; power1=keystates[SDLK_u]; power2=keystates[SDLK_i]; power3=keystates[SDLK_o]; power4=keystates[SDLK_p]; atack1_left=keystates[SDLK_z]; atack1_right=keystates[SDLK_z]; if(power1==1 && player2.mana>=10 && player2.hp<=90) { player2.mana-=10; player2.hp+=10; print_mana(player2.mana,2,COL_MAX+COL_START+2); print_hp(player2.hp,1,COL_MAX+COL_START+2); } if(power2==1 && player2.mana>=30 && player2.permission==0) { player2.mana-=30; player2.permission=1; if(max(player1.lin,player2.lin)-min(player1.lin,player2.lin)<=2 && max(player1.col,player2.col)-min(player1.col,player2.col)<=2) { player1.hp-=40+player2.fire_dmg*3/10-player1.fire_res*3/10; print_hp(player1.hp,1,0); } if(player2.lin-2<=0) beg1=1; else beg1=player2.lin-2; if(player2.lin+2>=LIN_MAX) end1=LIN_MAX; else end1=player2.lin+2; if(player2.col-2<=0) beg2=1; else beg2=player2.col-2; if(player2.col+2>=COL_MAX) end2=COL_MAX; else end2=player2.col+2; for(int i=beg1;i<=end1;i++) for(int j=beg2;j<=end2;j++) { if(obs[i][j]==0) { //get_burn(i,j); //burn=SDL_LoadBMP("fire.bmp"); apply_surface((j+COL_START)*40,i*40,burn,screen); } } print_mana(player2.mana,2,COL_MAX+COL_START+2); } if(power3==1 && player2.hp>10) { player2.hp-=10; player2.mana+=10; print_mana(player2.mana,2,COL_MAX+COL_START+2); print_hp(player2.hp,1,COL_MAX+COL_START+2); } if(atack_left==1 && player2.permission_basic==0) { player=SDL_LoadBMP("warrior_on_grass_left.bmp"); if(obs[player2.lin][player2.col-1]==3) { player2.permission_basic=1; player1.hp-=10+player2.attack/10-player1.block/10; print_hp(player1.hp,1,0); Mix_PlayChannel(-1, sound, 0); } } if(atack_right==1 && player2.permission_basic==0) { player=SDL_LoadBMP("warrior_on_grass.bmp"); if(obs[player2.lin][player2.col+1]==3) { player2.permission_basic=1; player1.hp-=10+player2.attack/10-player1.block/10; print_hp(player1.hp,1,0); Mix_PlayChannel(-1, sound, 0); } } if(up==1 && player2.lin>1) { time_ex++; if(obs[player2.lin-1][player2.col]==0) { obs[player2.lin][player2.col]=0; put_back(player2.lin,player2.col); player2.lin--; obs[player2.lin][player2.col]=2; } } if(down==1 && player2.lin<COL_MAX) { time_ex++; if(obs[player2.lin+1][player2.col]==0) { obs[player2.lin][player2.col]=0; put_back(player2.lin,player2.col); player2.lin++; obs[player2.lin][player2.col]=2; } } if(left==1 && player2.col>1) { time_ex++; if(obs[player2.lin][player2.col-1]==0) { obs[player2.lin][player2.col]=0; put_back(player2.lin,player2.col); player2.col--; obs[player2.lin][player2.col]=2; player=SDL_LoadBMP("warrior_on_grass_left.bmp"); } } if(right==1 && player2.col<LIN_MAX) { time_ex++; if(obs[player2.lin][player2.col+1]==0) { obs[player2.lin][player2.col]=0; put_back(player2.lin,player2.col); player2.col++; obs[player2.lin][player2.col]=2; player=SDL_LoadBMP("warrior_on_grass.bmp"); } } apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen); up=keystates[SDLK_w]; down=keystates[SDLK_s]; right=keystates[SDLK_d]; left=keystates[SDLK_a]; power1=keystates[SDLK_1]; power2=keystates[SDLK_2]; power3=keystates[SDLK_3]; power4=keystates[SDLK_4]; if(power1==1 && player1.mana>=10 && player1.hp<=90) { player1.mana-=10; player1.hp+=10; print_mana(player1.mana,2,0); print_hp(player1.hp,1,0); } if(power2==1 && player1.mana>=30 && player1.permission==0) { player1.mana-=30; player1.permission=1; if(max(player2.lin,player1.lin)-min(player1.lin,player2.lin)<=2 && max(player1.col,player2.col)-min(player1.col,player2.col)<=2) { player2.hp-=40+player1.fire_dmg*3/10-player2.fire_res*3/10; print_hp(player2.hp,1,COL_MAX+COL_START+2); } if(player1.lin-2<=0) beg1=1; else beg1=player1.lin-2; if(player1.lin+2>=LIN_MAX) end1=LIN_MAX; else end1=player1.lin+2; if(player1.col-2<=0) beg2=1; else beg2=player1.col-2; if(player1.col+2>=COL_MAX) end2=COL_MAX; else end2=player1.col+2; for(int i=beg1;i<=end1;i++) for(int j=beg2;j<=end2;j++) { if(obs[i][j]==0) { //get_burn(i,j); //burn=SDL_LoadBMP("fire.bmp"); apply_surface((j+COL_START)*40,i*40,burn,screen); } } print_mana(player1.mana,2,0); } if(power3==1 && player1.hp>10) { player1.hp-=10; player1.mana+=10; print_mana(player1.mana,2,0); print_hp(player1.hp,1,0); } if(atack1_left==1 && player1.permission_basic==0 && flag_player==0) { if(obs[player1.lin][player1.col-1]==2) { player1.permission_basic=1; player1=SDL_LoadBMP("warrior1_on_grass_left.bmp"); player2.hp-=10+player1.attack/10-player2.block/10; //SDL_FreeSurface(player); print_hp(player2.hp,1,COL_MAX+COL_START+2); /*player2=SDL_LoadBMP("hit_warrior_on_grass.bmp"); apply_surface(player2.col*40,player2.lin*40,player,screen);*/ SDL_Flip(screen); Mix_PlayChannel(-1, sound, 0); } } if(atack1_right==1 && player1.permission_basic==0 && flag_player==0) { if(obs[player1.lin][player1.col+1]==2) { player1.permission_basic=1; player1=SDL_LoadBMP("warrior1_on_grass.bmp"); player2.hp-=10+player1.attack/10-player2.block/10; print_hp(player2.hp,1,COL_MAX+COL_START+2); //SDL_FreeSurface(player); player2=SDL_LoadBMP("hit_warrior_on_grass.bmp"); /*apply_surface(player2.col*40,player2.lin*40,player,screen); SDL_Flip(screen);*/ Mix_PlayChannel(-1, sound, 0); } } if(up==1 && player1.lin>1) { time_ex++; if(obs[player1.lin-1][player1.col]==0) { obs[player1.lin][player1.col]=0; put_back(player1.lin,player1.col); player1.lin--; obs[player1.lin][player1.col]=3; } } if(down==1 && player1.lin<COL_MAX) { time_ex++; if(obs[player1.lin+1][player1.col]==0) { obs[player1.lin][player1.col]=0; put_back(player1.lin,player1.col); player1.lin++; obs[player1.lin][player1.col]=3; } } if(left==1 && player1.col>1) { time_ex++; if(obs[player1.lin][player1.col-1]==0) { obs[player1.lin][player1.col]=0; put_back(player1.lin,player1.col); player1.col--; obs[player1.lin][player1.col]=3; player1=SDL_LoadBMP("warrior1_on_grass_left.bmp"); } } if(right==1 && player1.col<LIN_MAX) { time_ex++; if(obs[player1.lin][player1.col+1]==0) { obs[player1.lin][player1.col]=0; put_back(player1.lin,player1.col); player1.col++; obs[player1.lin][player1.col]=3; player1=SDL_LoadBMP("warrior1_on_grass.bmp"); } } SDL_Delay(50); apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen); SDL_Flip(screen); SDL_PumpEvents(); } if(player2.hp>player1.hp) { player1=SDL_LoadBMP("dead_warrior1_on_grass.bmp"); apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen); message=TTF_RenderText_Solid(font,"Player 2 wins!",textColor); player2.money+=player2.hp+player2.mana+player1.money/50; player1.money+=player2.money/75+20; player2.xp+=100; player1.xp+=20; } else if(player2.hp!=player1.hp) { player=SDL_LoadBMP("dead_warrior_on_grass.bmp"); apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen); message=TTF_RenderText_Solid(font,"Player 1 wins!",textColor); player1.money+=player1.hp+player1.mana+player2.money/50; player2.money+=player1.money/75+20; player1.xp+=100; player2.xp+=20; } else { player1=SDL_LoadBMP("dead_warrior1_on_grass.bmp"); apply_surface((player1.col+COL_START)*40,player1.lin*40,player1,screen); player=SDL_LoadBMP("dead_warrior_on_grass.bmp"); apply_surface((player2.col+COL_START)*40,player2.lin*40,player,screen); message=TTF_RenderText_Solid(font,"Round draw!",textColor); int cash=(player2.money+player1.money)/2/25; player1.money+=cash; player2.money+=cash; player2.xp+=50; player1.xp+=50; } player1.save_player1("player1"); player2.save_player("player2"); Mix_CloseAudio(); Mix_OpenAudio(22050,MIX_DEFAULT_FORMAT,2,4096); sound=Mix_LoadWAV("win.wav"); Mix_PlayChannel(-1,sound,0); apply_surface(((COL_MAX+COL_START)/2-1)*40,(LIN_MAX/2-1)*40,message,screen); SDL_Flip(screen); SDL_Delay(2000); TTF_CloseFont(font); SDL_Quit(); return 0; }
void I_PlaySong (int handle, int _looping) { if(!music_initialized) return; if(--handle < 0 || handle >= MUSIC_TRACKS) return; if(!registered_tracks[handle].Track) return; #ifdef OSX if(MusicSequenceSetAUGraph(sequence, graph) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceSetAUGraph failed\n"); return; } if(MusicPlayerSetSequence(player, sequence) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerSetSequence failed\n"); return; } if(MusicPlayerPreroll(player) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerPreroll failed\n"); return; } UInt32 outNumberOfTracks = 0; if(MusicSequenceGetTrackCount(sequence, &outNumberOfTracks) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceGetTrackCount failed\n"); return; } for(UInt32 i = 0; i < outNumberOfTracks; i++) { MusicTrack track; if(MusicSequenceGetIndTrack(sequence, i, &track) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceGetIndTrack failed\n"); return; } struct s_loopinfo { MusicTimeStamp time; long loops; }LoopInfo; UInt32 inLength = sizeof(LoopInfo); if(MusicTrackGetProperty(track, kSequenceTrackProperty_LoopInfo, &LoopInfo, &inLength) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicTrackGetProperty failed\n"); return; } inLength = sizeof(LoopInfo.time); if(MusicTrackGetProperty(track, kSequenceTrackProperty_TrackLength, &LoopInfo.time, &inLength) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicTrackGetProperty failed\n"); return; } LoopInfo.loops = _looping ? 0 : 1; if(MusicTrackSetProperty(track, kSequenceTrackProperty_LoopInfo, &LoopInfo, sizeof(LoopInfo)) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicTrackSetProperty failed\n"); return; } } if(MusicPlayerStart(player) != noErr) { Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerStart failed\n"); return; } #else if(Mix_PlayMusic(registered_tracks[handle].Track, _looping ? -1 : 1) == -1) { Printf(PRINT_HIGH, "Mix_PlayMusic: %s\n", Mix_GetError()); current_track = 0; return; } // [Russell] - Hack for setting the volume on windows vista, since it gets // reset on every music change I_SetMusicVolume(snd_musicvolume); #endif current_track = handle; }
void SoundManager::playMusic(std::string id, int loop) { Mix_PlayMusic(m_music[id], loop); }
int main(int argc, char *argv[]) { Matrix projectionMatrix; Matrix modelMatrix; Matrix viewMatrix; init(); ShaderProgram program(RESOURCE_FOLDER "vertex_textured.glsl", RESOURCE_FOLDER "fragment_textured.glsl"); glUseProgram(program.programID); float lastFrameTicks = 0.0f; // float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; // float texCoords[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; // float vertices[] = {-0.09, -0.09, 0.09, -0.09, 0.09, 0.09, -0.09, -0.09, 0.09, 0.09, -0.09, 0.09}; Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 4096 ); SDL_Event event; bool done = false; /* Sprites courtesy of http://gooperblooper22.deviantart.com/art/Space-Invaders-Sprite-Sheet-135338373 */ GLuint spriteSheetTexture = LoadTexture("space_invaders_sprite_sheet_by_gooperblooper22.png"); GLuint white = LoadTexture("white.png"); GLuint textTexture = LoadTexture("font1.png"); Mix_Music *bgm = Mix_LoadMUS("bgm.mp3"); Mix_Chunk *missile = Mix_LoadWAV("157439__nengisuls__misslie-1.wav"); bool pressed = false; int score = 0; int currentIndex = 0; int state; const int numFrames = 2; float animation[] = {(74.0f/617.0f),(107.0f/617.0f)}; float animationElapsed = 0.0f; float framesPerSecond = 0.0004f; std::vector<SheetSprite> aliens; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } program.setProjectionMatrix(projectionMatrix); program.setModelMatrix(modelMatrix); program.setViewMatrix(viewMatrix); float ticks = (float)SDL_GetTicks()/1000; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; animationElapsed += 1/elapsed; if(animationElapsed > 1.0/framesPerSecond) { currentIndex++; animationElapsed = 0.0; if(currentIndex > numFrames-1) { currentIndex = 0; } } glClear(GL_COLOR_BUFFER_BIT); score = ticks; SheetSprite menu(spriteSheetTexture, 160.0f/617.0f, 1.0f/2035.0f, 250.0f/617.0f, 171.0f/2035.0f, 0.5); Entity text; Player cannon(spriteSheetTexture, 277.0f/617.0f, 227.0f/2035.0f, 26.0f/617.0f, 17.0f/2035.0f, 0.05); SheetSprite alien(spriteSheetTexture, animation[currentIndex], (225.0f/2035.0f), 22.0f/617.0f, 16.0f/2035.0f, 0.05); const Uint8 *keys = SDL_GetKeyboardState(NULL); switch (state) { case STATE_MAIN_MENU: menu.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, true); menu.draw(program); if (!Mix_PlayingMusic()) { Mix_PlayMusic(bgm, -1); } if (keys[SDL_SCANCODE_RETURN]) { state++; } break; case STATE_GAME_LEVEL: text.DrawText(program, textTexture, "Score:" + std::to_string(score), 0.075, 0, -0.23, 0.9); cannon.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, white, alien); cannon.draw(program); alien.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program, false); alien.draw(program); if (keys[SDL_SCANCODE_SPACE]) { Mix_PlayChannel( -1, missile, 0); Mix_VolumeChunk(missile, 15); } if (keys[SDL_SCANCODE_ESCAPE] && (state == 1)) { pressed = true; state++; } break; case STATE_PAUSE: if (Mix_PlayingMusic()) { Mix_PausedMusic(); } text.DrawText(program, textTexture, "Paused", 0.1, 0, -0.23, 0); if (keys[SDL_SCANCODE_ESCAPE] && pressed) { pressed = false; state--; } break; } SDL_GL_SwapWindow(displayWindow); } Mix_FreeMusic(bgm); Mix_FreeChunk(missile); Mix_Quit(); cleanup(); return 0; }
int main(int argc, char *argv[]) { /* Declare some variables */ SNDFILE *music_file = NULL; SF_INFO sfinfo; sfinfo.format = 0; printf("Audio visualizer for Comp 467\n"); printf("By: Jorenz Paragas, Carlos Henriquez, Joshua Licudo\n"); printf("----\n"); /* Check if the user provided a .wav file */ if (argc < 2) { fprintf(stderr, "Error: a .wav file was not provided.\n"); fprintf(stderr, "Usage: %s input.wav\n", argv[0]); return EXIT_FAILURE; } /* Open the .wav file */ music_file = sf_open(argv[1], SFM_READ, &sfinfo); if (music_file == NULL) { fprintf(stderr, "Cannot open .wav file: %s\n", argv[1]); return EXIT_FAILURE; } printf("Name of file: %s\n", argv[1]); printf("Sample rate: %d\n", sfinfo.samplerate); printf("Channels: %d\n", sfinfo.channels); /* The buffer size for libsndfile must be as large as the product of * the number of channels and the number of samples to be read */ const int buffer_size = SAMPLE_COUNT * sfinfo.channels; /* For a real-to-complex transform, according to the FFTW docs, * the expected size of the array is n / 2 + 1 */ const int out_buffer_size = buffer_size / 2 + 1; /* Declare the two buffers to hold the data and tell * FFTW how to calculate the frequencies */ double samples[buffer_size]; memset(&samples, 0, buffer_size); fftw_complex output[out_buffer_size]; fftw_plan plan = fftw_plan_dft_r2c_1d(buffer_size, samples, output, FFTW_ESTIMATE); if (plan == NULL) { fprintf(stderr, "Plan cannot be created.\n"); sf_close(music_file); return EXIT_FAILURE; } /* Start SDL */ if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError()); return EXIT_FAILURE; } atexit(SDL_Quit); /* Create the window */ SDL_Window *window = SDL_CreateWindow("Comp 467 Project", 10, 10, WINDOW_WIDTH, WINDOW_HEIGHT, 0); if (window == NULL) { fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError()); return EXIT_FAILURE; } /* Get the window's surface */ SDL_Surface *surface = SDL_GetWindowSurface(window); /* Initialize the random number generator */ srand(time(NULL)); /* Open the music file */ Mix_OpenAudio(sfinfo.samplerate, MIX_DEFAULT_FORMAT, sfinfo.channels, 4096); Mix_Music *music = Mix_LoadMUS(argv[1]); if (music == NULL) { fprintf(stderr, "Mix_LoadMUS error: %s\n", Mix_GetError()); } /* Start playing it */ Mix_PlayMusic(music, 0); /* Timer-related variables */ unsigned int start_time = SDL_GetTicks(); unsigned int last_time = start_time; unsigned int current_time = start_time; /* The main loop */ bool running = true; while (running) { /* Obtain any user input */ SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } } /* Based on the sample rate and the current time, * figure out what position to read the audio file from */ double seconds = (current_time - start_time) / 1000.0; //printf("Current time: %.2f\n", seconds); sf_count_t sample_pos = (int) sfinfo.samplerate * seconds; int result = sf_seek(music_file, sample_pos, SEEK_SET); if (result == -1) { running = false; } /* Read the samples */ int samples_read = sf_readf_double(music_file, samples, SAMPLE_COUNT); if (samples_read <= 0) { running = false; } /* Calculate the FFT */ fftw_execute(plan); /* Fill the screen with black first */ SDL_Rect surf_rect; surf_rect.w = WINDOW_WIDTH; surf_rect.h = WINDOW_HEIGHT; surf_rect.x = 0; surf_rect.y = 0; SDL_FillRect(surface, &surf_rect, SDL_MapRGB(surface->format, 0, 0, 0)); /* Draw all the rectangles */ int x_pos; for (x_pos = 0; x_pos < WINDOW_WIDTH; x_pos += 1) { SDL_Rect rect; /* Based on the rectangle's position, get a different * frequency; the second half of the buffer is useless * data, so ignore that portion */ double relative_pos = x_pos * 1.0f / WINDOW_WIDTH; int buf_range_max = out_buffer_size / 2; int index = (int) (relative_pos * buf_range_max); /* Figure out the normalized magnitude of the frequency */ double mag = sqrt(output[index][0] * output[index][0] + output[index][1] * output[index][1]); double norm_mag = mag * (1 / sqrt(buffer_size)); //printf("%d: %f\n", index, norm_mag); /* Set the rectangle's size */ rect.w = 1; rect.h = norm_mag * WINDOW_HEIGHT; /* Set the rectangle's lower left corner */ rect.x = x_pos; rect.y = WINDOW_HEIGHT - rect.h; /* Draw the rectangle to the screen */ SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format, 0, 0, 255)); } /* Update the display */ SDL_UpdateWindowSurface(window); /* Ensure that it runs around 30 FPS and also update the * timer variables */ current_time = SDL_GetTicks(); int delta = current_time - last_time; if (delta <= 33) { SDL_Delay(33 - delta); } last_time = current_time; } /* Stop the music and free its memory */ Mix_HaltMusic(); Mix_FreeMusic(music); /* Clean up and exit */ SDL_FreeSurface(surface); SDL_DestroyWindow(window); fftw_destroy_plan(plan); sf_close(music_file); return EXIT_SUCCESS; }
/* Callback function for restarting the currently-selected music */ void ContinueSong() { Mix_PlayMusic(mix_music, 0); Mix_HookMusicFinished(ContinueSong); }
void Music::Play(){ Mix_PlayMusic(msong,loop); }
//the massive main function int main(int argc, char* args[]) // Gets command line input { bool quit = false, playing = true, falling = true, held = false, paused = false, cheating = false; // All our miscellaneous bools to keep track of game states. int level = 0, lines = 0, score = 0, choice = 0, cheatseq = 0; Scores scores("gfx"); // Opens the uber camoflaged gfx file for getting highscores. Tricksy, eh? Uint32 start = 0; // A REALLY big int for keeping track of time srand(SDL_GetTicks()); // seeding the random... seed if( init() == false ) // Initialize SDL { cout << "Init fail" << endl; return 1; //ERR !!!! } block = load_image( "blocks.png" ); // load blocks if(block == NULL) { cout << "Error loading blocks.png" << endl; return 1; //ERR! } back = load_image( "back.png" ); // load background if(back == NULL) { cout << "Error loading back.png" << endl; return 1; //ERR! } smallblock = load_image( "smallblocks.png" ); // small blocks for next and hold if(smallblock == NULL) { cout << "Error loading smallblocks.png" << endl; return 1; //ERR! } title = load_image( "title.png" ); // title if(title == NULL) { cout << "Error loading title.png" << endl; return 1; //ERR! } cursor = load_image( "cursor.png" ); // cursor in menu if(cursor == NULL) { cout << "Error loading cursor.png" << endl; return 1; //ERR! } font = TTF_OpenFont("ProggyClean.ttf", FONTSIZE); // our font if(font == NULL) { cout << "Error loading ProggyClean.ttf" << endl; return 1; //Yup. Didn't load. } effect = Mix_LoadWAV( "pause.wav" ); // dee doo sound if(effect == NULL) { cout << "Mix_LoadWAV: " << Mix_GetError() << endl; } while(playing) // while the user hasn't quit { score = 0; quit = false; Mix_FadeOutMusic(100); // fades out the music (if playing) for menu. Mix_FreeMusic(music); // gets rid of any music we might have loaded if(XM == true) // load title music { music = Mix_LoadMUS("title.xm"); } else { music = Mix_LoadMUS("title.mp3"); } if(!music) { cout << "Mix_LoadMUS(\"title.mp3\"): %s\n" << Mix_GetError() << endl; // music didn't load... } Mix_PlayMusic(music, -1); // play it til the user can't stand it no mo'. for(int i = 600; i>=100; i--) // slowly bring up the title { while( SDL_PollEvent( &event ) ) // gets any recent events (mouse, keyboard, whatev) { if( event.type == SDL_QUIT ) // X button { i = 100; playing = false; quit = true; } else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) //escape { i = 100; // brings the title screen instantly } } SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); // fill screen black apply_surface( 200, i, title, screen ); // apply title if( SDL_Flip( screen ) == -1 ) // hand *screen to video card { return 1; //ERRRRRRR !! } SDL_Delay(2); // slows it down a wee bit. } apply_surface( 325, 402 + choice * 50, cursor, screen ); // display cursor numbers = TTF_RenderText_Blended(font, "START", fontColor); // start apply_surface( 350, 400, numbers, screen ); numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor); // high scores apply_surface( 350, 450, numbers, screen ); numbers = TTF_RenderText_Blended(font, "EXIT", fontColor); // exit apply_surface( 350, 500, numbers, screen ); if( SDL_Flip( screen ) == -1 ) { return 1; //ERRRRRRR !! } paused = true; //pause for menu while(paused && !quit) { while( SDL_PollEvent( &event ) ) // wait for events { if( event.type == SDL_QUIT ) { paused = false; playing = false; quit = true; } else if( event.type == SDL_KEYDOWN ) { switch(event.key.keysym.sym) { case SDLK_ESCAPE: paused = false; quit = true; playing = false; break; case SDLK_RETURN: switch(choice) { case 0: paused = false; break; case 1: scores.display(); break; case 2: paused = false; quit = true; playing = false; break; } break; case SDLK_DOWN: // down, move cursor down Mix_PlayChannel(-1, effect, 0); // dee doo sound if(choice < 2) { choice++; } else { choice = 0; } break; case SDLK_UP: // up, move cursor up Mix_PlayChannel(-1, effect, 0); // see above if(choice > 0) { choice--; } else { choice = 2; } break; } SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); apply_surface( 200, 100, title, screen ); apply_surface( 325, 402 + choice * 50, cursor, screen ); numbers = TTF_RenderText_Blended(font, "START", fontColor); apply_surface( 350, 400, numbers, screen ); numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor); apply_surface( 350, 450, numbers, screen ); numbers = TTF_RenderText_Blended(font, "EXIT", fontColor); apply_surface( 350, 500, numbers, screen ); if( SDL_Flip( screen ) == -1 ) { return 1; //ERRRRRRR !! } } } } if(!quit) // if the user didn't quit { Mix_FadeOutMusic(100); //fade out title music Mix_FreeMusic(music); //free it if(XM == true) // change to game music { music = Mix_LoadMUS("music.xm"); } else { music = Mix_LoadMUS("music.mp3"); } if(!music) { cout << "Mix_LoadMUS(\"music.mp3\"): %s\n" << Mix_GetError() << endl; // music didn't load... } Mix_PlayMusic(music, -1); SDL_Delay(1500); // wait for ba-ding! to finish } Tile *tile = NULL, *next = NULL, *next2 = NULL, *next3 = NULL, *hold = NULL, *blank = NULL; //current tile, next tiles 1 2 3, hold, and the tile used for switching hold setclips(); // set the clip boxes for tiles clearfield(); // initialize the field next = new Tile(); // inits new tiles next2 = new Tile(); next3 = new Tile(); while(!quit) { SDL_Delay(50); // wait a bit for the next block to drop tile = next; // next to current next = next2; // move nexts next2 = next3; next3 = new Tile(); // new next 3 if(!tile->check(0, 0)) // if the tile is colliding from the get go { tile->show(); if( SDL_Flip( screen ) == -1 ) { return 1; //ERRRRRRR !! } gameOver(); // THEN YOU LOSE! HA! scores.checkScore(score); // Did you get a high score? scores.save(); // save the high score file scores.display(); // display the current high scores quit = true; } falling = true; while(falling && !quit) // the there a lot of !quits from now on so it goes straight back to the menu { apply_surface( 0, 0, back, screen ); // background tile->show(); // show the current tile if(hold != NULL) { hold->disp(27,78); // display hold } next->disp(390, 78); // display nexts next2->disp(390, 158); next3->disp(390, 238); start = SDL_GetTicks(); // start the timer while( falling && SDL_GetTicks() - start < (1/((static_cast<double>(level)/25) + 1))*(SPEED - MINSPEED)+MINSPEED) // spiffy formula I took way to long to make for speeding up { while( SDL_PollEvent( &event ) ) // get events { if( event.type == SDL_QUIT ) // quit immediatly { clean(); exit(0); playing = false; } else if( event.type == SDL_KEYDOWN ) // was a key pressed? { switch( event.key.keysym.sym ) // what key was pressed? { case SDLK_LEFT: // move left tile->check(-1, 0); break; case SDLK_RIGHT: // move right tile->check(1, 0); break; case SDLK_z: // rotate CCW tile->rotate(CC); break; case SDLK_x: // rotate CW tile->rotate(CW); break; case SDLK_DOWN: // soft drop if(!tile->check(0,1)) // if it hits something as a result of dropping once { falling = false; // apply the tile } start = SDL_GetTicks(); // reset the timer break; case SDLK_UP: // hard drop while(tile->check(0,1)) // move it down til it cant any more { score += 2 * (level + 1); // you get points for being so daring! } start -= 1000; //Lock that sucka! break; case SDLK_n: // this is the cheat key. But you have to be cheating to use it ;D if(cheating) { delete tile; // basically just gives you new tiles tile = new Tile(); } break; case SDLK_ESCAPE: // back to main menu quit = true; break; case SDLK_k: //SUPER SECRET KYLE-MODE! block = load_image( "kyles.png" ); back = load_image( "kyleback.png" ); smallblock = load_image("smallkyles.png"); Mix_HaltMusic(); music = Mix_LoadMUS("rawk.mp3"); Mix_PlayMusic(music, -1); break; case SDLK_o: // back to original block = load_image( "blocks.png" ); back = load_image( "back.png" ); smallblock = load_image("smallblocks.png"); Mix_HaltMusic(); music = Mix_LoadMUS("music.mp3"); Mix_PlayMusic(music, -1); break; case SDLK_c: // hold if(hold && !held) // if there is something held and you haven't held yet this turn { blank = hold; // switch current and held hold = tile; tile = blank; } else if(!hold) // if you've never held { hold = tile; // hold current and make more tiles tile = next; next = next2; next2 = next3; next3 = new Tile(); } hold->reset(); // reset the x and y values of the tile held = true; break; case SDLK_p: // pause paused = true; Mix_PauseMusic(); // pause music Mix_PlayChannel(-1, effect, 0); // play the dee doo apply_surface( 0, 0, back, screen ); // cover the tiles numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // but keep the scores apply_surface( 550, 50, numbers, screen ); numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); apply_surface( 550, 120, numbers, screen ); if( SDL_Flip( screen ) == -1 ) // display screen { return 1; //ERRRRRRR !! } while(paused) { while(SDL_PollEvent( &event )) // get events { if( event.type == SDL_QUIT ) // quit immediatly { quit = true; paused = false; playing = false; } else if( event.type == SDL_KEYDOWN ) // key down? { switch( event.key.keysym.sym ) // what key? { case SDLK_ESCAPE: // unpause case SDLK_p: // unpause paused = false; break; case SDLK_UP: // CHEATING!! WOO!!! UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT A B. <3 CONTRA. if(cheatseq == 0 || cheatseq == 1) { cheatseq++; } else { cheatseq = 0; // if you screwed up } break; case SDLK_DOWN: if(cheatseq == 2 || cheatseq == 3) { cheatseq++; } else { cheatseq = 0; } break; case SDLK_LEFT: if(cheatseq == 4 || cheatseq == 6) { cheatseq++; } else { cheatseq = 0; } break; case SDLK_RIGHT: if(cheatseq == 5 || cheatseq == 7) { cheatseq++; } else { cheatseq = 0; } break; case SDLK_z: if(cheatseq == 8) { cheatseq++; } else { cheatseq = 0; } break; case SDLK_x: if(cheatseq == 9) { Mix_PlayChannel(-1, effect, 0); cheating = true; } else { cheatseq = 0; } break; default: cheatseq = 0; break; } } } } cheatseq = 0; // If you screwed up the cheat sequence Mix_ResumeMusic(); // play that funky music break; } apply_surface( 0, 0, back, screen ); // put the background up screen << *tile; //There. Overloading. Huzzah. if(hold != NULL) // display hold { hold->disp(27,78); } next->disp(390, 78); // display all the nexts next2->disp(390, 158); next3->disp(390, 238); numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); //display scores apply_surface( 550, 50, numbers, screen ); numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); //Pretty sweet you can use all the sweet string functions with a function that returns a string =D apply_surface( 550, 120, numbers, screen ); if( SDL_Flip( screen ) == -1 ) // show screen { return 1; //ERRRRRRR !! } } } numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // display scores apply_surface( 550, 50, numbers, screen ); numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); apply_surface( 550, 120, numbers, screen ); if( SDL_Flip( screen ) == -1 ) { return 1; //ERRRRRRR !! } SDL_Delay(1); } if(tile->check(0, 1) == 0) // if it can't fall any more { falling = false; // stop falling } } tile->apply(); // apply it to the pile held = false; // you can hold again! score += (level+1)*checklines(lines); // check the lines and score accordingly level = lines/10; // level up? delete tile; // delete the current tile so we don't get yelled at } delete next; // delete all the other tiles if you lost delete next2; delete next3; delete hold; } clean(); // uninitialize SDL and everything return 0; // RETURN THAT ZERO, BABY. } // Fin
/*Cette fonction sert de page d'accueil du jeu du Pendu, elle fait appel à la fonction jouer_Pendu quand l'utilisateur appuie sur "Entrer", et à la fin elle récupère l'indice du gagnant et le renvoie à son tour*/ int Accueil_Pendu(SDL_Surface *ecran, char *j1, char *j2) { //Déclaration des variables locales nécessaires pour la fonction. SDL_Surface *texte1 = NULL, *texte2 = NULL, *pendu = NULL; SDL_Rect positiontexte1, positiontexte2, positionpendu; SDL_Event event; TTF_Font *police1 = NULL, *police2 = NULL; SDL_Color couleurNoire = {0, 0, 0, 0}, couleurBlanche = {255, 255, 255, 0}; int continuer = 1, gagnant; Mix_Music *musique; //Création d'un pointeur de type Mix_Music Mix_VolumeMusic(MIX_MAX_VOLUME); musique = Mix_LoadMUS("../Music/Mini-jeux/pendu.ogg"); //Chargement de la musique Mix_PlayMusic(musique, -1); //Jouer infiniment la musique //Chargement de l'image du pendu pendu = IMG_Load("../images/Mini-jeux/Pendu10.png"); //Chargement de la police police1 = TTF_OpenFont("../Police/chata.ttf", 65); police2 = TTF_OpenFont("../Police/chata.ttf", 25); //Initialisation du texte texte1 = TTF_RenderText_Shaded(police1, "Le Pendu", couleurNoire, couleurBlanche); texte2 = TTF_RenderText_Shaded(police2, "Appuyer sur entrer pour commencer", couleurNoire, couleurBlanche); SDL_SetColorKey(texte1, SDL_SRCCOLORKEY, SDL_MapRGB(texte1->format, 255, 255, 255)); SDL_SetColorKey(texte2, SDL_SRCCOLORKEY, SDL_MapRGB(texte2->format, 255, 255, 255)); //Remplissage de l'écran principal avec la couleur blanche SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100)); //Initialisation des positions des différentes surfaces et textes positiontexte1.x = (ecran->w - texte1->w) / 2; positiontexte1.y = 0; positiontexte2.x = (ecran->w - texte2->w) / 2; positiontexte2.y = 250 + (ecran->h - texte2->h) / 2; positionpendu.x = (ecran->w / 2) - (pendu->w / 2); positionpendu.y = (ecran->h / 2) - (pendu->h / 2); //Remplissage de l'écran principal avec la couleur blanche SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100)); //Blit du texte de la page d'accueil SDL_BlitSurface(texte1, NULL, ecran, &positiontexte1); SDL_BlitSurface(texte2, NULL, ecran, &positiontexte2); //Blit de l'image du pendu SDL_BlitSurface(pendu, NULL, ecran, &positionpendu); //Mise à jour de l'écran SDL_Flip(ecran); /*Une boucle infine afin de maintenir l'affichage et quitter le programme quand l'utilisateur ferme la fenêtre*/ while (continuer) { SDL_PollEvent(&event); switch(event.type) { case SDL_QUIT: continuer = 0; break; //En cas d'apuui sur un bouton case SDL_KEYDOWN : //S'il s'agit du bouton "Entrer", appeler la fonction joueur_Pendu if(event.key.keysym.sym == SDLK_RETURN) gagnant = jouer_Pendu(ecran,j1,j2); continuer = 0; break; default: break; } } //Libération de la mémoire occupée par les surfaces et les polices et arrêt de la SDL TTF_CloseFont(police1); TTF_CloseFont(police2); SDL_FreeSurface(pendu); SDL_FreeSurface(texte1); SDL_FreeSurface(texte2); Mix_FreeMusic(musique); //Libération de la musique return gagnant; }
void handle_credit_music() { rw = SDL_RWFromMem(music_credit_ogg, music_credit_ogg_len); music = Mix_LoadMUS_RW(rw); Mix_PlayMusic(music, -1); }
void PlayMusic(Mix_Music* music) { //Play the music Mix_PlayMusic( music, -1 ); }