School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,140 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,750 people online right now. Registration is fast and FREE... Join Now!




Beginning SDL - Part 2 - The Basic Framework

 
Reply to this topicStart new topic

> Beginning SDL - Part 2 - The Basic Framework

stayscrisp
Group Icon



post 17 Jun, 2009 - 01:48 AM
Post #1


Hi, this is the second part of my beginning SDL tutorials, in this tutorial we will create a basic framework for our games. The start of this tutorial is more conceptual than core SDL so it can be used in any of your games using C++ no matter which library you are using.

Ok so lets begin, first we will create our Game class, this will contain some of the functions for our game.

Game.h
CODE

#ifndef  _GAME_H_
#define _GAME_H_

#include <SDL.h>

class Game
{
       public:
            
              Game();
              
              void Init();

       private:
              
               bool m_bRunning
};

#endif


Quite basic to start with, we create our constructor and the Initialize function, this will be the first call for the program.

Next lets write our Game.cpp file

CODE

#include "Game.h"

// constructor
Game::Game()
{
}

void Game::Init()
{
     m_bRunning = true;
}


This will be the class that most of our game will run through, so lets write our main.cpp and test it out

CODE

#include "Game.h"

int main(int argc, char* argv[])
{
     Game game;
      
      game.Init();
}


Ok that should compile now, it won't do anything at the moment but should compile with no errors.

So that the hub of our game where we will call all of the functions needed to keep the game running, if you recall from the last tutorial I covered the functions needed for a main game loop these were:
CODE

Initialize
// while the game is running
Handle Events
Update
Draw
// once the game is done
Clean


we will incorporate the basic framework of these functions now, open up the Game.h file and add the functions.

CODE

#ifndef  _GAME_H_
#define _GAME_H_

#include <SDL.h>

class Game
{
       public:
            
              Game();
              
              bool Init();
              
              void HandleEvents();
              
              void Update();
              
              void Draw();

              void Clean();

        private:
              
              bool  m_bRunning;
};

#endif



Ok now lets go to our Game.cpp file and create the function body's

CODE

#include "Game.h"

// constructor
Game::Game()
{
  
}

void Game::Init()
{
    m_bRunning = true;
}

void Game::HandleEvents()
{
}

void Game::Update()
{
}

void Game::Draw()
{
}

void Game::Clean()
{
}


That is the main framework of our game created, Init will load anything we need such as NPC's, player files, map files or sound files. Handle Events will check for key-presses and handle them accordingly. Update will do any movement and time based features and Draw will draw everything to the screen. These functions will be called in a constant loop when the game is running.

Lets write our main.cpp to incorporate these functions

CODE

#include "Game.h"

int main(int argc, char* argv[])
{
    Game game;
    
    game.Init();
    
    while(game.Running())
    {
        game.HandleEvents();
        game.Update();
        game.Draw();
    }
    
    // cleanup the engine
    game.Clean();
    
    return 0;
}


Ok so now we have the framework down, we can now add some SDL code to create a window once we initialize our game. First we have to think about what we need to do when creating an SDL window, we need to know the height and width of the screen, bpp and whether the window is fullscreen or not.

Re-open the Game.h file and we will incorporate this code, I won't paste the entire file again only the part's we are working on.

CODE


// change our init function to incorporate the parameters we will need
public:
void Init(const char* title, int width, int height,
                  int bpp, bool fullscreen);

// add a pointer to an SDL surface for our screen and also a bool for fullscreen
private:

SDL_Surface* screen;
bool m_bFullscreen;



now open up the Game.cpp file so we can write the body of this function

CODE

void Game::Init(const char* title, int width, int height,
                int bpp, bool fullscreen)
{
    int flags = 0;
    
    // initialize SDL
    SDL_Init(SDL_INIT_EVERYTHING);
    
    // set the title bar text
    SDL_WM_SetCaption(title, title);
    
    if ( fullscreen ) {
        flags = SDL_FULLSCREEN;
    }
    
    // create the screen surface
    screen = SDL_SetVideoMode(width, height, bpp, flags);
    
    m_bFullscreen = fullscreen;
    
    m_bRunning = true;

        // print our success
    printf("Game Initialised Succesfully\n");
}


Now the program creates a window using SDL according to our parameters so lets update our main.cpp to incorporate this revised function

CODE

#include "Game.h"

int main(int argc, char* argv[])
{
    Game game;
    
    game.Init("test",640,480,32,false);
    
    while(game.Running())
    {
        game.HandleEvents();
        game.Update();
        game.Draw();
    }
    
    // cleanup the engine
    game.Clean();
    
    return 0;
}


That should compile fine but there is one problem we have no way to exit the program, you will most likely have to force it to close using CTRL+ALT+DELETE or ForceQuit. Lets write a way to close this window using SDL so that we can quit it easier.

Open up the Game.h file and we need to update our handle events function, we need to pass in a pointer to our current game.

CODE

void HandleEvents(Game* game);


now open up the Game.cpp file and we will add some way of handling events so we can use the SDL_QUIT event. An SDL_QUIT event is when you click the cross button on an SDL window, we earlier wrote a quit function that simply sets our m_bRunning bool to false, this in turn stops the game loop and our Clean function is called. So lets write a way to handle this event

CODE

void Game::HandleEvents(Game* game)
{
    SDL_Event event;
    
    if (SDL_PollEvent(&event)) {
        switch (event.type) {
            case SDL_QUIT:
                game->Quit();
                break;
                
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym) {
                    case SDLK_ESCAPE:
                        game->Quit();
                }
                break;
        }
    }
    
}


There we go, I also added a way to quit using the escape key, this is useful while building and debugging but make sure to remove it once you are finished.

Ok then back to the main.cpp file for a small update.

CODE

#include "Game.h"

int main(int argc, char* argv[])
{
    Game game;
    
    game.Init("test",640,480,32,false);
    
    while(game.Running())
    {
        game.HandleEvents(&game);
        game.Update();
        game.Draw();
    }
    
    // cleanup the engine
    game.Clean();
    
    return 0;
}


We update the handle events function and pass in our game.

To recap we create a basic framework for our games incorporating the main game loop, we created a way to create a window according to our needs by passing in values needed to our init function and we created a way for SDL to handle events, one of which is our quit function which is called via escape key or by clicking the cross on and SDL window.

Thanks for reading, in part 3 I am hoping to incorporate a state manager or a sprite class any requests?

Happy coding and of course any questions will be answered icon_up.gif




Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

J3d1
*



post 26 Jun, 2009 - 03:34 PM
Post #2
Very good articles, many thanks to the author! I will wait for continuation smile.gif
Go to the top of the page
+Quote Post

stayscrisp
Group Icon



post 18 Aug, 2009 - 03:15 AM
Post #3
One little thing to add to this tutorial that was pointed out to me by BlackPhoenix, I have not wrote the function for Game::Running, this function returns the variable bool m_bRunning;

so here it is, its very small so just chuck it into the Game.h file

CODE

bool Running() {return m_bRunning;}


Thanks smile.gif
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 03:29PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month