Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) SDL example 1: moving colors

 

This SDL example shows colors moving, like this screenshot (png).

 

Operating system: Ubuntu

IDE: Qt Creator 2.0.0

Project type: Qt4 Console Application

Selected required modules: QtCore

Compiler: G++ 4.4.1

Additional libraries: SDL

 

 

 

 

 

 

Qt project file

 

#-------------------------------------------------
#
# Project created by QtCreator 2010-07-17T14:57:33
#
#-------------------------------------------------

QT += core

QT -= gui

TARGET = CppSdlExample1
CONFIG += console
CONFIG -= app_bundle

TEMPLATE = app

LIBS += -L/usr/local/lib -lSDL
SOURCES += main.cpp

 

 

 

 

 

Source code

 

#include <cassert>
#include <cstdlib>
#include <iostream>
#include <SDL/SDL.h>

//Adapted from http://www.libsdl.org/intro.en/usingvideo.html
int main()
{
  if ( SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) < 0 )
  {
    std::cerr << "Unable to initialize SDL: " << SDL_GetError() << '\n';
    return 1;
  }
  std::atexit(SDL_Quit);

  const int width = 256; //640;
  const int height = 256; //480;
  SDL_Surface * const screen = SDL_SetVideoMode(width,height, 16, SDL_SWSURFACE);
  if (!screen)
  {
    std::cerr << "Unable to initialize screen: " << SDL_GetError() << '\n';
    return 1;
  }

  Uint16 * const pixels = reinterpret_cast<Uint16*>(screen->pixels);
  const Uint16 pitch = screen->pitch;
  const SDL_PixelFormat * const pixel_format = screen->format;

  int z = 0;

  while (1)
  {
    //Draw pixels
    for (int y=0;y!=height;++y)
    {
      for (int x=0;x!=width;++x)
      {
        *(pixels + y*pitch/2 + x) = SDL_MapRGB(pixel_format, z+x, z+y, z+x+y);
      }
    }
    //Redraw screen
    SDL_UpdateRect(screen, 0, 0, width, height);
    //Wait for user to close window
    SDL_Event event;
    SDL_PollEvent(&event);
    if (event.type == SDL_QUIT) exit(0);
    ++z;
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict