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!

Diary of a Death March: Terry's Story

June 2nd

It went through! After all the effort the three of us put into this deal, the company we have been trying to purchase for more than a year is finally ours. They have got a great name, a wonderful team, myriad projects, and satisfied customers. And now they are ours.

Song did an incredible job at the negotiations, especially near the end. He, Hannah, and I will now head up this company, and I am sure we are going to get the ball rolling just like it has been. We had been looking for a good opportunity to pave our own way, to create our own thing, and now we finally, finally got it. Top of the ladder, here we come!

A headshot of a middle-aged businessman with close-cropped blond/grey hair

June 3rd

Met the employees today. Of course, I already knew one of them, since he and I have been drinking buddies for years. Rodrigo is a good guy, a team player, so when he relayed to us that the previous ownership group was looking to sell, I knew we had to jump on it. An opportunity like this just does not come along very often, so when it does you have to seize it and never let go.

Here's to a new beginning! Now let's go kick ass and make money!

June 14th

Two weeks in, and it has been nothing but smooth sailing. The engineering teams are doing an incredible job pumping out products; in fact, they are almost too good at it. This is a great team we have got here, no doubt about it.

July 7th

Jamie filed for divorce today. It is... not exactly unexpected, but it is still... I dunno. Sad?

We have drifted further and further apart; there is no point in denying it. In the last few months we have barely spoken to each other. We have no children, so when it is all said and done there is nothing really binding us together.

Except... I love her. She's funny, she's radiant, she's smart. She's perfect. I can't help but to love her. I know I spend too much time at my job, but why can't she see that I am needed here, just like I was needed at our previous company? They will fail without me. Isn't it obvious?

This has been a long time coming. I don't want her to leave, I would much prefer to have her stay with me, but I doubt I can change her mind now. It is far too late for that.

August 15th

The contracts are drying up. I am not entirely sure when that happened, but today Rodrigo came to me and told me, no BS, that he needs more work. I am going to have to get new jobs lined up, so I have told Bianca to help find us new customers. She is a solid sales rep, so I am sure she will come through.

August 28th

My instincts never lie. Bianca's got a meeting set up with a new customer. We are quickly running out of billable projects, so we need a big win to keep the company in the black. It is what the company needs. I am sure we will get it, we just need to be patient.

September 4th

And, once again, my patience pays off. The customer Bianca got in touch with has hired us to produce this project scheduling app that Bianca says (and Rodrigo agrees) we will have no problem with. Now we have got work and everybody can get started right away. Bianca is still out looking for more customers just in case, but I got a good feeling about this one.

October 19th

Met with the lawyers today. I never knew a room could be so cold. I tried pleading with her, with my beloved Jamie, tried to make her see that I will change, that I want to change. I can spend less time at the company, more time with her, I promise, just after we get it up and running on its own. This time, for once, I really meant it.

Not that it mattered. She doesn't believe me. Hell, I'm not sure I believe me.

November 9th

The new project is proceeding right on schedule. We are going to blow the customers' minds! At least, that is what Rodrigo is telling me, and he has never let me down before.

December 10th

The divorce went final today. I went out drinking with Rodrigo and George to try to get out of this funk, and all that did was make me feel worse.

Why am I such an idiot?

December 17th

We had our first Christmas party today, and Song and Hannah wanted me to make a speech to galvanize our troops. Rodrigo still insists that we can make the deadline, but I felt that I needed to make it clear that we have all got to pull together and buckle down to get this project finished.

I just hope they heard me. We really need this win. I really need this win.

January 4th

So far, so good. Rodrigo's team has been pulling lots of overtime to get this project done, and it seems to be working. They are doing a great job, and their company thanks them for it.

January 27th

Almost there. Delivery is on the 4th, and Rodrigo keeps telling me that we will be good to go. And yet, I keep seeing his lead developer sleeping on the floor of his cube. I wonder what that is all about.

February 4th

Well, the delivery was today. Or, at least, it was supposed to be. Turns out that Rodrigo's team, despite all the overtime, has not finished the project, and the system isn't ready to ship. Bianca and I scrambled to get the customer to agree to a new date, and they did, so we will get a second chance at this.

Here's hoping that is all the chances we need. Come on, Engineering! What's taking you so long?

February 6th

We need some more bodies on the scheduler project, so I have reassigned Engineering Team 3 to help. It is what the company needs. Their manager, Francis, was part of the old guard here and just wasn't quite fitting in with the new order of things, so I have decided to let him go as well. My buddy George has stepped up to the plate and agreed to lead that team, a fact for which I am eternally grateful. Now we just need the developers to pull their weight.

February 11th

George has had a few days to really dig into this scheduler app, and he tells me that it is not looking good. He recommended pushing the delivery date another few months, but Bianca objected (quite rightly) that we have already failed to deliver once, so any further delay might just cause the customer to drop us altogether. We cannot afford that.

So, I need George's team to pull overtime to get this project done. They will not like it, but it needs to happen.

March 10th

Song is now on my back because the lead server admin, some chick named Kelly, quit yesterday. So now I gotta go find a new server admin, and they don't exactly grow on trees.

For now, Rodrigo's lead Steve has the most server experience, so the company needs him to fill the gap until I can find a new server admin. Hopefully that won't take too long.

March 31st

Delivery day tomorrow. Here's hoping it goes better than the first one. Rodrigo assured me it would while we were at the bar after work, and he has been nothing but consistent in his affirmations. I asked George what he thought, and he said they were closer than they had ever been.

We will be fine.

April 1st

Or maybe we won't.

Demo did not go well. The customer wasn't happy with some of the changes, and wanted a few more, so Bianca and I agreed. Gotta keep the customer happy.

Rodrigo and George are just as stunned as I am. How could they not like this project when we're closer than we have ever been to finishing it? They seem to think that the root problem is Rodrigo's lead developer, Steve. Rodrigo said he would handle it tomorrow.

I hope Steve has said his goodbyes.

April 16th

It was all going so well. Now, the scheduler project is way behind (thanks to Steve's incompetence), and I am not at all sure we can save it in time.

No! I can't think like that. We have to complete it. It is the biggest job we have had since the acquisition, it cannot fail!

On the bright side, all this commotion at work means today was the first day I have not had time to think about how much I miss Jamie. I don't know how to feel about that.

May 13th

Apparently there is something going on with Engineering Team 2; several of the interns are refusing to work late. That cannot be allowed to stand have that, the company needs every man on deck for this project. Our very survival is at stake!

I'm going to have to find whoever started this and give them their just rewards. After the project, anyway.

May 26th

Tomorrow is our last chance. The new lead, Marisol, says we're not going to make it, but Rodrigo and George have seen the product and they say it's good enough. I'm sure my buddies have a handle on this.

If not, well, I am going to need a lot more drinks.

May 27th

Shit.

The customer was fed up with us. Engineering didn't come through, despite all the promises made. They dropped us, and now we're stuck with no work and a scheduler app that nobody wants.

Somebody's going to pay for this. It is what the company needs.

May 28th

Had a heated argument with Team 2 lead Neil today. He got all pissy, saying we had not given him enough time to get his interns up to speed on the new project. Which is crap, and I told him as much. Had he put as much effort into this as we have, it would not have been a problem.

I also informed him that, while his own job is safe, we will be disbanding Team 2 and reintegrating him with Team 1. He lost his cool, something I had not seen before and, quite frankly, was rather unbecoming of him. He yelled about "broken promises" and other crap, and at that point I stopped listening.

As far as I am concerned, he, Marisol, and Steve caused this project to spiral out of control. Since Steve's gone and Marisol will be shortly, he should be pretty damn glad to still have a job.

May 29th

I fired the interns today; Neil refused to do it. I am not sure how much longer I will let his insubordination stand, but for now we are understaffed and the company needs him around. When the company no longer needs him, well...

May 30th

And now we begin the long process of finding a new team, a real team, one that will pull their weight when asked and can do the job they signed up for. I've already got several candidates coming in; replacements for Steve and Kelly, and a possible new manager. All we need is a team we can gel with; keeping the existing team employed might have been a bad idea after all.

It has been a rough few months. Lots of turmoil; Song is unhappy about the whole thing and I do not blame him. But Rodrigo, George, and I will get us back on our feet.

As long as we have a solid engineering team supporting us. We need them to be ready for anything, ready for a challenge, ready to get down and dirty. We need them to pull their weight.

It is what the company needs.

Programming Is Awesome, But Programmers Suck

I was re-reading the fantastic piece by Peter Welch called Programming Sucks, which is a classic despite it being only two years old. In the piece, Mr. Welch repeatedly demonstrates why programming (and the atmosphere surrounding it), well, sucks, which results in simultaneously hilarious and sobering paragraphs such as this one:

"You discover that one day [while debugging a program], some idiot decided that since another idiot decided that 1/0 should equal infinity, they could just use that as a shorthand for "Infinity" when simplifying their code. Then a non-idiot rightly decided that this was idiotic, which is what the original idiot should have decided, but since he didn't, the non-idiot decided to be a dick and make this a failing error in his new compiler. Then he decided he wasn't going to tell anyone that this was an error, because he's a dick, and now all your snowflakes are urine and you can't even find the cat."

You'll have to read the whole piece to have that last sentence make sense. Go on, I'll wait.

That post got me thinking: why exactly does programming suck? Most of the piece details that the work itself actually doesn't suck; rather, the people involved in it do. It got me thinking: exactly why can programming be so frustrating, so annoying, so terrible? And I've come up with a theory.

In short: programming doesn't suck, programmers suck. Yes, including me. Here's why:

We think "I can do better than that." Every damn time. It doesn't matter if we've spent five seconds perusing a new codebase or a couple minutes watching a senior developer explain what his application does, we can always do better than that idiot. Until we actually try to do it better, and after a few hours of "this can't be that hard" and "why won't you work, stupid code" and "I know I'm better than this" we're more likely to silently give up than concede that we got Dunning-Krugered once again. Why admit defeat when you can just delete?

But while we will do better than that, nobody else can. Everyone else's applications are steaming piles of dog crap next to our own beautifully-crafted, complete, artful pieces of shit code. And we don't even have enough sense to realize that what we've written is crap, as it always has been and always will be; since it's our crap we assume that it must be good. After all, we're good at programming, therefore what we write must be good. I mean, obviously.

A programmer, sitting on a couch with a computer on his lap, captioned

In our own little insular world, we are gods, and we get treated as such. Have you ever fixed a family member's computer after they did something to it? You'd think they just saw water turned into wine. What was a few minutes of googling and an hour of random button-pressing while trying to get a different error becomes a work of utter genius in the eyes of the non-techie. To them, we are not so much technicians as magicians, and we can't even deny it because "oh, you're just being modest." To the non-programmer, we are miracle-workers. And, if we're being really honest with ourselves, we love it. We crave that praise, that acknowledgement; it's something we don't often get in the real world because code, on the whole, is supposed to be invisible. It's a truly addictive feeling, that of doing something no one else can do.

We believe that management hates us because we "tell it like it is" (which invariably means "how we want it to be"), but in reality they hate us because we don't bother explaining ourselves clearly. We say "there's a problem" and then launch into some long and indecipherable technobabble rant about why the proposed solution won't work, when in reality we're just stalling, saying it won't work because we don't have the time or energy to research and understand the proposed solution.

Worse, if we do bother to attempt to explain why it won't work, we'll probably only do that once, because when we invariably fail to make them understand how smart we are and how dumb they must be, we just won't bother explaining anything to them because it's a waste of time. They didn't understand before, so they won't understand now. It's an endless loop, one we perpetuate because it makes us feel smart, feel needed, when in reality it just pisses off our managers.

In short, we are whiny, selfish, dense little buggers who just want to feel smart.

Programming, to be clear, is awesome. We programmers are fortunate. We get to solve problems using code that only a few people understand, that are difficult to conceptualize, that, if we're lucky, can actually make a difference in someone's day-to-day life. The feeling of doing good work is up there with good sex and good food: it feels amazing. Even better, we get paid to do this, and in many cases paid quite well compared to other professions. Yet we can't seem to remember any of that because we're too busy puffing our chests and destroying code.

Programming doesn't suck, programmers suck. All of us, including me. This is one of the reasons I believe that a core part of being a programmer is being a good communicator. Maybe the time we spend perfecting our code would be better spent explaining it, understanding others' code, or just chilling out. We're not gods, we can't always do better, and most of all we are people just like everyone else. Spend your time learning how to communicate, analyze, and teach; what you'll find is that these are all more important skills than knowing how to code.