The offending code


In [18]:
def evaluator(dealer, player_, new_deck):
    """Compares hand values and decides who wins and loses.
    """
    """Player wins outright"""
    if player_.hand.handValue() > dealer.hand.handValue() and (
        dealer.hand.handValue() < 22):
        print("\n\nYou win!\n\n\n") 
    """Dealer busts"""
    if player_.hand.handValue() < dealer.hand.handValue() and (
        dealer.hand.handValue() > 22):
        print("\n\nYou win!\n\n\n")
    """Player loses outright"""
    if player_.hand.handValue() < dealer.hand.handValue() and (
        dealer.hand.handValue() < 22):
        print("\n\nYou lose!\n\n\n")
    """Draw situation"""
    if player_.hand.handValue() == dealer.hand.handValue():
        print("\n\nIt's a draw!\n\n\n")

Re-implement as a dictionary


In [138]:
class Player:
    
    def __init__(self, score=0):
        self.score = score
        self.won = None


    def evaluator(self, other):

        def win():
            self.won = True
            return "Player won"

        def lose():
            self.won = False
            return "Player lost"
            
        win_dict = {True: {True: lose(), False: win()},
            False: {True: win(), False: lose()}}
            
        if self.score == other.score:
            return "It's a draw"
        else:
            return win_dict[self.score > other.score][other.score > 22]

In [140]:
player = Player(19)
dealer = Player(24)

player.evaluator(dealer)


Out[140]:
'Player won'

Can we clean this up even more?


In [141]:
class Player:

    def __init__(self, score=0):
        self.score = score
        self.won = None


    def evaluator(self, other):


        win_dict = {True: {True: False, False: True},
        False: {True: True, False: False}}

        if (self.score == other.score):
            print("It's a draw")
                    
        else:
            self.score = win_dict[self.score > other.score][other.score > 22]
            print("self.score = ", self.score)
            print("Player has {}".format((self.score and "won") or "lost"))

In [143]:
player = Player(21)
dealer = Player(20)

player.evaluator(dealer)


self.score =  True
Player has won

Observation: our win dict is an XOR


In [148]:
class Player:

    def __init__(self, score=0):
        self.score = score
        self.won = None


    def evaluator(self, other):


        if (self.score == other.score):
            print("It's a draw")
                    
        else:
            self.won = (self.score > other.score) != (other.score > 22) # Is this readable?
            print("self.score = ", self.score)
            print("Player has {}".format((self.won and "won") or "lost"))

In [149]:
player = Player(21)
dealer = Player(20)

player.evaluator(dealer)


self.score =  21
Player has won

In [ ]: