C# Menu System will not work - c#

I'm not sure how to explain this but I'll try my best since I'm new to c# programming.
I have created a Menu System
string sChoice;
//Menu
Console.WriteLine("1 - Instructions");
Console.WriteLine("2 - New User");
Console.WriteLine("3 - Record & Score");
Console.WriteLine("4 - Exit System");
Console.Write("Please enter your choice between 1-4: ");
sChoice = Console.ReadLine();
Pressing 1 will then take you to the instructions section of the console application and so on.
//Instructions
if (sChoice == "1")
{
Console.WriteLine();
Console.WriteLine("*Instructions*");
Console.WriteLine();
I have tried an else statement which will repeat the menu and prompt the user of an invalid key, however this will only repeat itself another 3 times before closing. Is there a way for me to block any other keys other than 1-4 being entered or a solution to my problem
Because as it seems, if any key other than 1-4 is pressed then the console application will simply close.

This question remembers me when I was young and started programming.
Maybe you want someting like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int mainMenuOption = OptionMenu("Instructions", "New User", "Record & Score", "Exit System");
switch (mainMenuOption)
{
case 1: Instructions(); break;
case 2: NewUser(); break;
case 3: RecordAndScore(); break;
case 4: Console.WriteLine("Goodbye.."); return;
}
}
}
static void Instructions()
{
// Handle Instructions here
Console.WriteLine("Instrucctions done");
}
static void NewUser()
{
// Handle New User here
Console.WriteLine("New user done");
}
static void RecordAndScore()
{
// handle recorde and score here
Console.WriteLine("Record & score done");
}
static int OptionMenu(params string[] optionLabels)
{
Console.WriteLine("Please Choose an option");
for (int optionIndex = 0; optionIndex < optionLabels.Length; optionIndex++)
{
Console.Write(optionIndex + 1);
Console.Write(".- ");
Console.WriteLine(optionLabels[optionIndex]);
}
while (true)
{
var input = Console.ReadLine();
int selectedOption;
if (int.TryParse(input, out selectedOption) && selectedOption > 0 && selectedOption <= optionLabels.Length)
{
return selectedOption;
}
else
{
Console.WriteLine("Invalid option, please try again");
}
}
}
}
}

Related

c# endless method switch loop. Trying to execute the method and end it with a return; statement but it loops back to the begining of the method

I am having an issue where my method is running endlessly i have tested and it runs through the do while loop fine and terminates, but despite it having a return; statement. My program is not ending the method and returning to main.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, What would you like to do?\n1. add a phonebook entry.\n2. search for a specific phonebook entry.\n3. see all phonebook entries.\n4. quit.");
var choice = Console.ReadLine();
int Choice;
var END = "";
do
{
if (int.TryParse(choice, out Choice) && Choice >= 1 && Choice <= 4)
{
switch (Choice)
{
case 1:
addName();
Choice = 0;
break;
case 2:
findName();
break;
case 3:
seeNames();
break;
case 4:
END = "123898761hgasdbfasd";
break;
default:
Console.WriteLine("Hello, What would you like to do?\n1. add a entry.\n2. search for a specific entry.\n3. see all entries.\n4. quit.");
break;
}
}
else { Console.WriteLine("Hello, What would you like to do?\n1. add a entry.\n2. search for a specific entry.\n3. see all entries.\n4. quit.");
choice = Console.ReadLine();
}
}while(END != "123898761hgasdbfasd");
}
private static void seeNames()
{
throw new NotImplementedException();
}
private static void findName()
{
throw new NotImplementedException();
}
private static void addName()
{
int place = 1,end = 0;
string name = null, address = null, numer = null;
do {
switch (place)
{
case 1:
Console.WriteLine("What name would you like to add?");
var User = Console.ReadLine();
Console.WriteLine("You entered {0} is that right?", User);
name = User;
User = Console.ReadLine();
if (User == "y" || User == "Y") { place = 2; }
else { place = 1; }
break;
case 2:
Console.WriteLine("What address would you like to add?");
User = Console.ReadLine();
address = User;
Console.WriteLine("You entered {0} is that right?", User);
User = Console.ReadLine();
if (User == "y" || User == "Y") { place = 3; } else { place = 2; }
break;
case 3:
Console.WriteLine("What phone number would you like to add?");
User = Console.ReadLine();
Console.WriteLine("You entered {0} is that right?", User);
numer = User;
User = Console.ReadLine();
if (User == "y" || User == "Y") { place = 4; } else { place = 3; }
break;
case 4:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("Addressbook.txt", true))
{ file.WriteLine("Name : {0} Address: {1} Phone-Numer: {2}", name, address, numer); file.Close(); }
Console.WriteLine("Would you like to subbmit another entry?");
User = Console.ReadLine();
if (User == "y" || User == "Y") { place = 1; }
else { end = 5; return; }
break;
default:
break;
}
} while (end != 5);
return;
}
}
}
After reaching place 4 and telling the program i do not want to input another address it loops back and ask for another name. I cant seem to break this loop and cause the program to go back to the main program(main is a 4 choice menu that call other methods.)

Return to a specific block of code in my application

I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.

How to reloop the game and ask something

I made a program that calculates the temperature in different ways.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise_7
{
class Program
{
static void Main(string[] args)
{
showBegin();
decide();
secondPlay();
showEnd();
}
// Decide code
static void decide() {
int choice;
string input;
input = Console.ReadLine();
int.TryParse(input, out choice);
if (choice == 1)
{
Console.WriteLine("");
celciusSystem();
}
else if (choice == 2)
{
Console.WriteLine("");
farenheitSystem();
}
else if (choice == 3)
{
Console.WriteLine("");
kelvinSystem();
}
else {
Console.WriteLine("");
Console.WriteLine("Make sure u write a number between 1 and 3! No text!");
Console.WriteLine("");
showBegin();
decide();
}
}
static void secondPlay()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
}
// Begin code
static void showBegin()
{
Console.WriteLine("Welcom at the temperature calculator, pick the mode u prefer!");
Console.WriteLine("Press 1 for Celcius mode");
Console.WriteLine("Press 2 for Fahrenheit mode");
Console.WriteLine("Press 3 for Kelvin mode");
Console.WriteLine("Press the correct number and then hit the enter button!");
Console.WriteLine("");
}
// Temperature Calculators
static void celciusSystem()
{
Console.WriteLine("This is the Celsius calculator");
Console.Write("Enter the amount of celsius: ");
int celsius = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", celsius + 273);
Console.WriteLine("The temperature in Fahrenheit = {0}", celsius * 18 / 10 + 32);
}
static void farenheitSystem()
{
Console.WriteLine("This is the Fahrenheit calculator");
Console.Write("Enter the amount of Fahrenheit: ");
int Fahrenheit = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", (Fahrenheit + 459.67) / 1.8);
Console.WriteLine("The temperature in Celsius = {0}", (Fahrenheit - 32) / 1.8);
}
static void kelvinSystem()
{
Console.WriteLine("This is the Kelvin calculator");
Console.Write("Enter the amount of Kelvin: ");
int Kelvin = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Fahrenheit = {0}", Kelvin * 1.8 - 459.67);
Console.WriteLine("The temperature in Celsius = {0}", Kelvin - 273.15);
}
// End code
static void showEnd()
{
Console.WriteLine("");
Console.WriteLine("We hoped u enjoyed our application!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
So now my question, I made a class called second play. Within that class i tried to make a kind a statement that would ask the user if he or she wanted to "play" again. So if they write 1 he should loop the game again.
I have tried it with this
if (choice2 == 1)
{
while (choice2 == 1) {
Console.WriteLine("");
showBegin();
decide();
}
}
else {
Console.WriteLine("");
Console.WriteLine("Cheers!!");
}
}
then he actually worked but not the way I wanted to because if the user writes 1 it will loop the first thing all over again. So the user can't quit the game any more.
I want the application to ask after every trail if he or she wants to play again by typing 1 or 2.
You already know how to read lines from the console, you also know how to use if to compare booleans, so why don't you just apply this and check if they wrote a 1 or 2?
private bool playAgain()
{
int number = 2; //Invalid option: close game
Int32.TryParse(Console.ReadLine(), out number);
if (number == 1)
{
return true;
}
else if (number == 2)
{
return false;
}
else
{
Console.WriteLine("Unknown option, quitting!");
return false;
}
}
Then you just have to use that function to determine if they want to play again in a do-loop.
static void Main(string[] args)
{
showBegin(); //Show begin sequence
do
{
decide();
secondPlay();
} while(playAgain()); //Play again if they want to
showEnd(); //Show end sequence when they decided not to play
}
Pro tip: use a switch-case statement instead of multiple if-else statements.
You can use a do while loop, which serves you well in cases like yours, when you want to execute your loop at least once:
do {
Console.WriteLine("");
showBegin();
decide();
//Ask for choice2 here
}
while(choice2 == 1);
Console.WriteLine("");
Console.WriteLine("Cheers!!");
To enter game loop, it is most useful to start with simple while or do-while.
while( conditionToRun )
{
//run the program
if( userWantToExit )
conditionToRun = false;
}
Or
do
{
// run the program
} while ( !userWantToExit )
This code shows the most basic stuff to handle this.
To apply on Your game/program, use:
static void Main(string[] args)
{
bool userWantToEnd = false;
showBegin();
while( !userWantToEnd)
{
decide();
userWantToEnd = IsUserWillingToContinue();
}
showEnd();
}
And adjust the SecondPlay() method into something like IsUserWillingToContinue():
public bool IsUserWillingToContinue()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
return choice2 == 1;
}
Adding more info based on comment of #devRicher - You should split up a bit the code so it work in this way
bool runAgain = true;
Console.WriteLine("Begin info: (Hello this is XY game.)");
while(runAgain)
{
Console.WriteLine("You have 3 options: 1, 2, 3");
PickOptionAndRunTheCode();
bool runAgain = DoYouWantToContinue();
Console.Clear(); // clear the Console screen (next time You will see only options, not the text on first run).
}
I would recommend to get more knowledge about games to go to this page -> http://gameprogrammingpatterns.com/ (and read the book)
Check this pattern: Game Loop

Counting until a specific number and start again + backwards

The thing is, I want to be able to increase/decrease a variable (int) by pressing up and down arrow keys. But how do I manipulate the variable, so it goes from 3 to 1 and backwards from 1 to 3 again?
I'm using Visual C# express 2010 and it is a Windows Console application! Sorry for the trouble!
I'm desperately trying to get into C# and am struggling with such basic things. I'd be very grateful if someone could help me with this. I've got this far, this should become a menu on where the user can scroll through three options: 1- New Game // 2- Load Game and 3- Exit Game
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int iMOP = 0;
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.UpArrow){
}
else if (keyInfo.Key == ConsoleKey.DownArrow){
}
switch (iMOP)
{
case 0:
break;
case 1:
break;
case 2:
break;
}
}
}
}
Additional: I'll try to refresh the menu with Console.Clear, though I'll have to figure the counting issue.
I've translated it into this now: AND IT WORKS NOW THANKS FOR THE INPUT, GUYS!
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;
}
}
}
}
}
To "loop" the numbers; replace:
if (iMOP == 0)
{
iMOP = 3;
}
else if (iMOP == 4)
{
iMOP = 1;
}
with:
iMOP = (iMOP % 3) + 1;
% returns the remainder after division; so it can only return 0, 1, or 2. Then you add 1 to get the range 1, 2, and 3. Note this trick is exactly the same as the one you use to scale a random double:
int scaledRandom = (rand.NextDouble() % max) + min;

C# Making a Football Game Console Application

I have a C# Console application that I would like to write using this code but I have tried a couple of things and seem to run a block. I am trying to make a timer on a game at the top but the only way for me to print to the console and sort of keep it is by eliminating the Console.Clear from this Code. Is there a way that I can keep the Countdown timer at the top while Console.Clear is only active for the timer not everything in the console window?
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00?
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 10;
static void Main(string[] args)
{
timer.Elapsed+=timer_Elapsed;
timer.Start();
Console.Read();
}
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
Console.Clear();//here is where I disable and it prints out all the timer in the widow
// if I leave this console window it wipes out my print?
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Huddle ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Timeout");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}
}
}
Okay here is the extension of the code
I am having issues trying to keep my game on the bottom of the window and really trying to code the countdown timer to be active as soon as the game starts but also keeping my game selection print for the user any suggestions would help
{}....
++++++++++++++++++++++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 300;
private void Run()
{
Header();
Story();
timer.Elapsed += timer_Elapsed;
timer.Start();
// Console.ReadLine();
bool appRunning = true;
bool playerExists = false;
//bool drinkExists = false;
int userInput = 0;
//loop
while (appRunning)
{
Console.WriteLine("\n\n....................\n");
Console.WriteLine("What would you like to do?\n");
Console.WriteLine("1.)Choose Role 2.)Show Credits 3.)Exit Application");
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Console.WriteLine("Chose a player: ");
//take user input and ocnvert to string to int data type
userInput = Int16.Parse(Console.ReadLine());
//switch statement o flip through menu options
switch (userInput)
{
case 1:
//intelligence to monitor that we only make one sandwich per customer
if (playerExists == false)
{
Console.WriteLine("Does my sandwich exist? Answer is" + playerExists);
Console.WriteLine("Lets make you a snadwich, then shall we??\n");
//set default sandwich variable values
String Quarterback = "Quarterback";
String Runningback = "Runningback";
String Receiver = "Receiver";
//get type of bread from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Short, Run, Pass Long");
Quarterback = Console.ReadLine();
//get type of Option from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Left, Right, or Staight");
Runningback = Console.ReadLine();
//get type of jelly from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Long, Short, or Mid");
Receiver = Console.ReadLine();
//create an instance of the sandwichclass
Player myPlayer = new Player(Quarterback, Runningback, Receiver);
myPlayer.AboutPlayer();
playerExists = true;
}
{
Console.WriteLine("You've already made your role choice!");
}
break;
case 2:
ShowCredits();
break;
case 3:
appRunning = false;
break;
default:
Console.WriteLine("You have not chosen a valid option.");
Console.WriteLine("Please chose from the menu....");
break;
}//end switch
}//end of while
}//end of private void run
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
// Console.Clear();
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Time Out ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Huddle");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}//end ofprivatestaticvoidtimer
class Player
{
//set default vaulues for our sandwich type
private String Quarterback = "";
private String Runningback = "";
private String Receiver = "";
//build the constructor for the sandwich class
public Player(String Quarterback, String Runningback, String Receiver)
{
this.Quarterback = Quarterback;
this.Runningback = Runningback;
this.Receiver = Receiver;
}
public void AboutPlayer()
{
Console.WriteLine("You have made your selection!");
Console.WriteLine("As");
Console.WriteLine("Press enter to coninue...");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Console.ReadKey();
Program myProgram = new Program();
myProgram.Run();
Console.ReadLine();
}//endofmain
private void ShowCredits()
{
Console.Clear();
Console.WriteLine("An in-class assigment for Intro to Programming");
Console.WriteLine("Cesar Mojarro");
}
private void Header()
{
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("+++++++1967 Tackle Football Championships v.1.0 ++++++");
Console.WriteLine("++++++++++++++Studded Diamond Cup ++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++By IAM!+++++++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
Console.ReadKey();
}
private void Story()
{
Console.WriteLine("It's the year 1967 and in the First Quarter Steve Miller is running Quarterback for the Packs.");
Console.WriteLine("Young Styler is running Quarterback for the Texan Ranchers.");
Console.WriteLine("Your frontline is hung over from the party last nite, ouch! ");
Console.WriteLine("The team owner is ready to collect on the pay day from the Studded Diamond Cup");
Console.WriteLine("Don't let him replace you for a rookie!");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
Console.WriteLine("The Coin Toss is about to take place,\nyou are nervous and are about to take a chance at this tackle unit.");
Console.WriteLine("Rules are simple keep the ball running yards,\nstay head strong and keep your eye on defense!");
Console.WriteLine("Don't let them tackle you down and\nreturn you all the way to the goal line by allowing your apponent to score");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
}
}//endofProgram
}
Use Console.CursorLeft and Console.CursorTop to move the cursor to the line with the time, you can then overwrite that line with your new value.
private void UpdateTime(int i)
{
//Move to the first column.
Console.CursorLeft = 0;
//Move to the 4th row
Console.CursorTop = 3;
//Write your text. Extra spaces to overwrite old numbers
Console.Write(" Time Remaining: " + i.ToString() + " ");
}
You can be even more efficient by figuring out the column i is written to and just overwrite that.
private string _timeRemainingString = " Time Remaining: ";
private void UpdateTime(int i)
{
//Move to the first column that would have had numbers.
Console.CursorLeft = _timeRemainingString.Length;
//Move to the 4th row
Console.CursorTop = 3;
//overwrite just the number portion.
Console.Write(i.ToString() + " ");
}
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00
If i represents the number of seconds left in the game it the easiest solultion would be convert it in to a TimeSpan then you can use time span's formatting to get the format you want.
private void UpdateTime(int i)
{
Console.CursorLeft = _timeRemainingString.Length;
Console.CursorTop = 3;
var time = TimeSpan.FromSeconds(i);
//the `.ToString("c")` on a TimeSpan will give you a time in the format "00:00:00"
//you don't need the extra spaces anymore because the time will always be 8 digits long.
Console.Write(time.ToString("c"));
}

Categories