I wrote a simple wrapper in C++ for the SDL Keyboard library. It should make life a bit easier for handling
- 1. Single Key Input
- 2. Simultaneous Key Combos (Keys all pressed in any order)
- 3. Sequential Key Combonations (Keys all pressed in specific order)
Download the whole ZIP file here -> Download
Keyboard.h
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 | #ifndef __SDL__KEYBOARD__H__ #define __SDL__KEYBOARD__H__ #include <SDL/SDL.h> #include <iostream> #include <vector> #define KEYBOARD_MAX_KEYS 322 class Keyboard { public: Keyboard(); virtual ~Keyboard(); void listen(); bool keyDown(int key); bool isCombo(std::vector<int> keys); bool isSequentialCombo(std::vector<int> keys); void clear(); private: bool keys[KEYBOARD_MAX_KEYS]; // 322 is the number of SDLK_DOWN events, 0 for not pressed, 1 for pressed Uint32 keysPressedTime[KEYBOARD_MAX_KEYS]; // the time each key was pressed }; #endif |
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 | #include "Keyboard.h" Keyboard::Keyboard() { clear(); } Keyboard::~Keyboard() { } void Keyboard::listen() { SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: keys[event.key.keysym.sym] = true; keysPressedTime[event.key.keysym.sym] = SDL_GetTicks(); break; case SDL_KEYUP: keys[event.key.keysym.sym] = false; keysPressedTime[event.key.keysym.sym] = 0; break; } } } bool Keyboard::keyDown(int key) { if(keys[key]) { return true; } return false; } void Keyboard::clear() { for(int i = 0; i < KEYBOARD_MAX_KEYS; i++ ) { keys[i] = false; keysPressedTime[i]= 0; } } bool Keyboard::isCombo(std::vector<int> keys) { for(Uint16 i = 0; i < keys.size(); i++) { if(!keyDown(keys[i])) { return false; } } return true; } bool Keyboard::isSequentialCombo(std::vector<int> keys) { Uint32 lastKeyTime = 0; for(Uint16 i = 0; i < keys.size(); i++) { if(!(keyDown(keys[i]) && keysPressedTime[keys[i]] > lastKeyTime)) { return false; } lastKeyTime = keysPressedTime[keys[i]]; } return true; } |
Try out Main.cpp to actually see a how to use the Keyboard

Posted in
Tags: 
