티스토리 뷰

반응형

11강 요약

 사용자와 컴퓨터가 대결하는 블랙잭 게임을 파이썬을 활용하여 만들어보았다.

 일단 블랙잭 게임은 카드 게임이고, 21이라는 특정한 수에 제일 먼저 도달하는 쪽이 이기는 게임이다. 

 아래 사이트와 같이 온라인 상에서도 로그인 없이쉽게 접할 수 있는 게임이다. 나는 처음 접하는 게임이라 아래 사이트에서 실제로 해봤는데, 사람들이 도박에 왜 빠지는지 간접체험하였다; 무엇보다 게임룰이 굉장히 쉽고 잘만 하면 쉽게 이길 수 있을 것만 같은 심리를 느끼게 된다. 파이썬 강의듣다가 시간가는줄 모르고 게임에 몰입했다 ㅎㅎㅎ

 

참고: 블랙잭 게임사이트 링크: https://www.247blackjack.com/ 

 

 

247 Blackjack

Welcome to 24/7 Blackjack! Blackjack, also known to some as twenty-one, is one of the most popular casino games around - and also super simple to learn! This easy to use, simple Blackjack game will certainly become your new favorite on the web! Blackjack i

www.247blackjack.com

 

블랙잭 게임 룰

우선 게임을 만들려면 블랙잭의 기본적인 룰과 조건을 알아야 한다. 

여기서 언급한 룰과 조건은 코드 상에 그대로(순서도 거의 동일하게) 적용된다. 

 

  1. Deal both user and computer a starting hand of 2 random card values.
    사용자와 컴퓨터 각각에게 랜덤한 카드를 2개씩 돌려 시작한다. 
  2. Detect when computer or user has a blackjack. (Ace + 10 value card).
    컴퓨터 또는 사용자가 블랙잭을 가지고 있는지 확인한다 (보유한 카드의 합이 21인지 확인)
  3. If computer gets blackjack, then the user loses (even if the user also has a blackjack). If the user gets a blackjack, then they win (unless the computer also has a blackjack).
    컴퓨터가 블랙잭에 걸리면 사용자는 짐 (사용자에게도 블랙잭이 있더라도). 사용자가 블랙잭을 얻으면 사용자가 이김(컴퓨터에도 블랙잭이 없는 경우).
  4. Calculate the user's and computer's scores based on their card values.
    카드 값을 기준으로 사용자와 컴퓨터의 합산 점수를 계산
  5. If an ace is drawn, count it as 11. But if the total goes over 21, count the ace as 1 instead.
    에이스가 뽑히면 11로 계산. 그러나 합계가 21을 초과하면 에이스를 1로 계산
  6. Reveal computer's first card to the user.
    컴퓨터의 첫 번째 카드를 사용자에게 내보임 (컴퓨터가 뽑은 카드 2개 리스트의 첫번째 인덱스를 보여주면됨)
  7. Game ends immediately when user score goes over 21 or if the user or computer gets a blackjack.
    사용자 점수가 21점을 넘거나, 사용자 또는 컴퓨터가 블랙잭이 있으면 게임이 즉시 종료됨 (if 조건문 써야함)
  8. Ask the user if they want to get another card.
    사용자에게 다른 카드를 받을건지 질의 
  9. Once the user is done and no longer wants to draw any more cards, let the computer play. The computer should keep drawing cards unless their score goes over 16.
    사용자가 더 이상 카드를 뽑고 싶지 않으면 컴퓨터가 시작할 차례임. 컴퓨터는 점수가 16점을 넘지 않는 한 계속해서 카드를 뽑음 (while문을 사용하면됨) 
  10. Compare user and computer scores and see if it's a win, loss, or draw.
    사용자와 컴퓨터 점수를 비교하여 승, 패 또는 무승부인지를 판단함 (if문 및 승패/무승부 결과를 return해야함)
  11. Print out the player's and computer's final hand and their scores at the end of the game.
    게임이 끝나면 플레이어와 컴퓨터의 마지막 패와 점수를 출력함
  12. After the game ends, ask the user if they'd like to play again. Clear the console for a fresh start.
    게임이 끝나면 사용자에게 다시 게임을 실행할지 질의함. 새 게임시작을 위해 콘솔을 초기화함 (clear 모듈 import해야함) 

 

블랙잭 게임 코드

!나와 같은 초급레벨에선 매우 어려움 주의!

import random
from replit import clear
from art import logo


def deal_card():
  """Returns a random card from the deck."""
  cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
  random_card = random.choice(cards)
  return random_card
  
  #Hint 6: Create a function called calculate_score() that takes a List of cards as input 
  #and returns the score. 
  #Look up the sum() function to help you do this.
  
def calculate_score(cards):
  """Take a list of cards and return the score calculated from the cards"""
    #Hint 7: Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
  if sum(cards) == 21 and len(cards) ==2:
    return 0
  
    #Hint 8: Inside calculate_score() check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1. You might need to look up append() and remove().
  if 11 in cards and sum(cards) > 21:
    cards.remove(11)
    cards.append(1)
  return sum(cards)
  
  
  #Hint 13: Create a function called compare() and pass in the user_score and computer_score. If the computer and user both have the same score, then it's a draw. If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins. If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses. If none of the above, then the player with the highest score wins.
  
def compare(user_score, computer_score):
    if computer_score == user_score:
      return "Draw :X"
    elif computer_score == 0:
      return "Lose, opponent has Blackjack :X"
    elif user_score == 0:
      return "You win with a Blackjack :)"
    elif user_score > 21:
      return "You went over. You lose."
    elif computer_score > 21:
      return "Opponent went over. You win."
    elif user_score > computer_score:
      return "You win :)"
    else:
      return "You lose :("


def start_game():
  
  print(logo)
  
  user_cards = []
  computer_cards = []
  is_game_over = False
  
  for _ in range(2):
    #new_card = deal_card()
    user_cards.append(deal_card())
    computer_cards.append(deal_card())
  
  #Hint 11: The score will need to be rechecked with every new card drawn and the checks in Hint 9 need to be repeated until the game ends.
  
  while not is_game_over:
  
    user_score = calculate_score(user_cards)
    computer_score = calculate_score(computer_cards)
    
    print(f" Your cards: {user_cards}, current score: {user_score}")
    print(f" Computer's first card: {computer_cards[0]}")
    
    
    #Hint 9: Call calculate_score(). If the computer or the user has a blackjack (0) or if the user's score is over 21, then the game ends.
    
    #Hint 10: If the game has not ended, ask the user if they want to draw another card. If yes, then use the deal_card() function to add another card to the user_cards List. If no, then the game has ended.
    
    if user_score == 0 or computer_score == 0 or user_score > 21: 
      is_game_over = True
    
    else:
      user_draw_cards = input("Do you want to draw another card? Type 'y' to draw a card or 'n' to end: ")
      if user_draw_cards == "y":
        user_cards.append(deal_card())
      else:
        is_game_over = True
    
  #Hint 12: Once the user is done, it's time to let the computer play. The computer should keep drawing cards as long as it has a score less than 17.
  
  while computer_score != 0 and computer_score < 17:
    computer_cards.append(deal_card())
    computer_score = calculate_score(computer_cards)
  
  
  print(f" Your final hand: {user_cards}, final_score: {user_score}")
  print(f" Computer's final hand: {computer_cards}, final_score: {computer_score}")
  print(compare(user_score, computer_score))
  
#Hint 14: Ask the user if they want to restart the game. If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py.



while input("Do you want to play a game of Blackjack ? Type 'y' or 'n': ") == "y":
  clear()
  start_game()

 

느낀점

안젤라유 선생님의 유데미 파이썬 강의를 듣는 사람이라면 이미 fork한 코드 상에 힌트가 수십개 나열되어 있으므로 

해당 힌트를 따라가며 어느정도 코드를 작성해보면 게임이 대~충은 작동한다는 것을 알 것이다. 심지어 힌트가 나열된 순서 그대로 코드를 작성하다보면 완벽하지는 않더라도 게임이 실행된다. 

 

문제는 힌트 없이도 스스로 이러한 코드를 논리적으로 짜낼 수 있는가? 없다면 1) 정답 코드를 주욱 읽어내려가며 왜 이렇게 작성된 것인지 흐름을 이해해야 하며, 2) 혼자서 생각해낸 흐름을 위 힌트처럼 수십개의 문장으로 쪼개 작성해야 하며, 3) 스스로 작성한 힌트를 토대로 다시 한번 코드를 작성해 봐야한다. 이 모든게 반복적으로 계속 진행되어야 한다. 단순 반복 암기가 여기서도 통할 것 같다.