I am fairly new to C# and programming in general and I am attempting to make a text-based RPG to learn programming techniques. I would like to have one button such as F5 that can be used at any point in the game to display player stats. At first I thought of using a while loop to allow this but then I have no idea how to return to the same part of the story in the code. Instead I thought of just printing all of the stats in to a text document but this still requires a button press that works throughout the code. I don't really know what code to include as I don't really know where to start and this is more of a logic question.
1 Answers
What you are looking for is to have a concurrent thread checking for inputs.
An extremelly simple example is this:
public class Program
{
static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(ReadKey);
Thread t = new Thread(ts);
t.Start();
while(true)
{
Console.WriteLine(DateTime.Now);
// Simulate some processing
Thread.Sleep(1000);
}
}
static void ReadKey()
{
while(true)
{
if (Console.KeyAvailable)
{
Console.WriteLine("Pressed!");
Console.ReadKey(true); // Flush the input stream without showing the key on screen.
}
}
}
}
What's happening here is that we are creating a new Thread which is checking for user input in such a way that neither thread depend on each other.
This is meant just as an example!
Note that concurrent programming is an extremelly complex subject prone to many kind of errors, most of them being really hard do diagnose. If you are just learning how to program, I would suggest you to focus on the basics first. Eventually you will get to more advanced topics.
Also note that I have not used some best practices in this code.
Other than that, great job on having the initiative of actually developing something while you learn to code! Keep it up and don't forget to also read some books or trustworthy online resources while you are at it!

- 309
- 1
- 5
-
This is exactly what I'm looking for thank you very much. And yeah, doing this text-based RPG I have learned way more than I ever have from any books because the problems are real and visible. Thanks again :) – C Dog Jul 20 '16 at 00:16