2016年1月13日 星期三

SDL- Step2 鍵盤按鍵控制方塊的移動


#include<stdlib.h>
#include<SDL/SDL.h>
int main(int argc,char** argv)
{
   SDL_Init(SDL_INIT_EVERYTHING);
   SDL_Surface *screen;
   screen=SDL_SetVideoMode(300,300,32,SDL_SWSURFACE);
   bool running=true;

   Uint32 start;
   bool b[4]={0,0,0,0};
   SDL_Rect rect;
   rect.x=145;
   rect.y=145;
   rect.w=10;
   rect.h=10;
   Uint32 color=SDL_MapRGB(screen->format,0,0,0);
   Uint32 color2=SDL_MapRGB(screen->format,0xff,0xff,0xff);
   while(running)
   {
        start = SDL_GetTicks();
        SDL_Event event;
        while(SDL_PollEvent(&event))
        {
switch(event.type)
             {
                    case SDL_QUIT:
                         running=false;
                         break;
                    case SDL_KEYDOWN:
                         switch(event.key.keysym.sym)
                         {
                                case SDLK_UP:
                                    b[0]=1;
                                    break;
                                case SDLK_LEFT:
                                    b[1]=1;
                                    break;
                                case SDLK_DOWN:
                                    b[2]=1;
                                    break;
                                case SDLK_RIGHT:
                                    b[3]=1;
                                    break;

                          }
                          break;
                     case SDL_KEYUP:
                          switch(event.key.keysym.sym)
                          {
                                 case SDLK_UP:
                                     b[0]=0;
                                     break;
                                 case SDLK_LEFT:
                                     b[1]=0;
                                     break;
                                 case SDLK_DOWN:
                                     b[2]=0;
                                     break;
                                 case SDLK_RIGHT:
                                     b[3]=0;
                                     break;
                          }
                          break;
             }

        }
        //logic
        if(b[0])
          rect.y-=10;
        if(b[1])
          rect.x-=10;
        if(b[2])
          rect.y+=10;
        if(b[3])
          rect.x+=10;


        if( rect.y<0)
                rect.y=0;
        if(rect.y>290)
                rect.y=290;
        if(rect.x<0)
                rect.x=0;
        if(rect.x>290)
                rect.x=290;
        //render
         SDL_FillRect(screen,&screen->clip_rect,color);
         SDL_FillRect(screen,&rect,color2);
         SDL_Flip(screen);
   SDL_Delay(50);
   }
 SDL_Quit();
 return 0;

}

編譯指令 : g++ XXX.c -o LLL -lSDL

沒有留言:

張貼留言