Reputation: 113
I'm trying to write some unit test methods. I want to test method which checks if key is pressed or released. And here is my question:
Is it possible in SFML with C++ to simulate random key press on keyboard?
Or I will just have to trust myself that this works?
Upvotes: 3
Views: 1374
Reputation: 2735
The internals of sf::Keyboard::isKeyPressed
would make simulation difficult, but if you are looking to simulate KeyPressed or KeyReleased events I'm pretty sure the following should work:
const sf::Event simulateKeypress(sf::Keyboard::Key key, bool alt, bool control, bool shift, bool system)
{
sf::Event::KeyEvent data;
data.code = key;
data.alt = alt;
data.control = control;
data.shift = shift;
data.system = system;
sf::Event event;
event.type = sf::Event::KeyPressed;
event.key = data;
return event;
}
//your handler here
handleEvent(simulateKeypress(sf::Keyboard::Key::A, false, false, false, false));
I'm unable to test this at the moment... If it works, then you should be able to make similar functions for other events.
Upvotes: 3
Reputation: 350
Sure you can if you use a key manager of your own. An example in C with SDL (but its exactly the same in C++ with SFML, just few name to change) :
typedef struct
{
char key[SDLK_LAST];
int mousex,mousey;
int mousexrel,mouseyrel;
char mousebuttons[8];
char quit;
} Input;
void UpdateEvents(Input* in)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
in->key[event.key.keysym.sym]=1;
break;
case SDL_KEYUP:
in->key[event.key.keysym.sym]=0;
break;
case SDL_MOUSEMOTION:
in->mousex=event.motion.x;
in->mousey=event.motion.y;
in->mousexrel=event.motion.xrel;
in->mouseyrel=event.motion.yrel;
break;
case SDL_MOUSEBUTTONDOWN:
in->mousebuttons[event.button.button]=1;
break;
case SDL_MOUSEBUTTONUP:
in->mousebuttons[event.button.button]=0;
break;
case SDL_QUIT:
in->quit = 1;
break;
default:
break;
}
}
}
int main()
{
Input in;
memset(&in,0,sizeof(in));
while(!in.key[SDLK_ESCAPE] && !in.quit)
{
UpdateEvents(&in);
if (in.mousebuttons[SDL_BUTTON_LEFT])
{
in.mousebuttons[SDL_BUTTON_LEFT] = 0;
}
if (in.key[SDLK_UP] && in.key[SDLK_LEFT])
{
}
}
return 0;
}
Edit : Found a key manager for C++ SFML : https://github.com/dabbertorres/SwiftInputManager
Can't give you my own code cause the code is not in english
Upvotes: 1