c-sharp

Modeling Practice: UNO in C# Part 3 - Final Steps and Playing The Game

Note: This post is the third in a three-part series which attempts to model the card game UNO as a C# application. Here's Part One and Part Two. You may want to use the GitHub repository to follow along.

In the previous parts of this series we first saw how to play UNO and how to model the cards and moved on to how to model the player behavior. In this post, the last part of the series, we're going to take the results from the first two parts and combine them together to make a fully-working UNO-playing robot.

Well, UNO-playing C# application anyway. What? I can dream.

The Game Manager

The most critical component that we haven't yet built is a class called GameManager. In a real UNO game, the players themselves are responsible for keeping track of everybody else following the rules. However, in our model, we'll need a non-player class to do this, as well as control the game flow and keep track of which player's turn is next.

Here's the skeleton of the GameManager class. The next step will be to establish what each of these methods actually do.

public class GameManager  
{
    public List<Player> Players { get; set; }
    public CardDeck DrawPile { get; set; }
    public List<Card> DiscardPile { get; set; }

    public GameManager(int numPlayers) { }
    public void PlayGame() { }
    private void AddToDiscardPile(PlayerTurn currentTurn) { }
}

Creating the Game

The first method is just the GameManager class's constructor, which we will use to set up the game being played. The only input to this method is an int numPlayers, which is the number of players that will be playing the game.

Given the number of players, the GameManager must set up the game, which consists of:

  1. Creating the deck of cards.
  2. Dealing seven cards to each player.
  3. Placing a single card from the draw pile into the discard pile.

Here's how our constructor does this:

public GameManager(int numPlayers)  
{
    Players = new List<Player>();
    DrawPile = new CardDeck();
    DrawPile.Shuffle();

    //Create the players
    for (int i = 1; i <= numPlayers; i++)
    {
        Players.Add(new Player()
        {
            Position = i
        });
    }

    int maxCards = 7 * Players.Count;
    int dealtCards = 0;

    //Deal 7 cards to each player
    while(dealtCards < maxCards)
    {
        for(int i = 0; i < numPlayers; i ++)
        {
            Players[i].Hand.Add(DrawPile.Cards.First());
            DrawPile.Cards.RemoveAt(0);
            dealtCards++;
        }
    }

    //Add a single card to the discard pile
    DiscardPile = new List<Card>();
    DiscardPile.Add(DrawPile.Cards.First());
    DrawPile.Cards.RemoveAt(0);

    //Game rules do not allow the first discard to be a wild.
    while(DiscardPile.First().Value == CardValue.Wild || DiscardPile.First().Value == CardValue.DrawFour)
    {
        DiscardPile.Insert(0, DrawPile.Cards.First());
        DrawPile.Cards.RemoveAt(0);
    }

    //And now we're ready to play!
}

With all that setup out of the way, we can finally let GameManager start an actual game!

Playing the Game

GameManager kicks off the game by telling Player 1 to take his turn. Play must then proceed (to Player 2, then Player 3, so on) until somebody plays a Reverse card. At that point, we need GameManager to note that a Reverse card was played and reverse the turn order.

GameManager also needs to stop the game when a player no longer has any cards in his/her hand.

We can implement the actual playing of the game using the PlayGame() and AddToDiscardPile() methods like so:

public void PlayGame()  
{
    int i = 0;
    bool isAscending = true;

    //First, let's show what each player starts with
    foreach (var player in Players)
    {
        player.ShowHand();
    }

    //Game won't start until user presses Enter
    Console.ReadLine();

    //We need a "mock" PlayerTurn representing the first discard
    PlayerTurn currentTurn = new PlayerTurn()
    {
        Result = TurnResult.GameStart,
        Card = DiscardPile.First(),
        DeclaredColor = DiscardPile.First().Color
    };

    Console.WriteLine("First card is a " + currentTurn.Card.DisplayValue + ".");

    //Game continues until somebody has no cards in their hand
    while(!Players.Any(x => !x.Hand.Any()))
    {
        //If the draw pile is getting low, shuffle the discard pile into the draw pile
        if(DrawPile.Cards.Count < 4)
        {
            var currentCard = DiscardPile.First();

            //Take the discarded cards, shuffle them, and make them the new draw pile.
            DrawPile.Cards = DiscardPile.Skip(1).ToList();
            DrawPile.Shuffle();

            //Reset the discard pile to only have the current card.
            DiscardPile = new List<Card>();
            DiscardPile.Add(currentCard);

            Console.WriteLine("Shuffling cards!");
        }

        //Now the current player can take their turn
        var currentPlayer = Players[i];
        currentTurn = Players[i].PlayTurn(currentTurn, DrawPile);

        //We must add the current player's discarded card to the discard pile.
        AddToDiscardPile(currentTurn);

        //When somebody plays a reverse card, we need to reverse the turn order
        if (currentTurn.Result == TurnResult.Reversed)
        {
            isAscending = !isAscending;
        }

        //Now we figure out who has the next turn.
        if (isAscending)
        {
            i++;
            if (i >= Players.Count) //Reset player counter
            {
                i = 0;
            }
        }
        else
        {
            i--;
            if (i < 0)
            {
                i = Players.Count - 1;
            }
        }        
    }

    //Let's see who won the game!
    var winningPlayer = Players.Where(x => !x.Hand.Any()).First();
    Console.WriteLine("Player " + winningPlayer.Position.ToString() + " wins!!");

    //Finally, calculate and display each player's score
    foreach(var player in Players)
    {
        Console.WriteLine("Player " + player.Position.ToString() + " has " + player.Hand.Sum(x => x.Score).ToString() + " points in his hand.");
    }
}

private void AddToDiscardPile(PlayerTurn currentTurn)  
{
    if (currentTurn.Result == TurnResult.PlayedCard
            || currentTurn.Result == TurnResult.DrawTwo
            || currentTurn.Result == TurnResult.Skip
            || currentTurn.Result == TurnResult.WildCard
            || currentTurn.Result == TurnResult.WildDrawFour
            || currentTurn.Result == TurnResult.Reversed)
    {
        DiscardPile.Insert(0, currentTurn.Card);
    }
}

Whew! We are finally done with our code. All that's left to do now is to run a sample game!

Running a Sample Game

With all the code in place, let's run the app a few times to make sure it works the way we think it does.

The first time we boot the app (there's a complete working version over on GitHub), we'll see something like this:

Well well, looks like Player 3 has a pretty good hand, what with all the wilds. But, let's run the app to see how everyone does.

And, sure enough, Player 3 ends up winning the game. Those wilds help.

Drawbacks of This Model

As I've said many times throughout this series, the point of those posts is not to model UNO precisely, the point is to take a complex real-world problem and break it down into smaller, more manageable little problems.

That said, I can identify a few ways in which, given unlimited time, I might improve this model:

  • Different player "personalities": Not every player is going to be a stupid jackass. I'd like to model different kinds of player strategy (e.g. offensive vs. defensive, hold wilds vs play them, etc.).
  • A GUI: I mean, I know the hardcore programmers among us LOVE them some command line, but really this could use a GUI to make it pop.
  • Rules modification: Different UNO sets use different kinds of rules, and I love to find a way to model lots of different rules and have the players react to them.

That said, I'm pretty darn happy with how this turned out.

Summary

The point of modeling practice is to practice. Sounds obvious, I know, but I firmly believe that the difficulty in creating complex software programs is not writing the code, but in getting the correct requirements. Modeling practice helps us consider all possibilities, and when we do it against a known game like UNO (or Candy Land or Minesweeper) we have a distinct set of rules to work against, something we often lack in real-world projects.

As always, feel free to leave any comments you may have (good or bad) in the comments section below, and check out the GitHub repository and maybe even run the app a few times. I'm quite proud of how it turned out.

Happy Coding!

Modeling Practice: UNO in C# Part 2 - Player Behavior

Note: This post is the second in a three-part series which attempts to model the card game UNO as a C# application. Here's Part One. You may want to use the GitHub repository to follow along.

Now that we have modeled the cards and the draw pile, we come to the first really tricky part of this modeling practice: we must model the players of the game AND how they will behave during the game itself.

The first part (modeling the players themselves) is simpler, and so we will do it first. A "player" in this game is really just a set of cards (the "hand"), the position that the player is sitting in (first, second, third, etc.) and the logic the player uses to decide which card to play. The simplest possible player class would then look like this:

public class Player  
{
    public List<Card> Hand { get; set; }

    //This determines the starting turn order
    public int Position { get; set; } 

    public Player()
    {
        Hand = new List<Card>();
    }
}

The problem with this simple class is that it leaves out the logic the player must use to determine which card s/he wants to play. That logic is not simple, and in my model it takes quite a few steps to work out.

Assumptions

First, we need to make some critical assumptions. There is no mathematical way to have a "perfect" game of UNO, so our players will often need to decide which card to play of two or they could play.

First, we must remember a few rules from earlier:

  • A player playing a card must match the current discard by either color or value, or play a regular Wild card.
  • A player following a Wild card must match the color declared by the person who laid that card down.
  • A player cannot use a Wild Draw Four card if another card in his/her hand can be played.

Those rules leave a lot of possible situations up to interpretation. For example, if the current discard is a Green Five and I have a Green Skip and a Yellow 5, which should I play?

I've made this model a bit simpler by assuming that my players are stupid jackasses.

That is, every time a player has to make a decision about which card to play, s/he will always play the card that causes the most pain to the next player, regardless of his/her own strategic situation. If I can play a Skip or a 7, I'm playing the Skip (and Lord help you if I have a Draw Two).

Also, if a player has no matches, they must draw a card. If that card can play, then the player will play it; otherwise, his/her turn is over and play moved to the next player.

The PlayerTurn Object

UNO is also a bit different than other games we've modeled (Candy Land, Minesweeper) because the actions of a player have a direct consequence on the next player. We will need our players to take that into account, and they must abide by whatever the "attacking" card says they do.

Therefore, in order for the player to know what action s/he must take, we need the player to be aware of what happened on the previous player's turn. To model the actions taken by a player, we will use the PlayerTurn object, which looks like this:

public class PlayerTurn  
{
    public Card Card { get; set; }
    public CardColor DeclaredColor { get; set; } //Used mainly for Wild cards
    public TurnResult Result { get; set; }
}

The TurnResult enum has all the possible situations which arise from a player completing his/her turn. Those values are as follows:

public enum TurnResult  
{
    //Start of game.
    GameStart,

    //Player played a normal number card.
    PlayedCard,

    //Player played a skip card.
    Skip,

    //Player played a draw two card.
    DrawTwo,

    //Player was forced to draw by other player's card.
    Attacked,

    //Player was forced to draw because s/he couldn't match the current discard.
    ForceDraw,

    //Player was forced to draw because s/he couldn't match the current discard, but the drawn card was playable.
    ForceDrawPlay,

    //Player played a regular wild card.
    WildCard,

    //Player played a draw-four wild card.
    WildDrawFour,

    //Player played a reverse card.
    Reversed
}

Each player takes a turn, and the action performed during that turn are represented by the PlayerTurn object. When the next player takes his/her turn, s/he will also receive the PlayerTurn object for the previous player's turn.

Player Order of Operations

With all the assumptions and the PlayerTurn object in place, let's lay out a skeleton for how our stupid jackass players will behave. Here's how each player will act during his/her turn.

  1. If the previous player "attacked" the current player (via a Skip, a Draw Two, or a Draw Four), then the current player must suffer the attack.
  2. If the current player can play an "attacking" card (within the rules), then s/he does so.
  3. If the current player can play a number card, then s/he does so.
  4. If the current player has no matching cards except a Wild card, s/he plays the Wild. The current player will then declare the color to be the one s/he has the most cards of (the declared color is random if the current player has the same number of card in two or more colors).
  5. If the current player has no cards to play, s/he draws a single card from the draw pile. If the drawn card can be played, s/he plays that card.

NOTE: In either step 2 or step 3, if the player has many possible cards to play, s/he will play the one which results in the color s/he has the most of.

All of those steps are pretty straightforward, but let me explain the reasoning behind Step 4. If we have only one card left, and that card is a Wild card, we are guaranteed to discard our final card on our next turn. Therefore, it behooves the players to hold on to Wild cards until the last possible moment.

Now comes the tricky part; how in the world do we model this?

Being Attacked

Let's start with Step 1 in our Player Order of Operations:

Step 1: If the previous player "attacked" the current player (via a Skip, a Draw Two, or a Draw Four), then the current player must suffer the attack.

The interesting thing about being "attacked" is that being attacked always results in the current player not being able to discard a card. This is why a Reverse card is not an attacking card.

So, let's create a method called ProcessAttack(), during which we will create a PlayerTurn object representing what action the current player took during his/her turn (when s/he suffered the attack).

private PlayerTurn ProcessAttack(Card currentDiscard, CardDeck drawPile)  
{
    PlayerTurn turn = new PlayerTurn();
    turn.Result = TurnResult.Attacked;

    //The player after the current player must match the card that attacked the current player; hence we pass those values through to the next PlayerTurn.
    turn.Card = currentDiscard; 
    turn.DeclaredColor = currentDiscard.Color;

    if(currentDiscard.Value == CardValue.Skip)
    {
        Console.WriteLine("Player " + Position.ToString() + " was skipped!");
    }
    else if(currentDiscard.Value == CardValue.DrawTwo)
    {
        Console.WriteLine("Player " + Position.ToString() + " must draw two cards!");
        Hand.AddRange(drawPile.Draw(2));
    }
    else if(currentDiscard.Value == CardValue.DrawFour)
    {
        Console.WriteLine("Player " + Position.ToString() + " must draw four cards!");
        Hand.AddRange(drawPile.Draw(4));
    }

    return turn;
}

On the Offensive

If the current player is not attacked, s/he will attempt to play an attacking card that matches the color or value of the current discard. Let's create several methods which will make the player decide which card to play.

public PlayerTurn PlayTurn(PlayerTurn previousTurn, CardDeck drawPile) { }

private PlayerTurn DrawCard(PlayerTurn previousTurn, CardDeck drawPile) { }

private bool HasMatch(Card card) { }

private bool HasMatch(CardColor color) { }

private PlayerTurn PlayMatchingCard(CardColor color) { }

private PlayerTurn PlayMatchingCard(Card currentDiscard) { }

private CardColor SelectDominantColor() { }  

Notice the overloads for HasMatch() and PlayMatchingCard(). One of the quirks of this model is that, whenever a player plays a Wild card, s/he declares a color to be played; the next discard can only be matched on color, not value. For my model, I decided to make matching color or value vs matching color only two completely separate "thought processes" as it were.

We'll start with a skeleton of the PlayTurn() method, since it will need to call the ProcessAttack() method we defined earlier. Here's an outline of this method:

public PlayerTurn PlayTurn(PlayerTurn previousTurn, CardDeck drawPile)  
{
    PlayerTurn turn = new PlayerTurn();

    //If the current player was attacked
    if (previousTurn.Result == TurnResult.Skip
        || previousTurn.Result == TurnResult.DrawTwo
        || previousTurn.Result == TurnResult.WildDrawFour)
    {
        return ProcessAttack(previousTurn.Card, drawPile);
    }

    //When the current discard is a Wild card
    else if ((previousTurn.Result == TurnResult.WildCard 
                || previousTurn.Result == TurnResult.Attacked 
                || previousTurn.Result == TurnResult.ForceDraw) 
                && previousTurn.Card.Color == CardColor.Wild
                && HasMatch(previousTurn.DeclaredColor))
    {
        turn = PlayMatchingCard(previousTurn.DeclaredColor);
    }

    //When the current discard is a non-wild card
    else if (HasMatch(previousTurn.Card))
    {
        turn = PlayMatchingCard(previousTurn.Card);
    }

    //When the player has no matching cards
    else //Draw a card and see if it can play
    {
        turn = DrawCard(previousTurn, drawPile);
    }

    DisplayTurn(turn);
    return turn;
}

Let's remind ourselves of Player Logic Steps 2, 3, and 4, as well as the pertinent note:

Step 2: If the player can play an "attacking" card (within the rules), then s/he does so.

Step 3: If the player can play a number card, then s/he does so.

Step 4: If the player has no matching cards except a Wild card, s/he plays the Wild. The player will then declare the color to be the one s/he has the most cards of (the color is random if the player has the same number of card in two or more colors).

NOTE: In either step 2 or step 3, if the player has many possible cards to play, s/he will play the one which results in the color s/he has the most of.

With these steps in mind, let's start building the PlayMatchingCard() methods.

Matching a Wild

If the card we need to match is a Wild, we will need to use the property DeclaredColor in the PlayerTurn object. We must play a card of that color.

Here's the code for the Wild card version of PlayMatchingCard() (the logic involved in the method is in the comments):

private PlayerTurn PlayMatchingCard(CardColor color)  
{
    var turn = new PlayerTurn();
    turn.Result = TurnResult.PlayedCard;
    var matching = Hand.Where(x => x.Color == color || x.Color == CardColor.Wild).ToList();

    //We cannot play wild draw four unless there are no other matches.  But if we can play it, we must.
    if (matching.All(x => x.Value == CardValue.DrawFour))
    {
        turn.Card = matching.First();
        turn.DeclaredColor = SelectDominantColor();
        turn.Result = TurnResult.WildCard;
        Hand.Remove(matching.First());

        return turn;
    }

    //Otherwise, we play the card that would cause the most damage to the next player.
    if (matching.Any(x => x.Value == CardValue.DrawTwo))
    {
        turn.Card = matching.First(x => x.Value == CardValue.DrawTwo);
        turn.Result = TurnResult.DrawTwo;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    if (matching.Any(x => x.Value == CardValue.Skip))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Skip);
        turn.Result = TurnResult.Skip;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    if (matching.Any(x => x.Value == CardValue.Reverse))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Reverse);
        turn.Result = TurnResult.Reversed;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    //If we cannot play an "attacking" card, we play any number card
    var matchOnColor = matching.Where(x => x.Color == color);
    if (matchOnColor.Any())
    {
        turn.Card = matchOnColor.First();
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(matchOnColor.First());

        return turn;
    }

    //We only play a regular Wild card if we have no other matches
    if (matching.Any(x => x.Value == CardValue.Wild))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Wild);
        turn.DeclaredColor = SelectDominantColor();
        turn.Result = TurnResult.WildCard;
        Hand.Remove(turn.Card);

        return turn;
    }

    //This should never happen
    turn.Result = TurnResult.ForceDraw;
    return turn;
}

Matching a Non-Wild

Now we must consider the situation when the current discard is not a wild card. In my model, the code for this method is very, very similar to the Wild situation, but I couldn't figure out an appropriate way to separate them sanely. Anyway, here's the non-wild version of PlayMatchingCard():

private PlayerTurn PlayMatchingCard(Card currentDiscard)  
{
    var turn = new PlayerTurn();
    turn.Result = TurnResult.PlayedCard;
    var matching = Hand.Where(x => x.Color == currentDiscard.Color || x.Value == currentDiscard.Value || x.Color == CardColor.Wild).ToList();

    //We cannot play wild draw four unless there are no other matches.
    if(matching.All(x => x.Value == CardValue.DrawFour))
    {
        turn.Card = matching.First();
        turn.DeclaredColor = SelectDominantColor();
        turn.Result = TurnResult.WildCard;
        Hand.Remove(matching.First());

        return turn;
    }

    //Otherwise, we play the card that would cause the most damage to the next player.
    if(matching.Any(x=> x.Value == CardValue.DrawTwo))
    {
        turn.Card = matching.First(x => x.Value == CardValue.DrawTwo);
        turn.Result = TurnResult.DrawTwo;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    if(matching.Any(x => x.Value == CardValue.Skip))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Skip);
        turn.Result = TurnResult.Skip;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    if (matching.Any(x => x.Value == CardValue.Reverse))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Reverse);
        turn.Result = TurnResult.Reversed;
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(turn.Card);

        return turn;
    }

    // At this point the player has a choice of sorts
    // Assuming he has a match on color AND a match on value 
    // (with none of the matches being attacking cards), 
    // he can choose which to play.  For this modeling practice, we'll assume 
    // that playing the match with MORE possible matches from his hand 
    // is the better option.

    var matchOnColor = matching.Where(x => x.Color == currentDiscard.Color);
    var matchOnValue = matching.Where(x => x.Value == currentDiscard.Value);
    if(matchOnColor.Any() && matchOnValue.Any())
    {
        var correspondingColor = Hand.Where(x => x.Color == matchOnColor.First().Color);
        var correspondingValue = Hand.Where(x => x.Value == matchOnValue.First().Value);
        if(correspondingColor.Count() >= correspondingValue.Count())
        {
            turn.Card = matchOnColor.First();
            turn.DeclaredColor = turn.Card.Color;
            Hand.Remove(matchOnColor.First());

            return turn;
        }
        else //Match on value
        {
            turn.Card = matchOnValue.First();
            turn.DeclaredColor = turn.Card.Color;
            Hand.Remove(matchOnValue.First());

            return turn;
        }
    }
    else if(matchOnColor.Any()) //Play the match on color
    {
        turn.Card = matchOnColor.First();
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(matchOnColor.First());

        return turn;
    }
    else if(matchOnValue.Any()) //Play the match on value
    {
        turn.Card = matchOnValue.First();
        turn.DeclaredColor = turn.Card.Color;
        Hand.Remove(matchOnValue.First());

        return turn;
    }

    //Play regular wilds last.  If a wild becomes our last card, we win on the next turn!
    if (matching.Any(x => x.Value == CardValue.Wild))
    {
        turn.Card = matching.First(x => x.Value == CardValue.Wild);
        turn.DeclaredColor = SelectDominantColor();
        turn.Result = TurnResult.WildCard;
        Hand.Remove(turn.Card);

        return turn;
    }

    //This should never happen
    turn.Result = TurnResult.ForceDraw;
    return turn;
}

Selecting the Dominant Color

In both the Wild and non-Wild versions of this method, we see a call to SelectDominantColor(), which returns the color that appears most often in the current players' hand. Here's that method:

private CardColor SelectDominantColor()  
{
    if (!Hand.Any())
    {
        return CardColor.Wild; //Null case, causes a passthrough in the calling method
    }
    var colors = Hand.GroupBy(x => x.Color).OrderByDescending(x => x.Count());
    return colors.First().First().Color;
}

Drawing a Card

We've now completed implementation Player Logic Steps 2, 3, and 4, so let's move on to Step 5:

Step 5: If the player has no cards to play, s/he draws a single card from the draw pile. If the drawn card can be played, s/he plays that card.

We now need to implement the DrawCard() method defined earlier. This method turns out to be surprisingly simple now that PlayMatchingCard() is already implemented. Here it is:

private PlayerTurn DrawCard(PlayerTurn previousTurn, CardDeck drawPile)  
{
    PlayerTurn turn = new PlayerTurn();
    var drawnCard = drawPile.Draw(1);
    Hand.AddRange(drawnCard);

    if (HasMatch(previousTurn.Card))  //If the drawn card matches the discard, play it
    {
        turn = PlayMatchingCard(previousTurn.Card);
        turn.Result = TurnResult.ForceDrawPlay;
    }
    else
    {
        turn.Result = TurnResult.ForceDraw;
        turn.Card = previousTurn.Card;
    }

    return turn;
}

And with that, there's only one thing left to do: implement the decision tree!

Putting It All Together

Now that the individual player actions are all scripted, the only thing we have left to do is implement a method which will be called by the Game Manager (which we will implement fully in Part 3 of this series) and will make the Player decide what action to take. The method is called PlayTurn() and here it is:

public PlayerTurn PlayTurn(PlayerTurn previousTurn, CardDeck drawPile)  
{
    PlayerTurn turn = new PlayerTurn();
    if (previousTurn.Result == TurnResult.Skip
        || previousTurn.Result == TurnResult.DrawTwo
        || previousTurn.Result == TurnResult.WildDrawFour)
    {
        return ProcessAttack(previousTurn.Card, drawPile);
    }
    else if ((previousTurn.Result == TurnResult.WildCard 
                || previousTurn.Result == TurnResult.Attacked 
                || previousTurn.Result == TurnResult.ForceDraw) 
                && previousTurn.Card.Color == CardColor.Wild
                && HasMatch(previousTurn.DeclaredColor))
    {
        turn = PlayMatchingCard(previousTurn.DeclaredColor);
    }
    else if (HasMatch(previousTurn.Card))
    {
        turn = PlayMatchingCard(previousTurn.Card);
    }
    else //Draw a card and see if it can play
    {
        turn = DrawCard(previousTurn, drawPile);
    }

    DisplayTurn(turn);
    return turn;
}

Summary

Well, would you look at that! We've now completed our Players' behavior (stupid jackasses that they are), and all that's left to do is wire the entire thing together and play some UNO! In the final part of this series, we'll do just that.

Don't forget to check out the GitHub repository for this series.

Happy Coding!

Modeling Practice: UNO in C# Part 1 - Rules, Assumptions, Cards

Note: This post is the first in a three-part series based around modeling the card game UNO in a C# application. You may want to use the GitHub repository to follow along.

I often find that one of the hardest things to do in software development is take a large complex problem and break it down into smaller, more easy problems. As with nearly anything, the only way to get better at this is to practice, so today I'm introducing a new series that aims at providing a practice for both and my readers on how to take real-world problems and model them in C# applications. I'm calling them Modeling Practice.

I've written two groups of posts prior to this one that can be also be considered modeling practice. The first one was a series based around the board game Candy Land, and the second was my longest post ever which detailed how to solve many games of Minesweeper. But for this series of posts, I've decided to take on my hardest challenge yet.

In this series, we're going to model the Mattel card game UNO.

A set of sample UNO cards and the game box

I have very fond memories of this game; my family played it quite a bit when I was younger, and now playing a hand of it is one of my son's favorite things to do. However, this game is considerably more complex than either Candy Land (in which, after the cards are dealt, the winner has already been determined) or Minesweeper (which can be solved mathematically, in many cases). The problem here is that when playing UNO there is some strategy involved; part of designing this model will be making proper and careful assumptions about how these

Let's see if we can take this large problem (how can we play UNO in a C# application?) and break it down into smaller components, then actually build those components to produce a working application. (Hint: we absolutely can, and the repository for it is over on GitHub).

Assumptions and Goals

In this series, we will model the playing of a single UNO round, from the dealing of cards, to the play of the round, to the players shouting "Uno!", to assigning a score to each player at the end of the hand. What we're trying to do here is practice taking a real-world scenario and breaking it down into manageable pieces so that we can solve for those pieces individually, rather than trying to tackle the entire problem at the same time.

We will have to make some assumptions: for example, our players will never forget to yell "Uno!". But our goal is not to model every single possibility; our goal is to make some sacrifices to the demands of the real world and model a working solution to the problem at hand. We will phrase the problm like this:

How would you model a round of UNO being played?

To do that, we must first make sure we understand the rules of the game.

How To Play UNO

For those of you who might not be familiar with the game UNO, let's describe how we play a round. Those of you who do know how to play can skip to the next section.

Basic Rules

Uno! is a card game in which players attempt to remove all cards from their hands by discarding them. Each player starts the round with 7 random cards in their hand.

During a player's turn, s/he attempts to discard a card by matching it to the last-discarded card, either by playing a card with the same color, the same face value, or by playing a wild card.

When a player has one card remaining in their hand, they must shout "Uno!" If they fail to do so, and another player notices and calls them out on it, the player must draw two cards (or one, rules vary).

The Deck

The card deck in Uno is comprised of 108 cards: 25 of each color (red, green, blue, yellow) and 8 wild cards. The color cards each have a corresponding value of 0-9 or an "action" card. Action cards can do the following:

  • Skip (🚫): Skips the next player's turn.
  • Reverse (⇆): Reverses the turn order.
  • Draw Two (+2): Forces the next player to draw two cards and miss their turn.

The wild cards also come in two flavors:

  • Wild: Allows the player to declare which color the next card should be.
  • Wild Draw Four (+4): Allows the player to declare which color the next card should be AND forces the next player to draw four cards and miss their turn. This card can only be played if no other card in the player's hand can be played.

Here's a sample deck of UNO cards:

A sample deck of UNO cards, with all colors and values shown

Scoring

In a real UNO game, players are assigned a score depending on how many cards are left in their hand and the values of those cards. The cards are worth the following points:

  • 0-9: What number is shown.
  • Draw Two, Reverse, Skip: 20 points.
  • Wild, Wild Draw Four: 50 points.

The original Mattel rules state that as players reach a 500 point threshold, those players are eliminated and play continues with the remaining players. The version my family played, however, had the entire game stop when a person reached 500 points, and the person with the lowest number of points would win.

Official Rules

The official rules are a pain to find on Mattel's site, so here's a link directly to the version we'll be using. Please note that different versions of UNO occasionally use different rules as well.

Breaking Down The Problem

Now that we know the rules of the game, we can start to break our big problem down into little ones.

Let's think about this: if we wanted to play UNO in real life but had never actually played it before, what would we need? I see five different things we would need:

  • Cards: We need the physical cards to play the game.
  • Game Setup: How do we shuffle and deal the cards at the beginning of the game?
  • Players: How many players will play the game? Since we're not playing with real people, how will our fake players behave during the game?
  • Game End: How will we know when the game is over?
  • Scoring: How do we know who won?

We'll model each of these independently, starting with the cards. The game setup and the players will be modeled in Part 2 of this series, and the game end scenarios and scoring will be modeled in Part 3.

First Step: Modelling the Cards

Obviously we cannot play a game of UNO without the cards, so let's tackle the medium-sized problem of modelling the cards themselves.

Here's a sample UNO card:

A green zero card

Each card has three properties:

  1. A color
  2. A value
  3. A score

For our sample card, it's pretty clear that the color is Green, the value is 0, and the score is 0. For each of the numbered cards, the value equals the score, but for the action and wild cards, the score and value are different.

Let's model the possible colors and values using enumerations:

public enum CardColor  
{
    Red,
    Blue,
    Yellow,
    Green,
    Wild
}

public enum CardValue  
{
    Zero,
    One,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Reverse,
    Skip,
    DrawTwo,
    DrawFour,
    Wild
}

With the range of possible colors and values defined, we can build a simple class to represent a single card:

public class Card  
{
    public CardColor Color { get; set; }
    public CardValue Value { get; set; }
    public int Score { get; set; }
}

With that, we have modeled the cards themselves. Now we can begin modeling how to set up a hand of UNO.

Setting Up The Game

Here's a (totally not staged) shot of an UNO game which has been set up for four players:

(Yes, we play on the floor. It's easier for little hands to reach the draw pile than sitting at the table would be.)

There are four hands of seven cards each, one for each player, as well as a draw pile and a discard pile. Let' use my l33t paint skillz to show which is which.

In a real game, it's up the players to enforce the rules and make sure everyone plays by them. But in our model, we'll need an object to do that, and we will call this object the GameManager.

public class GameManager  
{
    public List<Player> Players { get; set; }
    public CardDeck DrawPile { get; set; }
    public List<Card> DiscardPile { get; set; }
}

We will define what the Player class is during the Strategy section, so for now let's focus on the properties DiscardPile and DrawPile.

DiscardPile is just a List<Card>, and really only exists so that we a) know what card was last discarded and b) can reshuffle the discard pile into the draw pile when the draw pile runs out of cards.

DrawPile is the more interesting property. In my model, it is a class CardDeck, which looks something like this:

public class CardDeck  
{
    public List<Card> Cards { get; set; }

    public CardDeck() { ... }
    public void Shuffle() { ... }
    public List<Card> Draw(int count) { ... }
}

Let's take each of the three methods in this class and define what we need them to do.

Creating the Cards

When the CardDeck is created, we need it to populate itself with enough cards to represent a proper UNO deck. To do this, we use the constructor to create enough cards.

Here's the full constructor, with annotated comments.

public CardDeck()  
{
    Cards = new List<Card>();

    //For every color we have defined
    foreach (CardColor color in Enum.GetValues(typeof(CardColor)))
    {
        if (color != CardColor.Wild) //Wild cards don't have a color
        {
            foreach (CardValue val in Enum.GetValues(typeof(CardValue)))
            {
                switch (val)
                {
                    case CardValue.One:
                    case CardValue.Two:
                    case CardValue.Three:
                    case CardValue.Four:
                    case CardValue.Five:
                    case CardValue.Six:
                    case CardValue.Seven:
                    case CardValue.Eight:
                    case CardValue.Nine:
                        //Add two copies of each color card 1-9
                        Cards.Add(new Card()
                        {
                            Color = color,
                            Value = val,
                            Score = (int)val
                        });
                        Cards.Add(new Card()
                        {
                            Color = color,
                            Value = val,
                            Score = (int)val
                        });
                        break;
                    case CardValue.Skip:
                    case CardValue.Reverse:
                    case CardValue.DrawTwo:
                        //Add two copies per color of Skip, Reverse, and Draw Two
                        Cards.Add(new Card()
                        {
                            Color = color,
                            Value = val,
                            Score = 20
                        });
                        Cards.Add(new Card()
                        {
                            Color = color,
                            Value = val,
                            Score = 20
                        });
                        break;

                    case CardValue.Zero:
                        //Add one copy per color for 0
                        Cards.Add(new Card()
                        {
                            Color = color,
                            Value = val,
                            Score = 0
                        });
                        break;
                }
            }
        }
        else //Handle wild cards here
        {
            //Add four regular wild cards
            for (int i = 1; i <= 4; i++)
            {
                Cards.Add(new Card()
                {
                    Color = color,
                    Value = CardValue.Wild,
                    Score = 50
                });
            }
            //Add four Draw Four Wild cards
            for (int i = 1; i <= 4; i++)
            {
                Cards.Add(new Card()
                {
                    Color = color,
                    Value = CardValue.DrawFour,
                    Score = 50
                });
            }
        }
    }
}

That method is pretty straightforward, and results in us having a complete deck of UNO cards. But, something's missing. Obviously we wouldn't want to play the game without shuffling the cards first, so let's implement that Shuffle() method:

public void Shuffle()  
{
    Random r = new Random();

    List<Card> cards = Cards;

    for (int n = cards.Count - 1; n > 0; --n)
    {
        int k = r.Next(n + 1);
        Card temp = cards[n];
        cards[n] = cards[k];
        cards[k] = temp;
    }
}

(Note that this method implements the Knuth-Fisher-Yates shuffle I've written about before)

Finally, we need a Draw() method, which returns a certain number of cards from the top of the deck. Given that our collection of cards is a List<>, we can use LINQ's Take() statement to give us the cards.

public List<Card> Draw(int count)  
{
    var drawnCards = Cards.Take(count).ToList();

    //Remove the drawn cards from the draw pile
    Cards.RemoveAll(x => drawnCards.Contains(x));

    return drawnCards;
}

Ta-da! We've completed our CardDeck class, which means that we can move on to the next step: players!

Summary

In this post, we learned how to play UNO, saw my mad paint skillz put to good use, and modeled some cards. In the next post of this series, we will tackle the most complex part of this model: how the players behave.

Don't forget to check out the GitHub repository for this series!

Happy Coding!

Introducing the Daily Design Pattern

Lately I've been on something of a design patterns kick, from realizing that patterns are tools, not goals to developing and recording an extensive course for my employer and my fellow programmers at my current employer. It's been enlightening, to say the least.

In fact, I think I'm suffering from pattern fever, as it were, because I've started noticing them everywhere, even in places where I couldn't previously see that they existed. To help me deal with this, I began coding up a few sample projects that demonstrated common patterns and their usages. It wasn't supposed to turn into anything major, just a few samples to help me wrap my head around these patterns.

Of course, nothing ever turns out exactly the way you planned.

It was I then said, "to hell with it," and spent the next several nights creating sample apps for nearly all of the patterns described in the Gang of Four book. Overkill? Maybe. But now I understand them better than I did before.

Since I'm not content with building these example projects for no reason, this series of posts is the manner by which I am releasing all of my C# sample code for the world to see and correct me on, as inevitably will happen (and is welcome). Come along with me as we explore the world of software design patterns and learn when to, and when not to, apply them to our software projects!

What Are Design Patterns?

Software design patterns are common solutions to problems which are regularly encountered in programming. These particular patterns deal with object-oriented programming exclusively, so applying these patterns to, say, a functional environment is a thoroughly bad idea. Some pattern proponents even go so far as to say that, in the object-oriented world, these design patterns are full-fledged best practices, though I often stop short of such an assertion.

The patterns I'll be describing in this series originate from a book titled, appropriately enough, Design Patterns - Elements of Reusable Object-Oriented Software, written by a group of authors who have come to be known as the Gang of Four (GoF). These authors are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. The original book was released in 1995, but despite what you may think it didn't really create new patterns so much as give names to ones that already occurred naturally, so to speak.

That said, given that the examples in the book were given in C++ and Smalltalk, I thought I personally would be better served by having examples in modern C#, so that's what my examples will be written in.

The Patterns

I'm releasing the articles in this series in no particular order. Below is a list of all the patterns found in the Gang of Four book and their corresponding release dates for their articles. Each example pattern will be done in C# using .NET.

Further, all of my posts will have examples that are, in some way, related to food. This is mostly because I was hungry when I created the first three examples and decided to just run with it (part of the "to hell with it" moment mentioned earlier). The repository which stores all of my sample code is over on GitHub, so please take a look and see if you can improve on my examples.

Creational

These are the patterns which deal with the creation of objects.

Structural

These are the patterns concerning the structure of objects and code.

Behavioral

These patterns define and control the behavior of objects and instances.

What I'm Leaving Out

I'm not going to cover the Interpreter pattern as its usage is so specific as to be unusable for any application I've worked on. I'm of the opinion that this pattern is outdated enough that it can be discarded, but am willing to listen to other ideas should any arise. I may change my mind later, and if I do, all you dear readers will be the first to know.

Get My eBook FREE!

I've compiled all of these Daily Design Pattern posts into a PDF eBook, which you can get for free simply by signing up for my email list.

Summary

Design Patterns are structures that solve commonly-encountered problems in computer science. I've regularly come across situations that required the use of a pattern (or just fit very well into a pattern's usage) and I've encountered them enough to know that understanding what they are, what they are not, and how they're used is becoming more and more critical to me and my fellow devs.

True to the series name, I'll be releasing one of these articles every Monday, Tuesday, Wednesday, Thursday, and Friday through the month of June and into July. Why am I not doing weekends? Because I have a family and I like to spend time with them.

I've been working on this project for quite a while, and would love to hear how it helped you (or if I can improve). Please feel free to share in the comments.

Happy Coding!