Daniel W. answered 06/07/23
A Software Engineer with 12+ years of Web Development Experience
- Maintain a file that contains all the questions and the acceptable answers.
- Create a function that will read from std::cin, that will timeout after the amount of time that the game allows.
- This function will create a std::future that calls a lambda function that reads from std::cin and returns the user's input.
- This function will then call .wait_for() on that future. If the return value is std::future_status::timeout, then the answer could be set to some sentinel value that denotes an incorrect answer, for example an empty string. Otherwise, return the user's input.
- If the answer hasn't timed out, then check the user's answer against the acceptable answers for the question using an equality operation. If the user's answer equals the expected answer, then add to the user's score.
- After all questions are asked and answered, output the total score of the user.
Additional modifications can be made to this game. For example:
- The score for each question can be weighted to the amount of time it took the user to answer. For this to work, you could have the async lambda return a struct containing the amount of time taken, as well as the user's input.
- A countdown clock can be displayed on the console and updated every second. This would also require some way to update the console in-place for that timer. This tends to be an OS-specific operation.
- More complex user input parsing can take place. For example, it might be acceptable for the user's input to contain, rather than equal, the accepted answer. You may also want to match user input in a case-insensitive way. And you may also loop through an array of acceptable answers, if there's more than one acceptable answer.
- You might want to use a database for the questions and answers if the file is too unwieldy and the game logic is too complex. Take into consideration not just how you want the game to function, but how you want the developer(s) or maintainer(s) of the app to populate the game with data.
This all assumes that this is a console application. If it's a windowed application, the core functionality of parsing and scoring would remain the same, but the input, timing, and output methods would change to conform to whichever graphics framework is being used. For example, rather than the linear approach above, you might need to rely on an event-based approach, based on events emitted by UI elements.