Pong

SDL Entwurf editieren

In diesem Teil des Tutorials befassen wir uns damit, den SDL Entwurf, den wir als Ausgangscode bekommen, zu editieren.

Zuerst einmal wird aus der Funktion alles gelöscht, was wir noch nicht brauchen. main.cpp

int main ( int argc, char** argv )
{
    // initialize SDL video
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        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
    SDL_Surface* screen = SDL_SetVideoMode( 640, 480, 16,
                                           SDL_HWSURFACE | SDL_DOUBLEBUF );
    if( !screen )
    {
        printf( "Unable to set 640x480 video: %s\n", SDL_GetError() );
        return 1;
    }
 
    // program main loop
    bool done = false;
    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;
 
            } // end switch
        } // end of message processing
 
        // DRAWING STARTS HERE
 
        // DRAWING ENDS HERE
 
        // finally, update the screen :)
        SDL_Flip(screen);
    } // end main loop
 
    // all is well ;)
    printf("Exited cleanly\n");
    return 0;
}

All zuviel ist nicht geflogen, aber gleich wird sich der Code etwas verändern. Zurzeit haben wir eine Bildschirmhöhe von 640×480. Es wäre aber eventuell komfortabler die Auflösung vorher zu definieren. Also erstellen wir zurerst einmal eine „pong.h“. Der Inhalt wird sich vorerst auf folgendes Beschränken:

#ifndef PONG_H_INCLUDED
#define PONG_H_INCLUDED
 
// screen settings
#define SCREEN_WIDTH 800 // default: 800
#define SCREEN_HEIGHT 600 // default: 600
 
#endif // PONG_H_INCLUDED

Nun wird folgendes in der main.cpp editiert: Im Preprozessorabschnitt:

#ifdef __cplusplus
    #include <cstdlib>
 
    #include "pong.h"
#else
    #error A C++ Compiler is required for OOP!
#endif
 
#ifdef __APPLE__
  #include <SDL/SDL.h>
#else
  #include <SDL.h>
#endif

In der main:

    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 16,
                                           SDL_HWSURFACE | SDL_DOUBLEBUF );
    if ( !screen )
    {
        printf( "Unable to set %dx%d video: %s\n", SCREEN_WIDTH, SCREEN_HEIGHT, SDL_GetError() );
        return 1;
    }

Nun, da wir den Bildschirm mit SDL initialisiert haben müssen wir uns Gedanken machen, wie wir die Bilder auf den Bildschirm bekommen. Wir werden das ganze über Klassen machen. Das ganze wird hier genauer erklärt.