guideinputkeyboard.html 17.4 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
<HTML
><HEAD
><TITLE
>Handling the Keyboard</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.76b+
"><LINK
REL="HOME"
TITLE="SDL Library Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Input handling"
HREF="guideinput.html"><LINK
REL="PREVIOUS"
TITLE="Input handling"
HREF="guideinput.html"><LINK
REL="NEXT"
TITLE="Examples"
HREF="guideexamples.html"></HEAD
><BODY
CLASS="SECT1"
BGCOLOR="#FFF8DC"
TEXT="#000000"
LINK="#0000ee"
VLINK="#551a8b"
ALINK="#ff0000"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
>SDL Library Documentation</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="guideinput.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
>Chapter 3. Input handling</TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="guideexamples.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="GUIDEINPUTKEYBOARD"
></A
>Handling the Keyboard</H1
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN271"
></A
>Keyboard Related Structures</H2
><P
>It should make it a lot easier to understand this tutorial is you are familiar with the data types involved in keyboard access, so I'll explain them first.</P
><DIV
CLASS="SECT3"
><H3
CLASS="SECT3"
><A
NAME="AEN274"
></A
>SDLKey</H3
><P
><SPAN
CLASS="STRUCTNAME"
>SDLKey</SPAN
> is an enumerated type defined in SDL/include/SDL_keysym.h and detailed <A
HREF="sdlkey.html"
>here</A
>. Each <SPAN
CLASS="STRUCTNAME"
>SDLKey</SPAN
> symbol represents a key, <TT
CLASS="LITERAL"
>SDLK_a</TT
> corresponds to the 'a' key on a keyboard, <TT
CLASS="LITERAL"
>SDLK_SPACE</TT
> corresponds to the space bar, and so on.</P
></DIV
><DIV
CLASS="SECT3"
><H3
CLASS="SECT3"
><A
NAME="AEN282"
></A
>SDLMod</H3
><P
>SDLMod is an enumerated type, similar to <SPAN
CLASS="STRUCTNAME"
>SDLKey</SPAN
>, however it enumerates keyboard modifiers (Control, Alt, Shift). The full list of modifier symbols is <A
HREF="sdlkey.html#SDLMOD"
>here</A
>. <SPAN
CLASS="STRUCTNAME"
>SDLMod</SPAN
> values can be AND'd together to represent several modifiers.</P
></DIV
><DIV
CLASS="SECT3"
><H3
CLASS="SECT3"
><A
NAME="AEN288"
></A
>SDL_keysym</H3
><PRE
CLASS="PROGRAMLISTING"
>typedef struct{
  Uint8 scancode;
  SDLKey sym;
  SDLMod mod;
  Uint16 unicode;
} SDL_keysym;</PRE
><P
>The <SPAN
CLASS="STRUCTNAME"
>SDL_keysym</SPAN
> structure describes a key press or a key release. The <TT
CLASS="STRUCTFIELD"
><I
>scancode</I
></TT
> field is hardware specific and should be ignored unless you know what your doing. The <TT
CLASS="STRUCTFIELD"
><I
>sym</I
></TT
> field is the <SPAN
CLASS="STRUCTNAME"
>SDLKey</SPAN
> value of the key being pressed or released. The <TT
CLASS="STRUCTFIELD"
><I
>mod</I
></TT
> field describes the state of the keyboard modifiers at the time the key press or release occurred. So a value of <TT
CLASS="LITERAL"
>KMOD_NUM | KMOD_CAPS | KMOD_LSHIFT</TT
> would mean that Numlock, Capslock and the left shift key were all press (or enabled in the case of the lock keys). Finally, the <TT
CLASS="STRUCTFIELD"
><I
>unicode</I
></TT
> field stores the 16-bit unicode value of the key.</P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>It should be noted and understood that this field is only valid when the <SPAN
CLASS="STRUCTNAME"
>SDL_keysym</SPAN
> is describing a key press, not a key release. Unicode values only make sense on a key press because the unicode value describes an international character and only key presses produce characters. More information on Unicode can be found at <A
HREF="http://www.unicode.org"
TARGET="_top"
>www.unicode.org</A
></P
></BLOCKQUOTE
></DIV
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>Unicode translation must be enabled using the <A
HREF="sdlenableunicode.html"
><TT
CLASS="FUNCTION"
>SDL_EnableUNICODE</TT
></A
> function.</P
></BLOCKQUOTE
></DIV
></DIV
><DIV
CLASS="SECT3"
><H3
CLASS="SECT3"
><A
NAME="AEN307"
></A
>SDL_KeyboardEvent</H3
><PRE
CLASS="PROGRAMLISTING"
>typedef struct{
  Uint8 type;
  Uint8 state;
  SDL_keysym keysym;
} SDL_KeyboardEvent;</PRE
><P
>The <SPAN
CLASS="STRUCTNAME"
>SDL_KeyboardEvent</SPAN
> describes a keyboard event (obviously). The <TT
CLASS="STRUCTFIELD"
><I
>key</I
></TT
> member of the <A
HREF="sdlevent.html"
><SPAN
CLASS="STRUCTNAME"
>SDL_Event</SPAN
></A
> union is a <SPAN
CLASS="STRUCTNAME"
>SDL_KeyboardEvent</SPAN
> structure. The <TT
CLASS="STRUCTFIELD"
><I
>type</I
></TT
> field specifies whether the event is a key release (<TT
CLASS="LITERAL"
>SDL_KEYUP</TT
>) or a key press (<TT
CLASS="LITERAL"
>SDL_KEYDOWN</TT
>) event. The <TT
CLASS="STRUCTFIELD"
><I
>state</I
></TT
> is largely redundant, it reports the same information as the <TT
CLASS="STRUCTFIELD"
><I
>type</I
></TT
> field but uses different values (<TT
CLASS="LITERAL"
>SDL_RELEASED</TT
> and <TT
CLASS="LITERAL"
>SDL_PRESSED</TT
>). The <TT
CLASS="STRUCTFIELD"
><I
>keysym</I
></TT
> contains information of the key press or release that this event represents (see above).</P
></DIV
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN324"
></A
>Reading Keyboard Events</H2
><P
>Reading keybaord events from the event queue is quite simple (the event queue and using it is described <A
HREF="sdlevent.html"
>here</A
>). We read events using <A
HREF="sdlpollevent.html"
><TT
CLASS="FUNCTION"
>SDL_PollEvent</TT
></A
> in a <TT
CLASS="LITERAL"
>while()</TT
> loop and check for <TT
CLASS="LITERAL"
>SDL_KEYUP</TT
> and <TT
CLASS="LITERAL"
>SDL_KEYDOWN</TT
> events using a <TT
CLASS="LITERAL"
>switch</TT
> statement, like so:</P
><DIV
CLASS="EXAMPLE"
><A
NAME="AEN334"
></A
><P
><B
>Example 3-10. Reading Keyboard Events</B
></P
><PRE
CLASS="PROGRAMLISTING"
>  SDL_Event event;
  .
  .
  /* Poll for events. SDL_PollEvent() returns 0 when there are no  */
  /* more events on the event queue, our while loop will exit when */
  /* that occurs.                                                  */
  while( SDL_PollEvent( &#38;event ) ){
    /* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
    switch( event.type ){
      case SDL_KEYDOWN:
        printf( "Key press detected\n" );
        break;

      case SDL_KEYUP:
        printf( "Key release detected\n" );
        break;

      default:
        break;
    }
  }
  .
  .</PRE
></DIV
><P
>This is a very basic example. No information about the key press or release is interpreted. We will explore the other extreme out our first full example below - reporting all available information about a keyboard event.</P
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN338"
></A
>A More Detailed Look</H2
><P
>Before we can read events SDL must be initialised with <A
HREF="sdlinit.html"
><TT
CLASS="FUNCTION"
>SDL_Init</TT
></A
> and a video mode must be set using <A
HREF="sdlsetvideomode.html"
><TT
CLASS="FUNCTION"
>SDL_SetVideoMode</TT
></A
>. There are, however, two other functions we must use to obtain all the information required. We must enable unicode translation by calling <TT
CLASS="FUNCTION"
>SDL_EnableUNICODE(1)</TT
> and we must convert <SPAN
CLASS="STRUCTNAME"
>SDLKey</SPAN
> values into something printable, using <A
HREF="sdlgetkeyname.html"
><TT
CLASS="FUNCTION"
>SDL_GetKeyName</TT
></A
></P
><DIV
CLASS="NOTE"
><BLOCKQUOTE
CLASS="NOTE"
><P
><B
>Note: </B
>It is useful to note that unicode values &#60; 0x80 translate directly a characters ASCII value. THis is used in the example below</P
></BLOCKQUOTE
></DIV
><DIV
CLASS="EXAMPLE"
><A
NAME="AEN351"
></A
><P
><B
>Example 3-11. Interpreting Key Event Information</B
></P
><PRE
CLASS="PROGRAMLISTING"
>&#13;    #include "SDL.h"

    /* Function Prototypes */
    void PrintKeyInfo( SDL_KeyboardEvent *key );
    void PrintModifiers( SDLMod mod );

    /* main */
    int main( int argc, char *argv[] ){
        
        SDL_Event event;
        int quit = 0;
        
        /* Initialise SDL */
        if( SDL_Init( SDL_INIT_VIDEO ) &#60; 0){
            fprintf( stderr, "Could not initialise SDL: %s\n", SDL_GetError() );
            exit( -1 );
        }

        /* Set a video mode */
        if( !SDL_SetVideoMode( 320, 200, 0, 0 ) ){
            fprintf( stderr, "Could not set video mode: %s\n", SDL_GetError() );
            SDL_Quit();
            exit( -1 );
        }

        /* Enable Unicode translation */
        SDL_EnableUNICODE( 1 );

        /* Loop until an SDL_QUIT event is found */
        while( !quit ){

            /* Poll for events */
            while( SDL_PollEvent( &#38;event ) ){
                
                switch( event.type ){
                    /* Keyboard event */
                    /* Pass the event data onto PrintKeyInfo() */
                    case SDL_KEYDOWN:
                    case SDL_KEYUP:
                        PrintKeyInfo( &#38;event.key );
                        break;

                    /* SDL_QUIT event (window close) */
                    case SDL_QUIT:
                        quit = 1;
                        break;

                    default:
                        break;
                }

            }

        }

        /* Clean up */
        SDL_Quit();
        exit( 0 );
    }

    /* Print all information about a key event */
    void PrintKeyInfo( SDL_KeyboardEvent *key ){
        /* Is it a release or a press? */
        if( key-&#62;type == SDL_KEYUP )
            printf( "Release:- " );
        else
            printf( "Press:- " );

        /* Print the hardware scancode first */
        printf( "Scancode: 0x%02X", key-&#62;keysym.scancode );
        /* Print the name of the key */
        printf( ", Name: %s", SDL_GetKeyName( key-&#62;keysym.sym ) );
        /* We want to print the unicode info, but we need to make */
        /* sure its a press event first (remember, release events */
        /* don't have unicode info                                */
        if( key-&#62;type == SDL_KEYDOWN ){
            /* If the Unicode value is less than 0x80 then the    */
            /* unicode value can be used to get a printable       */
            /* representation of the key, using (char)unicode.    */
            printf(", Unicode: " );
            if( key-&#62;keysym.unicode &#60; 0x80 &#38;&#38; key-&#62;keysym.unicode &#62; 0 ){
                printf( "%c (0x%04X)", (char)key-&#62;keysym.unicode,
                        key-&#62;keysym.unicode );
            }
            else{
                printf( "? (0x%04X)", key-&#62;keysym.unicode );
            }
        }
        printf( "\n" );
        /* Print modifier info */
        PrintModifiers( key-&#62;keysym.mod );
    }

    /* Print modifier info */
    void PrintModifiers( SDLMod mod ){
        printf( "Modifers: " );

        /* If there are none then say so and return */
        if( mod == KMOD_NONE ){
            printf( "None\n" );
            return;
        }

        /* Check for the presence of each SDLMod value */
        /* This looks messy, but there really isn't    */
        /* a clearer way.                              */
        if( mod &#38; KMOD_NUM ) printf( "NUMLOCK " );
        if( mod &#38; KMOD_CAPS ) printf( "CAPSLOCK " );
        if( mod &#38; KMOD_LCTRL ) printf( "LCTRL " );
        if( mod &#38; KMOD_RCTRL ) printf( "RCTRL " );
        if( mod &#38; KMOD_RSHIFT ) printf( "RSHIFT " );
        if( mod &#38; KMOD_LSHIFT ) printf( "LSHIFT " );
        if( mod &#38; KMOD_RALT ) printf( "RALT " );
        if( mod &#38; KMOD_LALT ) printf( "LALT " );
        if( mod &#38; KMOD_CTRL ) printf( "CTRL " );
        if( mod &#38; KMOD_SHIFT ) printf( "SHIFT " );
        if( mod &#38; KMOD_ALT ) printf( "ALT " );
        printf( "\n" );
    }</PRE
></DIV
></DIV
><DIV
CLASS="SECT2"
><H2
CLASS="SECT2"
><A
NAME="AEN354"
></A
>Game-type Input</H2
><P
>I have found that people using keyboard events for games and other interactive applications don't always understand one fundemental point.</P
><A
NAME="AEN357"
></A
><BLOCKQUOTE
CLASS="BLOCKQUOTE"
><P
>Keyboard events <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>only</I
></SPAN
> take place when a keys state changes from being unpressed to pressed, and vice versa.</P
></BLOCKQUOTE
><P
>Imagine you have an image of an alien that you wish to move around using the cursor keys: when you pressed the left arrow key you want him to slide over to the left, and when you press the down key you want him to slide down the screen. Examine the following code; it highlights an error that many people have made.
<PRE
CLASS="PROGRAMLISTING"
>    /* Alien screen coordinates */
    int alien_x=0, alien_y=0;
    .
    .
    /* Initialise SDL and video modes and all that */
    .
    /* Main game loop */
    /* Check for events */
    while( SDL_PollEvent( &#38;event ) ){
        switch( event.type ){
            /* Look for a keypress */
            case SDL_KEYDOWN:
                /* Check the SDLKey values and move change the coords */
                switch( event.key.keysym.sym ){
                    case SDLK_LEFT:
                        alien_x -= 1;
                        break;
                    case SDLK_RIGHT:
                        alien_x += 1;
                        break;
                    case SDLK_UP:
                        alien_y -= 1;
                        break;
                    case SDLK_DOWN:
                        alien_y += 1;
                        break;
                    default:
                        break;
                }
            }
        }
    }
    .
    .</PRE
>
At first glance you may think this is a perfectly reasonable piece of code for the task, but it isn't. Like I said keyboard events only occur when a key changes state, so the user would have to press and release the left cursor key 100 times to move the alien 100 pixels to the left.</P
><P
>To get around this problem we must not use the events to change the position of the alien, we use the events to set flags which are then used in a seperate section of code to move the alien. Something like this:</P
><DIV
CLASS="EXAMPLE"
><A
NAME="AEN363"
></A
><P
><B
>Example 3-12. Proper Game Movement</B
></P
><PRE
CLASS="PROGRAMLISTING"
>    /* Alien screen coordinates */
    int alien_x=0, alien_y=0;
    int alien_xvel=0, alien_yvel=0;
    .
    .
    /* Initialise SDL and video modes and all that */
    .
    /* Main game loop */
    /* Check for events */
    while( SDL_PollEvent( &#38;event ) ){
        switch( event.type ){
            /* Look for a keypress */
            case SDL_KEYDOWN:
                /* Check the SDLKey values and move change the coords */
                switch( event.key.keysym.sym ){
                    case SDLK_LEFT:
                        alien_xvel = -1;
                        break;
                    case SDLK_RIGHT:
                        alien_xvel =  1;
                        break;
                    case SDLK_UP:
                        alien_yvel = -1;
                        break;
                    case SDLK_DOWN:
                        alien_yvel =  1;
                        break;
                    default:
                        break;
                }
                break;
            /* We must also use the SDL_KEYUP events to zero the x */
            /* and y velocity variables. But we must also be       */
            /* careful not to zero the velocities when we shouldn't*/
            case SDL_KEYUP:
                switch( event.key.keysym.sym ){
                    case SDLK_LEFT:
                        /* We check to make sure the alien is moving */
                        /* to the left. If it is then we zero the    */
                        /* velocity. If the alien is moving to the   */
                        /* right then the right key is still press   */
                        /* so we don't tocuh the velocity            */
                        if( alien_xvel &#60; 0 )
                            alien_xvel = 0;
                        break;
                    case SDLK_RIGHT:
                        if( alien_xvel &#62; 0 )
                            alien_xvel = 0;
                        break;
                    case SDLK_UP:
                        if( alien_yvel &#60; 0 )
                            alien_yvel = 0;
                        break;
                    case SDLK_DOWN:
                        if( alien_yvel &#62; 0 )
                            alien_yvel = 0;
                        break;
                    default:
                        break;
                }
                break;
            
            default:
                break;
        }
    }
    .
    .
    /* Update the alien position */
    alien_x += alien_xvel;
    alien_y += alien_yvel;</PRE
></DIV
><P
>As can be seen, we use two extra variables, alien_xvel and alien_yvel, which represent the motion of the ship, it is these variables that we update when we detect keypresses and releases.</P
></DIV
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="guideinput.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="guideexamples.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Input handling</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="guideinput.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>Examples</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>