Mastering Objectoriented Python
上QQ阅读APP看书,第一时间看更新

Some additional class definitions

As noted previously, a player has two strategies: one for betting and one for playing their hand. Each Player instance has a sequence of interactions with a larger simulation engine. We'll call the larger engine the Table class.

The Table class requires the following sequence of events by the Player instances:

  • The player must place an initial bet based on the betting strategy.
  • The player will then receive a hand.
  • If the hand is splittable, the player must decide to split or not based on the play strategy. This can create additional Hand instances. In some casinos, the additional hands are also splittable.
  • For each Hand instance, the player must decide to hit, double, or stand based on the play strategy.
  • The player will then receive payouts, and they must update their betting strategy based on their wins and losses.

From this, we can see that the Table class has a number of API methods to receive a bet, create a Hand object, offer a split, resolve each hand, and pay off the bets. This is a large object that tracks the state of play with a collection of Players.

The following is the beginning of a Table class that handles the bets and cards:

class Table:
    def __init__( self ):
        self.deck = Deck()
    def place_bet( self, amount ):
        print( "Bet", amount )
    def get_hand( self ):
        try:
            self.hand= Hand2( d.pop(), d.pop(), d.pop() )
            self.hole_card= d.pop()
        except IndexError:
            # Out of cards: need to shuffle.
            self.deck= Deck()
            return self.get_hand()
        print( "Deal", self.hand )
        return self.hand
    def can_insure( self, hand ):
        return hand.dealer_card.insure

The Table class is used by the Player class to accept a bet, create a Hand object, and determine if theinsurance bet is in play for this hand. Additional methods can be used by the Player class to get cards and determine the payout.

The exception handling shown in get_hand() is not a precise model of casino play. This may lead to minor statistical inaccuracies. A more accurate simulation requires developing a deck that reshuffles itself when empty instead of raising an exception.

In order to interact properly and simulate realistic play, the Player class needs a betting strategy. The betting strategy is a stateful object that determines the level of the initial bet. The various betting strategies generally change the bet based on whether the game was a win or a loss.

Ideally, we'd like to have a family of betting strategy objects. Python has a module with decorators that allows us to create an abstract superclass. An informal approach to creating Strategy objects is to raise an exception for methods that must be implemented by a subclass.

We've defined an abstract superclass as well as a specific subclass as follows to define a flat betting strategy:

class BettingStrategy:
    def bet( self ):
        raise NotImplementedError( "No bet method" )
    def record_win( self ):
        pass
    def record_loss( self ):
        pass

class Flat(BettingStrategy):
    def bet( self ):
        return 1

The superclass defines the methods with handy default values. The basic bet() method in the abstract superclass raises an exception. The subclass must override the bet() method. The other methods can be left to provide the default values. Given the game strategy in the previous section plus the betting strategy here, we can look at more complex __init__() techniques surrounding the Player class.

We can make use of the abc module to formalize an abstract superclass definition. It would look like the following code snippet:

import abc
class BettingStrategy2(metaclass=abc.ABCMeta):
    @abstractmethod
    def bet( self ):
        return 1
    def record_win( self ):
        pass
    def record_loss( self ):
        pass

This has the advantage that it makes the creation of an instance of BettingStrategy2, or any subclass that failed to implement bet(), impossible. If we try to create an instance of this class with an unimplemented abstract method, it will raise an exception instead of creating an object.

And yes, the abstract method has an implementation. It can be accessed via super().bet().