1 / 25

Topics in Python Blackjack & TKinter

Topics in Python Blackjack & TKinter. Professor Frank J. Rinaldo Creation Core - office 401. BlackJack Cards module. # Cards Module class Card(object): “”” A Playing Card “”” RANKS = [“A”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”] SUITS = [“c”, “d”, “h”, “s”]

arnie
Télécharger la présentation

Topics in Python Blackjack & TKinter

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Topics in PythonBlackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

  2. BlackJackCards module # Cards Module class Card(object): “”” A Playing Card “”” RANKS = [“A”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”] SUITS = [“c”, “d”, “h”, “s”] def __init__(self, rank, suit, face_up = True): self.rank = rank self.suit = suit self.is_face_up = face_up def __str__(self): if self.is_face_up: rep = self.rank + self.suit else: rep = “XX” return rep def flip(self) self.is_face_up = not self.is_face_up

  3. BlackJackCards module continued class hand(object): def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = “” for card in self.cards: rep += str(card) + “\t” else: rep = “<empty>” return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card)

  4. BlackJackCards module continued class Deck(Hand): “”” A deck of playing cards “”” def populate(self): for suit in Card.SUITS: for rank in Cards.RANKS: self.add(Card(rank, suit)) def shuffle(self): import random random.shuffle(self.cards) def deal(self, hands, per_hand = 1) for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print “Can’t continue deal. Out of cards.”

  5. BlackJackCards module continued if __name__ == “__main__”: print “This is a module with classes for playing cards.” raw_input(“\n\nPress the enter key to exit.”)

  6. BlackJackClass Design • BJ_Card derived from cards.Card • BJ_Deck derived from cards.Deck • BJ_Hand derived from cards.Hand • BJ_Player derived from BJ_Hand • BJ_Dealer derived from BJ_Hand • BJ_Game derived from object

  7. BlackJack Pseudocode Deal each player and dealer initial two cards For each player While the player asks for a hit and player not busted Deal the player an additional card If there are no players still playing Show the dealer’s two cards Otherwise While the dealer must hit and dealer is not busted Deal the dealer an additional card If the dealer is busted For each player who is still playing The player wins Otherwise For each player who is still playing If the player’s total > dealer’s total The player wins Otherwise, if the player’s total < dealer’s total The player loses Otherwise The player pushes

  8. BlackJackGame # Blackjack # From 1 to 7 players compete against the dealer import cards, games class BJ_Card(cards.Card): “”” A Blackjack Card. “”” ACE_VALUE = 1 def get_value(self): if self.is_face_up: value = BJ_Card.RANKS.index(self.rank) + 1 if value > 10: value = 10 else: value = None return value value = property(get_value)

  9. BlackJackGame class BJ_Deck(cards.deck): “”” A Blackjack Hand “”” def populate(self): for suit in BJ_Card.SUITS for rank in BJ_Card.RANKS: self.cards.append(BJ_Card(rank, suit))

  10. BlackJackGame class BJ_Hand(cards.Hand): “”” A Blackjack Hand. “”” def __init__(self, name): super(BJ_hand, self).__init__() self.name = name def __str__(self): rep = self.name + “:\t” + super(BJ_Hand, self.__STR__() if self.total: rep = “(“ + str(self.total) + “)” return rep def is_busted(self): return self.total > 21

  11. BlackJackGame def get_total(self): # if a card in hand has value None, total is None for card in self.cards: if not card.value: return None # add up card values, treat each Ace as 1 total = 0 for card in self.cards: total += card.value # determine if hand contains an Ace contains_ace = False for card in self.cards: if card.value == BJ_Card.ACE_VALUE: contains_ace = True # if hand contains Ace & total is low enough, treat Ace as 11 if contains_ace and total <= 11: total += 10 return total total = property(get_total)

  12. BlackJackGame class BJ_Player(BJ_Hand): “”” A Blackjack Player “”” def is_hitting(self): response = games.ask_yes_no(“\n” + self.name + “, do you want a hit? (Y/N): “) return response def bust(self): print self.name, “busts.” self.lose def lose(self): print self.name, “loses.” def win(self): print self.name, “wins.” def push(self): print self.name, “pushes.”

  13. BlackJackGame class BJ_Dealer(BJ_Hand): “”” A Blackjack Dealer “”” def is_hitting(self): return self. total < 17 def bust(self): print self.name, “busts” def flip_first_card(self): first_card = self.cards[0] first_card.flip()

  14. BlackJackGame class BJ_Game(object): “”” A Blackjack Game “”” def __init__(self, names): self.players = [] for name in names: player = BJ_Player(name) self.player.append(player) self.dealer = BJ_Dealer(“Dealer”) self.deck = BJ_Deck() self.deck.populate() self.deck.shuffle()

  15. BlackJackGame def get_still_playing(self): remaining = [] for player in self.players: if not player.is_busted: remaining.append(player) return remaining def __additional_cards(self, player): while not player.is_busted() and player.is_hitting(): self.deck.deal(player) print player if player.is_busted(): player.bust()

  16. BlackJackGame def play(self): # deal initial 2 cards to everyone self.deck.deal(self.players + [self.dealer].per_hand = 2) self.dealer.flip.first_card() for player in self.players: print player print self.player for player in self.players: self.__additional_cards(player) self.dealer.flip_first_card() if not self.still_playing: print self.dealer else: print self.dealer self.__additional_cards(self.dealer)

  17. BlackJackGame if self.dealer.is_busted(): for player in self.still_playing: player.win() else: for player in self.still_playing: if player.total > self.dealer.total: player.win() elif player.total < self.dealer.total: player.lose() else: player.push() for player in self.players: player.clear() self.dealer.clear()

  18. BlackJackGame # Main Function (method) def main(): print “\t\tWelcome to Blackjack!\n” names = [] number = games.ask_number(“How many players? (1-7):”, low = 1, high = 8) for i in range(number): name = raw_input(Enter player name: “) names.append(name) print game = BJ_Game(names) again = None while again != “n”: game.play() again = games.ask_yes_no(“\nDo you want to play again?: “) # Main program main() raw_input(“\n\nPress the enter key to exit.”

  19. Graphical User InterfaceDevelopment • Learn to work with a GUI toolkit • Create and fill frames (“window”) • Create and use buttons • Create and use text entries and text boxes • Create and use check buttons • Create and use radio buttons

  20. GUI’s • All of our development to date has used ‘text’ graphics & ‘text’ input & output • Now we will learn how to start to use graphical user interfaces to make input to & output from the computer more interesting!

  21. TK • Tk is a popular (and standard) GUI Toolkit • It is supports many programming languages: • Python • Tcl • Perl • Ruby • Etc… • It runs on many operating systems: • Most UNIX (and UNIX like) systems • MS Windows • Apple

  22. TKinter • TKinter is a standard Python interface to the Tk GUI toolkit • It consists of a number of modules (libraries) • It allows us to create a user interface ‘window’ for input & output

  23. Sample TKinter Program # File: hello2.py from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame,text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello",command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" # Main program root = Tk() app = App(root) root.mainloop() # NOTE: See “An Introduction to Tkinter ”: # http://www.pythonware.com/library/tkinter/introduction/

  24. Sample TKinter Widget Classes • Button A simple button to execute a command • Checkbutton Creates a button that can be ‘checked’ • Entry A text entry field • Frame A container widget • Label Displays a text or an image • Listbox Displays a list of alternatives • Menu A menu pane for pulldown & popup menus • Menubutton Used to implement a pulldown menu • Message Display text message • Radiobutton Multi-valued button • Scrollbar Standard scrollbar • Text Formatted text display

  25. Homework • Due week 11 • Write a Python Program: • See problem #3 on page 289 of textbook. • In other words, allow players to bet money. As an example, if they bet 1000 Yen and win then they get back 2000 Yen. Keep track of each player’s money and remove any player who runs out of money • Include: • Simple Specification Document • Simple Pseudocode • Python code • Demonstrate program in class

More Related