Home > Articles > Programming > Java

Crafting Java with Test-Driven Development, Part 7: Adding Some Bulk

📄 Contents

  1. Building and Testing "Critical Mass"
  2. Reminders
Jeff Langr's poker application has come a long way in the last few installments of this series. In this segment, he adds the first set of code for handling some of those specialized poker terms you've might recognize from TV: the flop, the turn, the river, and the blinds.
Like this article? We recommend

Building and Testing "Critical Mass"

In our last installment, we started building support into the Texas Hold ’Em application for the actual game. We got to the point of proving that we could deal hole cards to players.

In an attempt to get a bit of critical mass built into the application, I coded about an hours’ worth of test and code since our last installment. I’m going to expect you to be willing to go forward with this code, but we’ll want to make sure that you have a good understanding of it first.

The bulk of changes I made were driven by tests in GameTest. The complete source for GameTest is shown in Listing 1.

Listing 1 GameTest.

package domain;

import junit.framework.*;

public class GameTest extends TestCase {
  private static final int BURN = 1;
  private Game game;
  private Deck deck;
  private Player player1;
  private Player player2;
  private Player player3;
  private static final int STAKE = 1000;
  private static final int SMALL = 10;
  private static final int BIG = 20;

  protected void setUp() {
   game = new Game();
   game.setBlinds(SMALL, BIG);

   deck = game.deck();

   player1 = new Player("a");
   player1.add(STAKE);
   player2 = new Player("b");
   player2.add(STAKE);
   player3 = new Player("c");
   player3.add(STAKE);
  }

  public void testCreate() {
   assertPlayers();
  }

  public void testAddSinglePlayer() {
   final String name = "Jeff";
   game.add(new Player(name));
   assertPlayers(name);
  }

  public void testAddMaximumNumberOfPlayers() {
   for (int i = 0; i < Game.CAPACITY; i++)
     game.add(new Player("" + i));
   assertPlayers("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
  }

  public void testDealCompleteHand() {
   addTwoPlayers();
   game.setButton(2);
   game.startHand();

   Card[] hole = deck.top(4);
   game.dealHoleCards();

   assertHoleCards(player1, hole, 0, 2);
   assertHoleCards(player2, hole, 1, 3);

   int remaining = Deck.SIZE - hole.length;
   assertEquals(remaining, deck.cardsRemaining());
   Card[] flop = deck.top(BURN + 3);

   game.dealFlop();
   remaining -= flop.length;
   assertCardsDealt(remaining, flop);
   CardTest.assertCards(
     game.community(), flop[1], flop[2], flop[3]);

   Card[] turn = deck.top(BURN + 1);
   game.dealTurn();
   remaining -= turn.length;
   assertCardsDealt(remaining, turn);
   CardTest.assertCards(
     game.community(), flop[1], flop[2], flop[3], turn[1]);

   Card[] river = deck.top(BURN + 1);
   game.dealRiver();
   remaining -= river.length;
   assertCardsDealt(remaining, river);
   CardTest.assertCards(game.community(), flop[1], flop[2], flop[3],
      turn[1], river[1]);
  }

  public void testDealOrderStartsFromButton() {
   addTwoPlayers();
   game.setButton(1);
   game.startHand();

   Card[] hole = deck.top(4);
   dealAllCardsInHand();

   assertHoleCards(player1, hole, 1, 3);
   assertHoleCards(player2, hole, 0, 2);

   game.stopHand();

   game.startHand();
   hole = deck.top(4);
   dealAllCardsInHand();

   assertHoleCards(player1, hole, 0, 2);
   assertHoleCards(player2, hole, 1, 3);
  }

  public void testBlinds() {
   addThreePlayers();
   game.setButton(3);

   game.startHand();

   assertEquals(STAKE - SMALL, player1.chipCount());
   assertEquals(STAKE - BIG, player2.chipCount());
   assertEquals(STAKE, player3.chipCount());
  }

  public void testHandFlow() {
   addThreePlayers();
   game.setButton(3);

   game.startHand();
   dealAllCardsInHand();

   game.stopHand();
   assertEquals(1, game.buttonPosition());
   assertNoCardsOut();

   game.startHand();
   dealAllCardsInHand();
   game.stopHand();
   assertEquals(2, game.buttonPosition());
   assertNoCardsOut();

   game.startHand();
   dealAllCardsInHand();
   game.stopHand();
   assertEquals(3, game.buttonPosition());
   assertNoCardsOut();

   fail("need to ensure blinds are extracted properly");
  }

  // missing tests:
  // - use a new deck each time!

  private void assertNoCardsOut() {
   for (Player player: game.players())
     assertTrue(player.holeCards().isEmpty());
   assertTrue(game.community().isEmpty());
  }

  private void dealAllCardsInHand() {
   game.dealHoleCards();
   game.dealFlop();
   game.dealTurn();
   game.dealRiver();
  }

  private void addThreePlayers() {
   game.add(player1);
   game.add(player2);
   game.add(player3);
  }

  private void addTwoPlayers() {
   game.add(player1);
   game.add(player2);
  }

  private void assertCardsDealt(int remaining, Card[] turn) {
   assertDeckCount(remaining);
   DeckTest.assertCardsDealt(deck, turn);
  }

  private void assertHoleCards(
     Player player, Card[] hole, int... indices) {
   Card[] cards = new Card[indices.length];
   for (int i = 0; i < indices.length; i++)
     cards[i] = hole[indices[i]];
   DeckTest.assertCardsDealt(deck, cards);
   CardTest.assertCards(player.holeCards(), cards);
  }

  private void assertDeckCount(int expected) {
   assertEquals(expected, deck.cardsRemaining());
  }

  private void assertPlayers(String... expected) {
   assertEquals(expected.length, game.players().size());
   int i = 0;
   for (Player player : game.players())
     assertEquals(expected[i++], player.getName());
  }
}

Let’s step through each of the tests and see what we have.

  • testCreate, testAddSinglePlayer, testAddMaximumNumberOfPlayers: These three tests remain unchanged from what we built in the last installment.
  • testDealCompleteHand: This test grew out of testDealHoleCards, which we started in the last installment. The idea of this test is to demonstrate that cards are dealt properly to all players within a single Texas Hold ’Em hand. Paraphrased, the test says the following:
    1. Add two players to the game.
    2. Set the button to the second (last) player. This means that dealing starts from the first player.
    3. Start the hand. This implies that a new deck is ready and shuffled.
    4. Peek at the top four cards from the deck, so that we have a way of verifying the actual hole cards that get dealt. A Texas Hold ’Em hand starts with two cards dealt to each player in turn, starting with the player to the left of the button. The ability to peek at cards is a testing need that required some changes to the Deck class. We’ll review these changes shortly.
    5. Deal the hole cards. We call assertHoleCards twice, to verify that player 1 received the first (0th, using Java’s zero-based indexing) and third cards dealt and player 2 received the second and fourth cards dealt. We also verify that 48 cards remain in the deck.
    6. Peek at the top four cards, representing a burn plus the flop. The flop is three community cards—they are dealt face-up at the center of the table. Prior to dealing the flop, the dealer must "burn" (discard) a card, per Texas Hold ’Em dealing convention.
    7. Deal the flop. Similar to the way we verified the hole cards, we compare the community cards against the cards we peeked. We also verify the number of cards remaining in the deck.
    8. Peek at the next two cards, representing a burn and the "turn." The turn is the fourth community card dealt. We compare the turn to the result of calling dealTurn against the Game object. We also verify the number of cards remaining in the deck.
    9. Peek at the next two cards, representing a burn and the "river." The river is the fifth and final community card dealt. We compare the river to the result of calling dealRiver against the Game object. We also verify the number of cards remaining in the deck.

The DeckTest method assertCardsDealt originally started in GameTest. It makes more sense on the DeckTest class, since it deals with a deck and cards, but knows nothing about a game. Here’s what it looks like:

public static void assertCardsDealt(Deck deck, Card... cards) {
  for (Card card: cards)
   assertFalse(deck.contains(card.getRank(), card.getSuit()));
}

The method assertCards in CardTest originally came from PlayerTest. I changed assertCards to be a static method so that other tests could use it. Here’s what it looks like now:

public static void assertCards(List<Card> cards, Card... expected) {
  assertEquals(expected.length, cards.size());
  int i = 0;
  for (Card card: expected)
   assertEquals(card, cards.get(i++));
}

Test code in GameTest needs the capability to look at cards in the deck without dealing them. This means that our Deck class needed to change. Listing 2 shows a couple of tests in DeckTest that drove out support for peeking.

Listing 2 Testing the ability to peek in DeckTest.

// seeing the top card is very valuable in testing
public void testTop() {
  Card top = deck1.top();
  assertEquals(Deck.SIZE, deck1.cardsRemaining());
  Card card = deck1.deal();
  assertEquals(top, card);
}

// seeing the top N cards is very valuable in testing
public void testTopN() {
  Card[] top = deck1.top(3);
  assertEquals(Deck.SIZE, deck1.cardsRemaining());
  assertEquals(3, top.length);
  assertEquals(top[0], deck1.deal());
  assertEquals(top[1], deck1.deal());
  assertEquals(top[2], deck1.deal());
}

These two "top" tests resulted in the production methods in Deck shown in Listing 3.

Listing 3 Peek code in Deck.

// primarily used for testing
Card top() {
  return cards.get(0);
}

// primarily used for testing
public Card[] top(int count) {
  Card[] results = new Card[count];
  for (int i = 0; i < count; i++)
   results[i] = cards.get(i);
  return results;
}

Let’s step through each of the tests.

  • testHandFlow: In Texas Hold ’Em, one hand is almost never the entire game. It results in one player winning the pot, to which that player and others contributed during the course of the hand. Once the pot is won, a new hand begins. The purpose of testHandFlow is to demonstrate the game flow from hand to hand. We show that the button moves upon completion of each hand. Also, at the end of a hand, we show that no cards should be outstanding—no players should hold any cards, and the community should contain no cards. Note the fail method call at the very end of the test. We’ll discuss why this call exists later in this installment.
  • testDealOrderStartsFromButton: This test verifies that the player to the left of the button receives the first hole card. It does so by dealing two hands, and verifying that the deal moves appropriately with each hand.
  • testBlinds: In order to promote more betting action in each hand, Texas Hold ’Em requires that blinds be posted by the two players to the left of the button. Blinds are preset chip amounts. The player to the left of the button is known as the small blind; the second player in line is the big blind. Usually, but not always, the small blind is half of the big blind. Our setUp method sets the blinds:
game.setBlinds(SMALL, BIG);

The code in testBlinds starts a hand by calling startHand. It then verifies that each player’s chip count was appropriately decremented (or not). The code in this test required changes to the Player class to manage chips. We’ll review these changes later in this installment.

The production Game code appears in Listing 4.

Listing 4 Production Game code.

package domain;

import java.util.*;

public class Game {
  public static final int CAPACITY = 10;
  private List<Player> players = new ArrayList<Player>();
  private List<Card> community = new ArrayList<Card>();
  private Deck deck = new Deck();
  private int button = 1;
  private int smallAmount;
  private int bigAmount;

  public List<Player> players() {
   return players;
  }

  public void dealHoleCards() {
   for (int round = 0; round < 2; round++) {
     int dealer = button + 1;
     for (int position = dealer;
       position < dealer + players.size();
       position++) {
      Player player = getPlayer(position);
      player.dealToHole(deck.deal());
     }
   }
  }

  public void add(Player player) {
   players.add(player);
  }

  // needed for testing
  Deck deck() {
   return deck;
  }

  public void dealFlop() {
   burn();
   for (int i = 0; i < 3; i++)
     community.add(deck.deal());
  }

  private void burn() {
   deck.deal();
  }

  public List<Card> community() {
   return community;
  }

  public void dealTurn() {
   burnAndTurn();
  }

  public void dealRiver() {
   burnAndTurn();
  }

  private void burnAndTurn() {
   burn();
   community.add(deck.deal());
  }

  public void setButton(int i) {
   button = i;
  }

  public void setBlinds(int small, int big) {
   this.smallAmount = small;
   this.bigAmount = big;
  }

  public void startHand() {
   collectBlinds();
  }

  private void collectBlinds() {
   Player small = getPlayer(button + 1);
   Player big = getPlayer(button + 2);
   small.bet(smallAmount);
   big.bet(bigAmount);
  }

  public int buttonPosition() {
   return button;
  }

  public void stopHand() {
   removeAllCards();
   advanceButton();
  }

  private void removeAllCards() {
   for (Player player: players())
     player.removeCards();
   community.clear();
  }

  private void advanceButton() {
   button++;
   if (button > players.size())
     button = 1;
  }

  private Player getPlayer(int position) {
   int index = position - 1;
   if (position > players.size())
     index -= players.size();
   return players.get(index);
  }
}

The Game class is starting to do way too much. It’s managing both the flow of the game from hand to hand as well as the hand itself. That description suggests violation of the single-responsibility principle, a good class-design guideline that says classes should have one reason to change. We’ll do something about this design concern in an upcoming installment.

The methods advanceButton and getPlayer have some duplicate concepts. One significant key to keeping your system clean through refactoring is to recognize duplication where it may not be obvious. Here, both methods have logic that deals with finding the next position in the ring of players. Refactoring them resulted in the slightly cleaner code shown in Listing 5. I think the dealHoleCards method is now much easier to follow.

Listing 5 Refactored Game code.

public void dealHoleCards() {
  for (int round = 0; round < 2; round++) {
   for (int i = 1; i <= players.size(); i++) {
     Player player = getPlayer(button + i);
     player.dealToHole(deck.deal());
   }
  }
}

private void advanceButton() {
  button = ringPosition(button + 1);
}

private int ringPosition(int position) {
  if (position > players.size())
   return position - players.size();
  return position;
}

private Player getPlayer(int position) {
  return players.get(ringPosition(position) - 1);
}

The changes to Player were minor. In addition to the changes need to manage the player’s bankroll (chips), we need the ability to remove cards from each Player:

public void testRemoveCards() {
  player.dealToHole(CardTest.CARD1);
  player.dealToHole(CardTest.CARD2);
  player.removeCards();
  assertTrue(player.holeCards().isEmpty());
}

The implementation for Player.removeCards is trivial. (Remember that the code for each installment of this series is always available for download.)

A couple of tests in PlayerTest show how we manage a player’s chips (see Listing 6). The production code resulting from those two tests is shown in Listing 7.

Listing 6 PlayerTest.

public void testBankroll() {
  assertEquals(0, player.chipCount());
  player.add(1000);
  assertEquals(1000, player.chipCount());
  player.bet(200);
  assertEquals(800, player.chipCount());
}

public void testInsufficientFunds() {
  try {
   player.bet(1);
   fail("expected insuff. funds exception");
  }
  catch (InsufficientFundsException expected) {
   assertEquals(0, player.chipCount());
  }
}

Listing 7 Player.

public class Player {
  ...
  private int chips = 0;
  ...
  public int chipCount() {
   return chips;
  }

  public void add(int amount) {
   chips += amount;
  }

  public void bet(int amount) {
   if (amount > chips)
     throw new InsufficientFundsException();
   chips -= amount;
  }
}

InsufficientFundsException is simply a RuntimeException subclass.

You might want to look further through the rest of the code. I made some minor refactorings for clarity and organizational reasons.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020