views:

363

answers:

1

I'm writing a game and I'm wound up in needing a console for simple text input; filenames and simple values.

Using SDL, my console looks the following at it's simplest:

class   Console
{
public:
  typedef std::list<String> InputList;

  enum  Result
  {
 NOTHING = 0,
 ENTERED,
 ESCAPED
  };

  static const String&  GetInput() { return input; }

  static Result Query(SDLKey lastKey)
  {
    if(lastResult == ENTERED || lastResult == ESCAPED)
    {
      input.clear();
    }

    switch (lastKey)
    {
 case SDLK_a:
 case SDLK_b:
 case SDLK_c:
 case SDLK_d:
 case SDLK_e:
 case SDLK_f:
 case SDLK_g:
 case SDLK_h:
 case SDLK_i:
 case SDLK_j:
 case SDLK_k:
 case SDLK_l:
 case SDLK_m:
 case SDLK_n:
 case SDLK_o:
 case SDLK_p:
 case SDLK_q:
 case SDLK_r:
 case SDLK_s:
 case SDLK_t:
 case SDLK_u:
 case SDLK_v:
 case SDLK_w:
 case SDLK_x:
 case SDLK_y:
 case SDLK_z:
 case SDLK_0:
 case SDLK_1:
 case SDLK_2:
 case SDLK_3:
 case SDLK_4:
 case SDLK_5:
 case SDLK_6:
 case SDLK_7:
 case SDLK_8:
 case SDLK_9:
 case SDLK_SLASH:
 case SDLK_BACKSLASH:
 case SDLK_PERIOD:
 case SDLK_COMMA:
 case SDLK_SPACE:
 case SDLK_UNDERSCORE:
 case SDLK_MINUS:
  input += static_cast<char> (lastKey);
  lastResult = NOTHING;
  break;
 case SDLK_RETURN:
  lastResult = ENTERED;
  break;
 case SDLK_ESCAPE:
  lastResult = ESCAPED;
  break;
 }
    return lastResult;
  }

protected:
  static Result lastResult;
  static String input;
};

This would be called from the application's main event loop, if the console is active and the last event was a keypress, then the result of the input is processed at a state where it's necessary.

Of course, it looks incredibly awkward... What's a better way to implement a simple console that can be easily rendered in my game's window? (Not going anywhere near to highly unportable solutions like having to reroute std::cout or writing code to bring up a UNIX console etc.)

+3  A: 

One suggestion I would offer is to use if statements instead of a switch in this case:

if(lastKey == SDLK_RETURN)
    lastResult = ENTERED;
else if(lastKey == SDLK_ESCAPE)
    lastResult = ESCAPED;
else if(lastKey >= SDLK_SPACE && lastKey <= SDLK_z)
{
    input += static_cast<char> (lastKey);
    lastResult = NOTHING;
}

I took some liberties and included some characters that you didn't have in your code above, such as the ampersand, quotes, parentheses, brackets, etc. If you don't want those keys, you can add a few more if statements to break it down a bit more.

This assumes that the enum for the keys doesn't change a lot. If it does change a lot you may be better off with what you had.

Venesectrix