Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SDL.h>
- #include <SDL_image.h>
- #include <stdio.h>
- #include <string>
- #include <iostream>
- using namespace std;
- //The dimensions of the level
- const int LEVEL_WIDTH = 1280;
- const int LEVEL_HEIGHT = 960;
- //Screen dimension constants
- const int SCREEN_WIDTH = 1200;
- const int SCREEN_HEIGHT = 600;
- //Button constants
- const int BUTTON_WIDTH = 300;
- const int BUTTON_HEIGHT = 100;
- const int TOTAL_BUTTONS = 4;
- enum LButtonSprite
- {
- BUTTON_SPRITE_MOUSE_OUT = 0,
- BUTTON_SPRITE_MOUSE_OVER_MOTION = 1,
- BUTTON_SPRITE_MOUSE_DOWN = 2,
- BUTTON_SPRITE_MOUSE_UP = 3,
- BUTTON_SPRITE_TOTAL = 4
- };
- //The mouse button
- class LButton
- {
- public:
- //Initializes internal variables
- LButton();
- //Sets position
- void setPosition(int x, int y);
- void setNumber(int x);
- //Handles mouse event
- void handleEvent(SDL_Event* e);
- //Shows button sprite
- void render();
- private:
- //Top left position
- SDL_Point mPosition;
- //Currently used global sprite
- LButtonSprite mCurrentSprite;
- };
- //Texture wrapper class
- class LTexture
- {
- public:
- //Initializes variables
- LTexture();
- //Deallocates memory
- ~LTexture();
- //Loads image at specified path
- bool loadFromFile(std::string path);
- #ifdef _SDL_TTF_H
- //Creates image from font string
- bool loadFromRenderedText(std::string textureText, SDL_Color textColor);
- #endif
- //Deallocates texture
- void free();
- //Set color modulation
- void setColor(Uint8 red, Uint8 green, Uint8 blue);
- //Set blending
- void setBlendMode(SDL_BlendMode blending);
- //Set alpha modulation
- void setAlpha(Uint8 alpha);
- //Renders texture at given point
- void render(int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE);
- //Gets image dimensions
- int getWidth();
- int getHeight();
- private:
- //The actual hardware texture
- SDL_Texture* mTexture;
- //Image dimensions
- int mWidth;
- int mHeight;
- };
- //The dot that will move around on the screen
- class Dot
- {
- public:
- //The dimensions of the dot
- static const int DOT_WIDTH = 20;
- static const int DOT_HEIGHT = 20;
- //Maximum axis velocity of the dot
- static const int DOT_VEL = 10;
- //Initializes the variables
- Dot();
- //Takes key presses and adjusts the dot's velocity
- void handleEvent(SDL_Event& e);
- //Moves the dot
- void move();
- //Shows the dot on the screen relative to the camera
- void render(int camX, int camY);
- //Position accessors
- int getPosX();
- int getPosY();
- private:
- //The X and Y offsets of the dot
- int mPosX, mPosY;
- //The velocity of the dot
- int mVelX, mVelY;
- };
- bool init();
- //Loads media
- bool loadMedia();
- //Frees media and shuts down SDL
- void close();
- //The window we'll be rendering to
- SDL_Window* gWindow = NULL;
- //The window renderer
- SDL_Renderer* gRenderer = NULL;
- //Mouse button sprites
- SDL_Rect gSpriteClips[BUTTON_SPRITE_TOTAL];
- LTexture gButtonSpriteSheetTexture;
- //MOUSE BUTTON objects
- LButton gButtons[TOTAL_BUTTONS];
- //Scene textures
- LTexture gDotTexture;
- LTexture gBGTexture;
- LTexture::LTexture()
- {
- //Initialize
- mTexture = NULL;
- mWidth = 0;
- mHeight = 0;
- }
- LTexture::~LTexture()
- {
- //Deallocate
- free();
- }
- bool LTexture::loadFromFile(std::string path)
- {
- //Get rid of preexisting texture
- free();
- //The final texture
- SDL_Texture* newTexture = NULL;
- //Load image at specified path
- SDL_Surface* loadedSurface = IMG_Load(path.c_str());
- if (loadedSurface == NULL)
- {
- printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
- }
- else
- {
- //Color key image
- SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0, 0xFF, 0xFF));
- //Create texture from surface pixels
- newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
- if (newTexture == NULL)
- {
- printf("Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
- }
- else
- {
- //Get image dimensions
- mWidth = loadedSurface->w;
- mHeight = loadedSurface->h;
- }
- //Get rid of old loaded surface
- SDL_FreeSurface(loadedSurface);
- }
- //Return success
- mTexture = newTexture;
- return mTexture != NULL;
- }
- //we dont use this
- #ifdef _SDL_TTF_H
- bool LTexture::loadFromRenderedText(std::string textureText, SDL_Color textColor)
- {
- //Get rid of preexisting texture
- free();
- //Render text surface
- SDL_Surface* textSurface = TTF_RenderText_Solid(gFont, textureText.c_str(), textColor);
- if (textSurface != NULL)
- {
- //Create texture from surface pixels
- mTexture = SDL_CreateTextureFromSurface(gRenderer, textSurface);
- if (mTexture == NULL)
- {
- printf("Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError());
- }
- else
- {
- //Get image dimensions
- mWidth = textSurface->w;
- mHeight = textSurface->h;
- }
- //Get rid of old surface
- SDL_FreeSurface(textSurface);
- }
- else
- {
- printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
- }
- //Return success
- return mTexture != NULL;
- }
- #endif
- void LTexture::free()
- {
- //Free texture if it exists
- if (mTexture != NULL)
- {
- SDL_DestroyTexture(mTexture);
- mTexture = NULL;
- mWidth = 0;
- mHeight = 0;
- }
- }
- void LTexture::setColor(Uint8 red, Uint8 green, Uint8 blue)
- {
- //Modulate texture rgb
- SDL_SetTextureColorMod(mTexture, red, green, blue);
- }
- void LTexture::setBlendMode(SDL_BlendMode blending)
- {
- //Set blending function
- SDL_SetTextureBlendMode(mTexture, blending);
- }
- void LTexture::setAlpha(Uint8 alpha)
- {
- //Modulate texture alpha
- SDL_SetTextureAlphaMod(mTexture, alpha);
- }
- void LTexture::render(int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip)
- {
- //Set rendering space and render to screen
- SDL_Rect renderQuad = { x, y, mWidth, mHeight };
- //Set clip rendering dimensions
- if (clip != NULL)
- {
- renderQuad.w = clip->w;
- renderQuad.h = clip->h;
- }
- //Render to screen
- SDL_RenderCopyEx(gRenderer, mTexture, clip, &renderQuad, angle, center, flip);
- }
- int LTexture::getWidth()
- {
- return mWidth;
- }
- int LTexture::getHeight()
- {
- return mHeight;
- }
- Dot::Dot()
- {
- //Initialize the offsets
- mPosY = SCREEN_HEIGHT/2;
- mPosX = SCREEN_WIDTH/2;
- //Initialize the velocity
- mVelX = 0;
- mVelY = 0;
- }
- void Dot::handleEvent(SDL_Event& e)
- {
- //If a key was pressed
- if (e.type == SDL_KEYDOWN && e.key.repeat == 0)
- {
- //Adjust the velocity
- switch (e.key.keysym.sym)
- {
- case SDLK_UP: mVelY -= DOT_VEL; break;
- case SDLK_DOWN: mVelY += DOT_VEL; break;
- case SDLK_LEFT: mVelX -= DOT_VEL; break;
- case SDLK_RIGHT: mVelX += DOT_VEL; break;
- }
- }
- //If a key was released
- else if (e.type == SDL_KEYUP && e.key.repeat == 0)
- {
- //Adjust the velocity
- switch (e.key.keysym.sym)
- {
- case SDLK_UP: mVelY += DOT_VEL; break;
- case SDLK_DOWN: mVelY -= DOT_VEL; break;
- case SDLK_LEFT: mVelX += DOT_VEL; break;
- case SDLK_RIGHT: mVelX -= DOT_VEL; break;
- }
- }
- }
- void Dot::move()
- {
- //Move the dot left or right
- mPosX += mVelX;
- //If the dot went too far to the left or right
- if ((mPosX < 0) || (mPosX + DOT_WIDTH > LEVEL_WIDTH))
- {
- //Move back
- mPosX -= mVelX;
- }
- //Move the dot up or down
- mPosY += mVelY;
- //If the dot went too far up or down
- if ((mPosY < 0) || (mPosY + DOT_HEIGHT > LEVEL_HEIGHT))
- {
- //Move back
- mPosY -= mVelY;
- }
- }
- void Dot::render(int camX, int camY)
- {
- //Show the dot relative to the camera
- gDotTexture.render(mPosX - camX, mPosY - camY);
- }
- int Dot::getPosX()
- {
- return mPosX;
- }
- int Dot::getPosY()
- {
- return mPosY;
- }
- LButton::LButton()
- {
- mPosition.x = 0;
- mPosition.y = SCREEN_HEIGHT - BUTTON_HEIGHT;
- mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT;
- }
- void LButton::setPosition(int x, int y)
- {
- mPosition.x = x;
- mPosition.y = y;
- }
- void LButton::handleEvent(SDL_Event* e)
- {
- //If mouse event happened
- if (e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP)
- {
- //Get mouse position
- int x, y;
- int bNumber;
- SDL_GetMouseState(&x, &y);
- //Check if mouse is in button
- bool inside = true;
- //Mouse is left of the button
- if (x < mPosition.x)
- {
- inside = false;
- }
- //Mouse is right of the button
- else if (x > mPosition.x + BUTTON_WIDTH)
- {
- inside = false;
- }
- //Mouse above the button
- else if (y < mPosition.y)
- {
- inside = false;
- }
- //Mouse below the button
- else if (y > mPosition.y + BUTTON_HEIGHT)
- {
- inside = false;
- }
- //Mouse is outside button
- if (!inside)
- {
- mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT;
- }
- //Mouse is inside button
- else
- {
- //Set mouse over sprite
- switch (e->type)
- {
- case SDL_MOUSEMOTION:
- mCurrentSprite = BUTTON_SPRITE_MOUSE_OVER_MOTION;
- break;
- case SDL_MOUSEBUTTONDOWN:
- mCurrentSprite = BUTTON_SPRITE_MOUSE_DOWN;
- //call function
- //what button did we push
- if (x < BUTTON_WIDTH) {
- cout << "first button!!" << endl;
- }
- else if (x < (BUTTON_WIDTH * 2)) {
- cout << "second button!!" << endl;
- }
- else if (x < (BUTTON_WIDTH * 3)) {
- cout << "third button!!" << endl;
- }
- else if (x < (BUTTON_WIDTH * 4)) {
- cout << "fourth button!!" << endl;
- }
- case SDL_MOUSEBUTTONUP:
- mCurrentSprite = BUTTON_SPRITE_MOUSE_UP;
- break;
- }
- }
- }
- }
- void LButton::setNumber(int x){
- for (int i = 0; i < TOTAL_BUTTONS; ++i) {
- }
- }
- void LButton::render()
- {
- //Show current button sprite
- gButtonSpriteSheetTexture.render(mPosition.x, mPosition.y, &gSpriteClips[mCurrentSprite]);
- }
- bool init()
- {
- //Initialization flag
- bool success = true;
- //Initialize SDL
- if (SDL_Init(SDL_INIT_VIDEO) < 0)
- {
- printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
- success = false;
- }
- else
- {
- //Set texture filtering to linear
- if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
- {
- printf("Warning: Linear texture filtering not enabled!");
- }
- //Create window
- gWindow = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
- if (gWindow == NULL)
- {
- printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
- success = false;
- }
- else
- {
- //Create vsynced renderer for window
- gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
- if (gRenderer == NULL)
- {
- printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
- success = false;
- }
- else
- {
- //Initialize renderer color
- SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
- //Initialize PNG loading
- int imgFlags = IMG_INIT_PNG;
- if (!(IMG_Init(imgFlags) & imgFlags))
- {
- printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
- success = false;
- }
- }
- }
- }
- return success;
- }
- bool loadMedia()
- {
- //Loading success flag
- bool success = true;
- //Load dot texture
- if (!gDotTexture.loadFromFile("30_scrolling/dot.bmp"))
- {
- printf("Failed to load dot texture!\n");
- success = false;
- }
- //Load background texture
- if (!gBGTexture.loadFromFile("30_scrolling/bg.png"))
- {
- printf("Failed to load background texture!\n");
- success = false;
- }
- if (!gButtonSpriteSheetTexture.loadFromFile("30_scrolling/button.png"))
- {
- printf("Failed to load button button sprite texture!\n");
- success = false;
- }
- else
- {
- //Set sprites
- for (int i = 0; i < BUTTON_SPRITE_TOTAL; ++i)
- {
- gSpriteClips[i].x = 0;
- gSpriteClips[i].y = i * 200;
- gSpriteClips[i].w = BUTTON_WIDTH;
- gSpriteClips[i].h = BUTTON_HEIGHT;
- }
- //Set buttons
- for (int i = 0; i < BUTTON_SPRITE_TOTAL; ++i)
- {
- gButtons[i].setPosition(0, SCREEN_HEIGHT - BUTTON_HEIGHT);
- gButtons[i].setPosition(i * BUTTON_WIDTH, SCREEN_HEIGHT - BUTTON_HEIGHT);
- gButtons[i].setPosition(i * BUTTON_WIDTH, SCREEN_HEIGHT - BUTTON_HEIGHT);
- gButtons[i].setPosition(i * BUTTON_WIDTH, SCREEN_HEIGHT - BUTTON_HEIGHT);
- }
- }
- return success;
- }
- void close()
- {
- //Free loaded images
- gDotTexture.free();
- gBGTexture.free();
- gButtonSpriteSheetTexture.free();
- //Destroy window
- SDL_DestroyRenderer(gRenderer);
- SDL_DestroyWindow(gWindow);
- gWindow = NULL;
- gRenderer = NULL;
- //Quit SDL subsystems
- IMG_Quit();
- SDL_Quit();
- }
- int main(int argc, char* args[])
- {
- //Start up SDL and create window
- if (!init())
- {
- printf("Failed to initialize!\n");
- }
- else
- {
- //Load media
- if (!loadMedia())
- {
- printf("Failed to load media!\n");
- }
- else
- {
- //Main loop flag
- bool quit = false;
- //Event handler
- SDL_Event e;
- //The dot that will be moving around on the screen
- Dot dot;
- //The camera area
- SDL_Rect camera = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
- //While application is running
- while (!quit)
- {
- //Handle events on queue
- while (SDL_PollEvent(&e) != 0)
- {
- //User requests quit
- if (e.type == SDL_QUIT)
- {
- quit = true;
- }
- //Handle button events
- for (int i = 0; i < TOTAL_BUTTONS; ++i)
- {
- gButtons[i].handleEvent(&e);
- }
- if (e.type == SDL_MOUSEBUTTONDOWN) {
- cout << "this is inside the main function" << endl;
- SDL_Rect fillRect = { SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 };
- SDL_SetRenderDrawColor(gRenderer, 0xFF, 0x00, 0x00, 0xFF);
- SDL_RenderFillRect(gRenderer, &fillRect);
- //Update screen
- SDL_RenderPresent(gRenderer);
- }
- //Handle input for the dot
- dot.handleEvent(e);
- }
- //Move the dot
- dot.move();
- //Center the camera over the dot
- camera.x = (dot.getPosX() + Dot::DOT_WIDTH / 2) - SCREEN_WIDTH / 2;
- camera.y = (dot.getPosY() + Dot::DOT_HEIGHT / 2) - SCREEN_HEIGHT / 2;
- //Keep the camera in bounds
- if (camera.x < 0)
- {
- camera.x = 0;
- }
- if (camera.y < 0)
- {
- camera.y = 0;
- }
- if (camera.x > LEVEL_WIDTH - camera.w)
- {
- camera.x = LEVEL_WIDTH - camera.w;
- }
- if (camera.y > LEVEL_HEIGHT - camera.h)
- {
- camera.y = LEVEL_HEIGHT - camera.h;
- }
- //Clear screen
- SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
- SDL_RenderClear(gRenderer);
- //Render background
- gBGTexture.render(0, 0, &camera);
- //Render objects
- dot.render(camera.x, camera.y);
- //Render buttons
- for (int i = 0; i < TOTAL_BUTTONS; ++i)
- {
- gButtons[i].render();
- }
- //Update screen
- SDL_RenderPresent(gRenderer);
- }
- }
- }
- //Free resources and close SDL
- close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment