I want to write an small article about game programming, of course using
sdl. I need some revision to the following code and some opinion. Can it
be smaller or more compact? Can it be smaller or more compact or clear
in Direct X? And other libs? The code is not finished yet, but any
optimization is welcome.
#include <stdio.h>
#include <stdlib.h>
#include “SDL.h”
#define UP 1
#define RIGTH 2
#define DOWN 3
#define LEFT 4
SDL_Surface *sp, *screen, *back;
void loadimg()
{
SDL_Surface *tmp;
//Load background from a bitmap
tmp=SDL_LoadBMP(“backg.bmp”);
back=SDL_DisplayFormat(tmp);
//SDL_BlitSurface(back, NULL, screen, NULL);
//now load the image to move
SDL_UpdateRect(screen,0,0,0,0);
tmp=SDL_LoadBMP(“sail.bmp”);
/* Set transparent pixel as the pixel at (0,0) */
if ( tmp->format->palette ) {
SDL_SetColorKey(tmp, (SDL_SRCCOLORKEY|SDL_RLEACCEL),
*(Uint8 *)tmp->pixels);
}
// Convert image to display format
sp = SDL_DisplayFormat(tmp);
SDL_FreeSurface(tmp);
}
int main(int argc, char *argv[])
{
SDL_Rect area;
SDL_Event event;
int direc; //direccion
int end;
/* Inicializar SDL */
if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
//Si falla, mostrar el mensaje de error y abortar
fprintf(stderr, “No se puede inicializar SDL: %s\n”,SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
if ((screen=SDL_SetVideoMode(640,480,24,SDL_SWSURFACE)) == NULL ) {
fprintf(stderr, “Couldn’t set 640x480 video mode: %s\n”,SDL_GetError());
exit(2);
}
//Activar repeticion de teclas
SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,SDL_DEFAULT_REPEAT_INTERVAL);
//Cargamos la imagen
loadimg();
end=0;
direc=0;
area.x=310;
area.y=400;
//Lazo principal
while (end!=1) {
if (SDL_PollEvent(&event)>0) {
//hay un evento pendiente
if (event.type==SDL_KEYDOWN) {
// fue presionada una tecla
//SDL_BlitSurface(saved, NULL, screen, &area);
//Ver que tecla fue
switch ((int)event.key.keysym.sym) {
case SDLK_LEFT:
direc=LEFT;
break;
case SDLK_RIGHT:
direc=RIGTH;
break;
case SDLK_UP:
direc=UP;
break;
case SDLK_DOWN:
direc=DOWN;
break;
case SDLK_ESCAPE:
//nos vamos
end=1;
break;
}
} else if (event.type==SDL_MOUSEBUTTONDOWN)
//set stop flag
end=1;
} //if EventPoll
//Ahora movemos la imagen de acuerdo a la direccion
switch (direc){
case UP:
if (area.y>1) area.y–;
break;
case RIGTH:
if (area.x<640) area.x++;
break;
case DOWN:
if (area.y<480) area.y++;
break;
case LEFT:
if (area.x>1) area.x–;
break;
}
SDL_BlitSurface(back, NULL, screen, NULL);
SDL_BlitSurface(sp, NULL, screen, &area);
if ((screen->flags & SDL_DOUBLEBUF) != SDL_DOUBLEBUF) SDL_UpdateRect(screen,0,0,0,0);
else SDL_Flip(screen);
}
return(0);
}–
Roger D. Vargas | El sistema se apagara en 5 segundos.
ICQ: 117641572 | Salvese el que pueda!
Linux User: 180787 |