Detecting multiple keys held down in a specific order can be useful for complex input sequences, such as cheat codes or combo moves in a game.
This involves tracking the sequence of key presses and ensuring they match the desired order.
Here’s an example demonstrating this approach. This example checks for two presses of the up arrow, followed by two presses of the down arrow:
#include <SDL.h>
#include <iostream>
#include <vector>
class Window {
public:
Window() {
SDL_Init(SDL_INIT_VIDEO);
SDLWindow = SDL_CreateWindow(
"Detect Key Order",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
640, 480, SDL_WINDOW_SHOWN
);
}
~Window() {
SDL_DestroyWindow(SDLWindow);
SDL_Quit();
}
void HandleKeyboard() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_KEYDOWN) {
keySequence.push_back(
event.key.keysym.scancode);
if (keySequence.size() > desiredSequence.size()) {
keySequence.erase(keySequence.begin());
}
CheckSequence();
}
}
}
private:
SDL_Window* SDLWindow{nullptr};
std::vector<SDL_Scancode> keySequence;
const std::vector<SDL_Scancode> desiredSequence {
SDL_SCANCODE_UP, SDL_SCANCODE_UP,
SDL_SCANCODE_DOWN, SDL_SCANCODE_DOWN
};
void CheckSequence() {
if (keySequence == desiredSequence) {
std::cout << "Sequence matched!\n";
keySequence.clear(); // Reset sequence after match
}
}
};
int main(int argc, char* argv[]) {
Window GameWindow;
bool running = true;
while (running) {
GameWindow.HandleKeyboard();
// Rendering code here
}
return 0;
}
Sequence matched!
keySequence
vector is used to record the sequence of key presses.desiredSequence
). If they match, a message is printed.keySequence
exceeds desiredSequence
, the oldest key is removed to maintain the correct length.Detecting multiple keys in a specific order involves tracking the sequence of key presses and comparing it with the desired order.
This method is useful for implementing complex input sequences and can be extended with additional features such as timeouts for more robust handling.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to detect and handle keyboard input in SDL2 using both event-driven and polling methods. This lesson covers obtaining and interpreting the keyboard state array.