Minigame blackjack - c#

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

Related

using continue and break statements properly for a game

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

console application where the user has 5 tries to guess number between 1 and 100

I have created a console application where the user has 5 tries to guess number between 1 and 100. After 5 guesses the game ends, but I don’t know how to introduce at the 5th wrong intent something like “you have achieved maximum of guesses! The answer was number (X). I have tried different ways ,but is not working. This is my program
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
}
}
}
Here some Sample code
This might help
for( i=10;i>0 ; i--) {
System.out.println(" === you have " + i +" Guesses left ===");
int guess = scanner.nextInt();
if (random_number < guess) System.out.println("Smaller than guess " + guess);
if (random_number > guess) System.out.println("Greater than guess " + guess);
if (random_number == guess)
{
result = true;
break;
}
}
if (result)
{
System.out.println("You WON in "+(10-i) +" tries ");
System.out.println("******* CONGRATULATIONS **************************************");
System.out.println("*********************** YOU WON **********************");
}
else
{
System.out.println("The random number was "+random_number);
System.out.println("************************** OPPS You loose **************************************** ");
System.out.println("You are near it TRY Next time ************ GOOD LUCK ");
System.out.println("You are near it TRY Nexttime***********NEXTTIME********");
}
}
If that's all your program does, you can do the following trick. Print your message after the for loop, but now the problem is that you get the message in all cases. The trick is to return from the Main (instead of breaking the loop) on a correct guess:
Console.WriteLine("You got it!");
return;
If you've some other code to execute that returning from Main won't be a good solution, you can do the following:
Create a variable before the for loop. Let's call it isCorrectAnswer and set it to false in the beginning.
At the point where he answers correctly, set isCorrectAnswer to true before breaking the loop.
After the loop, check for that variable:
if (!isCorrectAnswer)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}.");
}
You have to have an int outside of your loop like this : int wrongAnswersCount = 0;
When the user enter a wrong number you
should add one unit to your variable wrongAnswersCount++;
In the start of the loop, you should check if the user reached the maximum amount of gueses or not, if yes break the loop and say the answer.
Your code will be something like this :
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
int wrongAnswersCount = 0;
for (var i = 0; i < 5; i++)
{
if(wrongAnswersCount == 5)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}");
break;
}
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
wrongAnswersCount++;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number && i!=5)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
Console.WriteLine(" the maximam guse");
}
}
//Try this one

C# Play Again Number Game

I'm trying to implement the ability for the user to input Y or N to play the game again or exit, but I'm struggling to get my head round it without a massive rewrite of the code logic... I'm just getting back into C# today and am a beginner so please go easy on me :) I've already got the userContinue string ready and just want to enter a simple way of repeating the game and adding on ways of keeping score (slowly improving the game)
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do
{
PlayGame();
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
public static voic PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
string userContinue;
bool correctGuess = false;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
userGuess = int.Parse(Console.ReadLine());
while (correctGuess == false)
{
if (userGuess == randNum)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
correctGuess = true;
}
if (userGuess > randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to high!");
correctGuess = false;
}
else if (userGuess < randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to low!");
correctGuess = false;
}
}
}
}
}
It would help if you put your game logic in its own method. Say PlayGame(). Then you can simply write:
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
Also, you can simplify your logic if you make an "infinite" loop and break out of it with break; when the guess is correct.
You can read and parse the user input at the beginning of each loop.
Setting the user score the number of incorrect guesses and the red console color can be done only once also.
Tested and working code:
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
private static void PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
while (true) {
userGuess = int.Parse(Console.ReadLine());
if (userGuess == randNum) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
break;
}
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
if (userGuess > randNum) {
Console.WriteLine("Wrong guess again, to high!");
} else { // Must be userGuess < randNum
Console.WriteLine("Wrong guess again, to low!");
}
}
}
}
}

Guessing Game C# Enter

I have a question, how to set the condition that if the user presses "Enter" when guessing a number, the program would ask "Enter a number"!
Program randomNumberA = new Program();
int r = randomNumberA.RandomNumber();
do
{
Console.WriteLine("Take a guess.\n");
string n = userNumberA.UserNumber();
int num;
int.TryParse(n, out num);
ConsoleKeyInfo key = Console.ReadKey();
if (IsAllDigits(n))
{
if (num > r)
{
Console.WriteLine("Your guess is too high!\n");
userGuess++;
}
if (num < r)
{
Console.WriteLine("Your guess is too low!\n");
userGuess++;
}
if (num == r)
{
Console.WriteLine($"Good job, {name}! You guessed my number in {userGuess} guesses!");
break;
}
}
else if (!IsAllDigits(n) || string.IsNullOrEmpty(n) || !char.IsNumber(key.KeyChar))
{
Console.WriteLine("Please enter the correct number!");
continue;
}
} while (userGuess <= USER_LIMIT);
if (userGuess > USER_LIMIT)
{
Console.WriteLine("Game Over!");
}
This logic checks the game, but still does not work if the user presses the "Enter" button
The code you've posted is slightly incomplete, but you're comparing the result of userNumberA.UserNumber() to r and not using key until the very last else if condition, which is confusing.
I think your logic can be changed slightly. Here is a sample with some hard-coded values that you should be able to leverage in your existing code:
private static Random _random = new Random();
static void Main(string[] args)
{
// Pick a random number between 1 and 100 for the user to guess
int secretNumber = _random.Next(1, 101);
int USER_LIMIT = 3;
int userGuess = 0;
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
while (userGuess < USER_LIMIT)
{
userGuess++;
Console.Write("Guess a number between 1 and 100: ");
int num;
if (int.TryParse(Console.ReadLine(), out num))
{
if (num > secretNumber)
{
Console.WriteLine("Your guess is too high!\n");
}
else if (num < secretNumber)
{
Console.WriteLine("Your guess is too low!\n");
}
else
{
Console.WriteLine($"\nGood job, {name}! That only took {userGuess} guesses!");
break;
}
}
else
{
Console.WriteLine("Please enter a valid number!");
}
}
Console.WriteLine("\nGame Over!");
if (userGuess == USER_LIMIT) Console.WriteLine($"\nThe number was: {secretNumber}");
GetKeyFromUser("\nDone! Press any key to exit...");
}

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
}

Categories