Blackjack is a simple, popular card game that is played in many casinos. Cards in Blackjack have the following values: an ace may be valued as either 1 or 11 (player's choice), face cards (kings, queens and jacks) are valued at 10 and the value of the remaining cards corresponds to their number. During a round of Blackjack, the players plays against a dealer with the goal of building a hand (a collection of cards) whose cards have a total value that is higher than the value of the dealer's hand, but not over 21. (A round of Blackjack is also sometimes referred to as a hand.)
The game logic for our simplified version of Blackjack is as follows. The player and the dealer are each dealt two cards initially with one of the dealer's cards being dealt faced down (his hole card). The player may then ask for the dealer to repeatedly "hit" his hand by dealing him another card. If, at any point, the value of the player's hand exceeds 21, the player is "busted" and loses immediately. At any point prior to busting, the player may "stand" and the dealer will then hit his hand until the value of his hand is 17 or more. (For the dealer, aces count as 11 unless it causes the dealer's hand to bust). If the dealer busts, the player wins. Otherwise, the player and dealer then compare the values of their hands and the hand with the higher value wins. The dealer wins ties in our version.In phase one, we will provide testing templates for four of the steps. The templates are designed to check whether your class implementations work correctly. You should copy your class definition into the testing template and compare the console output generated by running the template with the provided output. If the output matches, it is likely that your implementation of the class is correct. DO NOT PROCEED TO THE NEXT STEP UNTIL YOUR CODE WORKS WITH THE PROVIDED TESTING TEMPLATE. Debugging code that uses incorrectly implemented classes is extremely difficult. Avoid this problem by using our provided testing templates.
Phase one
Card
class. This class is already implemented so your task is to familiarize yourself with the code. Start by pasting the Card
class definition into the provided testing template and verifying that our implementation works as expected.__init__, __str__, add_card
for the Hand
class. We suggest modeling a hand as a list of cards. For help in implementing the__str__
method for hands, refer back to practice exercise number four from last week. Remember to use the string method for cards to convert each card object into a string. Once you have implemented the Hand
class, test it using the provided testing template.Deck
class listed in the mini-project template. We suggest modeling a deck of cards as list of cards. You can generate this list using a pair of nested for
loops or a list comprehension. Remember to use the Card
initializer to create your cards. Use random.shuffle()
to shuffle this deck of cards. Once you have implemented the Deck
class, test your Deck class using the provided testing template.deal
for this button should shuffle the deck (stored as a global variable), create new player and dealer hands (stored as global variables), and add two cards to each hand. To transfer a card from the deck to a hand, you should use the deal_card
method of the Deck
class and the add_card
method of Hand
class in combination. The resulting hands should be printed to the console with an appropriate message indicating which hand is which.get_value
method for the Hand
class. You should use the provided VALUE
dictionary to look up the value of a single card in conjunction with the logic explained in the video lecture for this project to compute the value of a hand. Once you have implemented the get_value
method, test it using the provided testing template . Remember that the deck is randomized after shuffling, so the output of the testing template should match the output in the comments in form but not in exact value.With this design, the player needs to explicitly press "Deal" to start a new deal. This choice will make using the canvas to build an image-based version of Blackjack easier. At this point, we would suggest testing your implementation of Blackjack extensively.
Phase twoIn the second phase of your implementation, you will add five features. For those involving drawing with global variables, remember to initialize these variables to appropriate values (like creating empty hands for the player and dealer) just before starting the frame.
draw
method for the Hand
class using the draw
method of the Card
class. We suggest drawing a hand as a horizontal sequence of cards where the parameter pos
is the position of the upper left corner of the leftmost card. To simplify your code, you may assume that only the first five cards of a player's hand need to be visible on the canvas.outcome
string that is drawn in the draw handler usingdraw_text
. These messages should prompt the player to take some require action and have a form similar to "Hit or stand?" and "New deal?". Also, draw the title of the game, "Blackjack", somewhere on the canvas.in_play
that keeps track of whether the player's hand is still being played. If the round is still in play, you should draw an image of the back of a card (provided in the template) over the dealer's first (hole) card to hide it. Once the round is over, the dealer's hole card should be displayed.deal
function such that, if the "Deal" button is clicked during the middle of a round, the program reports that the player lost the round and updates the score appropriately.经验:list作为collection使用时,for-in调用元素对象的方法前无需确认不为空。函数调用时一定要加括号。
测试代码:
class t: def __init__(self): self.v=0 def d(self): pass def a(b): c=b #c[1]=0 for tmp in c: tmp.d #b=[t(),t()] b=[] a(b) print b
代码如下:
# Mini-project #6 - Blackjack import simplegui import random # load card sprite - 949x392 - source: jfitz.com CARD_SIZE = (73, 98) CARD_CENTER = (36.5, 49) card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png") CARD_BACK_SIZE = (71, 96) CARD_BACK_CENTER = (35.5, 48) card_back = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/card_back.png") # initialize some useful global variables in_play = False outcome = "Hit or stand?" score = 0 # define globals for cards SUITS = ('C', 'S', 'H', 'D') RANKS = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K') VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10} # define card class class Card: def __init__(self, suit, rank): if (suit in SUITS) and (rank in RANKS): self.suit = suit self.rank = rank else: self.suit = None self.rank = None print "Invalid card: ", suit, rank def __str__(self): return self.suit + self.rank def get_suit(self): return self.suit def get_rank(self): return self.rank def draw(self, canvas, pos): card_loc = (CARD_CENTER[0] + CARD_SIZE[0] * RANKS.index(self.rank), CARD_CENTER[1] + CARD_SIZE[1] * SUITS.index(self.suit)) canvas.draw_image(card_images, card_loc, CARD_SIZE, [pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], CARD_SIZE) # define hand class class Hand: def __init__(self): self.cards=[] # create Hand object def __str__(self): s='Hand contains: ' for tmp in self.cards: s+=str(tmp)+' ' return s # return a string representation of a hand def add_card(self, card): self.cards.append(card) # add a card object to a hand def get_value(self): # count aces as 1, if the hand has an ace, then add 10 to hand value if it doesn't bust value=0 # compute the value of the hand, see Blackjack video num_ace=0 if len(self.cards)==0: return value for index in range(0,len(self.cards)): tmp=self.cards[index].get_rank() value+=VALUES[tmp] if tmp=='A':num_ace+=1 if (num_ace>0)and(value+10<=21):value+=10 return value def draw(self, canvas, pos): tmppos=pos[:] if len(self.cards)==0: return for index in range(0,len(self.cards)): # draw a hand on the canvas, use the draw method for cards self.cards[index].draw(canvas,tmppos) tmppos[0]+=100 # define deck class class Deck: def __init__(self): self.cards=[] # create a Deck object for tmp1 in SUITS: for tmp2 in RANKS: card=Card(tmp1,tmp2) self.cards.append(card) def shuffle(self): # shuffle the deck random.shuffle(self.cards) # use random.shuffle() def deal_card(self): tmp=self.cards.pop() #print str(tmp) return tmp # deal a card object from the deck def __str__(self): s='Deck contains ' # return a string representing the deck if len(self.cards)==0: return s for tmp in self.cards: s+=tmp+' ' return s #define event handlers for buttons def deal(): global outcome, in_play,player,dealer,deck,score # your code goes here player=Hand() dealer=Hand() deck=Deck() deck.shuffle() tmp=deck.deal_card() player.add_card(tmp) tmp=deck.deal_card() dealer.add_card(tmp) if in_play: outcome='You give up ! New game start' score-=1 else: outcome='New game start' in_play = True #print 'dealer '+str(dealer)+'\nplayer '+str(player) def hit(): # replace with your code below global in_play,score,outcome if in_play: tmp=deck.deal_card() player.add_card(tmp) if player.get_value()>21: outcome = "You have busted! New deal?" in_play=False score-=1 #print 'dealer '+str(dealer)+'\nplayer '+str(player) # if the hand is in play, hit the player # if busted, assign a message to outcome, update in_play and score def stand(): global score,outcome,in_play if not in_play:return if player.get_value()>21: # replace with your code below outcome = "You have busted! New deal?" score-=1 else: while(dealer.get_value()<17): tmp=deck.deal_card() dealer.add_card(tmp) if dealer.get_value()>21: outcome = "dealer have busted! New deal?" score+=1 else: if player.get_value()>dealer.get_value(): outcome = 'You win! New deal?' score+=1 else: score-=1 outcome = 'You loose! New deal?' in_play=False #print 'dealer '+str(dealer)+'\nplayer '+str(player) # if hand is in play, repeatedly hit dealer until his hand has value 17 or more # assign a message to outcome, update in_play and score # draw handler def draw(canvas): canvas.draw_text('Blackjack', (50, 200), 36, "Yellow") canvas.draw_text(outcome, (300, 150), 16, "White") canvas.draw_text('Score = '+str(score), (300, 200), 24, "White") pos=[100,300] dealer.draw(canvas, pos) player.draw(canvas, [pos[0],pos[1]+100]) if in_play: card_loc = (CARD_BACK_CENTER[0] + CARD_BACK_SIZE[0],CARD_BACK_CENTER[1] + CARD_BACK_SIZE[1]) #canvas.draw_image(card_back, card_loc, CARD_SIZE, [pos[0] + CARD_BACK_CENTER[0], pos[1]+100 + CARD_BACK_CENTER[1]], CARD_BACK_SIZE) # test to make sure that card.draw works, replace with your code below deal() # initialization frame frame = simplegui.create_frame("Blackjack", 600, 600) frame.set_canvas_background("Green") #create buttons and canvas callback frame.add_button("Deal", deal, 200) frame.add_button("Hit", hit, 200) frame.add_button("Stand", stand, 200) frame.set_draw_handler(draw) # get things rolling frame.start() # remember to review the gradic rubric