Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - 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();
  }
  }
}
question from:https://stackoverflow.com/questions/65834092/using-continue-and-break-statements-properly-for-a-game

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. 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.
  2. 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.
  3. 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)
  4. 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).
  5. 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.
  6. 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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...