The Code

In this tutorial I will help you continue learning programming on your own by walking you through the code necessary to build a blackjack app.

Included is a link to my project which as the time of this writing I am still working on (and that’s  one of the wonderful things about github btw!)

As always, I recommend that you do not use my completed project unless you get stuck.

Therefore I would say that you should avoid copy and pasting any of code outlined here. As a matter of fact ,If you are doing this tutorial because you are new to coding there are many things you can learn with each line that you type!

We are going to be covering a lot of ground today and if you’re learning programming on your own there is supplemental post that I created which goes over the concepts covered here in detail.

Here is a link to that post if you would like to read it!

Ok so you found your way here! Lets get to point.. learning programming on your own!

We will be exploring some of the very basic concepts of C# and Visual Studio 2019.I will not be taking much time to explain the concepts here, as I have a supplemental post that covers most of  them in more detail.

Concepts Covered:

      • Variables – Variables allow you to name a value that is likely to change in your program for use throughout runtime.
      • Collections – Collections are groups of variables or objects that let you hold multiple values for use in your project.
      • The Console.Writeline() and Console.ReadLine() – The Console is a .net construct that lets you read and write text for display to the user. (This will be the main part of our program)
      • Basic loops / control flow – Loops let you perform an action (usually in conjunction with variables to complete actions in a program.)
      • Functions / methods / Sub-routines – Functions are sometimes referred to as methods or subs. With a function you can write a bit of code, name it and call the function to repeat the code contained with in. You will often construct a function to accept a couple variables or arguments that it will use when performing the function.
      • The random operator – This gets a random number between the a range that we set in code.
      • Basic Math functions and operators – In most any programming language there will be pre-defined operators for performing math or assignment tasks here are a few of the ones commonly used in C#.
        • Add + : Add two valuers together. (A + B)
        • Subtract – : Subtract one value from the other (A – B)
        • Assignment = : Assignment is for variables this means that the value on the left is being set to whatever is on the right .
          • int A = 1
          • String a = “this is a string”;
        • Comparison = = : This means we want to do a comparison
          • += : This means we want to ADD the the value on the right to the variable on the left
            • int a = 1
              a += 5 : this sets the value to 6 (1 + 5)

Review the Design

OK so let’s start with our design which we laid out in the previous post. I will include it here to make things easy: Something to note here, my code highlighter is not properly saving spacing so the finished app will look a little different than yours. Just let visual studio do the spacing for you, spacing is there to make code readable it doesn’t serve a function.

The game loop

    • Display a welcome message to the user.
    • When the game starts we will get 2 new cards for the player and 2 for the dealer
    • Display the dealers second card to the player (advanced only )
    • Total the players cards and display them
    • Ask the Player to type H for hit or S for stay
      • Accept a uppercase or lower case response
    • If the player chooses to “hit” another card will be drawn and the loop will continue until the player stays or busts
    • After the player decides to “stay” the dealer’s turn will commence
    • The dealer will follow Standard black jack rules
      • When the dealer has served every player
      • The dealer’s face-down card is turned up (Advanced version only )
      • If the total is 17 or more, the dealer must stand.
      • If the total is 16 or under, the dealer must hit.
      • The dealer must continue to take cards until the total is 17 or more, at which point the dealer must stand.
    • When the dealer stands, or busts the game is over.
    • If the dealer busts, the player wins
    • If the dealer does not bust the total of the two hands will be compared and the person with the highest total wins.
    • Ask the Player to quit or play again

Create a new Project

Create a new project

Choose .net console app

Name it BlackjackConsole (or something like that)

The editor will open and now you will be looking at Program.cs in the editing window.

Organizing our thoughts / planning for the code.

 

Usually when I start a program I like to review what I am building and in what order. Sometimes I do this in a separate document and sometimes I write it in comments in the app.

Today I’ll just write a plan here. Then we can start writing the actual code. This is just one more step toward learning programming on your own.

      • Create some variables to hold program state.
      • Greet the user. (Console.Writeline() )
      • Write code to generate a random number which will represent a card being dealt
      • Write a way to assign the output from the random to a card type
      • Let the user know what cards they got
      • Ask them if they want to hit or stay
      • Check for bust or 21
      • Play out the dealer hand according to standard rules
      • Do a comparison of the player hand vs the dealers
      • Announce the winner and then ask if they want to play again

Start the coding process

You will be working with a file which has one method Main(string[] args)

For the first part of this program we are going to write a method that Displays a Welcome message to the user. This will make use of the Console, a function, (which does not take any arguments and doesn’t return any values), the random function,  and our first loop.

Set up the variables to control the program .

using System;

namespace Blackjack
{
    class Blackjack

{

     static string[] playerCards = new string[11];
     //users to store the player choice (hit or stay)
     static string playerChoice = "";

     static int playerTotal = 0;
     static int cardCount = 1;
     static int dealerTotal = 0;
     static Random cardRandomizer = new Random();
     static string playAgain ="Y";

Set up main to call the first part of the game.

**Note** Here we are using a couple methods for the first time. When you call a method in C# , control moves to the definition of the method. (which can come later or be earlier in the program ) The relevant lines of code will be processed, and then when the method is finished, control will be passed back to where the call was made initially. You can also set up methods to return a value. When this happens you will often see that the method is used to set a variable.

If you see something like “total = GetTotalFromSomething(); ” don’t be freaked out. Just understand that we called the method to do some work, and are expecting it to complete the work and then return a value for us to use.

Below, you can see that we have methods for “StartGame() , StartGameLoop() and PlayAgain(). There is also a variable named playAgain. When looking at C# code it is important to remember that variables usually start with a lowercase letter and do not have parenthesis following them (as methods do ) .

Deal the cards, prompt the user , show a total and then call the main loop of the game.

static void Main(string[] args)
{
//Main loop: playagain is always yes unless they choose no
     while (playAgain.ToUpper() == "Y")
     {
     //Deal cards and display a welcome message
     StartGame();
    //handle the loop which plays out the users hand (Hit or stay)
    StartGameLoop();

    Console.WriteLine("Would you like to play again? (Y)es or (N)o?");
    PlayAgain();
}

Now let’s look at some of the method definitions!

Understanding methods will help you in learning programming on your own.

StartGame() is used to deal the cards and then calls a method DisplayWelcomeMessage() that displays a welcome message. We only call this from one point in the game so we didn’t NEED to make this a method but sometimes it makes things cleaner to do so.

static void StartGame()
{
     dealerTotal = cardRandomizer.Next(15, 22);
     playerCards[0] = DealCard();
     playerCards[1] = DealCard();
     DisplayWelcomeMessage();
}

private static void DisplayWelcomeMessage()
{
     Console.WriteLine("Welcome to Blackjack! You were dealt the cards : {0} and {1} ", playerCards[0], playerCards[1]);
     Console.WriteLine("Your playerTotall is {0} ", playerTotal);
}

Build a game loop

Next we have a method StartGameLoop() that is used to process the main functions of the game.

This method will ask the user if they would like to hit or stay , then loop until the user inputs a valid choice (do {} while() )

If the player chooses “H” then we call the Hit() method.

**note that the Hit() method calls itself over and over until the player chooses to stay**

If the player chooses S or stay then we start the process of validating the hand.

Reviewing our logic

The logic is simple:

If the player’s total is greater than the dealers AND neither of them have went over 21. you win.

If the player’s total is less than the dealers, you lose.

static void StartGameLoop()
{
do
{
Console.WriteLine("Would you like to (H)it or (S)tay?");
playerChoice = Console.ReadLine().ToUpper();
}
while (!playerChoice.Equals("H") && !playerChoice.Equals("S"));

if (playerChoice.Equals("H"))
{
//hit will get them a card / check the total and ask for another hit
Hit();
}

if (playerChoice.Equals("S"))
{
if (playerTotal > dealerTotal && playerTotal <= 21)
{
Console.WriteLine("Congrats! You won the game! The dealer's playerTotal was {0} ", dealerTotal);
}
else if (playerTotal < dealerTotal)
{
Console.WriteLine("Sorry, you lost! The dealer's playerTotal was {0}", dealerTotal);
}
}

}

The Hit method

The Hit() method is out next one to examine. It is in charge with getting the player a new card, checking if they busted or got a blackjack , and ultimately asking the user if they would like to hit again. Then, we perform a loop continuing to ask the player if they want more cards until they win , lose, or opt to stay.

static void Hit()
{
cardCount += 1;
playerCards[cardCount] = DealCard();
Console.WriteLine("You card is a(n) {0} and your new Total is {1}. ", playerCards[cardCount] , playerTotal);

if (playerTotal.Equals(21))
{
Console.WriteLine("You got Blackjack! The dealer's Total was {0}. ", dealerTotal );

}
else if (playerTotal > 21)
{
Console.WriteLine("You busted! Sorry!. The dealer's Total was {0}",dealerTotal );

}
else if (playerTotal < 21)
{
do
{
Console.WriteLine("Would you like to hit or stay? h for hit s for stay");
playerChoice = Console.ReadLine().ToUpper();
}
while (!playerChoice.Equals("H") && !playerChoice.Equals("S"));
if (playerChoice.ToUpper() == "H")
{
Hit();
}

  }
}

Dealing cards

Next we have the DealCard()  method this one handles getting one card for the player and giving it a value.

static string DealCard()
{
int cards = cardRandomizer.Next(1, 14);
string Card = GetCardValue(cards);
return Card;
}

Next up is the method GetCardValue() which returns the name of the card and handles processing the players new total. An important thing to note here is that in this method we use a switch statement.

A switch statement is like an if statement, but handles a result that could be many different values. In the same fashion as an if statement, the switch statement simply proceeds until it finds a match. (In this case we are matching the “Case”)

Equally important,the break statement is then used to tell the program to break from the switch and return the processing.

You typically use a switch when you only want one possible value to be processed.

Note that in each case we are adding the value of the card to the player total this is how we know what the players current total is.

static string GetCardValue(int cards)
{
string Card;
switch (cards)
{
case 1:
Card = "Two"; playerTotal += 2;
break;
case 2:
Card = "Three"; playerTotal += 3;
break;
case 3:
Card = "Four"; playerTotal += 4;
break;
case 4:
Card = "Five"; playerTotal += 5;
break;
case 5:
Card = "Six"; playerTotal += 6;
break;
case 6:
Card = "Seven"; playerTotal += 7;
break;
case 7:
Card = "Eight"; playerTotal += 8;
break;
case 8:
Card = "Nine"; playerTotal += 9;
break;
case 9:
Card = "Ten"; playerTotal += 10;
break;
case 10:
Card = "Jack"; playerTotal += 10;
break;
case 11:
Card = "Queen"; playerTotal += 10;
break;
case 12:
Card = "King"; playerTotal += 10;
break;
case 13:
Card = "Ace"; playerTotal += 11;
break;
default:
Card = "2"; playerTotal += 2;
break;
}
return Card;
}

 

 

Play Again?

In this section, we have the PlayAgain() method.

This method simply prompts the user to ask if they would like to play again.

If they say yes, then we reinitialize our starting variables. (so that they don’t retain any values from the previous run)

Similarly, if they choose no, then we just exit the program.

static void PlayAgain()
{

//Loop until they make a valid choice
do
{
playAgain = Console.ReadLine().ToUpper();
}
while (!playAgain.Equals("Y") && !playAgain.Equals("N"));

if (playAgain.Equals("Y"))
{
Console.WriteLine("Press enter to restart the game!");
Console.ReadLine();
Console.Clear();
dealerTotal = 0;
cardCount = 1;
playerTotal = 0;
}
else if (playAgain.Equals("N"))
{
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Enter)
{
Environment.Exit(0);
}
else
{
Console.Read();
Environment.Exit(0);
}
}
}
}
}

 

And that’s it for today! In this lesson we have learned quite a few C# .net concepts. Therefore you have taken another step toward learning programming on your own.

 

Leave a Reply

Your email address will not be published.