티스토리 뷰
강의 요약
"Higher Lower"이라는 게임을 직접 구현해보는 미니 프로젝트를 진행했다.
이번 강의에서는 새로운 개념을 익힌 것은 아니고, 기존에 배웠던 개념을 충분히 활용하여 게임을 혼자서 만들어보고
이에 대해 해설하는 강의로만 진행됐다. 이런 방식의 강의가 한 3번정도 더 반복되면 좋겠다고 생각했다. 여태 배운 것들을 충분히 활용해보기에 참 괜찮은 내용이었다.
Higher Lower 게임 소개
우리나라로 치면 이상형월드컵 게임과 행맨게임을 오묘하게 섞어놓은 게임이랄까...
다양한 주제(ex. 영화, 드라마, 팝송 등)로 할 수 있는 게임이고, 랜덤으로 선택된 A와 B중에 '어떤게 더 평점이 높았을까?', '관객수가 더 많았을까?' 등의 질문에 둘중 하나를 선택하면 된다. 맞히는 대로 게임 스코어가 올라가고, 틀리는 순간 바로 게임 종료이므로 후덜덜하다.
* 게임 링크: https://www.higherorlowergame.com/
한국 드라마나 영화 평점 맞추기도 있다. 새삼 느껴지는 K-culture ㅋㅋㅋ
Higher or Lower Game
Trivia higher or lower games for stats nerds. Featuring games about Google, Movies, Music, Sports and more. Play now!
www.higherorlowergame.com
게임을 만들기 위한 초석 다지기
혼자서 게임을 만드는게 너무 힘들었다. 일단 첫 스타트를 끊는게 제일 고통스럽다 ㅠㅠ
게임을 파이썬이 아닌 한국어로 정리하는 것은 쉬우니... 일단 아래와 같이 게임의 흐름이나 조건을 정리하는 것으로 시작해보았다.
우선 이 게임은 월드스타나 인플루언서들의 인스타 계정을 임의로 추출하여, 어떤 계정의 팔로워 수가 더 많을지 맞히는 게임이다.
# 1. 로고(higher lower) 뿌리기
# 2. 랜덤으로 인스타계정 추출
# 3. 첫 게임에는 두번 추출 (A, B 각각)
# 4. 유저에게 A, B중 누가 더 많을지 ask
# 5. 추출된 계정간 팔로워수 비교
# 6. 유저의 추측이 맞으면, 해당 인스타 계정이 A가됨
# 7. 그 다음 B가 될 랜덤 계정 추출
# 8. 유저의 추측이 틀리면, 게임 종료
그리고 다음과 같이 함수 단위로 쪼개보았는데, 사실 이부분은 코드를 주욱 작성하다가 해도 되는 부분 같다.
나는 도저히 하다하다 안되겠어서, 안젤라쌤의 코드를 살짝 스캐닝하다가 미리 정리하게 된 부분이라... ㅠㅠ
# 필요한 함수
1. 랜덤 인스타그램 계정 추출 (A, B계정)
2. A, B간 인스타그램 팔로워수 비교
3. 게임 시작
- 게임 스코어
- 게임 시작 및 종료 판단
- 게임이 반복되는 경우 고려 (while문)
(최종) 코드 작성 비교
1. 내가 작성한 코드
import random
from replit import clear
from art import logo, vs
from game_data import data
#step 1. 랜덤 계정 추출 함수
def select_account():
account = random.choice(data)
#print(account)
return account
#account = select_account()
#step 2. 랜덤 계정 정보 나열(이름, 팔로워수, 직업, 출신국가)
def account_info(account):
name = account['name']
description = account['description']
country = account['country']
follower_count = account['follower_count']
#print(follower_count)
return f"{name}, a {description} from {country}"
#account_info(account)
# step 3. 팔로워수 비교
def compare_followers(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 guess == "a" and a_followers > b_followers or guess == "b" and b_followers > a_followers:
return True
elif guess == "a" and a_followers < b_followers or guess == "b" and a_followers > b_followers:
return False
def game_start():
#초기 세팅
print(logo)
score = 0
should_continue = True
account_a = select_account()
account_b = select_account()
while should_continue:
print(f"Compare A: {account_info(account_a)}.")
print(vs)
print(f"Against B: {account_info(account_b)}.")
guess = input("Who has more follower? Type 'A' or 'B': ").lower()
acc_a_followers = account_a['follower_count']
acc_b_folloers = account_b['follower_count']
is_right_guess = compare_followers(guess, acc_a_followers, acc_b_folloers)
clear()
print(logo)
if is_right_guess == True:
account_a = account_b
account_b = select_account()
score += 1
print(f"You win! Your score is {score}.")
else:
print(f"Game Over. Your final score is {score}")
should_continue = False
game_start()
2. 안젤라유 쌤이 제공한 정답 코드
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()
결론
퇴근후 집에와서 약 2-3일간 짧으면 30분, 길면 1시간씩 붙잡고 있으면서 고민하던 거라, 결국 어찌저찌 완성이 돼서 보람차고 뿌듯했다.
요 정도의 난이도 또는 이거보다 약간 쉬운 난이도로 비슷한 연습문제를 더 많이 풀어보고 싶다!
지금은 끝냈으니 후련하지만, 중간중간 고민하는 과정은 너무 고통스러웠는데 그때마다 작성한 코드까지 일단 print해보거나 정 안될때는 Thonny를 활용해서 잘못 작성한 부분을 잡아내려고 했다. 그리고 실제로 효과가 있었다! 어려울땐 혼자 끙끙대기만 하지 말고, 실용적으로 해결하려고 노력해보자~ >_<
'study' 카테고리의 다른 글
[파이썬] 13강 디버깅하는 방법 (feat. Everyone gets bugs) (0) | 2024.04.23 |
---|---|
[파이썬] 12강 지역범위(Local Scope), 전역 범위(Global Scope) +랜덤숫자 추출하여 예측하는 게임 만들기 (0) | 2024.04.20 |
[파이썬] 11강 블랙잭 게임 만들기(함수, 조건문 활용 실습) (0) | 2024.04.12 |
[파이썬] 10강 함수 출력, 독스트링(docstrings), 재귀함수 (1) | 2024.04.06 |
[파이썬] 9강 딕셔너리와 리스트 중첩(dictionaries, list nesting) (0) | 2024.03.30 |
- Total
- Today
- Yesterday
- 아야진해변
- 파이썬 안젤라유 강의
- 고성
- 벡터
- 파이썬반복문
- 파이썬전역범위
- 파이썬디버깅
- 파이썬초급강의
- 파이썬디버거
- 파이썬강의소개
- 불어문법
- 복합과거
- 프랑스어문법
- 큐러닝
- 안젤라유강의
- 아야진
- 파이썬안젤라유
- higher lower game
- 숫자업다운게임
- 유데미파이썬강의
- 파이썬for문
- 반과거
- 파이썬 초급강의
- 파이썬안젤라유강의
- 선형대수
- 안젤라유파이썬
- qlearning
- 파이썬thonny
- 파이썬 게임 만들기
- higherlower게임
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |