숫자 업다운 게임

JOOYEUN SEO·2024년 8월 19일

100 Days of Python

목록 보기
14/76
post-thumbnail

🗂️ Day14 프로젝트: 숫자업다운 게임

The Higher Lower Game 클래식 버전

  • 온라인 무료 플레이 가능
  • 두 검색어를 비교하여 구글 월 평균 검색량이 더 많은 검색어를 맞춰야 함
  • 맞추면 맞춘 검색어 vs 새 검색어 로 다시 비교
  • 틀릴 때까지 반복 후, 맞춘 횟수만큼 점수로 계산

🔍 유의 사항

  • 프로젝트는 클래식 버전을 변형
    • 검색어는 유명인(또는 브랜드)들의 이름
    • 구글 월 평균 검색량 대신 해당 인물(또는 브랜드)의 인스타그램 팔로워 수로 비교
    • game_data.py의 딕셔너리에 있는 유명인의 모든 정보가 활용되어야 함
  • 진행 방식
    • 먼저 인물(또는 브랜드) A vs 인물(또는 브랜드) B를 진행 후,
      • 다음 라운드의 A : 이전 라운드에서 이긴 인물(또는 브랜드)
      • 다음 라운드의 B : 새 인물(또는 브랜드)
    • 다음 라운드로 갈 때,
      • 콘솔창을 비우고 이전 라운드의 결과와 현재 점수를 출력
      • 이전 라운드가 정답일 경우 다시 A vs B 시작
  • 코드 작성을 위한 단계
    1. 큰 문제를 작은 문제들로 나누기
    2. 프로그래밍 할 내용을 Todo 리스트로 정리하고 쉬운 것부터 선택
    3. 선택한 작업을 주석처리하여 코드에 나눠 입력
    4. 주석 처리한 부분을 해제하여 실제로 코드를 작성 후 실행
    5. 실행해 본 후 코드 고치기
      (4-5번 반복)
    6. 완료되면 다시 3번으로 돌아가 다른 작업을 골라서 똑같이 진행

📄 art.py

logo = """아스키 아트"""
vs = """아스키 아트"""

📄 game_data.py

data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': 'Social media platform',
        'country': 'United States'
    },
    {
        'name': 'Cristiano Ronaldo',
        'follower_count': 215,
        'description': 'Footballer',
        'country': 'Portugal'
    },
    {
        'name': 'Ariana Grande',
        'follower_count': 183,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Dwayne Johnson',
        'follower_count': 181,
        'description': 'Actor and professional wrestler',
        'country': 'United States'
    },
    {
        'name': 'Selena Gomez',
        'follower_count': 174,
        'description': 'Musician and actress',
        'country': 'United States'
    },
    {
        'name': 'Kylie Jenner',
        'follower_count': 172,
        'description': 'Reality TV personality and businesswoman and Self-Made Billionaire',
        'country': 'United States'
    },
    {
        'name': 'Kim Kardashian',
        'follower_count': 167,
        'description': 'Reality TV personality and businesswoman',
        'country': 'United States'
    },
    {
        'name': 'Lionel Messi',
        'follower_count': 149,
        'description': 'Footballer',
        'country': 'Argentina'
    },
    {
        'name': 'Beyoncé',
        'follower_count': 145,
        'description': 'Musician',
        'country': 'United States'
    },
    {
        'name': 'Neymar',
        'follower_count': 138,
        'description': 'Footballer',
        'country': 'Brasil'
    },

 ...중략(총 50개의 원소로 이루어진 리스트)...
 
 ]

⌨️ 작성한 코드

from random import choice
from replit import clear
from art import logo, vs
from game_data import data

# A와 B의 팔로워 수를 비교해서 어느 쪽이 더 많은지 반환하는 함수
def compare(a_follower, b_follower):
    if a_follower > b_follower:
        return 'A'
    else:
        return 'B'
        
# 콘솔창을 지우고 다시 로고를 보여주는 함수
def clean_console():
    clear()
    print(logo)
    
def game():
    # 플레이어의 점수 초기화
    score = 0
    next_round = True
    
    # A vs B 시작
    print(logo)
    a = choice(data)
    data.remove(a)
    # 이전 라운드에서 이긴 쪽이 새로운 A가 되므로 다음 라운드의 시작은 여기부터
    while next_round:
        print(f"Compare A : {a['name']}, a {a['description']}, from {a['country']}")
        
        print(vs)
        
        b = choice(data)
        data.remove(b)
        print(f"Against B : {b['name']}, a {b['description']}, from {b['country']}")
        
        pick = input("Who has more followers on The instagram? Type 'A' or 'B' : ").upper()
        winner = compare(a['follower_count'], b['follower_count'])
        
        if pick == winner and not data:
            score += 1
            clean_console()
            print(f"You are right! and you finished all in the list. Final score : {score}")
            return
        elif pick == winner:
            score += 1
            clean_console()
            print(f"You are right! Current score : {score}\n")
            if winner == 'B':
                a = b
        else:
            clean_console()
            print(f"Sorry that's wrong. Final score : {score}")
            return
# game 함수 호출
game()
[ 출력 결과 ]


    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     

Compare A : NASA, a Space agency, from United States

 _    __    
| |  / /____
| | / / ___/
| |/ (__  ) 
|___/____(_)

Against B : Taylor Swift, a Musician, from United States
Who has more followers on The instagram? Type 'A' or 'B' : ❚B



    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     

You are right! Current score : 1

Compare A : Taylor Swift, a Musician, from United States

 _    __    
| |  / /____
| | / / ___/
| |/ (__  ) 
|___/____(_)

Against B : Demi Lovato, a Musician and actress, from United States
Who has more followers on The instagram? Type 'A' or 'B' : ❚B



    __  ___       __             
   / / / (_)___ _/ /_  ___  _____
  / /_/ / / __ `/ __ \/ _ \/ ___/
 / __  / / /_/ / / / /  __/ /    
/_/ ///_/\__, /_/ /_/\___/_/     
   / /  /____/_      _____  _____
  / /   / __ \ | /| / / _ \/ ___/
 / /___/ /_/ / |/ |/ /  __/ /    
/_____/\____/|__/|__/\___/_/     

Sorry that's wrong. Final score : 1

🖍️ 답안

import random

from replit import clear

from art import logo, vs
from game_data import data


def get_random_account():
  """Get data from random account"""
  return random.choice(data)

def format_data(account):
  """Format account into printable format: name, description and country"""
  name = account["name"]
  description = account["description"]
  country = account["country"]
  # print(f'{name}: {account["follower_count"]}')
  return f"{name}, a {description}, from {country}"

def check_answer(guess, a_followers, b_followers):
  """Checks followers against user's guess 
  and returns True if they got it right.
  Or False if they got it wrong.""" 
  if a_followers > b_followers:
    return guess == "a"
  else:
    return guess == "b"


def game():
  print(logo)
  score = 0
  game_should_continue = True
  account_a = get_random_account()
  account_b = get_random_account()

  while game_should_continue:
    account_a = account_b
    account_b = get_random_account()

    while account_a == account_b:
      account_b = get_random_account()

    print(f"Compare A: {format_data(account_a)}.")
    print(vs)
    print(f"Against B: {format_data(account_b)}.")
    
    guess = input("Who has more followers? Type 'A' or 'B': ").lower()
    a_follower_count = account_a["follower_count"]
    b_follower_count = account_b["follower_count"]
    is_correct = check_answer(guess, a_follower_count, b_follower_count)

    clear()
    print(logo)
    if is_correct:
      score += 1
      print(f"You're right! Current score: {score}.")
    else:
      game_should_continue = False
      print(f"Sorry, that's wrong. Final score: {score}")

game()

'''

FAQ: Why does choice B always become choice A in every round, even when A had more followers? 

Suppose you just started the game and you are comparing the followers of A - Instagram (364k) to B - Selena Gomez (174k).
Instagram has more followers, so choice A is correct.
However, the subsequent comparison should be between Selena Gomez (the new A) and someone else.
The reason is that everything in our list has fewer followers than Instagram. 
If we were to keep Instagram as part of the comparison (as choice A) then Instagram would stay there for the rest of the game.
This would be quite boring.
By swapping choice B for A each round, we avoid a situation where the number of followers of choice A keeps going up over the course of the game.
Hope that makes sense :-)

'''



# Generate a random account from the game data.

# Format account data into printable format.

# Ask user for a guess.

# Check if user is correct.
## Get follower count.
## If Statement

# Feedback.

# Score Keeping.

# Make game repeatable.

# Make B become the next A.

# Add art.

# Clear screen between rounds.
  • random 모듈의 choice로 리스트에서 A와 B를 뽑을 때, 두 값이 같지 않도록 조치하기
    • 나의 코드 : 값 하나를 뽑을 때마다 리스트에서 바로 삭제 → 리스트가 비면 게임도 끝나는 걸로 설정
    • 강의 코드 : 먼저 두 값을 뽑고, while문으로 두 값이 같은지 체크 → 같다면 다를 때까지 B를 다시 뽑음
  • 강의 코드에서는 check_answer 함수 안에서 A와 B의 팔로워 수를 비교한 후,
    플레이어의 추측(guess)과 맞는지 비교까지 한 뒤, 정답을 맞춘 여부에 따라 참/거짓 값을 반환
    • a_followers > b_followers 이면, guess == "a" 반환
      • 더 많은 쪽(a)을 추측했다면 반환값은 True
      • 더 많은 쪽(a)을 추측하지 못했다면 반환값은 False
    • a_followers < b_followers 이면, guess == "b" 반환
      • 더 많은 쪽(b)을 추측했다면 반환값은 True
      • 더 많은 쪽(b)을 추측하지 못했다면 반환값은 False
  • 다음 라운드로 올라갈 때 A와 B 처리
    • 나의 코드 : 팔로워 수가 더 많은 쪽이 A가 되고, B는 새로운 대상이 됨
    • 강의 코드 : 다음 라운드로 진행할 때 이전 라운드의 B가 A가 되고, B는 다른 대상이 됨
      • 답안의 FAQ (A의 팔로워가 더 많을 때도 항상 B가 다음 라운드에 가는 이유)
        만약 A에 팔로워가 제일 많은 Instagram(364k)이 올 경우
        게임이 끝날 때까지 계속 A에 Instagram이 머무르기 때문에 지루해질 수 있음
    • 강의 코드의 순서
      1. 게임 시작 시 먼저 A, B를 뽑음
      2. while game_should_continue 안에서 B를 A에 넣음
      3. B를 새로 다시 뽑음 (while account_a == account_b 으로 두 값이 달라질 때까지)




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글