#include <cassert>
#include <cstdlib>
#include <SDL/SDL.h>
int main()
{
//Start SDL
if (SDL_Init( SDL_INIT_EVERYTHING ) < 0)
{
assert(!"Should not get here. Initialization failed");
}
//Call SDL_Quit upon exit
std::atexit(SDL_Quit);
//Load background
SDL_Surface * const background = SDL_LoadBMP( "Background.bmp");
assert(background && "Assume background image is found in same folder as binary");
assert(background->w > 100);
assert(background->h > 100);
//Set up screen, same size as background
SDL_Surface * const screen = SDL_SetVideoMode(background->w,background->h, 32, SDL_SWSURFACE );
assert(screen && "Assume screen can be initialized");
//Load sprite
SDL_Surface * const sprite = SDL_LoadBMP("Butterfly.bmp");
SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL,SDL_MapRGB(sprite->format,0,255,0));
assert(sprite && "Assume sprite image is found in same folder as binary");
//Create a sprite rect, same dimensions as sprite image
SDL_Rect sprite_rect;
sprite_rect.x = 0;
sprite_rect.y = 0;
sprite_rect.h = sprite->h;
sprite_rect.w = sprite->w;
int dx = 1; //Horizontal speed
int dy = 1; //Vertical speed
//Blit background to screen
SDL_BlitSurface( background, 0, screen, 0);
while (1)
{
//Remove-blit image from screen
SDL_BlitSurface( background, &sprite_rect, screen, &sprite_rect);
//Move sprite
sprite_rect.x+=dx;
sprite_rect.y+=dy;
//Make sprite bounce
if (sprite_rect.x < 0) dx=-dx;
if (sprite_rect.x + sprite_rect.w > screen->w) dx=-dx;
if (sprite_rect.y < 0) dy=-dy;
if (sprite_rect.y + sprite_rect.h > screen->h) dy=-dy;
//Blit image to screen
SDL_BlitSurface( sprite, 0, screen, &sprite_rect);
//Update screen
SDL_Flip( screen );
//Wait for user to close window
SDL_Event event;
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) break;
}
//Free the loaded image
SDL_FreeSurface( background );
}
|