Counting until a specific number and start again + backwards - c#

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;

Related

Minigame blackjack

For 2 players in a console app the game draws numbers from 1 to 10 instead of cards. With a do-while loop asking the question, whether you want to choose a card. I have a problem with giving the right word after the answer not, because then the loop should be broken and when it gives break it asks still and how to return it exits the program at the end the program says who won.
`enter code here` Console.WriteLine("now the first player's turn");
int number = 0;
Random r = new Random();
` do
{
Console.WriteLine("Are you downloading the card?");
string odp = Console.ReadLine();
switch (odp)
{
case "yes":
int rInt = r.Next(1, 10);
number += rInt;
Console.WriteLine(number);
break;
case "not":
?
}
if (number >= 22)
{
Console.WriteLine("The player 1 lost with {0} pkt", number);
break;
}
} while (number < 22);
Here is a version that seems to do what you need with your current code.
I add a boolean condition (bool continuePlaying) to stay inside the "do loop" or not.
using System;
namespace BlackJack
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("First player's turn");
int number = 0;
Random random = new Random();
bool continuePlaying = true;
do
{
Console.WriteLine("Are you downloading the card? [Y]es/[N]o");
string userAnswer = Console.ReadLine();
switch (userAnswer.ToLower())
{
case "y":
int randomNumber = random.Next(1, 10);
number += randomNumber;
Console.WriteLine($"Your total of points is: {number}");
continuePlaying = true;
break;
case "n":
Console.WriteLine($"Your total of points is: {number}");
continuePlaying = false; // Stop playing
break;
default:
Console.Clear();
Console.WriteLine("Please choose [Y]es or [N]o");
continuePlaying = true;
break;
}
} while (number < 22 && continuePlaying == true);
if (number <= 21)
{
Console.WriteLine($"You end the game with a total of {number} points");
}
else
{
Console.WriteLine($"The player 1 lost with {number} points");
}
Console.ReadLine();
}
}
}

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.)

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

C# Menu System will not work

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");
}
}
}
}
}

How do I jump into another menu without nesting unnecessarily?

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);
}
}
}

Categories