[Python] blackjack 게임하기

‍허진·2023년 2월 27일
0

Programming

목록 보기
7/10
post-thumbnail

> 과제 요구사항

이번에는 블랙잭 게임을 만들어보자! 블랙잭 게임의 규칙은 다음과 같다.

Twenty-One으로도 알려진 블랙잭(Blackjack)은 보통 하나 이상의 표준 카드 덱으로 플레이되는 카드 게임이다.
이 과제에서 6개의 덱을 사용한다고 가정해보자. 표준 카드 한 벌에는 52장의 카드가 들어 있으며, 클럽, 다이아몬드, 하트, 스페이드 등 4벌의 카드가 각각 13장씩 들어 있다. A(에이스), 2, 3, 4, 5, 6, 7, 8, 9, 10, J(잭), Q(퀸), K(킹) 등 13개의 카드가 있다. 카드는 순위에 따라 포인트 값이 다르다.

[카드의 포인트 값]

  • 페이스카드(잭,퀸,킹) : 10점
  • 에이스 : 1점 또는 11점
  • 기타 모든 항목: 카드의 숫자 값

이 게임의 목적은 카드 포인트 값의 합을 초과하지 않고 21에 가깝게 얻는 것이다. 선수(또는 딜러)는 점수가 21점을 넘으면 게임에서 진다.

플레이 과정은 다음과 같다.

There is one dealer and one or more player(s). Here is a “simplified” progression of the game:
1. Player wagers an initial bet for the hand before the cards are dealt.
2. One card is dealt face up to the player, and then one card is dealt face up to the dealer. Another card is dealt face up to the player, and then another card is dealt face down to the dealer. The face-down card is the hole-card, and it is hidden from the player.
3. The player (or the dealer) has a blackjack if the point values of the 2 cards “initially” dealt to them add up to exactly 21 (an Ace and a card with value 10). (The following might NOT be the standard rule.)

  • If the player gets a blackjack, then the player gets 2.5 of what they bet.
  • If the dealer gets a blackjack, then the dealer wins even if a player’s value is 21. • If not, game play continues with the next step..
  1. The player has fewer than 21 points, so they have three options:
  • Hit : Request another card. The player can do this as many times as they want in a single turn.
  • Stand : Indication to keep the current cards. Player stays at the current best value of their cards.
  • Double : The player doubles their bet and hits one more time, but then must stand (they do not have the option to keep hitting).
  1. The dealer will always employ the same simple strategy. If the dealer does not have 21, they hit until they get to a value of 17 or above. This is also known as “stand on soft 17.”
  • For one of the game play strategies under consideration, you will analyze the performance of when the player mimics the dealers strategy and plays this way too.
  1. Each player may win/lose/draw (not blackjack nor bust) by comparing the player’s number and the dealer’s number. If win, the player earns the doubled betting money. If lose, the player gets nothing. If draw, they player returns the betting money.

영어 해석은 스스로 해보도록 하자! ㅎㅎ

실제 게임을 할 때 알아야 할 사항은 다음과 같다.

당신은 싱글 플레이어로 경기를 하고 딜러를 상대로 돈을 모은다. 당신은 100개 이하의 동전으로 시작할 수 있지만, 매 게임 당 베팅은 항상 '2'개의 동전으로 한다.
게임에서의 각 턴마다 세 가지 옵션(H/S/D, Hit/Stand/Double)이 있으며

  • 값이 21이면 "S"를 선택해야 합니다.
  • D – Double을 선택하면 카드가 하나만 더 표시됩니다.
  • 블랙잭(2카드의 합이 21)을 얻으면 이길 수밖에 없다.

> 출력 예시

> 코드

Card 그룹을 만드는 부분에서 Class를 이용하였다.

import math

class Card:
    def __init__(self,value,suit):
        self.value=value
        self.suit=suit
    def __repr__(self):
        names=['J','Q','K','A']
        if self.value<=10:
            return '{}{}'.format(self.value,self.suit)
        else:
            return '{}{}'.format(names[self.value-11],self.suit)

import random

class Card_group:
    def __init__(self,cards=[]):
        self.cards=cards
    def nextCard(self):
        return self.cards.pop(0)
    def hasCard(self):
        return len(self.cards)>0
    def size(self):
        return len(self.cards)
    def shuffle(self):
        random.shuffle(self.cards)

class Standard_deck(Card_group):
    def __init__(self):
        self.cards=[]
        cnt=0
        while cnt<5:
            for s in['H','D','C','S']:
                for v in range(2,15):
                    self.cards.append(Card(v,s))
            cnt+=1 

def cal_sum(sample):
    tmp=[]
    for i in sample:
        tmp.append(list(i))
    sum=[0]
    res=0
    for card in tmp:
        test=card[0]
        if test=='K' or test=='Q' or test=='J':
            for i in range(len(sum)):
                sum[i]+=10
        elif test=='A':
            for i in range(len(sum)):
                tmp=sum[i]
                sum[i]+=1
                sum.append(tmp+11)
        else:
            if test=='1':
                if card[1]=='0':
                    for i in range(len(sum)):
                        sum[i]+=10
                else:
                    for i in range(len(sum)):
                        sum[i]+=int(test)
            else:
                for i in range(len(sum)):
                        sum[i]+=int(test)
        
    flag=0
    for i in sum:
        if i<=21:
            flag=1
    
    if flag==0:
        res=sum[0]
    
    if flag==1:
        for i in sum:
            if i>21:
                break
            else:
                res=i 
    return res


print('Welcome to the World of 21 !!!')
coin=input('What is your total coins to begin (default = 100) : ')
coin=int(coin)

while(1):
    flag=0
    if coin<2:
        print('Oh no! There are not enough coins to play game. Goodbye~~')
        break

    coin-=2
    print(f'Let’s start a game. You bet 2 coins and {coin} coins remain.')
    deck=Standard_deck()
    deck.shuffle()
    player=[]
    dealer=[]
    
    player.append(str(deck.nextCard()))
    dealer.append(str(deck.nextCard()))
    player.append(str(deck.nextCard()))
    dealer.append(str(deck.nextCard()))
    dsum=cal_sum(dealer)

    while(1):
        psum=cal_sum(player)
        show_player=' '.join(player)
        print('Dealer has : ',dealer[0])
        if psum==21 and len(player)==2:
            print(f'You have : {show_player} --> You got a Blackjack. Congrat.\n')
            coin+=5
            break

        if psum<22:
            next=input(f'You have : {show_player} ... Your choice is : ')
        else:
            print(f'You have : {show_player} --> You are busted.\n')
            break


        if next.lower()=='h':
            player.append(str(deck.nextCard()))

        if next.lower()=='s':
            while dsum<17:
                dealer.append(str(deck.nextCard()))
                dsum=cal_sum(dealer)
            
            show_dealer=' '.join(dealer)
            if dsum>21:
                print(f'Dealer has : {show_dealer} --> Dealer is busted.\n')
                coin+=4
                break
            else:
                print(f'Dealer has : {show_dealer}')
                if psum>dsum:
                    print(f'You have : {show_player} --> You win. Congrat.\n')
                    coin+=4
                    break
                elif psum<dsum:
                    print(f'You have : {show_player} --> Dealer wins.\n')
                    break
                else:
                    print(f'You have : {show_player} --> Draw.\n')
                    coin+=2
                    break

        if next.lower()=='d':
            coin-=2
            print(f'Now you bet 4 coins and {coin} coins remain.')
            player.append(str(deck.nextCard()))
            show_player=' '.join(player)
            psum=cal_sum(player)
            print('Dealer has : ',dealer[0])
            if psum>21:
                print(f'You have : {show_player} --> You are busted.\n')
                break
            else:
                print(f'You have : {show_player}')
                while dsum<17:
                    dealer.append(str(deck.nextCard()))
                    dsum=cal_sum(dealer)
                
                show_dealer=' '.join(dealer)
                if dsum>21:
                    print(f'Dealer has : {show_dealer} --> Dealer is busted.\n')
                    coin+=8
                    break
                else:
                    print(f'Dealer has : {show_dealer}')
                    if psum>dsum:
                        print(f'You have : {show_player} --> You win. Congrat.\n')
                        coin+=8
                        break
                    elif psum<dsum:
                        print(f'You have : {show_player} --> Dealer wins.\n')
                        break
                    else:
                        print(f'You have : {show_player} --> Draw.\n')
                        coin+=4
                        break

        if next=='0':
            coin+=2
            print(f'\nGoodbye~~ You are left with {coin} coins.')
            flag=1
            break

    if flag==1:
        break
profile
매일 공부하기 목표 👨‍💻 

0개의 댓글