using continue and break statements properly for a game - c#

I have to make a card game like HiLo where you enter your cash amount, you get two cards, and then you bet. if the third randomly generated card is between the other two, you add that money to your total and if its not you lose that money. One thing the code is supposed to do is if you don't like the two cards you are given at the beginning you should be able to enter 0 and they give you new cards. My biggest problem comes from when I enter 0 it gives me two new cards and then asks how much I want to put up and when I enter that number it basically ignores the new bet money and asks me again. essentially i have to write twice the betmoney for it to work, how do I fix that.
using System;
//find how to print dollar signs
class MainClass {
public static void Main (string[] args) {
var rnd = new Random();
int card1, card2, card3;
int playermoney = 0;
int betmoney = 0;
string exit = "";
Console.WriteLine("HiLo Card Game");
Console.Write("Enter the starting cash amount: $");
playermoney = Convert.ToInt32(Console.ReadLine());
while(exit!="n"){
card1 = rnd.Next(1,15);
card2 = rnd.Next(1,15);
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", card1, card2);
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
if (betmoney>=0){
if (betmoney == 0){
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", rnd.Next(1,15), rnd.Next(1,15));
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
continue;
}//end if 0
card3 = rnd.Next(1,15);
Console.WriteLine("Your card is a {0}", card3);
if(card1<card2){
if((card3>card1 && card3<card2)){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}//end winner if
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
if (card1>card2){
if(card3>card2 && card3<card1){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
}
else{
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}
Console.Write("Play Again? <y/n> ");
exit = Console.ReadLine();
Console.Clear();
}
}
}

I think what you want to do is continue right away if the betAmount is 0 (or less than zero), rather than trying to pick new cards again inside the main loop:
if (betMoney < 1) continue;
Some other thoughts:
Additionally, you should use int.TryParse to parse the integer input because Convert.ToInt32 will throw an exception if the input is not a valid integer. This way we can use TryParse as an if condition and continue to ask them for a valid number.
Random should almost always be declared as a class field rather than a local variable. In this case it doesn't matter, but it's a good habit to get into.
We can use Math.Max and Math.Min to determine which of the two random cards are the largest and smallest, to avoid the repetitive code (the code in the if (card1 > card2) block is repeated for card2 > card1)
We can use Math.Abs to determine the absolute value of the difference of card1 and card2, so if they are the same card or are sequential, we can just continue the loop (there is no chance to win in those cases).
We can move the Console.Clear inside the loop so after they enter the initial playerMoney amount, we always see the same screen while playing.
We can use Console.ReadKey() to get a single key from the user (for y/n), and then use the .Key property to determine if it's an n or N.
Here's some code with these ideas implemented:
private static Random rnd = new Random();
static void Main()
{
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.Write("Enter the starting cash amount: $");
int playerMoney;
while (!int.TryParse(Console.ReadLine(), out playerMoney) ||
playerMoney < 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a positive number for cash amount: $");
Console.ResetColor();
}
while (true)
{
// Draw two random cards
int card1 = rnd.Next(1, 15);
int card2 = rnd.Next(1, 15);
// Start the loop again if there is not at least
// one card available between card1 and card2
if (Math.Abs(card1 - card2) < 2) continue;
// Determine the min and max of the two random cards
var minCard = Math.Min(card1, card2);
var maxCard = Math.Max(card1, card2);
Console.Clear();
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.WriteLine("Cash balance is: ${0}", playerMoney);
Console.WriteLine("{0} - {1}", minCard, maxCard);
Console.Write("Enter the amount you want to bet: $");
int betMoney;
while (!int.TryParse(Console.ReadLine(), out betMoney))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a valid number for bet amount: $");
Console.ResetColor();
}
// If the bet amount is negative or 0, restart
// the loop so they can get new cards
if (betMoney < 1) continue;
// Draw a card for the player
int playerCard = rnd.Next(1, 15);
Console.WriteLine("Your card is: {0}", playerCard);
// If the players card is between the random cards, they win
if (playerCard < maxCard && playerCard > minCard)
{
playerMoney += betMoney;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("WINNER! New Balance is ${0}", playerMoney);
Console.ResetColor();
}
else
{
playerMoney -= betMoney;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("LOSER! New Balance is ${0}", playerMoney);
Console.ResetColor();
if (playerMoney <= 0)
{
Console.WriteLine("--------------");
Console.Write("Game over. Press any key to exit...");
Console.ReadKey();
break;
}
}
Console.Write("Play Again? <y/n>: ");
if (Console.ReadKey().Key == ConsoleKey.N) break;
}
}

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

How to put Pin in 4 digits only when entering a PIN and how to verified it?

I don't know the codes as I'm a beginner in c#, so could anyone help me with these? I want my pin to enter in 4 digits only and re verified the pin to continue in the menu?
{
class program
{
public static void Main()
{
int amount = 1000, deposit, withdraw;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter Your Pin Number ");
pin = int.Parse(Console.ReadLine());
while (true)
{
Console.WriteLine("********Welcome to ATM Service**************\n");
Console.WriteLine("1. Check Balance\n");
Console.WriteLine("2. Withdraw Cash\n");
Console.WriteLine("3. Deposit Cash\n");
Console.WriteLine("4. Quit\n");
Console.WriteLine("*********************************************\n\n");
Console.WriteLine("Enter your choice: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount);
break;
case 2:
Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: ");
withdraw = int.Parse(Console.ReadLine());
if (withdraw % 100 != 0)
{
Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
}
else if (withdraw > (amount - 500))
{
Console.WriteLine("\n INSUFFICENT BALANCE");
}
else
{
amount = amount - withdraw;
Console.WriteLine("\n\n PLEASE COLLECT CASH");
Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount);
}
break;
case 3:
Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT");
deposit = int.Parse(Console.ReadLine());
amount = amount + deposit;
Console.WriteLine("YOUR BALANCE IS {0}", amount);
break;
case 4:
Console.WriteLine("\n THANK U USING ATM");
break;
}
}
Console.WriteLine("\n\n THANKS FOR USING OUT ATM SERVICE");
}
}
}
I suggest something like this:
// read size (4) digits
private static string ReadPin(int size = 4) {
StringBuilder sb = new StringBuilder(size);
while (sb.Length < size) {
var key = Console.ReadKey(true); // we don't want to show the secret pin on the screen
// Uncomment, if you want to let user escape entering the PIN
// if (key.Key == ConsoleKey.Escape) {
// return "";
// }
if (key.KeyChar >= '0' && key.KeyChar <= '9') {
sb.Append(key.KeyChar);
Console.Write('*'); // let's show * instead of actual digit
}
}
return sb.ToString();
}
...
// private: there's no need for Main to be public
private static void Main() {
...
Console.WriteLine("Enter Your Pin Number ");
int pin = int.Parse(ReadPin());
If you want to verify the given string (pin) which is expected to be of length size, you can try either Linq
using System.Linq;
...
string pin = ...
int size = 4;
bool isValidPin = pin.Length == size && pin.All(c => c >= '0' && c <= '9');
Or regular expressions:
using System.Text.RegularExpressions;
...
bool isValidPin = Regex.IsMatch(pin, $"^[0-9]{{{size}}}$");
int password;
int repassword
Do{
Console.WriteLine("\n Enter the password");
password= int.Parse(Console.ReadLine()); //first password
string ps = Convert.ToString(password);
}while(ps.Length!=4) //request the password if is not composed by 4 digits
//menu part//
Do{
Console.WriteLine("\n Reinsert the password");
repassword= int.Parse(Console.ReadLine()); //reinsert password
} while(repassword!=password)

C# How do I error check the input ensuring only integers between 1-100 are accepted

I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}

Breaking out of a loop when user inputs quit or exit c#

I'm having trouble with looping my program so that it breaks out of the loop if user enters "quit" or "exit".
When I type any string, my program crashes as it tries to parse the string input to an int. Any advice?
namespace DiceRolling
{
/* We’re going to write a program that makes life easier for the player of a game like this. Start the
program off by asking the player to type in a number of dice to roll.Create a new Random
object and roll that number of dice.Add the total up and print the result to the user. (You should
only need one Random object for this.) For bonus points, put the whole program in a loop and allow them to keep typing in numbers
until they type “quit” or “exit”. */
class DiceRolling
{
static void RollDice(int numTries)
{
Random random = new Random();
//Console.Write("Please enter the number of dice you want to roll: ");
//int numTries = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int dieRoll;
for (int i = 1; i <= numTries; i++)
{
dieRoll = random.Next(6) + 1;
Console.WriteLine(dieRoll);
sum += dieRoll;
}
Console.WriteLine("The sum of your rolls equals: " + sum);
}
static void Main(string[] args)
{
while (true)
{
Console.Write("Please enter the number of dice you want to roll: ");
string input = Console.ReadLine();
int numTries = Convert.ToInt32(input);
//bool isValid = int.TryParse(input, out numTries);
RollDice(numTries);
Console.ReadKey();
if (input == "quit" || input == "exit")
break;
}
}
}
}
Tigrams is pretty close, this is slightly better
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
while (input != "quit" && input != "exit")
{
int numTries = 0;
if (int.tryParse(input, out numTries)
{
RollDice(numTries);
}
Console.Write("Please enter the number of dices you want to roll: ");
input = Console.ReadLine();
}
tried to make it as similar as possible to what you have
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
int numTries;
if (int.TryParse(input, out numTries))
{
RollDice(numTries);
}
else if(input == "quit" || input == "exit")
{
break;
}
}
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
if (input == "quit" || input == "exit") //check it immediately here
break;
int numTries = 0;
if(!int.TryParse(input, out numTries)) //handle not valid number
{
Console.WriteLine("Not a valid number");
continue;
}
RollDice(numTries);
Console.ReadKey();
}
Try int numTries =int.Parse(input != null ? input: "0");

need help on creating a counter with a total, number enter, and average

The requirement are:
create an application that will allow the user to enter numbers and
provide the average of the numbers entered. The user will be allowed to enter as many numbers as they choose. After each entry we will display the current average.
Keep repeating until the user decides to quit.
I want to user to keep entering number until they type "q" to quit. Please help.
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
total += Convert.ToInt32(input);
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
while (input.ToUpper() == "Q");
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
Console.ReadKey();
Put the Console.ReadLine inside the loop -- and put the writing of the total/average after calculating those numbers.
Also, you might want to validate the input, instead of assuming it is a number -- use int.TryParse.
do
{
Console.WriteLine("Enter a number of Q to quit", input);
input = Console.ReadLine();
int val;
if (int.TryParse(input, out val))
{
total += val;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
}
while (input.ToUpper() != "Q");
There are three points needs to be corrected.
numbersEntered is 0 in the first calculation. You should pre-increment it while dividing by it.
also in the condation of while loop, it should be input.ToUpper() != "Q" instead of input.ToUpper() == "Q".
After correcting above two things your current code is calculating the average but it clearing the console after printing it. So, you should want after printing it by Console.Read();
Following is the code corrected:
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
int valueEntered;
if (int.TryParse(input, out valueEntered))
{
total += valueEntered;
average = (total / ++numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
}
}
while (input.ToUpper() != "Q");
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Simply a typo(?) Your while needs to be:
...
while (input.ToUpper() != "Q");
That is != instead of ==.
Minimalistic solution:
int nTotal = 0;
double avg = 0;
string input;
while ((input = Console.ReadLine()).ToUpper() != "Q")
{
int number = int.Parse(input);
avg += (number-avg) / ++nTotal;
Console.WriteLine("Total numbers entered: {0}. Average: {1}", nTotal, avg);
}

Categories