업무에 파이썬 활용할 줄 알기
Day11 | 초급 | 블랙잭 게임 프로젝트 본문
My solution : 실패코드
내 코드의 문제점: "Type 'y' to get another card, type 'n' to pass: "가 n일 때, 다음으로 못넘어감
import random
import art
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
yesno_for_start = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
yourcard = []
comcard = []
if yesno_for_start == 'y':
print(art.logo)
#Your cards 랜덤선택 2개 > 리스트화, 합계계산
for i in range(2):
chosen_card = random.choice(cards)
if chosen_card == 11:
chosen_card = 1
yourcard.append(chosen_card)
user_current_score = sum(yourcard)
#return your card < 이게 필요한지 안한지 잘모르겠다
#Computer cards 랜덤선택 2개 중 첫번째것만 보여주기
for i in range(2):
chosen_card = random.choice(cards)
comcard.append(chosen_card)
com_first_card = comcard[0]
print(f'Your cards: {yourcard}, current score: {user_current_score}')
print(f"Computer's first card: {com_first_card}")
#yesno선택
yesno_for_more_try = input("Type 'y' to get another card, type 'n' to pass: ")
#while문을 작성하고 싶은데 y or n을 계속 선택해야해서 while문을 쓸 수 있는 상황인지 판단이 잘 안된다
#(나는 while을 못썼는데)while문을 사용했던 코드작성문 찾아보기, 행맨이었나?
if yesno_for_more_try == 'y':
yesno_for_more_try2 = yesno_for_more_try
while yesno_for_more_try2 == 'y':
#yourcard에 카드추가 랜덤선택
chosen_card = random.choice(cards)
yourcard.append(chosen_card)
user_current_score = sum(yourcard)
print(f' Your cards: {yourcard}, current score: {user_current_score}')
print(f" Computer's first card: {com_first_card}")
#사용자합계 결과가 21이상일 때
if user_current_score >= 21:
#승패진단(일단 무조건 짐)
#컴퓨터 함계 계산
#17이상이 될 때까지 카드 추가
com_card_sum = sum(comcard)
while sum(comcard) < 17:
chosen_card = random.choice(cards)
comcard.append(chosen_card)
com_card_sum #이렇게 해줘야하나?
#승패진단(사용자가 무조건 짐)
print(f" Your final hand: {yourcard}, final score: {user_current_score}")
print(f" Computer's final hand: {comcard}, final score: {com_card_sum}")
print(f"You went over. You lose")
input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")
#사용자합계 결과가 21미만일 때
elif user_current_score < 21:
#여기서 오류가 생기는데, 값을 다시 설정해주려면 어떻게 해야하나.. > yesno_for_more_try2로 변경했으나 이상함
#여기서 n선택하면 다음으로 못넘어감 > 아래에서 yesno_for_more_try2를 받게 or로 추가했는데..안되지
yesno_for_more_try2 = input("Type 'y' to get another card, type 'n' to pass: ")
#첨으로 돌아가는거 어떻게 하는지 방법 생각안남..
elif yesno_for_more_try2 == 'n' or yesno_for_more_try == 'n':
#comcard 17이상이 될 때까지 카드 추가
com_card_sum = sum(comcard)
while com_card_sum < 17:
chosen_card = random.choice(cards)
comcard.append(chosen_card)
com_card_sum
print(f' Your cards: {yourcard}, current score: {user_current_score}')
print(f" Computer's first card: {com_first_card}")
if user_current_score > com_card_sum:
print(f"You win.")
elif user_current_score < com_card_sum:
print(f" Your final hand: {yourcard}, final score: {user_current_score}")
print(f" Computer's final hand: {comcard}, final score: {com_card_sum}")
print(f"You went over. You lose")
else:
print(f"draw")
yesno_for_start
(일단 코드작성 후, 실패했지만) 소감
10일차 수업과 11일차 수업사이에 간격이 꽤 있었다.
10일차 수업까지 배운걸 모두 녹여내는 캡스톤 프로젝트라니.. 11일차 수업을 앞두고 되게 많이 무서웠고, 여기서 며칠을 써야될까봐 겁이 났는데 꼬박 거의 하루반만에 해냈다
비록 모범답안과는 거리가 먼 코드일지라도 혼자 코드를 최대한 써봤다는게 뿌듯하다
못할 줄 알았다. 배운게 기억이 안날 것 같았다. 막막했다. 플로우차트 짜려고 생각하니 엄두가 안났다.
근데 코드가 짜졌고 비스무리하게나마 실행이 됐다. 이렇게 차근차근 가보자
모범답안
Flowchart 그려낼 줄 알기
정답코드
import random
from replit import clear
def deal_card():
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):
#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 user_score == computer_score:
return "Draw"
elif computer_score == 0:
return "Lose, opponent has Blackjack"
elif user_score == 0:
return "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 play_game():
#Hint 5: Deal the user and computer 2 cards each using deal_card() and append().
user_cards = []
computer_cards = []
is_game_over = False
for _ in range(2):
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:
#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.
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]")
if computer_score == 0 or user_score == 0 or user_score > 21:
is_game_over = True
else:
#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.
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == '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 scores: {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 of Blackjack? Type 'y' or 'n': ") == 'y':
clear()
play_game()
(복습 후) 느낀 점
전부다 def로 처리하고 실행문은 아래와 같이 간단하게 만들다니 놀랍다..!
while input("Do you want to play of Blackjack? Type 'y' or 'n': ") == 'y':
clear()
play_game()
나는 flowchart를 그려놓고 flowchart 절차대로 코드를 짰다면
모범답안은 flowchart안에서도 def와 while을 활용하여 다시 구조를 갖추었다.
여전히 def와 while을 잘사용하지 못하는 나에게 많은 깨달음을 주는 코드작성문이다.
(특히 while not is_game_over: 와 같이 True/False를 임의로 지정해주는 변수를 잘 만들어내지 못한다)
화면에 띄울 텍스트와 텍스트(질문 또는 결과)사이에 어떤 계산들을 해주어야하는지를 구조를 갖춘 것으로 보인다.
'Python > [Udemy] 100개의 프로젝트로 Python 개발 완전 정복' 카테고리의 다른 글
Day 18 | 중급 | 터틀 & 그래픽 사용자 인터페이스 (GUI) (2) | 2024.01.02 |
---|---|
Day17 | 중급 | 퀴즈 프로젝트와 OOP의 장점 (0) | 2023.12.28 |
Day16 | 중급 | 객체 지향 프로그래밍(OOP) (0) | 2023.12.27 |
Day15 | 중급 | 커피 머신 프로젝트 (0) | 2023.12.26 |
Day12 | 초급 | 유효 범위와 숫자 맞추기 게임 복습 (0) | 2023.12.20 |