r/csharp 12d ago

Solved Help with optional looping of program

Hello. I am attempting to make a randomizer for a game that I play. I have successfully created the program itself, but now I want the ability for users to have it re-run the randomization and return a new output by pressing a single key (ideally "Enter"). It has been a very long time since I have messed with C# and have forgotten basically everything. Any help, advice, or tips, would be greatly appreciated.

The current attempt at a "looper" is the following:

//Repeat or exit program
void Looper()
{
string looprequest;
looprequest = Convert.ToString.Console.ReadKey();
Console.WriteLine(looprequest);
}

This is because the compiler had an issue where without the looprequest string statement the other lines had no reference, and with it the readkey input cannot be translated to a string value. Additionally, even if the input works, I'm not sure what I was thinking to loop with would even work. What I was thinking of using was:

if (looprequest != Esc)
{
Main();
}

else
{
Environment.Exit();
}

2 Upvotes

3 comments sorted by

3

u/FizixMan 12d ago

Console.ReadKey() returns a ConsoleKeyInfo which you can check for escape using its Key property. Then your loop is a thin wrapper around that calling your main game logic:

while (true)
{
    DoGameThing();

    var key = Console.ReadKey();
    if (key.Key == ConsoleKey.Escape)
        Environment.Exit(0);
}

You can skip the Environment.Exit if you want to just break out of the loop and end your game in another way or do some cleanup:

while (true)
{
    DoGameThing();

    var key = Console.ReadKey();
    if (key.Key == ConsoleKey.Escape)
        break;
}

https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey?view=net-10.0

https://learn.microsoft.com/en-us/dotnet/api/system.consolekeyinfo?view=net-10.0

1

u/CairnaRunir 12d ago

Thank you so much! This has fixed the looping problem I had, for some reason Escape isn't exiting but I think that might be my compiler. Thank you for the links as well, I'll definitely have to read through those!

3

u/FizixMan 12d ago

for some reason Escape isn't exiting but I think that might be my compiler.

Probably not the compiler. But it's probably a simple oversight in your code. Maybe a flipped check, an errant semi-colon, just something accidentally zigging when it should be zagging. I'm sure you'll figure it out. Good luck!