Reputation: 41
I have made a hangman game, and I want to be able to restart it after you've won/lost, rather than having to restart the program manually every time.
I saw on the internet 'Application' which can be used to restart the console. However, it says that Application doesnt exist.
Close();
System.Diagnostics.Process.Start(Application.ExecutablePath);
Please help me!
Upvotes: 0
Views: 214
Reputation: 9498
I don't think you really need to restart your console application to restart your game. Here is a possible game restarting scenario which can be used:
class Program
{
static void Main(string[] args)
{
Game game = new Game();
Menu menu = new Menu(game);
game.Finished += menu.AskAndRun;
menu.Welcome();
}
}
class Menu
{
public readonly IRunnable runnable;
public Menu(IRunnable runnable)
{
this.runnable = runnable;
}
public void Welcome()
{
Console.WriteLine("Welcome, Player!");
AskAndRun();
}
public void AskAndRun()
{
Console.WriteLine("\nTo play a new game, press [ENTER]");
Console.ReadLine();
Console.Clear();
runnable.Run();
}
}
interface IRunnable
{
void Run();
}
class Game : IRunnable
{
public event Action Finished;
public void Run()
{
Console.WriteLine("Game started here...");
Console.WriteLine("Oops! Game finished already");
if (Finished != null)
{
Finished();
}
}
}
As you can see, the Game
class was separated from the restarting logic which now handled by Menu
class. Now it is trivial to introduce new features like exiting and counting number of started games.
Pay attention to the fact that Menu
doesn't depend on Game
. It depends on IRunnable
and this will help you in changing the Game
, testing Menu
and introducing new features painlessly.
Upvotes: 0
Reputation: 156978
You can find it over here:
You need to include the System.Windows.Forms
assembly and add a using
using System.Windows.Forms
But for Console apps I would prefer to use this (when in your Console assembly):
System.Reflection.Assembly.GetExecutingAssembly().Location
Like Andre said as comment, you'd even better use Assembly.GetEntryAssembly()
since it gets the first assembly that is called (which is of course the executable in console applications)
And of couse, like the previous answer which is removed already, first reopen, and then close the application.
Upvotes: 1