Skip to main content

Command Palette

Search for a command to run...

Deal from a deck of cards in C#

Updated
3 min read
Deal from a deck of cards in C#

This post is a the next step from my other posts "Creating a deck of cards in C#" and "Shuffling an Array in C#". So now that I had a deck of cards and the deck could be shuffled, I needed to find a way to deal the cards to the players in the game. Again I knew I was using arrays, so it needed to work with this. The examples I had found were more complex than what I was learning so I needed to figure out a way to deal the cards with what I knew and understood already.

Why was I doing this?

I needed to take cards from the array of cards in the deck and place a certain amount of them in an array. This seems like it would be quite simple to do based on the fact that I need to take some cards from one place and put them somewhere else. However, this is not the case.

Problem 1

The first issue I encountered with my code was that it kept adding new cards to the same position, so if there was a card already in a place it would just overwrite the original in that place. To counter this problem I set a condition that if the card was null then place the card at the next blank index in the array.

for (int cardIndex = 0; cardsDealt != amount && cardIndex < Cards.Length; cardIndex++)
  {
      if (Cards[cardIndex] == null) 
      {
          cardIndex++;
          continue;
      }

      tempCardsToDeal[cardsDealt] = Cards[cardIndex];
      Cards[cardIndex] = null;
      cardsDealt++;
  }

Giving cards to the Players

Dealing cards from the deck led me to the next method of my program, which was giving these cards to the player's hand. To do this I created an array of cards called Hand, this hand would then hold the cards dealt to the player.

Problem 2

I ran into an issue similar to the deal cards method, except in this case the cards duplicated over all of the available/null array objects. For example, if you wanted 2 cards to be dealt, it would deal these cards for the length of the array, so cards 1 & 2, were duplicating for 10 card spaces in the Hand array. To correct this issue I set a condition to check if the index was null, and if it was to place a new card in that space, but if the index was not null it would skip this and go to the next free array before dealing a card.

My learning...

  • Index outside the bounds of the array exceptions: From creating the deck of cards, I learnt about checking the indexes of an Array before something is added. My main problems included Array indexes being overwritten and filling an entire Array with the same values. Knowing this now will save me a lot of frustration in the future when I am using or adding to an Array.

  • Null reference exceptions: I learned that associating this problem with real-life problem, I used an actual deck of cards, helped me see the problem more clearly and was a way of problem solving.