예제 #1
0
void DrawText(int x, int y, char *text, int color, int spacing) {
	int x2 = x; // The working x-coordinate (so we don't lose the real x
	            // argument)
	const int tabW = FONT_W * 4; // Tab width
	int c; // current character

	// Guard against invalid color values
	if (color < 0) {
		color = 0;
	} else if (color > static_cast<int>(NUM_FONT_COLORS) - 1) {
		color = NUM_FONT_COLORS - 1;
	}
	
	// Loop over each character of text
	for (uint i = 0; i < static_cast<uint>(strlen(text)); i++) {
		// Store the current character
		c = text[i];
		
		// If this is a line-break character
		if (c == '\n') {
			// Move y down, and add a little padding
			y += FONT_H + 2;
			
			// Move x2 back to the original x
			x2 = x;
			
			// Go to the next character
			continue;
		}

		// Tab
                if (c == '\t') {
                        x2 = (tabW * static_cast<int>(x2 / tabW)) + tabW;
                        
                        // Go to next character
                        continue;
                }	

		// Subtract 33 to find the font index number (so that '!'
		// starts at 0)
		c -= 33;

		// If it's a space
		if (c == -1) {
			x2 += FONT_W + spacing;
		} else {
			// Blit a "shadow" character
			ApplySurface(x2 + 2, y + 2, font[c].surf[0],
				screenSurface);
			
			// Blit the correct color version of the character
			ApplySurface(x2, y, font[c].surf[color], screenSurface);
			
			// Advance the x2 position
			x2 += (font[c].w + 2) + spacing;
		}
	}
}
예제 #2
0
파일: Character.cpp 프로젝트: KrysG/Unuk
void Character::Render(void) {
  // Draw some fancy speach bubbles. It is a bit of a mess, I am playing.
  if(_speachBubble.size() != 0) {
    if(_speachBubbleTimer.GetTicks() < SPEACH_BUBBLE_DISPLAY_LENGTH) {
      roundedBoxRGBA(screen, (x + w / 2) - 100,
                     y - 100,
                     (x + w / 2) + 100,
                     y - 35,
                     5, 255, 255, 255, 255);

      filledTrigonRGBA(screen, (x + w / 2) - 100,
                       y - 100,
                       (x + w / 2) - 10,
                       y - 40,
                       (x + w / 2) + 10,
                       y - 40,
                       255, 255, 255, 255);

      _speachBubbleText.Render((x + w / 2) - 90, y - 90);
    }
  }

  if(attacking && attackTimer.GetTicks() < ATTACKING_DISPLAY_LEN) {
    ApplySurface(x, y, _texture, screen, &_sprites[directionFacing][ANIM_ATTACK]);
    return;
  }
  else if(attacking)
    attacking = false;
  
  if(xVel == 0.0f && yVel == 0.0f)
    ApplySurface(x, y, _texture, screen, &_sprites[directionFacing][ANIM_NO_FOOT]);
  else {
    if(_animationTimer.GetTicks() > ANIMATION_SPEED) {
      if(_animationStage == ANIM_NO_FOOT) {
        if(_leftFoot == true)
          _animationStage = ANIM_RIGHT_FOOT;
        else
          _animationStage = ANIM_LEFT_FOOT;
      }
      else if(_animationStage == ANIM_LEFT_FOOT) {
        _animationStage = ANIM_NO_FOOT;
        _leftFoot = true;
      }
      else if(_animationStage == ANIM_RIGHT_FOOT) {
        _animationStage = ANIM_NO_FOOT;
        _leftFoot = false;
      }
      _animationTimer.Start();
    }
    ApplySurface(x, y, _texture, screen, &_sprites[directionFacing][_animationStage]);
  }
}
예제 #3
0
int playerClass::drawObject() {

	// Play animations
	if (collisionDetected) {
		playerAnimHurt->playAnimation();
		if (health == 0) {
			collisionEnabled = false;
		}
	} 
	else if(health == 0) {
		playerDeath();
	} 
	else {
		playerAnimIdle->playAnimation();
	}
	
	// Draw health
	for (int i = 0; i != health; i++) {
		ApplySurface(i * 20, 10, playerHealthIcon);
	}

	// Draw score
	this->displayScore();

	return 0;
}
예제 #4
0
	void LoggerTTF::draw(Surface ecran)
	{
		if(m_buffer.empty() )
			return;
		
		if(SDL_GetTicks() - m_last_message >= 3000)
		{
			m_buffer.erase( m_buffer.begin() );
			
			m_last_message = SDL_GetTicks();
		}
		
		if(m_police)
		{
			SDL_Color noir = {0, 0, 0};
			
			vector<string>::iterator message = m_buffer.begin();
			IRect boite = m_boite_ecriture;
		
			for(; message != m_buffer.end(); message++)
			{
				SDL_Surface *text = TTF_RenderText_Blended(m_police, message->c_str(), noir);
				
				if(text)
				{
					boite.y += text->h;
					boite.h -= text->h;
					
					ApplySurface(text, ecran.getSurface(), IRect(), boite );
				}
			}
		}
	}
예제 #5
0
void LayerControl::DrawScoreBoard(SDL_Surface *screen)
{
    TTF_Font *font = TTF_OpenFont("Verdana.ttf", 24);
    SDL_Color textColor = {COLOR_Score_Board.r, COLOR_Score_Board.g, COLOR_Score_Board.b};

    //
    // Create surfaces.
    //

    SDL_Surface *scoreLabelSurface = TTF_RenderText_Solid(font, "SCORE:", textColor);
    SDL_Surface *levelLabelSurface = TTF_RenderText_Solid(font, "LEVEL:", textColor);

    char bufferScoreValue[100];
	sprintf(bufferScoreValue, "%i", System::GetScore());
    SDL_Surface *scoreValueSurface = TTF_RenderText_Solid(font, bufferScoreValue, textColor);

    char bufferLevelValue[100];
	sprintf(bufferLevelValue, "%i", System::GetGameLevel());
    SDL_Surface *levelValueSurface = TTF_RenderText_Solid(font, bufferLevelValue, textColor);

    //
    // Set static positions.
    //

    const int startY = (CONTROL_PADDING_HEIGHT) + (CONTROL_PREVIEW_SEG * PUZZLE_TILE_SIZE) + 10;
    const int textHeight = scoreLabelSurface->clip_rect.h + CONTROL_ITEM_SPACE;

    //
    // Draw score board items to screen.
    //

    ApplySurface(GetXScoreBoardItem(scoreLabelSurface), startY, scoreLabelSurface, screen);
    ApplySurface(GetXScoreBoardItem(scoreValueSurface), startY + textHeight, scoreValueSurface, screen);
    ApplySurface(GetXScoreBoardItem(levelLabelSurface), startY + (textHeight * 2), levelLabelSurface, screen);
    ApplySurface(GetXScoreBoardItem(levelValueSurface), startY + (textHeight * 3), levelValueSurface, screen);

    //
    // Free SDL items.
    //

    TTF_CloseFont(font);
    SDL_FreeSurface(scoreLabelSurface);
    SDL_FreeSurface(levelLabelSurface);
    SDL_FreeSurface(scoreValueSurface);
    SDL_FreeSurface(levelValueSurface);
}
예제 #6
0
int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        std::cout << SDL_GetError() << std::endl;
        return 1;

    }

    SDL_Window* win = NULL;
    win = SDL_CreateWindow("TTF", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
    if (!win) {
        std::cerr << SDL_GetError() << std::endl;
        return 1;

    }

    SDL_Renderer* ren = NULL;
    ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (!ren) {
        std::cerr << SDL_GetError() << std::endl;
        return 1;

    }

    if (TTF_Init() == -1) {
        std::cerr << TTF_GetError() << std::endl;
        return 2;
    }


    SDL_Texture *image = NULL;
    try {
        SDL_Color color = {255, 1, 90, 100};
        image = RenderText( ren, "TTF fonts are cool!", "/usr/share/fonts/truetype/tlwg/Waree-Oblique.ttf", color, 64);

        } catch (const std::runtime_error& e) {
            std::cout << e.what() << std::endl;
            return 4;
        }


    SDL_RenderClear(ren);
    ApplySurface(10, 10, image, ren);
    SDL_RenderPresent(ren);

    SDL_Delay(20000);


    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);

    SDL_Quit();

    return 0;
}
예제 #7
0
void LayerControl::Draw(SDL_Surface *screen)
{

    if (System::IsGameOver())
    {
        m_startButton.SetLabel("Start");
    }

    //
    // Draw Start/Stop Button.
    //

    m_startButton.Draw(m_startButtonSurface);
    ApplySurface(m_startButton.GetX(), m_startButton.GetY(), m_startButtonSurface, screen);

    //
    // Draw Pause button.
    //

    m_resetButton.Draw(m_resetButtonSurface);
    ApplySurface(m_resetButton.GetX(), m_resetButton.GetY(), m_resetButtonSurface, screen);

    //
    // Draw Exit button.
    //

    m_exitButton.Draw(m_exitButtonSurface);
    ApplySurface(m_exitButton.GetX(), m_exitButton.GetY(), m_exitButtonSurface, screen);

    //
    // Draw preview.
    //

    m_preview.Draw(m_previewSurface);
    ApplySurface(m_preview.GetX(), m_preview.GetY(), m_previewSurface, screen);

    //
    // Draw score.
    //

    DrawScoreBoard(screen);
}
void Texts::DisplayCentered(Screens screen)
{

	//get the dimension of the screen

	SDL_Surface screen2 = *(screen.GetScreen());
	int width = screen2.clip_rect.w;

	//Apply the surface at  the center (x = (width of screen - width of message)/2)

	ApplySurface((width-_box.w)/2,_box.y,_message,screen.GetScreen());
}
Screens::Screens(int screenWidth, int screenHeight, int screenBPP, std::string fileName): _screen(NULL)
{

	//assignment of the attributes
	_screenWidth = screenWidth ;//the width of the screen
	_screenHeight = screenHeight ;//its height
	_screenBPP = screenBPP;//and the number of bytes per point
	_fileName = fileName;//link for the backrgound image
	
	//initialization of the screen
	SDL_Surface* screenBackground =NULL;
	_screen = SDL_SetVideoMode( _screenWidth, _screenHeight, _screenBPP, SDL_SWSURFACE );// we set the window
	SDL_WM_SetCaption( "Multi Armed Bandit", NULL );//we name the window
	screenBackground = LoadImage(fileName);// We load the wallpaper
	ApplySurface(0,0,screenBackground,_screen);//we blit the wallpaper to the window
	SDL_FreeSurface(screenBackground);//Once it's blitted we delete the SDL8surface avoiding memory leak

}
예제 #10
0
void BgScroll(unsigned int speed_time, SDL_Texture* image, SDL_Renderer* renderer)
{
    SDL_Rect pos;
    pos.x = 0;
    pos.y = 0;

    SDL_Rect clip;
    clip.x = speed_time;
    clip.y = 0;
    clip.w = 960 - speed_time;
    clip.h = 720;

    SDL_RenderClear(renderer);

    ApplySurface(pos.x, pos.y, image, renderer, &clip);
    SDL_RenderPresent(renderer);
    SDL_RenderClear(renderer);

}
예제 #11
0
int main(int argc, char *argv[])
{

    InitEnv();
    SDL_Window* win = NULL;
    SDL_Renderer* ren = NULL;
    SDL_Texture* tex = NULL;

    // CreateWindowRendererWrapper(std::ref(win), std::ref(ren));
    win = SDL_CreateWindow("Flappy Bird", 100, 100, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI);
    ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);

    if (win == NULL )
        std::cout << "win == NULL" << std::endl;
    if (ren == NULL)
        std::cout << "ren == NULL" << std::endl;


    SDL_RenderClear(ren);
    tex = LoadImage("./res/bg.png", &ren);
    ApplySurface(0, 0, tex, ren);

    SDL_RenderPresent(ren);

    SDL_Delay(1000);


    BgScroll(100, tex, ren);


    SDL_Delay(2000000);

    SDL_DestroyTexture(tex);
    SDL_DestroyRenderer(ren);
    SDL_DestroyWindow(win);


    SDL_Quit();


    return 0;
}
예제 #12
0
bool Shot::render(SDL_Renderer * rend, const int32_t center_x, const int32_t center_y) const {
	double x = this->end.x - center_x + GameConstants::SCREEN_WIDTH / 2 - GameConstants::FIELD_WIDTH / 2,
		y = this->end.y - center_y + GameConstants::SCREEN_HEIGHT / 2 - GameConstants::FIELD_HEIGHT / 2;

	if (x + GameConstants::FIELD_WIDTH / 2 < 0 || x + GameConstants::FIELD_WIDTH / 2 > GameConstants::SCREEN_WIDTH)
		return false;
	if (y + GameConstants::FIELD_HEIGHT / 2 < 0 || y + GameConstants::FIELD_HEIGHT / 2 > GameConstants::SCREEN_HEIGHT)
		return false;

	SDL_Texture *shot = LoadImage(GameConstants::SHOT_PATH, rend);	//texture of human
	if (shot == nullptr) {
		std::cout << "Invalid Image" << std::endl;
		return false;	//invalid png name
	}
	ApplySurface(static_cast<int32_t>(x), static_cast<int32_t>(y), shot, rend);

	SDL_DestroyTexture(shot);
	shot = nullptr;

	return true;
}
예제 #13
0
void Pause()
{
    bool Resumed = false;
    ApplySurface(0,0,PausedScreen,Screen);
    SDL_Flip(Screen);
    while (Quit == false && Resumed == false && State == GAME)
    {
        SDL_Delay(500);
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_RETURN) {
                Resumed = true;
                SDL_WM_GrabInput( SDL_GRAB_ON );
                SDL_ShowCursor(SDL_DISABLE);
            }
            if(event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) {
                State = MENU;
                Restart = true;
            }
        }
    }
}
예제 #14
0
void ApplySurface(int32_t x, int32_t y, SDL_Texture *tex, SDL_Renderer *rend, const double angle) {
	SDL_Rect pos;
	SDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h);
	ApplySurface(x, y, tex, rend, pos.w, pos.h, angle);
}
예제 #15
0
int main(int argc, char** argv){

	initSDL();
	
	const int SCREEN_FPS = 60;
	const int SCREEN_TICK_PER_FRAME = 1000 / SCREEN_FPS;

	// Resource handler
	DataHandler gameDataHandler;

	// Load assets
	SDL_Texture* title = nullptr;
	title = LoadImage("data\\title.png");
	


	// Game variables
	bool quit = false;
	int gameState = 0;
	
	// Game classes
	rendererClass gameRenderer;
	KeyboardHandler keyboard;
	HighScore highscore;

	// FPS capper
	Timer frameTimer;
	Timer capTimer;
	int countedFrames = 0;

	// Start counting frames since game start
	frameTimer.Start();

	// Notification text object
	std::stringstream notificationText;
	textClass notification;
	notification.x = 180;
	notification.y = 120;

	//Debug
	std::stringstream teksti;
	textClass debugtext;
	debugtext.x = 200;
	debugtext.y = 200;


	// end debug
	Level level1;
	level1.loadLevel("data\\test.dat");

	
	highscore.readHighScoreFile("data\\score.dat");


	while(keyboard.quitPressed == false && quit == false) {	
		
		// Start counting frames since gameloop start
		capTimer.Start();

		// Clear screen
		clearScreen();


		// Check gamestates
		switch (gameState)
		{
			// Title screen
			case 0:
				ApplySurface( 20, 50, title);

				// Check if the user presses Enter to start a game
				if(keyboard.isPressed(SDL_SCANCODE_RETURN)) {
					gameState = 1;
				}
				break;
			// Start new game
			case 1: 
			{
				// Start level
				level1.initLevel();
				
				gameState = 2;
				break;
			}
			// Start game
			case 2:
			{
				
				if (!level1.playLevel(gameRenderer)) {
					if (level1.levelCompleted == true) {
						gameState = 4;
					}
					else {
						gameState = 3;
					}
				}

				break;
			}
			// Death screen
			case 3:

				// Set you are dead text
				notificationText.str("");
				notificationText << "You are dead! Play again? ( Y / N )";
				notification.setMessage(notificationText);
				notification.drawObject();
				highscore.displayHighScore();

				if(keyboard.isPressed(SDL_SCANCODE_Y)) {
					gameState = 1;
				}
				else if (keyboard.isPressed(SDL_SCANCODE_N)) {
					quit = true;
				}

				break;
			// Level1  complete
			case 4:
				notificationText.str("");
				notificationText << "Level complete! Press enter for level 2 ";
				notification.setMessage(notificationText);
				notification.drawObject();

				if(keyboard.isPressed(SDL_SCANCODE_RETURN)) {
					gameState = 5;
				}
				else if (keyboard.isPressed(SDL_SCANCODE_N)) {
					quit = true;
				}
			// Level 2
			case 5:
				break;
			// Level 2 complete
			case 6:
				break;
			// Level 3
			case 7:
				break;
			// Game complete
			case 8:
				break;

			default:
				break;
		}
		
		//Calculate and correct fps
		float avgFPS = countedFrames / ( frameTimer.getTicks() / 1000.f );
		if( avgFPS > 2000000 )
		{
			avgFPS = 0;
		}
		
		// Handle keyboard for player
		keyboard.handleKeyboardEvents(*level1.playerObject, gameRenderer);

		// Draw all the gameObjects
		gameRenderer.drawRenderQueue();

		// Handle game logic
		gameRenderer.handleLogicQueue();
		
		// Update screen
		updateScreen();
		

		// Add a counted frame
		++countedFrames;

		//If frame finished early
		int frameTicks = capTimer.getTicks();
		if( frameTicks < SCREEN_TICK_PER_FRAME )
		{
			//Wait remaining time
			SDL_Delay( SCREEN_TICK_PER_FRAME - frameTicks );
		}

	}

	// Quit SDL
    SDL_Quit();
 
    return 0;
}
void Texts::Display(Screens screen)
{
	ApplySurface(_box.x,_box.y,_message,screen.GetScreen());
}
예제 #17
0
int main(int argc, char** argv){
	//Start up SDL and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1){
		std::cout << SDL_GetError() << std::endl;
		return 1;
	}

	//Setup our window and renderer
	window = SDL_CreateWindow("Lesson 2", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (window == nullptr){
		std::cout << SDL_GetError() << std::endl;
		return 2;
	}
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (renderer == nullptr){
		std::cout << SDL_GetError() << std::endl;
		return 3;
	}

	//The textures we'll be using
	SDL_Texture *background = nullptr, *image = nullptr;
	background = LoadImage("../res/Lesson2/background.bmp");
	image = LoadImage("../res/Lesson2/image.bmp");
	//Make sure it went ok
	if (background == nullptr || image == nullptr)
		return 4;

	//Clear the window
	SDL_RenderClear(renderer);

	//Get the width and height from the texture so we know how much to move x,y by
	//to tile it correctly
	int bW, bH;
	SDL_QueryTexture(background, NULL, NULL, &bW, &bH);
	//We want to tile our background so draw it 4 times
	ApplySurface(0, 0, background, renderer);
	ApplySurface(bW, 0, background, renderer);
	ApplySurface(0, bH, background, renderer);
	ApplySurface(bW, bH, background, renderer);
	//Draw our image in the center of the window
	//We also need its width so query it as well
	int iW, iH;
	SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
	int x = SCREEN_WIDTH / 2 - iW / 2;
	int y = SCREEN_HEIGHT / 2 - iH / 2;
	ApplySurface(x, y, image, renderer);

	//Update the screen
	SDL_RenderPresent(renderer);
	SDL_Delay(2000);

	//Destroy the various items
	SDL_DestroyTexture(background);
	SDL_DestroyTexture(image);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

	SDL_Quit();
	
	return 0;
}
예제 #18
0
파일: Entity.cpp 프로젝트: krej/SDL-Game
void Entity::Draw(SDL_Surface* pDestination) {
    SDL_Rect currentClip = m_asAnimations.GetCurrentClip(m_sCurrentAnimation);

    ApplySurface(m_iX, m_iY, pDestination, &currentClip);
}
예제 #19
0
char LoadFont(const char *file) {
	char fullPath[strlen(DATA_PATH) + strlen(FONT_PATH) + strlen(file) + 1];
	sprintf(fullPath, "%s%s%s", DATA_PATH, FONT_PATH, file);
	#ifdef DEBUG
		printf("Font path = %s\n", fullPath);
	#endif
	
	// The surface holding the big long list of characters
	SDL_Surface *fontSurf = FillSurface(fullPath, 0);
	if (fontSurf == NULL) {
		return 1;
	}
	
	// For holding the rgb values for pre-rendering differently-colored
	// letters
	SDL_Color palette[256];
	uint r, g, b;
	
	// For finding the left and right side of each character (to determine
	// width)
	int leftSide;
	int rightSide;
	
	uint i = 0;
	uint transColor = SDL_MapRGB(fontSurf->format, 0xff, 0x00, 0xff);
	int sourceOffset = 0;
	for (int y = 0; y < fontSurf->h; y += FONT_H) {
		// Lock the surface (for subsequent GetPixel calls)
		SDL_LockSurface(fontSurf);
				
		/*** Determine the letter's width ***/
		// Find left side
		leftSide = -1;
		for (int x2 = 0; x2 < FONT_W; x2++) {
			for (int y2 = y; y2 < y + FONT_H; y2++) {
				if (GetPixel(fontSurf, x2, y2) != transColor) {
					leftSide = x2;
					break;
				}
			}
			if (leftSide != -1) break;
		}
		
		// Find right side
		rightSide = -1;
		for (int x2 = FONT_W - 1; x2 > 0; x2--) {
			for (int y2 = y; y2 < y + FONT_H; y2++) {
				if (GetPixel(fontSurf, x2, y2) != transColor) {
					rightSide = x2;
					break;
				}
			}
			if (rightSide != -1) break;
		}
		font[i].w = (rightSide - leftSide) + 1;
		
		SDL_UnlockSurface(fontSurf);
		
		// Blit this character and pre-render different color versions
		// of it
		for (uint j = 0; j < NUM_FONT_COLORS; j++) {
			// Prepare a surface for this color of the character
			font[i].surf[j] = MakeSurface(FONT_W, FONT_H);
			
			// Blit the temporary fontSurf onto this letter's
			// surface
			ApplySurface(-leftSide, sourceOffset, fontSurf,
			             font[i].surf[j]);
			
			// Get the rgb values for this color
			switch (j) {
				case 0: // Shadow
					r = 0;
					g = 0;
					b = 0;
					break;
				case 1: // Normal text
					r = 220;
					g = 220;
					b = 220;
					break;
				case 2: // Highlighted text
					r = 251;
					g = 177;
					b = 17;
					break;
				case 3: // Title
					r = 255;
					g = 255;
					b = 255;
			}
			
			// Set the palette of the surface
			for (uint k = 0; k < 256; k++) {
				palette[k].r = static_cast<Uint8>(r);
				palette[k].g = static_cast<Uint8>(g);
				palette[k].b = static_cast<Uint8>(b);
			}
			
			// Change the palette of the surface
			SDL_SetPalette(font[i].surf[j], SDL_LOGPAL, palette, 0,
			               256);
		}
		
		i++;
		if (i > FONT_ARRAY_SIZE - 1) break;
		
		sourceOffset -= FONT_H; // Move the big tall bmp up
	}
	
	SDL_FreeSurface(fontSurf);

	return 0;
}
예제 #20
0
void ParticleEmitter::Render(void) {
  for(int i = 0; i < _particleCount; i++) {
    ApplySurface(m_particle[i].x, m_particle[i].y, _particleTexture, screen);
  }
}
예제 #21
0
void Gui::SetArm(const char* text)
{	
	//Initialize a surface used to hide a part of the screen wich is used later
	SDL_Surface* hide = NULL;
	hide=LoadImage("Images/hide.png");

	//The variables that the window is going to get

	double mean =0;//the mean of the arm
	double variance =0;//its variance
	char armType ='A';//its type

	//Initializing the texts
	Texts arm(0,150,_font,text,_textColor);	
	Texts instructions(0,250,_font2,"Choose a type of arm then click in the boxes and type the parameters",_textColor);
	//Initializing the buttons

	//Ok button to skip to the next window
	Buttons ok(361,500, "Images/ok1.png", "Images/ok2.png","Images/ok3.png");

	//Type zones for the mean and the variance
	TypeZone meanT(300,400,_font2,"Mean",_textColor);	
	TypeZone varianceT(600,400,_font2,"Variance",_textColor);
	

	//Radiobuttons to choose the type of arm (exponential, uniform real, uniform int, poisson, logNormal)
	RadioButtons exp(100,300,"Exponential",_font2,_textColor);
	RadioButtons unifr(exp.GetBox().x+exp.GetBox().w+20,300,"Uniform real",_font2,_textColor);
	RadioButtons unifi(unifr.GetBox().x+unifr.GetBox().w+20,300,"Uniform int",_font2,_textColor);
	RadioButtons poisson(unifi.GetBox().x+unifi.GetBox().w+20,300,"Poisson",_font2,_textColor);
	RadioButtons logNormal(poisson.GetBox().x+poisson.GetBox().w+20,300,"Log-normal",_font2,_textColor);

	//Calculate the x for centering them (width of the screen minus the sum the width of the buttons)

	int xCentered = ((*(_screen.GetScreen())).clip_rect.w-exp.GetBox().w-unifr.GetBox().w-unifi.GetBox().w-poisson.GetBox().w-logNormal.GetBox().w-80)/2;

	//Relocate the buttons

	exp.SetPosition(xCentered,exp.GetBox().y);
	unifr.SetPosition(exp.GetBox().x+exp.GetBox().w+20,unifr.GetBox().y);
	unifi.SetPosition(unifr.GetBox().x+unifr.GetBox().w+20,unifi.GetBox().y);
	poisson.SetPosition(unifi.GetBox().x+unifi.GetBox().w+20,poisson.GetBox().y);
	logNormal.SetPosition(poisson.GetBox().x+poisson.GetBox().w+20,logNormal.GetBox().y);

	//Display them all

	arm.DisplayCentered(_screen);
	instructions.DisplayCentered(_screen);
	//meanT.Display(_screen);

	
	
	ok.Show(_screen);
	exp.Show(_screen);
	unifr.Show(_screen);
	unifi.Show(_screen);
	poisson.Show(_screen);
	logNormal.Show(_screen);

	
	meanT.DisplayLeft(_screen,mean,_font2,_textColor);
	varianceT.DisplayRight(_screen,mean,_font2,_textColor);
	
	
	
		//Initialize the event structure
	SDL_Event event;

	//Initialization of the loop
	bool isChoiceCorrect= false;
	bool skip=false;
	while((skip==false)&&(_quit==false))
	{	//While there's an event to handle
		while( SDL_PollEvent( &event ) )
			{	
				//the buttons react to the user's actions 
				ok.HandleEvents(event);
				exp.HandleEvents(event);
				unifr.HandleEvents(event);
				unifi.HandleEvents(event);
				poisson.HandleEvents(event);
				logNormal.HandleEvents(event);

				meanT.HandleEvents(event,mean);
				
				
				//For some button we just need the mean to set the distribution so in this case we hide the variance
				if((exp.IsActive()==false)&&(poisson.IsActive()==false))
				{				
				varianceT.HandleEvents(event,variance);
				
				}
				//we check if one option was chosen
				isChoiceCorrect = (exp.IsActive()|| unifr.IsActive()||unifi.IsActive()||poisson.IsActive()||logNormal.IsActive());

				//If the user clicks on ok and made a choice 
				if((ok.HandleEvents(event)==false)&&(isChoiceCorrect))
				{
					//skip to the next window
				skip=true;
				}

				//If he clicks on ok and hasn't made a choice then change color of the text
				if((ok.HandleEvents(event)==false)&&(isChoiceCorrect==false))
				{
					SDL_Color red={240,0,0};
					exp.SetColor(red);
					unifr.SetColor(red);
					unifi.SetColor(red);
					poisson.SetColor(red);
					logNormal.SetColor(red);
				}
				
				//If the user has Xed out the window
				if( event.type == SDL_QUIT )
					{
					//Quit the program
					_quit = true;
					}
			}

	    //Display all
	    ok.Show(_screen);
		exp.Show(_screen);
		unifr.Show(_screen);
		unifi.Show(_screen);
		poisson.Show(_screen);
		logNormal.Show(_screen);
	
		meanT.DisplayLeft(_screen,mean, _font2,_textColor);
		
		
		//For some button we just need the mean to set the distribution so in this case we hide the variance
		if((exp.IsActive()==false)&&(poisson.IsActive()==false))
			{
			 varianceT.DisplayRight(_screen,variance, _font2,_textColor);	
			 
			}
		else
			{
			 ApplySurface(400,398,hide,_screen.GetScreen());
			}

		_screen.Display();
	}
	
	_screen.Clean("Images/background.png");

	//Then we save the parameters in the Gui's attributes

	//First we get the type of arm:
	if(exp.IsActive()){armType='A';}
	if(unifr.IsActive()){armType='B';}
	if(unifi.IsActive()){armType='C';}
	if(poisson.IsActive()){armType='D';}
	if(logNormal.IsActive()){armType='E';}

	std::vector<double> parameter;
	
	//Then acoording to the type of arms we calculate the parameters required
	switch(armType)
		{
		case 'A'://Exponential: we need the lambda

			_choices.push_back('A');//we save the type in _choices 

			
			parameter.push_back(1.0/(mean*1.0));
			_parameters.push_back(parameter);//and the parameters calculated using the mean and the variance in _parameters

			break;
		case 'B'://uniform real on [a,b]  we need a and b

			_choices.push_back('B');

			
			parameter.push_back((2.0*mean-sqrt(12.0*variance))/2.0);
			parameter.push_back((2.0*mean+sqrt(12.0*variance))/2.0);
			_parameters.push_back(parameter);
			break;


		case 'C':

			_choices.push_back('C');//uniform integer on [a,b] we need a and b

			
			parameter.push_back((2.0*mean -sqrt(12.0*variance+1.0)+1)/2.0);
			parameter.push_back((2.0*mean+sqrt(12.0*variance+1)-1)/2.0);
			_parameters.push_back(parameter);
			break;


		case 'D': //poisson we just need the mu wich equal to the mean

			_choices.push_back('D');

			
			parameter.push_back(mean);
			_parameters.push_back(parameter);
			break;

		default:

			_choices.push_back('E'); //log-normal we need mu and sigma square

			
			parameter.push_back(log(mean*1.0)-0.5*log(1.0+((variance*1.0)/(mean*mean*1.0))));
			parameter.push_back((2.0*mean+sqrt(12.0*variance+1.0)-1.0)/2.0);
			_parameters.push_back(parameter);
			break;		

		}


}
void Buttons::Show(Screens screen) const
{
 //Show the button 
 ApplySurface( _box.x, _box.y, _activeImage , screen.GetScreen() );
}
예제 #23
0
int main(int argc, char** argv){
	//Start up SDL and make sure it went ok
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1){
		std::cout << SDL_GetError() << std::endl;
		return 1;
	}

	//Setup our window and renderer
	window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED, 
		SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
	if (window == nullptr){
		std::cout << SDL_GetError() << std::endl;
		return 2;
	}
	renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED 
		| SDL_RENDERER_PRESENTVSYNC);
	if (renderer == nullptr){
		std::cout << SDL_GetError() << std::endl;
		return 3;
	}
	
	SDL_Texture *image = nullptr;
	try {
		image = LoadImage("../res/Lesson5/image.png");
	}
	catch (const std::runtime_error &e){
		std::cout << e.what() << std::endl;
		return 4;
	}
	//Setup image positioning
	int iW = 100, iH = 100;
	int x = SCREEN_WIDTH / 2 - iW / 2;
	int y = SCREEN_HEIGHT / 2 - iH / 2;
	//Setup the clips
	//iW and iH are the desired clip width and height
	SDL_Rect clips[4];
	//We use a for loop this time to setup our clips
	int column = 0;
	for (int i = 0; i < 4; ++i){
		if (i != 0 && i % 2 == 0)
			++column;
		
		clips[i].x = column * iW;
		clips[i].y = i % 2 * iH;
		clips[i].w = iW;
		clips[i].h = iH;
	}
	//Specify a default clip to start with
	int useClip = 0;

	//Our event type
	SDL_Event e;
	//For tracking if we want to quit
	bool quit = false;
	while (!quit){
		//Event Polling
		while (SDL_PollEvent(&e)){
			//If user closes he window
			if (e.type == SDL_QUIT)
				quit = true;
			//If user presses any key
			if (e.type == SDL_KEYDOWN){
				switch (e.key.keysym.sym){
					case SDLK_1:
						useClip = 0;
						break;
					case SDLK_2:
						useClip = 1;
						break;
					case SDLK_3:
						useClip = 2;
						break;
					case SDLK_4:
						useClip = 3;
						break;
					//For quitting, escape key
					case SDLK_ESCAPE:
						quit = true;
						break;
					default:
						break;
				}
			}
		}
		//Rendering
		SDL_RenderClear(renderer);
		//Draw the image
		ApplySurface(x, y, image, renderer, &clips[useClip]);

		//Update the screen
		SDL_RenderPresent(renderer);
	}

	//Destroy the various items
	SDL_DestroyTexture(image);
	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);

	SDL_Quit();

	return 0;
}
void RadioButtons::Show(Screens screen)
{
	//We display the text and the button itself
	ApplySurface(_box.x,_box.y,_activeImage,screen.GetScreen());
	_text.Display(screen);
}
예제 #25
0
int main(int argc, char** argv) {
    //Start up SDL and make sure it went ok
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }
    if (TTF_Init() == -1) {
        std::cout << TTF_GetError() << std::endl;
        return 2;
    }

    //Setup our window and renderer
    window = SDL_CreateWindow("Lesson 6", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (window == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 2;
    }
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED
                                  | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 3;
    }

    //The textures we'll be using
    SDL_Texture *image = nullptr;
    try {
        SDL_Color color = { 255, 255, 255 };
        image = RenderText("TTF fonts are cool!", "../res/Lesson6/SourceSansPro-Regular.ttf", color, 64);
    }
    catch (const std::runtime_error &e) {
        std::cout << e.what() << std::endl;
        return 4;
    }
    //Our texture size won't change, so we can get it here
    //instead of constantly allocating/deleting ints in the loop
    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = SCREEN_WIDTH / 2 - iW / 2;
    int y = SCREEN_HEIGHT / 2 - iH / 2;

    //Our event type
    SDL_Event e;

    //For tracking if we want to quit
    bool quit = false;
    while (!quit) {
        //Event Polling
        while (SDL_PollEvent(&e)) {
            //If user closes he window
            if (e.type == SDL_QUIT)
                quit = true;
            //If user presses any key
            if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)
                quit = true;
        }
        //Rendering
        SDL_RenderClear(renderer);
        //Draw the image
        ApplySurface(x, y, image, renderer);

        //Update the screen
        SDL_RenderPresent(renderer);
    }

    //Destroy the various items
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}
void Screens::Clean(std::string fileName)
{	SDL_Surface* screenBackground =NULL;
	screenBackground = LoadImage(fileName);// We load the wallpaper
	ApplySurface(0,0,screenBackground,_screen);//we blit the wallpaper to the window the other objects are then covered
	SDL_FreeSurface(screenBackground);
}