Exemplo n.º 1
0
int main(int argc, char* argv[]) {

  bool running = true;
  int i, j, xfrog, yfrog, xfly, yfly, leech[MAX_PLAYERS], tadswim = 0, swavenum[MAX_PLAYERS], swave_clk[MAX_PLAYERS], cls, kk;
  float dist;
  int nfrogs = 7; // Number of frogs
  int sp = 1;    // Speed (1-3)
  int a_i = 3;  // AI (1-3)
  FILE *fp;

  // Open hiscores.txt

  if((fp = fopen("hiscores.txt","r")) == NULL) {
    printf("Can't find file: hiscores.txt\n");
    return 1;
  }

  for(kk = 0; kk < 32; kk++) {
    hiscores[kk].name = (char*)malloc(MAX_NAME_LENGTH*sizeof(char));
    hiscores[kk].time = 0;
  }

  
  int ret = 1;
  kk = 0;
  while(ret != EOF) {
    ret = fscanf(fp,"%s %d", hiscores[kk].name, &hiscores[kk].time);
    kk++;
  }

  // Close hiscores.txt
  fclose(fp);

  // Bubble sort
  for(i=0; i<31; i++) {
    for(j=31; j > i; j--) {
      if(hiscores[j].time > hiscores[j-1].time) {
	strcpy(buf,hiscores[j-1].name);
	kk = hiscores[j-1].time;
	strcpy(hiscores[j-1].name,hiscores[j].name);
	hiscores[j-1].time = hiscores[j].time;
	strcpy(hiscores[j].name,buf);
	hiscores[j].time = kk;
      }
    }
  }

  
#ifdef TADPOLE_COLLISIONS  

  int tempvel;
  int collisions[MAX_PLAYERS][MAX_PLAYERS];

  for(i=0;i<MAX_PLAYERS;i++) {
    for(j=0;j<MAX_PLAYERS;j++) {
      collisions[i][j] = 0;
    }
  }

#endif


  for(i=0;i<MAX_PLAYERS;i++) {
    leech[i] = 0;
    swavenum[i] = 0;
    swave_clk[i] = 0;
    leaderboard_rank[i] = -1;
  }
  
  int bwavenum = 0, bwave_clk, mm_clk = 0, suwavenum = 0, suwave_clk = 0;  // various wave clocks and wave counters (storing latest wave to be animated)

  int nherd[10], nflychasers = 0; // nherd[i] counts number of close frogs to ith frog in jumpstate 0.
  int tadflip = 0, mmtadx = SCREEN_WIDTH/2, mmtady = SCREEN_HEIGHT/2+BANNER_HEIGHT/2;

  float ran; // random number storing
  char Tadname[MAX_NAME_LENGTH];


  strcpy(Tadname,"Player_0"); // Name of local player, no spaces

  set_frogclips();
  set_tadclips();
  set_flyclips();
  set_swaveclips();
  set_bwaveclips();
  set_suwaveclips();
  
  Timer fps;  
  Timer gameclock;
  Timer flyspan;
  std::vector<Timer> warpspan(nfrogs);
  
//    Setting wave flags to 'not animate / done animation'

  for(j=0; j<NUMWAVES; j++) {
    nherd[j] = 0;
    for(kk=0; kk<MAX_PLAYERS; kk++) {
      smallwaves[kk][j][0] = 6;
    }
  }

  for(j=0; j<NUMWAVES; j++) {
    bigwaves[j][0] = 24;
    suwaves[j][0] = 24;
  }

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

  if (load_files() == false) return 1;

  // Spawn Tadpole
  //  Tadpole myTad;
  std::vector<Tadpole> myTad(MAX_PLAYERS);


  // Spawn fly
  xfly = 10+drand48()*(SCREEN_WIDTH-LEADER_WIDTH-HISCORE_WIDTH-20)+LEADER_WIDTH;
  yfly = 10+drand48()*(SCREEN_HEIGHT-BANNER_HEIGHT-20) + BANNER_HEIGHT;
  Fly myfly( xfly, yfly );

  // Spawn Frogs
  std::vector<Frog> myfrogs(nfrogs);


  for(i = 0; i < nfrogs; i++ ) {
    xfrog = drand48()*(SCREEN_WIDTH-LEADER_WIDTH-HISCORE_WIDTH-20)+LEADER_WIDTH;
    yfrog = drand48()*(SCREEN_HEIGHT-BANNER_HEIGHT-20) + BANNER_HEIGHT;
    if(distance(xfrog, yfrog, mmtadx, mmtady) < (SCREEN_HEIGHT-BANNER_HEIGHT)/4) {
      i--;
    }
    myfrogs[i].Frog_set(xfrog, yfrog, sp, a_i);
  }


  for(i=0; i<nfrogs; i++)
    myfrogs[i].show(sp);

  myfly.show();


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

  SDL_Delay(500);

  gameclock.start();
  
#ifdef PRINT_MESSAGES  
  printf("Tadpole server is up!\n");
#endif
  

#ifdef WITH_SOUND
//    if(Mix_PlayMusic(ambience, -1) == -1)
    if(Mix_FadeInMusic(ambience, -1, 2000) == -1)
	return 1;
#endif
  

  // Game Server loop
  while (running) {

    fps.start();

    // Listen for connections, argument 0 means no wait-time
    int numActiveSockets = SDLNet_CheckSockets(socketSet, 0);

    if(numActiveSockets > 0) {

      // Check help socket. If activity detected, then open temporary socket and dump help text. Then close socket.
      int helpSocketActivity = SDLNet_SocketReady(helpSocket);
      if(helpSocketActivity != 0) {
	TCPsocket tempSock = SDLNet_TCP_Accept(helpSocket);
	SDLNet_TCP_Send(tempSock,(void*)reply,strlen(reply)+1);
	// Close temporary connection
	SDLNet_TCP_Close(tempSock);
      }

      
      // Check if our server socket has received any data
      // Note: SocketReady can only be called on a socket which is part of a set and that has CheckSockets called on it (the set, that is)
      // SDLNet_SocketRead returns non-zero for activity, and zero is returned for no activity.
      int serverSocketActivity = SDLNet_SocketReady(serverSocket);
      // All server activity interpreted as request for TCP connection
      if(serverSocketActivity != 0) {
	// If we have room for more clients...
	if(ntads < MAX_PLAYERS) {
	  int freeSpot = -99;
	  for(int i = 0; i < MAX_PLAYERS; i++) {
	    if(!myTad[i].alive && !myTad[i].TCP_limbo) {
	      freeSpot = i;
	      break;
	    }
	  }
	  // Accept the client connection
	  myTad[freeSpot].socket = SDLNet_TCP_Accept(serverSocket);

	  // get clients IP
	  remoteip = SDLNet_TCP_GetPeerAddress(myTad[freeSpot].socket);
	  if(!remoteip) {
#ifdef SERVER_DEBUG
	    printf("SDLNet_TCP_GetPeerAddress: %s\n",SDLNet_GetError());
#endif
	    // No remote ip?! NO CONNECTION!
	    SDLNet_TCP_Close(myTad[freeSpot].socket);	  
	  } else {
#ifdef SERVER_DEBUG	  
	    ipaddr=SDL_SwapBE32(remoteip->host);
	    printf("Accepted a connection from %d.%d.%d.%d port %hu.",
		   ipaddr>>24,
		   (ipaddr>>16)&0xff,
		   (ipaddr>>8)&0xff,
		   ipaddr&0xff,
		   remoteip->port);
	    printf(" There are now %d client(s) online.\n",
		   ntads+1);
#endif
	    ntads++;
	    myTad[freeSpot].TCP_limbo = true;
	    // Add new client socket to socket set, to check activity
	    SDLNet_TCP_AddSocket(socketSet, myTad[freeSpot].socket);
	    // Send 'N' asking for name
	    strcpy(buf,"N");
	    SDLNet_TCP_Send(myTad[freeSpot].socket,(void*)buf,2);
	  }
	} else { // No new room for clients
#ifdef SERVER_DEBUG
	  printf("No room. Rejecting client.\n");
#endif
	  // Accept client connection to clear it from incoming list
	  TCPsocket tempSock = SDLNet_TCP_Accept(serverSocket);
	  // Send 'X' telling that there is no room
	  strcpy(buf,"X");
	  SDLNet_TCP_Send(tempSock,(void*)buf,2);
	  // Close temporary connection
	  SDLNet_TCP_Close(tempSock);
	}
      }
Exemplo n.º 2
0
int
main(int argc, char *argv[])
{
	putenv("SDL_VIDEODRIVER=dga");

	if (SDL_Init(SDL_INIT_VIDEO) == -1) {
		fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	SDL_ClearError();
	printf("SDL initialized\n");

	atexit(end_SDL);


	/* Creat a SDL window, and get the window's surface. */
	/* PS: use hardware--> SDL_HWSURFACE */
	SDL_Surface *screen = NULL;
	screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
	if (screen == NULL) {
		fprintf(stderr, "SDL_SetVideoMode() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}

	/* Show the SDL window's surface */
	if (SDL_Flip(screen) == -1) {
		fprintf(stderr, "SDL_Flip() failed: %\n", SDL_GetError());
		exit(EXIT_FAILURE);
	}


	char name[30];
	if (SDL_VideoDriverName(name, 30) == NULL) {
		fprintf(stderr, "SDL_VideoDriverName() failed: %s", SDL_GetError());
		exit(EXIT_FAILURE);
	}
	printf("name = %s\n", name);


	const SDL_VideoInfo *info = SDL_GetVideoInfo();
	printf("Is it possible to create hardware surfaces: %d\n",
		info->hw_available);
	printf("Is there a window manager available: %d\n",
		info->wm_available);
	printf("Are hardware to hardware blits accelerated: %d\n",
		info->blit_hw);
	printf("Are hardware to hardware colorkey blits accelerated: %d\n",
		info->blit_hw_CC);
	printf("Are hardware to hardware alpha blits accelerated: %d\n",
		info->blit_hw_A);
	printf("Are software to hardware blits accelerated: %d\n",
		info->blit_sw);
	printf("Are software to hardware colorkey blits accelerated: %d\n",
		info->blit_sw_CC);
	printf("Are software to hardware alpha blits accelerated: %d\n",
		info->blit_sw_A);
	printf("Are color fills accelerated: %d\n", info->blit_fill);
	printf("Total amount of video memory in Kilobytes: %d\n",
		info->video_mem);
	printf("Width of the current video mode: %d\n",
		info->current_w);
	printf("Height of the current video mode: %d\n",
		info->current_h);


	press_ESC_to_quit();

	return 0;
}
Exemplo n.º 3
0
int main(int argc, char *argv[])
{
    Uint32 initflags = SDL_INIT_VIDEO;
    SDL_Surface *ecran;
    Dimensions fenetre; // main window
   	
    fenetre.h = WINHI;  // en pixels
    fenetre.w = WINWI;   

    Uint8  video_bpp = 32; // 32 bits de couleur
    Uint32 videoflags = SDL_HWSURFACE; // utiliser la mémoire vidéo
    
    bool continuer; // pour la boucle principale des évènements 
    SDL_Event event; // aussi
 
    /* Initialize the SDL library */
    if ( SDL_Init(initflags) < 0 )
    {
        fprintf(stderr, "N'arrive pas a` initialiser la SDL : %s\n", SDL_GetError());
        exit(1);
    }
 
    /* Set video mode */
    ecran = SDL_SetVideoMode(fenetre.w, fenetre.h, video_bpp, videoflags); // surface principale

    if (ecran == NULL)
    {
        fprintf(stderr, "N'arrive pas a` etablir mode video%dx%dx%d : %s\n", fenetre.w, fenetre.h, video_bpp, SDL_GetError());
        SDL_Quit();
        exit(2);
    }
       
    SDL_WM_SetCaption("Hexcaliba", NULL); // legende de la fenêtre

    TTF_Init();
    
	extern_init();
      
     SDL_Rect posPionTemp;
	
	SDLKey key_pressed ;
    int coup_valide =0 ,menu=1,j,nb_tour=0, i=0,afficher_rolldice=0,afficher_resultat=0,de1,de2,afficher_valider=0,retour_bouton=0;
    int qui_commence = 0,contre_IA=0;
    continuer = true; // un furieux du c ferait plutôt une boucle infinie. Je préfère rester correct.
    int now=105, before=100, interval=50,k;
    default_menu1(ecran);
    while (continuer)
    {
	now = SDL_GetTicks();
        while ( SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_MOUSEMOTION:
			if(menu==1)
				hover_menu1(ecran,event);
			else if(menu==2)
				hover_choix_adversaire(ecran,event);
			else if(menu==3)
				hover_choix_difficulte(ecran,event);
			else if(menu==4)
			{
				if(!afficher_rolldice)
					hover_roll_dice(ecran,event);
				if((afficher_resultat)&&(afficher_rolldice)&&(!afficher_valider))
					hover_valider(ecran,event);
				if((afficher_resultat)&&(afficher_rolldice)&&(afficher_valider))
					hover_jouer(ecran,event);
			}
			else if( menu == 5)
			{
				hover_historique(ecran, event);
			}
			else if (menu == 6)
				hover_charger(ecran,event);
			else if (menu ==7)
				hover_quitter(ecran,event);
			else if (menu == 8)
				hover_winner(ecran,event);
				
			
                    break;
		    
                case SDL_MOUSEBUTTONDOWN:
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {   
                        int clicX = event.motion.x;
                        int clicY = event.motion.y;

			if (menu==1)
				button_menu1(&menu,&continuer,clicX,clicY);
			else if (menu==2)
				button_choix_adversaire(&menu,&continuer,clicX,clicY,&i,&afficher_resultat,&afficher_rolldice,&afficher_valider,&retour_bouton,&contre_IA,&qui_commence);
			else if (menu==3)
				button_choix_difficulte(&menu,clicX,clicY,&contre_IA);
			else if (menu==4)
			{
				if(!afficher_rolldice)
				{
					button_roll_dice(clicX,clicY,&de1,&de2,&afficher_rolldice);
					if(de1==de2)
					{
						afficher_rolldice=0;
						afficher_resultat=0;
					}else if (de1<de2)
						qui_commence++;
				}
				if((afficher_rolldice)&&(afficher_resultat))
					button_valider(&afficher_valider,clicX,clicY);
				if((afficher_rolldice)&&(afficher_resultat)&&(afficher_valider))
					button_jouer(&menu,&continuer,clicX,clicY,&i, &nb_tour, &retour_bouton,qui_commence,contre_IA);
			}
			else if (menu == 5 )
			{
				button_historique(&menu, clicX, clicY);
			}else if (menu == 6)
				button_charger(&menu,clicX,clicY,&i,&afficher_rolldice,&afficher_resultat,&afficher_valider);
			else if (menu == 7 && retour_bouton)
					button_quitter_2(&menu,clicX,clicY,i);
			else if (menu == 7 && !retour_bouton)
					button_quitter(&menu,&continuer,clicX,clicY,i);
			else if (menu == 8)
				button_winner(&menu, clicX,clicY,i);
				    
                    }
                    break;
                case SDL_KEYDOWN:
                    key_pressed = event.key.keysym.sym; // on récupère la touche
                    switch (key_pressed)
                    {
                    	case SDLK_ESCAPE: /* Esc keypress quits the app... */
                     		if (menu == 4)
					menu = 7;
				else
					continuer=0;
                        break;
                    }
                    break;
                case SDL_QUIT:
                    	if (menu == 4)
				menu = 7;
			else
				continuer=0;
                    break;
                default:
			if(menu==1)
				default_menu1(ecran);
			else if(menu==2)
				default_choix_adversaire(ecran);
			else if(menu==3)
				default_choix_difficulte(ecran);
			else if(menu==4)
			{
				if(!afficher_rolldice)
					default_roll_dice(ecran);
				if((!afficher_resultat)&&(afficher_rolldice))
				{
					default_roll_resultat(ecran,de1,de2);
					afficher_resultat++;
				}
				if((afficher_resultat)&&(afficher_rolldice)&&(!afficher_valider))
					default_valider(ecran,de1,de2);
				if((afficher_resultat)&&(afficher_rolldice)&&(afficher_valider))
					default_jouer(ecran,i, qui_commence, &menu);
			}
			else if(menu == 5)
			{
				default_historique(ecran,i);
			}
			else if (menu == 6)
				default_charger(ecran);
			else if (menu == 7)
				default_quitter(ecran);
			else if (menu == 8)
				default_winner(ecran,qui_commence,i);
                    break;
            }
        }
        if (now-before<interval)
		SDL_Delay(interval-(now-before));
        // refresh screen
        // mettre ici tous les blit utiles s'il y a des changements dans les surfaces, board, nouveaux pions
        SDL_Flip(ecran); //maj des surfaces pour affichage
	before=now;
    }
    
    /* Clean up the SDL library */
    SDL_FreeSurface(pionBleu);
    SDL_FreeSurface(pionRouge);
    SDL_FreeSurface(ecran);
    SDL_FreeSurface(board);
    SDL_FreeSurface(background);
    SDL_FreeSurface(bienvenue);
    SDL_FreeSurface(texte_Charger);
    SDL_FreeSurface(texte_Jouer);
    SDL_FreeSurface(texte_Quitter);
    SDL_FreeSurface(ia);
    SDL_FreeSurface(ia1);
    SDL_FreeSurface(retour);
    SDL_FreeSurface(ia2);
    SDL_FreeSurface(human);
    SDL_FreeSurface(difficulte);
    SDL_FreeSurface(adversaire);
    SDL_FreeSurface(background2);
    SDL_FreeSurface(historique);
    SDL_FreeSurface(sauvegarder);
    SDL_FreeSurface(undo);
    SDL_FreeSurface(valider);
    SDL_FreeSurface(stringHist);
    SDL_FreeSurface(names);
    TTF_CloseFont(fontMenu);
    TTF_CloseFont(fontSousMenu);
    TTF_CloseFont(fontSousMenu2);
    TTF_Quit();
    SDL_Quit();
    fclose(f_in);
    return(0);
}
Exemplo n.º 4
0
void
GlobalEvent::on_button_press(const SDL_KeyboardEvent& event)
{
  switch (event.keysym.sym)
  {
    case SDLK_F10:
      config_manager.set_print_fps(!config_manager.get_print_fps());
      break;

    case SDLK_RETURN:
      if (event.keysym.mod & KMOD_ALT)
      {
        config_manager.set_fullscreen(!config_manager.get_fullscreen());
      }
      break;

    case SDLK_TAB: // unlock mouse grab if Alt-Tab is pressed to allow the user to change windows
      if (config_manager.get_mouse_grab())
      {
        if (event.keysym.mod & KMOD_ALT)
        {
          // FIXME: should suspend the grab till the user clicks the
          // window again, not completely disable it
          config_manager.set_mouse_grab(false);
        }
      }
      break;

    case SDLK_F11:
      config_manager.set_fullscreen(!config_manager.get_fullscreen());
      break;

    case SDLK_F5:
      if (!dynamic_cast<OptionMenu*>(ScreenManager::instance()->get_current_screen().get()))
        ScreenManager::instance()->push_screen(std::make_shared<OptionMenu>());
      break;

    case SDLK_o:
      if (event.keysym.mod & KMOD_CTRL)
      {
        if (!dynamic_cast<OptionMenu*>(ScreenManager::instance()->get_current_screen().get()))
          ScreenManager::instance()->push_screen(std::make_shared<OptionMenu>());
      }
      break;

    case SDLK_F6:
      if (globals::developer_mode)
      {
        if (!dynamic_cast<AddOnMenu*>(ScreenManager::instance()->get_current_screen().get()))
          ScreenManager::instance()->push_screen(std::make_shared<AddOnMenu>());
      }
      break;

    case SDLK_F12:
      {
        Screenshot::make_screenshot();
      }
      break;

    case SDLK_c:
      if (globals::developer_mode)
        globals::draw_collision_map = !globals::draw_collision_map;
      break;

    case SDLK_k:
      if (globals::developer_mode)
      {
#ifdef OLD_SDL1
        log_info("Low level screen clear triggered");
        SDL_Surface* screen = SDL_GetVideoSurface();
        SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 255, 0));
        SDL_Flip(screen);
#endif
      }
      break;

    case SDLK_m:
      if (event.keysym.mod & KMOD_CTRL)
      {
        log_info("Developer Mode: %1%", globals::developer_mode);
        globals::developer_mode = !globals::developer_mode;
      }
      break;

    case SDLK_g:
      if (event.keysym.mod & KMOD_CTRL)
      {
        config_manager.set_mouse_grab(!config_manager.get_mouse_grab());
      }
      break;

    case SDLK_KP_PLUS:
      globals::game_speed -= 5;
      if (globals::game_speed < 5)
        globals::game_speed = 5;
      break;

    case SDLK_KP_MINUS:
      globals::game_speed += 5;
      break;

    case SDLK_KP_ENTER:
      globals::game_speed = 20;
      break;

    default:
      // console << "GlobalEvent: Unknown key pressed: " << key.id;
      break;
  }
}
Exemplo n.º 5
0
int main( int argc, char* args[] )
{

    quit = 0;
    Tile *tiles[ TOTAL_TILES ];

    Timer fps;    levelwon = 0;

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

        if( TTF_Init() == -1 )
        {
            return false;
        }


        //Initialize SDL_mixer
        if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
        {
            return false;
        }

 //Load the files
        if( load_files() == false )
        {
            return 1;
        }

        //Clip the tile sheeti
        if( Mix_PlayMusic( music, -1 ) == -1 ) { return 1; }

        clip_tiles();

        if(!welcome)return 1;
        SDL_BlitSurface(welcome, NULL, screen, NULL );
        SDL_Flip( screen );
        SDL_Delay(6000);

        robin robinp;

    while(quit ==false)
    {

        if(level!= 1)
        {
            SDL_BlitSurface( prepare, NULL, screen, NULL );
            SDL_Flip(screen);
            SDL_Delay(3000);
        }

        robinp.reset();

        //Set the tiles
        if( set_tiles( tiles ) == false )
        {
            return 1;
        }
       // SDL_Delay(3000);
        first=1;
    /////////////////////////////////////////////////////////////////////////////////////
        while( quit == false && levelwon == 0)///////////////////////////////////
        {

            //Start the frame timer
            fps.start();

            //While there's events to handle
            while( SDL_PollEvent( &event ) )
            {

              robinp.handle_events();


                //If the user has Xed out the window
                if( event.type == SDL_QUIT )
                {
                    //Quit the program
                    quit = true;
                }
            }

            SDL_BlitSurface( background, NULL, screen, NULL );


            robinp.move(tiles);
            robinp.set_camera();

         for( int t = 0; t < TOTAL_TILES; t++ )
            {
                tiles[ t ]->show();
            }


        for(int i=0;i< en_num;i++)
        {
            enemys[en_num]->show();        //robinp.reset();
        }


            robinp.show();
            showscore();

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

            //Cap the frame rate
            if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
            {
                SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
            }


        }

        clean_up(tiles);
        level++;
        levelwon = 0;
    /////////////////////////////////////////////////////////////////////////////////////
        //cout<<"out of level";
    }


        SDL_FreeSurface( background );
        SDL_FreeSurface( gameover );
         SDL_FreeSurface( tileSheet );

        //Free the music
        Mix_FreeMusic( music );
        Mix_FreeChunk( jumpsou );
        Mix_FreeChunk( coinsou );
        Mix_FreeChunk( hitsou );
        Mix_FreeChunk( diamoundsou );

        //Close the font
        TTF_CloseFont( font );

        //Quit SDL_mixer
        Mix_CloseAudio();
          SDL_Quit();
        //Quit SDL_ttf
        TTF_Quit();

    return 0;

    }
Exemplo n.º 6
0
int main( int argc, char* args[] ) 
{
	
	// this is the last time (SDL_Getticks()) that beasts were evaluated
	int beastLastEval=0;
	// this is how many times per second the beasts should be evaluated
	int beastEvalsPerSec = 30;
	
	paused = 0;
	//get a random seed.
	sgenrand(time(NULL));
	
    //mouse variables and cell types
    int x, y, sleepTime = 0, countVar = 0;
	
    //mouse is held variables
    int mouseStatusLeft = 0, mouseStatusRight = 0;
    
    // these keep track of the position of the right mouse button when it was clicked down
    int mouseRDx;
	int mouseRDy;
	
	//make sure the program waits for a quit
	int quit = false;
	
	init_mats();
	init_graphics();
	init_controls();
	
    //Initialize
    if( init() == false ) return 1;
	
    //Load the files
    if( load_files() == false ) return 2;
	
    //Update the screen
    if( SDL_Flip( screen ) == -1 ) return 3;
    
    gen_world();
	
	// these keep track of the WASD keys.
	int keyw=0, keya=0, keys=0, keyd=0;
	int key; // used as a stand-int for the verbose event.key.keysym.sym
	bool keyF3=true;
	
	//these are used to calculating and keeping track of the FPS
	int ticksSinceLastFPSUpdate = 0;
	int cumulativeFrames = 0;
	int currentTicks = 0;
	
	SDL_Rect screenRect;
	screenRect.x = screenRect.y = 0;
	screenRect.w = SCREEN_WIDTH;
	screenRect.h = SCREEN_HEIGHT;
	
	
    //While the user hasn't quit
    while(1){
		
    	//While there's an event to handle
    	while( SDL_PollEvent( &event ) ){
			
    		//If the user has Xed out the window
    		if( event.type == SDL_QUIT || quit == true ){
				//Quit the program
				clean_up();
				return 0;
			}
			
            if( event.type == SDL_MOUSEBUTTONDOWN ){						/// mouse down
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 1;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 1;
                    mouseRDx = x;
                    mouseRDy = y;
                }
                
                else if( event.button.button == SDL_BUTTON_WHEELUP )
					;//zoom_in(x,y);
				else if( event.button.button == SDL_BUTTON_WHEELDOWN )
					;//zoom_out(x,y);
				
            }
            else if(event.type == SDL_MOUSEBUTTONUP){						/// mouse up
				x = event.motion.x;
				y = event.motion.y;
                if( event.button.button == SDL_BUTTON_LEFT ){
                    mouseStatusLeft = 0;
                }
                else if( event.button.button == SDL_BUTTON_RIGHT ){
                    mouseStatusRight = 0;
                }
            }
            else if( event.type == SDL_MOUSEMOTION ){						/// mouse motion
				x = event.motion.x;
				y = event.motion.y;
				/*
				// if the alt key (camera panning key) is down and the coordinates have changed, then let the screen be panned!
				if(alt && x != mouse_x_when_pan && y != mouse_y_when_pan){
					// this adjusts the x-axis camera (this scales with the CELL_SIZE)
					camera_x += (x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE;
					camera_y += (y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE;
					//calculate the remainders of the mouse motion.
					// these values represent the motion of the mouse that is not utilized by the discrete nature of the operation on the camera_x and camera_y values.
					remainder_panning_motion_x = (x-mouse_x_when_pan+remainder_panning_motion_x) - (int)((x-mouse_x_when_pan+remainder_panning_motion_x)/CELL_SIZE)*CELL_SIZE;
					remainder_panning_motion_y = (y-mouse_y_when_pan+remainder_panning_motion_y) - (int)((y-mouse_y_when_pan+remainder_panning_motion_y)/CELL_SIZE)*CELL_SIZE;
					// make sure the camera is not out of bounds.
					verify_camera();
					
					//reset the user's curcor position to the original position the curcor was in when the user started panning the camera
					SDL_WarpMouse(mouse_x_when_pan, mouse_y_when_pan);
				}
				*/
            }
            else if(event.type == SDL_VIDEORESIZE){							/// window resize
				// don't resize the grid.
				//float new_cell_size = CELL_SIZE * event.resize.h/((float)SCREEN_HEIGHT); // adjust the pixel size.
				//if(new_cell_size - ((int)new_cell_size) >= 0.5f) CELL_SIZE = new_cell_size + 1;
				//else CELL_SIZE = new_cell_size;
				screenRect.w = SCREEN_WIDTH = event.resize.w;
				screenRect.h = SCREEN_HEIGHT = event.resize.h;
				set_window_size(event.resize.w, event.resize.h);		// set window to correct dimensions
			}
			
            if( event.type == SDL_KEYDOWN ){		///keyboard event
                key = event.key.keysym.sym;
				if     (key == controlsGame.pan[d_up])		camera_pan(d_up);		// pan up
				else if(key == controlsGame.pan[d_down])	camera_pan(d_down);		// pan down
				else if(key == controlsGame.pan[d_left])	camera_pan(d_left);		// pan left
				else if(key == controlsGame.pan[d_right])	camera_pan(d_right);	// pan right
				else if(key == controlsGame.debug)			keyF3 ^= 1;				// toggle the keyF3 state
				
			}
			if( event.type == SDL_KEYUP ){								///keyboard event
                // nothing here yet
			}
                
		
    	} // end while(event)
		//no more events to handle at the moment.
		if(mouseStatusLeft==true && beast_find_at_cell(x/CELL_SIZE+cameraX,y/CELL_SIZE+cameraY) == NULL){
			// add beast function
			struct beastData *myBeast;
			myBeast = beast_create(NULL);
			if(myBeast != NULL ){
				myBeast->x = x/CELL_SIZE + cameraX;
				myBeast->y = y/CELL_SIZE + cameraY;
			}
		}
		
		if(SDL_GetTicks()-beastLastEval > 1000/beastEvalsPerSec){
			// evaluate all beasts
			beasts_evaluate();
			beastLastEval = SDL_GetTicks();
		}
		
        // print the grid data
        print_grid(screen);
        print_beasts(screen);
        print_beasts_targets(screen);
        
        // print debugging information
        if(keyF3) print_debugging_information(screen);
        //updates the screen
        SDL_Flip( screen );
        SDL_FillRect(screen, &screenRect, 0);
        //----------------------------------------------------
		// FPS calculation and variable handling
		//----------------------------------------------------
        currentTicks = SDL_GetTicks();
        // it is officially the next second
        if(currentTicks >= ticksSinceLastFPSUpdate + 1000){
			// calculate the FPS
			FPS = cumulativeFrames;//(cumulativeFrames*1000 ) / (currentTicks-ticksSinceLastFPSUpdate);
			cumulativeFrames=0;				// reset cumulative amount of frames
			ticksSinceLastFPSUpdate = currentTicks;	// reset the last FPS update to the number of ticks now.
        }
        cumulativeFrames++;
		
    }// end while(quit == false)


    //Free the surface and quit SDL
    clean_up();

    return 0;
}
Exemplo n.º 7
0
void vultures_refresh(void)
{
	SDL_Flip( vultures_screen );
}
Exemplo n.º 8
0
void DrawScreen(SDL_Surface* screen, Audio *audio, int xx)
{

    if(SDL_MUSTLOCK(screen))
    {
        if(SDL_LockSurface(screen) < 0) return;
    }

    int ii, xs, ys;
    Real value;
    int red, green, blue;

    for (ii=0; ii<(HEIGHT/Y_STRETCH); ii++) {
        value = frequency_component( audio, frequency( FREQ_BASE + (((double)(ii*Y_STRETCH)) * FREQ_MULT) ) );
#ifdef FORMAT_AMP
        value = value * (Real)ii;
#endif
        ((Real *)fourier->data)[ii] = value;
    }

#ifdef NORMALIZE_FOURIER
    normalize( fourier );
    audio_scale( fourier, 20000.0 );
#endif

    for (ii=0; ii<(HEIGHT/Y_STRETCH); ii++) {
        value = ((Real *)fourier->data)[ii];
#ifdef SQUARE_SUPPRESS
        value *= 0.001;
        value *= value;
#endif

        value *= 0.001;

#ifndef SQUARE_SUPPRESS
        if (value < 0) value = -value;
#endif
/*
#ifdef FORMANT_AMP
        value *= (Real)ii;
#endif
*/

          // If capturing, sum the frequencies
        if (capturing) {
            ((Real *)captured->data)[ii] += value;
            captured_slices++;
        }

        red   = (int)value;
        green = 0;
        blue  = 0;
        if (red > 16000) {
            red = 0;
            green = 255;
            blue = 0;
        } else if (red > 255) {
            green = (int)((value-255.0)/20.0);
            if (blue > 512) {
                blue  = (int)((value-512.0)/100.0);
            }
            red   = 255;
        }

          // x stretch
        for (xs=0; xs<X_STRETCH; xs++) {
            for (ys=0; ys<Y_STRETCH; ys++) {
                setpixel(screen, xx+xs, (HEIGHT-1)-(ii*Y_STRETCH)-ys, red, green, blue);
            }
        }

        if (xx+X_STRETCH < WIDTH-X_STRETCH) {
            for (ys=Y_STRETCH; ys<HEIGHT; ys++) {
                if (windowing) {
                    setpixel(screen, xx+X_STRETCH, ys, 0, 0, 255);
                } else {
                    setpixel(screen, xx+X_STRETCH, ys, 0, 255, 0);
                }
            }
        }

    }

    if(SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);

    SDL_Flip(screen);
}
Exemplo n.º 9
0
	SDL_Surface *Movement(SDL_Surface *screen)
	{
		// Movement
		// D -- Mario move LEFT
		// A -- Mario move RIGHT

		SDL_Surface *background = NULL;
		SDL_Surface *mario0 = NULL;
		//SDL_Surface *mario1 = NULL;
		//SDL_Surface *mario2 = NULL;
		SDL_Surface *mario3 = NULL;
		//SDL_Surface *mario4 = NULL;
		//SDL_Surface *mario5 = NULL;
		
		int x,y;
		x = 125;
		y = 520;

		// Image filenames
		const char *background_image = "bin/stage.bmp";
		const char *mario_image0 = "bin/IMG0.bmp";
		//const char *mario_image1 = "bin/IMG1.bmp";
		//const char *mario_image2 = "bin/IMG2.bmp";
		const char *mario_image3 = "bin/IMG3.bmp";
		//const char *mario_image4 = "bin/IMG4.bmp";
		//const char *mario_image5 = "bin/IMG5.bmp";

		background = scrnfunk::load_image(background_image);
		mario0 = scrnfunk::load_image(mario_image0);
		//mario1 = scrnfunk::load_image(mario_image1);
		//mario2 = scrnfunk::load_image(mario_image2);
		mario3 = scrnfunk::load_image(mario_image3);
		//mario4 = scrnfunk::load_image(mario_image4);
		//mario5 = scrnfunk::load_image(mario_image5);
		
		SDL_Rect clip;

		clip.x = x;
		clip.y = y;
		clip.w = 100;
		clip.h = 100;

		scrnfunk::RemoveColor(mario0, 0x00, 0x00, 0xFF); // Blue
		//scrnfunk::RemoveColor(mario1, 0x00, 0x00, 0xFF); // Blue
		//scrnfunk::RemoveColor(mario2, 0x00, 0x00, 0xFF); // Blue
		scrnfunk::RemoveColor(mario3, 0x00, 0x00, 0xFF); // Blue
		scrnfunk::apply_image(x, y, mario0, screen);
					
		if(screen != 0)
			SDL_Flip(screen);

		SDL_Event event;
		
		while(1)
		{
			while(SDL_PollEvent(&event))
			{
				if(event.type == SDL_QUIT)
					return NULL;

				else if(event.type == SDL_KEYDOWN)
				{
					if(event.key.keysym.sym == SDLK_d) // RIGHT
					{	
						scrnfunk::apply_image(x, y, background, screen, &clip); // Cover current Mario
						x=x+10;
						clip.x = x;
						scrnfunk::apply_image(x, y, mario3, screen); // Place new Mario
					}
					else if(event.key.keysym.sym == SDLK_a) // LEFT
					{
						scrnfunk::apply_image(x, y, background, screen, &clip); // Cover current Mario
						x=x-10;
						clip.x = x;
						scrnfunk::apply_image(x, y, mario3, screen); // Place new Mario
					}
				}
			}
			
			if(screen != 0)
				SDL_Flip(screen);
			else
				fprintf(stderr, "Couldn't update screen.\n");
		}
			
		return screen;
	}
Exemplo n.º 10
0
//Fonction principale du jeu du Pendu, elle gérera l'affichage des différentes étapes d'une partie
int jouer_Pendu(SDL_Surface *ecran, char j1[], char j2[]) {
  //Déclaration des variables locales nécassaires pour la fonction
  SDL_Surface *s_mot_cache = NULL, *s_mot_decouvert = NULL, *resultat = NULL, *joueur = NULL;
  SDL_Rect position_mot_decouvert={200,500,0,0}, positionresultat = {50,400,0,0}, positionjoueur = {0,350,0,0};
  SDL_Event event;
  TTF_Font *police = NULL, *police2 = NULL;
  SDL_Color couleurNoire = {0, 0, 0, 0};
  int j=0, i, continuer=1, coups_reussis=0, coups_rates=1, joueuractuel = 1, joueur1, joueur2;
  char c, ch[30], mot_cache[30], mot_decouvert[30];
  Mix_Chunk *son1, *son2; 
  son1 = Mix_LoadWAV("../Music/Mini-jeux/coup_reussi_pendu.ogg");
  son2 = Mix_LoadWAV("../Music/Mini-jeux/coup_rate_pendu.ogg");

  srand(time(NULL));

  //Chargement de la police
  police = TTF_OpenFont("../Police/comicbd.ttf", 30);
  police2 = TTF_OpenFont("../Police/comicbd.ttf", 40);
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
  joueur1 = joueur2 = 0;

  //Point de départ d'un tour (On retourne à cette ligne pour alterner les tours entre les joueurs)
 debut:
  /*Initialisation des variables utilisées durant une partie*/
  c = '0';
  //Génération d'un nombre au hasard entre 1 et 100, ce nombre sera l'indice du mot caché qui sera chargé du fichier mots.txt avec la fonction chargement_Mot
  i = rand()%100+1;
  chargement_Mot(mot_cache,i);
  //Initialisation de la chaine qui va contenir le mot saisi par un joueur
  initialiser(mot_cache,mot_decouvert);
  s_mot_decouvert = TTF_RenderText_Blended(police, mot_decouvert, couleurNoire);
  j++;
  continuer = 1;
  //Alternance du tour
  if(joueuractuel == 1) sprintf(ch,"Joueur : %s",j1);
  else sprintf(ch,"Joueur : %s",j2);
  joueur = TTF_RenderText_Blended(police2, ch, couleurNoire);
  //Boucle while qui gérera l'affichage des différentes étapes du jeu
  while(continuer) {
    SDL_WaitEvent(&event);
    switch(event.type) {
      //En cas de fermeture de la fenêtre
      case SDL_QUIT: continuer = 0; return 0; break;
	//En cas d'appuie sur un bouton, stocker le caractère dans la variable c
      case SDL_KEYDOWN : 
        switch(event.key.keysym.sym) {
          default : c = event.key.keysym.sym; break;
	}

	//Si c'est une lettre en majuscule, la convertir en minuscule
	if(c >= 'A' && c <= 'Z') c -= 32;
	//Si c'est une lettre, faire les tests nécessaires pour voir si le mot caché contient la lettre saisie
	if(c >= 'a' && c <= 'z') {
	  //Si la lettre saisie existe dans le mot caché, l'afficher dans sa/ses position(s) dans le mot découvert (le mot qui contient n tirets | n c'est la longueur du mot caché)
	  if (existe(mot_cache,c) > existe(mot_decouvert,c)) {
	    coups_reussis++;
	    Mix_PlayChannel(1,son1,0);
	    for (i = 0; mot_cache[i] != '\0'; i++) {
	      if (mot_cache[i] == c)
		mot_decouvert[i] = c;
	    }
	    s_mot_decouvert = TTF_RenderText_Blended(police, mot_decouvert, couleurNoire);  
	  }
    /*Si la lettre n'existe pas dans mot_cache, on incrémente les coups ratés de 1, puis on appelle la fonction bonhomme 
      avec le nombre coups_rates qui s'occupera d'afficher l'image correspondante du pendu*/ 
	  else if(existe(mot_cache,c) == existe(mot_decouvert,c)){
	    Mix_PlayChannel(1,son2,0);
	    coups_rates++;
	  } 
	}
	break;
	default : break;
    }

    SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
    bonhomme(ecran,coups_rates);
    SDL_BlitSurface(s_mot_decouvert,NULL, ecran, &position_mot_decouvert);
    //Si le joueur atteint le nombre max de coups ratés, on affiche le mot caché et on garde le nombre de coups ratés afin de le comparer avec celui de l'autre joueur.
    if(coups_rates == 10) {
      if(joueuractuel == 1) {joueuractuel = 2; joueur1 = coups_rates;}
      else {joueuractuel = 1; joueur2 = coups_rates;}
      continuer = 0;
      coups_rates = 1;
      sprintf(ch,"Le mot etait '%s'",mot_cache);
      resultat = TTF_RenderText_Blended(police2, ch, couleurNoire);
      SDL_BlitSurface(resultat,NULL, ecran, &positionresultat);
    }
    //Si le joueur trouve le mot caché, on affiche le texte correspondant et on garde le nombre de coups ratés afin de le comparer avec celui de l'autre joueur.
    else if(!strcmp(mot_cache,mot_decouvert)) {
      if(joueuractuel == 1) {joueuractuel = 2; joueur1 = coups_rates;}
      else {joueuractuel = 1; joueur2 = coups_rates;}
      sprintf(ch,"Bravoo !");
      resultat = TTF_RenderText_Blended(police2, ch, couleurNoire);
      SDL_BlitSurface(resultat,NULL, ecran, &positionresultat);
      continuer = 0;
      coups_rates = 1;
    }
    SDL_BlitSurface(joueur,NULL, ecran, &positionjoueur);
    SDL_Flip(ecran);
  }
  sleep(2);

  //Si les 2 joueurs ont le même score ou si c'est le tour du 2ème joueur, relancer le jeu avec un mot différent.
  if(joueur1 == joueur2 || j&1) goto debut;

  SDL_FreeSurface(s_mot_decouvert);
  SDL_FreeSurface(s_mot_cache);
  SDL_FreeSurface(resultat);
  Mix_FreeChunk(son1);//Libération du son
  Mix_FreeChunk(son2);//Libération du son

  //Renvoie de l'indice du gagnant
  if(joueur1 > joueur2) return 2;
  else return 1;
}
Exemplo n.º 11
0
void Graphics::flip(){
	SDL_Flip(screen_);
}
Exemplo n.º 12
0
/*Cette fonction sert de page d'accueil du jeu du Pendu, elle fait appel à la fonction jouer_Pendu quand l'utilisateur
  appuie sur "Entrer", et à la fin elle récupère l'indice du gagnant et le renvoie à son tour*/
int Accueil_Pendu(SDL_Surface *ecran, char *j1, char *j2) {
  //Déclaration des variables locales nécessaires pour la fonction.
  SDL_Surface *texte1 = NULL, *texte2 = NULL, *pendu = NULL;
  SDL_Rect positiontexte1, positiontexte2, positionpendu;
  SDL_Event event;
  TTF_Font *police1 = NULL, *police2 = NULL;
  SDL_Color couleurNoire = {0, 0, 0, 0}, couleurBlanche = {255, 255, 255, 0};
  int continuer = 1, gagnant;
  Mix_Music *musique; //Création d'un pointeur de type Mix_Music
  Mix_VolumeMusic(MIX_MAX_VOLUME);
  musique = Mix_LoadMUS("../Music/Mini-jeux/pendu.ogg"); //Chargement de la musique
  Mix_PlayMusic(musique, -1); //Jouer infiniment la musique

  //Chargement de l'image du pendu
  pendu = IMG_Load("../images/Mini-jeux/Pendu10.png");

  //Chargement de la police
  police1 = TTF_OpenFont("../Police/chata.ttf", 65);
  police2 = TTF_OpenFont("../Police/chata.ttf", 25);

  //Initialisation du texte
  texte1 = TTF_RenderText_Shaded(police1, "Le Pendu", couleurNoire, couleurBlanche);
  texte2 = TTF_RenderText_Shaded(police2, "Appuyer sur entrer pour commencer", couleurNoire, couleurBlanche);

  SDL_SetColorKey(texte1, SDL_SRCCOLORKEY, SDL_MapRGB(texte1->format, 255, 255, 255));
  SDL_SetColorKey(texte2, SDL_SRCCOLORKEY, SDL_MapRGB(texte2->format, 255, 255, 255));

  //Remplissage de l'écran principal avec la couleur blanche
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100));

  //Initialisation des positions des différentes surfaces et textes
  positiontexte1.x = (ecran->w - texte1->w) / 2;
  positiontexte1.y = 0;
  positiontexte2.x = (ecran->w - texte2->w) / 2;
  positiontexte2.y = 250 + (ecran->h - texte2->h) / 2;
  positionpendu.x = (ecran->w / 2) - (pendu->w / 2);
  positionpendu.y = (ecran->h / 2) - (pendu->h / 2);

  //Remplissage de l'écran principal avec la couleur blanche
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100));

  //Blit du texte de la page d'accueil
  SDL_BlitSurface(texte1, NULL, ecran, &positiontexte1);
  SDL_BlitSurface(texte2, NULL, ecran, &positiontexte2);

  //Blit de l'image du pendu
  SDL_BlitSurface(pendu, NULL, ecran, &positionpendu);

  //Mise à jour de l'écran
  SDL_Flip(ecran);

  /*Une boucle infine afin de maintenir l'affichage et quitter le programme quand l'utilisateur ferme la fenêtre*/
  while (continuer) {
    SDL_PollEvent(&event);
    switch(event.type) {
    case SDL_QUIT:
      continuer = 0;
      break;
    //En cas d'apuui sur un bouton
    case SDL_KEYDOWN :
      //S'il s'agit du bouton "Entrer", appeler la fonction joueur_Pendu
      if(event.key.keysym.sym == SDLK_RETURN) gagnant = jouer_Pendu(ecran,j1,j2);
      continuer = 0;
      break;
    default: break;
    }
  }

  //Libération de la mémoire occupée par les surfaces et les polices et arrêt de la SDL
  TTF_CloseFont(police1);
  TTF_CloseFont(police2);
  SDL_FreeSurface(pendu);
  SDL_FreeSurface(texte1);
  SDL_FreeSurface(texte2);
  Mix_FreeMusic(musique); //Libération de la musique

  return gagnant;
}
Exemplo n.º 13
0
int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <bbbout-file>\n", argv[0]);
        return 1;
    }

    int err;
    bbbout_stream *bbbout = bbbout_open_read(argv[1], &err);

    if (err != BBBOUT_SUCCESS) {
        fprintf(stderr, "%s: while reading '%s': %s", argv[0], argv[1], bbbout_strerror(err));
        return 1;
    }

    const int width = bbbout->width, height = bbbout->height;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
        fprintf(stderr, "Error initializing SDL: %s\n", SDL_GetError());
        return 1;
    }

    screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    if (screen == NULL) {
        fprintf(stderr, "Unable to set %ix%i at 32 bpp: %s\n", width, height, SDL_GetError());
    }

    uint32_t gen_id;

    char *alive = malloc(width * height * sizeof(char));
    char *dying = malloc(width * height * sizeof(char));

    err = bbbout_read_generation(bbbout, &gen_id, alive, dying);

    while (err == BBBOUT_SUCCESS) {
        unsigned int ticks1 = SDL_GetTicks();

        handle_events();

        int i;

        for (i = 0; i < width * height; i++) {
            if (dying[i]) {
                struct rgb24 team_color = bbbout->team_colors[(unsigned char) dying[i]];

                *((uint32_t *) screen->pixels + i) = SDL_MapRGB(screen->format, team_color.red/2, team_color.green/2, team_color.blue/2);
            } else {
                *((uint32_t *) screen->pixels + i) = 0;
            }
        }

        for (i = 0; i < width * height; i++) {
            if (alive[i]) {
                struct rgb24 team_color = bbbout->team_colors[(unsigned char) alive[i]];

                *((uint32_t *) screen->pixels + i) = SDL_MapRGB(screen->format, team_color.red, team_color.green, team_color.blue);
            }
        }

        SDL_Flip(screen);

        char *temp = dying;
        dying = alive;
        alive = temp;

        err = bbbout_read_generation(bbbout, &gen_id, alive, NULL);

        unsigned int ticks2 = SDL_GetTicks();

        if (ticks2 - ticks1 >= 33) {
            SDL_Delay(1);
        } else {
            SDL_Delay(33 - (ticks2 - ticks1));
        }
    }

    if (err < BBBOUT_SUCCESS) {
        puts(bbbout_strerror(err));
    }

    free(alive);
    free(dying);

    SDL_Quit();

    return 0;
}
Exemplo n.º 14
0
/*-----------------------------------------------------------------
 * Desc: should do roughly what getchar() does, but in raw 
 * 	 (SLD) keyboard mode. 
 * 
 * Return: the (SDLKey) of the next key-pressed event cast to (int)
 *
 *-----------------------------------------------------------------*/
int
getchar_raw (void)
{
  SDL_Event event;
  int Returnkey = 0;
  
  //  keyboard_update ();   /* treat all pending keyboard-events */

  while ( !Returnkey )
    {
      while (!SDL_WaitEventTimeout (&event, 10))    /* wait for next event */
	SDL_Flip (ne_screen);
      
      switch (event.type)
	{
	case SDL_KEYDOWN:
	  /* 
	   * here we use the fact that, I cite from SDL_keyboard.h:
	   * "The keyboard syms have been cleverly chosen to map to ASCII"
	   * ... I hope that this design feature is portable, and durable ;)  
	   */
	  Returnkey = (int) event.key.keysym.sym;
	  if ( event.key.keysym.mod & KMOD_SHIFT ) 
	    Returnkey = toupper( (int)event.key.keysym.sym );
	  break;

	case SDL_JOYBUTTONDOWN: 
#ifdef JOY_BUTTON_COUNT
	  if (event.jbutton.button < JOY_BUTTON_COUNT)
	    Returnkey = joy_button_map[event.jbutton.button];
#else
	  if (event.jbutton.button == 0)
	    Returnkey = JOY_BUTTON1;
	  else if (event.jbutton.button == 1) 
	    Returnkey = JOY_BUTTON2;
	  else if (event.jbutton.button == 2) 
	    Returnkey = JOY_BUTTON3;
#endif
	  break;

	case SDL_MOUSEBUTTONDOWN:
	  if (event.button.button == SDL_BUTTON_LEFT)
	    Returnkey = MOUSE_BUTTON1;
	  else if (event.button.button == SDL_BUTTON_RIGHT)
	    Returnkey = MOUSE_BUTTON2;
	  else if (event.button.button == SDL_BUTTON_MIDDLE)  
	    Returnkey = MOUSE_BUTTON3;
	  else if (event.button.button == SDL_BUTTON_WHEELUP)
	    Returnkey = MOUSE_WHEELUP;
	  else if (event.button.button == SDL_BUTTON_WHEELDOWN)
	    Returnkey = MOUSE_WHEELDOWN;
	  break;

	default:
	  SDL_PushEvent (&event);  /* put this event back into the queue */
	  update_input ();  /* and treat it the usual way */
	  continue;
	}

    } /* while(1) */

  return ( Returnkey );

} /* getchar_raw() */
Exemplo n.º 15
0
int your_test(int argc, char **argv)
{
    int done=0;

    /* check args */
    if(argc!=2)
    {
        fprintf(stderr,"%s file.ttf\n",argv[0]);
        return 1;
    }

    /* initialize the cache to NULL */
    memset(text,0,sizeof(text));

    /* start SDL video */
    if(SDL_Init(SDL_INIT_VIDEO)==-1)
    {
        printf("SDL_Init: %s\n",SDL_GetError());
        return 1;
    }
    atexit(SDL_Quit); /* remember to quit SDL */

    /* open the screen */
    if(!(screen=SDL_SetVideoMode(1200,1000,0,0)))
    {
        printf("SDL_SetVideoMode: %s\n",SDL_GetError());
        return 1;
    }

    /* allow for key repeat (so the user can hold down a key...) */
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    /* start SDL_ttf */
    if(TTF_Init()==-1)
    {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 2;
    }
    atexit(TTF_Quit); /* remember to quit SDL_ttf */
    atexit(free_font); /* remember to free any loaded font and glyph cache */

    while(!done)
    {
        SDL_Event event;
        static int x=0, y=0, need_draw=1,last_size=0, last_start_glyph=-1;

        /* smartly load font and generate new glyph cache (font_size change) */
        if(last_size!=font_size)
        {
            if(font_size<1)
                font_size=1;
            load_font(argv[1], font_size);
            need_draw=1;
            last_size=font_size;
        }
        /* smartly generate new glyph cache (page change) */
        if(last_start_glyph!=start_glyph)
        {
            cache_glyphs();
            need_draw=1;
            last_start_glyph=start_glyph;
        }
        /* smartly redraw as needed */
        if(need_draw)
        {
            SDL_FillRect(screen,0,~0);
            draw_table(x,y);
            SDL_Flip(screen);
            need_draw=0;
        }
        /* wait for events and handle them */
        /* this waits for one, then handles all that are queued before finishing */
        if(SDL_WaitEvent(&event))
            do {
                switch(event.type)
                {
                case SDL_QUIT:
                    done=1;
                    break;
                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym)
                    {
                    case '0':
                        start_glyph=0;
                        break;
                    case SDLK_LEFT:
                        start_glyph=(start_glyph+0x10000-0x80)&0xffff;
                        break;
                    case SDLK_RIGHT:
                        start_glyph=(start_glyph+0x80)&0xffff;
                        break;
                    case SDLK_UP:
                        font_size++;
                        break;
                    case SDLK_DOWN:
                        font_size--;
                        break;
                    case 'n':
                        style=TTF_STYLE_NORMAL;
                        last_start_glyph=-1;
                        break;
                    case 'b':
                        style^=TTF_STYLE_BOLD;
                        last_start_glyph=-1;
                        break;
                    case 'i':
                        style^=TTF_STYLE_ITALIC;
                        last_start_glyph=-1;
                        break;
                    case 'u':
                        style^=TTF_STYLE_UNDERLINE;
                        last_start_glyph=-1;
                        break;
                    case 's':
                        style^=TTF_STYLE_STRIKETHROUGH;
                        last_start_glyph=-1;
                        break;
                    case 'k':
                        kerning=!kerning;
                        printf("kerning=%d\n",kerning);
                        last_start_glyph=-1;
                        break;
                    case 'h':
                        hinting=(hinting+1)%4;
                        printf("hinting=%s\n",
                            hinting==0?"Normal":
                        hinting==1?"Light":
                        hinting==2?"Mono":
                        hinting==3?"None":
                        "Unknonwn");
                        last_start_glyph=-1;
                        break;
                    case '=':
                        ++outline;
                        printf("outline=%d\n",outline);
                        last_start_glyph=-1;
                        break;
                    case '-':
                        if(outline>0)
                            --outline;
                        printf("outline=%d\n",outline);
                        last_start_glyph=-1;
                        break;
                    case 'q':
                    case SDLK_ESCAPE:
                        done=1;
                        break;
                    default:
                        break;
                    }
                    break;
                case SDL_MOUSEMOTION:
                    if(event.motion.state)
                    {
                        x=event.motion.x;
                        y=event.motion.y;
                        need_draw=1;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    x=event.button.x;
                    y=event.button.y;
                    need_draw=1;
                    break;
                }
            } while(SDL_PollEvent(&event));
    } /* main loop */

    return 0;
}
Exemplo n.º 16
0
int
SDL_WM_ToggleFullScreen(SDL_Surface * surface)
{
    int length;
    void *pixels;
    Uint8 *src, *dst;
    int row;
    int window_w;
    int window_h;

    if (!SDL_PublicSurface) {
        SDL_SetError("SDL_SetVideoMode() hasn't been called");
        return 0;
    }

    /* Copy the old bits out */
    length = SDL_PublicSurface->w * SDL_PublicSurface->format->BytesPerPixel;
    pixels = SDL_malloc(SDL_PublicSurface->h * length);
    if (pixels) {
        src = (Uint8*)SDL_PublicSurface->pixels;
        dst = (Uint8*)pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += SDL_PublicSurface->pitch;
            dst += length;
        }
    }

    /* Do the physical mode switch */
    if (SDL_GetWindowFlags(SDL_VideoWindow) & SDL_WINDOW_FULLSCREEN) {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 0) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags &= ~SDL_FULLSCREEN;
    } else {
        if (SDL_SetWindowFullscreen(SDL_VideoWindow, 1) < 0) {
            return 0;
        }
        SDL_PublicSurface->flags |= SDL_FULLSCREEN;
    }

    /* Recreate the screen surface */
    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        /* We're totally hosed... */
        return 0;
    }

    /* Center the public surface in the window surface */
    SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h);
    SDL_VideoViewport.x = (window_w - SDL_VideoSurface->w)/2;
    SDL_VideoViewport.y = (window_h - SDL_VideoSurface->h)/2;
    SDL_VideoViewport.w = SDL_VideoSurface->w;
    SDL_VideoViewport.h = SDL_VideoSurface->h;

    /* Do some shuffling behind the application's back if format changes */
    if (SDL_VideoSurface->format->format != SDL_WindowSurface->format->format) {
        if (SDL_ShadowSurface) {
            if (SDL_ShadowSurface->format->format == SDL_WindowSurface->format->format) {
                /* Whee!  We don't need a shadow surface anymore! */
                SDL_VideoSurface->flags &= ~SDL_DONTFREE;
                SDL_FreeSurface(SDL_VideoSurface);
                SDL_free(SDL_ShadowSurface->pixels);
                SDL_VideoSurface = SDL_ShadowSurface;
                SDL_VideoSurface->flags |= SDL_PREALLOC;
                SDL_ShadowSurface = NULL;
            } else {
                /* No problem, just change the video surface format */
                SDL_FreeFormat(SDL_VideoSurface->format);
                SDL_VideoSurface->format = SDL_WindowSurface->format;
                SDL_VideoSurface->format->refcount++;
                SDL_InvalidateMap(SDL_ShadowSurface->map);
            }
        } else {
            /* We can make the video surface the shadow surface */
            SDL_ShadowSurface = SDL_VideoSurface;
            SDL_ShadowSurface->pitch = SDL_CalculatePitch(SDL_ShadowSurface);
            SDL_ShadowSurface->pixels = SDL_malloc(SDL_ShadowSurface->h * SDL_ShadowSurface->pitch);
            if (!SDL_ShadowSurface->pixels) {
                /* Uh oh, we're hosed */
                SDL_ShadowSurface = NULL;
                return 0;
            }
            SDL_ShadowSurface->flags &= ~SDL_PREALLOC;

            SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0);
            SDL_VideoSurface->flags = SDL_ShadowSurface->flags;
            SDL_VideoSurface->flags |= SDL_PREALLOC;
            SDL_FreeFormat(SDL_VideoSurface->format);
            SDL_VideoSurface->format = SDL_WindowSurface->format;
            SDL_VideoSurface->format->refcount++;
            SDL_VideoSurface->w = SDL_ShadowSurface->w;
            SDL_VideoSurface->h = SDL_ShadowSurface->h;
        }
    }

    /* Update the video surface */
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels +
        SDL_VideoViewport.y * SDL_VideoSurface->pitch +
        SDL_VideoViewport.x  * SDL_VideoSurface->format->BytesPerPixel);
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    /* Copy the old bits back */
    if (pixels) {
        src = (Uint8*)pixels;
        dst = (Uint8*)SDL_PublicSurface->pixels;
        for (row = 0; row < SDL_PublicSurface->h; ++row) {
            SDL_memcpy(dst, src, length);
            src += length;
            dst += SDL_PublicSurface->pitch;
        }
        SDL_Flip(SDL_PublicSurface);
        SDL_free(pixels);
    }

    /* We're done! */
    return 1;
}
Exemplo n.º 17
0
int main( int argc, char* args[] )
{
    //Quit flag
    bool quit = false;

    //The timer starting time
    Uint32 start = 0;

    //The timer start/stop flag
    bool running = true;

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

    //Load the files
    if( load_files() == false )
    {
        return 1;
    }

    //Generate the message surface
    startStop = TTF_RenderText_Solid( font, "Press S to start or stop the timer", textColor );

    //Start the timer
    start = SDL_GetTicks();

    //While the user hasn't quit
    while( quit == false )
    {
        //While there's an event to handle
        while( SDL_PollEvent( &event ) )
        {
            //If a key was pressed
            if( event.type == SDL_KEYDOWN )
            {
                //If s was pressed
                if( event.key.keysym.sym == SDLK_s )
                {
                    //If the timer is running
                    if( running == true )
                    {
                        //Stop the timer
                        running = false;
                        start = 0;
                    }
                    else
                    {
                        //Start the timer
                        running = true;
                        start = SDL_GetTicks();
                    }
                }
            }

            //If the user has Xed out the window
            else if( event.type == SDL_QUIT )
            {
                //Quit the program
                quit = true;
            }
        }

        //Apply the background
        apply_surface( 0, 0, background, screen );

        //Apply the message
        apply_surface( ( SCREEN_WIDTH - startStop->w ) / 2, 200, startStop, screen );

        //If the timer is running
        if( running == true )
        {
            //The timer's time as a string
            std::stringstream time;

            //Convert the timer's time to a string
            time << "Timer: " << SDL_GetTicks() - start;

            //Render the time surface
            seconds = TTF_RenderText_Solid( font, time.str().c_str(), textColor );

            //Apply the time surface
            apply_surface( ( SCREEN_WIDTH - seconds->w ) / 2, 50, seconds, screen );

            //Free the time surface
            SDL_FreeSurface( seconds );
        }

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

    //Clean up
    clean_up();

    return 0;
}
Exemplo n.º 18
0
int
main ( int argc, char *argv[] )
{
    bool quit = false;
    int sprite_x = 0;
    int inc_val  = 0;
    char m[80];
    int u = 0;
    int bgX = 0;
    int bgY = 0;

    if( init() == false )
        return EXIT_FAILURE;
    if( load_files() == false )
        return EXIT_FAILURE;

    clip[0].x = 0;
    clip[0].y = 0;
    clip[0].w = 32;
    clip[0].h = 32;

    //apply_surface( 0, 0, background, screen );
    apply_surface( 10, 10, sprite_image, screen, &clip[0] );
    //apply_surface( 10, 10, sprite_image, screen );
    if( SDL_Flip( screen ) == -1 )
    {
        return EXIT_FAILURE;
    }

    next_time = SDL_GetTicks() + TICK_INTERVAL;

    while( quit == false ){

        SDL_Rect tmp;
        SDL_Rect tmp2;
        
        tmp.x = sprite_x;
        tmp.y = 0;
        tmp.w = 32;
        tmp.h = 32;

        quit = handle_events( &inc_val );

        tmp2.x = 210 + 150;
        tmp2.y = 0;
        tmp2.w = 16;
        tmp2.h = 16;

        if( rightdown )
            inc_val++;

        if( inc_val > 0 && leftdown )
            inc_val--;

        //rightdown = false;
        //leftdown = false;

        //
        //fprintf(stderr, "x = %d\n", sprite_x);

        sprintf( m, "%d", inc_val );

        message = TTF_RenderText_Solid( font, m, textColor );

        SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, 0, 0, 0 ) );
        //apply_surface( 10, 10, sprite_image, screen, &tmp );
        //apply_surface( 100, 100, sprite_image2, screen, &tmp2 );
        draw();

        bgX -= 2;

        if( bgX <= -background->w ){
            bgX = 0;
        }
        /*
        if( !updown && u != 50 ){
            u = 100;

        }
        */
        apply_surface( bgX, bgY, background, screen );
        apply_surface( bgX + background->w, bgY, background, screen );
        apply_surface( 50, 50, message, screen );
        //apply_surface( 10, 10, sprite_image, screen );
        if( SDL_Flip( screen ) == -1 )
        {
            return EXIT_FAILURE;
        }

        sprite_x = (sprite_x + 32) % 256;
        //SDL_Delay(30);
        SDL_Delay( time_left() );
        //SDL_free( tmp );
        next_time += TICK_INTERVAL;
    }

    //SDL_Delay(5000);

    return EXIT_SUCCESS;
}/* ----------  end of function main  ---------- */
Exemplo n.º 19
0
void PrintMissingFilesToScreen() {
	SDL_ShowCursor(SDL_ENABLE);

    std::string instruction = "Dune Legacy uses the data files from original Dune II. The following files are missing:\n";

    std::vector<std::string> MissingFiles = FileManager::getMissingFiles(LNG_ENG);

    std::vector<std::string>::const_iterator iter;
    for(iter = MissingFiles.begin(); iter != MissingFiles.end(); ++iter) {
        instruction += " " + *iter + "\n";
    }

    instruction += "\nPut them in one of the following directories:\n";
    std::vector<std::string> searchPath = FileManager::getSearchPath();
    std::vector<std::string>::const_iterator searchPathIter;
    for(searchPathIter = searchPath.begin(); searchPathIter != searchPath.end(); ++searchPathIter) {
        instruction += " " + *searchPathIter + "\n";
    }

    instruction += "\nYou may want to add GERMAN.PAK or FRENCH.PAK for playing in these languages.\n";
    instruction += "\n\nPress ESC to exit.";

    SDL_Surface* pSurface = pFontManager->createSurfaceWithMultilineText(instruction, 255, FONT_STD12);
    SDL_Rect dest = { 30, 30, pSurface->w, pSurface->h };
    SDL_BlitSurface(pSurface, NULL, screen, &dest);
    SDL_FreeSurface(pSurface);

	SDL_Flip(screen);

	SDL_Event	event;
	bool quiting = false;
	while(!quiting)	{
	    SDL_Delay(20);

		while(SDL_PollEvent(&event)) {
		    //check the events
            switch (event.type)
            {
                case (SDL_KEYDOWN):	// Look for a keypress
                {
                    switch(event.key.keysym.sym) {
                        case SDLK_ESCAPE:
                            quiting = true;
                            break;

                        default:
                            break;
                    }
                } break;


                case SDL_QUIT:
                    quiting = true;
                    break;

                default:
                    break;
            }
		}
	}
}
Exemplo n.º 20
0
int main( int argc, char* args[] )
{
    if ( SDL_Init( SDL_INIT_VIDEO ) == -1 )
        return 1;

    SDL_Surface *screen = SDL_SetVideoMode( WIDTH, HEIGHT, 32, SDL_SWSURFACE );
    if ( !screen )
        return 1;

	// Initialize the grid from the BMP file.
    SDL_Surface *temp = SDL_LoadBMP( "test.bmp" );
	temp = SDL_ConvertSurface( temp, screen->format, SDL_SWSURFACE ); 
	SDL_LockSurface( temp );
	for( int y=0;y<HEIGHT;y++ )
	{
		for ( int x=0;x<WIDTH;x++ )
		{
			Uint8 r,g,b;
			Uint32 *src = ( (Uint32 *)( (Uint8 *)temp->pixels + y*temp->pitch ) ) + x;
			SDL_GetRGB( *src, temp->format, &r, &g, &b );
			
			// Points inside get marked with a dx/dy of zero.
			// Points outside get marked with an infinitely large distance.
			if ( g < 128 )
			{
				Put( grid1, x, y, inside );
				Put( grid2, x, y, empty );
			} else {
				Put( grid2, x, y, inside );
				Put( grid1, x, y, empty );
			}
		}
	}
	SDL_UnlockSurface( temp );

	// Generate the SDF.
	GenerateSDF( grid1 );
	GenerateSDF( grid2 );
	
	// Render out the results.
	SDL_LockSurface( screen );
	for( int y=0;y<HEIGHT;y++ )
	{
		for ( int x=0;x<WIDTH;x++ )
		{
			// Calculate the actual distance from the dx/dy
			int dist1 = (int)( sqrt( (double)Get( grid1, x, y ).DistSq() ) );
			int dist2 = (int)( sqrt( (double)Get( grid2, x, y ).DistSq() ) );
			int dist = dist1 - dist2;

			// Clamp and scale it, just for display purposes.
			int c = dist*3 + 128;
			if ( c < 0 ) c = 0;
			if ( c > 255 ) c = 255;

			Uint32 *dest = ( (Uint32 *)( (Uint8 *)screen->pixels + y*screen->pitch ) ) + x;
			*dest = SDL_MapRGB( screen->format, c, c, c );
		}
	}
	SDL_UnlockSurface( screen );
	SDL_Flip( screen );

	// Wait for a keypress
	SDL_Event event;
	while( true )
	{
		if ( SDL_PollEvent( &event ) ) 
		switch( event.type )
		{
		case SDL_QUIT:
		case SDL_KEYDOWN:
			return true;
		}
	}

	return 0;
}
Exemplo n.º 21
0
//Shows menu texts
void Game::showMenu() {
	Surface::apply_surface(0, 200, menu, screen);
	Surface::apply_surface(0, 300, menu2, screen);
	SDL_Flip(screen);
}
Exemplo n.º 22
0
	bool CGame::Start()
	{
		// Esta variable nos ayudara a controlar la salida del juego...
		int salirJuego = false;
		int i = 0;

		while (salirJuego == false)
		{

			//Maquina de estados
			switch (estado)
			{

			case Estado::ESTADO_INICIANDO: //inicializando
				printf("1.- Estado_Iniciando");
				Iniciando();
				InicializandoStage();
				estado = ESTADO_MENU;    //estado = ESTADO_MENU 
				break;
			case Estado::ESTADO_MENU:	   //MENU
				menu->Pintar();
				textos->Pintar(MODULO_FondoTexto_TITULO,160,50);
				textos->Pintar(MODULO_FondoMenu_NOMBRE,400, 410);
				Menu();
				
				
				

				//estado= ESTADO_JUGANDO
				break;

			case ESTADO_PRE_JUGANDO:
				NivelActual = 0;
				vida = 1;
				enemigosEliminados = 0;
				estado = ESTADO_JUGANDO;

				break;
			case Estado::ESTADO_JUGANDO: //JUGAR
				
				for (int i = 0; i < nivel[NivelActual].NumeroEnemigosVisibles; i++)
				{
					enemigoArreglo[i]->GetNaveObjeto()->Actualizar();
				}
				MoverEnemigo();
				fondo->Pintar();
				//SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
				keys = SDL_GetKeyState(NULL);
				if (keys[SDLK_RIGHT])
				{
					if (!EsLimitePantalla(nave->GetNaveObjeto(), BORDE_DERECHO))
						nave->MoverDerecha(nivel[NivelActual].VelocidadNavePropia);

				}
				if (keys[SDLK_LEFT])
				{
					if (!EsLimitePantalla(nave->GetNaveObjeto(), BORDE_IZQUIERDO))
						nave->MoverIzquierda(nivel[NivelActual].VelocidadNavePropia);
				}
				if (keys[SDLK_UP])
				{
					if (!EsLimitePantalla(nave->GetNaveObjeto(), BORDE_SUPERIOR))
						nave->MoverArriba(nivel[NivelActual].VelocidadNavePropia);
				}
				if (keys[SDLK_DOWN])
				{
					if (!EsLimitePantalla(nave->GetNaveObjeto(), BORDE_INFERIOR))
						nave->MoverAbajo(nivel[NivelActual].VelocidadNavePropia);
				}
				if (keys[SDLK_SPACE])
				{
					nave->Disparar(NAVE_PROPIA, nivel[NivelActual].BalasMaximas);
				}

				//////////////simulacion de coliciones
				if (keys[SDLK_x]){//bala enemigo a nuestra nave
					nave->simularColision(true);

				}

				if (keys[SDLK_c]){//nuestra bala a nave enemigo
					int enemigoAEliminar = rand() % nivel[NivelActual].NumeroEnemigosVisibles;
					enemigoArreglo[enemigoAEliminar]->simularColision(true);
				}


				if (keys[SDLK_v]){//nuestra nave a nave enemigo
				}
				///////////////////////////////////////////////
				//control de coliciones

				for (int i = 0; i<nivel[NivelActual].NumeroEnemigosVisibles; i++){
					if (enemigoArreglo[i]->estaColicionandoConBala(nave))
						vida--;
					if (nave->estaColicionandoConBala(enemigoArreglo[i])){
						enemigoArreglo[i]->setVisible(false);
						enemigosEliminados++;
						nave->simularColision(false);
						if (enemigosEliminados < nivel[NivelActual].NumeroEnemigoAEliminar){
							enemigoArreglo[i]->CrearNuevo();
						}
					}

				}

				///////////////////////////////////////
				if (vida <= 0)
					estado = ESTADO_TERMINANDO;
				if (enemigosEliminados >= nivel[NivelActual].NumeroEnemigoAEliminar){
					NivelActual++;

				}
			
				nave->Pintar(NAVE_PROPIA);
				
				for (int i = 0; i < nivel[NivelActual].NumeroEnemigosVisibles; i++)
				{
					enemigoArreglo[i]->Pintar(NAVE_ENEMIGO);
					enemigoArreglo[i]->AutoDispara(nivel[NivelActual].BalasMaximas);
				}

				if (keys[SDLK_ESCAPE])
				{
			
					
				}
				break;

			case Estado::ESTADO_TERMINANDO: //TERMINAR
				
				break;

			case Estado::ESTADO_FINALIZADO:  //FINALIZAR
				
				break;
			}
			while (SDL_PollEvent(&event))
			{
				if (event.type == SDL_QUIT) { salirJuego = true; }     //    Si se detecta una salida 
				if (event.type == SDL_KEYDOWN) {} //   una dirección (abajo) del teclado.
			}
			SDL_Flip(screen);  //guarda en memoria buffer

			//calculando FPS
			tiempoFrameFinal = SDL_GetTicks();
			while (tiempoFrameFinal < (tiempoFrameInicial + FPS_DELAY)){
				tiempoFrameFinal = SDL_GetTicks();
				SDL_Delay(1);
			}


			printf("Frames:%d Tiempo:%d Tiempo Promedio:%f Tiempo Por Frame:%d FPS:%f\n", tick, SDL_GetTicks(), (float)SDL_GetTicks() / (float)tick, tiempoFrameFinal - tiempoFrameInicial,1000.0f / (float) (tiempoFrameFinal-tiempoFrameInicial));
		    tiempoFrameInicial = tiempoFrameFinal; //Marcamos el inicio nuevamente
			tick++;
		}
		return true;
}
Exemplo n.º 23
0
bool SDLDraw::copyDoubleBufferandFlip()
{
    if(SDL_Flip(FrontBuffer)==0)
        return true;
    return false;
}
Exemplo n.º 24
0
int
main (int argc, char **argv)
{
    SDL_Surface *image;
    nile_t *nl;
    char mem[500000];
    uint32_t texture_pixels[TEXTURE_WIDTH * TEXTURE_HEIGHT] = {0};
    real angle = 0;
    real scale;

    if (SDL_Init (SDL_INIT_VIDEO) == -1)
        DIE ("SDL_Init failed: %s", SDL_GetError ());
    if (!SDL_SetVideoMode (DEFAULT_WIDTH, DEFAULT_HEIGHT, 0,
                           SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF))
        DIE ("SDL_SetVideoMode failed: %s", SDL_GetError ());
    image = SDL_GetVideoSurface ();

    nl = nile_new (NTHREADS, mem, sizeof (mem));

    ilInit ();
    ilBindImage (iluGenImage ());
    if (argc < 3)
        return -1;
    printf ("loading: %s\n", argv[1]);
    ilLoadImage (argv[1]);
    ilCopyPixels (0, 0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, IL_BGRA,
                  IL_UNSIGNED_BYTE, &texture_pixels);
    int filter = atoi (argv[2]);

    for (;;) {
        angle += 0.001;
        scale = fabs (angle - (int) angle - 0.5) * 10;
        SDL_Event event;
        if (SDL_PollEvent (&event) && event.type == SDL_QUIT)
            break;

        SDL_FillRect (image, NULL, 0);
        SDL_LockSurface (image);

            matrix_t M = matrix_new ();
            M = matrix_translate (M, 250, 250);
            M = matrix_rotate (M, angle);
            M = matrix_scale (M, scale, scale);
            M = matrix_translate (M, -250, -250);
            matrix_t I = matrix_inverse (M);

            nile_Kernel_t *texture =
                gezira_ReadFromImage_ARGB32 (nl, texture_pixels, TEXTURE_WIDTH,
                                             TEXTURE_HEIGHT, TEXTURE_WIDTH);
            /*
             */
            texture = nile_Pipeline (nl,
                    gezira_ImageExtendReflect (nl, TEXTURE_WIDTH, TEXTURE_HEIGHT),
                    texture, NULL);
            if (filter == 2)
                texture = gezira_BilinearFilter (nl, texture);
            if (filter == 3)
                texture = gezira_BicubicFilter (nl, texture);
            /*
             */
            texture = nile_Pipeline (nl, 
                gezira_TransformPoints (nl, I.a, I.b, I.c, I.d, I.e - 150, I.f - 125),
                texture, NULL);
            nile_Kernel_t *pipeline = nile_Pipeline (nl,
                gezira_TransformBeziers (nl, M.a, M.b, M.c, M.d, M.e, M.f),
                gezira_ClipBeziers (nl, 0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT),
                gezira_Rasterize (nl),
                gezira_ApplyTexture (nl, texture),
                gezira_WriteToImage_ARGB32 (nl, image->pixels,
                                            DEFAULT_WIDTH, DEFAULT_HEIGHT,
                                            image->pitch / 4),
                NULL);

            nile_feed (nl, pipeline, path, 6, path_n, 1);
            nile_sync (nl);

        SDL_UnlockSurface (image);
        SDL_Flip (image);
    }

    nile_free (nl);
    printf ("done\n");

    return 0;
}
Exemplo n.º 25
0
void		place_life(t_struct *st)
{
  st->img = IMG_Load(LIFE1);
  SDL_BlitSurface(st->img, NULL, st->ecran, &st->pos);
  SDL_Flip(st->ecran);
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
    
    //Network vars
    int udpSd, tcpSd;
    char buffer[5];
    int myId;
    
    //SDL vars
    SDL_Event event;
    
    //Screen
    SDL_Surface* screen = NULL;
    
    //Tanks
    SDL_Surface* blueTank = NULL;
    SDL_Surface* blueCannon = NULL;
    SDL_Surface* redTank = NULL;
    SDL_Surface* redCannon = NULL;
    
    //Bullet
    SDL_Surface* bullet = NULL;
    
    //WorldMap
    SDL_Surface* worldMap = NULL;
    
    //rotation Images
    //SDL_Surface* rotatedTank[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    //SDL_Surface* rotatedCannon[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    SDL_Surface* rotatedBullet[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    
    //SDL_Rect Tankoffset[6] = {400,300,0,0};
    //SDL_Rect Cannonoffset[6] = {400,300,0,0};

    //UserInterface vars
    SDL_Surface* UIhealth;
    SDL_Surface* UIreload;
    SDL_Surface* UIredPoints;
    SDL_Surface* UIbluePoints;
    
    TTF_Font *font = NULL;
    TTF_Font *reloadFont = NULL;
    
    SDL_Color textColor = { 255, 255, 255 };
    char textBuffer[32];
    char reload[32] = "FIRE: ";
    
    
    //Thread vars
    pthread_t reciveUdpData;

    //Game vars
    int run;
    struct playerInfo player[6];
    struct timerInfo fps;
    struct cameraInfo camera;
    int bulletAngle[6];
    
    //int oldCannonAngle[6];
    //int oldTankAngle[6];
    
    //Other vars
    int i;
    
    //Inits the player struct
    for (i = 0; i < MAX_PLAYERS; i++)
    {
        player[i].slot = -1;
        player[i].connected = 0;
    }
    
    //inits Sdl and opens the screen
    screen = init_sdl();
    if(screen == 0)
    {
        printf("Error initializing SDL\n");
        return 0;
    }
    
    //Makes the connection to the server
    if(!(init_udp_tcp(&udpSd, &tcpSd, argv[1], argv[2])))
    {
        printf("Error making connection\n");
        return 0;
    }
    
    //load the images (Function maybe)
    blueTank = load_image( "./images/blueTank.bmp" );
    blueCannon = load_image( "./images/blueCannon.bmp" );
    redTank = load_image( "./images/redTank.bmp" );
    redCannon = load_image( "./images/redCannon.bmp" );
    worldMap = load_image( "./images/worldMap.bmp" );
    bullet = load_image( "./images/bullet.bmp" );

    //Load the fonts
    font = TTF_OpenFont( "./fonts/Army.ttf", 24 );
    reloadFont = TTF_OpenFont( "./fonts/Armyfat.ttf", 24 );
    
    //Moves udp info to global var
    udpInfo.udpSd = udpSd;
    strcpy(udpInfo.serverIp, argv[1]);

    //Recives the first information from the server
    recv(tcpSd, buffer, sizeof(buffer), 0);
    myId = atoi(buffer);
    
    //Starts the Recive data thread
    pthread_create( &reciveUdpData, NULL, recive_udp_data, &(player));

    while (run)
    {
        //Start the timer
        timer_start(&fps);

        while( SDL_PollEvent( &event ) )
        {
            
            if( event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE)
            {
                run = FALSE;
            }
            
            handel_input(&event, tcpSd );
            
        }
        
        camera.xCord = -player[myId].xCord;
        camera.yCord = -player[myId].yCord;
        
        
        //From here we draw stuff on the screen
        SDL_FillRect(screen,NULL, 0x000000);

        
        //Draws WorldMAps
        draw_map(player[myId].xCord,player[myId].yCord, worldMap, screen);

        
        //DISPLAYES YOUR TANK+++++++++++++++++++++++++++++
        if (player[myId].team == 1)
        {
            draw_tank_self(player[myId].tankAngle, blueTank, screen);
            draw_cannon_self(player[myId].cannonAngle, blueCannon, screen);
        }
        else
        {
            draw_tank_self(player[myId].tankAngle, redTank, screen);
            draw_cannon_self(player[myId].cannonAngle, redCannon, screen);
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        //DISPLAYES OTHER TANKS+++++++++++++++++++++++++++++
        for (i = 0; i < MAX_PLAYERS; i++)
        {
            if (player[i].slot == myId)
            {
                continue;
            }
            
            if (player[i].slot > -1 && player[i].connected == 1)
            {
                if (player[i].team == 1)
                {
                    draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,blueTank,screen);
                    if (player[i].dead == 0)
                        draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,blueCannon,screen);
                }
                else
                {
                    draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,redTank,screen);
                    if (player[i].dead == 0)
                        draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,redCannon,screen);
                }
            }
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        
        //DRAWS ALL THE BULLETS ON THE SCREEEN+++++++++++++++++++++++++++
        for (i = 0; i < MAX_PLAYERS; i++)
        {
            if (player[i].slot > -1 && player[i].connected == 1)
            {
                if (player[i].fire > 0)
                {
                    if (bulletAngle[i] == 0)
                    {
                        SDL_FreeSurface( rotatedBullet[i] );
                        rotatedBullet[i] = rotozoomSurface(bullet,player[i].cannonAngle,1.0,0);
                        playSound(soundShoot);
                    }
                    draw_bullet(&player[i], &camera, rotatedBullet[i], screen );
                    bulletAngle[i] = 1;
                }
                
                if (player[i].fire == 0)
                {
                    bulletAngle[i]=0;
                }
            }
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        
        //DRAWS THE USER INTERFACE ON SCREEN+++++++++++++++++++++++++++++
        
        textColor.r=0;
        textColor.g=0;
        textColor.b=255;
        sprintf(textBuffer, "BLUE POINTS: %d", bluePoints);
        UIbluePoints = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 10, 10, UIbluePoints, screen);
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        sprintf(textBuffer, "RED POINTS: %d", redPoints);
        UIredPoints = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 600, 10, UIredPoints, screen);
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        sprintf(textBuffer, "HP: %d", player[myId].healthPoints);
        UIhealth = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 20, 570, UIhealth, screen);
        
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        if (player[myId].fire == 0)
        {
            strcpy(reload, "FIRE: READY");
            UIreload = TTF_RenderText_Solid( font, reload, textColor );
        }
        else
        {
            strcpy(reload, "FIRE: RELOADING");
            UIreload = TTF_RenderText_Solid( font, reload, textColor );
        
        }
        draw_UI( 580, 570, UIreload, screen);


        //Update Screen
        SDL_Flip( screen );
        

        //Cap the frame rate
        if( timer_get_ticks(&fps) < 1000 / FPS )
        {
            SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
        }

    }
    
    
    pthread_cancel(reciveUdpData);
    return 0;
}
Exemplo n.º 27
0
int main()
{
  SDL_Surface* background, *background2, *background3, *background4;
  SDL_Rect src, dest;
  int frames;  
  Uint32 colorkey;


  SDL_AudioSpec desired, obtained;
  sound_t bus_sound;

  /*initialize video and sound subsystem*/
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0){
    printf("Unable to initialize video: %s\n.", SDL_GetError());
    return 1;
  }

  /*ensure all subsystems exit safely*/
  atexit(SDL_Quit);
  atexit(SDL_CloseAudio);

  /*set video mode*/
  screen = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF | SDL_HWSURFACE);
  if (screen == NULL) {
    printf("Unable to set video mode: %s\n", SDL_GetError());
    return 1;
  }

  /*load background images*/
  background = SDL_LoadBMP("img/src.bmp");
  if (background == NULL) {
    printf("Unable to load image.");
    return 1;
  }

  background2 = SDL_LoadBMP("img/background2.bmp");
  if (background2 == NULL) {
    printf("Unable to load background2.");
    return 1;
  }

  background3 = SDL_LoadBMP("img/background3.bmp");
  if (background3 == NULL) {
    printf("Unable to load background3.");
    return 1;
  }

  background4 = SDL_LoadBMP("img/background4.bmp");
  if (background4 == NULL) {
    printf("Unable to load background4.");
    return 1;
  }

  /*load bus*/
  bus = SDL_LoadBMP("img/bus.bmp");
  if (bus == NULL) {
    printf("Unable to load image.");
    return 1;
  }
  colorkey = SDL_MapRGB(bus->format, 255, 255, 255);

  /*set color key*/
  SDL_SetColorKey(bus,
		  SDL_SRCCOLORKEY,
		  colorkey);
  
  /*load man*/
  man = SDL_LoadBMP("img/man.bmp");
  if (man == NULL) {
    printf("Unable to load image");
    return 1;
  }

  colorkey = SDL_MapRGB(man->format, 255, 255, 255);

  /*set color key*/
  SDL_SetColorKey(man,
		  SDL_SRCCOLORKEY,
		  colorkey);

  man2 = SDL_LoadBMP("img/man2.bmp");
  if (man2 == NULL) {
    printf("Unable to load image");
    return 1;
  }

  colorkey = SDL_MapRGB(man2->format, 255, 255, 255);

  /*set color key*/
  SDL_SetColorKey(man2,
		  SDL_SRCCOLORKEY,
		  colorkey);

  car1 = SDL_LoadBMP("img/car1.bmp");
  if (car1 == NULL) {
    printf("Unable to load image");
    return 1;
  }

  colorkey = SDL_MapRGB(car1->format, 255, 255, 255);

  /*set color key*/
  SDL_SetColorKey(car1,
		  SDL_SRCCOLORKEY,
		  colorkey);


  car2 = SDL_LoadBMP("img/car2.bmp");
  if (car2 == NULL) {
    printf("Unable to load image");
    return 1;
  }

  colorkey = SDL_MapRGB(car2->format, 255, 255, 255);

  /*set color key*/
  SDL_SetColorKey(car2,
		  SDL_SRCCOLORKEY,
		  colorkey);

  
  //open audio device
  desired.freq = 44100;
  desired.format = AUDIO_S16;
  desired.samples = 4096;
  desired.channels = 2;
  desired.callback = AudioCallback;
  desired.userdata = NULL;

  if (SDL_OpenAudio(&desired, &obtained) < 0) {
    printf("Unable to open audio device: %s\n", SDL_GetError());
    return 1;
  }

  //load sound files and convert them to sound card's format
  if (LoadAndConvertSound("audio/bus-pass.wav", &obtained, &bus_sound) != 0) {
    printf("Unable to load sound.\n");
    return 1;
  }

  ClearPlayingSounds();
  SDL_PauseAudio(0);

  init_bus();
  init_man();
  
  int passenger_in = 0;

  PlaySound(&bus_sound);
  while (psv.x > 0) {
    src.x = 0;
    src.y = 0;
    src.w = background->w;
    src.h = background->h; 
    dest = src;
    SDL_BlitSurface(background, &src, screen, &dest);

    draw_obj(&psv, bus);
    
    if (psv.x < screen->w/2 && !passenger_in) { /*pause bus for passenger to enter*/
      SDL_PauseAudio(1);
      if (passenger.x > psv.x + 40){  /*check if passenger has got in*/
	passenger_in = 1; SDL_PauseAudio(0);
      }

      draw_man();
      SDL_Flip(screen);
      move_obj(&passenger);
    } else {
      SDL_Flip(screen);
      move_obj(&psv);
    }
  }

  psv.x = 639;  psv.y = 320;
  init_cars();
  PlaySound(&bus_sound);
  while (psv.x + bus->w/2 > 0) {
    SDL_BlitSurface(background2, &src, screen, &dest);
    draw_obj(&priv1, car1); draw_obj(&priv2, car2);
    draw_obj(&psv, bus);
    SDL_Flip(screen);
    move_obj(&psv);
    move_obj(&priv1); move_obj(&priv2);
  }

  psv.x = 639; psv.y = 350;
  PlaySound(&bus_sound);
  while (psv.x + bus->w/2 > 0) {
    SDL_BlitSurface(background3, &src, screen, &dest);
    draw_obj(&psv, bus);
    SDL_Flip(screen);
    move_obj(&psv);
  }

  psv.x = 639; psv.y = 267; passenger.y = 270;
  passenger_in = 1;
  int has_paused = 0;
  PlaySound(&bus_sound);
  while (psv.x + bus->w/2 > 0) {
    SDL_BlitSurface(background4, &src, screen, &dest);
    if (screen->w/2 > psv.x && passenger_in == 1) {
      SDL_PauseAudio(1);
      if (has_paused == 0) { SDL_Delay(1000); has_paused = 1;}
      if (passenger.x > 639) {passenger_in = 0; SDL_PauseAudio(0);}
      draw_obj(&psv, bus);
      draw_man();
      SDL_Flip(screen);
      move_obj(&passenger);
    } else {
      draw_obj(&psv, bus);
      SDL_Flip(screen);
      move_obj(&psv);
    }
  }

  //pause and lock sound system
  SDL_PauseAudio(1);
  SDL_LockAudio();

  free(bus_sound.samples);

  SDL_UnlockAudio();


  SDL_FreeSurface(background4);
  SDL_FreeSurface(background3);
  SDL_FreeSurface(background2);
  SDL_FreeSurface(background);
  SDL_FreeSurface(man);
  SDL_FreeSurface(bus);
  return 0;
}
Exemplo n.º 28
0
void UnlockScreen()
{
	if(SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen);

    SDL_Flip(screen);
}
Exemplo n.º 29
0
/******************************************************************************
Description.: this is the main worker thread
              it loops forever, grabs a fresh frame, decompressed the JPEG
              and displays the decoded data using SDL
Input Value.:
Return Value:
******************************************************************************/
void *worker_thread(void *arg)
{
    int frame_size = 0, firstrun = 1;

    SDL_Surface *screen = NULL, *image = NULL;
    decompressed_image rgbimage;

    /* initialze the buffer for the decompressed image */
    rgbimage.buffersize = 0;
    rgbimage.buffer = NULL;

    /* initialze the SDL video subsystem */
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    /* just allocate a large buffer for the JPEGs */
    if((frame = malloc(4096 * 1024)) == NULL) {
        OPRINT("not enough memory for worker thread\n");
        exit(EXIT_FAILURE);
    }

    /* set cleanup handler to cleanup allocated ressources */
    pthread_cleanup_push(worker_cleanup, NULL);

    while(!pglobal->stop) {
        DBG("waiting for fresh frame\n");
        pthread_cond_wait(&pglobal->db_update, &pglobal->db);

        /* read buffer */
        frame_size = pglobal->size;
        memcpy(frame, pglobal->buf, frame_size);

        pthread_mutex_unlock(&pglobal->db);

        /* decompress the JPEG and store results in memory */
        if(decompress_jpeg(frame, frame_size, &rgbimage)) {
            DBG("could not properly decompress JPEG data\n");
            continue;
        }

        if(firstrun) {
            /* create the primary surface (the visible window) */
            screen = SDL_SetVideoMode(rgbimage.width, rgbimage.height, 0, SDL_ANYFORMAT | SDL_HWSURFACE);
            SDL_WM_SetCaption("MJPG-Streamer Viewer", NULL);

            /* create a SDL surface to display the data */
            image = SDL_AllocSurface(SDL_SWSURFACE, rgbimage.width, rgbimage.height, 24,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                                     0x0000FF, 0x00FF00, 0xFF0000,
#else
                                     0xFF0000, 0x00FF00, 0x0000FF,
#endif
                                     0);

            /* copy the decoded data across */
            memcpy(image->pixels, rgbimage.buffer, rgbimage.width * rgbimage.height * 3);
            free(rgbimage.buffer);

            /* now, that we know the dimensions, we can directly copy to the right surface */
            rgbimage.buffer = image->pixels;
            rgbimage.buffersize = rgbimage.width * rgbimage.height * 3;

            firstrun = 0;
        }

        /* copy the image to the primary surface */
        SDL_BlitSurface(image, NULL, screen, NULL);

        /* redraw the whole surface */
        SDL_Flip(screen);
    }

    pthread_cleanup_pop(1);

    /* get rid of the image */
    SDL_FreeSurface(image);

    return NULL;
}
Exemplo n.º 30
0
void start_freehand_drawing(void)
{
    FreehandGeometry geometry;

    int oldmouse_x, oldmouse_y;
    int offsetx = cxoff + canvas->get_absxpos();
    int offsety = cyoff + canvas->get_absypos();
    //SDL_Surface *sur = canvas->get_image(canvas->get_active_image_n());

    SDL_Surface *behind = SDLGui::createSurface(screen->w, screen->h);
    blit(screen, behind, 0, 0, 0, 0, screen->w, screen->h);
                
    SDL_Event event;
    oldmouse_x = mouse.x;
    oldmouse_y = mouse.y;
    
    unsigned processed = 0;
    StlStroke& stroke = *(geometry.currStroke);


    while(mouse.b == SDL_BUTTON_LEFT)
    {
        // Update the screen with the last round of geometry read from the 
        // event queue.
        SDL_PumpEvents();
        for (unsigned i = processed; i < stroke.size(); i++)
        {
            if (i == 0)
            {
                //putpixel(screen, stroke[i].x + offsetx,
                //        stroke[i].y + offsety, BLACK);
                continue;
            }

            aalineRGBA(screen, (int) stroke[i - 1].x + offsetx,
                    (int) stroke[i - 1].y + offsety, 
                    (int) stroke[i].x + offsetx,
                    (int) stroke[i].y + offsety, 0, 0, 0, 128);
            processed++;
        }
        SDL_PumpEvents();
        SDL_Flip(screen);

        // Wait for a new event.
        SDL_WaitEvent(&event);
        // Process all events in the queue.
        do
        {
            switch (event.type)
            {
                case SDL_MOUSEMOTION:
                    mouse.x = event.motion.x;
                    mouse.y = event.motion.y;
                    if ((oldmouse_x != mouse.x) || (oldmouse_y != mouse.y))
                    {
                        geometry.addPoint(mouse.x - offsetx, mouse.y - offsety);
                        oldmouse_x = mouse.x;
                        oldmouse_y = mouse.y;
                    }
                    break;
                case SDL_MOUSEBUTTONUP:
                    mouse.b = 0;
                    break;
                case SDL_QUIT:
                    mouse.kill_sig = 1;
                    break;
                default:
                    break;
            }
        }
        while ((mouse.b != 0) && SDL_PollEvent(&event));
    }

    //qDebug("Points: %d", (int) points.size());
    SDL_FastBlit(behind, screen, 0, 0, 0, 0, screen->w, screen->h);
    SDL_FreeSurface(behind);
   
    if (lastFreehand == NULL)
    {
        strokeTimerID = SDL_AddTimer(strokeTimeout, freehand_timer_callback, 
                NULL);
        
        lastFreehand = new Freehand(geometry);
        // Visibility graph stuff:
        visalgo->obj_add(lastFreehand);

        //QT canvas_deselect_shapes();
    }
    else
    {
        SDL_RemoveTimer(strokeTimerID);
        strokeTimerID = SDL_AddTimer(strokeTimeout, freehand_timer_callback, 
                NULL);
        lastFreehand->addStroke(geometry);
        visalgo->obj_resize(lastFreehand);
    }
#if defined(__APPLE__)
    // After using carbon for mouse input, we need to resync the sdl mouse.
    GUI_DummyMouseEvent();
    while(SDL_PollEvent(&event));
        // noop;
    reset_mouse();
    mouse.bstate = mouse.b = 0;
#endif
    repaint_canvas();
}