• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
baosalman

[SDL] Window instantly closes

4 posts in this topic

Hello everyone. I'm trying to learn SDL and I wrote some code in dev-C++. Everything is fine when I have only the background image but when I try to make a new class which is called Player and try to put a ninja on the screen, it doesn't work. The compiler doesn't give any errors but the window opens up and instantly closes. Ill put my code here.
 
--system.h--
 

#include "SDL/SDL.h"

class System

{

      private:

              int screenWidth, screenHeight;

              bool fullscreen;

              SDL_Surface *buffer;

      public:

             System(){

                 screenWidth=1024;

                 screenHeight=768;

                 }

             System(int W,int H){

                 screenWidth=W;

                 screenHeight=H;

                 }

             

             void Setup();

             SDL_Surface *Screen();

};

 

void System::Setup()

{

     // Initialization

    SDL_Init(SDL_INIT_EVERYTHING);

    // Set window caption

    SDL_WM_SetCaption("BAO SO PRO",NULL);

    bool fullscreen=false;

    

    if (fullscreen==true)

    {

         buffer=SDL_SetVideoMode(screenWidth,screenHeight,32,SDL_SWSURFACE | SDL_FULLSCREEN);

    }

    else

         buffer=SDL_SetVideoMode(screenWidth,screenHeight,32,SDL_SWSURFACE);

}



SDL_Surface * System::Screen()

{

     return buffer;

}

 
 
--player.h--
 
#include "SDL/SDL.h"

class Player {

      private:

              int locx;

              int locy;

              SDL_Surface *playerimage;

      public:

              Player(){

                  locx=0;

                  locy=0;

                  playerimage=NULL;

                  }

              Player(int x,int y){

                  locx=x;

                  locy=y;

                  playerimage=NULL;

                  }

              SDL_Surface *getsurface();

              int getlocx();

              int getlocy();

              void getInput();

              void draw(SDL_Surface *);

              void load(char *);

};

 

int Player::getlocx()

{

    return locx;

}

int Player::getlocy()

{

    return locy;

}

void Player::getInput()

{

    

}

void Player::draw(SDL_Surface *screen)

{

     SDL_Rect *dest;

     dest->x=getlocx();

     dest->y=getlocy();     

     SDL_BlitSurface(playerimage, NULL, screen, NULL);

     delete dest;

}



void Player::load(char *filename)

{

     playerimage=SDL_LoadBMP(filename);

     Uint32 colorkey=SDL_MapRGB(image->format,255,0,255);

     SDL_SetColorKey(image,SDL_SRCCOLORKEY,colorkey);

}



SDL_Surface *Player::getsurface()

{

    return playerimage;

}

 
--main.cpp--
 
#include <iostream>

#include "SDL/SDL.h"

#include "system.h"

#include "player.h"

using namespace std;



int main(int argc, char* args[])

{

    System sys(1024,768);

    sys.Setup();



// Load the image

    Player hero(250,400);

    hero.load("ninja1.bmp");

    SDL_Surface* image;    

    image = SDL_LoadBMP("background.bmp");

 



 



 

 // Main loop

    SDL_Event event;

    while(event.type!=SDL_QUIT)

    {

        // Check for messages

        SDL_PollEvent(&event);

        // Game loop will go here...

        // Apply the image to the display

        

        SDL_BlitSurface(image, NULL, sys.Screen(), NULL);

        hero.draw(sys.Screen());

        

        //Update the display

        SDL_Flip(sys.Screen());



    }



    // Tell the SDL to clean up and shut down

    //SDL_FreeSurface(hero.getsurface());

    SDL_FreeSurface(sys.Screen());

    SDL_Quit();

    

    return 0;    

}


 
Sorry for the long code. I hope someone can help me! If you comment out every hero code, then the program works whereas it pastes the background on the window.
 
Thanks again! Edited by baosalman
0

Share this post


Link to post
Share on other sites

Please use the editor tools, or manually type [[size="1"][/size]code] and [/[size="1"][/size]code] tags, to insert your code. As you will see in my post, it creates a nice, colour formatted text field.

 

You have no error checking or handling in your SDL calls. Most SDL calls can return an error, ones that return a pointer may return NULL and most other ones return a negative integer when a problem occurs. At the very least, when SDL returns an error you should log or display the error message returned by SDL_GetError().

 

That said, you are accessing an uninitialised pointer in Player::draw. Consider the following instead:

void Player::draw(SDL_Surface *screen)

{

     SDL_Rect dest = {};

     dest.x = getlocx();

     des.y = getlocy();     

     SDL_BlitSurface(playerimage, NULL, screen, &dest);

}
0

Share this post


Link to post
Share on other sites

Thanks for the hint and the reply! I'll try it right now.

 

Well it didn't work sad.png

 

 

EDIT: Ok I've changed my while loop in the main function. I said while(1) instead of while(event.type!=SDL_QUIT).  Can anyone explain me why this works now?

 

EDIT: Alrighty I've fixed my code! Thanks again.

Edited by baosalman
0

Share this post


Link to post
Share on other sites

So has your original code been updated to include the check for SDL_QUIT? As far as I'm aware, while(1) should run the loop continuously.

 

Where you say it works if you comment out the player code is probably due to accessing the non-initialised pointer that rip-off raised. Deleting it without being initially set with 'new' or NULL will probably have an unexpected effect also.

 

Stitchs.

0

Share this post


Link to post
Share on other sites

In the code you posted, you never initialised "event". You then access a member in the loop condition, which is undefined behaviour. Undefined behaviour is C++ lawyer speak for "anything can happen". Here, anything can include:

  • Your program crashes at a point conveniently close to the problematic code
  • Your program writes to arbitrary memory:
    • Crashing sometime later...
    • Continues on with bizarre behaviour (all enemies now have 999 health)
  • Your program appears to work as you intended:
    • Until you try to demo it to your boss/spouse/friend
    • Until someone tries it on a different computer
    • For the time being...
  • ...
  • Ghosts escaping from your computer

Undefined behaviour is often not diagnosed at compile time - that is even if your code compiles cleanly with full errors and warnings, that does not mean that it is correct. Most debug runtimes will try their best to help you detect some types of undefined behaviour, however the very fact that the runtime itself changes how it works in debug versus release mode can sometimes hide such problems.

So, uh, we were talking about your code.

A common fix would be to have the game loop controlled by a boolean variable, and when a SDL_QUIT event is received ensure that the variable becomes false:

bool running = true;
while(running)
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        if(event.type == SDL_QUIT)
        {
            running = false;
        }
        else
        {
            // ...
        }
    }
     // ...
}

It may appear that we are still accessing "event" when it is not initialised. However, when SDL_PollEvent() returns true, it will have written some value to event.type. We only access event.type when SDL_PollEvent is true, thus we are not relying on undefined behaviour.

This is one example of why it is so difficult for compilers to help, this extremely common C idiom means that what appears to be a pointer to uninitialised memory is passed into a function which is designed to initialise it, meaning that most compilers will not implement a warning, let alone an error, for such code.

Edited by rip-off
editor eating my code formatting
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0