分类: LINUX
2006-05-26 11:01:50
精灵动画程序:
以下是编程步骤:
1。初始化SDL,创建窗口
2。载入精灵动画。设置显示模式。设置透明色键值。
3。载入背景图片。进入游戏循环。
4。检测事件,用SDL_GetKeyState()取得当前的键盘状态。
注:这个函数返一个指向用来描述键盘数据的数组的指针。如果某个键
被按下。则对应的数组值设为1。否则为0
5。检测数组的对应键值。并进行相应的移动
6。检测移动是否超出窗口。进行相应处理。
7。显示背景
8。显示精灵
9。用SDL_FreeSurface释放内存,用SDL_Quit()释放SDL
SDL教程--移动精灵
代码:
#include "SDL.h"
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#define SPRITE_SIZE 32
int main ( int argc, char *argv[] )
{
SDL_Surface *screen, *temp, *sprite, *grass;
SDL_Rect rcSprite, rcGrass;
SDL_Event event;
Uint8 *keystate;
int colorkey, gameover;
/* initialize SDL */
SDL_Init(SDL_INIT_VIDEO);
/* set the title bar */
SDL_WM_SetCaption("SDL Move", "SDL Move");
/* create window */
SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH,
SCREEN_HEIGHT, 0, 0);
/* load sprite */
temp = SDL_LoadBMP("sprite.bmp");
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
/* setup sprite colorkey and turn on RLE */
colorkey = SDL_MapRGB(screen->format, 255, 0, 255);
SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey);
/* load grass */
temp = SDL_LoadBMP("grass.bmp");
grass = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
/* set sprite position */
rcSprite.x = 0;
rcSprite.y = 0;
gameover = 0;
/* message pump */
while (!gameover)
{
/* look for an event */
if (SDL_PollEvent(&event)) {
/* an event was found */
switch (event.type) {
/* close button clicked */
case SDL_QUIT:
gameover = 1;
break;
/* handle the keyboard */
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
case SDLK_q:
gameover = 1;
break;
}
break;
}
}
/* handle sprite movement */
keystate = SDL_GetKeyState(NULL);
if (keystate[SDLK_LEFT] ) {
rcSprite.x -= 2;
}
if (keystate[SDLK_RIGHT] ) {
rcSprite.x += 2;
}
if (keystate[SDLK_UP] ) {
rcSprite.y -= 2;
}
if (keystate[SDLK_DOWN] ) {
rcSprite.y += 2;
}
/* collide with edges of screen */
if ( rcSprite.x < 0 ) {
rcSprite.x = 0;
}
else if ( rcSprite.x > SCREEN_WIDTH-SPRITE_SIZE ) {
rcSprite.x = SCREEN_WIDTH-SPRITE_SIZE;
}
if ( rcSprite.y < 0 ) {
rcSprite.y = 0;
}
else if ( rcSprite.y > SCREEN_HEIGHT-SPRITE_SIZE ) {
rcSprite.y = SCREEN_HEIGHT-SPRITE_SIZE;
}
/* draw the grass */
for (int x = 0; x < SCREEN_WIDTH / SPRITE_SIZE; x++) {
for (int y = 0; y < SCREEN_HEIGHT / SPRITE_SIZE; y++) {
rcGrass.x = x * SPRITE_SIZE;
rcGrass.y = y * SPRITE_SIZE;
SDL_BlitSurface(grass, NULL, screen, &rcGrass);
}
}
/* draw the sprite */
SDL_BlitSurface(sprite, NULL, screen, &rcSprite);
/* update the screen */
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
/* clean up */
SDL_FreeSurface(sprite);
SDL_FreeSurface(grass);
SDL_Quit();
return 0;
}