2014年11月25日 星期二

Blackjack!!


Blackjack based on codeskulpter.
You can play on Codeskulptor.
Just copy and paste, and then click the play button on top left.
You can also give me some advisement.
import simplegui
import random
# load music
music = simplegui.load_sound('https://dl.dropboxusercontent.com/s/buy9765drpfttm2/03%20-%20%E3%81%8A%E3%81%A6%E3%82%93%E3%81%B0%E3%83%97%E3%83%AC%E3%83%AA%E3%83%A5%E3%83%BC%E3%83%89.mp3')
# load card sprite 
CARD_SIZE = (220, 300)
CARD_CENTER = (110, 150)
card_images = simplegui.load_image("https://dl.dropbox.com/s/tzn12sme7d2sh6n/Deck.png")
card_back = simplegui.load_image("https://dl.dropbox.com/s/mnhcddvkx0o4lp0/Deck_back.png")    
background = simplegui.load_image('https://dl.dropbox.com/s/v9enhpsen7gv79v/1_bg_blue.png')

# initialize some useful global variables
in_play = False
outcome = ""
turn = 0
log = [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[0]*0.7,CARD_SIZE[1]*0.7])
    def draw_back(self, canvas, pos):
        card_loc = (CARD_CENTER[0], CARD_CENTER[1])
        canvas.draw_image(card_back, card_loc, CARD_SIZE,[pos[0] + CARD_CENTER[0], pos[1] + CARD_CENTER[1]], [CARD_SIZE[0]*0.7,CARD_SIZE[1]*0.7])
# define hand class
class Hand:
    def __init__(self):
        self.cards = []
        self.value = 0
        self.is_aces = False

    def __str__(self):
        handcards = []
        for card in self.cards:
            handcards.append(str(card))
        return str(handcards)

    def add_card(self, card):
        # also compute the hard point of the hand,
        self.cards.append(card)
        self.value += VALUES[card.rank]
        if card.rank == 'A':
            self.is_aces = True
            
    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
        if self.is_aces and self.value + 10 <=21:
            return self.value + 10
        else:
            return self.value
    def draw(self, canvas, pos):
        # draw a hand on the canvas, use the draw method for cards
        i = 0
        for card in self.cards:
            card.draw(canvas,[pos[0]+i*160,pos[1]])
            i += 1
# define deck class 
class Deck:
    def __init__(self):
        self.deck = []  # create a Deck object
        for rank in RANKS:
            for suit in SUITS:
                self.deck.append(Card(suit,rank))

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

    def deal_card(self):
        card = self.deck.pop(0)    # deal a card object from the deck
        return card
    
    def __str__(self):
        cards = [str(card) for card in self.deck]    # return a string representing the deck
        return str(cards)
    def __len__(self):
        cards = [str(card) for card in self.deck]
        return len(cards)
# define gamble
class Gamble:
            """store the token and calculate"""
            def __init__(self,token):
                self.token = token
                self.wager = 0
                self.five_card = False
                self.turn = 0
                self.rank = ''
                #cheat XD
                self.is_cheat = False
            def lose(self):
                self.token -= self.wager
            def win(self):
                self.token += self.wager
            def blackjack(self):
                self.token += self.wager*3/2
            def five(self):
                self.token += self.wager*2
                self.five_card = True
            def get_token(self):
                return self.token
            def get_wager(self):
                return self.wager
            def gameover(self):
                if game.token < 0:
                    game.rank = 'F'
                    return True
                else:
                    return False
            def is_rank(self):
                if self.token >= 100000:
                    self.rank = 'SS'
                elif self.token >= 20000:
                    self.rank = 'S'
                    return None
                elif self.token >= 10000:
                    self.rank = 'A'
                    return None
                elif self.token > 0:
                    self.rank = 'B'
                    return None
                else:
                    self.rank = 'F'
            
class Music:
    def __init__(self,music):
        self.music = music
        self.timer = simplegui.create_timer(76000,self.play_music)
        self.is_play = False
        self.volume = 1
    def volume_up(self):
        self.volume += 0.2
        self.music.set_volume(self.volume)
    def volume_down(self):
        self.volume -= 0.2
        self.music.set_volume(self.volume)
    def play_bgm(self):
        self.music.play()
        self.timer.start()
        self.is_play = True
    def play_music(self):
        self.music.rewind()
        self.music.play()
        self.is_play = True
    def quit(self):
        self.music.pause()
        self.timer.stop()
        self.is_play = False
#define event handlers for buttons
def deal(wager):
    global outcome, in_play, player, dealer, deck, game
    if game.turn < 10:
        if game.gameover():
            outcome = "Game Over"
        else:
            if not(in_play):
                if int(wager) > game.get_token():
                    outcome = "You don't have so many tokens!"
                else:
                    game.wager = int(wager)
                    outcome = "Hit or Stand"
                    deck = Deck()
                    deck.shuffle()
                    player = Hand()
                    dealer = Hand()
                    for i in [0,1]:
                        player.add_card(deck.deal_card())
                        dealer.add_card(deck.deal_card())
#                 player.add_card(Card('S','A'))
#                 player.add_card(Card('S','J'))
#                 dealer.add_card(Card('D','2'))
#                 dealer.add_card(Card('D','3'))
                    game.turn += 1
                    in_play = True
def hit():
    # if the hand is in play, hit the player
    # if busted, assign a message to outcome, update in_play and game
    global outcome, game,in_play, dealer, player
    if in_play:
        player.add_card(deck.deal_card())
        if player.get_value() > 21:
            outcome = "Your are busted !!!"
            game.lose()
            in_play = False
            if game.gameover():
                outcome = "Game Over"
        elif len(player.cards) == 5:
            outcome ="Five cards!!!"
            game.five()
            in_play = False
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 token
    global in_play, outcome, game, player, dealer, deck

    if in_play:
        in_play = False
        if player.get_value() == 21 and len(player.cards) == 2:
            game.blackjack()
            outcome = "Winner Winner Chicken Dinner!"
        else:
            while dealer.get_value() < 17:
                dealer.add_card(deck.deal_card())
            if dealer.get_value() >= player.get_value() and dealer.get_value() <= 21:
                outcome = "You lose!"
                game.lose()
                if game.gameover():
                    outcome = "Game Over!"
            else:
                outcome = "Congradulation!!"
                game.win()
def set_wager(text):
    global game, outcome
    if not(game.gameover()):
        if game.wager + int(text) <= game.token:
            game.wager += int(text)
            outcome = "Are you sure?"
            hit()
        else:
            outcome = "You don't have so many token!"
def reset():
    global in_play, game
    game = Gamble(10000)
    in_play = False
    game.turn = 0
    deal(100)
    in_play = True   
def quit():
    global bgm, frame
    bgm.quit()
    frame.stop()
def keydown(key):
    global game, in_play, bgm
    if chr(key) == 'H':
        hit()
    elif chr(key) == 'S':
        stand()
    elif chr(key) == 'M':
        if not(in_play):
            deal(game.token)
        else:
            set_wager(game.token-game.wager)
    elif chr(key) == 'R':
        reset()
    elif chr(key) == 'Q':
        quit()
    elif chr(key) == '1':
        if not(in_play):
            deal(100)
        else:
            set_wager(100)
    elif chr(key) == '2':
        if not(in_play):
            deal(500)
        else:
            set_wager(500)
    elif chr(key) == '3':
        if not(in_play):
            deal(1000)
        else:
            set_wager(1000)
    elif chr(key) == '4':
        if not(in_play):
            deal(5000)
        else:
            set_wager(5000)
    elif chr(key) == '5':
        if not(in_play):
            deal(10000)
        else:
            set_wager(10000)
    elif chr(key) == 'P':
        if bgm.is_play:
            bgm.quit()
        else:
            bgm.play_bgm()
    elif chr(key) == 'O':
        bgm.volume_up()
    elif chr(key) == 'I':
        bgm.volume_down()
    #cheat
#    if chr(key) == 'C':
#        game.is_cheat = True
    #controll

def keyup(key):
    global game
    if chr(key) == 'C':
        game.is_cheat = False

# draw handler    
def draw(canvas):
    global dealer, player, outcome, in_play, game, game_log
    # test to make sure that card.draw works, replace with your code below
    canvas.draw_image(background, (400,240), ( 800, 473), (550,325), (1100, 650))
    dealer.draw(canvas,(80,100))
    if in_play:
        dealer.cards[0].draw_back(canvas,(80,100))
    player.draw(canvas,(80,375))
    if game.is_cheat:
        deck.deck[0].draw(canvas,(800,100))
    canvas.draw_text("Blackjack",(20,50),40,"Black","monospace")
    canvas.draw_text("Dealer",(75,125),32,"Black","monospace")
    canvas.draw_text("Player",(75,400),32,"Black","monospace")
    canvas.draw_text("token: " + str(game.get_token()),(850,50), 32,"Black","monospace")
    canvas.draw_text("wager: " + str(game.get_wager()),(850,100), 32,"Black","monospace")
    if not(in_play):
        canvas.draw_text("Points: "+ str(dealer.get_value()),(20,160),12,"Black","monospace")
    canvas.draw_text("Points: "+ str(player.get_value()),(20,435),12,"Black","monospace")
    canvas.draw_text(outcome,(500-(frame.get_canvas_textwidth(outcome,32)/2),60),32,"Black","monospace")
    if game.token == 0:
        game.is_rank()
        canvas.draw_text('Your rank is '+str(game.rank),(500,100),30,"Black","monospace")
    elif game.turn >= 10 and not(in_play):
        game.is_rank()
        canvas.draw_text('Your rank is '+str(game.rank),(500,100),30,"Black","monospace")
        log.append(game.token)
        log.sort()
        game_log.set_text('Earn most: '+ str(log[-1]))
    else:
        canvas.draw_text('Turn: '+str(game.turn),(500,100),20,"Black","monospace")
        

# initialization frame
frame = simplegui.create_frame("Otaku-Blackjack", 1100,650,140)
#frame.set_canvas_background(background)

#create buttons and canvas callback
#frame.add_input("Deal", deal, 100)
#frame.add_button("Hit",  hit, 100)
#frame.add_button("Stand", stand, 100)
#frame.add_button("Reset", reset, 100)
#frame.add_input("wager", set_wager, 100)
#frame.add_button("Quit", quit, 100)
frame.add_label('Demonstrate:')
frame.add_label('You have ten turns')
frame.add_label('to get more token!')
frame.add_label('')
frame.add_label('Add wager:')
frame.add_label('(or deal)')
frame.add_label('1: add $100')
frame.add_label('2: add $500')
frame.add_label('3: add $1000')
frame.add_label('4: add $5000')
frame.add_label('5: add $10000')
frame.add_label('M: ShowHand')
frame.add_label('')
frame.add_label('Control:')
frame.add_label('H: hit')
frame.add_label('S: stand')
frame.add_label('R: restart')
frame.add_label('Q: quit')
frame.add_label('')
game_log = frame.add_label('Earn most: 0')
frame.set_draw_handler(draw)
#key control
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)

# get things rolling

reset()
frame.start()
bgm = Music(music)
bgm.play_bgm()

沒有留言:

張貼留言

歡迎發表意見