topics in python blackjack & tkinter professor frank j. rinaldo creation core - office 401

25
Topics in Python Topics in Python Blackjack & TKinter Blackjack & TKinter Professor Frank J. Professor Frank J. Rinaldo Rinaldo Creation Core - office Creation Core - office 401 401

Upload: parker-latus

Post on 31-Mar-2015

245 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

Topics in PythonTopics in PythonBlackjack & TKinterBlackjack & TKinter

Professor Frank J. RinaldoProfessor Frank J. Rinaldo

Creation Core - office 401Creation Core - office 401

Page 2: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackCards moduleCards module

# Cards Module# Cards Module

class Card(object):class Card(object):“”” “”” A Playing Card “””A Playing Card “””RANKS = [“A”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”]RANKS = [“A”, “1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “J”, “Q”, “K”]SUITS = [“c”, “d”, “h”, “s”]SUITS = [“c”, “d”, “h”, “s”]def __init__(self, rank, suit, face_up = True):def __init__(self, rank, suit, face_up = True):

self.rank = rankself.rank = rankself.suit = suitself.suit = suitself.is_face_up = face_upself.is_face_up = face_up

def __str__(self):def __str__(self):if self.is_face_up:if self.is_face_up:

rep = self.rank + self.suitrep = self.rank + self.suitelse:else:

rep = “XX”rep = “XX”return repreturn rep

def flip(self)def flip(self)self.is_face_up = not self.is_face_upself.is_face_up = not self.is_face_up

Page 3: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackCards module continuedCards module continued

class hand(object):class hand(object):def __init__(self):def __init__(self):

self.cards = []self.cards = []

def __str__(self):def __str__(self):if self.cards:if self.cards:

rep = “”rep = “”for card in self.cards:for card in self.cards:

rep += str(card) + “\t”rep += str(card) + “\t”else:else:

rep = “<empty>”rep = “<empty>”return repreturn rep

def clear(self):def clear(self):self.cards = []self.cards = []

def add(self, card):def add(self, card):self.cards.append(card)self.cards.append(card)

def give(self, card, other_hand):def give(self, card, other_hand):self.cards.remove(card)self.cards.remove(card)other_hand.add(card)other_hand.add(card)

Page 4: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackCards module continuedCards module continued

class Deck(Hand):class Deck(Hand):“”” “”” A deck of playing cards “””A deck of playing cards “””def populate(self):def populate(self):

for suit in Card.SUITS:for suit in Card.SUITS:for rank in Cards.RANKS:for rank in Cards.RANKS:

self.add(Card(rank, suit))self.add(Card(rank, suit))

def shuffle(self):def shuffle(self):import randomimport randomrandom.shuffle(self.cards)random.shuffle(self.cards)

def deal(self, hands, per_hand = 1)def deal(self, hands, per_hand = 1)for rounds in range(per_hand):for rounds in range(per_hand):

for hand in hands:for hand in hands:if self.cards:if self.cards:

top_card = self.cards[0]top_card = self.cards[0]self.give(top_card, hand)self.give(top_card, hand)

else:else:print “Can’t continue deal. Out of cards.”print “Can’t continue deal. Out of cards.”

Page 5: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackCards module continuedCards module continued

if __name__ == “__main__”:if __name__ == “__main__”:

print “This is a module with classes for playing cards.”print “This is a module with classes for playing cards.”

raw_input(“\n\nPress the enter key to exit.”)raw_input(“\n\nPress the enter key to exit.”)

Page 6: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackClass DesignClass Design

BJ_CardBJ_Card derived fromderived from cards.Cardcards.Card BJ_DeckBJ_Deck derived from cards.Deckderived from cards.Deck BJ_HandBJ_Hand derived fromderived from cards.Handcards.Hand

BJ_PlayerBJ_Player derived fromderived from BJ_HandBJ_Hand BJ_DealerBJ_Dealer derived from BJ_Handderived from BJ_Hand BJ_GameBJ_Gamederived from objectderived from object

Page 7: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJack BlackJack PseudocodePseudocode

Deal each player and dealer initial two cardsDeal each player and dealer initial two cardsFor each playerFor each player

While the player asks for a hit and player not bustedWhile the player asks for a hit and player not bustedDeal the player an additional cardDeal the player an additional card

If there are no players still playingIf there are no players still playingShow the dealer’s two cardsShow the dealer’s two cards

OtherwiseOtherwiseWhile the dealer must hit and dealer is not bustedWhile the dealer must hit and dealer is not busted

Deal the dealer an additional cardDeal the dealer an additional cardIf the dealer is bustedIf the dealer is busted

For each player who is still playingFor each player who is still playingThe player winsThe player wins

OtherwiseOtherwiseFor each player who is still playingFor each player who is still playing

If the player’s total > dealer’s totalIf the player’s total > dealer’s totalThe player winsThe player wins

Otherwise, if the player’s total < dealer’s totalOtherwise, if the player’s total < dealer’s totalThe player losesThe player loses

OtherwiseOtherwiseThe player pushesThe player pushes

Page 8: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

# Blackjack# Blackjack# From 1 to 7 players compete against the dealer# From 1 to 7 players compete against the dealer

import cards, gamesimport cards, games

class BJ_Card(cards.Card):class BJ_Card(cards.Card):“”” “”” A Blackjack Card. “””A Blackjack Card. “””ACE_VALUE = 1ACE_VALUE = 1def get_value(self):def get_value(self):

if self.is_face_up:if self.is_face_up:value = BJ_Card.RANKS.index(self.rank) + 1value = BJ_Card.RANKS.index(self.rank) + 1if value > 10:if value > 10:

value = 10value = 10else:else:

value = Nonevalue = Nonereturn valuereturn value

value = property(get_value)value = property(get_value)

Page 9: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

class BJ_Deck(cards.deck):class BJ_Deck(cards.deck):

“”” “”” A Blackjack Hand “””A Blackjack Hand “””

def populate(self):def populate(self):

for suit in BJ_Card.SUITSfor suit in BJ_Card.SUITS

for rank in BJ_Card.RANKS:for rank in BJ_Card.RANKS:

self.cards.append(BJ_Card(rank, suit))self.cards.append(BJ_Card(rank, suit))

Page 10: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

class BJ_Hand(cards.Hand):class BJ_Hand(cards.Hand):“”” “”” A Blackjack Hand. “””A Blackjack Hand. “””def __init__(self, name):def __init__(self, name):

super(BJ_hand, self).__init__()super(BJ_hand, self).__init__()self.name = nameself.name = name

def __str__(self):def __str__(self):rep = self.name + “:\t” + super(BJ_Hand, self.__STR__()rep = self.name + “:\t” + super(BJ_Hand, self.__STR__()if self.total:if self.total:

rep = “(“ + str(self.total) + “)”rep = “(“ + str(self.total) + “)”return repreturn rep

def is_busted(self):def is_busted(self):return self.total > 21return self.total > 21

Page 11: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

def get_total(self):def get_total(self):# if a card in hand has value None, total is None# if a card in hand has value None, total is Nonefor card in self.cards:for card in self.cards:

if not card.value:if not card.value:return Nonereturn None

# add up card values, treat each Ace as 1# add up card values, treat each Ace as 1total = 0total = 0for card in self.cards:for card in self.cards:

total += card.valuetotal += card.value

# determine if hand contains an Ace# determine if hand contains an Acecontains_ace = Falsecontains_ace = Falsefor card in self.cards:for card in self.cards:

if card.value == BJ_Card.ACE_VALUE:if card.value == BJ_Card.ACE_VALUE:contains_ace = Truecontains_ace = True

# if hand contains Ace & total is low enough, treat Ace as 11# if hand contains Ace & total is low enough, treat Ace as 11if contains_ace and total <= 11:if contains_ace and total <= 11:

total += 10total += 10

return totalreturn total

total = property(get_total)total = property(get_total)

Page 12: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

class BJ_Player(BJ_Hand):class BJ_Player(BJ_Hand):“”” “”” A Blackjack Player “””A Blackjack Player “””def is_hitting(self):def is_hitting(self):

response = games.ask_yes_no(“\n” + self.name + “, do you want response = games.ask_yes_no(“\n” + self.name + “, do you want a hit? (Y/N): “)a hit? (Y/N): “)

return responsereturn response

def bust(self):def bust(self):print self.name, “busts.”print self.name, “busts.”self.loseself.lose

def lose(self):def lose(self):print self.name, “loses.”print self.name, “loses.”

def win(self):def win(self):print self.name, “wins.”print self.name, “wins.”

def push(self):def push(self):print self.name, “pushes.”print self.name, “pushes.”

Page 13: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

class BJ_Dealer(BJ_Hand):class BJ_Dealer(BJ_Hand):“”” “”” A Blackjack Dealer “””A Blackjack Dealer “””def is_hitting(self):def is_hitting(self):

return self. total < 17return self. total < 17

def bust(self):def bust(self):print self.name, “busts”print self.name, “busts”

def flip_first_card(self):def flip_first_card(self):first_card = self.cards[0]first_card = self.cards[0]first_card.flip()first_card.flip()

Page 14: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

class BJ_Game(object):class BJ_Game(object):“”” “”” A Blackjack Game “””A Blackjack Game “””def __init__(self, names):def __init__(self, names):

self.players = []self.players = []for name in names:for name in names:

player = BJ_Player(name)player = BJ_Player(name)self.player.append(player)self.player.append(player)

self.dealer = BJ_Dealer(“Dealer”)self.dealer = BJ_Dealer(“Dealer”)

self.deck = BJ_Deck()self.deck = BJ_Deck()self.deck.populate()self.deck.populate()self.deck.shuffle()self.deck.shuffle()

Page 15: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

def get_still_playing(self):def get_still_playing(self):remaining = []remaining = []for player in self.players:for player in self.players:

if not player.is_busted:if not player.is_busted:remaining.append(player)remaining.append(player)

return remainingreturn remaining

def __additional_cards(self, player):def __additional_cards(self, player):while not player.is_busted() and player.is_hitting():while not player.is_busted() and player.is_hitting():

self.deck.deal(player)self.deck.deal(player)print playerprint playerif player.is_busted():if player.is_busted():

player.bust()player.bust()

Page 16: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

def play(self):def play(self):# deal initial 2 cards to everyone# deal initial 2 cards to everyoneself.deck.deal(self.players + [self.dealer].per_hand = 2)self.deck.deal(self.players + [self.dealer].per_hand = 2)self.dealer.flip.first_card()self.dealer.flip.first_card()for player in self.players:for player in self.players:

print playerprint playerprint self.playerprint self.player

for player in self.players:for player in self.players:self.__additional_cards(player)self.__additional_cards(player)

self.dealer.flip_first_card()self.dealer.flip_first_card()

if not self.still_playing:if not self.still_playing:print self.dealerprint self.dealer

else:else:print self.dealerprint self.dealerself.__additional_cards(self.dealer)self.__additional_cards(self.dealer)

Page 17: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

if self.dealer.is_busted():if self.dealer.is_busted():for player in self.still_playing:for player in self.still_playing:

player.win()player.win()else:else:

for player in self.still_playing:for player in self.still_playing:if player.total > self.dealer.total:if player.total > self.dealer.total:

player.win()player.win()elif player.total < self.dealer.total:elif player.total < self.dealer.total:

player.lose()player.lose()else:else:

player.push()player.push()

for player in self.players:for player in self.players:player.clear()player.clear()

self.dealer.clear()self.dealer.clear()

Page 18: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

BlackJackBlackJackGameGame

# Main Function (method)# Main Function (method)def main():def main():

print “\t\tWelcome to Blackjack!\n”print “\t\tWelcome to Blackjack!\n”

names = []names = []number = games.ask_number(“How many players? (1-7):”, low = 1, high = 8)number = games.ask_number(“How many players? (1-7):”, low = 1, high = 8)for i in range(number):for i in range(number):

name = raw_input(Enter player name: “)name = raw_input(Enter player name: “)names.append(name)names.append(name)

printprint

game = BJ_Game(names)game = BJ_Game(names)

again = Noneagain = Nonewhile again != “n”:while again != “n”:

game.play()game.play()again = games.ask_yes_no(“\nDo you want to play again?: “)again = games.ask_yes_no(“\nDo you want to play again?: “)

# Main program# Main programmain()main()raw_input(“\n\nPress the enter key to exit.”raw_input(“\n\nPress the enter key to exit.”

Page 19: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

Graphical User InterfaceGraphical User InterfaceDevelopmentDevelopment

Learn to work with a GUI toolkitLearn to work with a GUI toolkit Create and fill frames (“window”)Create and fill frames (“window”) Create and use buttonsCreate and use buttons Create and use text entries and text Create and use text entries and text

boxesboxes Create and use check buttonsCreate and use check buttons Create and use radio buttonsCreate and use radio buttons

Page 20: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

GUI’sGUI’s

All of our development to date has All of our development to date has used ‘text’ graphics & ‘text’ input & used ‘text’ graphics & ‘text’ input & outputoutput

Now we will learn how to start to use Now we will learn how to start to use graphical user interfaces to make graphical user interfaces to make input to & output from the computer input to & output from the computer more interesting!more interesting!

Page 21: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

TKTK Tk is a popular (and standard) GUI ToolkitTk is a popular (and standard) GUI Toolkit It is supports many programming languages:It is supports many programming languages:

• PythonPython• TclTcl• PerlPerl• RubyRuby• Etc…Etc…

It runs on many operating systems:It runs on many operating systems:• Most UNIX (and UNIX like) systemsMost UNIX (and UNIX like) systems• MS WindowsMS Windows• AppleApple

Page 22: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

TKinterTKinter

TKinter is a standard Python TKinter is a standard Python interface to the Tk GUI toolkitinterface to the Tk GUI toolkit

It consists of a number of modules It consists of a number of modules (libraries)(libraries)

It allows us to create a user interface It allows us to create a user interface ‘window’ for input & output‘window’ for input & output

Page 23: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

Sample TKinter ProgramSample TKinter Program# File: hello2.py # File: hello2.py

from Tkinter import * from Tkinter import * class App: class App:

def __init__(self, master): def __init__(self, master): frame = Frame(master) frame = Frame(master) frame.pack()frame.pack()

self.button = Button(frame,text="QUIT", fg="red", command=frame.quit) self.button = Button(frame,text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.button.pack(side=LEFT)

self.hi_there = Button(frame, text="Hello",command=self.say_hi) self.hi_there = Button(frame, text="Hello",command=self.say_hi) self.hi_there.pack(side=LEFT) self.hi_there.pack(side=LEFT)

def say_hi(self): def say_hi(self): print "hi there, everyone!" print "hi there, everyone!"

# Main program# Main programroot = Tk() root = Tk() app = App(root) app = App(root) root.mainloop() root.mainloop()

# NOTE: See “An Introduction to Tkinter ”: # NOTE: See “An Introduction to Tkinter ”: ## http://www.pythonware.com/library/tkinter/introduction/http://www.pythonware.com/library/tkinter/introduction/

Page 24: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

Sample TKinter Widget ClassesSample TKinter Widget Classes ButtonButton A simple button to execute a commandA simple button to execute a command Checkbutton Checkbutton Creates a button that can be ‘checked’Creates a button that can be ‘checked’ EntryEntry A text entry fieldA text entry field FrameFrame A container widgetA container widget LabelLabel Displays a text or an imageDisplays a text or an image ListboxListbox Displays a list of alternativesDisplays a list of alternatives MenuMenu A menu pane for pulldown & popup menusA menu pane for pulldown & popup menus MenubuttonMenubutton Used to implement a pulldown menuUsed to implement a pulldown menu MessageMessage Display text messageDisplay text message RadiobuttonRadiobutton Multi-valued buttonMulti-valued button ScrollbarScrollbar Standard scrollbarStandard scrollbar TextText Formatted text displayFormatted text display

Page 25: Topics in Python Blackjack & TKinter Professor Frank J. Rinaldo Creation Core - office 401

HomeworkHomework Due week 11Due week 11 Write a Python Program:Write a Python Program:

• See problem #3 on page 289 of textbook.See problem #3 on page 289 of textbook.• In other words, allow players to bet money. As In other words, allow players to bet money. As

an example, if they bet 1000 Yen and win then an example, if they bet 1000 Yen and win then they get back 2000 Yen. Keep track of each they get back 2000 Yen. Keep track of each player’s money and remove any player who player’s money and remove any player who runs out of moneyruns out of money

• Include:Include: Simple Specification DocumentSimple Specification Document Simple PseudocodeSimple Pseudocode Python codePython code

• Demonstrate program in classDemonstrate program in class