Lecture 23: War and Tests

Announcements

Quiz Monday!

Organizing your War code

Do what you like, of course, but I suggest something like the following pseudocode:

findWinner():
    initialize values/decks (if needed)
    while !gameOver:
      battle()
    return outcome

battle():
  if game over (winner or draw):
      set outcome
        return
    increment battle count
    draw cards from each player
    if a player wins:
      allocate spoils
    else war()

war():
  if game over (not enough cards for war):
      set outcome
        return
    add three cards from each player to spoils

Writing tests

Edge cases you want to check might be challenging. For instance, how can you possibly check if the 1,000 battles causes a technical draw? You’re not going to write out 2,000 cards, right? Of course not. But your tests can be programmatic too. For example, we can deal out 999 cards to each player and make sure that A is the winner:

@Test
public void testNoTechnicalDraw() {
    List<Integer> deck = new ArrayList<>();
    for (int i = 0; i < 999; i++) {
        deck.add(2);
        deck.add(1);
    }
    assertEquals(1, War.findWinner(deck));
}

And then deal 1,000 and make sure it’s a tie (even though B is out of cards, it’s still a tie, since they both had a card during battle 1,000!).

@Test
@GradedTest(name = "testTechnicalDraw", max_score = 0.5)
public void testTechnicalDraw() {
    List<Integer> deck = new ArrayList<>();
    for (int i = 0; i < 999; i++) {
        deck.add(2);
        deck.add(1);
    }
    assertEquals(1, War.findWinner(deck));

    deck = new ArrayList<>();
    for (int i = 0; i < 1000; i++) {
        deck.add(2);
        deck.add(1);
    }
    assertEquals(0, War.findWinner(deck));
}

What about if we want exactly enough cards so that we have war all the way to a technical draw (show derivations of 2 + 8 * 999 on board):

@Test
public void testTechnicalDrawDuringWar() {
    List<Integer> deck = new ArrayList<>();
    for (int i = 0; i < 2 + 8 * (999); i++) {
        deck.add(0);
    }
    assertEquals(0, War.findWinner(deck));
}

(Mostly an interactive class, sorry more of this wasn’t pre-planned. Get notes from a friend. Heck, have ‘em send ‘em to me.)