Exemple #1
0
    def test_computer_stops_at_21(self):
        player_hand = Hand("")
        player_hand.add(Card("spades", 13))
        player_hand.add(Card("clubs", 8))

        cards = [Card("hearts", 1), Card("hearts", 7), Card("hearts", 13)]
        pile = Deck(cards)

        computer_hand = Hand("")
        Computer().play(computer_hand, pile, player_hand)
        self.assertEqual(computer_hand.sum(), 21)
Exemple #2
0
    def test_computer_always_tries_to_get_higher_total_than_player(self):
        player_hand = Hand("")
        player_hand.add(Card("spades", 13))
        player_hand.add(Card("clubs", 7))

        cards = [Card("hearts", 3), Card("hearts", 6), Card("hearts", 13)]
        deck = Deck(cards)

        computer_hand = Hand("")
        Computer().play(computer_hand, deck, player_hand)
        self.assertTrue(computer_hand.sum() > 21)
Exemple #3
0
def playGame(f):
    # Set up deck and hand
    deck = Deck()
    hand = Hand()

    # Write deck setup
    f.write("Deck: ")
    for i in range(len(deck)):
        f.write(deck.view(i).getNickName() + " ")

    f.write("\n")

    stillPlaying = True
    needToDraw = True
    noMatch = False

    while stillPlaying:

        # draw up to 4 if able and if need to
        while (len(hand) < 4 and needToDraw) or noMatch:
            if len(deck) > 0:
                hand.add(deck.draw())
                noMatch = False
            else:
                break

        needToDraw = False

        while not needToDraw:
            if not isMatch(hand) and not isSuit(hand):
                needToDraw = True
                noMatch = True
            elif isMatch(hand):
                hand.matchRemove()
            elif isSuit(hand):
                hand.suitsRemove()

        if len(deck) == 0 and noMatch:
            stillPlaying = False

    # Determine Results
    cardsLeft = len(hand)
    f.write("Ending Hand: ")

    for j in range(cardsLeft):
        f.write(hand.view(j).getNickName() + " ")

    f.write("\n" + str(cardsLeft) + " Cards Left\n\n")

    if cardsLeft == 0:
        return True
    else:
        return False
Exemple #4
0
    def play(hand: Hand, deck: Deck, player_hand: Hand):

        if RuleSet.is_bust(player_hand):
            # No need to do anything
            return

        while deck.count() > 0:
            hand.add(deck.draw())

            if RuleSet.sums_to_21(hand) or RuleSet.is_bust(
                    hand) or hand.sum() >= player_hand.sum():
                # Computer is cheating looking at player cards
                return
    def test_three_of_a_kind(self):
        deck = Deck()
        deck.get_new_deck()

        community_cards = []
        community_cards.append (Card('2', 'D'))
        community_cards.append (Card('2', 'C'))
        community_cards.append (Card('4', 'D'))

        my_hand = Hand(community_cards)
        my_hand.add (Card('2', 'S'))
        my_hand.add (Card('6', 'D'))

        assert my_hand.three_of_a_kind() and not my_hand.one_pair()
    def test_one_pair(self):
        deck = Deck()
        deck.get_new_deck()

        community_cards = []
        community_cards.append (Card('2', 'D'))
        community_cards.append (Card('3', 'D'))
        community_cards.append (Card('4', 'D'))

        my_hand = Hand(community_cards)
        my_hand.add (Card('2', 'S'))
        my_hand.add (Card('6', 'D'))

        assert my_hand.one_pair() and not my_hand.is_flush()
    def test_straight_flash(self):
        deck = Deck()
        deck.get_new_deck()

        community_cards = []
        community_cards.append (deck.deal())
        community_cards.append (deck.deal())
        community_cards.append (Card('2', 'D'))
        community_cards.append (Card('3', 'D'))
        community_cards.append (Card('4', 'D'))

        my_hand = Hand(community_cards)
        my_hand.add (Card('5', 'D'))
        my_hand.add (Card('6', 'D'))

        assert my_hand.is_straight() and my_hand.is_flush()
    def test_flushes2(self):
        deck = Deck()
        deck.get_new_deck()

        community_cards = []
        community_cards.append (deck.deal())
        community_cards.append (deck.deal())
        community_cards.append (Card('2', 'D'))
        community_cards.append (Card('3', 'D'))
        community_cards.append (Card('4', 'D'))

        my_hand = Hand(community_cards)
        my_hand.add (Card('T', 'D'))
        my_hand.add (Card('J', 'D'))

        assert my_hand.is_flush()
Exemple #9
0
    def test_full_house(self):
        pygame.image = unittest.mock.Mock()
        pygame.image.load.return_value = None

        hand = Hand()
        hand.add(Card("ten", "hearts", False))
        hand.add(Card("ten", "spades", False))
        hand.add(Card("jack", "diamonds", False))
        hand.add(Card("jack", "clubs", False))
        hand.add(Card("jack", "hearts", False))
        c = ComboList()
        self.assertEqual(Combo.FULL_HOUSE, c.match_any(hand).combo_type)
Exemple #10
0
 def test_ace_ranks_1_when_hand_getting_bust(self):
     hand = Hand("")
     hand.add(Card("diamond", 5))
     hand.add(Card("diamond", 1))
     hand.add(Card("clubs", 1))
     hand.add(Card("hearts", 1))
     self.assertEqual(hand.sum(), 21)
Exemple #11
0
def add_or_remove_card(card: int, hand: Hand,
                       card_hand_chamber: CardHandChamber):
    # here, we attempt to add a card that has just been clicked:
    #   if the card is not in the current hand, it is added
    #   else, it is remove
    # particular order is to hopefully minimize exceptions but should be
    # verified empirically TODO
    try:
        hand.add(card)
        card_hand_chamber.select_card(card)
    # TODO: should I just pass the error message through no matter the problem?
    #       what is the point of having these separate errors?
    except DuplicateCardError:
        hand.remove(card)
        card_hand_chamber.deselect_card(card)
    except FullHandError:
        alert_current_hand_full()
        # TODO: why do i need the line below
        # client_update_current_hand(hand)  # TODO: this one doesn't require changing the session
        return
    except Exception as e:
        print("Bug: probably the card hand chamber freaking out.")
        raise e
Exemple #12
0
def main():
    d = Deck()
    d.shuffle()

    player_hand = Hand()
    dealer_hand = Hand()

    for i in range(2):
        player_hand.add(d.draw())
        dealer_hand.add(d.draw())

    print("Player's hand:")
    print(player_hand)
    print("Dealer's hand:")
    print(dealer_hand)

    while player_hand.getValue() < 21:
        choice = input("Would you like hit or stay? ")
        if choice == "hit":
            player_hand.add(d.draw())
            print("Player's hand:")
            print(player_hand)
        elif choice == "stay":
            break
        else:
            print("Invalid choice!")

    if player_hand.getValue() > 21:
        print("You lose! busted.")
    else:
        while dealer_hand.getValue() < 17:
            dealer_hand.add(d.draw())

        if dealer_hand.getValue() > 21:
            print("You win! Dealer busted.")
        else:
            if dealer_hand.getValue() < player_hand.getValue():
                print("You win!")
            elif dealer_hand.getValue() == player_hand.getValue():
                print("It's a draw!")
            else:
                print("You lose!")

    print("Player's hand:")
    print(player_hand)
    print("Dealer's hand:")
    print(dealer_hand)
Exemple #13
0
    def test_straight(self):
        pygame.image = unittest.mock.Mock()
        pygame.image.load.return_value = None

        hand = Hand()
        hand.add(Card("ten", "hearts", False))
        hand.add(Card("six", "spades", False))
        hand.add(Card("eight", "diamonds", False))
        hand.add(Card("seven", "clubs", False))
        hand.add(Card("nine", "hearts", False))
        c = ComboList()
        self.assertEqual(Combo.STRAIGHT, c.match_any(hand).combo_type)
    def test_hand(self):
        window = tk.Tk()
        window.title('test')

        thisCard = Card(Card.SPADES, 10, 10)
        anotherCard = Card(Card.SPADES, 5, 5)
        thirdCard = Card(Card.CLUBS, 11, 1)

        thisHand = Hand()
        thisHand.add(thisCard)
        thisHand.add(anotherCard)
        thisHand.add(thirdCard)

        self.assertEqual(len(thisHand.cards), 3)
        self.assertEqual(thisHand.total, 26)

        thisHand.reset()
        self.assertEqual(len(thisHand.cards), 0)
Exemple #15
0
card7 = Card(rank="7", suit="c")
card8 = Card(rank="8", suit="c")
card9 = Card(rank="9", suit="c")
card10 = Card(rank="10", suit="c")
card11 = Card(rank="11", suit="c")
card12 = Card(rank="12", suit="c")
card13 = Card(rank="13", suit="c")

print(card1)  # Ac
print(card2)  # 2c
print(card3)  # 3c
print(card4)  # 4c
print(card5)  # 5c

my_hand = Hand()
print(my_hand)  # <empty>
my_hand.add(card1)
my_hand.add(card2)
my_hand.add(card3)
my_hand.add(card4)
my_hand.add(card5)
print(my_hand)  # Ac 2c 3c 4c 5c

your_hand = Hand()
my_hand.give(card1, your_hand)
my_hand.give(card2, your_hand)
print(your_hand)  # Ac 2c
print(my_hand)  # 3c 4c 5c
my_hand.clear()
print(my_hand)  # <empty>
Exemple #16
0
class BlackJack(GameGUI):
    """Implements a simple version of the BlackJack card game and displays the
    game to the player."""
    def __init__(self, window):
        super().__init__(window)
        self.player_wins = 0
        self.dealer_wins = 0
        self.game_status = 'In Progress...'
        self.in_progress = True
        self.status_color = 'green'
        self.text_font = tk.font.Font(family='Helvetica',
                                      size=15,
                                      weight='bold')
        Card.load_images()
        self.deck = Deck()
        self.player_hand = Hand()
        self.dealer_hand = Hand()

    def refresh_canvas(self):
        """Method which refreshed the canvas (text and player/dealer cards)
        based on the updated BlackJack attributes.
        No inputs or outputs."""
        self._canvas.delete(tk.ALL)
        self._canvas.create_text(10,
                                 10,
                                 anchor=tk.NW,
                                 fill='black',
                                 font=self.text_font,
                                 text=f'Player Hand Total:'
                                 f' {self.player_hand.total}')
        self._canvas.create_text(10,
                                 150,
                                 anchor=tk.NW,
                                 font=self.text_font,
                                 fill='black',
                                 text=f'Dealer Hand Total:'
                                 f' {self.dealer_hand.total}')
        self._canvas.create_text(100,
                                 300,
                                 anchor=tk.NW,
                                 fill=self.status_color,
                                 font=self.text_font,
                                 text=f'Game Status: {self.game_status}')
        self._canvas.create_text(10,
                                 330,
                                 anchor=tk.NW,
                                 fill='black',
                                 font=self.text_font,
                                 text=f'Dealer Wins: {self.dealer_wins}')
        self._canvas.create_text(10,
                                 355,
                                 anchor=tk.NW,
                                 fill='black',
                                 font=self.text_font,
                                 text=f'Player Wins: {self.player_wins}')
        self.player_hand.draw(self._canvas, 10, 35)
        self.dealer_hand.draw(self._canvas, 10, 175)

    def reset(self):
        """Restarts the game (resets player/dealer hands, deals two cards for
        the player and dealer, and checks for the edge case of two Aces).
        No inputs or outputs."""
        self.player_hand.reset()
        self.dealer_hand.reset()
        self.player_hand.add(self.deck.deal())
        self.player_hand.add(self.deck.deal())
        self.dealer_hand.add(self.deck.deal())
        self.dealer_hand.add(self.deck.deal())
        # Checking for edge cases where player/dealer (or both) have two aces
        if self.player_hand.total == 22 and self.dealer_hand.total == 22:
            self.status_color = 'red'
            self.game_status = "TIE Game... Press 'r' to start game"
            self.in_progress = False
        elif self.player_hand.total == 22:
            self.status_color = 'red'
            self.game_status = "Dealer WINS... Press 'r' to start game"
            self.dealer_wins += 1
            self.in_progress = False
        elif self.dealer_hand.total == 22:
            self.status_color = 'red'
            self.game_status = "Player WINS... Press 'r' to start game"
            self.player_wins += 1
            self.in_progress = False
        else:
            self.game_status = 'In Progress...'
            self.status_color = 'green'
            self.in_progress = True
        self.refresh_canvas()

    def player_hit(self):
        """Functionality for when a player 'hits'. If the player's total score
        is over 21, the player loses.
        No inputs or outputs."""
        if self.in_progress:
            self.player_hand.add(self.deck.deal())
            if self.player_hand.total > 21:
                self.status_color = 'red'
                self.game_status = "Dealer WINS... Press 'r' to start game"
                self.dealer_wins += 1
                self.in_progress = False
            self.refresh_canvas()

    def player_stand(self):
        """Functionality for when a player 'stands'. The dealer automatically
        draws cards until their total score is 17 or greater. Based on the
        dealer's score, determines who wins.
        No inputs or outputs."""
        if self.in_progress:
            while self.dealer_hand.total < 17:
                self.dealer_hand.add(self.deck.deal())
            if self.dealer_hand.total > 21 or self.dealer_hand.total < \
                    self.player_hand.total:
                self.status_color = 'red'
                self.game_status = "Player WINS... Press 'r' to start game"
                self.player_wins += 1
            elif self.player_hand.total == self.dealer_hand.total:
                self.status_color = 'red'
                self.game_status = "TIE Game... Press 'r' to start game"
            else:
                self.status_color = 'red'
                self.game_status = "Dealer WINS... Press 'r' to start game"
                self.dealer_wins += 1
            self.in_progress = False
            self.refresh_canvas()
Exemple #17
0
class Player(object):
	
	score = 0
	num_wins = 0
    
	def __init__(self, name="", ai=True):
		self.name = name
		self.hand = Hand()
		self.live = True
		self.busted = False
		self.ai = ai
		
	def optimize(self):	
		# Optimize Ace value for player score
		for card in self.hand.cards:
			if self.score > 21:
				if card.value == 11:
					card.value = 1
					self.score -= 10
        
	def draw_card(self, card):
		self.hand.add(card)
		self.score += card.value
		self.optimize()
		if self.score > 21:
			self.live = False
		
	def get_card(self, index):
		card = self.hand.cards[index]
		return card
		
	def gen_name(self):
		# Use names.txt to generate random AI name
		line = random.randint(100, 4000)
		self.name = linecache.getline('names.txt', line)
		self.name = self.name.split()[0]

	def hit(self, max_val, live_players):
		# Human determines decision
		if not self.ai:
			choice = raw_input("{0}, do you want a hit? (yes/no): ".format(self.name))
			if choice in ("yes", "y", "yeah", "yea"):
				return True
			elif choice in("no", "n", "nope"):
				return False
			else:
				return hit(self, max_val, live_players)
		# AI determines decision
		else:
			# In lead
			if self.score == max_val:
				if self.score >= 19:
					return False
				else:
					return True
			# Not in lead
			else:
				if self.score < 11:
					return True
						
				if self.score < 18:
					hit_chance = random.randint(0, 5)
					if hit_chance > 1:
						return True
					else:
						return False
				else:
					return False
Exemple #18
0
class BlackJack(GameGUI):
    '''implements a simple version of the cardgame  and  displays  the  game  state  to  the  player'''


    # In pixels, specify the vertical separation between different elements in the canvas.
    SMALL_VERTICAL_OFFSET= 20
    MEDIUM_VERTICAL_OFFSET= 30

    # Specify where to put the game status axis
    GAME_STATUS_TEXT_X_AXIS= Card.IMAGE_WIDTH_IN_PIXELS*3 + 10


    def __init__(self, window):
        '''
        Attributes (not already defined in the superclass):
        numPlayerWins: an int, keep track of times the player has won
        numDealerWins: an int, keep track of times the dealer has won
        gameStatusText: a str, game status text indicating the current state of the game
        gameStatusColor: a str, the color of the game status text
        playerHand: a Hand object, representing the player's hand
        dealerHand: a Hand object, representing the dealer's hand
        deck: a Deck object, representing the current deck of cards
        '''

        super().__init__(window)

        self.reset()

    def reset(self):
        '''Restarts the game.  This method is automatically called whenever the user hits the “r” key.'''


        # Initialize game situation
        self.numPlayerWins= 0
        self.numDealerWins= 0
        self.gameStatusText= "In Progress..."
        self.gameStatusColor= "green"

        # Initialize (empty) player and dealer hands
        self.playerHand= Hand()
        self.dealerHand= Hand()

        # Initialize deck
        self.deck= Deck()

        # Load images
        Card.load_images()

        # Draw canvas
        self.draw_canvas()

    def player_hit(self):
        '''
        The user is requesting to perform a hit on their hand.  
        This means that the method must draw acard from the deck and add it to the player’s hand.
        '''

        # Is this the first hit in a new game? If so, clear the player and dealer hands, and reset the game status
        self.new_game_check()

        # Deal a new card to the player
        self.playerHand.add(self.deck.deal())
        self.reshuffle_check()

        # Did the player bust?
        if self.playerHand.total > 21:
            self.gameStatusColor= "red"
            self.gameStatusText= "Dealer WINS... Press 'r' to start a new game"
            self.numDealerWins+= 1

        # Update GUI
        self.draw_canvas()

    def player_stand(self):
        '''
        The user is requesting to perform a stand on their hand.  This means that the method must
        continuously add cards to the dealer’s hand until their hand is greater than or equal to 17.
        '''

        # Is this the first stand in a new game? If so, clear the player and dealer hands, and reset the game status
        self.new_game_check()
        
        # Add cards to the dealer's hand until the dealer's hand is greater than or equal to 17
        while self.dealerHand.total < 17:
            self.dealerHand.add(self.deck.deal())
            self.reshuffle_check()

        self.gameStatusColor= "red"
        # Did the dealer bust OR did the player's total exceed the dealer's score?
        if (self.dealerHand.total > 21) or (self.dealerHand.total < self.playerHand.total):
            self.gameStatusText= "Player WINS... Press 'r' to start a new game"
            self.numPlayerWins+= 1

        # Was there a tie?    
        elif (self.dealerHand.total == self.playerHand.total):
            self.gameStatusText= "TIE Game...Press 'r' to start a new game"

        # Did the dealer win?
        elif (self.dealerHand.total > self.playerHand.total):
            self.gameStatusText= "Dealer WINS... Press 'r' to start a new game"
            self.numDealerWins+= 1

        # Update GUI
        self.draw_canvas()

    def reshuffle_check(self):
        '''Check if the deck has 13 cards remaining. If so, reschuffle the deck.'''

        if self.deck.size <= 13:
            self.deck.shuffle()

    def new_game_check(self):
        '''
        If this is a new game, clear the player and dealer hands, and reset the game status
        '''
        
        if self.gameStatusText != "In Progress...":
            self.gameStatusText= "In Progress..."
            self.gameStatusColor= "green"
            self.playerHand.reset()
            self.dealerHand.reset()

    def draw_canvas(self):
        ''' Update the GUI and redraw everything '''

        # Initial coordinates
        current_x= 10
        current_y= 10

        # Define the font for everything
        REGULAR_FONT= font.Font(family='Helvetica', size=10, weight='bold')

        # Time to update the GUI
        self._canvas.delete(tk.ALL)

        # Text with the current player hand total
        self._canvas.create_text(current_x, current_y, 
                                            anchor=tk.NW, 
                                            font=REGULAR_FONT, 
                                            text=f'Player Hand Total: {self.playerHand.total}')

        # The images of the player's current hand
        current_y+= BlackJack.SMALL_VERTICAL_OFFSET
        self.playerHand.draw(self._canvas, current_x, current_y, None, None)

        # The text of the dealer's current hand total
        current_y+= (BlackJack.MEDIUM_VERTICAL_OFFSET + Card.IMAGE_HEIGHT_IN_PIXELS)
        self._canvas.create_text(current_x, current_y, 
                                            anchor=tk.NW, 
                                            font=REGULAR_FONT, 
                                            text=f'Dealer Hand Total: {self.dealerHand.total}')

        # The images of the dealer's current hand total
        current_y+= BlackJack.SMALL_VERTICAL_OFFSET
        self.dealerHand.draw(self._canvas, current_x, current_y, None, None)

        # The game status
        current_y+= (BlackJack.MEDIUM_VERTICAL_OFFSET + Card.IMAGE_HEIGHT_IN_PIXELS)
        self._canvas.create_text(BlackJack.GAME_STATUS_TEXT_X_AXIS, current_y, 
                                            anchor=tk.NW, 
                                            font=REGULAR_FONT,
                                            fill= self.gameStatusColor,
                                            text=f'Game Status: {self.gameStatusText}')

        # The text with the dealer wins and the player wins
        current_y+= BlackJack.SMALL_VERTICAL_OFFSET
        self._canvas.create_text(current_x, current_y, 
                                            anchor=tk.NW, 
                                            font=REGULAR_FONT, 
                                            text=f'Dealer Wins: {self.numDealerWins}')
                                            
        current_y+= BlackJack.SMALL_VERTICAL_OFFSET
        self._canvas.create_text(current_x, current_y, 
                                            anchor=tk.NW, 
                                            font=REGULAR_FONT, 
                                            text=f'Player Wins: {self.numPlayerWins}')
Exemple #19
0
    count_my_one_pair = 0
    count_my_hand_strength = 0
    deck = Deck()

    for i in xrange(int(total)):
        deck.get_new_deck()

        community_cards = []
        community_cards.append (community_cards1 or deck.deal())
        community_cards.append (community_cards2 or deck.deal())
        community_cards.append (community_cards3 or deck.deal())
        community_cards.append (community_cards4 or deck.deal())
        community_cards.append (community_cards5 or deck.deal())

        my_hand = Hand(community_cards)
        my_hand.add (my_cards1)
        my_hand.add (my_cards2)

        if my_hand.is_flush(): count_my_flushes += 1.0
        if my_hand.is_straight(): count_my_straights += 1.0
        if my_hand.four_of_a_kind(): count_my_four_of_a_kind += 1.0
        if my_hand.three_of_a_kind(): count_my_three_of_a_kind += 1.0
        if my_hand.one_pair(): count_my_one_pair += 1.0
        count_my_hand_strength += my_hand.get_strength()

    count_their_straights = 0
    count_their_flushes = 0
    count_their_four_of_a_kind = 0
    count_their_three_of_a_kind = 0
    count_their_one_pair = 0
    count_their_hand_strength = 0
Exemple #20
0
class Player(object):

    def __init__(self):
        self.topHand = Hand()
        self.midHand = Hand()
        self.botHand = Hand()

    def addTop(self, card):
        if len(self.topHand) >=3:
            raise OFCError('This hand is full!')
            return
        self.topHand.add(card)
        

    def addMid(self, card):
        if len(self.midHand) >= 5:
            raise OFCError('This hand is full!')
            return
        self.midHand.add(card)

    def addBot(self, card):
        if len(self.botHand) >= 5:
            raise OFCError('This hand is full!')
            return
        self.botHand.add(card)

    def fullHands(self):
        return len(self.botHand) == 5 and len(self.midHand) == 5 and len(self.topHand) == 3

    def printStatus(self):
        print ("Top Hand: ")
        self.topHand.printHand()
        print ("\n\nMiddle Hand: ")
        self.midHand.printHand()
        print ("\n\nBottom Hand: ")
        self.botHand.printHand()

    def addCard(self, card, hand):
        if hand == 1:
            self.addBot(card)
        elif hand == 2:
            self.addMid(card)
        elif hand == 3:
            self.addTop(card)

    def playManual(self, deck):
        nextCard = deck.pop()
        print "\nthe current card is " + nextCard.value
        choice = raw_input("where would you like this card?\nplease enter bot or 1 for bottom,\nmid or 2 for middle, top or 3 for top\n--> ")
        if choice == "1" or choice == "bot":
            try:
                self.addBot(nextCard)
            except OFCError:
                print("that hand is full! try again")
                deck.heap(nextCard)
                self.playManual(deck)
        elif choice == "2" or choice == "mid":
            try:
                self.addMid(nextCard)
            except OFCError:
                print("that hand is full! try again")
                deck.heap(nextCard)
                self.playManual(deck)
        elif choice == "3" or choice == "top":
            try:
                self.addTop(nextCard)
            except OFCError:
                print("that hand is full! try again")
                deck.heap(nextCard)
                self.playManual(deck)
        else:
            print "that choice was not recognized!"
            deck.heap(nextCard)

    def playRandom(self, card):
        spaces = []
        for i in range(5 - len(self.botHand)):
            spaces.append(1)
        for i in range(5 - len(self.midHand)):
            spaces.append(2)
        for i in range(3 - len(self.topHand)):
            spaces.append(3)
        if len(spaces) == 0:
            raise OFCError("No empty spaces!")
        else:
            choice = random.choice(spaces)
            self.addCard(card, choice)
Exemple #21
0
 def test_hand_sums_according_to_rank(self):
     hand = Hand("")
     hand.add(Card("diamond", 7))
     hand.add(Card("diamond", 10))
     hand.add(Card("diamond", 2))
     self.assertEqual(hand.sum(), 19)
def run():
    global game_finished
    global startTime
    global scoreKeeper
    hard = False

    playfield = PlayField()
    hand = Hand()

    clock = pygame.time.Clock()
    is_running = True
    show_menu = True

    while is_running:
        if not show_menu:
            playfield.advance(hand, hard)
            clock.tick(25)

        #event handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_running = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    is_running = False
                if event.key == pygame.K_a:
                    a, b = new_easy_rectangle_pair(
                        pygame.Rect(100, 100, 100, 100),
                        pygame.Rect(100, 100, 100, 100))
                    hand.add(b)
                if event.key == pygame.K_l:
                    to_remove = randint(0, len(hand.pieces) - 1)
                    hand.remove(to_remove)

            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:

                    #catch event for dificulty selection
                    if show_menu and Menu.easy.rect.collidepoint(event.pos):
                        hard = False
                        show_menu = False
                    if show_menu and Menu.hard.rect.collidepoint(event.pos):
                        hard = True
                        show_menu = False

                    #catch event for GameOverScreen
                    if game_finished and GameOverScreen.restart.rect.collidepoint(
                            event.pos):
                        game_finished = False
                        show_menu = True  #set this to true when select dificulty is a thing
                        scoreKeeper = ScoreKeeper()
                        playfield = PlayField()
                        hand = Hand()
                        startTime = time.time()
                        elapsedTime = 0

                    for i, r in enumerate(hand.pieces):
                        grabbable = r.grabbable
                        r = r.rect
                        if r.collidepoint(
                                event.pos) and grabbable and not show_menu:
                            hand.selected = i
                            selected_offset_x = r.x - event.pos[0]
                            selected_offset_y = r.y - event.pos[1]

            elif event.type == pygame.MOUSEBUTTONUP:
                if event.button == 1:
                    if hand.selected is not None:
                        buckets = playfield.buckets()
                        foundMatch = False
                        for i in range(0, len(buckets)):
                            if buckets[i].rect.colliderect(
                                    hand.selected_piece().rect
                            ) and buckets[i].value == hand.selected_piece(
                            ).value:
                                playfield.remove(i)
                                playfield.speed += 0.01
                                hand.remove(hand.selected)
                                scoreKeeper.increment(
                                    buckets[i].value)  #increment score by 10
                                foundMatch = True
                                break

                        #reset combo if no matching piece was selected
                        if foundMatch == False:
                            scoreKeeper.endCombo()
                        hand.selected = None
                        hand.realign()

            elif event.type == pygame.MOUSEMOTION:
                if hand.selected is not None:  # selected can be `0` so `is not None` is required
                    # move object
                    hand.selected_piece(
                    ).rect.x = event.pos[0] + selected_offset_x
                    hand.selected_piece(
                    ).rect.y = event.pos[1] + selected_offset_y

        #keep track of game state here
        buckets = playfield.buckets()
        for bucket in buckets:
            if bucket.rect.colliderect(HAND_AREA):
                game_finished = True  #game over condition

        #draw graphics
        screen.fill((32, 34, 37))
        pygame.draw.rect(screen, (64, 68, 75), HAND_AREA)

        drawScoreAndTime()
        if game_finished:
            GameOverScreen.draw(screen)
        else:
            for r in playfield.buckets():
                r.draw_on(screen)
            for r in hand.pieces:
                r.draw_on(screen)
            if show_menu:
                Menu.draw(screen)
        pygame.display.update()

    pygame.quit()
Exemple #23
0
 def test_ace_ranks_14(self):
     hand = Hand("")
     hand.add(Card("diamond", 1))
     self.assertEqual(hand.sum(), 14)
Exemple #24
0
 def draw(hand: Hand, deck: Deck):
     hand.add(deck.draw())
Exemple #25
0
     print("BANKRUPT!")
     game = False
 else:
     if deck.length() < 52 / 2:
         deck = Deck()
         deck.shuffle()
         print("..shuffling..")
     # bet
     lastbet = getwager(bank, lastbet)
     bank -= lastbet
     print(f"Bet: {lastbet}, Bank: {bank}")
     # hand
     dealer = Hand()
     player = Hand()
     # deal
     dealer.add(deck.draw())
     player.add(deck.draw())
     dealer.add(deck.draw())
     player.add(deck.draw())
     # redraw
     print(
         f"Dealer: {dealer.dealershow()}, total: {range(dealer.dealersum(),dealer.dealersum()+11)}"
     )
     print(f"Player: {player}, total: {player.sum()}")
     # Dealer blackjack?
     if dealer.sum() == 21 and player.sum() < 21:
         print("Dealer blackjack!")
         print(f"Lost {lastbet}")
         continue
     # Player blackjack?
     if player.sum() == 21: