• About Me




    Lily@Melbourne, Australia

    Login

  • Follow 静水深流 || Still waters run deep on WordPress.com
  • Archives

Python-Mini-project (Week6)

老师在演示这个游戏的时候,拿出一张表格来决定是Deal or Stand,最后果然他是赢家。他说这是每一位去LV的必备,我对Game一无所知,这样听来倒颇觉新鲜。

Mini-project description – Blackjack

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.

Mini-project development process

We suggest you develop your Blackjack game in two phases. The first phase will concentrate on implementing the basic logic of Blackjack while the second phase will focus on building a more full-featured version. In phase one, you will use buttons to control the game and print the state of the game to the console using print statements. In the second phase, you will replace the print statements by drawing images and text on the canvas and add some extra game logic.

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

  1. Download the program template for this mini-project and review the class definition for the 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.
  2. Implement the methods __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.
  3. Implement the methods for the 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. 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.
  4. Implement the handler for a “Deal” button that shuffles the deck and deals the two cards to both the dealer and the player. The event handler 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_cardmethod 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.
  5. Implement the 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 .
  6. Implement the handler for a “Hit” button. If the value of the hand is less than or equal to 21, clicking this button adds an extra card to player’s hand. If the value exceeds 21 after being hit, print “You have busted”.
  7. Implement the handler for a “Stand” button. If the player has busted, remind the player that they have busted. Otherwise, repeatedly hit the dealer until his hand has value 17 or more (using a while loop). If the dealer busts, let the player know. Otherwise, compare the value of the player’s and dealer’s hands. If the value of the player’s hand is less than or equal to the dealer’s hand, the dealer wins. Otherwise the player has won. Remember the dealer wins ties in our version.

Code:

效果在这里:>>

# Mini-project #6 – Blackjack

import simplegui
import random

# load card sprite – 949×392 – 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
score1 = 0
score2 = 0
P_X = 10
P_Y = 340
D_X = 10
D_Y = 150

# 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

#draw the card_image
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)

#draw the card_back
def drawss(self, canvas, pos):

canvas.draw_image(card_back, CARD_BACK_CENTER , CARD_BACK_SIZE, [pos[0] + CARD_BACK_CENTER[0], pos[1] + CARD_BACK_CENTER[1]], CARD_BACK_SIZE)
# define hand class
class Hand:
def __init__(self):
self.hand = []

def __str__(self):
hand = ”
for item in self.hand:
hand = hand + ” “+ str(item)
return hand

def add_card(self, card):
self.hand.append(card)
return self.hand

def get_value(self):
has_A = False
v = 0
for item in self.hand:
v += VALUES[item.get_rank()]
if item.get_rank() == ‘A’:
has_A = True

if has_A :
if v + 10 <= 21 :
return v + 10
else :
return v

return v

#draw the player card in play and both sides after paly
# pos here is a list
def draw(self, canvas, pos):
i = 0
for item in self.hand:
item.draw(canvas, pos[i])
i += 1

#draw the dealer card in play
def drawss(self, canvas, pos):
the_first = True
j = 1
for item in self.hand:
#the first did not show
if the_first :
item.drawss(canvas, pos[0])
the_first = False
else :
item.draw(canvas, pos[j])
j += 1

# define deck class
class Deck:
def __init__(self):
# create a Deck object
self.deck = []
#SUITS = [‘C’, ‘S’, ‘H’, ‘D’]
#RANKS = [‘A’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘T’, ‘J’, ‘Q’, ‘K’]
for i in SUITS:
for j in RANKS:
self.deck.append( i+j )

def shuffle(self):
# shuffle the deck
random.shuffle(self.deck) # use random.shuffle()

def deal_card(self):
#return the Card object
m = random.randrange(0,len(self.deck))
t= self.deck.pop(m)
return Card(t[0],t[1])

def __str__(self):
return str(self.deck)# return a string representing the deck
#define event handlers for buttons
def deal():
global outcome2, outcome1, p_hand, d_hand, dk
global add_p_pos, add_d_pos, p_pos, d_pos
global in_play, score1

if not in_play:
add_p_pos = 2
add_d_pos = 2
p_pos = [[P_X, P_Y],[P_X + 100, P_Y]]
d_pos = [[D_X, D_Y],[D_X + 100, D_Y]]
d_hand = Hand()
p_hand = Hand()
dk = Deck()
dk.shuffle()
for i in range(2):
d_hand.add_card(dk.deal_card())
p_hand.add_card(dk.deal_card())

outcome2 = “Hit or stand ?”
outcome1 = “”
in_play = True

state = 1

else:
outcome1 = “You deal in play.Lose”
outcome2 = “”
score1 += 1
in_play = False

def hit():
# if the hand is in play, hit the player
# if busted, assign a message to outcome, update in_play and score
global outcome1,outcome2, in_play, score1

if in_play:
global add_p_pos
p_hand.add_card(dk.deal_card())
p_pos.append([P_X + add_p_pos * 100, P_Y])
add_p_pos += 1
if p_hand.get_value() > 21 :
outcome1 = “You went bust and lose”
outcome2 = “New deal ?”
score1 += 1
in_play = False
else :
outcome2 = “Hit or stand ?”

def stand():
# 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
global outcome1, outcome2, in_play,score1, score2

if in_play :
global add_d_pos
while d_hand.get_value() < 17:
d_hand.add_card(dk.deal_card())
d_pos.append([D_X + add_d_pos * 100, D_Y])
add_d_pos += 1

if d_hand.get_value() > 21:
outcome1 = “You win!”
score2 += 1
else:
if d_hand.get_value() > p_hand.get_value():
outcome1 = “You lose”
score1 += 1
elif d_hand.get_value() < p_hand.get_value():
outcome1 = “You win!”
score2 += 1
else:
outcome1 = “It is a tie”
score1 += 1

in_play = False
outcome2 = “New deal?”

# draw handler
def draw(canvas):
canvas.draw_text(‘Blackjack’,[10,80],50,’Black’)
canvas.draw_text(‘dealer’,[10,140],30,’Black’)
canvas.draw_text(‘player’,[10,330],30,’Black’)
canvas.draw_text(outcome2,[200,330],30,’Black’)
canvas.draw_text(outcome1,[200,140],30,’Black’)
canvas.draw_text(str(score1) + ” : ” + str(score2),[400,80],30,’Red’)

p_hand.draw(canvas,p_pos)
if in_play:
d_hand.drawss(canvas,d_pos)
else :
d_hand.draw(canvas,d_pos)

# 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
deal()
frame.start()

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: