개발자로 가는길 :: '파이썬게임' 태그의 글 목록
반응형

파이썬게임에 해당하는 글
반응형
10

Python 인강 / 객체지향 커피머신 만들기

개발/파이썬|2023. 3. 22. 20:24
728x90
반응형
#메인 코드
from menu import Menu
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine

money_machine = MoneyMachine()
coffee_maker = CoffeeMaker()
menu = Menu()

is_on = True

while is_on:
    options = menu.get_items()
    choice = input(f"What would you like? ({options}): ")
    if choice == "off":
        is_on = False
    elif choice == "report":
        coffee_maker.report()
        money_machine.report()
    else:
        drink = menu.find_drink(choice)
        
        if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost):
          coffee_maker.make_coffee(drink)
#커피 만들기 클래스
class CoffeeMaker:
    """Models the machine that makes the coffee"""
    def __init__(self):
        self.resources = {
            "water": 300,
            "milk": 200,
            "coffee": 100,
        }

    def report(self):
        """Prints a report of all resources."""
        print(f"Water: {self.resources['water']}ml")
        print(f"Milk: {self.resources['milk']}ml")
        print(f"Coffee: {self.resources['coffee']}g")

    def is_resource_sufficient(self, drink):
        """Returns True when order can be made, False if ingredients are insufficient."""
        can_make = True
        for item in drink.ingredients:
            if drink.ingredients[item] > self.resources[item]:
                print(f"Sorry there is not enough {item}.")
                can_make = False
        return can_make

    def make_coffee(self, order):
        """Deducts the required ingredients from the resources."""
        for item in order.ingredients:
            self.resources[item] -= order.ingredients[item]
        print(f"Here is your {order.name} ☕️. Enjoy!")
#메뉴 클래스
class MenuItem:
    """Models each Menu Item."""
    def __init__(self, name, water, milk, coffee, cost):
        self.name = name
        self.cost = cost
        self.ingredients = {
            "water": water,
            "milk": milk,
            "coffee": coffee
        }


class Menu:
    """Models the Menu with drinks."""
    def __init__(self):
        self.menu = [
            MenuItem(name="latte", water=200, milk=150, coffee=24, cost=2.5),
            MenuItem(name="espresso", water=50, milk=0, coffee=18, cost=1.5),
            MenuItem(name="cappuccino", water=250, milk=50, coffee=24, cost=3),
        ]

    def get_items(self):
        """Returns all the names of the available menu items"""
        options = ""
        for item in self.menu:
            options += f"{item.name}/"
        return options

    def find_drink(self, order_name):
        """Searches the menu for a particular drink by name. Returns that item if it exists, otherwise returns None"""
        for item in self.menu:
            if item.name == order_name:
                return item
        print("Sorry that item is not available.")
#돈관리 클래스
class MoneyMachine:

    CURRENCY = "$"

    COIN_VALUES = {
        "quarters": 0.25,
        "dimes": 0.10,
        "nickles": 0.05,
        "pennies": 0.01
    }

    def __init__(self):
        self.profit = 0
        self.money_received = 0

    def report(self):
        """Prints the current profit"""
        print(f"Money: {self.CURRENCY}{self.profit}")

    def process_coins(self):
        """Returns the total calculated from coins inserted."""
        print("Please insert coins.")
        for coin in self.COIN_VALUES:
            self.money_received += int(input(f"How many {coin}?: ")) * self.COIN_VALUES[coin]
        return self.money_received

    def make_payment(self, cost):
        """Returns True when payment is accepted, or False if insufficient."""
        self.process_coins()
        if self.money_received >= cost:
            change = round(self.money_received - cost, 2)
            print(f"Here is {self.CURRENCY}{change} in change.")
            self.profit += cost
            self.money_received = 0
            return True
        else:
            print("Sorry that's not enough money. Money refunded.")
            self.money_received = 0
            return False
728x90
반응형

댓글()

나도코딩 Python 자율학습단 2기 2주차 -3

728x90
반응형

 

요새 일교차가 심해서 그런지 몸살이 와서 나도코딩 교재는 며칠 쉬었습니다.

해당 학습내용은 네이버카페 코딩학습단에 동일 내용 업로드됨을 알려드립니다.

9장 클래스부터..

자바 공부할때도 클래스 , 객체 부터 많이 어려워했었는데.. 파이썬이 그나마 자바 사용 언어보다 쉬워서

파이썬을 이용해 더 개념을 탄탄히 공부하려 합니다.

클래스.클래스명:
    def 메서드명 (self , 전달값1 , 전달값2, ....)
    실행할명령1
    실행할명령2
    ...
 

- 메서드의 첫번째 전달값은 self 가 들어와줘야함

- 메서드 안에서 정의한 변수를 인스턴스 변수라고 함

 

class unit:
    def __init__(self, name, hp, damage): #self , 전달값1 , 전달값2 , 전달값3
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{}유닛을 생성했습니다".format(self.name))
        print("체력 : {0}, 공격력 : {1} \n".format(self.hp,self.damage))
 

교재 유닛 클래스 생성

클래스 사용법 (위 유닛 클래스 사용)

soldier1 = Unit("보병" , 40 , 5)
soldier2 = Unit("보병" , 40 , 5)
soldier3=Unit("탱크",150,35 )
 

실행 결과

- 이렇게 클래스를 이용해 만들어진 유닛들을 객체라고 한다. (클래스의 인스턴스)

- 클래스안에 정의된 __init__ 은 생성자 라고 한다.

클래스를 만들때 __init__ 이라는 이름으로 메서드를 정의하면 자동으로 생성자가 됨

객체를 생성할때 생성자가 자동으로 호출되므로 생성자의 전달값 개수만큼 값을 전달해야함 ( 전달값 개수가 맞지않으면 error)

- 메서드에서 정의한 변수를 인스턴스 변수라고 함

- 인스턴수변수는 객체를 통해 직접 정의할수있다 (객체명.변수명)

 

메서드

- 메서드는 클래스 내보에 정의 한 함수

- 클래스 내부에서 전달값에 접근할땐 self. 으로 접근

 

276p 1분퀴즈 1번문제 보기 1,2 번 같음 오류있습니다

 

클래스 상속

상속 : 하위클래스가 상위클래스를 물려받음

다중 상속도 가능하다.

 

메서드 오버라이딩

부모 클래스의 함수를 자식클래스에서 재정의 하여 사용할수 있음.

class Unit: #일반유닛
    def __init__(self, name, hp, speed):
        self.name = name #인스턴수 변수 name
        self.hp = hp    #인스턴수 변수 hp
        self.speed = speed #지상 이동속도
        
    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. 속도[{2}]".format(self.name, location, self.speed))
                    
class AttackUnit : #공격유닛
    def __init__(self, name,hp, damage, speed):
        Unit.__init__(self,name,hp, speed) #공통적인 부분 -> 부모클래스의 생성자 호출 (상속)
        self.damage = damage
    def attack (self, location):
        print("{0} : {1} 방향 적군을 공격합니다 . [공격력{2}]".format(self.name,location,self.damage))
    def damaged  (self,damaged): #damage 만큼 유닛 피해
        print("{0} : {1} 만큼 피해를 입었습니다.".format(self.name,damaged))
        self.hp = self.hp - damaged #유닛 체력에서 전달받은 damage만큼 감소
        print("{0} : 현재 체력은 {1} 입니다.".format(self.name,self.hp))
        if self.hp <= 0:
            print("{0} :파괴되었습니다.".format(self.name))
#비행 속도
class Flyable : 
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed
    def fly(self,name , location):
        print("{0} : {1}방향으로 날아갑니다 . [속도{2]".format(name,location,self.flying_speed))
#공중 공격유닛
class FlyableAttackUnit(AttackUnit,Flyable): #다중상속
    def __init__(self,name,hp,damage,flying_speed):
        AttackUnit.__init__(self,name,hp,damage,0)
        Flyable.__init__(self,flying_speed)
    def move(self,location):    
        print("[공중유닛 이동]")
        self.fly(self.name,location)
 
 

이번장은 공부해야 할 내용이 많네요 아직 몸이 좋지않아 쉬고 내일 다시 달려보겠습니다

 

728x90
반응형

댓글()

Python 인강 Day 11 / Day 100 - 블랙잭 카드게임

개발/파이썬|2023. 3. 16. 20:10
728x90
반응형
#Day 11 = 블랙잭 게임
from random import randint , sample
while True:
    card = [1,2,3,4,5,6,7,8,9,10,10,10,10,11]

    dealer = sample(card, 2)
    player = sample(card, 2)

    sum_player = int(player[0] + player[1])
    sum_dealer = int(dealer[0] + dealer[1])

    print(f"당신의 카드는 {player[0],player[1]} 입니다.")

    add_one = input("카드를 한장 추가 하시려면 y , 아니면 n 을 눌러주세요 > >")

    if sum_dealer <=16:
        sec_dealer = sample(card, 1)
        dealer.append(sec_dealer[0])
        sum_dealer += int(sec_dealer[0])

    if add_one == "y" or add_one == "Y":
    
        sec_player = sample(card,1)
        sum_player += int(sec_player[0] )
        print(f"카드는 {sec_player[0]} 입니다.")
        
        yprint(f"당신의 총점은 {sum_player}")
        print(f"딜러의 카드는 {dealer}")
        print(f"딜러의 총점은 {sum_dealer}")
        
        if sum_dealer >= 21 and sum_player <= 21:
            print("딜러 버스트 당신의 승리입니다.")
        elif sum_player >= 21:
            print("버스트 입니다 , 패배했습니다")
        elif sum_player > sum_dealer:
            print("당신이 승리했습니다!")
        elif sum_player < sum_dealer:
            print("당신이 패배했습니다!")
        else:
            print("동점입니다.")
                        
            
    if add_one == "n" or add_one == "N":
        print(f"당신의 총점은 {sum_player}")
        print(f"딜러의 카드는 {dealer}")
        print(f"딜러의 총점은 {sum_dealer}")
        
        if sum_dealer >= 21 and sum_player <= 21:
            print("딜러 버스트 당신의 승리입니다.")
        elif sum_player >= 21:
            print("버스트 입니다 , 패배했습니다")
        elif sum_player > sum_dealer:
            print("당신이 승리했습니다!")
        elif sum_player < sum_dealer:
            print("당신이 패배했습니다!")
        else:
            print("동점입니다.")
    
    play_again = input("게임을 다시 시작 하시겠습니까?  y 를 누르면 다시시작  or n 을 누르면 종료 > > ")
    if play_again == "n" or play_again == "N":
        break

어찌어찌 동작은하는데 코드가 상당히 복잡해졌다.

def 문으로 함수를 만들어서 리팩토링이 가능할 것 같다.

728x90
반응형

댓글()

Python 인강 Day 9 / day 100 (비밀 경매 프로젝트)

개발/파이썬|2023. 3. 13. 19:10
728x90
반응형
from replit import clear
from art import logo
print(logo)

bids = {}
bidding_finished = False  

def find_highest_bidder(bidding_record):
  highest_bid = 0
  winner = ""
  # bidding_record = {"Angela": 123, "James": 321}
  for bidder in bidding_record:  
    bid_amount = bidding_record[bidder]
    if bid_amount > highest_bid: 
      highest_bid = bid_amount
      winner = bidder
  print(f"The winner is {winner} with a bid of ${highest_bid}")

while not bidding_finished:  
  name = input("What is your name?: ")
  price = int(input("What is your bid?: $"))
  bids[name] = price
  should_continue = input("Are there any other bidders? Type 'yes or 'no'.\n")
  if should_continue == "no":
    bidding_finished = True
    find_highest_bidder(bids)
  elif should_continue == "yes":
    clear()

얼마전부터 느꼈지만 해외강의다 보니 풀수있는 문제도 자막때문에 문제이해가 쉽지 않아 어려움을 겪는다...ㅠ

영어공부부터 해야하나...

728x90
반응형

댓글()

Python 인강 day 8 / day 100

개발/파이썬|2023. 3. 13. 08:03
728x90
반응형

카이사르 암호화 / 복호화

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def caesar(start_text, shift_amount, cipher_direction):
  end_text = ""
  if cipher_direction == "decode":
    shift_amount *= -1
  for char in start_text:
    #TODO-3: What happens if the user enters a number/symbol/space?
    #Can you fix the code to keep the number/symbol/space when the text is encoded/decoded?
    #e.g. start_text = "meet me at 3"
    #end_text = "•••• •• •• 3"
    if char in alphabet:
      position = alphabet.index(char)
      new_position = position + shift_amount
      end_text += alphabet[new_position]
    else:
      end_text += char
  print(f"Here's the {cipher_direction}d result: {end_text}")

#TODO-1: Import and print the logo from art.py when the program starts.
from art import logo
print(logo)

#TODO-4: Can you figure out a way to ask the user if they want to restart the cipher program?
#e.g. Type 'yes' if you want to go again. Otherwise type 'no'.
#If they type 'yes' then ask them for the direction/text/shift again and call the caesar() function again?
#Hint: Try creating a while loop that continues to execute the program if the user types 'yes'.
should_end = False
while not should_end:

  direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
  text = input("Type your message:\n").lower()
  shift = int(input("Type the shift number:\n"))
  #TODO-2: What if the user enters a shift that is greater than the number of letters in the alphabet?
  #Try running the program and entering a shift number of 45.
  #Add some code so that the program continues to work even if the user enters a shift number greater than 26. 
  #Hint: Think about how you can use the modulus (%).
  shift = shift % 26

  caesar(start_text=text, shift_amount=shift, cipher_direction=direction)

  restart = input("Type 'yes' if you want to go again. Otherwise type 'no'.\n")
  if restart == "no":
    should_end = True
    print("Goodbye")

이게 코딩이 문제가 아니라 강의가 영어인데 연습문제의 번역이 음.. 별로라 문제자체를 이해하고 시작하기 힘들다

어찌어찌 끝까지 하긴 했는데 아침부터 두시간을 진을 뺐다..ㅠ

728x90
반응형

댓글()

3/9 Python 인강 Day 7 / Day 100

개발/파이썬|2023. 3. 9. 21:31
728x90
반응형

오늘은 프로젝트였는데 

내기준에선 좀 어려웠다.

나중에 솔루션 코드를 보고 이해하긴 했는데 처음부터 끝까지 혼자하기엔 좀 근성이 부족했던것 같다.

 

행맨게임 프로젝트

#Day7 Project 
#HANGMAN 게임 만들기

import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

end_of_game = False
word_list = ["ardvark", "baboon", "camel"]  #정답 리스트
chosen_word = random.choice(word_list)      #정답중 한개를 랜덤으로 선택
word_length = len(chosen_word)              #선택된 정답의 문자열길이

#TODO-1: - Create a variable called 'lives' to keep track of the number of lives left. 
#Set 'lives' to equal 6.
lives = 6   #목숨 6개

#Testing code
print(f'Pssst, the solution is {chosen_word}.') #테스트 코드임 정답 보여줌

#Create blanks
display = []        #빈 리스트 생성
for _ in range(word_length):
    display += "_"  #정답의 문자열 길이 만큼 "_" 생성

while not end_of_game:  #게임이 끝나지 않았으면 반복
    guess = input("Guess a letter: ").lower() #문자 묻는 인풋

    #Check guessed letter
    for position in range(word_length): # 정답의 문자열 길이 만큼 반복
        letter = chosen_word[position]  # letter 에 정답 문자열 포지션 저장
       # print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:     # 입력한 문자가 letter 에 있을때
            display[position] = letter  #  디스플레이 포지션에 넣음

    #TODO-2: - If guess is not a letter in the chosen_word,
    #Then reduce 'lives' by 1. 
    #If lives goes down to 0 then the game should stop and it should print "You lose."
    if guess not in chosen_word: #입력한 문자가 정답안에 없을때
        lives -= 1      #목숨 -1
        if lives == 0:  #목숨이 0이 되면
            end_of_game = True #end_of_game 이 true로 바뀜 = while반복문 끝남
            print("You lose.")  # 졌다고 출력

    #Join all the elements in the list and turn it into a String.
    print(f"{' '.join(display)}") 

    #Check if user has got all letters.
    if "_" not in display:  #만약 display 에  _ 가 없으면 (문자가 다 체워지면)
        end_of_game = True  #while문 종료
        print("You win.")   #이겼다고 출력

    #TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining.
    print(stages[lives])

주말에 바다보이는 카페에 앉아서 다시 해봐야겠다

728x90
반응형

댓글()