Simple SDL example in C++

This is a simple SDL example. It plots a bunch of random points to the screen. On linux it will require the libsdl and libsdl-dev packages. compile it as follows:

g++ -L/usr/lib -lSDL -lpthread rand_points.c -o rand_points

#include
#include
#include

using namespace std;

int main(int argc, char *argv[]) {

SDL_Surface *screen;

if(SDL_Init(SDL_INIT_VIDEO)<0) { cout << "Failed SDL_Init " << SDL_GetError() << endl; return 1; } screen=SDL_SetVideoMode(800,600,32,SDL_ANYFORMAT); if(screen==NULL) { cout << "Failed SDL_SetVideoMode: " << SDL_GetError() << endl; SDL_Quit(); return 1; } for(;;) { SDL_Flip(screen); SDL_LockSurface(screen); for(int n=0;n<1000;n++) { int x=rand()%800; int y=rand()%600; int pixel=rand()*100000; int bpp = screen->format->BytesPerPixel;
Uint8 *p = (Uint8 *)screen->pixels + y * screen->pitch + x * bpp;
if((x>screen->w)||(y>screen->h)||(x<0)||(y<0)) return 0; *(Uint32 *)p = pixel; } SDL_Event event; while(SDL_PollEvent(&event)) { if(event.key.keysym.sym == SDLK_c ) { SDL_FillRect(screen,NULL,0); } } SDL_UnlockSurface(screen); } SDL_Quit(); return 0; } [/sourcecode]

  • Hi there, thanks a lot giving this example, it worked flawlessly which made me change my mind about learning SDL since I was hesitating… Here we go, any comprehensive book suggestions please ?

    just before typing the message I got great surprise reading you comment on your entropy contribution…. I’d say:” no matter what efforts are put there to try to locally reduce entropy generation, there will be increasing entropy outside that box we created to cool down our little planet, no matter what this universe is gonna melt down that’s the evolution arrow, now way to stop it, only one thing matters the work/entropy ratio how much useful work you accomplish while generating that amount of entropy?” you’re a good man thanks for this sweet sdl example,

  • new299

    Thanks! I’m glad it was useful. Keep fighting that entropy gradient! 🙂

  • Robert Stephens

    I made an equivalent for SDL2:

    http://pastebin.com/TRb6Ph1V