blackjack

Kolorwanie:
Status:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
import random
# import only system from os
from os import system, name

import pdb

from colorama import init
from colorama import Fore
from colorama import Back

figures = {2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'}
colors = {'spade', 'heart', 'diamond', 'club'}

# define our clear function


def clear():

    # for windows
    if name == 'nt':

        system('cls')

    # for mac and linux(here, os.name is 'posix')
    else:
        system('clear')


class Card():
    '''
    Card class representing gaming card like nine of heart etc.
    '''
    colors = {'spade': Fore.BLACK + '\u2660', 'heart': Fore.RED + '\u2665', 'diamond': Fore.RED + '\u2666', 'club': Fore.BLACK + '\u2663', 'unknown': Fore.BLACK + '\ufffd'}

    def __init__(self, color='heart', figure=9):
        # init colorama
        init()

        # check if proper color
        if color in Card.colors.keys():
            self.color = color
        else:
            raise Exception('Available colors: [club,diamond,heart,spade]')

        # set figure without testing
        self.figure = figure

    def __str__(self):
        s = ''
        card_style = f' {self.figure}{Card.colors[self.color]}'
        if self.figure != 10:
            card_style += ' '
        s += Back.WHITE + f'{" ":4}\n' + Fore.BLACK + \
            f'{card_style:^4}\n{" ":4}\n' + Back.BLACK + Fore.WHITE
        return s


class Deck():
    global colors, figures

    def __init__(self):
        self.cards = []
        for color in colors:
            for figure in figures:
                self.cards.append(Card(color, figure))

    def __str__(self):
        deck = ''
        for card in self.cards:
            deck += str(card)
        return deck

    def __len__(self):
        return len(self.cards)

    def shuffle(self):
        random.shuffle(self.cards)

    def deal(self):
        return self.cards.pop(0)


class Hand():

    def __init__(self):
        self.cards = []  # start with empty list
        self.value = 0
        self.aces = 0

    def __str__(self):
        hand = ''
        for card in self.cards:
            hand += str(card) + '\n'
        return hand

    def add_card(self, card):
        self.cards.append(card)
        if isinstance(card.figure, int):
            self.value += card.figure
        elif card.figure == 'A':
            self.aces += 1
            self.value += 11
        else:
            self.value += 10
        self.adjust_for_aces()

    def adjust_for_aces(self):
        while self.value > 21 and self.aces:
            self.aces -= 1
            self.value -= 10


class Chips():

    def __init__(self, init_amount):
        self.total = init_amount
        self.bet = 0

    def win_bet(self):
        self.total += self.bet*2
        self.bet = 0

    def keep_bet(self):
        self.total += self.bet
        self.bet = 0

    def lose_bet(self):
        self.bet = 0

    def take_bet(self, bet):
        if self.total-bet >= 0:
            self.bet = bet
            self.total -= bet
            return True
        else:
            return False


class Player():

    def __init__(self, init_chips):
        self.hand = Hand()
        self.chips = Chips(init_chips)

    def clear_hand(self):
        self.hand = Hand()


class DealerHand(Hand):

    def __init__(self):
        Hand.__init__(self)
        self.reveal = False

    def __str__(self):
        hand = ''
        if len(self.cards) == 2 and not self.reveal:
            unknown = Card('unknown', '?')
            hand += str(unknown) + '\n'
            hand += str(self.cards[0]) + '\n'
            return hand
        else:
            for card in self.cards:
                hand += str(card) + '\n'
            return hand

    def reveal_cards(self):
        self.reveal = True


class Dealer():

    def __init__(self):
        self.hand = DealerHand()
        self.deck = Deck()

    def clear_hand(self):
        self.hand = DealerHand()


class BlackJack():

    def __init__(self):
        while True:
            try:
                self.chips = int(input('What amount of money you take into a game?: '))
            except:
                print('Looks like you did not enter an integer!')
                continue
            else:
                self.player = Player(self.chips)
                break
        self.dealer = Dealer()

    def show_cards(self, reveal=False, callback=None):
        # clear()
        print("Dealer's hand:\n")
        if reveal:
            self.dealer.hand.reveal_cards()
        print(self.dealer.hand)
        print("Player's hand:\n")
        print(self.player.hand)
        if callback != None:
            callback()  
        print(f"Player's total: {self.player.chips.total}")

    def play_again(self):
        action = ''
        while action not in ('y', 'n'):
            action = input('Play again?: y or n?[y]: ')
        return action == 'y'

    def hit_or_stand(self):
        action = ''
        while action not in ('h', 's'):
            action = input('Choose action: Hit [h] or Stand [s]?: ')
        return action

    def reset(self):
        self.player = Player(self.chips)
        self.dealer = Dealer()

    def player_busts(self):
        self.player.chips.lose_bet()
        print("You've lost your bet!\n")

    def player_wins(self):
        self.player.chips.win_bet()
        print("You've won! Congratulations!!\n")

    def dealer_busts(self):
        print('Dealer busts, so..\n')
        self.player_wins()

    def dealer_wins(self):
        print('Dealer wins, so..\n')
        self.player_busts()

    def push(self):
        print('It looks like draw!')
        self.player.chips.keep_bet()

    def play(self):
        playing = True
        # game starts!!
        print('Welcome to Blackjack!\n')
        while playing:
                # init stage of a game
            self.dealer.deck.shuffle()
            card = self.dealer.deck.deal()
            self.dealer.hand.add_card(card)
            card = self.dealer.deck.deal()
            self.dealer.hand.add_card(card)
            card = self.dealer.deck.deal()
            self.player.hand.add_card(card)
            card = self.dealer.deck.deal()
            self.player.hand.add_card(card)
            
            self.show_cards()

            # know as for a bet
            while True:
                try:
                    bet = int(input('How much you want to bet?: '))
                except:
                    print('Looks like you did not enter an integer!')
                else:
                    if not self.player.chips.take_bet(bet):
                        print("You don't have enough money for that bet!\n")
                        continue
                    break
            # what next:

            while True:
                self.show_cards()
                action = self.hit_or_stand()
                if action == 'h':
                    self.player.hand.add_card(self.dealer.deck.deal())

                    if self.player.hand.value > 21:
                        callback = self.player_busts
                        break
                elif action == 's':
                    # now dealer hitting
                    while self.dealer.hand.value < 17:
                        self.dealer.hand.add_card(self.dealer.deck.deal())
                    if self.dealer.hand.value > 21:
                        callback = self.dealer_busts
                    elif self.dealer.hand.value > self.player.hand.value:
                        callback = self.dealer_wins
                    elif self.dealer.hand.value < self.player.hand.value:
                        callback = self.player_wins
                    else:
                        callback = self.push
                    break
            # results
            self.show_cards(True, callback)

            # play again?
            if self.player.chips.total > 0:
                playing = self.play_again()
            else:
                print("Further game isn't possible, due to lack of money\nGAME OVER!")
                playing = False
            self.player.clear_hand()
            self.dealer = Dealer()
            pdb.set_trace()

if __name__ == '__main__':
    black = BlackJack()
    black.play()


Copyrights 2014-2019 © Wklejaj.pl Wszelkie prawa zastrzeżone.