【转】Key Presses
FROM:http://lazyfoo.net/tutorials/SDL/04_key_presses/index.php
Key Presses
![](https://img2020.cnblogs.com/blog/394545/202008/394545-20200817153957427-1089477094.png)
Last Updated 6/11/19
Xing out the window is just one of the events SDL is capable of handling. Another type of input used heavily in games is the keyboard. In this tutorial we're going to make different images appear depending on which key you press.
//Key press surfaces constants enum KeyPressSurfaces { KEY_PRESS_SURFACE_DEFAULT, KEY_PRESS_SURFACE_UP, KEY_PRESS_SURFACE_DOWN, KEY_PRESS_SURFACE_LEFT, KEY_PRESS_SURFACE_RIGHT, KEY_PRESS_SURFACE_TOTAL };
Near the top of the source code we declare an enumeration of the different surfaces we have. Enumerations are a shorthand way to do symbolic constants instead of having to do const int KEY_PRESS_SURFACE_DEFAULT = 0; const int KEY_PRESS_SURFACE_UP = 1; const int KEY_PRESS_SURFACE_DOWN = 2; and such. They default to start counting at 0 and go up by one for each enumeration you declare. This means KEY_PRESS_SURFACE_DEFAULT is 0, KEY_PRESS_SURFACE_UP is 1, KEY_PRESS_SURFACE_DOWN is 2, KEY_PRESS_SURFACE_LEFT is 3, KEY_PRESS_SURFACE_RIGHT is 4, and KEY_PRESS_SURFACE_TOTAL is 5, It's possible to give them explicit integer values, but we won't be covering that here. A quick Google search on enumerations should cover that.
One bad habit beginning programmers have is using abritary numbers instead of symbolic constants. For example they'll have 1 mean main menu, 2 mean options, etc which is fine for small programs. When you're dealing with thousands of lines of code (which video games usually do), having a line that says "if( option == 1 )" will produce much more headaches than using "if( option == MAIN_MENU )".
One bad habit beginning programmers have is using abritary numbers instead of symbolic constants. For example they'll have 1 mean main menu, 2 mean options, etc which is fine for small programs. When you're dealing with thousands of lines of code (which video games usually do), having a line that says "if( option == 1 )" will produce much more headaches than using "if( option == MAIN_MENU )".
//Starts up SDL and creates window bool init(); //Loads media bool loadMedia(); //Frees media and shuts down SDL void close(); //Loads individual image SDL_Surface* loadSurface( std::string path ); //The window we'll be rendering to SDL_Window* gWindow = NULL; //The surface contained by the window SDL_Surface* gScreenSurface = NULL; //The images that correspond to a keypress SDL_Surface* gKeyPressSurfaces[ KEY_PRESS_SURFACE_TOTAL ]; //Current displayed image SDL_Surface* gCurrentSurface = NULL;
Along with our usual function prototypes, we have a new