MCVE is below. How do I avoid recursively calling StartGame() and DisplayEndScreen? One way is to loop over StartGame(), but this doesn't seem like an extensible solution, more of a hack. Another solution might be: when the user hits R to restart, return to the main menu and pass in the Enter key as input into the switch statement, somehow.
What's a good solution?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main Menu: Press Enter to start the game >>");
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.Enter:
StartGame();
break;
// Other Menu Items
}
}
private static void StartGame()
{
// Do Game
DisplayEndScreen(); // NB: This causes recursion! I don't want this.
}
private static void DisplayEndScreen()
{
Console.WriteLine("Game Over! Select an option >> \n\n" +
"R:\tPlay again\n" +
"M:\tReturn to Main Menu\n" +
"Q:\tQuit");
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.R:
StartGame(); // NB: This causes recursion! I don't want this.
break;
// Other Menu Items
}
}
}
}
Calling StartGame() inside StartGame() causes the recursion. The way to avoid it is simply not calling a method inside of itself.
I think the name of the functions are a bit confusing for your program, are you sure 'StartGame' is correctly describing what the function is doing? It seems more likely to be the actual game (game()?) itself. If the name instead was something that tells you that the game is actually running (as it looks like its doing), calling it again would make less sense for you.
Considering running a game, most basic solutions usually looks like this:
bool game = true;
while(game)
{
//game running
if(exit)
{
game = false;
}
}