update_status ModulePlayer::Update()
{
	if (App->UI->GameEnd == false)
	{
		int speed = 1;
		current_animation1 = &idle_right;
		if (current_animation2 == &bobShot){
			if (bobShot.Finished()){
				current_animation2 = &idle_left;
				bobShot.Reset();
			}
		}
		else{
			current_animation2 = &idle_left;
		}
		current_animation_BaseLeft = &base_left;
		current_animation_lever = &lever;


		if (App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_REPEAT)
		{
			if (current_animation1 != &right)
			{
				lever.speed = -0.4f;
				base_left.speed = -0.4f;
				right.speed = -0.4f;
				current_animation1 = &right;
			}

			if (angle > -70.0)
				angle -= 2.0;



		}

		if (App->input->keyboard[SDL_SCANCODE_D] == KEY_STATE::KEY_REPEAT)
		{
			if (current_animation1 != &right)
			{
				lever.speed = 0.4f;
				base_left.speed = 0.4f;
				right.speed = 0.4f;
				current_animation1 = &right;
			}


			if (angle < 70.0)
				angle += 2.0;

			//////
		}



		currentTime = SDL_GetTicks();


		if (App->input->keyboard[SDL_SCANCODE_W] == KEY_STATE::KEY_DOWN && App->spheres->next_sphere_left == true || currentTime - lastTime > 8000)
		{

			App->spheres->active_left[App->spheres->last_sphere_left - 1]->speed.x = (sin(angle*PI / 180)) * SPEED;
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->speed.y = -(cos(angle*PI / 180)) * SPEED;

			if (current_animation2 != &bobShot)
			{
				current_animation2 = &bobShot;
			}
			Mix_PlayChannel(-1, App->audio->shoot, 0);
			App->spheres->next_sphere_left = false;
			lastTime = currentTime;
			hurry_up.Reset();
			booblesCounterDown_left++;
		}



		if (App->input->keyboard[SDL_SCANCODE_D] == KEY_STATE::KEY_IDLE
			&& App->input->keyboard[SDL_SCANCODE_A] == KEY_STATE::KEY_IDLE){

			current_animation1 = &idle_right;
			base_left.speed = 0.0f;
			lever.speed = 0.0f;
		}

		/*
		0 Blue
		1 Gray
		2 Red
		3 Yellow
		4 Green
		5 Black
		6 Orange
		7 Violet
		*/

		if (App->input->keyboard[SDL_SCANCODE_F1] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(BLUE);
		}
		if (App->input->keyboard[SDL_SCANCODE_F2] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(GRAY);
		}
		if (App->input->keyboard[SDL_SCANCODE_F3] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(RED);
		}
		if (App->input->keyboard[SDL_SCANCODE_F4] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(YELLOW);
		}
		if (App->input->keyboard[SDL_SCANCODE_F5] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(GREEN);
		}
		if (App->input->keyboard[SDL_SCANCODE_F6] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(BLACK);
		}
		if (App->input->keyboard[SDL_SCANCODE_F7] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(ORANGE);
		}
		if (App->input->keyboard[SDL_SCANCODE_F8] == KEY_STATE::KEY_DOWN)
		{
			App->spheres->active_left[App->spheres->last_sphere_left - 1]->ChangeColor(VIOLET);
		}

		if (App->input->keyboard[SDL_SCANCODE_O] == KEY_STATE::KEY_DOWN)
		{
			for (int i = 0; i < App->spheres->last_sphere_left - 1; i++)
			{
				if (App->spheres->active_left[i] == nullptr)
					continue;
				App->spheres->active_left[i]->ChangeColor(App->spheres->active_left[App->spheres->last_sphere_left - 1]->sphere_color);
			}
		}

	}
		else
		{
			current_animation1 = &idle_right;
			current_animation2 = &idle_left;
			base_left.speed = 0.0f;
			lever.speed = 0.0f;
		}
	// Draw everything --------------------------------------

	App->render->Blit(graphics, position.x - 172*SCREEN_SIZE, position.y - 7*SCREEN_SIZE, &bag_complete);
	App->render->Blit(graphics, position.x - 172 * SCREEN_SIZE, position.y - 7 * SCREEN_SIZE, &bag_incomplete);
	App->render->Blit(graphics, position.x - 111 * SCREEN_SIZE, position.y - 23 * SCREEN_SIZE, &top_base);
	App->render->Blit(graphics, position.x - 126 * SCREEN_SIZE, position.y - 7 * SCREEN_SIZE, &(current_animation_BaseLeft->GetCurrentFrame()));
	App->render->Blit(graphics, position.x - 82 * SCREEN_SIZE, position.y + 1 * SCREEN_SIZE, &(current_animation_lever->GetCurrentFrame()));
	SDL_RenderCopyEx(App->render->renderer, graphics, p_arrow_src, p_arrow_dst, angle, p_center, SDL_FLIP_NONE);
	App->render->Blit(graphics, position.x - 102 * SCREEN_SIZE, position.y, &blow);
	if (App->UI->GameEnd == false){

		if (currentTime - lastTime > 3000)
		{

			current_animation3 = &hurry_up;
			current_animation2 = &hurry_up_dragon;
			App->render->Blit(graphics, position.x - 165 * SCREEN_SIZE, position.y - 20 * SCREEN_SIZE, &(current_animation3->GetCurrentFrame()));
		}
	}
	App->render->Blit(graphics, position.x - 80 * SCREEN_SIZE, position.y - 2 * SCREEN_SIZE, &(current_animation1->GetCurrentFrame()));
	App->render->Blit(graphics, position.x - 122 * SCREEN_SIZE, position.y - 10 * SCREEN_SIZE, &(current_animation2->GetCurrentFrame()));
	App->render->Blit(graphics, position.x - 135 * SCREEN_SIZE, position.y + 1 * SCREEN_SIZE, &prev_bobble[Random]);

	
	

	return update_status::UPDATE_CONTINUE;
}
Example #2
0
int main(int argc, char* argv[]){


  SNDFMT* smpls = gen_sin_buffer();
  //  smpls = snd_load("/media/c5bcf67f-e9eb-4e12-be75-d8b6e09e27ba/olivier/hti/ginf/cpu-emu/cpu-emu/sin.table");
  

  /* // start SDL with audio support */
  
  if (SDL_Init (SDL_INIT_VIDEO|SDL_INIT_AUDIO) < 0)
    exit (-1);

  atexit (SDL_Quit);
  screen = SDL_SetVideoMode (640, 480, 16, SDL_HWSURFACE);

  if (screen == NULL)
    exit (-1);

  // open SMPFREQ, signed 8bit, system byte order,
  //      stereo audio, using 1024 byte chunks
  if(Mix_OpenAudio(SMPFREQ, AUDIO_S8, 1, WAVEFORM_LENGTH)==-1) {
    printf("Mix_OpenAudio: %s\n", Mix_GetError());
    exit(2);
  }
  
  Mix_AllocateChannels(SID_VOICES_NR);

  Mix_Chunk *sound = NULL; 
	
  sound = Mix_QuickLoad_RAW(smpls,WAVEFORM_LENGTH);

  if(sound == NULL) { 
     fprintf(stderr, "Unable to load WAV file: %s\n", Mix_GetError()); 
   } 
  
  int channel;
  int channel2;
  channel = Mix_PlayChannel(-1, sound, -1);
  //  channel2 = Mix_PlayChannel(-1, sound, -1);
  if(channel == -1) {
    fprintf(stderr, "Unable to play WAV file: %s\n", Mix_GetError());
  }

  

  init_SID(&sid);
  
  
  
  if(!Mix_RegisterEffect(channel, adsrEffect0, NULL, sid.voicea )) {
    printf("Mix_RegisterEffect: %s\n", Mix_GetError());
  }
  /*
  if(!Mix_RegisterEffect(channel, adsrEffect0, NULL, sid.voiceb )) {
	printf("Mix_RegisterEffect: %s\n", Mix_GetError());
  }
  if(!Mix_RegisterEffect(channel, adsrEffect0, NULL, sid.voicec )) {
	printf("Mix_RegisterEffect: %s\n", Mix_GetError());
  }
  */ 

  /*

	play time

  */
  struct sid_6581_voice  *voicea = sid.voicea;
  struct sid_6581_voice  *voiceb = sid.voiceb;
  struct sid_6581_voice  *voicec = sid.voicec;

  int i=0,j=0;
  for(i=0;i<3;i++){
	voicea->frequency = 23436;
	voicea->control =  voicea->control | SID_GATE ;
	SDL_Delay (50);
	voicea->frequency = 7382;
	voicea->attack=200;
	voicea->decay=20;
	voicea->sustain = 8;
	voicea->release=20;
	voicea->attack = 200;
	voicea->control =  voicea->control & ~SID_GATE ;
	SDL_Delay (500);

	voicea->frequency = 14764;
	voicea->attack=200;
	voicea->decay=20;
	voicea->sustain = 6;
	voicea->release=1000;
	voicea->control =  voicea->control | SID_GATE ;
	for(j=0;j<10;j++){
	  SDL_Delay (10);
	  voicea->frequency = 14764+14764*j*1/100;
	}
	voicea->control =  voicea->control & ~SID_GATE ;	
	voicea->control =  voicea->control | SID_GATE ;
	SDL_Delay (50);
	voicea->control =  voicea->control & ~SID_GATE ;
	SDL_Delay (50);
	voicea->frequency = 10440;
	voicea->control =  voicea->control | SID_GATE ;
	SDL_Delay (50);
	voicea->control =  ((((voicea->control & ~SID_GATE) | SID_SAWT ) & ~SID_PULS )  & ~SID_TRIA ) & ~SID_NOIS ;
	SDL_Delay (50);
	voicea->frequency = 7382;
	voicea->control =  voicea->control | SID_GATE ;
	SDL_Delay (50);
	voicea->control =  voicea->control & ~SID_GATE ;
	SDL_Delay (50);
  }
  /*
	two voices
  */
    
  voicea->frequency = 7382;
  voicea->attack=200;
  voicea->decay=200;
  voicea->sustain = 6;
  voicea->release=1000;

  voiceb->frequency = 9301;
  voiceb->attack=120;
  voiceb->decay=20;
  voiceb->sustain = 6;
  voiceb->release=1000;

  voicea->control =  voicea->control | SID_GATE | SID_PULS ;
  voiceb->control =  voiceb->control | SID_GATE | SID_SAWT ;
  SDL_Delay(400);
  voicea->control =  voicea->control & ~SID_GATE ;
  voiceb->control =  voiceb->control & ~SID_GATE ;
  SDL_Delay(300);

  sid.voicea->frequency = 7382;
  sid.voiceb->frequency = 8286;
  sid.voicea->control =  voicea->control | SID_GATE ;
  sid.voiceb->control =  voiceb->control | SID_GATE ;
  SDL_Delay(400);
  sid.voicea->control =  voicea->control & ~SID_GATE ;
  sid.voiceb->control =  voiceb->control & ~SID_GATE ;
  SDL_Delay(300);

  sid.voicea->frequency = 7382;
  sid.voiceb->frequency = 8779;
  sid.voicea->control =  voicea->control | SID_GATE ;
  sid.voiceb->control =  voiceb->control | SID_GATE ;
  SDL_Delay(400);
  sid.voicea->control =  voicea->control & ~SID_GATE ;
  sid.voiceb->control =  voiceb->control & ~SID_GATE ;
  SDL_Delay(300);

  sid.voicea->frequency = 7382;
  sid.voiceb->frequency = 9301;
  sid.voicea->control =  voicea->control | SID_GATE ;
  sid.voiceb->control =  voiceb->control | SID_GATE ;
  SDL_Delay(400);
  sid.voicea->control =  voicea->control & ~SID_GATE ;
  sid.voiceb->control =  voiceb->control & ~SID_GATE ;
  SDL_Delay(300);


  SDL_Event event;
  int done=0;

  interface_voice = sid.voicea;

  while(!done) {
	while(SDL_PollEvent(&event)) {
	    
	  switch(event.type) {
	  case SDL_KEYDOWN:	
		switch(event.key.keysym.sym){
		case SDLK_LEFT:
		  (sid.filter->volume - 1) < 0 ? 0 : sid.filter->volume--;
		  volume-=10;
		  Mix_VolumeChunk(sound, volume);
		  //		Mix_VolumeChunk(sound, (volume>MIX_MAX_VOLUME-10) ?  (volume = MIX_MAX_VOLUME):(volume-=10) );
		  printf("SDLK_LEFT volume: %i\n",volume);
		  break;
		case SDLK_RIGHT:
		  (sid.filter->volume + 1) >16 ? 15 : sid.filter->volume++;
		  volume+=10;
		  Mix_VolumeChunk(sound, volume );
		  //		Mix_VolumeChunk(sound, (volume<10) ?  (volume = 0): (volume+=10) );
		  printf("SDLK_RIGHT volume: %i\n",volume);
		  break;
		case SDLK_UP:
		  printf("up active\n");
		  break;
		case SDLK_DOWN:
		  printf("down active\n");
		  break;
		default:
		  handleKey(event.key);
		  break;
		}
		break;
	  case SDL_KEYUP:
		switch(event.key.keysym.sym){
		case SDLK_LEFT:

		  break;
		case SDLK_RIGHT:

		  break;
		case SDLK_UP:
		  interface_voice->frequency = interface_voice->frequency + interface_voice->frequency*1/100;
		  printf("up in-active\n");
		  break;
		case SDLK_DOWN:
		  interface_voice->frequency = interface_voice->frequency - interface_voice->frequency*1/100;
		  printf("down in-active\n");
		  break;
		default:
		  handleKey(event.key);
		  break;
		}
		break;
	  case SDL_QUIT:
		done = 1;
		printf("SDL_QUIT\n");
		break;
	  case SDL_MOUSEBUTTONUP:
		switch(event.button.button){
		case SDL_BUTTON_WHEELUP:
		  interface_voice->frequency = interface_voice->frequency + interface_voice->frequency*1/100;
		  break;
		case SDL_BUTTON_WHEELDOWN:
		  interface_voice->frequency = interface_voice->frequency - interface_voice->frequency*1/100;
		  break;
		}
		break;
	  default:
		/* do nothing */
		break;
	  }
	}
	  

	//	  SDL_Flip(screen);
	SDL_Delay (50);
  }

	
  Mix_FreeChunk(sound);
	
  Mix_CloseAudio();
  SDL_Quit();
  return 0; 
	

	
} 
Example #3
0
File: sounds.cpp Project: Foest/sdl
int main(int argc, char* args[])
{
  bool quit = false;

  if(init() == false)
  {
    return 1;
  }

  //Load the files
  if(load_files() == false)
  {
    std::cout << "1";
    return 1;
  }

  apply_surface(0, 0, background, screen);
  message = TTF_RenderText_Solid(font, "1, 2, 3, or 4 to play a sound effect", textColor);

  if(message == NULL)
  {
    return 1;
  }

  apply_surface((SCREEN_WIDTH - message->w) / 2, 100, message, screen);

  SDL_FreeSurface(message);

  message = TTF_RenderText_Solid(font, "Press 9 to play or pause the music", textColor);
  if(message == NULL)
  {
    return 1;
  }

  apply_surface((SCREEN_WIDTH - message->w) / 2, 200, message, screen);
  SDL_FreeSurface(message);
  message = TTF_RenderText_Solid(font, "Press 0 to stop the music", textColor);

  if(message == NULL)
  {
    return 1;
  }

  apply_surface((SCREEN_WIDTH - message->w) / 2, 300, message, screen);
  SDL_FreeSurface(message);


  if(SDL_Flip(screen) == -1)
    {
      return 1;
    }

  //While user hasn't quit
  while(quit == false)
  {
    while(SDL_PollEvent(&event))
    {
      if(event.type == SDL_KEYDOWN)
      {
        if(event.key.keysym.sym == SDLK_1)
        {
          if(Mix_PlayChannel(-1, scratch, 0) == -1)
          {
            return 1;
          }
        }

        else if(event.key.keysym.sym == SDLK_2)
        {
          if(Mix_PlayChannel(-1, high, 0) == -1)
          {
            return 1;
          }
        }

        else if(event.key.keysym.sym == SDLK_3)
        {
          if(Mix_PlayChannel(-1, med, 0) == -1)
          {
            return 1;
          }
        }

        else if(event.key.keysym.sym== SDLK_4)
        {
          if(Mix_PlayChannel(-1, low, 0) == -1)
          {
            return 1;
          }
        }

        else if(event.key.keysym.sym == SDLK_9)
        {
          if(Mix_PlayingMusic() == 0)
          {
            if(Mix_PlayMusic(music, -1) == -1)
            {
              return 1;
            }
          }


        else
        {
          if(Mix_PausedMusic() == 1)
          {
            Mix_ResumeMusic();
          }

          else
          {
            Mix_PauseMusic();
          }
        }
      }
      else if (event.key.keysym.sym == SDLK_0)
          {
            Mix_HaltMusic();
          }
      }

      if(event.type == SDL_QUIT)
      {
        quit = true;
      }
    }
  }

  clean_up();
  return 0;
}
Example #4
0
void handle_player_key_event(SDLKey key)
{
    if (current_player.state & (1<<0)
            || current_player.state & (1<<7)) // PLAYER DEAD, or plummeting
        return;
    int w = current_player.sprite->w;
    int h = current_player.sprite->h;

    switch (key){
        case SDLK_LEFT:
            if (current_player.x - map_draw_offsetx < 0){
                current_player.x = map_draw_offsetx;
            }
            if(current_player.vx > -current_player.max_speed){
                current_player.vx -= 0.1;
                current_player.facing_dir = 0;
            }
            break;
        case SDLK_RIGHT:
            if(current_player.vx < current_player.max_speed){
                current_player.vx += 0.1;
                current_player.facing_dir = 1;
            }
            break;
        case SDLK_UP:
            if(!(current_player.state & (1<<7))){
            if(current_player.near_blocks & (1 << 0) && //SOLID BLOCK BELLOW
                        !(current_player.near_blocks & (1<<4))){ //and no block above
                current_player.vy = -current_player.max_speed * 1;
                Mix_PlayChannel(-1, mix_jump, 0);
            }
            if(current_player.state & (1<<1))
                current_player.vy = -current_player.max_speed * 0.75;
            }
            break;
        case SDLK_DOWN:
            if(!(current_player.near_blocks & (1 << 0))){
                current_player.state |= (1 << 7);
                current_player.action_timeout = 20;
            } else {
                current_player.vx *= 0.9;
            }
            break;
        case SDLK_a:
            if (current_player.facing_dir){ // FACING RIGHT
                if (current_player.near_blocks & (1 << 2) && current_player.state & (1<<6)){
                    attempt_to_break_block(current_player.x + 3 * w/2, current_player.y + h/2);
                    current_player.sprite = ramr;
                }
            } else { // FACING LEFT
                if (current_player.near_blocks & (1 << 6) && current_player.state & (1<<6)){
                    attempt_to_break_block(current_player.x - w/2, current_player.y + h/2);
                    current_player.sprite = raml;
                }
            }

        default:
            break;
    }


}
Example #5
0
void HelpButton::ButtonPressed(Uint32 mouse_button_state)
{
    WidgetButtonBase::ButtonPressed(mouse_button_state);
    Mix_PlayChannel( -1, sound_effect, 0 );
}
Example #6
0
void initOnePlayer() {

    //Some initial values
    compv = 0.0;
    pause = 0;
    initBallStats();
    srand(time(NULL));
    pointsLeft = pointsRight = 0;
    act = -1;

    //Main loop
    while (quit==0)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT || event.type == SDL_MOUSEBUTTONDOWN) {
                quit = 1;
                canRun = mainMenu;
            }
            if (keystates[SDLK_p])
                pause = pause==1?0:1;
        }

        //Limiting the movement of the players
        if (yRight>=H_MAX-SIZEPLAYER) {
            yRight=H_MAX-SIZEPLAYER-1;
            compv *= -1;
        }
        if (yLeft>=H_MAX-SIZEPLAYER)
            yLeft=H_MAX-SIZEPLAYER;
            
        if (yRight<=H_MIN-SIZEPLAYER/2) {
            yRight=H_MIN-SIZEPLAYER/2+1;
            compv *= -1;
        }

        if (yLeft<=H_MIN-SIZEPLAYER/2)
            yLeft=H_MIN-SIZEPLAYER/2;

        
        if (pause == 0) {

            //Movement of the players
            if (keystates[SDLK_s])
            {
                yLeft+=6;
            }

            if (keystates[SDLK_w])
            {
                yLeft-=6;
            }
            
            if(ballx > WIDTH/2)
                if (bally > yRight)
                    compv+=COMP;
            else
                compv-=COMP;

            if (compv > 6) 
                compv = 6;
            else if (compv < -6) 
                compv = -6;
            
            yRight += (int)compv;

            //Physics of the ball ang limitation
            ballvy += gravity;
            bally +=(int)ballvy;
            ballx +=(int)ballvx;

            if (bally>=H_MAX-SIZEBALL) {
                ballvy *= -1.1;
                bally = H_MAX-SIZEBALL-1;
            }

            if (bally<=H_MIN-SIZEBALL) {
                ballvy *= -1.1;
                bally = H_MIN-SIZEBALL+1;
            }

            //Point of the left player
            if (ballx>=WIDTH-SIZEBALL){
                Mix_PlayChannel(-1, losesound, 0);
                initBallStats();
                SDL_Delay(2000);
                pointsLeft++;
                if (pointsLeft == 5) {
                    winner = 0;
                    quit = 1;
                    canRun = showWinner;
                    gameType = 0;
                    Mix_PlayChannel(-1, shallnotpass, 0);
                }
            }
            
            //Point of the right player
            if (ballx<=0){
                Mix_PlayChannel(-1, losesound, 0);
                initBallStats();
                SDL_Delay(2000);
                pointsRight++;
                if (pointsRight == 5) {
                    winner = 1;
                    gameType = 0;
                    quit = 1;
                    canRun = showWinner;
                    Mix_PlayChannel(-1, shallnotpass, 0);
                }
            }

            // Colision with the players.
            if (ballx <= xLeft+31 && bally >= yLeft-45 && bally <= yLeft+68)
            {
                Mix_PlayChannel(-1, boing, 0);
                ballvx *= -1.1;
                while (ballx <= xLeft+31)
                    ballx++;
                if (keystates[SDLK_s])
                    ballvy+=1;
                if (keystates[SDLK_w])
                    ballvy-=1;
            }

            if (ballx >= xRight-15 && bally >= yRight-45 && bally <= yRight+68){
                Mix_PlayChannel(-1, boing, 0);
                ballvx *= -1.1;
                while(ballx >= xRight-15)
                    ballx --;
                if (keystates[SDLK_l])
                    ballvy+=1;
                if (keystates[SDLK_o])
                    ballvy-=1;
            }
        }

        //For the tests with a orbit "robot" (to activate, use #define WITH_ROBOT 1)
        tmp = atan2(bally-roboty[ROBOT_PATH_SIZE-1], ballx-robotx[ROBOT_PATH_SIZE-1]);
        robotvx += 0.5*cos(tmp);
        robotvy += 0.5*sin(tmp);

        for (i = 0; i < ROBOT_PATH_SIZE-1; i++) {
            robotx[i] = robotx[i+1];
            roboty[i] = roboty[i+1];
        }

        robotx[ROBOT_PATH_SIZE-1] += robotvx;
        roboty[ROBOT_PATH_SIZE-1] += robotvy;

        
        if (robotvx > 10) robotvx = 10;
        if (robotvy > 10) robotvy = 10;


        //Limit the ball speed
        if (ballvx > 4) ballvx = 4;
        if (ballvy > 4) ballvy = 4;

        plotStuff2();
        SDL_Flip(screen);
        SDL_Delay(5);
    }

}
Example #7
0
int main(int argc, char* argv[]) {
    if(init()) {
        if(loadMedia()) {
            bool quit = false;
            SDL_Event e;
            Mix_PlayMusic(gMusic, -1);
            Uint8 prevTime = 0;
            Uint8 currTime = 0;
            Uint8 frameTime = 0;
            Uint8 totalFrameTime = 0;
            srand(time(NULL));
            while(!quit) {
                prevTime = currTime;
                currTime = SDL_GetTicks();
                frameTime = currTime - prevTime;
                totalFrameTime += frameTime;

                while(SDL_PollEvent(&e) != 0) {
                    if(e.type == SDL_QUIT) {
                        quit = true;
                    }
                    if(e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_p) {
                        if(!gamePaused) {
                            gamePaused = true;
                        }
                        else {
                            gamePaused = false;
                        }
                    }
                    if(!gamePaused && !gameOver && !gMenuButtons[OPTIONS].isClicked()) {
                        for(int i = PLAY; i < EXIT+1; i++) {
                            gMenuButtons[i].handleEvents(&e);
                        }
                    }
                    else if(gamePaused && !gameOver && !gMenuButtons[OPTIONS].isClicked()){
                        for(int i = RESUME; i < TOTAL_MENU_BUTTONS; i++) {
                            gMenuButtons[i].handleEvents(&e);
                        }
                    }
                    else if(gameOver) {
                        gNewGameButton.handleEvents(&e);
                        gMenuButtons[MAIN_MENU].handleEvents(&e);
                    }
                    else if(gMenuButtons[OPTIONS].isClicked()) {
                        gOptionButton.handleEvents(&e);
                    }

                    gMusicButton.handleEvents(&e);

                    if(gMenuButtons[PLAY].isClicked()) {
                        troy.handleEvents(&e);
                        zac.handleEvents(&e);
                        gBall.handleEvents(&e);
                    }
                }

                SDL_RenderClear(gRenderer);

                if(gMenuButtons[PLAY].isClicked()) {
                    if(!gamePaused && !gameOver) {
                        if(resetGame) {
                            troy.setNormalStance();
                            troy.setInitialPosition((SCREEN_WIDTH - troy.getTexture().getWidth())/2,(SCREEN_HEIGHT - troy.getTextureRealHeight()));
                            troy.setFacingDirection(RIGHT);
                            zac.setNormalStance();
                            zac.setInitialPosition((SCREEN_WIDTH - (zac.getTexture().getWidth())/3),(SCREEN_HEIGHT - zac.getTextureRealHeight()));
                            zac.setFacingDirection(RIGHT);
                            gBall.setPosition(100, SCREEN_HEIGHT - gBall.getTexture().getHeight());
                            gBall.setVelocity(0.0, 0.0);
                            troy.setInitialScore();
                            zac.setInitialScore();
                            resetGame = false;
                        }
                        while(totalFrameTime >= TIME_PER_FRAME) {
                            troy.update();
                            zac.update();
                            gBall.update();
                            troy.checkBallCollision();
                            zac.checkBallCollision();
                            troy.checkBasketballPoleCollision(&gBasketballPole);
                            zac.checkBasketballPoleCollision(&gBasketballPole);
                            troy.checkPlayerCollision(&zac);
                            zac.checkPlayerCollision(&troy);
                            totalFrameTime -= TIME_PER_FRAME;
                        }
                        if(!gBall.isPossessed()) {
                            gBall.checkCollisionWithPole();
                        }
                        gCourt.render(0, 0, &gCourtClip);\
                        if(troy.isBehindPlayer(&zac)) {
                            troy.render();
                            zac.render();
                        }
                        else {
                            zac.render();
                            troy.render();
                        }
                        gBall.render();
                        gBasketballPole.render();
                        troy.renderScoreIndicator();
                        zac.renderScoreIndicator();
                        if(troy.hasWon() || zac.hasWon()) {
                            gameOver = true;
                            SDL_Color textColor = {255, 0, 0, 0};
                            if(troy.hasWon()) {
                               gVictoryText.loadFromRenderedText(troy.getName() + " has won!", textColor);
                                troy.setVictory(false);
                            }
                            else {
                                gVictoryText.loadFromRenderedText(zac.getName() + " has won!", textColor);
                                zac.setVictory(false);
                            }

                            Mix_PlayChannel(-1, gCheer, 0);
                        }
                    }
                    else if(gamePaused && !gameOver){
                        gBackgroundTexture.render(0, 0, &gBackgroundClip);
                        gMenuButtons[RESUME].render();
                        gMenuButtons[MAIN_MENU].render();
                        if(gMenuButtons[RESUME].isClicked()) {
                            gamePaused = false;
                            gMenuButtons[RESUME].unclick();
                        }
                        else if(gMenuButtons[MAIN_MENU].isClicked()) {
                            gMenuButtons[PLAY].unclick();
                            gamePaused = false;
                            gMenuButtons[MAIN_MENU].unclick();
                        }
                    }
                    else if(gameOver) {
                        gVictoryBackgroundTexture.render(0, 0, &gVictoryBackgroundClip);
                        gVictoryText.render(100, 200);
                        gNewGameButton.render();
                        gMenuButtons[MAIN_MENU].render();
                        if(gNewGameButton.isClicked()) {
                            gameOver = false;
                            resetGame = true;
                            gNewGameButton.unclick();
                        }
                        else if(gMenuButtons[MAIN_MENU].isClicked()) {
                            gMenuButtons[PLAY].unclick();
                            gameOver = false;
                            gMenuButtons[MAIN_MENU].unclick();
                        }
                    }
                }
                else if(gMenuButtons[OPTIONS].isClicked()) {
                    gBackgroundTexture.render(0, 0, &gBackgroundClip);
                    gOptionButton.render();
                    if(gOptionButton.isClicked()){
                        gMenuButtons[OPTIONS].unclick();
                        gOptionButton.unclick();
                    }
                    gOptionText[0].render((SCREEN_WIDTH-gOptionText[0].getWidth())/2, 30);
                    gOptionText[1].render(50, 100);
                    gOptionText[2].render(20, 170);
                    gOptionText[3].render(20, 240);
                    gOptionText[4].render(20, 310);
                    gOptionText[5].render(20, 380);
                    gOptionText[6].render(20, 450);
                    gOptionText[7].render(20, 520);
                    gOptionText[8].render(20, 590);
                    gOptionText[9].render(SCREEN_WIDTH - gOptionText[9].getWidth() - 40, 100);
                    gOptionText[10].render(SCREEN_WIDTH - gOptionText[10].getWidth(), 170);
                    gOptionText[11].render(SCREEN_WIDTH - gOptionText[11].getWidth(), 240);
                    gOptionText[12].render(SCREEN_WIDTH - gOptionText[12].getWidth(), 310);
                    gOptionText[13].render(SCREEN_WIDTH - gOptionText[13].getWidth(), 380);
                    gOptionText[14].render(SCREEN_WIDTH - gOptionText[14].getWidth(), 450);
                    gOptionText[15].render(SCREEN_WIDTH - gOptionText[15].getWidth(), 520);
                    gOptionText[16].render(SCREEN_WIDTH - gOptionText[16].getWidth(), 590);
                }
                else if(gMenuButtons[EXIT].isClicked()) {
                    quit = true;

                    gBackgroundTexture.render(0, 0, &gBackgroundClip);

                    for(int j = PLAY; j < EXIT+1; j++) {
                        gMenuButtons[j].render();
                    }
                }
                else {

                    gBackgroundTexture.render(0, 0, &gBackgroundClip);

                    for(int j = PLAY; j < EXIT+1; j++) {
                        gMenuButtons[j].render();
                    }

                    if(!resetGame) {
                        resetGame = true;
                    }
                }

                gMusicButton.render();

                SDL_RenderPresent(gRenderer);
            }
        }
    }
    shutdown();
    return 0;
}
Example #8
0
   SDLSoundChannel(const ByteArray &inBytes, const SoundTransform &inTransform)
   {
      Mix_QuerySpec(&mFrequency, &mFormat, &mChannels);
      if (mFrequency!=44100)
         ELOG("Warning - Frequency mismatch %d",mFrequency);
      if (mFormat!=32784)
         ELOG("Warning - Format mismatch    %d",mFormat);
      if (mChannels!=2)
         ELOG("Warning - channe mismatch    %d",mChannels);

      if (sMusicFrequency==0)
      {
         sMusicFrequency = mFrequency;
      }

      mChunk = 0;
      mDynamicBuffer = new short[BUF_SIZE * STEREO_SAMPLES];
      memset(mDynamicBuffer,0,BUF_SIZE*sizeof(short));
      mSound = 0;
      mChannel = -1;
      mDynamicChunk.allocated = 0;
      mDynamicChunk.abuf = (Uint8 *)mDynamicBuffer;
      mDynamicChunk.alen = BUF_SIZE * sizeof(short) * STEREO_SAMPLES; // bytes
      mDynamicChunk.volume = MIX_MAX_VOLUME;
      mDynamicFillPos = 0;
      mSoundPos0 = 0;
      mDynamicDataDue = 0;

      mBufferAheadSamples = 0;//mFrequency / 20; // 50ms buffer

      // Allocate myself a channel
      for(int i=0;i<sMaxChannels;i++)
         if (!sUsedChannel[i])
         {
            IncRef();
            sDoneChannel[i] = false;
            sUsedChannel[i] = true;
            mChannel = i;
            break;
         }

      if (mChannel>=0)
      {
         FillBuffer(inBytes,true);
         // Just once ...
         if (mDynamicFillPos<1024)
         {
            mDynamicRequestPending = true;
            mDynamicChunk.alen = mDynamicFillPos * sizeof(short) * STEREO_SAMPLES;
            if (Mix_PlayChannel( mChannel , &mDynamicChunk,  0 ))
              onChannelDone(mChannel);
         }
         else
         {
            mDynamicRequestPending = false;
            // TODO: Lock?
            if (Mix_PlayChannel( mChannel , &mDynamicChunk,  -1 )<0)
              onChannelDone(mChannel);
         }
         if (!sDoneChannel[mChannel])
         {
            mSoundPos0 = getMixerTime(0);

            Mix_Volume( mChannel, inTransform.volume*MIX_MAX_VOLUME );
         }
      }
   }
Example #9
0
void CDemo::playSound(Mix_Chunk *sample)
{
	if (sample)
		Mix_PlayChannel(-1, sample, 0);
}
Example #10
0
void menu_logic(god_t *god){
	
	if(god->state.frame < 4){
		crunchball0_C0_0(god);
		crunchball0_R0_0(god);
		crunchball0_R0_1(god);
		crunchball0_U0_0(god);
		crunchball0_N0_0(god);
		crunchball0_C1_0(god);
		crunchball0_H0_0(god);
		crunchball0_B0_0(god);
		crunchball0_B0_1(god);
		crunchball0_B0_2(god);
		crunchball0_A0_0(god);
		crunchball0_A0_1(god);
		crunchball0_L0_0(god);
		crunchball0_L0_1(god);
		
		settings0_0(god);
		settings0_1(god);
		play0_0(god);
		stop0_0(god);
	} else if(god->state.frame < 8){
		crunchball1_C0_0(god);
		crunchball1_R0_0(god);
		crunchball1_R0_1(god);
		crunchball1_U0_0(god);
		crunchball1_N0_0(god);
		crunchball1_C1_0(god);
		crunchball1_H0_0(god);
		crunchball1_B0_0(god);
		crunchball1_B0_1(god);
		crunchball1_B0_2(god);
		crunchball1_A0_0(god);
		crunchball1_A0_1(god);
		crunchball1_L0_0(god);
		crunchball1_L1_0(god);
		
		settings1_0(god);
		settings1_1(god);
		play1_0(god);
		stop1_0(god);
	} else {
		crunchball2_C0_0(god);
		crunchball2_R0_0(god);
		crunchball2_R0_1(god);
		crunchball2_U0_0(god);
		crunchball2_N0_0(god);
		crunchball2_C1_0(god);
		crunchball2_H0_0(god);
		crunchball2_B0_0(god);
		crunchball2_B0_1(god);
		crunchball2_B0_2(god);
		crunchball2_A0_0(god);
		crunchball2_A0_1(god);
		crunchball2_L0_0(god);
		crunchball2_L1_0(god);
		
		settings2_0(god);
		settings2_1(god);
		play2_0(god);
		stop2_0(god);
	}
	
	if(god->state.frame < 4){
		if(god->state.menu_select == 0)
			select_settings0(god);
		else if(god->state.menu_select == 1)
			select_play0(god);
		else
			select_stop0(god);
	} else if(god->state.frame < 4){
		if(god->state.menu_select == 0)
			select_settings1(god);
		else if(god->state.menu_select == 1)
			select_play1(god);
		else
			select_stop1(god);
	} else { 
		if(god->state.menu_select == 0)
			select_settings2(god);
		else if(god->state.menu_select == 1)
			select_play2(god);
		else
			select_stop2(god);
	}
	
	if(god->keystate.lt == 1 && god->state.menu_select > 0){
		god->state.menu_select--;
		god->keystate.lt = 0;
		Mix_PlayChannel( -1, god->audio.sound_menu_change, 0 );
	}
	if(god->keystate.rt == 1 && god->state.menu_select < 2){
		god->state.menu_select++;
		god->keystate.rt = 0;
		Mix_PlayChannel( -1, god->audio.sound_menu_change, 0 );
	}
	
	if(god->keystate.ent == 1 ){
		if(god->state.menu_select == 0){
			god->state.menu = 0;
			god->keystate.ent = 0;
			god->state.settings = 1;
			god->state.settings_select = 0;
			Mix_PlayChannel( -1, god->audio.sound_menu_select, 0 );
		} else if(god->state.menu_select == 1){
			god->keystate.ent = 0;
			god->state.menu = 0;
			god->state.game = 1;
			god->state.score = 0;
			god->state.lives = 2;
			god->state.bounced = 0;
			god->state.ball_color = 15;
			god->state.ball_y = 50;
			god->state.paddle_x = 300;
			god->state.paddle_color = 12;
			god->state.paddle_color_delay = 0;
			god->state.ball_x_speed = 3;
			god->state.ball_y_speed = 2;
			Mix_PlayChannel( -1, god->audio.sound_menu_select, 0 );
		} else {
			god->scalar.quit = 1;
			Mix_PlayChannel( -1, god->audio.sound_menu_select, 0 );
		}
	}
	
}
Example #11
0
void playChunk(int idx) {
  if ( !useAudio ) return;
  Mix_PlayChannel(chunkChannel[idx], chunk[idx], 0);
}
int quizGame(Display *d)
{
  char rand_word[LENGTH], shuffle_word[LENGTH], original_word[LENGTH];
  char hintWord[HINTLENGTH];
  int i, word_size, j, yinit = 9, xinit, cnt=0, in, printHint=0, resetsent = 0;
  int hintNum=0;
  cell grid[H][W];
  entity *player, *door1, *door2, *rbutton, *hbutton;

  initGrid(grid);
  hintNum=enc_getWord(rand_word);
  enc_getHint(hintWord, hintNum-1);
  word_size = strlen(rand_word);
  rand_word[word_size]='\0';

  // here we make sure the word always apears in the middle
  xinit = (W/2) - (word_size/2);
  strcpy(shuffle_word, rand_word);
  enc_shuffle(shuffle_word, word_size);
  strcpy(original_word, shuffle_word);
  player = grid[8][3].foreground = newEntity(passable,P_R1,3,8);
  door1 = grid[7][W-4].background = newEntity(impassable,DOORCLOSED,W-4,7);
  door2 = grid[7][3].background = newEntity(impassable,DOORCLOSED,3,7);

  /* place the word in the grid */
  for (j=0; j<word_size; j++){
    enc_newLetter(grid, xinit+j, yinit, shuffle_word[j]);
  }
  makeBoundariesquizGame(grid);
  rbutton = grid[7][1].background = newEntity(impassable, RESETBUTTON,7,1);
  hbutton = grid[7][16].background = newEntity(impassable, HINTBUTTON,7,16);
  fillGrid(grid);   /* layer of floortiles */

  encGameDraw(d, grid, printHint, hintWord, resetsent, grid[yinit][player->x].background->type);

  /* MAIN LOOP */
  while(in!=10){

    in=input(d);

    if (grid[player->y][player->x].background == door1|| grid[player->y][player->x].background == door2) {
      freeEntityMem(grid);  /* free memory */
      return 0;
    }
    resetsent = 0;
    changeEntity(rbutton, RESETBUTTON);
    if( (in > 0) && (in < 5) ){ /*checks for arrowkeys */
      move(&grid[player->y][player->x],player->x,player->y,(direction)in,grid);
      printGrid(grid);
    }
    if (in == 9) { /*checks for spacebar */
      if(grid[player->y][player->x].background->type == DARROW) {// "$" is now the down arrow symbol
        enc_updateLetter(grid, player->y, player->x);
        Mix_PlayChannel( -1, d->zap, 0 );
        }
      else if(grid[player->y][player->x].background->type == UARROW) {
        enc_updateLetter(grid, player->y, player->x);
        Mix_PlayChannel( -1, d->zap, 0 );
      }
      else if(grid[player->y-1][player->x].background->type == RESETBUTTON) {
        for (i=0; i<word_size; i++){
          enc_newLetter(grid, xinit+i, yinit, original_word[i]);
        }
        resetsent = 1;
        changeEntity(rbutton, RBUTTON_PR);
        Mix_PlayChannel( -1, d->zap, 0 );
      }
      else if(grid[player->y-1][player->x].background == hbutton) {
        printHint = !printHint;
        if (hbutton->type == HINTBUTTON) {
          changeEntity(hbutton, HBUTTON_PR);
        }
        else {
          changeEntity(hbutton, HINTBUTTON);
        }
        Mix_PlayChannel( -1, d->zap, 0 );
      }
    }
    enc_updateWord(grid, yinit, xinit, shuffle_word);
    if(strcmp(shuffle_word, rand_word)==0){
      changeEntity(door1, DOOROPEN);
      changePassable(door1,passable);
      changeEntity(door2, DOOROPEN);
      changePassable(door2,passable);
    }
    printGrid(grid);
    encGameDraw(d, grid, printHint, hintWord, resetsent, grid[yinit][player->x].background->type);
    cnt++;
  }
  freeEntityMem(grid);  /* free memory */
  return 1;
}
Example #13
0
int main()
{
	int grid_rows = 6;
	int grid_cols = 6;

	int *grid = (int *)malloc(sizeof(int) * grid_rows * grid_cols);

	int audio_rate = 22050;
	Uint16 audio_format = AUDIO_S16SYS;
	int audio_channels = 6;
	int audio_buffers = 4096;

	SDL_Surface *screen;
	Mix_Chunk *sounds[NUM_SOUNDS];
	int channel;

	for(int i = 0; i < NUM_SOUNDS; i++)
	{
		sounds[NUM_SOUNDS] = NULL;
	}

	// Initialize Grid
	for(int i = 0; i < grid_rows; i++)
	{
		for(int j = 0; j < grid_cols; j++)
		{
			grid[grid_cols * i + j] = 0;

			if(i == 1) { grid[grid_cols * i + j] = 1; }
			if(i == 2) { grid[grid_cols * i + j] = 1; }
		}
	}


	if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
	{
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
	}

	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0)
	{
		printf("Unable to initialize audio: %s\n", Mix_GetError());
	}

	sounds[0] = Mix_LoadWAV("sounds/Piano.ff.C4.wav");
	sounds[1] = Mix_LoadWAV("sounds/Piano.ff.A4.wav");
	sounds[2] = Mix_LoadWAV("sounds/Piano.ff.D4.wav");
	sounds[3] = Mix_LoadWAV("sounds/Piano.ff.E4.wav");
	sounds[4] = Mix_LoadWAV("sounds/Piano.ff.G4.wav");
	sounds[5] = Mix_LoadWAV("sounds/Piano.ff.C5.wav");

	screen = SDL_SetVideoMode(320, 240, 0, SDL_ANYFORMAT);
	if(screen == NULL)
	{
		printf("Unable to set video mode: %s\n", SDL_GetError());
		return 1;
	}


	for(int i = 0; i < 4; i++)
	{
		for(int col = 0; col < grid_cols; col++)
		{
			for(int row = 0; row < grid_rows; row++)
			{
				if(grid[grid_cols * row + col] == 1)
				{
					Mix_PlayChannel(-1, sounds[row], 0);
					printf("Playing %i %i\n", row, col);
				}
			}

			SDL_Delay(300);
		}
	}


	SDL_Delay(1000);

	for(int i = 0; i < NUM_SOUNDS; i++)
	{
		Mix_FreeChunk(sounds[i]);
	}

	Mix_CloseAudio();
	SDL_Quit();

	return 0;
}
Example #14
0
void MenuManager::logic() {

	bool clicking_character = false;
	bool clicking_inventory = false;
	bool clicking_powers = false;
	bool clicking_log = false;
	ItemStack stack;
	
	hudlog->logic();
	enemy->logic();
	inv->logic();
	talker->logic();

	if (!inp->pressing[INVENTORY] && !inp->pressing[POWERS] && !inp->pressing[CHARACTER] && !inp->pressing[LOG])
		key_lock = false;
	
	// check if mouse-clicking a menu button
	act->checkMenu(inp->mouse, clicking_character, clicking_inventory, clicking_powers, clicking_log);

	// exit menu toggle
	if ((inp->pressing[CANCEL] && !inp->lock[CANCEL] && !key_lock && !dragging)) {
		inp->lock[CANCEL] = true;
		key_lock = true;
		if (menus_open) {
			closeAll(true);
		}
		else {
			exit->visible = !exit->visible;
		}
	}

	// inventory menu toggle
	if ((inp->pressing[INVENTORY] && !key_lock && !dragging) || clicking_inventory) {
		key_lock = true;
		if (inv->visible) {
			closeRight(true);
		}
		else {
			closeRight(false);
			inv->visible = true;
			Mix_PlayChannel(-1, sfx_open, 0);
		}
		
	}

	// powers menu toggle
	if ((inp->pressing[POWERS] && !key_lock && !dragging) || clicking_powers) {
		key_lock = true;
		if (pow->visible) {
			closeRight(true);
		}
		else {
			closeRight(false);
			pow->visible = true;
			Mix_PlayChannel(-1, sfx_open, 0);
		}
	}

	// character menu toggle
	if ((inp->pressing[CHARACTER] && !key_lock && !dragging) || clicking_character) {
		key_lock = true;
		if (chr->visible) {
			closeLeft(true);
		}
		else {
			closeLeft(false);
			chr->visible = true;
			Mix_PlayChannel(-1, sfx_open, 0);
		}
	}
	
	// log menu toggle
	if ((inp->pressing[LOG] && !key_lock && !dragging) || clicking_log) {
		key_lock = true;
		if (log->visible) {
			closeLeft(true);
		}
		else {
			closeLeft(false);
			log->visible = true;
			Mix_PlayChannel(-1, sfx_open, 0);
		}
	}
		
	if (MENUS_PAUSE) {
		pause = (inv->visible || pow->visible || chr->visible || log->visible || vendor->visible || talker->visible);
	}
	menus_open = (inv->visible || pow->visible || chr->visible || log->visible || vendor->visible || talker->visible);
	
	if (stats->alive) {
		int offset_x = (VIEW_W - 320);
		int offset_y = (VIEW_H - 416)/2;

		// handle right-click
		if (!dragging && inp->pressing[MAIN2] && !inp->lock[MAIN2]) {

			// activate inventory item
			if (inv->visible && isWithin( inv->carried_area, inp->mouse)) {
				inv->activate(inp);
				inp->lock[MAIN2] = true;
			}
		}
		
		// handle left-click
		if (!dragging && inp->pressing[MAIN1] && !inp->lock[MAIN1]) {
		
			// left side menu
			if (inp->mouse.x <= 320 && inp->mouse.y >= offset_y && inp->mouse.y <= offset_y+416) {
				if (chr->visible) {
				
					// applied a level-up
					if (chr->checkUpgrade(inp->mouse)) {
						inp->lock[MAIN1] = true;
						
						// apply equipment and max hp/mp
						items->applyEquipment(stats, inv->inventory[EQUIPMENT].storage);
						stats->hp = stats->maxhp;
						stats->mp = stats->maxmp;
					}
				}
				else if (vendor->visible) {
				
					if (inp->pressing[CTRL]) {
						inp->lock[MAIN1] = true;
						
						// buy item from a vendor
						if (!inv->full()) {
							stack = vendor->click(inp);
							if (stack.item > 0) {
								if( inv->full()) {
									// Can we say "Not enough place" ?
									vendor->itemReturn( stack);
								}
								else if( ! inv->buy( stack)) {
									// Can we say "Not enough money" ? (here or in MenuInventory::buy())
									vendor->itemReturn( stack);
								}
							}
						}
					}
					else {
						
						// start dragging a vendor item
						drag_stack = vendor->click(inp);
						if (drag_stack.item > 0) {
							dragging = true;
							drag_src = DRAG_SRC_VENDOR;
							inp->lock[MAIN1] = true;
						}
					}
				
				}
				else if (log->visible) {
				
					// click on a log tab to make it the active display
					if (isWithin(log->tabs_area, inp->mouse)) {
						log->clickTab(inp->mouse);
						inp->lock[MAIN1] = true;
					}
				}
			}
		
			// right side menu
			else if (inp->mouse.x >= offset_x && inp->mouse.y >= offset_y && inp->mouse.y <= offset_y+416) {
			
				// pick up an inventory item
				if (inv->visible) {
				
					if (inp->pressing[CTRL]) {
						inp->lock[MAIN1] = true;
						stack = inv->click(inp);
						if( stack.item > 0) {
							if (vendor->visible) {
								if( vendor->full()) {
									// Can we say "Not enough place" ?
									inv->itemReturn( stack);
								}
								else {
									// The vendor could have a limited amount of money in the future. It will be tested here.
									if (inv->sell(stack)) {
										vendor->add(stack);
									}
									else {
										inv->itemReturn(stack);
									}
								}
							}
							else {
								if (!inv->sell(stack)) {
									inv->itemReturn(stack);
								}
							}
						}
					}
					else {
						drag_stack = inv->click(inp);
						if (drag_stack.item > 0) {
							dragging = true;
							drag_src = DRAG_SRC_INVENTORY;
							inp->lock[MAIN1] = true;
						}
					}
				}
				// pick up a power
				else if (pow->visible) {
					drag_power = pow->click(inp->mouse);
					if (drag_power > -1) {
						dragging = true;
						drag_src = DRAG_SRC_POWERS;
						inp->lock[MAIN1] = true;
					}
				}
			}
			// action bar
			else if (isWithin(act->numberArea,inp->mouse) || isWithin(act->mouseArea,inp->mouse) || isWithin(act->menuArea, inp->mouse)) {
			
				// ctrl-click action bar to clear that slot
				if (inp->pressing[CTRL]) {
					act->remove(inp->mouse);
					inp->lock[MAIN1] = true;
				}
				// allow drag-to-rearrange action bar
				else if (!isWithin(act->menuArea, inp->mouse)) {
					drag_power = act->checkDrag(inp->mouse);
					if (drag_power > -1) {
						dragging = true;
						drag_src = DRAG_SRC_ACTIONBAR;
						inp->lock[MAIN1] = true;
					}
				}
				
				// else, clicking action bar to use a power?
				// this check is done by GameEngine when calling Avatar::logic()


			}
		}
		// handle dropping
		if (dragging && !inp->pressing[MAIN1]) {
			
			// putting a power on the Action Bar
			if (drag_src == DRAG_SRC_POWERS) {
				if (isWithin(act->numberArea,inp->mouse) || isWithin(act->mouseArea,inp->mouse)) {
					act->drop(inp->mouse, drag_power, 0);
				}
			}
			
			// rearranging the action bar
			else if (drag_src == DRAG_SRC_ACTIONBAR) {
				if (isWithin(act->numberArea,inp->mouse) || isWithin(act->mouseArea,inp->mouse)) {
					act->drop(inp->mouse, drag_power, 1);
				}
			}
		
			// rearranging inventory or dropping items
			else if (drag_src == DRAG_SRC_INVENTORY) {
			
				if (inv->visible && inp->mouse.x >= offset_x && inp->mouse.y >= offset_y && inp->mouse.y <= offset_y+416) {
					inv->drop(inp->mouse, drag_stack);
					drag_stack.item = 0;
				}
				else if (isWithin(act->numberArea,inp->mouse) || isWithin(act->mouseArea,inp->mouse)) {
					// The action bar is not storage!
					inv->itemReturn(drag_stack);

					// put an item with a power on the action bar
					if (items->items[drag_stack.item].power != -1) {
						act->drop(inp->mouse, items->items[drag_stack.item].power, false);
					}
				}
				else if (vendor->visible && isWithin(vendor->slots_area, inp->mouse)) {
					// vendor sell item
					if( vendor->full()) {
						// Can we say "Not enough place" ?
						inv->itemReturn( drag_stack);
					}
					else {
						if (inv->sell( drag_stack)) {
							vendor->add( drag_stack);
						}
						else {
							inv->itemReturn(drag_stack);
						}
					}
					drag_stack.item = 0;
				}
				else {
					// if dragging and the source was inventory, drop item to the floor
					
					// quest items cannot be dropped
					if (items->items[drag_stack.item].type != ITEM_TYPE_QUEST) {
						drop_stack = drag_stack;
						drag_stack.item = 0;
						drag_stack.quantity = 0;
					}
					else {
						inv->itemReturn(drag_stack);
					}
				}
			}
			
			else if (drag_src == DRAG_SRC_VENDOR) {

				// dropping an item from vendor (we only allow to drop into the carried area)
				if (inv->visible && isWithin( inv->carried_area, inp->mouse)) {
					if( inv->full()) {
						// Can we say "Not enough place" ?
						vendor->itemReturn( drag_stack);
					}
					else if( ! inv->buy( drag_stack, inp->mouse)) {
						// Can we say "Not enough money" ? (here or in MenuInventory::buy())
						vendor->itemReturn( drag_stack);
					}
					drag_stack.item = 0;
				}
				else {
					vendor->itemReturn(drag_stack);
				}
			}

			dragging = false;
		}

		exit->logic();
		if (exit->isExitRequested()) {
			done = true;
		}
	}
	
	// handle equipment changes affecting hero stats
	if (inv->changed_equipment || inv->changed_artifact) {
		items->applyEquipment(stats, inv->inventory[EQUIPMENT].storage);
		inv->changed_artifact = false;
		// the equipment flag is reset after the new sprites are loaded
	}

	// for action-bar powers that represent items, lookup the current item count
	for (int i=0; i<12; i++) {
		act->slot_enabled[i] = true;
		act->slot_item_count[i] = -1;
		
		if (act->hotkeys[i] != -1) {
			int item_id = powers->powers[act->hotkeys[i]].requires_item;
			if (item_id != -1 && items->items[item_id].type == ITEM_TYPE_CONSUMABLE) {
				act->slot_item_count[i] = inv->getItemCountCarried(item_id);
				if (act->slot_item_count[i] == 0) {
					act->slot_enabled[i] = false;
				}
			}
			else if (item_id != -1) {
			
				// if a non-consumable item power is unequipped, disable that slot
				if (!inv->isItemEquipped(item_id)) {
					act->slot_enabled[i] = false;
				}
			}
		}
	}

}
void PonscripterLabel::flushEventSub(SDL_Event &event)
{
    if (event.type == ONS_SOUND_EVENT) {
        if (music_play_loop_flag) {
            stopBGM(true);
            if (music_file_name)
                playSound(music_file_name, SOUND_OGG_STREAMING | SOUND_MP3, true);
        }
        else {
            stopBGM(false);
        }
    }
// The event handler for the mp3 fadeout event itself.  Simply sets the volume of the mp3 being played lower and lower until it's 0,
// and until the requisite mp3 fadeout time has passed.  Recommend for integration.  [Seung Park, 20060621]
    else if (event.type == ONS_FADE_EVENT) {
        if (skip_flag || draw_one_page_flag ||
            ctrl_pressed_status || skip_to_wait)
        {
            mp3fadeout_duration = 0;
            if (mp3_sample) SMPEG_setvolume(mp3_sample, 0);
        }

        Uint32 tmp = SDL_GetTicks() - mp3fadeout_start;
        if (tmp < mp3fadeout_duration) {
            tmp  = mp3fadeout_duration - tmp;
            tmp *= music_volume;
            tmp /= mp3fadeout_duration;

            if (mp3_sample) SMPEG_setvolume(mp3_sample, tmp);
        }
        else {
            SDL_RemoveTimer(timer_mp3fadeout_id);
            timer_mp3fadeout_id = 0;

            event_mode &= ~WAIT_TIMER_MODE;
            stopBGM(false);
            advancePhase();
        }
    }
    else if (event.type == ONS_MIDI_EVENT) {
#ifdef MACOSX
        if (!Mix_PlayingMusic()) {
            ext_music_play_once_flag = !midi_play_loop_flag;
            Mix_FreeMusic(midi_info);
            playMIDI(midi_play_loop_flag);
        }

#else
        ext_music_play_once_flag = !midi_play_loop_flag;
        Mix_FreeMusic(midi_info);
        playMIDI(midi_play_loop_flag);
#endif
    }
    else if (event.type == ONS_MUSIC_EVENT) {
        ext_music_play_once_flag = !music_play_loop_flag;
        Mix_FreeMusic(music_info);
        playExternalMusic(music_play_loop_flag);
    }
    else if (event.type == ONS_WAVE_EVENT) { // for processing btntim2 and automode correctly
        if (wave_sample[event.user.code]) {
            Mix_FreeChunk(wave_sample[event.user.code]);
            wave_sample[event.user.code] = NULL;
            if (event.user.code == MIX_LOOPBGM_CHANNEL0
                && loop_bgm_name[1]
                && wave_sample[MIX_LOOPBGM_CHANNEL1])
                Mix_PlayChannel(MIX_LOOPBGM_CHANNEL1,
                    wave_sample[MIX_LOOPBGM_CHANNEL1], -1);
        }
    }
}
Example #16
0
int main(int argc, char *argv[])
{
    int audio_rate;
    Uint16 audio_format;
    int audio_channels;
    int loops = 0;
    int i;
    int reverse_stereo = 0;
    int reverse_sample = 0;

#ifdef HAVE_SETBUF
    setbuf(stdout, NULL);    /* rcg06132001 for debugging purposes. */
    setbuf(stderr, NULL);    /* rcg06192001 for debugging purposes, too. */
#endif
    output_test_warnings();

    /* Initialize variables */
    audio_rate = MIX_DEFAULT_FREQUENCY;
    audio_format = MIX_DEFAULT_FORMAT;
    audio_channels = 2;

    /* Check command line usage */
    for ( i=1; argv[i] && (*argv[i] == '-'); ++i ) {
        if ( (strcmp(argv[i], "-r") == 0) && argv[i+1] ) {
            ++i;
            audio_rate = atoi(argv[i]);
        } else
        if ( strcmp(argv[i], "-m") == 0 ) {
            audio_channels = 1;
        } else
        if ( (strcmp(argv[i], "-c") == 0) && argv[i+1] ) {
            ++i;
            audio_channels = atoi(argv[i]);
        } else
        if ( strcmp(argv[i], "-l") == 0 ) {
            loops = -1;
        } else
        if ( strcmp(argv[i], "-8") == 0 ) {
            audio_format = AUDIO_U8;
        } else
        if ( strcmp(argv[i], "-f") == 0 ) { /* rcg06122001 flip stereo */
            reverse_stereo = 1;
        } else
        if ( strcmp(argv[i], "-F") == 0 ) { /* rcg06172001 flip sample */
            reverse_sample = 1;
        } else {
            Usage(argv[0]);
            return(1);
        }
    }
    if ( ! argv[i] ) {
        Usage(argv[0]);
        return(1);
    }

    /* Initialize the SDL library */
    if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
        return(255);
    }
#ifdef HAVE_SIGNAL_H
    signal(SIGINT, CleanUp);
    signal(SIGTERM, CleanUp);
#endif

    /* Open the audio device */
    if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, 4096) < 0) {
        fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
        CleanUp(2);
    } else {
        Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
        printf("Opened audio at %d Hz %d bit %s", audio_rate,
            (audio_format&0xFF),
            (audio_channels > 2) ? "surround" :
            (audio_channels > 1) ? "stereo" : "mono");
        if ( loops ) {
          printf(" (looping)\n");
        } else {
          putchar('\n');
        }
    }
    audio_open = 1;

#if (defined TEST_MIX_VERSIONS)
    test_versions();
#endif

#if (defined TEST_MIX_DECODERS)
    report_decoders();
#endif

    /* Load the requested wave file */
    wave = Mix_LoadWAV(argv[i]);
    if ( wave == NULL ) {
        fprintf(stderr, "Couldn't load %s: %s\n",
                        argv[i], SDL_GetError());
        CleanUp(2);
    }

    if (reverse_sample) {
        flip_sample(wave);
    }

#ifdef TEST_MIX_CHANNELFINISHED  /* rcg06072001 */
    Mix_ChannelFinished(channel_complete_callback);
#endif

    if ( (!Mix_SetReverseStereo(MIX_CHANNEL_POST, reverse_stereo)) &&
         (reverse_stereo) )
    {
        printf("Failed to set up reverse stereo effect!\n");
        printf("Reason: [%s].\n", Mix_GetError());
    }

    /* Play and then exit */
    Mix_PlayChannel(0, wave, loops);

    while (still_playing()) {

#if (defined TEST_MIX_PANNING)  /* rcg06132001 */
        do_panning_update();
#endif

#if (defined TEST_MIX_DISTANCE) /* rcg06192001 */
        do_distance_update();
#endif

#if (defined TEST_MIX_POSITION) /* rcg06202001 */
        do_position_update();
#endif

        SDL_Delay(1);

    } /* while still_playing() loop... */

    CleanUp(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}
void Sound_Manager::Play_Sound(Mix_Chunk * sample) {
	if (!mute && sample != NULL)
    	Mix_PlayChannel(-1, sample, 0);
}
Example #18
0
	void Sound::Play()
	{
		Mix_PlayChannel(-1,sample,0);
	}
Example #19
0
void CPlayer::Update(CMap* Map)
{
    int TilePos = 0;

    m_VelX = 5;
	m_VelY = 30;

	m_bScoreChanged = false;
	m_bLivesChanged = false;
	m_bCoinsChanged = false;

	m_bTouchesGround = false;

	//x axis first (--)
	if(m_bRight == true)
    {
        if (m_State != "JUMPING")
        {
            m_State = "WALKING_RIGHT";
        }
        else
        {
            m_State = "JUMPING";
        }

		if(Collision_Ver(m_PosX + m_Width + m_VelX, m_PosY, TilePos, Map) == 1)
        {
			m_PosX = (TilePos * Tile.GetSize()) - m_Width;
			Mix_PlayChannel(-1,cBlockhit,0);
        }
        else if (Collision_Ver(m_PosX + m_Width + m_VelX, m_PosY, TilePos, Map) == 2)
        {
            m_PosX = (TilePos * Tile.GetSize()) - m_Width;
            Mix_PlayChannel(-1,cBlockhit,0);
        }
        else if (Collision_Ver(m_PosX + m_Width + m_VelX, m_PosY, TilePos, Map) == 3) //Lava
        {
            m_VelX = 0;
            m_bDead = true;
            m_State = "DYING";
            m_Lives -= 1;
            m_bLivesChanged = true;
        }
        else if (Collision_Ver(m_PosX + m_Width + m_VelX, m_PosY, TilePos, Map) == 5) //Coins
        {
            m_PosX += m_VelX;
            m_Score += 100;
            m_bScoreChanged = true;
			m_Coins += 1;
			m_bCoinsChanged = true;
			Mix_PlayChannel(-1,cCoinCollected,0);

			Map->SetTileAtPos( (int) (m_PosX / 32), (int) (m_PosY / 32),0,0);
        }
		else
        {
            m_PosX += m_VelX;
        }
	}
	else if(m_bLeft)
	{
	    if (m_State != "JUMPING")
        {
            m_State = "WALKING_LEFT";
        }
        else
        {
            m_State = "JUMPING";
        }

		if(Collision_Ver(m_PosX - m_VelX, m_PosY, TilePos, Map) == 1)
        {
            m_PosX = (TilePos + 1)* Tile.GetSize();
            Mix_PlayChannel(-1,cBlockhit,0);
        }
        else if (Collision_Ver(m_PosX - m_VelX, m_PosY, TilePos, Map) == 2)
        {
            m_PosX = (TilePos + 1)* Tile.GetSize();
        }
        else if (Collision_Ver(m_PosX - m_VelX, m_PosY, TilePos, Map) == 3)
        {
            m_VelX = 0;
            m_State = "DYING";
            m_Lives -= 1;
            m_bLivesChanged = true;
        }
        else if (Collision_Ver(m_PosX - m_VelX, m_PosY, TilePos, Map) == 5) //Coins
        {
            m_PosX -= m_VelX;
            m_Score += 100;
            m_bScoreChanged = true;
			m_Coins += 1;
			m_bCoinsChanged = true;
			Mix_PlayChannel(-1,cCoinCollected,0);

			Map->SetTileAtPos( (int) ((m_PosX - m_VelX) / 32), (int) (m_PosY / 32),0,0);
        }
        else if (Collision_Ver(m_PosX, m_PosY, TilePos, Map) == 6) //
        {
            m_PosX = (TilePos + 1)* Tile.GetSize();
        }
		else
        {
            m_PosX -= m_VelX;
        }
	}

	//then y axis (|)
 	if(m_bIsJumping == true) //up
    {
        m_State = "JUMPING";

        Mix_PlayChannel(-1,cJump,0);

		if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 1)
        {
			m_PosY = (TilePos + 1)* Tile.GetSize();
			m_VelY = 0;
			m_bLockJump = true;
			m_bApexReached = true;
			if (m_bApexReached == true)
            {
                m_PosY += m_Gravity;
            }

			Mix_PlayChannel(-1,cBlockhit,0);
		}
		else if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 2)
        {
			m_PosY	-= m_VelY;
		}
		else if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 3)
        {
            m_VelX = 0;
            m_PosY += m_Gravity;
			m_State = "DYING";
            m_Lives -= 1;
            m_bLivesChanged = true;
		}
		else if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 5)
        {
			m_PosY	-= m_VelY;
			m_sScore = "";
			m_Score += 100;
			m_bScoreChanged = true;
			Mix_PlayChannel(-1,cCoinCollected,0);

			m_sCoins = "";
			m_Coins += 1;
			m_bCoinsChanged = true;

			Map->SetTileAtPos( (int) (m_PosX / 32), (int) (m_PosY / 32),0,0);

		}
		else if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 6)
        {
			m_PosY = (TilePos + 1)* Tile.GetSize();
			m_VelY = 0;
			Mix_PlayChannel(-1,cBlockhit,0);
		}
		else if(Collision_Hor(m_PosX, (m_PosY - m_VelY), TilePos, Map) == 7)
        {
			m_PosY = (TilePos + 1)* Tile.GetSize();
			m_VelY = 0;
		}
		else
        {
            if (m_bLockJump == false && m_bApexReached == false)
            {
                if (m_bOffsetIsSet == false)
                {
                    m_JumpOffset = m_PosY;
                    m_JumpApex = m_JumpOffset - m_JumpingHeight;
                    m_bOffsetIsSet = true;
                }

                if (m_PosY > m_JumpApex)
                {
                    m_PosY -= m_Gravity; //Move up at same speed like we move down
                }
                else if (m_PosY <= m_JumpApex)
                {
                    m_bApexReached = true;
                    m_bLockJump = true;
                }
            }

            if (m_bApexReached == true)
            {
                m_PosY += m_Gravity;
            }
		}
	}
	else
    {
		if(Collision_Hor(m_PosX, (m_PosY + m_Gravity + m_Height), TilePos, Map) == 1)
		{
            m_PosY = (TilePos * Tile.GetSize()) - m_Height - m_Gravity;
			m_VelY = 0;

			m_bTouchesGround = true;
			m_bIsJumping = false;
			m_bLockJump = false;
			m_bApexReached = false;

		}
		else if(Collision_Hor(m_PosX, (m_PosY + m_Gravity + m_Height), TilePos, Map) == 2)
		{
			m_PosY = (TilePos * Tile.GetSize()) - m_Height - m_Gravity;
			m_VelY = 0;

			m_bTouchesGround = true;
			m_bIsJumping = false;
			m_bLockJump = false;
			m_bApexReached = false;
		}
		else if(Collision_Hor(m_PosX, (m_PosY + m_Gravity + m_Height), TilePos, Map) == 3)
		{
			m_State = "DYING";
            m_Lives -= 1;

            m_bLockJump = true;
            m_bApexReached = false;
		}
		else if(Collision_Hor(m_PosX, (m_PosY + m_Gravity + m_Height), TilePos, Map) == 5)
		{
			m_VelY = m_Gravity;
			m_Score += 100;
			m_Coins += 1;
            Mix_PlayChannel(-1,cCoinCollected,0);

			Map->SetTileAtPos( (int) (m_PosX / 32), (int) (m_PosY / 32),0,0);

			m_bLockJump = true;
		}
		else if(Collision_Hor(m_PosX, (m_PosY + m_Gravity + m_Height), TilePos, Map) == 6)
		{
			m_PosY += m_VelX;
		}
        else
        {
			m_VelY = m_Gravity;

			if(m_VelY >= Tile.GetSize())
            {
				m_VelY = Tile.GetSize();
            }
			m_bLockJump = true;
		}

		std::cout << "m_bTouchesGround: " << m_bTouchesGround << "\n";

		if (m_bTouchesGround == true)
        {
            if (m_bRight == true)
            {
                m_State = "WALKING_RIGHT";
            }
            else if (m_bLeft == true)
            {
                m_State = "WALKING_LEFT";
            }
        }
        else
        {
            m_State = "JUMPING";
        }

        m_PosY += m_VelX;
	}

	UpdateScore();
	UpdateLives();
	UpdateCoins();

    HandleStates();
}
Example #20
0
EXPORT int op_calc_game(pdata data)
{
    int player;
    int steps;
    for (steps=0; steps<*(data->gameinfo->steps); steps++)
        for (player=0; player<data->gameinfo->playernum; player++)
            data->ist_position[player]+=(data->soll_position[player]-data->ist_position[player])*0.01;

    if (data->step==0) //Fade In
    {
        data->fade-=(float)(*(data->gameinfo->steps))/500.0;
        if (data->fade<=0.0)
        {
            data->fade=0.0;
            data->step=1;
        }
        return 0;
    }
    if (data->step==2) //Fade Out
    {
        float temp=data->fade;
        data->fade+=(float)(*(data->gameinfo->steps))/500.0;
        if (temp<0.0 && data->fade>=0.0)
            Mix_FadeOutMusic(500);
        if (data->fade>=1.0)
        {
            data->fade=1.0;
            return 1;
        }
        return 0;
    }
    if (data->countdown>0) //Countdown
    {
        data->countdown-=*(data->gameinfo->steps);
        return 0;
    }

    int winner=0;
    for (steps=0; steps<*(data->gameinfo->steps); steps++)
    {
        data->schlaeger_step++;
        if (data->schlaeger_step>=400+2*WAITTIME)
            data->schlaeger_step=0;
        if (data->schlaeger_step==0 || data->schlaeger_step==WAITTIME+200)
        {
            data->the_button=rand()%4;
            Mix_PlayChannel(-1,data->snd_drum,0);
            for (player=0; player<data->gameinfo->playernum; player++)
                data->chance[player]=true;
        }


        for (player=0; player<data->gameinfo->playernum; player++)
        {
            if (data->chance[player] && (*(data->gameinfo->joystick[player].button[data->the_button]) || (data->gameinfo->iscpu[player] && rand()%150==0)))
            {
                *(data->gameinfo->joystick[player].button[data->the_button])=0;
                data->chance[player]=false;
                data->soll_position[player]+=1.0;
                data->paddle_schlag[player]-=1.0;
            }
            int o1,o2,o3;
            switch (data->the_button)
            {
            case 0:
                o1=1;
                o2=2;
                o3=3;
                break;
            case 1:
                o1=0;
                o2=2;
                o3=3;
                break;
            case 2:
                o1=1;
                o2=0;
                o3=3;
                break;
            case 3:
                o1=1;
                o2=2;
                o3=0;
                break;
            }
            if (data->chance[player] && (*(data->gameinfo->joystick[player].button[o1]) ||
                                         *(data->gameinfo->joystick[player].button[o2]) ||
                                         *(data->gameinfo->joystick[player].button[o3]) || (data->gameinfo->iscpu[player] && rand()%300==0)))
            {
                *(data->gameinfo->joystick[player].button[o1])=0;
                *(data->gameinfo->joystick[player].button[o2])=0;
                *(data->gameinfo->joystick[player].button[o3])=0;
                data->chance[player]=false;
            }
            if (data->ist_position[player]>=24.95)
            {
                data->step=2;
                data->fade=-1.0;
                Mix_PlayChannel(-1,data->snd_win,0);
                return 0;
            }
            if (data->paddle_schlag[player]<0.0)
            {
                data->paddle_schlag[player]+=0.0015;
                if (data->paddle_schlag[player]>=0.0)
                    data->paddle_schlag[player]=0.0;
            }

        }

    }
    if (winner)
    {
        data->step=2;
        data->fade=-3.0;
        return 0;
    }
    return 0;
}
Example #21
0
/**
 * Will update the array of near blocks. If the currently touching block is
 * collectible, it will be collected. if it is deadly, it will kill the player
 */
static void update_near_blocks()
{
    current_player.near_blocks = 0;

    int w = current_player.sprite->w;
    int h = current_player.sprite->h;
    int nextx = current_player.x + current_player.vx;
    int nexty = current_player.y + current_player.vy;

    int blk = 0;
    blk = get_map_block(nextx + 4, nexty + h - 1);
    current_player.near_blocks |= block_is_solid(blk);
    blk = get_map_block(nextx + w - 4, nexty + h -1);
    current_player.near_blocks |= block_is_solid(blk);

    blk = get_map_block(nextx + w - 1, nexty + 4);
    current_player.near_blocks |= (block_is_solid(blk) << 2);
    blk = get_map_block(nextx + w - 1, nexty + h - 4);
    current_player.near_blocks |= (block_is_solid(blk) << 2);

    blk = get_map_block(nextx, nexty + 4);
    current_player.near_blocks |= (block_is_solid(blk) << 6);
    blk = get_map_block(nextx, nexty + h - 4);
    current_player.near_blocks |= (block_is_solid(blk) << 6);

    blk = get_map_block(nextx + 4, nexty);
    current_player.near_blocks |= (block_is_solid(blk) << 4);
    blk = get_map_block(nextx + w - 4, nexty);
    current_player.near_blocks |= (block_is_solid(blk) << 4);


    blk = get_map_block(nextx + w/2, nexty + h/2); //current block

    if(block_is_goal(blk)){
        //win
        extern bool win;
        win = true;
    }

    if (blk == BLK_WATR){
        if (!(current_player.state & (1 << 1))){ // in water and not wet
            Mix_PlayChannel(-1, mix_splash, 0);
            int x = current_player.x + current_player.sprite->w / 2;
            int y = current_player.y + current_player.sprite->h;
            int i;
            for (i = 0; i < 100; i++){
                    Particle *p = malloc(sizeof(Particle));
                    p->x = x;
                    p->y = y;
                    p->vx = ((rand() % 100)/40.0) - 1.25;
                    p->vy = -((rand() % 100)/40.0);
                    p->draw = particle_draw_normal;
                    p->update = particle_update_normal;
                    p->color = SDL_MapRGB(main_screen->format, 0, 0, 255);
                list_append(particles, p);
                free(p);
            }
            current_player.state |= (1 << 1);
        }
    } else {
        current_player.state &= ~(1<<1); // MAKE PLAYER NOT WET
    }

    if (!(current_player.state & (1 << 0))){ // PLAYER NOT DEAD
        if(block_is_collectible(blk)){ //remove collectible block
            remove_map_block(nextx + w/2, nexty + w/2);
            Mix_PlayChannel(-1, mix_coin, 0);
            if (current_player.state & (1<<7)){
                current_player.score+= 500;
            } else{ 
                current_player.score+= 100;
            }
        }
        if(block_is_deadly(blk)){
            //KILL PLAYER
             current_player.state = (1 << 0); //set player dead
             Mix_PlayChannel(-1, mix_ouch, 0);
             Mix_PlayChannel(-1, mix_spikes, 0);

            int x = current_player.x + current_player.sprite->w / 2;
            int y = current_player.y + current_player.sprite->h;
            int i;
            for (i = 0; i < 1000; i++){
                Particle *p = malloc(sizeof(Particle));
                p->x = x;
                p->y = y;
                p->vx = ((rand() % 100)/20.0) - 2.5;
                p->vy = -((rand() % 100)/20.0);
                p->color = SDL_MapRGB(main_screen->format, 255, 0, 0);
                p->draw = particle_draw_normal;
                p->update = particle_update_normal;
                list_append(particles, p);
                free(p);
            }
        }
    }
}
Example #22
0
int main()
{
    WORKING_DIR=SDL_GetBasePath();
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
    WORKING_DIR=WORKING_DIR.substr(0,WORKING_DIR.find_last_of("/\\"));
#ifdef __gnu_linux__
    WORKING_DIR+="/";
#elif __WIN32
    WORKING_DIR+="\\";
#endif
    std::cout<< WORKING_DIR<<std::endl;

    SDL_Window *mainwindow; /* Our window handle */
    SDL_GLContext maincontext; /* Our opengl context handle */
    Mix_Chunk *pong = NULL;
    Mix_Chunk *pong2 = NULL;
    Mix_Chunk *pong3 = NULL;
    if( SDL_Init( SDL_INIT_VIDEO| SDL_INIT_AUDIO ) < 0 )
    {
        sdldie("SDL could not initialize! SDL Error: %s\n");
    }
    else
    {
        //Use OpenGL 3.3 core
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );
        SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );

        //Create window
        mainwindow = SDL_CreateWindow( "pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |SDL_WINDOW_RESIZABLE );
        if( mainwindow == NULL )
        {
            sdldie("Unable to create window");
        }
        else
        {
            //Create context
            maincontext = SDL_GL_CreateContext( mainwindow );
            if( maincontext == NULL ){
                sdldie("OpenGL context could not be created! SDL Error: %s\n");
            }
            else
            {
                //Initialize GLEW
                glewExperimental = GL_TRUE;
                GLenum glewError = glewInit();
                if( glewError != GLEW_OK )
                {
                    std::cout<<"Error initializing GLEW! %s\n"<<glewGetErrorString( glewError );
                }

                //Use Vsync
                if( SDL_GL_SetSwapInterval( 1 ) < 0 )
                {
                    std::cout<<"Warning: Unable to set VSync! SDL Error: %s\n"<<SDL_GetError();
                }
                SDL_DisplayMode current;
                int should_be_zero = SDL_GetCurrentDisplayMode(0, &current); //@HACK:should check for multiple monitors
                if(should_be_zero != 0)
                  sdldie("Could not get display mode for video display");
                screenWidth=(3.0f/4.0f)*current.w;
                screenHeight=(3.0f/4.0f)*current.h;
                (*(int*)(&originalScreenHeight))=screenHeight;
                (*(int*)(&originalScreenWidth))=screenWidth;
            }
        }
    }
    //Initialize SDL_mixer
    if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ) {
        std::cout<<"SDL_mixer could not initialize! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
     //Load sound effects
    pong = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong.wav"));
    if( pong == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong2 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong2.wav"));
    if( pong2 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }
    pong3 = Mix_LoadWAV(WORKING_DIR_FILE("assets/sounds/pong3.wav"));
    if( pong3 == NULL ) {
        std::cout<< "Failed to load scratch sound effect! SDL_mixer Error: "<<Mix_GetError();
        return 1;
    }

    glEnable(GL_DEPTH_TEST);
    glViewport(0, 0, screenWidth, screenHeight);

    /* Clear our buffer with a red background */
    glClearColor ( 1.0, 0.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    /* Swap our back buffer to the front */
    SDL_GL_SwapWindow(mainwindow);
    /* Wait 2 seconds */
    SDL_Delay(100);

    /* Same as above, but green */
    glClearColor ( 0.0, 1.0, 0.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);

    /* Same as above, but blue */
    glClearColor ( 0.0, 0.0, 1.0, 1.0 );
    glClear ( GL_COLOR_BUFFER_BIT );
    SDL_GL_SwapWindow(mainwindow);
    SDL_Delay(100);


    GLfloat vertices[] = {
         0.5f,  0.5f, 0.0f,  // Top Right
         0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,  // Bottom Left
        -0.5f,  0.5f, 0.0f,   // Top Left
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3,  // First Triangle
        1, 2, 3   // Second Triangle
    };

    std::vector<Vertex> vertices2;
    std::vector<GLuint> indices2;
    {
        for(unsigned int i=0;i<(sizeof(vertices)/sizeof(vertices[0]));i+=3){
            Vertex aux;
            aux.position={vertices[i+0],vertices[i+1],vertices[i+2]};
            vertices2.push_back(aux);
        }
        for(unsigned int i=0;i<(sizeof(indices)/sizeof(indices[0]));i++){
            indices2.push_back(indices[i]);
        }

    }
    Sprite sprite(vertices2,indices2);

    GLfloat quadVertices[] = {   // Vertex attributes for a quad that fills the entire screen in Normalized Device Coordinates.
        // Positions   // TexCoords
        -1.0f,  1.0f,  0.0f, 1.0f,
        -1.0f, -1.0f,  0.0f, 0.0f,
         1.0f, -1.0f,  1.0f, 0.0f,

        -1.0f,  1.0f,  0.0f, 1.0f,
         1.0f, -1.0f,  1.0f, 0.0f,
         1.0f,  1.0f,  1.0f, 1.0f
    };

    // Setup cube VAO
    GLuint quadVAO, quadVBO;
    glGenVertexArrays(1, &quadVAO);
    glGenBuffers(1, &quadVBO);
    glBindVertexArray(quadVAO);
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
            glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
            glEnableVertexAttribArray(1);
            glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2 * sizeof(GLfloat)));
    glBindVertexArray(0);


    unsigned int points_p1=0,points_p2=0;
    bool first_point_p1=true,first_point_p2=true;

    GameObject player1(&sprite,{0.0f,2.0f});
    GameObject player2(&sprite,{0.0f,2.0f});
    GameObject ball(&sprite,{0.0f,0.0f});
    Entity roof(&sprite);
    Entity floor(&sprite);
    GameObject leftwall(&sprite,{0.0f,0.0f});
    GameObject rightwall(&sprite,{0.0f,0.0f});
    {
        player1.entity.setPos({-0.95f,0.0f});
        player2.entity.setPos({0.95f,0.0f});
        ball.entity.setPos({0.0f,8.0f});

        roof.setPos({-1.0f,1.10f});
        floor.setPos({-1.0f,-1.10f});
        roof.scale({4.0f,1.0f});
        floor.scale({4.0f,1.0f});

        leftwall.entity.setPos({-1.0f,0.0f});
        rightwall.entity.setPos({1.0f,0.0f});
        leftwall.entity.scale({0.025f,2.0f});
        rightwall.entity.scale({0.025f,2.0f});

        player1.entity.scale({0.025f, 0.49f});
        player2.entity.scale({0.025f, 0.49f});
        ball.entity.scale({0.0625f,0.0625f});
        ball.entity.order(SCALE,ROTATE,TRANSLATE);


    }

    std::vector<CollisionChecker> collisions;
    {
        collisions.push_back(CollisionChecker(&player1.entity,&roof));
        collisions.push_back(CollisionChecker(&player1.entity,&floor));
        collisions.push_back(CollisionChecker(&player2.entity,&roof));
        collisions.push_back(CollisionChecker(&player2.entity,&floor));
    }


    CollisionChecker ball_floor(&ball.entity,&floor);
    CollisionChecker ball_roof(&ball.entity,&roof);
    CollisionChecker ball_p1(&ball.entity,&player1.entity);
    CollisionChecker ball_p2(&ball.entity,&player2.entity);
    CollisionChecker ball_leftwall(&ball.entity,&leftwall.entity);
    CollisionChecker ball_rightwall(&ball.entity,&rightwall.entity);

    SDL_StartTextInput();
    bool quit = false;
    bool started=false;
    glm::vec2 p1_speed_gain(0.0f,0.0f);
    glm::vec2 p2_speed_gain(0.0f,0.0f);
    unsigned int i=0;
    Uint32 lastFrame=0;
    Uint32 deltaTime=0;
    float framerate=0.0f;
    float dt;


    framebuffer fb(originalScreenWidth,originalScreenHeight);
    Shader shader(WORKING_DIR_FILE("assets/shaders/shader.vert"),WORKING_DIR_FILE("assets/shaders/shader.frag"));
    Shader fb_shader(WORKING_DIR_FILE("assets/shaders/framebuffer_shader.vert"),WORKING_DIR_FILE("assets/shaders/framebuffer_shader.frag"));
    while(!quit)
    {
        SDL_PumpEvents();
        Uint32 currentFrame =            SDL_GetTicks();//miliseconds
        deltaTime           =  currentFrame - lastFrame;
        lastFrame           =              currentFrame;
        dt                  =         deltaTime/1000.0f;
        framerate          +=         1000.0f/deltaTime;

        p1_speed_gain={0.0f,0.0f};
        p2_speed_gain={0.0f,0.0f};
        {
            const Uint8 *keystates =                                     SDL_GetKeyboardState( NULL );
            quit                   = keystates[SDL_GetScancodeFromKey(SDLK_q)] || SDL_QuitRequested();
            started                =         started || keystates[SDL_GetScancodeFromKey(SDLK_SPACE)];
            if(started){
                if(keystates[SDL_GetScancodeFromKey(SDLK_w   )])
                {
                    player1.move( dt );
                    p1_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_s   )])
                {
                    player1.move(-dt );
                    p1_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_UP  )])
                {
                    player2.move( dt );
                    p2_speed_gain={ 0.0f , 1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_DOWN)])
                {
                    player2.move(-dt );
                    p2_speed_gain={ 0.0f ,-1.0f };
                }
                if(keystates[SDL_GetScancodeFromKey(SDLK_j)])
                {
                    player1.entity.rotate(15.0f );
                }

                do_ball_movement(ball,dt);
            }

        }
        {
            unsigned int size=collisions.size();
            for(unsigned int i=0;i<size;i++)
            {
                if(collisions[i].checkCollision())
                    handleCollision(collisions[i]);
            }
        }
        {
            glm::vec3 pos=ball.entity.position;
            glm::vec3 oldpos=ball.entity.oldPosition;
            if(ball_floor.checkCollision()){
                handleCollision(ball_floor);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_roof.checkCollision()){
                handleCollision(ball_roof);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(0.0f,-1.0f)))*glm::length(ball.speed);
                Mix_PlayChannel( -1, pong2, 0 );
            }
            if(ball_p1.checkCollision()){
                handleCollision(ball_p1);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(1.0f,0.0f)) + p1_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p1_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }
            if(ball_p2.checkCollision()){
                handleCollision(ball_p2);
                ball.speed=glm::normalize(glm::reflect(glm::vec2(pos.x-oldpos.x,pos.y-oldpos.y),glm::vec2(-1.0f,0.0f)) + p2_speed_gain)
                        *
                        (glm::length(ball.speed)+glm::length(p2_speed_gain));
                Mix_PlayChannel( -1, pong, 0 );
            }

            if(ball_leftwall.checkCollision()){
                points_p2++;
                ball.entity.setPos({0.0f,8.0f});//scale adjusted due the order it uses...
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(ball_rightwall.checkCollision()){
                points_p1++;
                ball.entity.setPos({0.0f,8.0f});
                ball.speed={0.0f,0.0f};
                Mix_PlayChannel( -1, pong3, 0 );
            }
            if(((ball.speed.y/ball.speed.x)>3.0f) || ((ball.speed.y/ball.speed.x)<-3.0f)){
                ball.speed.y/=2.0f;
                ball.speed.x*=4.0f;
            }
        }
        if(i==100){
            i=0;
            framerate/=100.0f;
            std::cout<<framerate<<std::endl;
            std::cout<<points_p1<<'-'<<points_p2<<std::endl;
            framerate=0.0f;
        }
        i+=1;
        shader.Use();
            fb.bind();
                glViewport(0,0,originalScreenWidth,originalScreenHeight);
                glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                glEnable(GL_DEPTH_TEST);
                glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

                glm::mat4 projection;//= glm::ortho(-1.0f,1.0f,-1.0f,1.0f,0.0f,1.0f);
                GLint projection_uniform=glGetUniformLocation(shader.Program, "projection");
                glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, glm::value_ptr(projection));


                glm::vec2 position;
                position=glm::vec2(-3.0f*1.06255f*0.125f,0.0f);
                if(points_p1>=5 || points_p2>=5){
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOP|DIGIT_MIDDLE|DIGIT_TOPLEFT|DIGIT_TOPRIGHT|DIGIT_BOTTOMLEFT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit((points_p1>=5)?1:2,&shader,position,{0.125f,0.125f});
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPLEFT |DIGIT_BOTTOMLEFT |DIGIT_BOTTOMLEFT_MIDDLE|
                                                                  DIGIT_TOPRIGHT|DIGIT_BOTTOMRIGHT|DIGIT_BOTTOMRIGHT_MIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_TOPMIDDLE|DIGIT_BOTTOMMIDDLE);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(-1,&shader,position,{0.125f,0.125f},DIGIT_BOTTOMLEFT |DIGIT_TOPLEFT|DIGIT_TOPLEFT_BOTTOMRIGHT|
                                                                  DIGIT_BOTTOMRIGHT|DIGIT_TOPRIGHT);
                    position+=glm::vec2(1.0625f*0.125f,0.0f);
                    drawdigit(5,&shader,position,{0.125f,0.125f});
                    started=false;
                }

                player1.entity.draw(&shader);
                player2.entity.draw(&shader);
                if(started) ball.entity.draw(&shader);
                roof.draw(&shader);
                floor.draw(&shader);
                leftwall.entity.draw(&shader);
                rightwall.entity.draw(&shader);




                unsigned int aux=points_p2;
                position=glm::vec2(0.25f,0.5f);
                //NOTE: when one of the points hits 20 I should put a you win screen
                first_point_p2=points_p2? false:true;
                while((aux/10) || (aux%10) || first_point_p2){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p2=false;//endless loop if I dont
                }

                aux=points_p1;
                position={-0.25f,0.5f};
                first_point_p1=points_p1? false:true;
                while((aux/10) || (aux%10) || first_point_p1){
                    drawdigit(aux%10,&shader,position,{0.125f,0.125f});
                    position.x-=1.5f*0.125f;
                    aux=aux/10;
                    first_point_p1=false;
                }


            fb.unbind();
        SDL_GetWindowSize(mainwindow,&screenWidth,&screenHeight);
        glViewport(0,0,screenWidth,screenHeight);
        glClearColor(0.0f, 0.0f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDisable(GL_DEPTH_TEST);
        fb_shader.Use();
            glm::mat4 screenscaler;
            float aspectRatio=(float)screenWidth/(float)screenHeight;
            float inverseAspectRatio=(float)screenHeight/(float)screenWidth;
            if(aspectRatio>1.0f)
            screenscaler = glm::perspective(radians(59.2f),aspectRatio,0.1f,1.0f);
            else
            screenscaler = glm::perspective(radians(59.2f),inverseAspectRatio,0.1f,1.0f);
            GLint model_uniform=glGetUniformLocation(fb_shader.Program, "model");
            glUniformMatrix4fv(model_uniform, 1, GL_FALSE, glm::value_ptr(screenscaler));

            glBindVertexArray(quadVAO);//should scale the scale to the % of resolution
            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, fb.texture);
                glDrawArrays(GL_TRIANGLES, 0, 6);
            glBindTexture(GL_TEXTURE_2D,0);
            glBindVertexArray(0);


        SDL_Delay(1);
        SDL_GL_SwapWindow(mainwindow);
        if(points_p1>=5 || points_p2>=5){
            points_p1=0;
            points_p2=0;
            ball.speed={0.0f,0.0f};
            SDL_Delay(3000);
        }
    }
    DESTRUCTOR(fb);
    DESTRUCTOR(shader);
    DESTRUCTOR(fb_shader);
    Mix_FreeChunk(pong);
    Mix_FreeChunk(pong2);
    Mix_FreeChunk(pong3);
    SDL_GL_DeleteContext(maincontext);
    SDL_DestroyWindow(mainwindow);
    SDL_Quit();

    return 0;
}
Example #23
0
void Application::PlaySound1()
{
	Mix_PlayChannel(-1, music, 0);
}
Example #24
0
void Ball::Collided(int ObjectID, col_dir dir){
    if(dir == NO_COLLISION)
        return;

    //checking for collision with PLAYER
    if(ObjectID == PLAYER){
        
        if(has_effect == MAGNET && stand_on_platform == false)
            stand_on_platform = true;
        else{
            switch(dir){
                case LEFT:
                    dirX = -1;
                    break;
                case RIGHT:
                    dirX = 1;
                    break;
                case TOP:
                    dirY = -1;
                    break;
                case TLCOR:
                    dirX = -1;
                    dirY = -1;
                    break;
                case TRCOR:
                    dirX = 1;
                    dirY = -1;
                    break;
            }
            if(velX <0) velX -= .2; else velX += .2;
            if(velY <0) velY -= .2; else velY += .2;
            dynamic_cast<PlayingState*>(g_GamePtr->GetState())->GetPlatform()->AddPoint();
            if(g_GamePtr->isSfxOn())
                Mix_PlayChannel(-1, g_GamePtr->GetSfx(), 0);
            
        }
    } else if(ObjectID == BLOCK){
        switch(dir){
            case LEFT:
                dirX = -1;
                break;
            case RIGHT:
                dirX = 1;
                break;
            case TOP:
                dirY = -1;
                break;
            case BOTTOM:
                dirY = 1;
                break;
            case TLCOR:
                dirX = -1;
                dirY = -1;
                break;
            case TRCOR:
                dirX = 1;
                dirY = -1;
                break;
            case BLCOR:
                dirX = -1;
                dirY = 1;
                break;
            case BRCOR:
                dirX = 1;
                dirY = 1;
                break;
        }
    }
}
Example #25
0
void audio_play(void){
  Mix_PlayChannel( -1, drum1_sound, 0 ); /* (channel -1 = dont care, sound, times to repeat)*/
}
Example #26
0
void GsSound::play(void)
{
    if (Mix_PlayChannel(-1, sound, 0) < 0)
        gsBug("Mix_PlayChannel");
}
Example #27
0
void SoundEffect::Play(SoundEffect* effect, int channel, int loops) {
  Mix_PlayChannel(channel, effect->_chunk, loops);
}
void SoundManager::playSound(std::string id, int loop)
{
	Mix_PlayChannel(-1, m_sfxs[id], loop);
}
Example #29
0
void Missile::playSoundEffect(){
    Mix_PlayChannel(-1,sound,0);
}
Example #30
0
void SPU(sounds Index)
{
//Local lcp
//If SoundVol#>0 Then
//ChannelVolume lcp,SoundVol#
    switch (Index)
    {
    case sBoom:
        Mix_PlayChannel(1,Boom_snd,0);
        //lcp=PlaySound(Boom_snd)
        break;
    case sBlock:
        Mix_PlayChannel(1,Block_snd,0);
        //lcp=PlaySound(Block_snd)
        break;
    case sBoth:
        Mix_PlayChannel(1,Both_snd,0);
        //lcp=PlaySound(Both_snd)
        break;
    case sCombo:
        Mix_PlayChannel(1,Combo_snd,0);
        //lcp=PlaySound(Combo_snd)
        break;
    case sChif:
        Mix_PlayChannel(1,Chif_snd,0);
        //lcp=PlaySound(Chif_snd)
        break;
    case sDrink:
        Mix_PlayChannel(1,Drink_snd,0);
        //lcp=PlaySound(Drink_snd)
        break;
    case sDzin:
        Mix_PlayChannel(1,Dzin_snd,0);
        //lcp=PlaySound(Dzin_snd)
        break;
    case sKlik:
        Mix_PlayChannel(1,Klik_snd,0);
        //lcp=PlaySound(Klik_snd)
        break;
    case sLose:
        Mix_PlayChannel(1,Lose_snd,0);
        //lcp=PlaySound(Lose_snd)
        break;
    case sMonetka:
        Mix_PlayChannel(1,Monetka_snd,0);
        //lcp=PlaySound(Monetka_snd)
        break;
    case sWin:
        Mix_PlayChannel(1,Win_snd,0);
        //lcp=PlaySound(Win_snd)
        break;
    case sKlik2:
        Mix_PlayChannel(1,klik2_snd,0);
        //lcp=PlaySound(klik2_snd)
        break;
    case sOtmen:
        Mix_PlayChannel(1,Otmen_snd,0);
        //lcp=PlaySound(Otmen_snd)
        break;
    case sSuper:
        Mix_PlayChannel(1,Super_snd,0);
        //lcp=PlaySound(Super_snd)
        break;
    case sBlocker:
        Mix_PlayChannel(1,Blocker_snd,0);
        //lcp=PlaySound(Blocker_snd)
        break;
    }
//End Select
//ChannelVolume lcp,SoundVol#
//End If

}