Spades in PHP: Play-by-Play versus Play-at-Once

Earlier this week I posted about my PHP spades project for automated testing of bidding and playing strategies. In that post I highlighted my use of the strategy design pattern to make it easy to test a variety of approaches to the game; however, I didn't provide much structural detail. Lucky you, as it turns out, because the structure I was using at the time was far from ideal.

My overall idea for running the tests was to be able to use a very thin controller script, something along these lines:

<?php
$game = new Spades_Game();
for ($i=0;$i<3;$i++) {
  $game->registerPlayer(new Spades_Player(new Spades_Strategy_Something()));
}
$scores = $game->play();

This simple "play-at-once" approach is very easy to call, as it leaves every last bit of the game's business logic to the model layer. Unfortunately, it doesn't leave a lot of room for flexibility, particularly in two areas:

  1. Since the entire game happens in a single function call, it's impossible for the controller layer to keep track of the game's progress for output and/or logging purposes.
  2. It's also impossible for the controller layer to allow user input and thereby facilitate the introduction of human players.

So, today I spent a good chunk of time re-architecting the game structure. In terms of tracking progress, I started to think in terms of atomicity: what's the smallest sequential part of a game of spades? Well, let's break it down. A game in its entirety consists of as many hands as necessary to get one team to 400 points without a tie. Each hand consists of each player bidding once, followed by as many tricks as necessary to lay down the entire deck. Each trick consists of every player laying down a single card in sequence. Tricks are won by the team who played the highest card (spades being higher than other suits), and hands are scored based on the number of tricks each player bid on winning.

The most atomic parts of all that are individual players' bids and plays. So, if the controller layer was to be able to track the progress of the game, it would need to be able to check in after each of those events to see what happened. This led to the following "play-by-play" structure:

<?php
$game = new Spades_Game();
for ($i=0;$i<3;$i++) {
  $game->registerPlayer(new Spades_Player(new Spades_Strategy_Something()));
}
while ($nextPlayer = $game->getNextPlayer()) {
  if ($game->getCurrentPhase() == Spades_Hand::PHASE_BIDDING) {
    $game->acceptBid($nextPlayer->placeBid(), $nextPlayer);
  } else if ($game->getCurrentPhase() == Spades_Hand::PHASE_PLAYING) {
    $game->acceptPlay($nextPlayer->playCard(), $nextPlayer);
  }
}
$scores = $game->getScores();

The nice thing about this is that, although there's quite a bit going on behind the scenes, the controller layer really only needs to be aware of the Spades_Game, Spades_Player, and Spades_Strategy_X classes. As long as the game object returns a player, the controller layer knows that there's more game to be played.

So what's going on internally? Well, Spades_Game is basically a facade managing a sequence of Spades_Hand objects, which in turn manage a sequence of Spades_Trick objects. Take a look:

<?php
class Spades_Game
{
  // ...
  public function getNextPlayer()
  {
    $hand = $this->getCurrentHand();
    if (null === $hand) {
      return null;
    }
 
    $player = $hand->getNextPlayer();
    if (null === $player) {
      // this hand is over...score it, register it, and
      // check to see if the game has been won
      $this->_score();
      $this->_handsPlayed[] = $hand;
      if ($this->_isWon()) {
        return null;
      }
 
      // hasn't been won yet, so we need to start up
      // a fresh hand...
      $this->_incrementDealer();
      $this->_currentHand = new Spades_Hand($this);
      $player = $this->_currentHand->getNextPlayer();
    }
    return $player;
  }
  // ...
}

Notice that, at this point, there isn't any logic regarding the phase we're in (bidding or playing); since the two phases each occur once per hand, it makes more sense to manage them within the Spades_Hand class. Each phase is handled by separate logic, so Spades_Hand::getNextPlayer() makes use of a couple of protected methods to keep things distinct:

<?php
class Spades_Hand
{
  // ...
  public function getNextPlayer()
  {
    switch ($this->getCurrentPhase()) {
      case Spades_Hand::PHASE_BIDDING :
        $player = $this->_getNextBidder();
        break;
      case Spades_Hand::PHASE_PLAYING :
      default :
        $player = $this->_getNextPlayer();
        break;
    }
    return $player;
  }
 
  protected function _getNextBidder()
  {
    if (count($this->getPlayerBids()) <= 0) {
      // nobody has bid yet, so this is the beginning of the hand;
      // deal, and then the player after the dealer is the first bidder
      $this->_cardsDealt = $this->getDeck()->deal($this->getPlayers(), $this->getDealer());
      $this->_currentTrick = new Spades_Trick($this->getGame());
      $position = $this->getDealer() + 1;
    } else {
      $lastbid = end($this->_bids);
      $lastpos = key($this->_bids);
      $position = $lastpos + 1;
    }
    if ($position > count($this->getPlayers()) - 1) {
      $position = 0;
    }
    $players = $this->getPlayers();
    $player = $players[$position];
    return $player;
  }
 
  protected function _getNextPlayer()
  {
    $trick = $this->getCurrentTrick();
    if (null === $trick) {
      return null;
    }
    $player = $trick->getNextPlayer();
    if (null === $player) {
      // the trick is over...score it, register it, and
      // check to see if the hand is complete
      $this->_score();
      $this->_tricksPlayed[] = $trick;
      if ($this->_isFinished()) {
        return null;
      }
 
      // not done yet, start a fresh trick
      $this->_currentTrick = new Spades_Trick($this->getGame());
      $player = $this->_currentTrick->getNextPlayer();
    }
    return $player;
  }
  // ...
}

Notice that the _getNextPlayer() half of the procedure is extremely similar to Spades_Game::getNextPlayer(); we're still passing the buck along the chain to a smaller unit of play...the Spades_Trick instance.

<?php
class Spades_Trick
{
  // ...
  public function getNextPlayer()
  {
    if (count($this->_plays) == count($this->getPlayers())) {
      // everybody's played, so we're done...determine the winner
      // and get on out of here.
      $this->_determineWinner();
      return null;
    } 
    if (null === $this->_currentPlayer) {
      // first play...determine the lead player
      $this->_currentPlayer = $this->getLeadPlayer();
    } else {
      // cycle through to next player
      $this->_currentPlayer = $this->getPlayerAfter($this->_currentPlayer);
    }
    return $this->_currentPlayer;
  } 
  // ...
}

All these layers taken together make it possible for the controller layer to always have access to the next player in sequence, without having to know much of anything about that sequence.

One nice side bonus of this structure is that it would be dead simple for the controller layer to identify certain players as user-controlled, injecting their input into the system in the $game->acceptBid() and $game->acceptPlay() methods.

The next step in all of this, I suppose, will be to develop a simple web interface for viewing the results, and possibly trying to beat all these wonderful computer players.

Categories: