Python🐍

파이썬을 이용한 블랙잭 게임

hoho0311 2025. 1. 21. 22:02

이번 프로젝트는 파이썬을 이용해서 블랙잭을 만들어 볼 것이다.

자꾸 강의에서 무섭다고 겁을 주는데 생각보다 생각보다 쉬웠지만... 지피티는 사용했다.

 

일단 내가 해본 카드게임이라고는 원카드, 조커뽑기라서 블랙잭 규칙에 대해서 조금 공부해봤다.

 

https://namu.wiki/w/%EB%B8%94%EB%9E%99%EC%9E%AD(%ED%94%8C%EB%A0%88%EC%9E%89%20%EC%B9%B4%EB%93%9C)#s-4.1

 

블랙잭(플레잉 카드)

플레잉 카드 로 즐길 수 있는 카지노 게임이다. 21에 딜러보다 더 가까이 만들면 이기는 게임이다. 그렇다고 숫자가

namu.wiki

혹시 규칙에 대해 궁금하다면 여기서 확인해보면 좋겠다.

 

 

https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExaTVyZWpvZjJqZ2czbDFkbzVqdDN3eWt4cmN1MzV5aHk5Yzlvczd2ZyZlcD12MV9naWZzX3NlYXJjaCZjdD1n/NaboQwhxK3gMU/giphy.gif

 

 

 

블랙잭의 모든 규칙을 그대로 적용하면 너무 어려울거같아 몇가지 규칙을 정했다.

 

  • 1. 덱의 사이즈는 제한되어 있다.
  • 2. 조커는 없다.
  • 3. 잭,퀸,킹은 모두 10으로 계산한다.
  • 4. 에이스는 11 또는 1로 계산한다.
  • 5. 덱에 있는 카드는 모두 동등한 확률로 뽑힌다.
  • 6. 덱에서 카드를 뽑아도 덱에서 카드가 사라지지 않는다.
  • 7. 컴퓨터가 딜러이다.

Blackjack_Flowchart.pdf
0.03MB

 

블랙잭 프로젝트의 흐름도이다. 참고하며 프로그래밍 했다.

 

자 이제 코드 첨부하겠다.

import random
import art  # 로고 출력용

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

# 점수 계산 함수
def calculate_score(hand):
    total = sum(hand)
    aces = hand.count(11)
    while total > 21 and aces:
        total -= 10  # Ace를 1로 조정
        aces -= 1
    return total

 

먼저 점수 계산을 하는 함수이다.

hand는 딜러나 유저의 손에 있는 카드를 말한다.

hand를 통해 점수의 총합을 구하고 

에이스를 11이나 1로 정하는 로직이다.

 

# 블랙잭 확인 함수
def check_blackjack(hand):
    return 11 in hand and 10 in hand


# 플레이어 행동
def player_turn(player_cards):
    while True:
        current_score = calculate_score(player_cards)

        # 현재 상태 출력은 루프 내에서 한 번만 실행
        more_card = input("Type 'y' to get another card, 'n' to pass: ").lower()
        if more_card == 'y':
            player_cards.append(random.choice(cards))
            current_score = calculate_score(player_cards)
            print(f"Your cards: {player_cards}, current score: {current_score}")
        else:
            break

        # 21 초과 시 종료
        if current_score > 21:
            print("You went over 21! You lose.")
            return current_score
    return current_score

 

ckeck_blackjack : 이름처럼 손에 블랙잭을 가지고 있는지 확인한다.

블랙잭은 11과 10이 모두 패에 있는것을 말한다.

 

플레이어의 행동을 담은 함수이다.

처음 패를 받은후 플레이어는 패를 더 받을지 아니면 게임을 끝낼지 선택할 수 있다.

만약 패를 더 뽑았는데 점수가 21점이 넘을 시에 게임은 패배하게 된다.

 

# 딜러 행동
def dealer_turn(dealer_cards):
    while calculate_score(dealer_cards) < 17:
        dealer_cards.append(random.choice(cards))
    return calculate_score(dealer_cards)


# 점수 비교
def compare_scores(player_score, dealer_score):
    if player_score > 21:
        return "You lose. Your score went over 21."
    if dealer_score > 21:
        return "You win! Dealer's score went over 21."
    if player_score > dealer_score:
        return "You win!"
    elif player_score < dealer_score:
        return "You lose!"
    else:
        return "It's a draw!"

 

딜러의 행동을 담은 함수이다

만약 딜러가 처음 카드 두 장을 받았을 때 합이 17보다 낮으면

카드를 한장 더 받는다.

그 다음 점수를 반환한다.

 

점수 비교 함수이다.

지금까지의 과정에서 반환된 

유저와 딜러의 점수를 비교하여 승패를 출력한다.

 

# 게임 실행
def play_game():
    print(art.logo)

    # 카드 배분
    player_cards = random.sample(cards, 2)
    dealer_cards = random.sample(cards, 2)

    # 초기 상태 출력
    print(f"Your cards: {player_cards}, current score: {calculate_score(player_cards)}")
    print(f"Computer's first card: {dealer_cards[0]}")

    # 블랙잭 확인
    if check_blackjack(player_cards) or check_blackjack(dealer_cards):
        if check_blackjack(player_cards) and check_blackjack(dealer_cards):
            print("Both have Blackjack! It's a draw.")
        elif check_blackjack(player_cards):
            print("You win with a Blackjack!")
        else:
            print("Computer wins with a Blackjack!")
        return

    # 플레이어 턴
    player_score = player_turn(player_cards)

 

게임 실행 함수이다.

함수 실행시

딜러와 유저는 카드 두장을 받는다.

그 다음 유저의 카드 2장과 점수를 보여주고

딜러의 첫 번째 카드만 보여준다.

 

# 게임 시작
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower() == 'y':
    play_game()

 

마지막으로 반복문을 사용하여 사용자가 원할 때 까지 게임을 반복 할 수 있게 만들었다.