예제 #1
0
def display_row(contestant):
	'''
	displays 6 cards in a row

	args:
		contestant = string: specifies which row cards are the be displayed on
	
	effect:

	'''
	global dealer_hand_display
	global player_hand_display

	if contestant == 'player':
		vs = 1
		save_loc = player_hand_display
	if contestant == 'dealer':
		vs = 0
		save_loc = dealer_hand_display
	for i in range(6):
		card_disp = CardLabel(root)
		card_disp.grid(row=vs,column=(i))
		root.columnconfigure(i, minsize=85)
		save_loc.append(card_disp)
		card_disp.display('blank')
예제 #2
0
def display_cards(hand,restart=False,show_hand=False):
	'''
	This creates the labels for each user and makes the first card of the comp
	uters  hand visible if show hand is true. If restart is true then all
	lables are reset.
	'''
	for i in range(len(hand)):
		a = CardLabel(root)
		if i == 0 and hand == computer_hand and not show_hand:
			a.display('back',hand[i].n)
		else:
			a.display('front',hand[i].n)
		if hand == computer_hand:
			a.grid(row=0,column=i+1)
		else:
			a.grid(row=1,column=i+1)
	if restart == True:
		for i in range(len(hand),6):
			a = CardLabel(root)
			a.display(1)
			if hand == computer_hand:
				a.grid(row=0,column=i+1)
			else:
				a.grid(row=1,column=i+1)
예제 #3
0
class BlackJack(Frame):
    ''' Creates Widgets: labels for players and buttons for the user to interact with and play the game '''
    players = ['Dealer:', 'Player1:']

    def __init__(self, master=None):
        Frame.__init__(self, master)
        CardLabel.load_images()
        # Create Labels
        dealerLabel = Label(root, text=self.players[0])
        dealerLabel.grid(row=0, column=0)
        player1Label = Label(root, text=self.players[1])
        player1Label.grid(row=2, column=0)
        # Set dimensions of the game space
        for i in range(6):
            root.columnconfigure(i, minsize=80)
        for i in [1, 3]:
            root.rowconfigure(i, minsize=106)
        # Buttons
        self._dealButton = Button(root,
                                  text='Deal',
                                  command=self.deal,
                                  padx=10)
        self._dealButton.grid(row=4, column=0, pady=0)
        self._hitButton = Button(root, text='Hit', command=self.hit, padx=14)
        self._hitButton.grid(row=4, column=1, pady=0)
        self._passButton = Button(root,
                                  text='Pass',
                                  command=self.stand,
                                  padx=10)
        self._passButton.grid(row=4, column=2, pady=0)

    def deal(self):
        ''' Adds cards to the game: Creates a deck, shuffles the deck, deals cards to the dealer and then the player '''
        BlackJack.__init__(
            self)  # Reinstantiates the class to reset the game space
        self._deck = Deck.Deck()  # 1) Create Deck
        self._deck.shuffle()  # 2) shuffle deck

        self._dealer = self._deck.deal(2)  # 3) Create Dealers Hand
        self._dealercard1 = CardLabel(root)
        self._dealercard1.grid(row=1, column=0)
        self._dealercard1.display('back', self._dealer[0].num())

        self._dealercard2 = CardLabel(root)
        self._dealercard2.grid(row=1, column=1)
        self._dealercard2.display('front', self._dealer[1].num())
        self._player = self._deck.deal(2)  # 4) Create Players hand

        for i in range(len(self._player)):
            self._playercards = CardLabel(root)
            self._playercards.grid(row=3, column=i)
            self._playercards.display('front', self._player[i].num())

    def hit(self):
        ''' Appends a card to the players hand and then displays that card. If the player busts gameover() is called'''
        self._player.append(self._deck.deal(1)[0])
        self.hits = CardLabel(root)
        self.hits.grid(row=3, column=len(self._player) - 1)
        self.hits.display('front', self._player[-1].num())
        #print(self._player)
        if (BlackJack.total(self._player)) > 21:
            BlackJack.gameover(self, 0, 'You Busted!')

    def stand(self):
        ''' this function is called when the player clicks the pass button. To stand in blackjack means you pass priority and allow the dealer to play out their hand '''
        self._dealercard1.display('front', self._dealer[0].num())
        while (BlackJack.total(self._dealer) < 22):
            if (BlackJack.total(self._dealer)) < 17:
                self._dealer.append(self._deck.deal(1)[0])
                self.dealerhits = CardLabel(root)
                #self.dealerhits.after(2000)
                self.dealerhits.grid(row=1, column=len(self._dealer) - 1)
                self.dealerhits.display('front', self._dealer[-1].num())
            else:
                return self.compare(self._dealer, self._player)

        return BlackJack.gameover(self, 1, 'Dealer Busted!')

    def compare(self, dealer, player):
        ''' Compares Dealer hand to Players hand and makes the call to gameover() with appropriate results '''
        dealertotal, playertotal = BlackJack.total(dealer), BlackJack.total(
            player)

        if dealertotal > playertotal:
            BlackJack.gameover(self, 0)
        elif dealertotal < playertotal:
            BlackJack.gameover(self, 1)
        elif dealertotal == 21 and 2 == len(dealer) < len(player):
            BlackJack.gameover(self, 0, "Dealer BlackJack!")
        elif playertotal == 21 and 2 == len(player) < len(dealer):
            BlackJack.gameover(self, 0, "Player BlackJack!")
        else:
            BlackJack.gameover(self, 2, "Push")

    def gameover(self, win=1, result="Highscore wins"):
        ''' called from many other methods; reports if the player wins or loses the game via message box and signals player to start new a game '''
        global Score
        script = [" YOU LOSE... ", "YOU WIN!", "No winners"]
        msg = showinfo(message=(script[win],
                                " Click the 'Deal' button to play again"),
                       title=("GAME OVER:",
                              result))  # This should be a message box
        self._hitButton['state'] = 'disabled'
        self._passButton['state'] = 'disabled'
        self._dealButton['bg'] = 'green'

    def total(hand):
        ''' calculates the total point value of a hand, allowing for smart handing of Aces dual, but mutually exclusive value state '''
        values = {
            "2": 2,
            "3": 3,
            "4": 4,
            "5": 5,
            "6": 6,
            "7": 7,
            "8": 8,
            "9": 9,
            "10": 10,
            "J": 10,
            "Q": 10,
            "K": 10,
            "A": 11
        }

        result = 0
        numAces = 0

        for i in range(len(hand)):
            result += values[hand[i].symb()]
            if hand[i].symb() == 'A':
                numAces += 1
        while result > 21 and numAces > 0:
            result -= 10
            numAces -= 1

        return result
예제 #4
0
		else:
			a.grid(row=1,column=i+1)
	if restart == True:
		for i in range(len(hand),6):
			a = CardLabel(root)
			a.display(1)
			if hand == computer_hand:
				a.grid(row=0,column=i+1)
			else:
				a.grid(row=1,column=i+1)




CardLabel.load_images()
root.bind("<Key>", key) #Key events
deck_lbl = CardLabel(root)
deck_lbl.grid(row=0,column=0)
deck_lbl.display('back',0)
deal_btn = Button(root,text="Deal",command=deal)
hit_btn = Button(root,text="Hit",command=hit)
hit_btn['state'] = 'disabled'
pass_btn = Button(root,text="Pass",command=end_turn)
pass_btn['state'] = 'disabled'
deal_btn.grid(row=3,column=1)
hit_btn.grid(row=3, column=2)
pass_btn.grid(row=3,column=3)

if __name__ == '__main__':
	root.mainloop()
예제 #5
0
class BlackjackFrame(Frame):
    """
    Subclass of Frame, creates a blackjack game.
    """
    
    _player_hand = []
    _dealer_hand = []
    
    _player_move = 0
    _dealer_move = 0
    
    _player_wins = 0
    _dealer_wins = 0
    
    def __init__(self, parent):
        """
        Buttons and card labels initialized.
        """
        
        Frame.__init__(self, parent)
        self.configure(background = 'white')
        
        self._cards = Deck(BlackjackCard)
        self._cards.shuffle()
        self.pack()
        
        CardLabel.load_images()
        
        self._dc1 = CardLabel(self)
        self._dc1.grid(row = 0, column = 0)
        self._dc2 = CardLabel(self)
        self._dc2.grid(row = 0, column = 1)
        self._dc3 = CardLabel(self)
        self._dc3.grid(row = 0, column = 2)
        self._dc4 = CardLabel(self)
        self._dc4.grid(row = 0, column = 3)
        self._dc5 = CardLabel(self)
        self._dc5.grid(row = 0, column = 4)
        self._dc6 = CardLabel(self)
        self._dc6.grid(row = 0, column = 5)
        
        self._pc1 = CardLabel(self)
        self._pc1.grid(row = 1, column = 0)
        self._pc2 = CardLabel(self)
        self._pc2.grid(row = 1, column = 1)
        self._pc3 = CardLabel(self)
        self._pc3.grid(row = 1, column = 2)
        self._pc4 = CardLabel(self)
        self._pc4.grid(row = 1, column = 3)
        self._pc5 = CardLabel(self)
        self._pc5.grid(row = 1, column = 4)
        self._pc6 = CardLabel(self)
        self._pc6.grid(row = 1, column = 5)
        
        self._deal = Button(self, text = 'Deal', command = self.dealcb)
        self._deal.grid(row = 2, column = 0, padx = 10, pady = 10)
        self._hit = Button(self, text = 'Hit', command = self.hitcb)
        self._hit.grid(row = 2, column = 2, padx = 10, pady = 10)
        self._stand = Button(self, text = 'Stand', command = self.standcb)
        self._stand.grid(row = 2, column = 4, padx = 10, pady = 10)

        self.dealcb()
        
    def dealcb(self):
        """
        Resets player and dealer hands with 2 cards each from top of deck and sets up starting layout for each hand.
        """
        self._hit.configure(state = ACTIVE)
        self._stand.configure(state = ACTIVE)
        old = self._dealer_hand + self._player_hand
        self._cards.restore(old)

        self._player_hand = self._cards.deal(2)
        self._dealer_hand = self._cards.deal(2)
        self._player_move = 0
        self._dealer_move = 0
        
        self._dc1.display('back')
        self._dc2.display('front', self._dealer_hand[1]._id)
        self._dc3.display('blank')
        self._dc4.display('blank')
        self._dc5.display('blank')
        self._dc6.display('blank')
        
        self._pc1.display('front', self._player_hand[0]._id)
        self._pc2.display('front', self._player_hand[1]._id)
        self._pc3.display('blank')
        self._pc4.display('blank')
        self._pc5.display('blank')
        self._pc6.display('blank')
        
        Label(self, text = 'Dealer Wins: ').grid(row = 3, column = 2, padx = 10, pady = 10)
        self.dcount = Label(self, text = self._dealer_wins)
        self.dcount.update_idletasks()
        self.dcount.grid(row = 3, column = 3, padx = 10, pady = 10)
        Label(self, text = 'Player Wins: ').grid(row = 4, column = 2, padx = 10, pady = 10)
        self.pcounts = Label(self, text = self._player_wins)
        self.pcounts.grid(row = 4, column = 3, padx = 10, pady = 10)
        self.pcounts.update_idletasks()
    
    def hitcb(self):
        """
        Appends card from top of deck to players hand, changes display of cards in players hand from blank to the new card. 
        """
    
        label = [self._pc3, self._pc4, self._pc5, self._pc6]
    
        if self._player_move < 4 and self.total(self._player_hand) <= 21:
            card = self._cards.deal(1)
            self._player_hand.extend(card)
            label[self._player_move].display('front', self._player_hand[self._player_move + 2]._id)
            self._player_move += 1
            
            if self.total(self._player_hand) > 21:
                self._hit.configure(state = DISABLED)
                showinfo(title = 'Game Over', message = 'You Lose, Total Over 21')
                self._player_move = 0
                self._dealer_wins += 1
    
    def standcb(self):
        """
        'flips' over dealers first card to front, compares total points of player and dealer to determine winner.
        """
        
        label = [self._dc3, self._dc4, self._dc5, self._dc6]
        
        while self.total(self._dealer_hand) < 17:
            card = self._cards.deal(1)
            self._dealer_hand.extend(card)
            label[self._dealer_move].display('front', self._dealer_hand[self._dealer_move + 2]._id)
            self._dealer_move += 1
            
        self._hit.configure(state = DISABLED)
        self._stand.configure(state = DISABLED)
        self._dc1.display('front', self._dealer_hand[0]._id)
        
        dealer_total, player_total = self.total(self._dealer_hand), self.total(self._player_hand)
        
        if dealer_total <= 21 and player_total <= 21:
            if dealer_total > player_total:
                showinfo(title = 'Game Over', message = 'You Lose, Dealer Wins')
                self._dealer_wins += 1
            elif player_total > dealer_total:
                showinfo(title = 'Game Over', message = 'You Win!')
                self._player_wins += 1
            elif dealer_total > 21:
                showinfo(title = 'Game Over', message = 'You Win!')
                self._player_wins += 1
            else:
                showinfo(title = 'Game Over', message = "It's a tie")
        else:
            showinfo(title = 'Game Over', message = "It's a tie")
        
        
    def total(self, hand):
        """
        Calculates the total for a given hand.
        """
        points = 0
        n_aces = 0
        
        for card in hand:
            points += card.points()
            if card.rank() == 12:
                n_aces += 1
        
        while points > 21 and n_aces > 0:
            points -= 10
            n_aces -= 1
            
        return points