Exemple #1
0
int main(int argc, char *argv[])
{
	int i, j;
	SDL_Texture *texture = NULL;
	TTF_Font *font;
	texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB555, SDL_TEXTUREACCESS_TARGET,	SCREEN_WIDTH, SCREEN_HEIGHT);
	Button button[20];
	for(i = 0; i < 20; i++){
		button[i].button_rect.x = button_x[i/5] + 4;
		button[i].button_rect.y = button_y[i%5] + 3;
		button[i].button_rect.w = BUTTON_WIDTH - 8;
		button[i].button_rect.h = BUTTON_HEIGHT - 6;
		button[i].button_char = button_ch[i];
		button[i].button_status = 0;
	}
	
	if(!init()) {
		printf("Failed to initialize!");
	}else{
		
		int quit = 0;
		SDL_Event e;
		while(!quit){

			SDL_SetRenderTarget(renderer, texture);
			SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);			
			SDL_RenderClear(renderer);

			SDL_SetRenderTarget(renderer, texture);
			SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);			
			for(i = 0; i < 4; i++){
				SDL_RenderDrawLine(renderer, button_x[i], button_y[0], button_x[i], SCREEN_HEIGHT);
			}
			for(i = 0; i < 5; i++){
				SDL_RenderDrawLine(renderer, button_x[0], button_y[i], SCREEN_WIDTH, button_y[i]);
			}
			for(i = 0; i < 20; i++){
				StatusButton(button[i]);
			
				font = TTF_OpenFont("Choko.ttf", 35);
				SDL_Color ttf_color = {0, 0, 0};

				SDL_Texture *ttexture;
				SDL_Surface *surface;
				SDL_Rect rect;
				ttexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB555, SDL_TEXTUREACCESS_TARGET, SCREEN_WIDTH, SCREEN_HEIGHT);
				surface = TTF_RenderText_Solid(font, button[i].button_char, ttf_color);
				ttexture = SDL_CreateTextureFromSurface(renderer, surface);

				TTF_SizeText(font, button[i].button_char, &rect.w, &rect.h);
				rect.x = button[i].button_rect.x + (BUTTON_WIDTH - rect.w)/2;
				rect.y = button[i].button_rect.y + (BUTTON_HEIGHT - rect.h)/2;
				
				SDL_SetRenderTarget(renderer, ttexture);
				SDL_RenderCopyEx(renderer, ttexture, NULL, &rect, 0.0, NULL, SDL_FLIP_NONE); 

				SDL_FreeSurface(surface);
				SDL_DestroyTexture(ttexture);
				TTF_CloseFont(font);
			}

			
			while(SDL_PollEvent(&e) != 0){
				if(e.type == SDL_QUIT){
					quit = 1;
				}else if(e.type == SDL_MOUSEBUTTONDOWN){
					if(e.button.button == SDL_BUTTON_LEFT){
						SDL_Point point;
						SDL_GetMouseState(&point.x, &point.y);
						for(i = 0; i < 20; i++){
							if(PointInRect(point, button[i].button_rect))
								button[i].button_status = 1;
						}
					}
				}else{
					for(i = 0; i < 20; i++){
						button[i].button_status = 0;
					}
				}
			}
			SDL_SetRenderTarget(renderer, NULL);
			SDL_RenderCopy(renderer, texture, NULL, NULL);   
			SDL_RenderPresent(renderer);
		}
	}
	
	TTF_Quit();
	SDL_DestroyRenderer(renderer);
	renderer = NULL;
	SDL_DestroyWindow(window);
	window = NULL;
	SDL_Quit();
	return 0;
}
Exemple #2
0
int main ( int argc, char** argv )
{
      if(Load_Wordlist()==-1)
    {
     printf( "Unable to load wordlist\n");
    return 1;
    }
    // initialize SDL video
    if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }
    if (TTF_Init()==-1)
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }


    // make sure SDL cleans up before exit
    atexit(SDL_Quit);

    // create a new window
   screen = SDL_SetVideoMode(480, 640, 16,SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    // *******************************************Load Resources********************************************/
    //******************************************************************************************************/
    //****************************************That's right, resources***************************************/
    //******************************************************************************************************/
    option=IMG_Load("option.png");
    if (!option)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }
      option2=IMG_Load("option2.png");
    if (!option)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }
    background=IMG_Load("background.png");
    if (!background)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }
   gamefont=TTF_OpenFont("Courier_New.ttf",25);
   gamefontsmall=TTF_OpenFont("Courier_New.ttf",16);
    if (gamefont==NULL||gamefontsmall==NULL)
    {
        printf("Unable to load font: %s\n", SDL_GetError());
        return 1;
    }
    // *************************************Initialising some vars********************************************/
    //********************************************************************************************************/
    cur_rect.w=200;
    cur_rect.h=80;
    cur_rect.x=(480-200)/2;
    cur_text_rect.h=20;
    screen_rect.w=480;
    screen_rect.h=640;
    screen_rect.x=0;
    screen_rect.y=0;
    int i;
    for(i=0;i<6;i++){options[i].text=NULL;}
    textColor.r=0;
    textColor.g=0;
    textColor.b=0;
    milliseconds=SDL_GetTicks();
    srand(time(NULL));
    //**************************************************Main loop LOL*******************************************/
    //**********************************************************************************************************/
    //****************************************************Here we go...*****************************************/
    //**********************************************************************************************************/
    displayMainMenu();

    //***********************************************************************************************************
    //********************************************Event processing***********************************************
    //***********************************************************************************************************

    while (!done)
    {
        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
                {
                    // exit if ESCAPE is pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE)
                        done = true;
                    break;
                }
            case SDL_MOUSEBUTTONDOWN:
            {
            handleClick(GetClickedOption(event.button.x,event.button.y));
            }
            } // end switch
        } // end of message processing
        //***************************************************************************************
        //*****************************Rendering*************************************************
        //***************************************************************************************
  // clear screengetline
        SDL_BlitSurface(background, 0, screen, &screen_rect);
        if(gamestate>=1&&gamestate<=3)
        {
        SDL_BlitSurface(questiontext,0,screen,&screen_rect);
        }
        int i;
        for(i=0;i<optnum;i++)
        {
        displayOption(options[i]);
        }

        //Run the physics
        runPhysics();
        // finally, update the screen :)
        SDL_Flip(screen);
    } // end main loop

    // free loaded bitmap
    SDL_FreeSurface(questiontext);
    SDL_FreeSurface(option2);
    SDL_FreeSurface(option);
    SDL_FreeSurface(background);
    TTF_CloseFont(gamefont);
    TTF_Quit();
    for(i=0;i<numwords;i++)
    {
    Free_Word(Words[i]);
    }
    free(Words);
    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
    }
SDLTexte::~SDLTexte()
{
	TTF_Quit();
}
SDLApplication::~SDLApplication()
{
    TTF_Quit();
    SDL_Quit();
}
Exemple #5
0
StringSDL::~StringSDL()
{
    TTF_CloseFont(_font);
    TTF_Quit();
}
Exemple #6
0
int main(int argc, char *argv[])
{
	srand(time(NULL));
	SDL_Window *screen;
	SDL_Renderer *renderPrim;
	SDL_Event eventHandle;
	SDL_Texture *scoreDisplay;
	TTF_Font *defaultText;
	SDL_Color cPlayer = {0,255,255,255};
	SDL_Color cPoint = {255,255,0,255};
	SDL_Color cBackground = {0,0,0,255};
	SDL_Color cScore = {0,255,0,255};
	int runningGame,gotPoint, pointCount, oldScore;
	runningGame = 0;
	gotPoint = 0;
	pointCount = -1;//first point spawns on player
	SDL_Rect rPlayer = {0,0,PLAYER_WIDTH, PLAYER_HEIGHT};
	SDL_Rect rPoint = {0,0,POINT_WIDTH,POINT_HEIGHT};
	SDL_Rect rScore = {0,0,0,0};
	screen = init("Piss easy snake", SCREEN_WIDTH, SCREEN_HEIGHT);
	renderPrim = createRenderer(screen);
	defaultText = loadFont("default.ttf", 15, renderPrim);
	while(runningGame == 0)
	{
		oldScore = pointCount;
		if(gotPoint == 1)
		{
			pointCount++;
			rPoint.x = rand() % SCREEN_WIDTH;//new random position
			rPoint.y = rand() % SCREEN_HEIGHT;
			gotPoint = 0;
		}
		while(SDL_PollEvent(&eventHandle) != 0)
		{
			if(eventHandle.type == SDL_KEYDOWN)
			{
				handleInput(&rPlayer, eventHandle, &runningGame);
			
			}
			else if(eventHandle.type == SDL_QUIT)
			{
				runningGame = 1;
			
			}
		
		
		}
		
		SDL_SetRenderDrawColor(renderPrim, cBackground.r,cBackground.g,cBackground.b,cBackground.a);
		SDL_RenderClear(renderPrim);
		SDL_SetRenderDrawColor(renderPrim,cPlayer.r,cPlayer.g,cPlayer.b,cPlayer.a);
		SDL_RenderFillRect(renderPrim,&rPlayer);
		SDL_SetRenderDrawColor(renderPrim,cPoint.r,cPoint.g,cPoint.b,cPoint.a);
		SDL_RenderFillRect(renderPrim,&rPoint);
		if(oldScore < pointCount)
		{
			scoreDisplay = renderScore(defaultText,cScore,&rScore, renderPrim, pointCount, scoreDisplay);
		}
		SDL_RenderCopy(renderPrim, scoreDisplay, NULL, &rScore); 
		SDL_RenderPresent(renderPrim);
		
		gotPoint = SDL_HasIntersection(&rPlayer,&rPoint);
	}
	SDL_DestroyRenderer(renderPrim);
	SDL_DestroyWindow(screen);
	TTF_CloseFont(defaultText);
	TTF_Quit();
	SDL_Quit();
	return 0;
}
Exemple #7
0
//Main function
int main(int argc, char* argv[])
{
  /*
    -----
    // INITIALIZATION
    -----
  */

  //Seed RNG
  srand(time(NULL));
  
  //Initialize all SDL subsystems
  if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
    {
      return 1;
    }

  //Initialize SDL_TTF
  TTF_Init();
  TTF_Font * planetFont = TTF_OpenFont("corbel.ttf", 20);

  //Set up the screen
  SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);

  //Make sure screen set up
  if (screen == NULL)
    {
      return false;
    }

  //Set the window caption
  SDL_WM_SetCaption("GAEM", NULL);

  //Create an event manager
  SDL_Event event;

  //Store keystates
  Uint8* keystates;

  //Set up camera
  SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
  float camerax = 0;
  float cameray = 0;

  /*
    -----
    GAME SETUP
    -----
  */

  //Set up ship stats
  std::vector<ShipStats> shipstats(10);
  for (int i = 0; i < 10; i++)
    {
      shipstats[i].attack = i+1;
      shipstats[i].defense = i+1;
      shipstats[i].speed = DEFAULT_FLEET_SPEED;
      shipstats[i].interceptRange = 200;
      shipstats[i].interceptDamage = 0.1;
      shipstats[i].interceptCD = 250;
    }

  //Set up ship type 1: Heavy ship
  shipstats[1].attack = 3;
  shipstats[1].defense = 2;
  shipstats[1].speed = DEFAULT_FLEET_SPEED/2;

  //Set up ship type 2: Fiery attack ship
  shipstats[2].attack = 2;
  shipstats[2].defense = 1;
  shipstats[2].speed = DEFAULT_FLEET_SPEED*1.25;

  //Set up buildings and building rules
  std::list<Building> buildings;
  std::vector<std::list<Building*> > buildRules;
  buildRules.resize(2);
  SDL_Surface* b01 = loadImage("b01.png");
  SDL_Surface* bc01 = loadImage("bc01.png");
  SDL_Surface* b02 = loadImage("b02.png");
  SDL_Surface* bc02 = loadImage("bc02.png");
  buildings.push_back(Building(b01, bc01, "build 0 2")); //0
  buildings.push_back(Building(b02, bc02, "fire damage 2 1")); //1
  buildings.push_back(Building(b01, bc01, "build 1 4")); //2
  buildings.push_back(Building(b01, bc01, "build 2 2")); //3
  buildings.push_back(Building(b02, bc02, "aura damage 1 total")); //4

  //0
  std::list<Building>::iterator bi = buildings.begin();
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //1
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(10000);
  bi->setRange(250);
  bi++;

  //2
  buildRules[0].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //3
  buildRules[1].push_back(&(*bi));
  bi->setBuildTime(15000);
  bi++;

  //4
  buildRules[1].push_back(&(*bi));
  bi->setBuildTime(10000);
  bi->setRange(200);
  bi->setCD(1000);

  //Building images are now in rotation caches
  SDL_FreeSurface(b01);
  SDL_FreeSurface(bc01);
  SDL_FreeSurface(b02);
  SDL_FreeSurface(bc02);

  //Create a list of planets
  std::list<Planet> planets;

  //The standard rate of production of basic ship 0
  float ship0rate = 1.0;

  //The array of indicators
  SDL_Surface* indicator[3];
  indicator[1] = loadImage("selectorb.png");
  indicator[2] = loadImage("selectorr.png");
  
  SDL_Surface* planet0img = loadImage("planet0.png");
  SDL_Surface* planet1img = loadImage("planet1.png");
  SDL_Surface* planet1_1img = loadImage("planet1-1.png");

  //Create the planets at random
  //First, create two home planets
  std::vector<int> homestart;
  homestart.resize(1,3);
  planets.push_back(Planet(planet0img, 1.0,
			   Vec2f(rand()%100, 100 + rand()%(LEVEL_HEIGHT-200)), 0));
  planets.back().setOwner(1, indicator);
  planets.back().setShipRate(0, ship0rate);
  planets.back().setRotSpeed(M_PI/20);
  planets.back().addShips(3, 0);
  planets.push_back(Planet(planet0img, 1.0,
			   Vec2f(LEVEL_WIDTH-(2*UNSCALED_PLANET_RADIUS)-(rand()%100),
				 100 + rand()%(LEVEL_HEIGHT-200)), 0));
  planets.back().setOwner(2, indicator);
  planets.back().setShipRate(0, ship0rate);
  planets.back().setRotSpeed(M_PI/20);
  planets.back().addShips(3, 0);

  //Now repeatedly create planets until either a target density is reached
  //or we go too many tries without finding a spot for a new planet.
  char tries = 0;
  char maxTries = 10;
  double density = 0.13;
  double totalSize = LEVEL_WIDTH*LEVEL_HEIGHT;
  double currentSize = M_PI*UNSCALED_PLANET_RADIUS*UNSCALED_PLANET_RADIUS*2;
  double spacing = 23;
  
  while (currentSize/totalSize < density && tries < maxTries)
    {
      //Create a new planet at a completely random location with a random size
      //For now, make half normal and half volcanic
      float psize = (double(rand())/double(RAND_MAX))*0.7 + 0.5;
      Planet p(planet0img, psize,
               Vec2f(rand()%(LEVEL_WIDTH-int(2*UNSCALED_PLANET_RADIUS*psize)),
                     rand()%(LEVEL_HEIGHT-int(2*UNSCALED_PLANET_RADIUS*psize))), 0);;
      if (rand()%2 == 0)
        {
          p.setType(0);
          p.setImage(planet0img);
        }
      else
        {
          p.setType(1);
          p.setImage(planet1img);
        }

      //Make sure it doesn't collide with any other planets
      bool skip = false;
      for (planetIter pi = planets.begin(); pi != planets.end(); pi++)
	{
	  Vec2f ppos = p.pos()+Vec2f(UNSCALED_PLANET_RADIUS*p.size(),UNSCALED_PLANET_RADIUS*p.size());
	  Vec2f pipos = pi->pos()+Vec2f(UNSCALED_PLANET_RADIUS*pi->size(),UNSCALED_PLANET_RADIUS*pi->size());
	  if ((pipos-ppos).length() <
	      p.size()*UNSCALED_PLANET_RADIUS +
	      pi->size()*UNSCALED_PLANET_RADIUS + spacing)
	    {
	      //There's a collision. Increment tries and try again
	      tries++;
	      skip = true;
	      break;
	    }
	}
      if (skip) continue;

      //At this point, we know there's no collision. Reset tries
      tries = 0;

      //Add a few more random attributes
      p.setOwner(0, indicator);
      p.setShipRate(0, ship0rate);
      p.setRotSpeed((fmod(rand(),M_PI)/5) - M_PI/10);
      p.setDifficulty(p.size()*20 + rand()%15 - 9);

      //Add this planet to the current size
      currentSize += M_PI*(UNSCALED_PLANET_RADIUS*p.size())*(UNSCALED_PLANET_RADIUS*p.size());

      //Add it to the list
      planets.push_back(p);
    }
  
  //Set up fleet list
  std::list<Fleet> fleets;

  //Set up projectile list
  std::list<Projectile> projectiles;

  //Filler to act as NULL
  planetIter planNull;

  //The currently selected planet
  planetIter selectPlanet = planNull;

  //Set up AI
  std::list<GalconAI> ai;

  //For now, AI controls player 2
  GalconAISettings aiSet;
  aiSet.attackFraction = .8;
  aiSet.surplusDefecitThreshold = .25;
  aiSet.attackExtraNeutral = .2;
  aiSet.attackExtraEnemy = .7;
  aiSet.perPlanetAttackStrength = .5;
  aiSet.delay = 200;
  aiSet.maximumBuildingFraction = .8;
  aiSet.minimumDefenseForBuilding = 10;
  aiSet.distancePower = 1.15;
  ai.push_back(GalconAI(2, aiSet));
  ai.begin()->init(planets, shipstats);
  ai.begin()->activate();

  //The number of the locally playing player
  char localPlayer = 1;

  //The type of ship that will currently be sent
  int shipSendType = 0;

  //A line drawer for the main surface
  LineDrawer linedraw(screen);
  
  /*
    -----
    MAIN LOOP
    -----
  */

  int time = SDL_GetTicks();
  uint8_t quit = 0;
  while (quit == 0)
    {
      //Update time and dt
      //Cap FPS
      int dt = SDL_GetTicks() - time;
      float minms = 1000.0/float(FPS_CAP);
      if (dt < minms) SDL_Delay(minms-dt);
      time = SDL_GetTicks();

      //Update keystates
      keystates = SDL_GetKeyState(NULL);

      //Check for arrow keys/wasd
      if (keystates[SDLK_UP] || keystates[SDLK_w])
	{
	  cameray -= CAMERA_SPEED * (dt/1000.0);
	  if (cameray < 0) cameray = 0;
	}
      
      if (keystates[SDLK_RIGHT] || keystates[SDLK_d])
	{
	  camerax += CAMERA_SPEED * (dt/1000.0);
	  if (camerax > LEVEL_WIDTH - SCREEN_WIDTH) camerax = LEVEL_WIDTH - SCREEN_WIDTH;
	}
      
      if (keystates[SDLK_DOWN] || keystates[SDLK_s])
	{
	  cameray += CAMERA_SPEED * (dt/1000.0);
	  if (cameray > LEVEL_HEIGHT - SCREEN_HEIGHT) cameray = LEVEL_HEIGHT - SCREEN_HEIGHT;
	}
      
      if (keystates[SDLK_LEFT] || keystates[SDLK_a])
	{
	  camerax -= CAMERA_SPEED * (dt/1000.0);
	  if (camerax < 0) camerax = 0;
	}

      //Update camera from camerax and cameray to struct
      camera.x = camerax;
      camera.y = cameray;
      
      //Handle events
      while (SDL_PollEvent(&event))
	{
	  //Quit if requested
	  if (event.type == SDL_QUIT)
	    {
	      quit = 1;
	    }

	  //Check for escape key, QWERTY to construct buildings, or numbers to select
	  //ship type.
	  //BUILDING CONSTRUCTION AND TYPE SELECTION THIS WAY IS TEMPORARY
	  if (event.type == SDL_KEYDOWN)
	    {
	      switch (event.key.keysym.sym)
		{
		case SDLK_ESCAPE:
		  quit = 1;
		  break;
		case SDLK_q:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 1) break;
                      
                      selectPlanet->build(*(buildRules[selectPlanet->type()].begin()),
                                          buildRules);
                    }
		  break;
		case SDLK_w:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 2) break;
                      
                      selectPlanet->build(*(++buildRules[selectPlanet->type()].begin()),
                                          buildRules);
                    }
		  break;
		case SDLK_e:
		  if (selectPlanet != planNull)
                    {
                      if (selectPlanet->owner() != localPlayer ||
                          buildRules[selectPlanet->type()].size() < 3) break;
                      
                      std::list<Building*>::iterator i;
                      i = buildRules[selectPlanet->type()].begin();
                      i++; i++;
                      selectPlanet->build(*i, buildRules);
                    }
                  break;
		case SDLK_1:
		  shipSendType = 0;
		  break;
		case SDLK_2:
		  shipSendType = 1;
		  break;
		case SDLK_3:
		  shipSendType = 2;
		  break;
		case SDLK_4:
		  shipSendType = 3;
		  break;
		case SDLK_5:
		  shipSendType = 4;
		  break;
		default:
		  break;
		}
	    }

	  //Check for mouse clicks
	  if (event.type == SDL_MOUSEBUTTONDOWN)
	    {
	      //Left click
	      if (event.button.button == SDL_BUTTON_LEFT)
		{
		  //Used to select a planet
		  //Check if any are being clicked on
		  selectPlanet = planNull;

		  //Adjust mouse coordinates based on camera
		  Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
		  
		  for (planetIter i = planets.begin(); i != planets.end(); i++)
		    {
		      //See if distance from center is less than planet radius
		      Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
				   i->y() + (UNSCALED_PLANET_RADIUS * i->size()));

		      if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
			{
			  //Ensure the planet belongs to this person
			  if ((*i).owner() == localPlayer)
			    {
			      selectPlanet = i;
			      break;
			    }
			}
		    }
		}

	      //Right click
	      if (event.button.button == SDL_BUTTON_RIGHT)
		{
		  //Used to choose the destination for a fleet
		  //See if we have a selected planet
		  if (selectPlanet != planNull)
		    {

		      //Adjust mouse coordinates based on camera
		      Vec2f click(event.button.x + camera.x, event.button.y + camera.y);
		      
		      //Check to see if any are being clicked on
		      for (planetIter i = planets.begin(); i != planets.end(); i++)
			{
			  Vec2f center(i->x() + (UNSCALED_PLANET_RADIUS * i->size()),
				       i->y() + (UNSCALED_PLANET_RADIUS * i->size()));
			  
			  //See if distance from center is less than planet radius
			  if ((click-center).length() < UNSCALED_PLANET_RADIUS * i->size())
			    {
			      //Split ships from the source planet
			      int transfer = (*selectPlanet).splitShips(0.5, shipSendType);
			      //Make sure we actually have a ship in the fleet
			      if (transfer > 0)
				{
				  //Add the new fleet
				  fleets.push_back(Fleet(transfer, shipSendType, shipstats[shipSendType], &(*selectPlanet), &(*i)));
				  break;
				}
			    }
			}
		    }
		}
	    }
	}

      //Draw a white background
      SDL_Rect back = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
      SDL_FillRect(screen, &back, 0xFFFFFF);

      //Update and display fleets
      for (fleetIter i = fleets.begin(); i != fleets.end(); i++)
	{
	  (*i).update();

	  //Check for arrival at destination
	  //See if distance from center is less than planet radius
	  Vec2f tar((*i).dest()->x() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()),
		    (*i).dest()->y() + (UNSCALED_PLANET_RADIUS*(*i).dest()->size()));
	  
	  if ((tar-i->pos()).length() < UNSCALED_PLANET_RADIUS * (i->dest())->size())
	    {
	      //Check if friendly or hostile
	      if ((*i).dest()->owner() == (*i).owner())
		{
		  //Add the fleet to the new planet
		  (*((*i).dest())).addShips(i->ships(), i->type());
		}
	      else //Hostile
		{
		  //Attack!
		  //Get ship counts before the attack
		  std::vector<int> ships1 = i->dest()->shipcount();
		  int oldowner = i->dest()->owner();

		  //Actually do the attack
		  (*((*i).dest())).takeAttack(i->ships(), i->type(), i->owner(), shipstats, indicator);

		  //If the attack changed ownership of the selected planet,
		  //deselect it
		  if (oldowner != i->dest()->owner() && i->dest() == &(*selectPlanet)) selectPlanet = planNull;

		  //Get ship counts after the attack
		  std::vector<int> ships2 = i->dest()->shipcount();

		  //Notify the defending AI about the losses
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (oldowner != j->player()) continue;
		      float newdefense = 0;
		      for (unsigned int k = 0; k < ships1.size(); k++)
			{
			  int diff;
			  //If ownership has changed
			  if (oldowner != i->dest()->owner())
			    {
			      diff = ships1[k];
			      j->notifyPlanetLoss(i->dest());
			    }
			  else
			    {
			      diff = ships1[k] - ships2[k];
			    }
			  
			  newdefense += diff * shipstats[k].defense;
			}
		      j->notifyDefendLoss(newdefense);
		    }

		  //Notify the attacking AI about the losses
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (i->owner() != j->player()) continue;
		      float lost;
		      
		      //If the attack failed
		      if (i->dest()->owner() != i->owner())
			{
			  //Lost everything
			  lost = i->ships();
			}
		      else //Successful attack
			{
			  //Lose the difference
			  lost = i->ships() - i->dest()->totalDefense(shipstats);
			  j->notifyPlanetGain(i->dest());
			}
		      
		      j->notifyAttackLoss(lost);
		    }
		}

	      //Delete all projectiles with this fleet as its target
	      for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
		{
		  if (pi->target() == &(*(i)))
		    {
		      pi = projectiles.erase(pi);
		      pi--;
		    }
		}

	      //Delete the fleet
	      i = fleets.erase(i);
	      i--;
	      continue;
	    }

	  //Check for interception
	  //Compare against every other fleet
	  for (fleetIter j = fleets.begin(); j != fleets.end(); j++)
	    {
	      //Atempt interception
	      char status = i->intercept(&(*j), shipstats);

	      //Greater than 0: Draw line
	      if (status <= 0) continue;
	      SDL_Color red = {255, 0, 0};
	      SDL_Color orange = {255, 255, 0};
	      linedraw.line(i->pos(), j->pos(), orange, red);

	      //Equal to 2: Dealt damage, but didn't notify
	      if (status == 2)
		{
		  //Notify the AI before we go around deleting things
		  for (std::list<GalconAI>::iterator k = ai.begin(); k != ai.end(); k++)
		    {
		      if (k->player() == j->owner())
			{
			  k->notifyFleetDamage(std::min(double(shipstats[i->type()].interceptDamage),
							double(j->totalDefense(shipstats))));
			}
		    }
		}

	      //Equal to 3: Destroy target
	      if (status != 3) break;

	      //We can have the projectile code handle the cleanup later
	      //Create a fake projectile right on top of it to deal the final blow
	      std::stringstream convertnum;
	      convertnum << "damage ";
	      convertnum << shipstats[i->type()].interceptDamage*i->ships()*2;
	      projectiles.push_back(Projectile(j->pos(), &(*j),
					       convertnum.str(),
					       shipstats[j->type()].speed*2));

	      //Don't attack more than one ship
	      break;
	    }
	  
	  (*i).display(screen, camera);
	}

      //Update and display planets
      for (planetIter i = planets.begin(); i != planets.end(); i++)
	{
	  //Get ship counts before the update
	  std::vector<int> ships1 = i->shipcount();

	  //Update the planet
	  (*i).update();

	  //Get ship counts after the update
	  std::vector<int> ships2 = i->shipcount();

	  //Notify a controlling AI about the construction
	  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
	    {
	      if (i->owner() != j->player()) continue;
	      float newattack = 0;
	      float newdefense = 0;
	      for (unsigned int k = 0; k < ships1.size(); k++)
		{
		  int diff = ships2[k] - ships1[k];
		  newattack += diff * shipstats[k].attack;
		  newdefense += diff * shipstats[k].defense;
		}
	      j->notifyConstruction(newattack, newdefense);
	    }

	  //If this planet is selected, add an indicator
	  if (i == selectPlanet)
	    {
	      SDL_Rect temprect = {Sint16((*i).x()-10 - camera.x), Sint16((*i).y()-10 - camera.y), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20), Uint16(UNSCALED_PLANET_RADIUS * (*i).size() * 2 + 20)};
	      SDL_FillRect(screen, &temprect, SDL_MapRGB(screen->format, 100, 100, 100));
	    }

          //If this is a lava planet and it is depleted, replace the image
          if (i->typeInfo() < 0 && i->type() == 1)
            {
              i->setImage(planet1_1img);
              i->setTypeInfo(0);
              i->setRotSpeed(0);
              i->setShipRate(0, ship0rate * PLANET1_DEPLETION_PENALTY);
            }

	  //Iterate over all buildings to handle effects from buildings to other objects

	  for (unsigned int j = 0; j < i->buildcount(); j++)
	    {
	      //Get the building
	      BuildingInstance* b = i->building(j);
	      
	      //Skip over nonexistant and incomplete buildings
	      if (!(b->exists()) || j == Uint32(i->buildIndex())) continue;

	      //Try to make it fire, remember result
	      bool fire = b->fire();
	      
	      //Create a string stream and vector for tokens
	      std::stringstream ss(b->effect());
	      std::string item;
	      std::vector<std::string> tokens;
	      while (std::getline(ss, item, ' '))
		{
		  tokens.push_back(item);
		}
	      
	      //Ensure the size is at least two
	      if (tokens.size() < 3) continue;
	      
	      //Parse it and apply effects that involve multiple objects
	      //Fire projectile: fire <effect> <effectvars> <speed as multiplier>
	      if (tokens[0] == "fire")
		{
		  //Ensure size of four
		  if (tokens.size() != 4) continue;
		  
		  //Loop over all potential target fleets, find closest
		  Fleet* closest = NULL;
		  float closestDist = -1;
		  Vec2f coords = i->buildcoords(j);
		  for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
		    {
		      //Only check further if it's an enemy fleet
		      if (k->owner() == i->owner()) continue;
		      //Compute the distance between them
		      double dist = (coords-k->pos()).length();
		      
		      //Continue if the fleet is out of range
		      if (dist > b->range()) continue;
		      
		      //Compare with previous best
		      if (dist < closestDist || closestDist < -0.5)
			{
			  closestDist = dist;
			  closest = &(*k);
			}
		    }
		  
		  //Fire a projectile from the building to the fleet
		  if (closest != NULL)
		    {
		      if (fire)
			{
			  //Create a proper string for the projectile
			  std::string projstr;
			  for (unsigned int word = 1; word < tokens.size()-1; word++)
			    { projstr += tokens[word] + " "; }
			  projectiles.push_back(Projectile(coords, closest, projstr, std::atof(tokens[tokens.size()-1].c_str())));
			}
		    }
		}

              //Aura: aura <effect> <effectvars>
              if (tokens[0] == "aura")
                {
                  //Find number of ships in range
                  int shipcount = 0;
                  for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
		    {
		      //Only check further if it's an enemy fleet
		      if (k->owner() == i->owner()) continue;
		      //Compute the distance between them
		      double dist = (i->buildcoords(j)-k->pos()).length();
                      if (dist <= b->range()) shipcount += k->ships();
                    }

                  //Deal damage with a fake projectile
                  if (fire)
                    {
                      bool hit = false;
                      for (fleetIter k = fleets.begin(); k != fleets.end(); k++)
                        {
                          //Only check further if it's an enemy fleet
                          if (k->owner() == i->owner()) continue;
                          //Compute the distance between them
                          double dist = (i->buildcoords(j)-k->pos()).length();
                          if (dist > b->range()) continue;
                          hit = true;
                          
                          std::string projstr;
                          //Divide appropriately if needed
                          if (tokens[tokens.size()-1] == "total")
                            {
                              std::stringstream toa;
                              toa << atof(tokens[tokens.size()-2].c_str())*float(k->ships())/float(shipcount);
                              tokens[tokens.size()-1] = toa.str();
                            }
                          //Depleted volcanic planets don't do as much
                          if (i->type() == 1 && i->typeInfo() <= 0)
                            {
                              std::stringstream toa;
                              toa << atof(tokens[tokens.size()-2].c_str())*PLANET1_DEPLETION_PENALTY;
                              tokens[tokens.size()-1] = toa.str();
                            }
                          //Create the projectile
                          for (unsigned int word = 1; word < tokens.size()-1; word++)
                            {
                              projstr += tokens[word] + " ";
                            }
                          projectiles.push_back(Projectile(k->pos(), &(*k), projstr, 1));
                        }

                      //Volcanic planets will lost some fuel
                      if (i->type() == 1 && hit && i->typeInfo() != 0)
                        {
                          i->setTypeInfo(i->typeInfo()-PLANET1_DEPLETION_RATE);
                          if (i->typeInfo() == 0) i->setTypeInfo(-1);
                        }
                      
                    }
                }
                      
	    } //for each building

	  (*i).display(screen, planetFont, camera);
	}

      //Update and display projectiles
      for (projectileIter i = projectiles.begin(); i != projectiles.end(); i++)
	{
	  (*i).update();

	  //Check if the projectile has hit its target fleet
	  if ((i->pos() - i->target()->pos()).length() < 12.345) //MAGIC NUMBER >:(
	    {
	      //Tokenize string to determine effect
	      std::stringstream ss(i->effect());
	      std::string item;
	      std::vector<std::string> tokens;
	      while (std::getline(ss, item, ' '))
		{
		  tokens.push_back(item);
		}

	      //Damage: damage <amount>
	      if (tokens[0] == "damage")
		{
		  //Ensure size of two
		  if (tokens.size() != 2) continue;

		  //Deliver the damage

		  //Notify the AI before we go around deleting things
		  for (std::list<GalconAI>::iterator j = ai.begin(); j != ai.end(); j++)
		    {
		      if (j->player() == i->target()->owner())
			{
			  j->notifyFleetDamage(std::min(std::atof(tokens[1].c_str()), double(i->target()->totalDefense(shipstats))));
			}
		    }
		  
		  //Check to see if the fleet is destroyed by this
		  if (!(i->target()->takeHit(std::atof(tokens[1].c_str()), shipstats)))
		    {
		      //Delete the fleet
		      for (fleetIter fi = fleets.begin(); fi != fleets.end(); fi++)
			{
			  if (&(*fi) == &(*(i->target())))
			    {
			      fleets.erase(fi);
			      break;
			    }
			}

		      //Delete all projectiles with this fleet as the target
		      for (projectileIter pi = projectiles.begin(); pi != projectiles.end(); pi++)
			{
			  if (pi->target() == i->target())
			    {
			      if (pi == i) continue;
			      pi = projectiles.erase(pi);
			      pi--;
			    }
			}

		    }

		  //Either way, destroy this projectile
		  i = projectiles.erase(i);
		  i--;
		  continue;
		}
	    }

	  (*i).display(screen, camera);
	}

      //Perform AI calculations
      for (std::list<GalconAI>::iterator i = ai.begin(); i != ai.end(); i++)
	{
	  //Get the command list
	  commandList com = i->update(planets, fleets, shipstats, buildRules);

	  //Execute each command
	  for (commandList::iterator j = com.begin(); j != com.end(); j++)
	    {
	      //Extract the info from the command
	      Planet* source = j->first;
	      int amount = j->second.first;
	      Planet* dest = j->second.second;

	      //Handle building construction
	      if (source == dest)
		{
		  std::list<Building*>::iterator build = buildRules[source->type()].begin();
		  while (amount > 0)
		    {
		      amount--;
		      build++;
		    }

		  //Build it!
		  source->build((*build), buildRules);
		  continue;
		}

	      //Get the number of ships from the source
	      std::vector<int> ships = source->shipcount();

	      //Send out a fleet for each ship type used
	      std::vector<int> newfleet;
	      newfleet.resize(ships.size());
	      int total = 0;
	      for (unsigned int k = 0; k < ships.size(); k++)
		{
		  //Handle it differently for attack or defense
		  float typeTotal;
		  if (dest->owner() == source->owner())
		    {
		      //Check the total defense of this ship type
		      typeTotal = ships[k] * shipstats[k].defense;
		    }
		  else
		    {
		      //Check the total attack of this ship type
		      typeTotal = ships[k] * shipstats[k].attack;
		    }
		  
		  //If there's more ships requested than there are of this type
		  if (total + typeTotal <= amount)
		    {
		      //Add them all
		      newfleet[k] += ships[k];
		      total += typeTotal;
		    }
		  else //More ships than space in the requested fleet
		    {
		      //Find the proper amount
		      //# of ships to send = defense requested / def per ship
		      float properAmount = (amount - total) / (typeTotal / ships[k]);
		      newfleet[k] += properAmount;
		      break;
		    }
		}
	      
	      //Fleet is built, send each type that has some ships
	      for (unsigned int k = 0; k < newfleet.size(); k++)
		{
		  if (newfleet[k] == 0) continue;
		  fleets.push_back(Fleet(newfleet[k], k, shipstats[k], source, dest));

		  //Also subtract the fleet from the original planet
		  newfleet[k] *= -1;
		  source->addShips(newfleet[k], k);
		}
	    }
	}

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

  //Free surfaces
  SDL_FreeSurface(indicator[1]);
  SDL_FreeSurface(indicator[2]);
  SDL_FreeSurface(planet0img);
  SDL_FreeSurface(planet1img);
  SDL_FreeSurface(planet1_1img);

  //Clean up TTF
  TTF_CloseFont(planetFont);
  TTF_Quit();

  SDL_Quit();
}
Exemple #8
0
char ModeloFactory::nuevoElegirMisiones(std::list<ParserYaml::stEscenario>& listaEscenarios){
	bool quit = false;
	bool clicBotonMouseIzquierdo = false;	
	int posicionMouseX, posicionMouseY;
	char misionElegida;
	SDL_Event event;
	TTF_Font *fuente = NULL;
	SDL_Color textColor = { 255, 255, 255 }; //color blanco 
	SDL_Surface* pantalla = NULL;
	SDL_Init( SDL_INIT_EVERYTHING );
	pantalla = SDL_SetVideoMode( PANTALLA_ANCHO, PANTALLA_ALTO, SCREEN_BPP, SDL_SWSURFACE );
	TTF_Init();
	SDL_WM_SetCaption( "Misiones", NULL );
	SDL_Surface *imagenDeFondo = NULL;
	imagenDeFondo = ImageLoader::getInstance().load_image( "./img/background4.png" );
	fuente = TTF_OpenFont( "./fonts/Verdana.ttf", 28 );	
	SDL_Surface* textoMisionCarnicero = TTF_RenderText_Solid( fuente, "Mision Carnicero", textColor );
	SDL_Surface* textoMisionBanderas = TTF_RenderText_Solid( fuente, "Mision Banderas", textColor );	
	SDL_BlitSurface( imagenDeFondo, NULL, pantalla, NULL );		
	SDL_Rect offset;
	offset.x = 50;
	offset.y = 190;
	SDL_BlitSurface( textoMisionCarnicero, NULL, pantalla, &offset );
	rectangleRGBA( pantalla, 48, 190, 295, 225, 0, 255, 0, 255);
	offset.x = 350;
	offset.y = 190;
	SDL_BlitSurface( textoMisionBanderas, NULL, pantalla, &offset );	
	rectangleRGBA( pantalla, 348, 190, 595, 225, 0, 255, 0, 255);	
	SDL_Flip( pantalla );
	while( quit == false ) {
        while( SDL_PollEvent( &event ) ) {            
			switch (event.type) {
				case SDL_QUIT:
					quit = true;
				break;
				case SDL_MOUSEMOTION:
					posicionMouseX = event.motion.x;
					posicionMouseY = event.motion.y;
				break;		
				case SDL_MOUSEBUTTONDOWN:
					switch (event.button.button) {
						case SDL_BUTTON_LEFT:	
							clicBotonMouseIzquierdo = true;
						break;						
					}			
					break;
				case SDL_MOUSEBUTTONUP:
					switch (event.button.button) {
						case SDL_BUTTON_LEFT:	
							clicBotonMouseIzquierdo = false;
						break;				
					}			
				break;
			}
		}				
		if (clicBotonMouseIzquierdo && posicionMouseX >48 && posicionMouseX <295 && posicionMouseY >190 && posicionMouseY <225){
			misionElegida = 1;
			std::cout << "Mision Elegida Carnicero" << std::endl;
			Log::getInstance().log(1,__FILE__,__LINE__,"Mision Elegida Carnicero");
			std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin();
			advance(it, 0);
			std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl;
			this->juegoElegido.nombreEscenario = (*it).nombre;
			this->juegoElegido.escenario = (*it);
			SDL_FreeSurface( imagenDeFondo );
			SDL_FreeSurface( textoMisionCarnicero );   
			SDL_FreeSurface( textoMisionBanderas );    				
			SDL_FreeSurface( pantalla );   
			TTF_CloseFont( fuente );
			TTF_Quit();   
			SDL_Quit();
			return misionElegida;
		}		
		else  if (clicBotonMouseIzquierdo && posicionMouseX >348 && posicionMouseX <595 && posicionMouseY >190 && posicionMouseY <225){
			misionElegida = 2;
			std::cout << "Mision Elegida Banderas" << std::endl;
			Log::getInstance().log(1,__FILE__,__LINE__,"Mision Elegida Banderas");
			std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin();
			advance(it, 1);
			std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl;
			this->juegoElegido.nombreEscenario = (*it).nombre;
			this->juegoElegido.escenario = (*it);
			SDL_FreeSurface( imagenDeFondo );
			SDL_FreeSurface( textoMisionCarnicero );   
			SDL_FreeSurface( textoMisionBanderas );    				
			SDL_FreeSurface( pantalla );   
			TTF_CloseFont( fuente );
			TTF_Quit();   
			SDL_Quit();				
			return misionElegida;
		}		
    }
	SDL_FreeSurface( imagenDeFondo );
	SDL_FreeSurface( textoMisionCarnicero );   
	SDL_FreeSurface( textoMisionBanderas );    				
	SDL_FreeSurface( pantalla );   
	TTF_CloseFont( fuente );
	TTF_Quit();   
	SDL_Quit();		
	return 3;
}
Exemple #9
0
int main(int argc, char *argv[])
{
    SDL_Surface *screen      = NULL,
                *image       = NULL,
                *scaledImage = NULL,
                *name        = NULL;
    SDL_Rect     picturePortion;
    TTF_Font    *font = NULL;
    double       scale = 1.0;
    int          currentImageNumber = 1,
                 showFileName = TRUE,
                 runSlideShow = FALSE,
                 isRunning = TRUE;
    SDL_TimerID  slideShowTimer = 0;

    // Process command line
    if (argc < 2) {
        fprintf(stderr,  "\n"
            " imgv v%s. Syntax: imgv <image files>\n\n"
            " Hotkeys:\n"
            " 'f' fit to screen\n"
            " 'z' zoom at pixel level\n"
            " 'i' zoom in  'o' zoom out\n"
            " 'l' rotate left  'r' rotate right\n"
            " 'n' next image  'p' previous image\n"
            " 'd' show / hide file name\n"
            " 's' start / stop slide show\n"
            " 'arrows' pan  'ESC' quit\n\n", VERSION);
        exit(0);
    }

    screen = initScreen();

    font = TTF_OpenFont("font.ttf", 11);
    if (font == (TTF_Font *) (NULL)) {
        font = TTF_OpenFont("/usr/share/imgv/font.ttf", 11);
    }
    if (font == (TTF_Font *) (NULL)) {
        font = TTF_OpenFont("/usr/share/fonts/ttf-dejavu/DejaVuSans.ttf", 11);
    }

    picturePortion.w = SCREENWIDTH;
    picturePortion.h = SCREENHEIGHT;

    image = loadImage(argv[1]);
    if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) {
        scaledImage = zoom100(image, &picturePortion, &scale);
    } else {
        scaledImage = zoomFit(image, &picturePortion, &scale);
    }
    name = drawFileName(argv[currentImageNumber], font, runSlideShow);
    drawImage(scaledImage, &picturePortion, screen, name);

    do {
        SDL_Event event;
        if (SDL_WaitEvent(&event) && event.type == SDL_KEYDOWN) {
            switch (event.key.keysym.sym) {
                case SDLK_LEFT: // PAN LEFT
                    pan(scaledImage, &picturePortion, -PANSTEP, 0);
	                break;
                case SDLK_RIGHT: // PAN RIGHT
                    pan(scaledImage, &picturePortion, PANSTEP, 0);
                    break;
                case SDLK_UP: // PAN UP
                    pan(scaledImage, &picturePortion, 0, -PANSTEP);
                    break;
                case SDLK_DOWN: // PAN DOWN
                    pan(scaledImage, &picturePortion, 0, PANSTEP);
                    break;
                case SDLK_i: // ZOOM IN
                    SDL_FreeSurface(scaledImage);
                    scaledImage = zoomIn(image, &picturePortion, &scale);
                    break;
                case SDLK_o: // ZOOM OUT
                    SDL_FreeSurface(scaledImage);
                    scaledImage = zoomOut(image, &picturePortion, &scale);
                    break;
                case SDLK_f: // ZOOM TO FIT SCREEN
                    SDL_FreeSurface(scaledImage);
                    scaledImage = zoomFit(image, &picturePortion, &scale);
                    break;
                case SDLK_z: // ZOOM TO ORIGINAL SIZE
                    SDL_FreeSurface(scaledImage);
                    scaledImage = zoom100(image, &picturePortion, &scale);
                    break;
                case SDLK_l: // ROTATE LEFT
                    {
                        SDL_FreeSurface(scaledImage);
                        SDL_Surface *tmp = rotateSurface90Degrees(image, 3);
                        SDL_FreeSurface(image);
                        image = tmp;
                        scaledImage = zoomSurface(image, scale, scale, SMOOTHING_ON);
                        int x = picturePortion.x;
                        picturePortion.x = picturePortion.y + SCREENHEIGHT/2 - SCREENWIDTH/2;
                        picturePortion.y = scaledImage->h - x - SCREENHEIGHT/2 - SCREENWIDTH/2;
                        pan(scaledImage, &picturePortion, 0, 0);
                    }
                    break;
                case SDLK_r: // ROTATE RIGHT
                    {
                        SDL_FreeSurface(scaledImage);
                        SDL_Surface *tmp = rotateSurface90Degrees(image, 1);
                        SDL_FreeSurface(image);
                        image = tmp;
                        scaledImage = zoomSurface(image, scale, scale, SMOOTHING_ON);
                        int x = picturePortion.x;
                        picturePortion.x = scaledImage->w - picturePortion.y - SCREENWIDTH/2
                                           - SCREENHEIGHT/2;
                        picturePortion.y = x + SCREENWIDTH/2 - SCREENHEIGHT/2;
                        pan(scaledImage, &picturePortion, 0, 0);
                    }
                    break;
                case SDLK_n: // NEXT IMAGE
                    if (currentImageNumber < argc-1) {
                        ++currentImageNumber;

                        SDL_FreeSurface(image);
                        SDL_FreeSurface(scaledImage);
                        SDL_FreeSurface(name);

                        image = loadImage(argv[currentImageNumber]);
                        if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) {
                            scaledImage = zoom100(image, &picturePortion, &scale);
                        } else {
                            scaledImage = zoomFit(image, &picturePortion, &scale);
                        }
                        name = drawFileName(argv[currentImageNumber], font, runSlideShow);
                    } else {
                        if (runSlideShow) {
                            SDL_RemoveTimer(slideShowTimer);
                            runSlideShow = FALSE;
                            name = drawFileName(argv[currentImageNumber], font, runSlideShow);
                        }
                    }
                    break;
                case SDLK_p: // PREVIOUS IMAGE
                    if (currentImageNumber > 1) {
                        --currentImageNumber;

                        SDL_FreeSurface(image);
                        SDL_FreeSurface(scaledImage);
                        SDL_FreeSurface(name);

                        image = loadImage(argv[currentImageNumber]);
                        if (image->w < SCREENWIDTH && image->h < SCREENHEIGHT) {
                            scaledImage = zoom100(image, &picturePortion, &scale);
                        } else {
                            scaledImage = zoomFit(image, &picturePortion, &scale);
                        }
                        name = drawFileName(argv[currentImageNumber], font, runSlideShow);
                    }
                    break;
                case SDLK_s: // START / STOP SLIDESHOW
                    runSlideShow = 1 - runSlideShow;
                    name = drawFileName(argv[currentImageNumber], font, runSlideShow);
                    if (runSlideShow) {
                        slideShowTimer = SDL_AddTimer(SLIDESHOWTIMEOUT, timerCallback, NULL);
                    } else {
                        SDL_RemoveTimer(slideShowTimer);
                    }
                    break;
                case SDLK_d: // SHOW / HIDE FILENAME
                    showFileName = 1 - showFileName;
                    break;
                case SDLK_ESCAPE: // QUIT
                case SDLK_q:
                    isRunning = FALSE;
                    break;
                default:
                    break;
             } // end of switch (event.key.keysym.sym)
        } // end of if(SDL_WaitEvent())
        drawImage(scaledImage, &picturePortion, screen, showFileName ? name : 0);
    } while(isRunning); // end of do

    SDL_FreeSurface(image);
    SDL_FreeSurface(scaledImage);
    SDL_FreeSurface(screen);

    TTF_CloseFont(font);
    TTF_Quit();

    SDL_Quit();

    return 0;
}
Exemple #10
0
int main(int argc , char ** argv)
{
  char a;
  struct key key;
  int loop;
  int menu;
  int selectedMenu;
  /* Initialisation simple */

  if (argc == 1)
    a = argv[0][0];
  if (SDL_Init(SDL_INIT_VIDEO) != 0 )
    {
      fprintf(stdout,"Échec de l'initialisation de la SDL (%s)\n",SDL_GetError());
      return -1;
    }
  //writeScore("Flo 2", 92);
  TTF_Init();
  /* Création de la fenêtre */
  SDL_Window* pWindow = NULL;
  SDL_Renderer* pRenderer = NULL;
  SDL_Surface* pSurface = NULL;
  TTF_Font* font = TTF_OpenFont("/Library/Fonts/Microsoft/Arial.ttf", 72);
  pWindow = SDL_CreateWindow("Space Invaders",SDL_WINDOWPOS_UNDEFINED,
			     SDL_WINDOWPOS_UNDEFINED,
			     640,
			     480,
			     SDL_WINDOW_SHOWN);
  pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_PRESENTVSYNC);
  /* Initialisation du texte */
  if ( pWindow )
    {
      loop = 1;
      menu = 1;
      selectedMenu = 1;
      while (loop == 1) {
	key = getKey(key);
	if (key.exit == 1)
	  loop = 0;
	if (menu == 1) {
	  if (key.down == 1 && selectedMenu < 4)
	    selectedMenu++;
	  else if (key.up == 1 && selectedMenu > 1)
	    selectedMenu--;
	  else if (key.enter == 1) {
	    if (selectedMenu == 1)
	      menu = 0;
	    else if (selectedMenu == 2)
	      menu = 1; //doing nothing yet
	    else if (selectedMenu == 3)
	      menu = 2;
            else if (selectedMenu == 4)
              loop = 0;
	  }
	  pRenderer = drawMenu(pRenderer, selectedMenu, font, pSurface);
	}
	else if (menu == 2) {
	  if (key.enter == 1)
	    menu = 1;
	  else
	    pRenderer = drawHighScores(pRenderer, font, pSurface);
	}
	else
	  pRenderer = drawGame(pRenderer);
	SDL_Delay(100);
	}
    }
  TTF_CloseFont(font);
  SDL_DestroyWindow(pWindow);
  TTF_Quit();
  SDL_Quit();
  return 0;
}
Exemple #11
0
//No es usado por hilos
bool ModeloFactory::nuevoElegirEscenario(std::list<ParserYaml::stEscenario>& listaEscenarios){
	bool quit = false;
	bool clicBotonMouseIzquierdo = false;	
	int posicionMouseX, posicionMouseY;
	SDL_Event event;
	TTF_Font *fuente = NULL;
	SDL_Color textColor = { 255, 255, 255 }; //color blanco 
	SDL_Surface* pantalla = NULL;
	SDL_Init( SDL_INIT_EVERYTHING );
	pantalla = SDL_SetVideoMode( PANTALLA_ANCHO, PANTALLA_ALTO, SCREEN_BPP, SDL_SWSURFACE );
	TTF_Init();
	SDL_WM_SetCaption( "Menu", NULL );
	SDL_Surface *imagenDeFondo3 = NULL;
	imagenDeFondo3 = ImageLoader::getInstance().load_image( IMG_CARNICERO );
	fuente = TTF_OpenFont( FUENTE_USADA, 28 );	
	SDL_Rect offsetDelFondo;
	offsetDelFondo.x = 0;
	offsetDelFondo.y = 0;
	SDL_BlitSurface( imagenDeFondo3, NULL, pantalla, &offsetDelFondo );
	vector <SDL_Surface*> vectorDeNombresDeEscenarios;
	for (std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin() ; it != listaEscenarios.end(); it++ ){		
		const char* nombreDeEscenario = it->nombre.c_str();		
		vectorDeNombresDeEscenarios.push_back( TTF_RenderText_Solid( fuente, nombreDeEscenario, textColor ) );
	}	
	int x = 100;
	int y = 65;		
	for (std::vector<SDL_Surface*>::iterator it=vectorDeNombresDeEscenarios.begin() ; it != vectorDeNombresDeEscenarios.end(); it++ ){
		SDL_Rect offsetDelTextoNombreDelEscenario;
		offsetDelTextoNombreDelEscenario.x = x;
		offsetDelTextoNombreDelEscenario.y = y;						
		SDL_BlitSurface( *it, NULL, pantalla, &offsetDelTextoNombreDelEscenario );			
		rectangleRGBA( pantalla, x-5, y-5, x+400, y+35, 0, 255, 0, 255);	
		y += 100;			
	}		
	SDL_Flip( pantalla );
	while( quit == false ) {
        while( SDL_PollEvent( &event ) ) {            
			switch (event.type) {
				case SDL_QUIT:
					quit = true;
				break;
				case SDL_MOUSEMOTION:
					posicionMouseX = event.motion.x;
					posicionMouseY = event.motion.y;
				break;		
				case SDL_MOUSEBUTTONDOWN:
					switch (event.button.button) {
						case SDL_BUTTON_LEFT:	
							clicBotonMouseIzquierdo = true;
						break;						
					}			
					break;
				case SDL_MOUSEBUTTONUP:
					switch (event.button.button) {
						case SDL_BUTTON_LEFT:	
							clicBotonMouseIzquierdo = false;
						break;				
					}			
				break;
			}
		}		
		x = 100;
		y = 65;		
		int k = 1;
		while (k <= vectorDeNombresDeEscenarios.size() ) {
			if (clicBotonMouseIzquierdo && posicionMouseX > x-5 && posicionMouseX < x+400 && posicionMouseY > y-5 && posicionMouseY < y+35){				
				std::list<ParserYaml::stEscenario>::iterator it=listaEscenarios.begin();
				for ( int a = 1; a <= k-1; a++ ){		
					it++;
				}
				std::cout << "Se usara el escenario: "<< (*it).nombre << std::endl;
				this->juegoElegido.nombreEscenario = (*it).nombre;				
				this->juegoElegido.escenario = (*it);		
				while (vectorDeNombresDeEscenarios.size() != 0) {
					SDL_Surface * nombreDeEscenario = NULL; 
					nombreDeEscenario = vectorDeNombresDeEscenarios.back();
					SDL_FreeSurface ( nombreDeEscenario );
					vectorDeNombresDeEscenarios.pop_back();
				}
				SDL_FreeSurface( pantalla );    
				SDL_FreeSurface( imagenDeFondo3 );    
				TTF_CloseFont( fuente );
				TTF_Quit();   
				SDL_Quit();
				return true;
			}	
			y+=100;
			k++;
		}		
    }
	while (vectorDeNombresDeEscenarios.size() != 0) {
		SDL_Surface * nombreDeEscenario = NULL; 
		nombreDeEscenario = vectorDeNombresDeEscenarios.back();
		SDL_FreeSurface ( nombreDeEscenario );
		vectorDeNombresDeEscenarios.pop_back();
	}
	SDL_FreeSurface( pantalla );    
	SDL_FreeSurface( imagenDeFondo3 );    
	TTF_CloseFont( fuente );
	TTF_Quit();   
	SDL_Quit();
	return false;
}
Exemple #12
0
int main(int argc, char *argv[])
{
	/* initialize SDL and its subsystems */
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) die();
	if (TTF_Init() == -1) die();

	/* set the height and width of the main window, as well as the number
	   of bits per pixel; this needs to be done prior to initializing the 
	   main window (*screen, below) */
	initWindowAttributes();

	/* the frame buffer */
	SDL_Surface *screen = SDL_SetVideoMode(W_WIDTH, W_HEIGHT,
			W_COLOR_DEPTH, SDL_HWSURFACE|SDL_FULLSCREEN);
	if (!screen) die();

	/* hide the mouse cursor */
	SDL_ShowCursor(SDL_DISABLE);

	/* the background color of the screen */
	const Uint32 clearColor = CLEAR_COLOR(screen->format);
	clearScreen(screen, clearColor);

	/* clearColor as an SDL_Color, for use with TTF */
	Uint8 r, g, b;
	SDL_GetRGB(clearColor, screen->format, &r, &g, &b);
	SDL_Color bgColor = { r: r, g: g, b: b };

	/* the score font */
	TTF_Font *font = TTF_OpenFont("resources/VeraMono.ttf", FONT_SIZE);
	if (!font) die();
	SDL_Color fontColor = FONT_COLOR;

	/* the score text; we'll allow three digits plus the terminating '\0' */
	char *lScoreStr = malloc(sizeof(char) * 4);
	char *rScoreStr = malloc(sizeof(char) * 4);
	if (!lScoreStr || !rScoreStr) die();
	SDL_Surface *lScore = NULL, *rScore = NULL;
	SDL_Rect lScorePos = { x: C_X+FONT_SIZE, y: C_HEIGHT/5,
		w: F_WIDTH, h: F_HEIGHT };
	SDL_Rect rScorePos = { x: (C_X+C_WIDTH)-3*FONT_SIZE, y: C_HEIGHT/5,
		w: F_WIDTH, h: F_HEIGHT };

	/* set up the playing court */
	Court *court = makeCourt(screen);
	if (!court) die();

	/* set up the players and their paddles */
	Player *lPlayer = makePlayer(screen);
	Player *rPlayer = makePlayer(screen);
	if (!lPlayer || !rPlayer) die();
	rPlayer->paddle.rect.x = C_X + C_WIDTH - P_WIDTH;

	/* add the ball */
	Ball *ball = makeBall(screen);
	if (!ball) die();

	/* because SDL_KEY(UP|DOWN) occurs only once, not continuously while
	   the key is pressed, we need to keep track of whether a key is
	   (still) pressed */
	bool lPlayerShouldMoveUp = false, lPlayerShouldMoveDown = false,
	     rPlayerShouldMoveUp = false, rPlayerShouldMoveDown = false;

	Uint32 startTime;	/* denotes the beginning of each iteration
				   of the main event loop */
	bool running = true;	/* true till the application should exit */
	while (running) {
		startTime = SDL_GetTicks();

		/* clear the previous frame's paddles and ball */
		SDL_FillRect(screen, &lPlayer->paddle.rect, clearColor);
		SDL_FillRect(screen, &rPlayer->paddle.rect, clearColor);
		SDL_FillRect(screen, &ball->rect, clearColor);

		/* clear the previous frame's score */
		SDL_FillRect(screen, &lScorePos, clearColor);
		SDL_FillRect(screen, &rScorePos, clearColor);

		/* redraw the walls in case they were clipped by the ball
		   in a previous frame */
		SDL_FillRect(screen, &court->upperWall, court->color);
		SDL_FillRect(screen, &court->lowerWall, court->color);

		/* get the current state of the players' controls */
		readPlayerInput(&running,
				&lPlayerShouldMoveUp, &lPlayerShouldMoveDown,
				&rPlayerShouldMoveUp, &rPlayerShouldMoveDown);

		/* save the current position of the paddles */
		lPlayer->paddle.prevY = lPlayer->paddle.rect.y;
		rPlayer->paddle.prevY = rPlayer->paddle.rect.y;

		/* move the paddles if appropriate */
		if (lPlayerShouldMoveUp)
			movePaddle(court, &lPlayer->paddle, UP);
		else if (lPlayerShouldMoveDown)
			movePaddle(court, &lPlayer->paddle, DOWN);
		if (rPlayerShouldMoveUp)
			movePaddle(court, &rPlayer->paddle, UP);
		else if (rPlayerShouldMoveDown)
			movePaddle(court, &rPlayer->paddle, DOWN);

		/* move the ball */
		moveBall(court, ball, lPlayer, rPlayer);

		/* update the score */
		updateScore(ball, lPlayer, rPlayer);

		/* update the on-screen score */
		if (lScore) SDL_FreeSurface(lScore);
		snprintf(lScoreStr, 4, "%2d", lPlayer->points);
		lScore = TTF_RenderText_Shaded(font, lScoreStr, fontColor,
				bgColor);
		if (rScore) SDL_FreeSurface(rScore);
		snprintf(rScoreStr, 4, "%2d", rPlayer->points);
		rScore = TTF_RenderText_Shaded(font, rScoreStr, fontColor,
				bgColor);

		/* draw the score */
		SDL_BlitSurface(lScore, NULL, screen, &lScorePos);
		SDL_BlitSurface(rScore, NULL, screen, &rScorePos);

		/* draw the paddles */
		SDL_FillRect(screen, &lPlayer->paddle.rect,
				lPlayer->paddle.color);
		SDL_FillRect(screen, &rPlayer->paddle.rect,
				rPlayer->paddle.color);

		/* draw the ball */
		SDL_FillRect(screen, &ball->rect, ball->color);

		/* render frame to screen */
		SDL_Flip(screen);

		/* keep a steady frame rate */
		Uint8 elapsedTime = SDL_GetTicks() - startTime;
		if (elapsedTime < FRAME_DURATION)
			SDL_Delay(FRAME_DURATION - elapsedTime);
	}

	/* free resources */
	free(lScoreStr);
	free(rScoreStr);
	free(court);
	free(lPlayer);
	free(rPlayer);
	free(ball);

	TTF_CloseFont(font);
	TTF_Quit();
	SDL_FreeSurface(lScore);
	SDL_FreeSurface(rScore);
	SDL_Quit();

	return EXIT_SUCCESS;
}
Exemple #13
0
bool uniInicializar(int largura_janela, int altura_janela, bool tela_cheia, string titulo_janela, int flags_sdl_window)
{
	if (uniEstaInicializada())
	{
		gDebug.erro("uniInicializar() falhou. A biblioteja já foi inicializada anteriormente.");
		return false;
	}

	//	inicializa SDL
	SDL_Init(SDL_INIT_EVERYTHING);
	if (!SDL_WasInit(0))
		return false;

	//	inicializa SDL_ttf (biblioteca de fontes)
	TTF_Init();
	if (!TTF_WasInit())
	{
		SDL_Quit();
		return false;
	}

	//	inicializa globais
	Global::getInstancia().inicializar();

	//	cria janela principal
	bool janela_ok = gJanela.criar(largura_janela, altura_janela, tela_cheia, titulo_janela, flags_sdl_window);
	if (!janela_ok)
	{
		Global::getInstancia().finalizar();
		TTF_Quit();
		SDL_Quit();
		return false;
	}

	uniInicializada = true;		//	seta uniInicializada para true. Precisa ser feito aqui para poder carregar a fonte padrao
	gGraficos.inicializar(gJanela.getSDL_Renderer());
	if (!gGraficos.getFontePadrao())
	{
		//	se a fonte padrao nao foi carregada,
		//  limpa o painel de debug e desativa 
		//	para nao tentar desenhar sem ter uma fonte.
		gDebug.limpar();
		gDebug.desativar();
	}
	uniInicializada = false;	//	volta a ser false para continuar a inicializacao

								//	inicializa painel de debug
	gDebug.inicializar();

	//	inicializa audio
	gAudios.inicializar();
	if (!gAudios.estaInicializado())
	{
		gDebug.finalizar();
		gGraficos.finalizar();
		gJanela.destruir();
		Global::getInstancia().finalizar();
		TTF_Quit();
		SDL_Quit();
		return false;
	}

	//	inicializa handlers de eventos
	gEventos.janela = &gJanela;
	gEventos.mouse = &gMouse;
	gEventos.teclado = &gTeclado;
	gEventos.joysticks = &gJoysticks;
	gEventos.toques = &gToques;
	gEventos.atualizar();

	//	inicializa gerenciador de tempo
	gTempo.inicializar();

	//	seta uniInicializada para true
	uniInicializada = true;

	return true;
}
Exemple #14
0
void clear()
{
	TTF_Quit();
	SDL_Quit();
}
Exemple #15
0
TTF_system::~TTF_system()
{
  TTF_Quit();
}
Exemple #16
0
int main(int argc, char ** argv) {
  SDL_Window * window;
  SDL_Renderer * renderer;
  SDL_Surface * set;
  KW_GUI * gui;
  TTF_Font * font;
  SDL_Rect geometry = {0, 0, 320, 240};
  KW_Widget * frame, * button;
  int i;
  SDL_Event ev;
  
  /* initialize SDL */
  SDL_Init(SDL_INIT_EVERYTHING);

  
#if defined(ANDROID)
  /* enjoy all the screen size on android */
  i = SDL_GetNumVideoDisplays();
  if (i < 1) exit(1);
  SDL_GetDisplayBounds(0, &geometry);
#endif
  SDL_CreateWindowAndRenderer(geometry.w, geometry.h, SDL_WINDOW_RESIZABLE, &window, &renderer);
  SDL_SetRenderDrawColor(renderer, 100, 200, 100, 1);
  TTF_Init();
  
  /* load tileset */
  set = IMG_Load("tileset.png");
  
  /* initialize gui */
  gui = KW_Init(renderer, set);
  font = TTF_OpenFont("SourceSansPro-Semibold.ttf", 12);
  TTF_SetFontHinting(font, TTF_HINTING_NONE);
  KW_SetFont(gui, font);

  geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875;
  frame = KW_CreateScrollbox(gui, NULL, &geometry);
  KW_AddWidgetDragStartHandler(frame, DragStart);
  KW_AddWidgetDragHandler(frame, Drag);
  KW_AddWidgetDragStopHandler(frame, DragStop);
  SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);

  geometry.x = 10; geometry.y = 0; geometry.h = 40; geometry.w = 230;
  
  for (i = 0; i < 5; i++) {
    button = KW_CreateButton(gui, frame, "Drag me, resize me.", &geometry);
    KW_AddWidgetDragStartHandler(button, DragStart);
    KW_AddWidgetDragHandler(button, Drag);
    KW_AddWidgetDragStopHandler(button, DragStop);
    geometry.y += geometry.h;
  }
    
  /* create another parent frame */
  while (!SDL_QuitRequested()) {
    while (SDL_PollEvent(&ev)) {
      if (ev.type == SDL_WINDOWEVENT && ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
        geometry.w = ev.window.data1;
        geometry.h = ev.window.data2;
        geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875;
        KW_SetWidgetGeometry(frame, &geometry);
      }
    }
    SDL_RenderClear(renderer);
    KW_Paint(gui);
    SDL_RenderPresent(renderer);
    SDL_Delay(1);
  }
  TTF_CloseFont(font);
  TTF_Quit();
  KW_Quit(gui);
  SDL_FreeSurface(set);
  SDL_Quit();
  
  return 0;
}
Exemple #17
0
static void _destroy_gfx(game *g) {
    SDL_GL_DeleteContext(g->gl_ctx);
    SDL_DestroyWindow(g->win);
    TTF_Quit();
    SDL_Quit();
}
Exemple #18
0
	/**
	*	Open the window and initialize sdl/opengl
	*	@return True if the window opened successfully
	*/
	bool System::InitEngine()
	{
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
		{
			ReportError("Erreur lors de l'initialisation de la SDL : " + std::string(SDL_GetError()));
			SDL_Quit();
			return false;
		}
		else
			Log("SDL Initialized !");

		if (TTF_Init() < 0)
		{
			TTF_Quit();
			SDL_Quit();
			return false;
		}
			else
				Log("SDL_TTF Initialized !");

		//Set sdl gl attribute
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,4);
		SDL_GL_SetAttribute(SDL_GL_RED_SIZE,8);
		SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8);
		SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,8);
		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,24);
#ifdef _DEBUG
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif

		_mainwindowPtr = SDL_CreateWindow("Rarium", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
			1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
		_width = 1280;
		_height = 720;

		if (!_mainwindowPtr) /* Die if creation failed */
		{
			Log("SDL Window creation failed : " + std::string(SDL_GetError()));
			TTF_Quit();
			SDL_Quit();
			return false;
		}
		else
			Log("Window created");

		_maincontext = SDL_GL_CreateContext(_mainwindowPtr);

		SDL_GL_SetSwapInterval(1);

		//SDL_ShowCursor(SDL_DISABLE);

		SDL_FlushEvents(SDL_FIRSTEVENT,SDL_LASTEVENT);

		PluginManager::GetRef().LoadPlugins();

		SDL_StartTextInput();

		static SDL_Rect rect;
		rect.x = 0;
		rect.y = 0;
		rect.w = 1280;
		rect.h = 720;

		SDL_SetTextInputRect(&rect);


		return true;
	}
JNIEXPORT void JNICALL Java_sdljava_x_swig_SWIG_1SDLTTFJNI_TTF_1Quit(JNIEnv *jenv, jclass jcls) {
    (void)jenv;
    (void)jcls;
    TTF_Quit();
    
}
Exemple #20
0
	/**
	*	Shut down sdl
	*/
	void System::StopEngine()
	{
		TTF_Quit();
		SDL_Quit();
	}
Exemple #21
0
int main(int argc, char** argv)
{
	SDL_Event ev;
	
	int quit = 0;
	int sleepCycle[] = {16, 17, 17};
	int sleepNth = 0;
	int sleepTotal = 0;
	int frameStart = 0;
	int frameEnd = 0;
	int frameDelta = 0;
	// int fps = 0, fpsreport = 0;
	
	nthlevel = 0;
	newlevelpause = 1;
	
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
	TTF_Init();
	
	sound_setup();
	sound_set_song(2);
	
	sfx_player_jump = sound_synth_get(0);
	sfx_player_jump->waveform = SYNTH_SQUARE;
	sfx_player_jump->length = 100;
	sfx_player_jump->amp_start = 0.3;
	sfx_player_jump->amp_end = 0.2;
	sfx_player_jump->freq_start = 300;
	sfx_player_jump->freq_end = 500;
	
	sfx_player_scare = sound_synth_get(1);
	sfx_player_scare->waveform = SYNTH_NOISE;
	sfx_player_scare->length = 320;
	sfx_player_scare->amp_start = 0.1;
	sfx_player_scare->amp_end = 0.1;
	sfx_player_scare->freq_start = 3200;
	sfx_player_scare->freq_end = 4800;
	
	sfx_player_scare2 = sound_synth_get(2);
	sfx_player_scare2->waveform = SYNTH_SQUARE;
	sfx_player_scare2->length = 320;
	sfx_player_scare2->amp_start = 0.15;
	sfx_player_scare2->amp_end = 0.0;
	sfx_player_scare2->freq_start = 1200;
	sfx_player_scare2->freq_end = 1550;
	
	sfx_clear_goat1 = sound_synth_get(3);
	sfx_clear_goat1->waveform = SYNTH_SQUARE;
	sfx_clear_goat1->length = 50;
	sfx_clear_goat1->amp_start = 0.3;
	sfx_clear_goat1->amp_end = 0.3;
	sfx_clear_goat1->freq_start = 450;
	sfx_clear_goat1->freq_end = 450;
	
	sfx_clear_goat2 = sound_synth_get(4);
	sfx_clear_goat2->waveform = SYNTH_SQUARE;
	sfx_clear_goat2->length = 50;
	sfx_clear_goat2->delay = 50;
	sfx_clear_goat2->amp_start = 0.3;
	sfx_clear_goat2->amp_end = 0.3;
	sfx_clear_goat2->freq_start = 1250;
	sfx_clear_goat2->freq_end = 1250;
	
	sfx_hurting = sound_synth_get(5);
	sfx_hurting->waveform = SYNTH_SQUARE;
	sfx_hurting->length = 180;
	sfx_hurting->delay = 0;
	sfx_hurting->amp_start = 0.3;
	sfx_hurting->amp_end = 0;
	sfx_hurting->freq_start = 1000;
	sfx_hurting->freq_end = 2;
	
	sfx_c4 = sound_synth_get(6);
	sfx_c4->waveform = SYNTH_SQUARE;
	sfx_c4->length = 180;
	sfx_c4->delay = 0;
	sfx_c4->amp_start = 0.3;
	sfx_c4->amp_end = 0.1;
	sfx_c4->freq_start = 261.626;
	sfx_c4->freq_end = 261.626;
	
	sfx_f4 = sound_synth_get(7);
	sfx_f4->waveform = SYNTH_SQUARE;
	sfx_f4->length = 180;
	sfx_f4->delay = 0;
	sfx_f4->amp_start = 0.3;
	sfx_f4->amp_end = 0.1;
	sfx_f4->freq_start = 349.228;
	sfx_f4->freq_end = 349.228;
	
	level = 0;
	gravity = 0.8;
	
	framefn = &_introfn;
	memset(&controls, 0, sizeof(Controls));
	memset(&player, 0, sizeof(Player));
	
	player.hearts = 10;
	
	player.rect.w = 48;
	player.rect.h = 64;
	
	// level_place_player();
	
	player.spriterect.x = 192;
	player.spriterect.y = 0;
	player.spriterect.w = 48;
	player.spriterect.h = 64;
	
	font = TTF_OpenFont("Vera.ttf", 16);
	screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE);
	
	load_sprites();
	
	mygoats = (Goat**) malloc(sizeof(Goat*) * 16);
	memset(mygoats, 0, sizeof(Goat*) * 16);
	
	// mygoats[0] = goat_create(100, 10);
	// mygoats[1] = goat_create(300, 10);
	// mygoats[2] = goat_create(500, 10);
	
	myslimes = (Slime**) malloc(sizeof(Slime*) * 16);
	memset(myslimes, 0, sizeof(Slime*) * 16);
	
	// myslimes[0] = slime_create(400, 10, 1);
	// myslimes[0]->controls.left = 1;
	
	// fpsreport = SDL_GetTicks() + 1000;
	
	while (!quit)
	{
		frameDelta = SDL_GetTicks() - frameStart;
		frameStart = SDL_GetTicks();
		
		framefn(frameDelta);
		
		while (SDL_PollEvent(&ev))
		{
			switch (ev.type)
			{
				case SDL_KEYDOWN:
					switch (ev.key.keysym.sym)
					{
						case SDLK_LEFT:
							controls.left = 1;
							break;
						
						case SDLK_RIGHT:
							controls.right = 1;
							break;
						
						case SDLK_UP:
							// controls.up = 1;
							controls.button1 = 1;
							break;
						
						case SDLK_DOWN:
							controls.down = 1;
							break;
						
						case SDLK_z:
						case SDLK_SPACE:
							controls.button1 = 1;
							break;
						
						case SDLK_x:
						case SDLK_LCTRL:
							controls.button2 = 1;
							break;
						
						default:
							break;
					}
					
					break;
				
				case SDL_KEYUP:
					switch (ev.key.keysym.sym)
					{
						case SDLK_LEFT:
							controls.left = 0;
							break;
						
						case SDLK_RIGHT:
							controls.right = 0;
							break;
						
						case SDLK_UP:
							// controls.up = 0;
							controls.button1 = 0;
							break;
						
						case SDLK_DOWN:
							controls.down = 0;
							break;
						
						case SDLK_z:
						case SDLK_SPACE:
							controls.button1 = 0;
							break;
						
						case SDLK_x:
						case SDLK_LCTRL:
							controls.button2 = 0;
							break;
						
						default:
							break;
					}
					
					break;
				
				case SDL_QUIT:
					quit = 1;
					break;
				
				default:
					break;
			}
		}
		
		// ++fps;
		
		frameEnd = SDL_GetTicks();
		
		// if (fpsreport <= frameEnd)
		// {
			// printf("%d fps\n", fps);
			// fps = 0;
			// fpsreport += 1000;
		// }
		
		if (sleepCycle[sleepNth] - (frameEnd - frameStart) > 0)
		{
			SDL_Delay(sleepCycle[sleepNth] - (frameEnd - frameStart));
		}
		
		if (++sleepNth > 2)
		{
			sleepNth = 0;
		}
	}
	
	sound_quit();
	TTF_CloseFont(font);
	TTF_Quit();
	SDL_Quit();
	
	return EXIT_SUCCESS;
}
Program::~Program(void)
{
	TTF_Quit();
	SDL_Quit();
}
TextGenerator::~TextGenerator() {
	for (auto &font : fonts)
		TTF_CloseFont(font.second);
	TTF_Quit();
	pTextGenerator = 0;
}
Exemple #24
0
	// Quits the engine.
	void Engin::quit()
	{
		TTF_Quit();
		SDL_Quit();
	}
Exemple #25
0
static void cleanup(int exitcode)
{
	TTF_Quit();
	SDL_Quit();
	exit(exitcode);
}
Exemple #26
0
int main(int argc, char * argv[])
{
    /*variable declarations,
	remember, all v. decls. are at the beginning of each function in C*/
    int done = 0;
    const Uint8 * keys;
    
    int mx,my;
    float mf = 0;
	float guyFrame = 0;
	Sprite *thing;
	Sprite *thing2;
	Sprite *guyx;
	Sprite *galSprite;
	Sprite *mehSprite;
	int controllerConnected = 0;
	/*Sprite *myTileMap;
	const int level[] = 
	{ 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2 };*/
	FILE *tilemapFile;
	int tileClicked = 0;
	int p = 0;

    Vector4D mouseColor = {100,255,255,200};
	Vector2D flipVert = { 0, 1 };
	Vector2D scaleDown = { 0.5, 0.5 };
	Vector2D scaleUp = { 2, 2 };
	Vector2D scaleHalfUp = { 1.5, 1.5 };
	//IntNode *myLL = IntNode_init(5);
	/*Student *person;*/
	/*Entity *guy, *testDude;
	Entity *en = NULL;
	Entity *biggo = NULL;
	FILE *infile;
	Entity *fileLoadedDude = NULL;
	Entity *fileLoadedDude2 = NULL;*/
	SDL_Event e;
	SDL_Surface *icon = SDL_LoadBMP("images/sprites/guy16x.bmp");

	FILE *bandFile;
	FILE *levelFile;

	Sound *NJITtheme = NULL;
	Sound *snareDrum = NULL;
	Sound *flute = NULL;
	Sound *trumpet = NULL;
	Sound *altoSax = NULL;
	Sound *tenorSax = NULL;
	Uint32 musicPlaying = 0;
	//Sound *clap = NULL;
	Sound *cdEject = NULL;

	/*TTF_Font *PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 24);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	SDL_Color colorBlack = { 255, 255, 255, 255 };
	SDL_Surface *surfaceMessage = TTF_RenderText_Solid(PencilFont, "placeholdha", colorBlack);
	SDL_Texture *message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer, surfaceMessage);
	Sprite *textBox;*/
	TTF_Font *PencilFont;
	SDL_Color colorBlack = { 0, 0, 0, 255 };
	SDL_Surface *surfaceMessage;
	SDL_Texture *message;
	Sprite *textBox;
	TextDisplay *nameText;
	int texW = 0, texH = 0;
	SDL_Rect rect = { 65, 630, 0, 0 };

	SDL_Surface *instrumentSurface;
	SDL_Texture *instrumentTexture;
	int instX = 0, instY = 0;
	SDL_Rect instrumentRect = { 65, 660, 0, 0 };

	Uint8 playButtonPressed = 0;

	srand(time(NULL));

    /*program initializtion*/
    init_logger("dmdwa.log");
    slog("---==== BEGIN ====---");
    gf2d_graphics_initialize(
        "Drum Majors Don't Wear Aussies",
        1200,
        720,
        1200,
        720,
        vector4d(0,0,0,255),
        0,
		icon);
	//SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); //This line makes images render crisp instead of blurry
    gf2d_graphics_set_frame_delay(16);
    gf2d_sprite_init(1024);
	entitySystemInit(1024);
	audioSystemInit(50, 10, 2, 0, 0, 0);
	soundSystemInit(25);
	text_system_init(50);
    SDL_ShowCursor(SDL_DISABLE);
	TTF_Init();
	//fileLoadedDude = entityNew();

	//derp
	//slog("%i", myLL->data);
    
    /*demo setup*/
    //backgroundSprite = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
	//textBox = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
    mouseSprite = gf2d_sprite_load_all("images/pointer.png",32,32,16);
	mouse = mouseSprite;
	//thing = gf2d_sprite_load_all("images/sprites/test_dude.png", 32, 32, 1);
	//thing2 = gf2d_sprite_load_all("images/sprites/test_dude3.png", 64, 64, 1);
	//guyx = gf2d_sprite_load_all("images/sprites/guy32x.png", 32, 32, 2);
	//galSprite = gf2d_sprite_load_all("images/sprites/gal32x.png", 32, 32, 2);
	//mehSprite = gf2d_sprite_load_all("images/sprites/meh32x.png", 32, 32, 2);
	//musicSheet = gf2d_sprite_load_image("images/gui/music_sheet.png");
	controllerIcon = gf2d_sprite_load_all("images/gui/controller64x.png", 64, 64, 1);
	//myTileMap = gf2d_sprite_load_all("images/field_tiles.png", 64, 64, 2);
	//person = student("Test", "Sex", thing2);
	//slog("Initializing student %s", person->name);
	/*guy = entityNew();
	strncpy(guy->name, "McBandgeek", 32);
	guy->mySprite = guyx;
	guy->scale = scaleUp;
	guy->currentFrame = 0;
	guy->minFrame = 0;
	guy->maxFrame = 2;
	guy->position = vector2d(300, 100);
	guy->update = move;
	guy->myInstrument = Instrument_Tenor_Saxophone;
	guy->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tenor_sax.png", 32, 32, 1);
	guy->boundingBox = rect_new(guy->position.x, guy->position.y, 64, 64);
	testDude = NULL;
	//SDL_SetTextureColorMod(thing2->texture, 100, 60, 0);
	infile = fopen("def/dude.dude", "r");
	fileLoadedDude = entityNew();
	fileLoadedDude = entityLoadFromFile(infile, fileLoadedDude);
	fclose(infile);
	//fileLoadedDude->mySprite = mehSprite;
	fileLoadedDude->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude->position = vector2d(64, 64);
	fileLoadedDude->boundingBox = rect_new(fileLoadedDude->position.x, fileLoadedDude->position.y, 64, 64);
	fileLoadedDude->scale = vector2d(2, 2);
	fileLoadedDude->currentFrame = 0;
	fileLoadedDude->minFrame = 0;
	fileLoadedDude->maxFrame = 2;
	fileLoadedDude->currentPosition = 19;
	slog("the thing made has name: %s", &fileLoadedDude->name);

	infile = fopen("def/dude2.dude", "r");
	fileLoadedDude2 = entityNew();
	fileLoadedDude2 = entityLoadFromFile(infile, fileLoadedDude2);
	fclose(infile);
	fileLoadedDude2->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude2->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude2->position = vector2d(128, 64);
	fileLoadedDude2->boundingBox = rect_new(fileLoadedDude2->position.x, fileLoadedDude2->position.y, 64, 64);
	fileLoadedDude2->scale = vector2d(2, 2);
	fileLoadedDude2->currentFrame = 0;
	fileLoadedDude2->minFrame = 0;
	fileLoadedDude2->maxFrame = 2;
	fileLoadedDude2->currentPosition = 20;*/

	tile_map = tilemap_init();
	load_level("def/level/mainMenu.txt", 0);

	//textBox->texture = message;

	//Trying to load a tilemap from file
	//tilemapFile = fopen("def/level/field_0.tilemap", "r");
	//tilemap_load_from_file(tilemapFile, tile_map);
	//fclose(tilemapFile);
	//slog("tilewidth: (%i) tileheight: (%i) tperline: (%i) filepath: (...) width: (%i) height: (%i) xPos: (%i) yPos: (%i)", tile_map->tileWidth,	tile_map->tileHeight, tile_map->tilesPerLine, tile_map->width, tile_map->height, tile_map->xPos, tile_map->yPos);
	//slog("do i have a sprite? %i", tile_map->tilemapSprite != NULL);
	//tile_map->space[19] = 1;
	//tile_map->space[20] = 1;
	/*slog("tile pq start");
	while (tile_map->tiles_head != NULL)
	{
		p = pq_delete(tile_map->tiles_head, tile_map->tiles_tail);
		if (p == NULL)
		{
			break;
		}
		slog("Removing (%d) from pq", p);
	}
	slog("tile pq end");*/
	/*slog("start array");
	for (p = 0; p < tile_map->width * tile_map->height; p++)
	{
		if (p == 512)
		{
			slog("end of array");
		}
		else if (tile_map->tiles[p] == -1)
		{
			slog("found a -1");
		}
		else
		{
			slog("tiles at index (%i) is (%i)", p, tile_map->tiles[p]);
		}
	}
	slog("end array");*/

	//Trying to load all entities from a file
	//bandFile = fopen("def/_myBand.band", "r");
	//entityLoadAllFromFile(bandFile);
	//fclose(bandFile);

	//Load sounds
	//NJITtheme = soundNew("music/bg/NJIT.ogg");
	//NJITtheme = soundLoad("music/bg/NJIT.ogg", 12.0f, 3);
	//slog("do i have a sound? %i", NJITtheme->sound != NULL);
	//soundPlay(NJITtheme, 1, 0, 0, 0);
	//Mix_VolumeChunk(NJITtheme->sound, MIX_MAX_VOLUME); //Use this to change volume on the fly!
	//clap = soundLoad("music/sfx/clap.ogg", 5.0f, 1);
	cdEject = soundNew();
	cdEject = soundLoad("music/sfx/cd_play.ogg", 18.0f, 0);

	snareDrum = soundNew("music/bg/meeeeh-Snare_Drum.ogg");
	snareDrum = soundLoad("music/bg/meeeeh-Snare_Drum.ogg", 12.0f, Instrument_Snare_Drum);
	flute = soundNew("music/bg/meeeeh-Flute.ogg");
	flute = soundLoad("music/bg/meeeeh-Flute.ogg", 12.0f, Instrument_Flute);
	trumpet = soundNew("music/bg/meeeeh-Bb_Trumpet.ogg");
	trumpet = soundLoad("music/bg/meeeeh-Bb_Trumpet.ogg", 12.0f, Instrument_Trumpet);
	altoSax = soundNew("music/bg/meeeeh-Alto_Saxophone.ogg");
	altoSax = soundLoad("music/bg/meeeeh-Alto_Saxophone.ogg", 12.0f, Instrument_Alto_Saxophone);
	tenorSax = soundNew("music/bg/meeeeh-Tenor_Saxophone.ogg");
	tenorSax = soundLoad("music/bg/meeeeh-Tenor_Saxophone.ogg", 12.0f, Instrument_Tenor_Saxophone);

	//soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
	//soundPlay(flute, -1, 1, flute->defaultChannel, 0);
	//soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
	//soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
	//soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);

	//text testing stuff
	PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 36);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
	message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
	SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
	rect.w = texW;
	rect.h = texH;
	nameText = text_new(PencilFont, "placeholda", colorBlack);
	//slog("nameText inuse (%i)", nameText->inUse);

	instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
	instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
	SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
	instrumentRect.w = instX;
	instrumentRect.h = instY;

	cd = entityNew();
	cd->mySprite = gf2d_sprite_load_all("images/gui/cd.png", 128, 128, 1);
	cd->position = vector2d(0, 0);
	cd->scale = vector2d(2, 2);
	cd->boundingBox = rect_new(cd->position.x, cd->position.y, 128, 128);

	playButton = entityNew();
	playButton->mySprite = gf2d_sprite_load_image("images/gui/play.png");
	playButton->position = vector2d(64, 256);
	strncpy(playButton->name, "playButton", MAX_CHARS);
	playButton->boundingBox = rect_new(playButton->position.x, playButton->position.y, playButton->mySprite->frame_w, playButton->mySprite->frame_h);
	

    /*main game loop*/
    while(!done)
    {
        SDL_PumpEvents();   // update SDL's internal event structures
        keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame
        /*update things here*/
        SDL_GetMouseState(&mx,&my);
		SDL_PollEvent(&e);
        mf+=0.1;
        if (mf >= 16.0)mf = 0;        
		guyFrame += 0.05;
		if (guyFrame >= 2.0)guyFrame = 0;
        
        gf2d_graphics_clear_screen();// clears drawing buffers
        // all drawing should happen betweem clear_screen and next_frame
		//backgrounds drawn first
		if (backgroundSprite)
		{
			gf2d_sprite_draw_image(backgroundSprite, vector2d(0, 0));
		}

		//Me! trying to add a sprite
		/*tilemap_draw(
			myTileMap,
			level,
			18,
			10,
			0,
			0);*/
		if (tile_map)
		{
			tilemap_draw_from_data(tile_map);
		}

		//gf2d_sprite_draw(thing, vector2d(100, 10), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(thing, vector2d(100, 10), NULL, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(guy->mySprite, guy->position, &(guy->scale), NULL, NULL, NULL, NULL, 0);

		/*if (keys[SDL_SCANCODE_W])
		{
			(*guy->update)(guy, vector2d(0, -2));
		}
		if (keys[SDL_SCANCODE_A])
		{
			(*guy->update)(guy, vector2d(-2, 0));
		}
		if (keys[SDL_SCANCODE_S])
		{
			(*guy->update)(guy, vector2d(0, 2));
		}
		if (keys[SDL_SCANCODE_D])
		{
			(*guy->update)(guy, vector2d(2, 0));
		}*/
		//guy->currentFrame = guyFrame;
		//fileLoadedDude->currentFrame = guyFrame;

		/*
		//create an entity if it doesn't exist
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			testDude = entityNew();
			testDude->mySprite = thing;
			testDude->position = vector2d(500, 500);
			testDude->update = move;
		}
		//if it exists, call its update function
		//slog("%i", testDude != NULL);
		if (testDude != NULL)
		{
			//(*testDude->update)(testDude, vector2d(1, 1));
			gf2d_sprite_draw(testDude->mySprite, testDude->position, NULL, NULL, NULL, NULL, NULL, 0);
		}
		//delete it from memory
		if (keys[SDL_SCANCODE_P] && testDude != NULL)
		{
			entityDelete(testDude);
		}*/
		/*if (keys[SDL_SCANCODE_L] && biggo == NULL)
		{
			biggo = entityNew();
			biggo->mySprite = guyx;
			biggo->position = vector2d(10, 10);
			biggo->scale = vector2d(25, 25);
			biggo->inUse = 1;
			biggo->currentFrame = 0;
			biggo->minFrame = 0;
			biggo->maxFrame = 2;
			biggo->update = move;
			biggo->velocity = vector2d(0.5f, 0.5f);
			biggo->acceleration = vector2d(0.5f, 0.5f);
			biggo->myInstrument = Instrument_Flute;
			biggo->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_flute.png", 32, 32, 1);
		}
		if (biggo != NULL)
		{
			//entityDraw(biggo);
			(*biggo->update)(biggo, vector2d(0.5f, 0.5f));
			//biggo->currentFrame = guyFrame;
		}
		if (biggo != NULL && biggo->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			biggo->inUse = 0;
			entityDelete(biggo);
			biggo = NULL;
		}
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			//slog("Let's make a new thing!");
			testDude = entityNew();
			testDude->mySprite = mehSprite;
			testDude->position = vector2d(200, 200);
			testDude->scale = scaleUp;
			testDude->inUse = 1;
			testDude->currentFrame = 0;
			testDude->minFrame = 1;
			testDude->maxFrame = 3;
			testDude->update = move;
			testDude->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tuba.png", 32, 32, 1);
		}
		if (testDude != NULL)
		{
			//gf2d_sprite_draw(testDude->mySprite, testDude->position, &(testDude->scale), NULL, NULL, NULL, NULL, 0);
			//entityDraw(testDude);
			(*testDude->update)(testDude, vector2d(1, 1));
			//testDude->currentFrame = guyFrame;
		}
		if (testDude != NULL && testDude->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			testDude->inUse = 0;
			entityDelete(testDude);
			testDude = NULL;
		}
		if (keys[SDL_SCANCODE_M] && en == NULL)
		{
			en = entityNew();
			en->mySprite = galSprite;
			en->position = vector2d(300, 500);
			en->scale = vector2d(1,1);
			en->inUse = 1;
			en->currentFrame = 0;
			en->minFrame = 0;
			en->maxFrame = 4;
			en->update = move;
			en->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_clarinet.png", 32, 32, 1);
			//soundPlay(clap, 0, clap->volume, clap->defaultChannel, 0);
		}
		if (en != NULL && en->inUse == 1)
		{
			//entityDraw(en);
			(*en->update)(en, vector2d(1, -1));
			//en->currentFrame = guyFrame;
		}
		if (en != NULL && en->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}
		if (en != NULL && en->inUse == 1 && en->position.x >= 400)
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}*/

		/*gf2d_sprite_draw(
			guyx,
			vector2d(64, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			galSprite,
			vector2d(128, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			mehSprite,
			vector2d(192, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);*/

		//entityDraw(fileLoadedDude);

		entityDrawAll();
		entityUpdateAll();
		entityIncrementCurrentFrameAll();

		if (pickedUp != NULL)
		{
			draw_line(vector2d(pickedUp->position.x + pickedUp->mySprite->frame_w, pickedUp->position.y + pickedUp->mySprite->frame_h),
						vector2d(mx, my), COLOR_RED);
		}

		switch (e.type)
		{
		case SDL_QUIT:
			done = 1;
			break;
		case SDL_MOUSEBUTTONDOWN:
			if (e.button.button == SDL_BUTTON_RIGHT)
			{
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0 && pickedUp != NULL)
				{
					if (tile_map->space[tileClicked] == 0)
					{
						slog("poop");
						tile_map->space[pickedUp->currentPosition] = 0;
						tile_map->space[tileClicked] = 1;
						pickedUp->currentPosition = tileClicked;
						mouse = mouseSprite;
						pickedUp->position.x = (mx - tile_map->xPos) / tile_map->tileWidth * (tile_map->tileWidth);
						pickedUp->position.y = (my - tile_map->yPos) / tile_map->tileHeight * (tile_map->tileHeight);
						pickedUp = NULL;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}
			}
			else if (e.button.button == SDL_BUTTON_LEFT)
			{
				if (playButton != NULL)
				{
					if (point_in_rect(mx, my, playButton->boundingBox))
					{
						//slog("hit da BUTT");
						playButtonPressed = 1;
						soundPlay(cdEject, 0, 5.0f, -1, 0);
					}
				}
			}
			break;
		case SDL_MOUSEBUTTONUP:
			if (e.button.button == SDL_BUTTON_LEFT)
			//if (mousePress(&e.button))
			{
				/*if (point_in_rect(mx, my, guy->boundingBox))
				{
					slog("collision with guy (%s)", guy->name);
				}
				if (point_in_rect(mx, my, fileLoadedDude->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude;
						mouse = fileLoadedDude->mySprite;
					}
				}
				if (point_in_rect(mx, my, fileLoadedDude2->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude2->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude2;
						mouse = fileLoadedDude2->mySprite;
					}
				}*/

				collision = entityCheckCollisionInAll(mx, my);
				if (collision != NULL && collision->myInstrument != Instrument_Unassigned)
				{
					slog("collision with guy (%s)", &collision->name);
					if (pickedUp == NULL)
					{
						pickedUp = collision;
						mouse = collision->mySprite;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, &pickedUp->name, colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, entityGetInstrumentName(pickedUp), colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}

				//if (point_in_rect(mx, my, tile_map->boundingBox))
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0)
				{
					//slog("collided with tilemap on tile (%i), occupied (%i)", tileClicked, tile_map->space[tileClicked]);
				}
			}
			break;
		case SDL_CONTROLLERDEVICEADDED:
			slog("Connected a controller");
			controllerConnected = 1;
			break;
		case SDL_CONTROLLERDEVICEREMOVED:
			slog("Removed a controller");
			controllerConnected = 0;
			break;
		}

		if (playButtonPressed && cd != NULL)
		{
			cd->position.x += 5;
		}

		if (cd != NULL)
		{
			if (point_in_rect(1000, 10, cd->boundingBox))
			{
				load_level("def/level/myLevel.txt", 1);
				if (musicPlaying > 0)
				{
					//Mix_RewindMusic();
					Mix_HaltChannel(-1);
				}
				soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
				soundPlay(flute, -1, 1, flute->defaultChannel, 0);
				soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
				soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
				soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
				musicPlaying = 1;
			}
		}
		//slog("ds %i %i %i %i", cd->boundingBox->x, cd->boundingBox->y, cd->boundingBox->w, cd->boundingBox->h);

		//UI elements last
		if (musicSheet)
			gf2d_sprite_draw(musicSheet, vector2d(0, 592), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (gui)
			gf2d_sprite_draw(gui, vector2d(0, 0), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//text_draw_all();
		//text_draw(nameText);
		if (message && musicSheet)
		{
			SDL_RenderCopy(gf2d_graphics_get_renderer(), message, NULL, &rect);
			SDL_RenderCopy(gf2d_graphics_get_renderer(), instrumentTexture, NULL, &instrumentRect);
		}
		//SDL_RenderPresent(renderer);
		//gf2d_sprite_draw_image(textBox, vector2d(50, 50));
		if (controllerConnected && controllerIcon)
			gf2d_sprite_draw(controllerIcon, vector2d(700, 600), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (pickedUp == NULL)
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				NULL,				//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				(int)mf);			//Which frame to draw at
		}
		else
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				&scaleHalfUp,		//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				0);			//Which frame to draw at
		}
		gf2d_grahics_next_frame();// render current draw frame and skip to the next frame
        
		if (keys[SDL_SCANCODE_Q])
		{
			//close_level(tile_map);
			load_level("def/level/myLevel.txt", 1);
			if (musicPlaying > 0)
			{
				//Mix_RewindMusic();
				Mix_HaltChannel(-1);
			}
			soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
			soundPlay(flute, -1, 1, flute->defaultChannel, 0);
			soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
			soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
			soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
			musicPlaying = 1;
		}

        if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition
        //slog("Rendering at %f FPS",gf2d_graphics_get_frames_per_second());
    }
    slog("---==== END ====---");
	TTF_Quit();
	SDL_DestroyTexture(message);
	SDL_FreeSurface(surfaceMessage);
    return 0;
}
void C_FontManager::Finalize()
{
    // フォントの終了処理
    TTF_Quit();
}
Exemple #28
0
gameClass::~gameClass()
{
	TTF_CloseFont(font);
	TTF_Quit();
	SDL_Quit();
}
Exemple #29
0
UI::~UI() {
	if (m_has_initialized_ttf) {
		TTF_Quit();
	}
}
Exemple #30
0
void CFontManager::Shutdown(void)
{
	TTF_CloseFont(m_pTTFont);
	TTF_Quit();
}