-
Hello ! I have a problem and I could not find a answer. I need handle a whichever key form keyboard (in specific case) and i dont know how to do it.
Below is code in c++.
void SnakeGame::initializeDirectionMap(){
mapOfDirects[sf::Keyboard::Right] = std::shared_ptr<DirectConditions>(new GoRight);
mapOfDirects[sf::Keyboard::Left] = std::shared_ptr<DirectConditions>(new GoLeft);
mapOfDirects[sf::Keyboard::Up] = std::shared_ptr<DirectConditions>(new GoUp);
mapOfDirects[sf::Keyboard::Down] = std::shared_ptr<DirectConditions>(new GoDown);
mapOfDirects[sf::Keyboard::End] = std::shared_ptr<DirectConditions>(new Pause);
mapOfDirects[sf::Keyboard::AnyKey] = std::shared_ptr<DirectConditions>(new Exit); // i don't know how to do it
}
direction=event.key.code; // take key from keyboard
mapOfDirects[direction]->choosenDirection(*this); // choose which method have to execute by key from keyboard
Is even possible handle all keys in sf::Keyboard::Key type ? I mean I press A,B,F5, whatever and always mapOfDirect[sf::Keyboard::"AnyKey"] will be choosen that is what I need. ("AnyKey" means my leak of knowledge :P I don't know what I have to put there instead of AnyKey)
If you know some tutorials or tips with events handle form keyboard which might help me solve this issue please share with me.
I would really appreciate help !
-
You can't refer to "any key" directly. But you can handle the case of "direction not found in map" easily:
auto it = mapOfDirects.find(direction);
if (it != mapOfDirects.end())
{
// direction found
(*it)->choosenDirection(*this);
}
else
{
// any other key
// exit...
}
-
Awesome ! Thanks a lot ! But I have problem with cpp :P
std::map<sf::Keyboard::Key, std::shared_ptr<DirectConditions>>::iterator
it=mapOfDirects.find(direction);
it->choosenDirection(*this); // any of this syntax work
// (*it)->choosenDirection(*this); //
// *it->choosenDirection(*this); //
error::<const sf::Keyboard::Key, std::shared_ptr<DirectConsition>> has no member 'choosenDirection' "
but this syntax works mapOfDirects[direction]->choosenDirection(*this);
I don't know how to do it ;/
Could you help me please ? Thanks advance !
EDIT
It works : it->second->choosenDirection(*this) :D
-
Yes, sorry for the wrong syntax.
And you should really use the 'auto" keyword here ;)