Dev c++ & Sdl 同步学2
加载并显示图片
今天我们要做的很简单,就是绘制一个好看的背景,然后绘制一个方块在上面,你能使用
键盘来移动方块。
定义三个表面,和一个坐标
SDL_Surface *
back;
SDL_Surface *
image;
SDL_Surface *
screen;
int
xpos=
0
,
ypos=
0
;
然后用下面的函数将图片加载到表面上
int
InitImages()
{
back =
SDL_LoadBMP(
"bg.bmp"
);
image =
SDL_LoadBMP(
"image.bmp"
);
return
0
;
}
接下来2
个函数将图片位拷贝到表面上:
int
SDL_BlitSurface(
SDL_Surface *
src,
SDL_Rect *
srcrect,
SDL_Surface *
dst,
SDL_Rect *
dstrect);
参数1
,原位图,参数2
,原位图矩形,参数3
,目标位图,参数4
,目标矩形
下面这个函数是我们创建的第一个DrawIMG
,忽略了参数4
,以及参数2
的width
和height
。
void
DrawIMG(
SDL_Surface *
img,
int
x,
int
y)
{
SDL_Rect dest;
dest.
x =
x;
dest.
y =
y;
SDL_BlitSurface(
img,
NULL,
screen,
&
dest);
}
第 2 个 drawing 函数
void
DrawIMG(
SDL_Surface *
img,
int
x,
int
y,
int
w,
int
h,
int
x2,
int
y2)
{
SDL_Rect dest;
dest.
x =
x;
dest.
y =
y;
SDL_Rect dest2;
dest2.x =
x2;
dest2.y =
y2;
dest2.w =
w;
dest2.h =
h;
SDL_BlitSurface(
img,
&
dest2,
screen,
&
dest);
}
接下来看这个绘制屏幕的主函数
void
DrawScene()
{
DrawIMG(
back,
xpos-
2
,
ypos-
2
,
132
,
132
,
xpos-
2
,
ypos-
2
);
DrawIMG(
image,
xpos,
ypos);
SDL_Flip(
screen);
}
剩下要做的的就在main
函数里面了,我们设置了一个uint8
的指针变量,
int main ( int argc**,** char * argv**[])**
{
Uint8* keys**;**
// 标准的初始化
if ( SDL_Init**(** SDL_INIT_AUDIO| SDL_INIT_VIDEO**)** < 0 )
{
printf**(** "Unable to init SDL: %s\n" , SDL_GetError**());**
exit**(** 1 );
}
atexit**(** SDL_Quit**);**
screen= SDL_SetVideoMode**(** 640 , 480**,** 32 , SDL_HWSURFACE| SDL_DOUBLEBUF**);**
if ( screen == NULL )
{
printf**(** "Unable to set 640x480 video: %s\n" , SDL_GetError**());**
exit**(** 1 );
}
InitImages**();**
DrawBG**();**
// 开始主循环,检测退出以及escape 按键.
int done= 0 ;
while ( done == 0 )
{
SDL_Event event**;**
while ( SDL_PollEvent**(** & event**)** )
{
if ( event**.** type == SDL_QUIT ) { done = 1 ; }
if ( event**.** type == SDL_KEYDOWN )
{
if ( event**.** key**.** keysym**.** sym == SDLK_ESCAPE ) { done = 1 ; }
}
}
然后我们调用SDL_GetKeyState(
NULL)
得到当下的按键状态,我们之所以没有在
游戏的主循环检测方向键,是因为没有在主循环中,只有按键被按下的时候才发生,而不知道目前是否依然处于按下状态。
keys =
SDL_GetKeyState(
NULL);
if
(
keys[
SDLK_UP]
)
{
ypos -=
1
;
}
if
(
keys[
SDLK_DOWN]
)
{
ypos +=
1
;
}
if
(
keys[
SDLK_LEFT]
)
{
xpos -=
1
;
}
if
(
keys[
SDLK_RIGHT]
)
{
xpos +=
1
;
}
// 然后我们绘制主屏幕
DrawScene**();**
}
// 最后退出
return 0 ;
}