Blackjack 项目 in python

效果图

首先根据游戏的规则得知实现需要设计三个class
Card类 —rank & suit
Hand类—Collection of cards 但是其功能是hit 和score
Deck 类 —同样是Collection of cards, 但是其功能是shuffle 和 deal
需要理解的知识点:
simplegui.load.image(“url”)
list.pop(obj)
list.index(“x”)
append(card)
重点是类的调用以及各个类之间的逻辑关系

# Mini-project #6 - Blackjack

import simplegui
import random

# load card sprite - 936x384 - source: jfitz.com
CARD_SIZE = (72, 96)
CARD_CENTER = (36, 48)
card_images = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/cards_jfitz.png")

CARD_BACK_SIZE = (72, 96)
CARD_BACK_CENTER = (36, 48)
card_back = simplegui.load_image("http://storage.googleapis.com/codeskulptor-assets/card_jfitz_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 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)
    def draws(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=[]    # create Hand object

    def add_card(self, card):
        self.hand.append(card)  # add a card object to a hand
        return self.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
        has_A = False
        value=0
        for item in self.hand:
            value += VALUES[item.get_rank()]
            if item.get_rank()=='A':
                has_A = True
        if has_A:
            if value + 10 <= 21:
                return value + 10
            else:
                return value
        return value         


    def draw(self, canvas, pos):
        i=0
        for item in self.hand:
            item.draw(canvas,pos[i])
            i += 1
    # draw a hand on the canvas, use the draw method for cards
    # draw the dealer's card in play
    def draws(self,canvas,pos):
        the_first=True
        j=1
        for item in self.hand:
            # the first card did not show
            if the_first:
                item.draws(canvas,pos[0])
                the_first = False
            else:
                item.draw(canvas,pos[j])
                j+=1

# define deck class 
class Deck:
    def __init__(self):
        self.deck=[]# create a Deck object
        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):
        t=random.randrange(0,len(self.deck))# deal a card object from the deck
        m=self.deck.pop(t)
        return Card(m[0],m[1])




#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():
    global outcome2, outcome1, score1, in_play
    if in_play: # replace with your code below
        global add_p_pos
        p_hand.add_card(dk.deal_card())
    # if the hand is in play, hit the player
        p_pos.append([P_X + add_p_pos * 100, P_Y])
        add_p_pos += 1 
    # if busted, assign a message to outcome, update in_play and score
        if p_hand.get_value() > 21:
            outcome1="You went bust and lose"
            outcome2 = "New deal?"
        else:
            outcome2="Hit or stand"
def stand():
    global outcome2, outcome1, in_play, score1,score2
    # replace with your code below
    if in_play:
    # if hand is in play, repeatedly hit dealer until his hand has value 17 or more
       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
    # assign a message to outcome, update in_play and score
       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's a tie"
                score1 += 1
    in_play= False
    outcome2 = "New deal"

# draw handler    
def draw(canvas):
    # test to make sure that card.draw works, replace with your code below
    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.draws(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()


# remember to review the gradic rubric
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值