I'm writing a terminal based text-game as a mini practice project, and I've written a function that waits for an amount of seconds to display another line of text, unless it's not the first playthrough (an int playthrough is declared at the top of the code, and if the user chooses to play again - playthrough ++), then the user can skip the waiting with a keystroke. The function looks like this:
void waitOrEnter(double seconds) {
auto start = std::chrono::steady_clock::now();
while (true) {
// Check if the specified time has passed if the playthrough is equal to 0
if (playthrough == 0) {
auto now = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(now - start).count();
if (elapsed >= seconds) {
cout << "\n";
break;
}
}
// Check for key press if the playthrough is equal to or greater than 1
if (playthrough >= 1) {
if (_kbhit()) {
getch();
break;
}
// Sleep for a short amount of time
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
And I'm calling it after every line of text:
std::cout << "You wake up confused in a tiny, unfamiliar room. It's dark and the air is heavy and thick.\n";
waitOrEnter(3);
std::cout << "You see a door right in front of you.\n";
waitOrEnter(3);
Now I would like to break that function into 2 and put in separate file to call, and I would like to avoid doing if else statements after every line like
cout << "You wake up confused in a tiny, unfamiliar room. It's dark and the air is heavy and thick.\n";
if (playthrough == 0) {
wait(3);
} else {
enter(3);
}
std::cout << "You see a door right in front of you.\n";
if (playthrough == 0) {
wait(3);
} else {
enter(3);
}
Is there a way to maybe use a different function to replace the wait function with the enter function if a condition is met, so that I would only have to declare the condition once?
Or maybe even a better way to do it?
I've searched far and wide but only thing I found it to replace a string or a portion of it.
You say you want
I would like to avoid doing if else statements after every line like
and you want
only have to declare the condition once
That's what your code does already:
std::cout << "You wake up confused in a tiny, unfamiliar room. It's dark and the air is heavy and thick.\n"; waitOrEnter(3); std::cout << "You see a door right in front of you.\n"; waitOrEnter(3);
If you like you can split the implementation into two functions. I would strongly advise to not use globals, but pass playthrough
as parameter, so you can change your waitOrEnter
function to:
void waitOrEnter(double seconds,int playthrough) {
if (playthrough == 0) wait(seconds);
else enter();
}
Where wait
and enter
are the two separate functions you want to write.
You could use a function pointer to call one of two functions, but it requires the functions to be of same type and there is no need to add such complexity when a plain function can do what you want already.