I am making a text game where at each situation the user may type in his/her choice on what action to do.

Is there a way to make it where if someone were to type "save" or push the "s" key to have the game save or go back to a certain place in the code (the main town)?

Dani AI

Generated

asked about letting the player type "save" or press "s" at any time; suggested a loop-based dispatch and raised good points about choosing clear designs over premature micro-optimizations. Below are practical, durable ways to implement global commands and single-key hotkeys in a console text game, plus safety tips for saving.

Keep a single command-dispatch layer

  • Check global commands first, then forward unknown input to the current game-state handler. This keeps state logic separate from global controls and avoids spaghetti control flow.
  • Use a data-driven dispatcher (map from command string to handler function) so adding commands is one-line and scales better than long conditional chains.

Example dispatcher pattern (not shown earlier in thread):

using Command = std::function<void(Game&)>;
std::unordered_map<std::string, Command> globalCommands = {
  {"save", [](Game& g){ g.save(); }},
  {"quit", [](Game& g){ g.requestQuit(); }}
};

void handleInput(const std::string& input, Game& game) {
  auto it = globalCommands.find(toLower(input));
  if (it != globalCommands.end()) { it->second(game); return; }
  game.currentState->handle(input);
}

Capturing single-key presses ("press s anytime")

  • Two options: put the console into noncanonical/raw mode and read single chars (POSIX termios) or run an input-listener thread that performs blocking reads and posts events to the main loop.
  • On Windows use the console APIs or _kbhit/_getch; on Unix use termios or a library like ncurses for portable single-key handling. See the POSIX termios overview and Windows kbhit docs for details: termios man page, .

Safe saves and concurrency

  • Make saves atomic: write to a temp file, flush, then rename/replace the real save file (rename is atomic on most systems). Use a mutex or pause game updates while creating a snapshot to avoid inconsistent state. Consider save slots and periodic backups.
  • For structured data, use a stable serialization format (JSON, protobuf, custom) rather than dumping raw pointers. Example libraries: nlohmann/json.

Troubleshooting tips

  • Avoid mixing raw single-char reads with high-level blocking reads (getline) without coordinating modes or threads. Test saving while in the middle of actions. Log save success/failure and give the player immediate feedback.
  • Start with the dispatcher approach, add a single input thread if you need instant hotkeys, and keep save logic transactional so corrupted saves are unlikely.

Recommended Answers

All 8 Replies

a infinite loop with switch case perhaps

what are the advantages of cases over just using if, else if, ect?

I read this is in a book.

Switch case is faster if there are more than 2 conditions to be checked, since it maintains a table of pointers to execute instruction. And the table is created in compile time and hence case cannot contain variables unlike if else.

And also switch case looks good.

switch (var)
{
case 1:
    // do someting
case 2:
   // do something else
// more cases
}

or 

if ( var == 1 )
{
    // do someting
}
else 
{
    if ( var == 2 )
    {
    }
    else
    {
         // nest & nest & nest
    }
}

0_o very useful. Thank you

>Switch case is faster if there are more than 2 conditions to be checked
First, you shouldn't use absolute statements like "X is faster than Y", because you'll nearly always be wrong. Second, where did you come up with two conditions? That seems like a very compiler-specific statement to me.

>since it maintains a table of pointers to execute instruction
That's one valid implementation, but it's not required. Even with that implementation, you can't claim a switch to be faster in all cases because in your example var could always be 1 and the first if will run every time, which amounts to the same thing as the table jump in a switch.

Hell, a switch could be orders of magnitude slower than an if chain (or vice versa) if you get unlucky with cache effects. There are so many variables in the performance of a program that it's always better to write your code with clarity in mind and optimize only after profiling shows that there's a bottleneck.

>And also switch case looks good.
Subjective. Not to mention that your example clearly used a style that makes the switch look better. This is more correct (I added breaks to the switch) and more conventional (most people don't indent their else ifs):

switch (var)
{
case 1:
  // do something
  break;
case 2:
  // do something else
  break;
// more cases
}

or 

if ( var == 1 )
{
    // do someting
}
else if ( var == 2 )
{
  // do something else
}
// more ifs

A significant difference between the two is that the cases in a switch are far less flexible. If you need to switch on non-integral types you're SOL, and switching on a range of values gets messy very quickly.

I was not sure what I gave was right, so I did say my source partially. Its a book devoted to turbo C++.

You saw through it. Yes indeed. I was subjective. I knew it too.

I did not add break, because it is not a must in switch case.

Thanks for your post I got valuable informations.

>I did not add break, because it is not a must in switch case.
If you don't break out of a case, you'll continue to execute the cases below it. That's very rarely desired behavior, which is why pretty much every style guideline requires a comment if you really want fallthrough:

switch ( radix ) {
case DECIMAL:
  // FALLTHROUGH
case OCTAL:
  // Do stuff for decimal and octal
  break;
default:
  // Error
  break;
}

Without the break in the octal case, every radix would be treated as an error even after being successfully processed as decimal or octal.

Yes indeed I use that a lot

case 'n': case 'N': /* something */break ;
case 'y': case 'Y': /* something */break ;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.