modeling-practice

Modeling Battleship in C# - Introduction and Strategies

NOTE: This is Part 1 of a three-part series demonstrating how we might model the classic game Battleship as a C# program. You might want to use the sample project over on GitHub to follow along with this post. Also, check out my other posts in the Modeling Practice series!

In software development, often we programmers are asked to take large, complex issues and break them down into smaller, more manageable chunks in order to solve any given problem. I find that this, as with many things, becomes easier the more you practice it, and so this blog has a series of posts called Modeling Practice in which we take large, complex problems and model them into working software applications.

In my case, I love games, so each of the previous entrants in this series have been popular, classic games (Candy Land, Minesweeper, UNO). That tradition continues here, and this time the board game we'll be modeling is the classic naval battle game Battleship.

A picture of the game box, showing two children playing the game and placing red and white pegs on the boards.

My boys (who I've written about before) are now old enough that they can play this game themselves, and so they've been killing hours trying to sink each other's ships.

That's the Modeling Practice we're going to do this time: we're going to model a game of Battleship from start to finish, including how our players will behave. So, let's get started!

What is Battleship?

For those of you who might not have played Battleship before, here's how it works. Each player gets a 10-by-10 grid on which to place five ships: the eponymous Battleship, as well as an Aircraft Carrier, a Cruiser, a Submarine, and a Destroyer. The ships have differing lengths, and larger ships can take more hits. Players cannot see the opposing player's game board.

More Modeling Practice:

Players also have a blank firing board from which they can call out shots. On each player's turn, they call out a panel (by using the panel coordinates, e.g. "A5" which means row A, column 5) on their opponent's board. The opponent will then tell them if that shot is a hit or a miss. If it's a hit, the player marks that panel with a red peg; if it is a miss, the player marks that panel with a white peg. It then becomes the other player's turn to call a shot.

When a ship is sunk, the player who owned that ship should call out what ship it was, so the other player can take note. Finally, when one player loses all five of his/her ships, that player loses.

Image is Sailors play "Battleship" aboard a carrier, found on Wikimedia. In this game, the player who owned the left board would have lost.

The game itself was known at least as far back as the 1890s, but it wasn't until 1967 that Mattel produced the peg-and-board version that most people have seen today. It is that version (and its official rules) that we will use as part of our modeling practice.

Image is You sunk my battleship!, found on Flickr and used under license.

Now, let's get started modeling! First, we need to figure out the components of the game.

Components of the Game

In order to play a game of Battleship, our system will need to be able to model the following components:

  • Coordinates: The most basic unit in the game. Represents a row and column location where a shot can be fired (and where a ship may or may not exist).
  • Panels: The individual pieces of the board that can be fired at.
  • Game Board: The board on which players place their ships and their opponent's shots.
  • Firing Board: The board on which players place their own shots and their results (hit or miss).
  • Ships: The five kinds of ships that the game uses.

All of that is fine and good, but if our system expects to be able to actually play a game, we're going to have to figure out the strategy involved.

Potential Strategies

Here's a sample Battleship game board:

There are two different strategies we'll need to model:

  1. How to place the ships AND
  2. How to determine what shots to fire.

Fortunately (or maybe unfortunately) the first strategy is terribly simple: place the ships randomly. The reason is that since your opponent will be firing at random for much of the game, there's no real strategy needed here.

The real interesting strategy is this one: how can we know where to fire our shots so as to sink our opponent's ships as quickly as possible? One possibility is that, just like placing the ships randomly, we also just fire randomly. This will eventually sink all the opponent's ships, but there is also a better way, and it involves combining two distinct strategies.

First, when selecting where to fire a shot, we don't need to pick from every possible panel. Instead, we only need to pick from every other panel, like so:

Because the smallest ship in the game (the Destroyer) is still two panels long, this strategy ensures that we will eventually hit each ship at least once.

But what about when we actually score a hit? At that point, we should only target adjacent panels, so as to ensure that we will sink that ship:

These are called "searching" shots in my system, and we only stop doing searching shots when we sink a ship.

By using these two strategies in tandem, we ensure that we can sink the opponent's ships in the shortest possible time (without using something like a probability algorithm, which more advanced solvers would do).

Summary

Here's all of the strategies we've discovered so far:

  1. Placement of ships is random; no better strategy available.
  2. Shot selection is partly random (every other panel) until a hit is scored.
  3. Once a hit is scored, we use "searching" shots to eventually sink that ship.
  4. The game ends when one player has lost all their ships.

In the next part of this series, we will begin our implementation by defining the components for our game, including the players, ships, coordinates, and so on. We'll also set up a game to be played by having our players place their ships.

Don't forget to check out the sample project over on GitHub!

Happy Modeling!

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!