I am trying to build a countdown timer that if the selected choice is set time, it will open and prompts the user to enter value to set the time. once the user is done in typing the numbers, it must show choices like this
Press S to start: Press P to pause
This is what I am lacking, I do not know what to code to enable to pause the time and to start it.
using System;
namespace time_console
{
class Program
{
static void Main(string[] args)
{
designNumbers Fancy = new designNumbers();
Program mainMenu = new Program();
mainMenu.RunMainMenu();
}
private void RunMainMenu()
{
string prompt = "Welcome to Neil's Countdown Timer. Select an option";
string[] options = { "Set Time", "Exit" };
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
SetTime();
break;
case 1:
Exit();
break;
}
}
private void SetTime()
{
Console.SetCursorPosition(4, 4);
Console.WriteLine("enter time in minutes:seconds ");
Console.SetCursorPosition(4, 5);
int m = Convert.ToInt32(Console.ReadLine());
Console.SetCursorPosition(4, 6);
int s = Convert.ToInt32(Console.ReadLine());
for (; ; )
{
if (s == 0 && m == 0)
{
Console.WriteLine("\nTime's up!");break;
}
if (s == 0)
{
s = 60;
m--;
}
System.Console.Clear();
Console.SetCursorPosition(4, 7);
Console.WriteLine(m + ":" + s--);
System.Threading.Thread.Sleep(1000);
}
WriteLine("Press M to return to Menu");
ConsoleKey a;
ConsoleKeyInfo b = ReadKey(true);
a = b.Key;
if(a == ConsoleKey.M)
{
RunMainMenu();
}
}
private void Exit()
{
WriteLine("press any key to exit...");
ReadKey(true);
Environment.Exit(0);
}
}
}
Related
I'm doing a school project and I really feel that I can acomplish what I want in my code, however I feel like i -always- repeat my code.
I have tried to put the switch cases into methods but haven't had any success though to out of scope.
I am beginner so sorry for the eyesore code!
However, if anyone have any tips for using methods or something else so I can clean up my code a little better.
So here is a bit of my code, this is the beginning branch of my menu.
I have translated the code roughly to english.
So this is a sub menu in the main method.
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
switch (menuInput03)
{
/////WATER PLANT////
case 1:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
if (plant[0] < 21)
{
for (int i = plant[0]; i < 21; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
Console.WriteLine("\nWatering plant..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has been watered!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
else
{
break;
}
Console.Clear();
break;
case 2:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
if (plant[0] > 19)
{
for (int i = plant[0]; i < 51; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
i++;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
Console.WriteLine("\nRipping out weeds..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has gotten it's weed removed!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
Console.Clear();
break;`
I came up with the following; don't just copy-paste for school project without understanding what is going on. If some things are not clear do not hesitate to ask follow-up questions.
public record Action
{
public string Title { get; }
public int RequiredHealth { get; }
public string ActionMessage { get; }
public string CompletedMessage { get; }
private Action(string title, int requiredHealth, string actionMessage, string completedMessage)
{
Title = title;
RequiredHealth = requiredHealth;
ActionMessage = actionMessage;
CompletedMessage = completedMessage;
}
public static Action WaterPlant { get; } = new Action(
title: "Press SPACEBAR several times to water plant!",
requiredHealth: 20,
actionMessage: "Watering plant..",
completedMessage: "Your plant has been watered!");
public static Action RemoveWeed { get; } = new Action(
title: "Press SPACEBAR several times to remove weed!",
requiredHealth: 50,
actionMessage: "Ripping out weeds..",
completedMessage: "Your plant has gotten it's weed removed!");
}
static void Main()
{
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
for (var menuInput03 = 1; menuInput03 <= 2; menuInput03++)
{
var action = menuInput03 switch
{
1 => Action.WaterPlant,
2 => Action.RemoveWeed,
};
Console.Clear();
Console.WriteLine(action.Title);
while (plant[0] < action.RequiredHealth)
{
if (Console.ReadKey().Key != ConsoleKey.Spacebar)
{
Console.Write("\b \b");
continue;
}
plant[0]++;
Console.Clear();
Console.WriteLine(action.Title);
Console.WriteLine(action.ActionMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
}
Console.Clear();
Console.WriteLine(action.CompletedMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
Console.WriteLine("To continue press ENTER.");
while (Console.ReadKey().Key != ConsoleKey.Enter)
{
Console.Write("\b \b");
}
Console.Clear();
}
}
How best to send method to another thread while listening for input from the user. How best to pause/resume that same threaded method?
A very trimmed down example of the kind of thing I am trying to achieve:
static int fuel = 100;
static bool tankEmpty = false;
static void Main(string[] args)
{
Debug.WriteLine("test");
ThreadStart fuelThreadStart = ProcessFuel;
var fuelThread = new Thread(fuelThreadStart);
fuelThread.Start();
Console.WriteLine("Press x to add fuel");
string input = Console.ReadLine(); // < where should this go?
if (input == "x")
{
AddFuel();
}
}
static void ProcessFuel()
{
while (!tankEmpty)
{
Console.Clear();
Console.WriteLine("Current fuel level: " + fuel);
Thread.Sleep(2000);
fuel -= 10;
if (fuel < 20)
{
Console.WriteLine("Fuel level is low.");
}
}
if (tankEmpty)
{
Console.WriteLine("You have run out of fuel")
)
}
static void AddFuel()
{
if (fuel > 80)
{
fuel = 100;
}
else { }
fuel += 20;
}
I am trying to go back to start in c# console program, and i am somehow able to do it, but the problem is that i am not able to do it using the Y/N statement. mean if i type the Y (yes) from keyboard then the program start from it's starting (beginning) point if i type N then it will terminate the program.
My Console code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace simple_calculation
{
class Program
{
static void Main(string[] args)
{
bool bktop = true;
string option;
while (bktop)
{
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper=Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
if(option=="Y")
{
bktop = false;
}
else
{
bktop = true;
}
}
Console.ReadLine();
}
}
}
}
What I want: i want that when the program reaches to the else condition then there is a text appear in the console "do you want to continue? enter Y/N" if the user enter Y then the program start again and if the user enter N then the program will terminate.
Any help will be appreciated.
class Program
{
static void Main(string[] args)
{
// Change 1
bool bktop = true;
string option;
while (bktop)
{
bktop = true;
Console.WriteLine("Please enter the values");
int val = int.Parse(Console.ReadLine());
int val1 = int.Parse(Console.ReadLine());
int res = val + val1;
int red = val / val1;
Console.WriteLine("Please enter the operator");
string oper = Console.ReadLine();
if (oper == "+")
{
Console.WriteLine("sum is:" + res);
}
else if (oper == "/")
{
Console.WriteLine("division is:" + red);
}
else
{
Console.WriteLine("do you want to continue? enter Y/N");
option = Console.ReadLine();
// Change 2
if (option.ToUpper() != "Y")
{
bktop = false;
}
}
}
}
}
So I've created a blackjack game using an interface whose entry point is "PlayGames()". However, once the game is finished, I want to give the option to the user to go back to the main menu, which is in Main(). Is there a way to call main so that the user can go back to the main menu? Simply calling Main() does not work.
Here's what I've got:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
if (a == "z") {
Main ();
}
}
The variable a is the string user-entered string that determines if the game closes, or continues to play. If the user enters that they want to go back to the main menu, the letter "z" is assigned to a, which will lead them back to the main menu.
Here's what Main() looks like, including class information. The error message that comes up says "Main does not exist in the current context":
using System;
using System.IO;
using System.Collections.Generic;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games;
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
while (n != 0 && n != 1 && n != 2) {
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
}
}
I would recommend you to put displaying menu & getting input into a function. Just to make it easy to comprehend. Also in your list of games, maybe you want to keep track of game history? if so you need to keep adding a new one like so:
using System;
using System.IO;
using System.Collections.Generic;
using ConsoleApplication8;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games = new List<Casino>();
private static const int INVALID_CODE = -111;
private static const int EXIT_CODE = 4;
public static void Main()
{
int choosen = INVALID_CODE;
while (choosen != EXIT_CODE)
{
switch (choosen)
{
case INVALID_CODE:
choosen = DisplayMenu();
break;
case 0:
displayHelp();
choosen = INVALID_CODE;
break;
case 1:
games.Add(new BlackJack());
games[games.Count-1].PlayGames();
break;
case 2:
games.Add(new QuarterGame());
games[games.Count-1].PlayGames();
break;
default:
DisplayMenu();
break;
}
}
}
private static void displayHelp()
{
Console.WriteLine("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
private static int DisplayMenu()
{
Console.WriteLine("MAIN MENU");
Console.WriteLine("(0 for help)");
Console.WriteLine("(1 for blackjack)");
Console.WriteLine("(2 for Quarter Game)");
Console.WriteLine("Please enter an integer to choose your game: ");
string input = Console.ReadLine();
int number;
if (Int32.TryParse(input, out number))
return number;
else
{
Console.WriteLine("Please Try an Integer");
return INVALID_CODE;
}
}
}
}
Your while is repeating the wrong stuff:
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
while (n != 0 && n != 1 && n != 2) {
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
Notice you never left the "Main" function, so in your "PlayGames" function you can just go ahead and return:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
//Do nothing, the while in Main function will already take us back to the menu
}
I'm stuck with the following code and what I'm trying to achieve now, is to NOT nest switches/if statements any further, which would result in ugly code, I assume. To visualize my intention:
ConsoleKeyInfo keyE = Console.ReadKey();
if (keyE.Key == ConsoleKey.Enter && iMOP == 1){
//Jump to character creation (but not nest this if statement even further)
{
I want to apply this idea to a solved problem which I have already asked before:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
int iMOP = 1;
Console.WriteLine(" >>New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" Exit Game");
while (iMOP != 5)
{
{
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.UpArrow)
{
iMOP--;
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
iMOP++;
}
}
if (iMOP == 0)
{
iMOP = 3;
}
else if (iMOP == 4)
{
iMOP = 1;
}
switch (iMOP)
{
case 1:
Console.Clear();
Console.WriteLine(" >>New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" Exit Game");
break;
case 2:
Console.Clear();
Console.WriteLine(" New Game");
Console.WriteLine(" >>Load Game");
Console.WriteLine(" Exit Game");
break;
case 3:
Console.Clear();
Console.WriteLine(" New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" >>Exit Game");
break;
}
}
}
}
The questions would be: How do I realize this? Are there decent tutorials which you could link me to?
If it is going to get too complicated, use a Console based Graphics engine (Is there any console "graphics" library for .Net?).
MonoCurses seem to be very friendly: http://www.mono-project.com/docs/tools+libraries/libraries/monocurses/
But, just for curiosity, something much simpler (from scratch):
Use Classes to Create, Display and Get the user input for your menu.
How it works
It is basically a Menu Class, that displays its MenuItem classes, and draw while wait the user select a option.
This menu class was then inserted in a nested Switch, for the Main Menu levels.
I tried to do something better, needs refactoring, so you can have some idea to improve:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
do
{
#region Main Menu
var m = new Menu() { Title = "MAIN MENU" };
m.Menus.Add(new MenuItem() { Title = "New Game", SelectedForegroundColor = ConsoleColor.Green });
m.Menus.Add(new MenuItem() { Title = "Load Game" });
m.Menus.Add(new MenuItem() { Title = "Exit Game", SelectedForegroundColor = ConsoleColor.Yellow });
var result = m.ShowAndWaitUserInput();
//Console.Write("selected was:" + result);
//Console.ReadLine();
#endregion
switch (result)
{
case 0:
#region // Jump to character creation
var m1 = new Menu() { Title = "CHARACTER CREATION" };
m1.Menus.Add(new MenuItem() { Title = "New Character" });
m1.Menus.Add(new MenuItem() { Title = "Load Character" });
m1.Menus.Add(new MenuItem() { Title = "Return" });
var result1 = m1.ShowAndWaitUserInput();
switch (result1)
{
case 0:
#region // CREATE THE NEW CHARACTER
Console.WriteLine("CREATE THE NEW CHARACTER");
Console.ReadKey();
#endregion
break;
case 1:
#region // LOAD CHARACTER
Console.WriteLine("LOAD CHARACTER");
Console.ReadKey();
// Write your code here...
#endregion
break;
case 2:
#region // DO ALMOST NOTHING: RETURNS TO PREVIOUS MENU
#endregion
break;
}
#endregion
break;
case 1:
#region // Load Game code...
Console.WriteLine("LOAD GAME");
Console.ReadKey();
// Write your code here...
#endregion
break;
case 2:
#region // EXIT GAME
#endregion
return;
}
} while (true); // Main Menu
}
}
public class MenuItem
{
public string Title { get; set; }
public ConsoleColor SelectedForegroundColor { get; set; }
public MenuItem()
{
this.SelectedForegroundColor = ConsoleColor.Yellow;
}
}
public class Menu
{
public string Title { get; set; }
public List<MenuItem> Menus { get; set; }
public Menu()
{
this.Menus = new List<MenuItem>();
}
public int ShowAndWaitUserInput()
{
Console.CursorVisible = false;
int selectedMenu = 0;
do
{
Console.Clear();
#region Display Menu and Sub-Menus
{
var i = 0;
// more at http://www.graphics.cornell.edu/~westin/misc/windows_charmap.html
Console.WriteLine(" ╔═══════════════════════════════════════════╗");
Console.WriteLine(" ║ ░ " + this.Title.ToUpper().PadRight(40).Substring(0, 40) + "║");
Console.WriteLine(" ╚═══════════════════════════════════════════╝");
Console.WriteLine("");
//var old_CB = Console.BackgroundColor;
var old_CF = Console.ForegroundColor;
foreach (var menu in Menus)
{
//Console.WriteLine(" New Game");
if (i == selectedMenu)
{
Console.ForegroundColor = menu.SelectedForegroundColor;
Console.Write(" >> ");
}
else
{
Console.ForegroundColor = old_CF;
Console.Write(" ");
}
Console.WriteLine(menu.Title);
i++;
}
Console.WriteLine("");
//Console.BackgroundColor = old_CB;
Console.ForegroundColor = old_CF;
}
#endregion
#region Get User Input
{
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.UpArrow)
{
selectedMenu--;
if (selectedMenu < 0) selectedMenu = Menus.Count() - 1;
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
selectedMenu++;
if (selectedMenu == Menus.Count()) selectedMenu = 0;
}
else if (keyInfo.Key == ConsoleKey.Enter)
{
return selectedMenu;
}
}
#endregion
} while (true);
}
}
}