프로그래밍/Python

Python 부트 캠프 - 경매 게임 만들기

Nowon9159 2023. 4. 26. 22:45
반응형

Python (https://towardsdatascience.com/the-zen-of-python-a-guide-to-pythons-design-principles-93f3f76d088a)

경메 게임을 만드는 로직을 구현해 보았다.

로직에 대한 설명은 이렇다

  1. 이름을 입력한다.
  2. 입찰가를 입력한다.
  3. 다른 입찰자가 있는지 물어본다
    1. 다른 입찰자가 있다면 다시 1번으로 돌아간다
    2. 다른 입찰자가 없다면 현재까지 입찰된 가격 중 가장 높은 가격과 그에 해당하는 입찰자의 이름을 print한다

이렇게 되어 있는 로직이다

처음 생각 했을 때 input을 입력하고 다른 입찰자가 없는 상황에서 모든 입찰자들을 한 딕셔너리에 넣고 ->
key value 형태에서 value 값만 추출 ->
value 값을 리스트안에 넣고 정렬 해 최고 입찰가 뽑아내기 ->
최고 입찰가를 기준으로 모든 입찰자를 넣은 딕셔너리에서 검색

굉장히 어렵게 생각했다

일단 1번 부터 3번까지의 로직을 순차적으로 구성 해 보았다.

 

 

# 1. 로고 출력 / 이름 입력, 입찰가 입력
# 2. 다른 입찰인 있는지 yes or no
#     2.1 if yes 라면 스크린 초기화 하고 이름과 입찰가 입력
#     2.2 if no 라면 누가 가장 높은 입찰가를 입력 했는 지 확인하고 낙찰인과 낙찰가 출력

import os
from art import logo

# os.system("cls") # 화면 초기화

print(logo)
print("Welcome to the secret auction program.")
user_name = input("What is your name? \n")
user_bid = input("What's your bid? \n")
have_others = input("Are there any other bidders? Type 'yes' or 'no'. \n")

dict_price = {
    user_name : user_bid 
}

while have_others == "yes" :
    user_name = input("What is your name? \n")
    user_bid = input("What's your bid? \n")
    have_others = input("Are there any other bidders? Type 'yes' or 'no'. \n")

    dict_price[user_name] = user_bid

    if have_others == "no" :
        print(f"456")
        break

여기 까지는 막힘 없이 진행 되었다.

 

import os
from art import logo

os.system("cls") # 화면 초기화

print(logo)
print("Welcome to the secret auction program.")
user_name = ""
user_bid = ""
have_others = "yes"

dict_price = {}
list_price = []
list_price_ascending = []

def auction(have_others) :
    while have_others == "yes" :
        
        user_name = input("What is your name? \n")
        user_bid = input("What's your bid? \n")
        have_others = input("Are there any other bidders? Type 'yes' or 'no'. \n")

        dict_price[user_name] = user_bid
        
        # os.system("cls") # 화면 초기화
        print(dict_price)

        for i in dict_price :
            list_price[i] = dict_price[i]
        
        list_price_ascending = list_price.sort(reverse=True)
        winner = list_price_ascending.index(list_price[0])
        winner_price = list_price[0]


        if  have_others == "no" :
            print(f"The winner is ${winner} with a bid of ${winner_price}")    
            break

auction(have_others)

그리고 no를 선택 했을 때 최고 입찰자와 최고 입찰가를 출력하게 끔 만들었다. -> 근데 로직이 잘 돌아가진 않았다.

# 비밀 경매 프로그램 제작
#
# 보통 경매는 모두가 입찰을 할 수 있고 모두의 입찰가를 볼 수 있습니다
# 그리고 경매인은 여러분들이 더 높은 입찰가를 부르도록
# 유도합니다 그리고 가장 높은 입찰가가 정해져서 경매가 끝날 때까지 다른 사람이 얼마를 입찰했는지
# 모르는 경매인 비밀 경매라는 것이 있습니다 이번엔 그 프로그램을 만들어보도록 하겠습니다

# 1. 로고 출력 / 이름 입력, 입찰가 입력
# 2. 다른 입찰인 있는지 yes or no
#     2.1 if yes 라면 스크린 초기화 하고 이름과 입찰가 입력
#     2.2 if no 라면 누가 가장 높은 입찰가를 입력 했는 지 확인하고 낙찰인과 낙찰가 출력

# 2번은 반복 로직 입찰인 있는지 체크 -> 있다면 반복문으로 이름과 입찰가 입력
# 반복문으로 입력한 이름과 입찰가를 Key Value 형식으로 딕셔너리에 저장
# Value 값만 뽑아내 가장 큰 수를 체크
# 가장 큰 수가 낙찰가가 되며 변수에 저장 후, 낙찰가의 값으로 Key 를 뽑아내 낙찰인을 변수에 저장


import os
from art import logo

def clear() : 
    os.system("cls") # 화면 초기화

print(logo)
print("Welcome to the secret auction program.")

bids = {}
continue_value = False

def pick_highest(bidding_record) :
    highest_bid = 0
    # for문을 이용해서 bidding_record 라는 파라미터를 받아서 해당하는 딕셔너리의 키를 돌려 bid_amount 에 집어 넣는다
    for bidder in bidding_record:
        bid_amount = bidding_record[bidder] # 왜냐하면 딕셔너리의 각 키를 이용해서 bid_amount 를 바꿔주기 때문에 -> 여러 값을 담는 게 아니라 계속 바꿔준다
        # 만약 bid_amount (여기서 bid_amount는 입찰자의 가격) 가 highest_bid 보다 크다면 highest_bid 를 bid_amount 로 교체 
        # 예를 들어 123 을 입찰자가 집어 넣었다면 당연히 0보다 123 이 크기 때문에 123이 highest_bid 가 된다.
        # 그 후로 누군가 123 보다 큰 수를 넣게 되면 highest_bid 가 변경됨
        if bid_amount > highest_bid:
            highest_bid = bid_amount
            # 누군가 현재 최고가 보다 큰 수를 넣게 되면 그 누군가를 winner로 지정함
            winner = bidder
    print(f"{winner} is {highest_bid}")

while not continue_value :
    name = input("What is your name? \n")
    price = int(input("What's your bid? \n$"))
    bids[name] = price # 오브젝트는 objname[key] = value 로 값을 집어넣을 수 있음
    have_others = input("Are there any other bidders? Type 'yes' or 'no'. \n")
    # input 값 받아서 key value 형식으로 dictionary 에 저장
    if have_others == "yes" :
        continue_value = False
        clear()
    elif have_others == "no" :
        continue_value = True
        pick_highest(bids)

결국 답안을 참고해 가면서 작성했는데, 주석을 통해서 최대한 이해하려고 했다.

생각보다 간단하게 로직을 구현할 수 있었는데 위에 기술했던 것 처럼 어렵게 로직을 구현하려고 했다.

개발할 때 중요한 게 최대한 쉽게 만들 수 있으면 쉽게 만드는 것이라고 생각이 든다.

 

생각보다 쉬운 문제 같은 데 자꾸 못푸니 답답하기도 하면서 더 열심히 해야 겠다는 생각이 든다.

 

얻은 것 :
 - 딕셔너리 형태는 dict_name[key] = value 로 값을 집어 넣을 수 있다.
 - for 문을 이용해서 어떠한 값을 비교할 때 굳이 리스트 안에 한데 모아 놓고 비교하지 않아도 된다.

 

반응형