개발자로 가는길 :: '코딩독학' 태그의 글 목록
728x90
반응형

코딩독학에 해당하는 글
728x90
반응형
7

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주차 -4

728x90
반응형

본 자율학습 내용은 네이버카페 코딩 자율학습단 에도 동일 내용이 업로드됨을 알려드립니다

 

 

9.4 pass부터 학습

 

pass - 아무것도 하지않고 일단 그냥 넘어감

 

당장 함수를 완성하지 않아도 pass로 동작이 진행될수 있게 사용할 수 있다.

if while 문 등에도 사용가능

def game_start():
    print("[알림] 새로운 게임을 시작합니다.")

def game_over():
    pass #아무런 동작을 하지 않지만 코드는 정상적으로 실행이 됨
 

부모 클래스 호출 super()

다중상속 클래스를 super(). 로 호출시 가장 먼저 상속받은 클래스에 접근하게됨

다중상속 클래스는 각 부모 클래스의 이름을 명시해서 접근

class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        Unit.__init__(self, name, hp, 0) #이부분을 super().__init__(name,hp,0) 으로 변경 가능 / self 없이 사용
        self.location = location
   
 

게임완성

 

from random import randint
class Unit: #일반유닛
    def __init__(self, name, hp, speed):
        self.name = name #인스턴수 변수 name
        self.hp = hp    #인스턴수 변수 hp
        self.speed = speed #지상 이동속도
        print("{0} 유닛을 생성했습니다.".format(name))

    def move(self, location):
        # print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. 속도[{2}]".format(self.name, location, self.speed))
    
    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 AttackUnit(Unit) : #공격유닛
    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))
    
        
#보병 유닛
class Soldier(AttackUnit):
    def __init__(self):
        AttackUnit.__init__(self, "보병", 40, 5, 1)
        
    #강화제 (일정시간 동안 이동,공격 속도 증가 , 체력1 감소)
    def booster(self):
        if self.hp > 10:
            self.hp -= 10
            print("{0} : 강화제를 사용합니다 (HP 10감소)".format(self.name))

        else:
            print("{0} : 체력이 부족해 기술을 사용할 수 없습니다.".format(self.name))
            
#탱크 유닛
class Tank(AttackUnit):
    siege_developed = False

    def __init__(self):
        AttackUnit.__init__(self, "탱크", 150, 35, 1)
        self.set_siege_mode = False
        
    def set_sige_mode(self):
        
        if Tank.siege_developed == False:
            return
        
        if self.set_siege_mode == False:
            print("{0} : 시지 모드로 전환합니다.".format(self.name))
            self.damage*=2
            self.set_siege_mode = True
            
        else:
            print("{0} : 시지 모드를 해제합니다.".format(self.name))
            self.damage //=2
            self.siege_mode = False
            
        
#비행 속도
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):
        self.fly(self.name, location)

        
#전투기 유닛
class Stealth(FlyableAttackUnit):
    def __init__(self):
        FlyableAttackUnit.__init__(self, "전투기", 180,20,5)
        self.cloaked = False
    def cloaking(self):
        if self.cloaked == True:
            print("{0} : 은폐모드를 해제합니다.".format(self.name))
            self.cloaked = False
        else:
            print("{0} : 은폐모드를 설정합니다.".format(self.name))
            self.cloaked = True
        
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        Unit.__init__(self, name, hp, 0)
        self.location = location
    
def game_start():
    print("[알림] 새로운 게임을 시작합니다.")
def game_over():
    print("Player : G.G")
    print("[Player] 님이 게임에서 퇴장했습니다 .")


#게임 실행하기
#1.게임시작
game_start()
#2.유닛 생성(보병3기,탱크 2기, 전투기 1기)
so1 = Soldier()
so2 = Soldier()
so3 = Soldier()
ta1 = Tank()
ta2 = Tank()
st1 = Stealth()
#전군 1시방향으로 이동
#유닛 일괄관리(생성된 모든 유닛 추가)
attack_unit = []
attack_unit.append(so1)
attack_unit.append(so2)
attack_unit.append(so3)
attack_unit.append(ta1)
attack_unit.append(ta2)
attack_unit.append(st1)
#탱크 시지모드 개발
Tank.siege_developed=True

#공격준비
for unit in attack_unit:
    if isinstance(unit, Soldier):
        unit.booster()
    elif isinstance(unit, Tank):
        unit.set_sige_mode()
    elif isinstance(unit, Stealth):
        unit.cloaking()
        
#전군 1시방향 공격 
for unit in attack_unit:
    unit.move("1시")
    
#전군 피해
for unit in attack_unit:
    unit.damaged(randint(5,20))

#게임종료
game_over()
    
 

실행해보며 약간 멘붕이 왔습니다 ㅋ

자꾸 여기저기서 오류가... 오탈자 , 빼먹은코드 등등 이게 은근히 찾기도 쉽지 않네요.

코드가 길어지니 클래스를 분리해서 관리하는게 좋겠다고 느꼈습니다.

실습문제까지 가려했지만 시간이 너무 길어져서 실습문제는 다음에!

모두 고생하셨습니다.

 

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 인강 Day10 / Day 100

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

계산기

 

#Day 10 Calculator 

from replit import clear
from art import logo

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}

def calculator():
  print(logo)

  num1 = float(input("What's the first number?: "))
  for symbol in operations:
    print(symbol)
  should_continue = True
 
  while should_continue:
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear()
      calculator()

calculator()
728x90
반응형

댓글()

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

728x90
반응형

 

어제 4.6 실습문제 하나 남겨놓고 잠들었네요.

일단 만들긴 했고 결과값은 나오는데 제대로 만든건진 모르겠어요

아직 솔루션은 보지 못했습니다 ㅠ

본 자율학습 내용은 네이버카페 코딩 자율학습단에도 동일한 내용이 업로드 됨을 알려드립니다.

 

5장 자료구조

-리스트 : 리스트명=[값1,값2,값3...... ] 인덱스 위치니 0부터 시작

 

특정 요소 인덱스 위치 출력 : print(리스트명.index() )

인덱스 위치로 특정요소 출력 : print(리스트명[인덱스] )

 

리스트 추가 : append(추가할 값) -> 리스트의 가장 마지막에 추가

insert(인덱스,삽입할 값) -> 익덱스 위치에 값을 넣음

 

리스트 삭제 : 리스트명.pop() -> 리스트 가장 마지막부터 삭제

리스트명.clear() -> 리스트 전체를 삭제

 

리스트 정렬하기 : sort() , sorted() - > 기본적으로 오름차순 , 내림차순은 sort(reverse=True) 로 표현

다시 뒤집으려면 sort(reverse)

sort() 같은 리스트 내의 값을 변경 < > sorted() 정렬된 새로운 리스트를 만듦

 

리스트에는 각종 자료형을 섞어서 넣을수 있다.

 

리스트 합치기: 리스트1.extend(리스트2) < 리스트1 뒤에 리스트2를 확장

 

- 딕셔너리 : key와 value 가 한쌍 / 딕셔너리명 = {key: value , key2:value2.......}

key는 문자열로도 사용 가능하다.

 

print(딕셔너리명[key]) -> value 값 출력 / print(딕셔너리명.get(key) ) -> value 값 출력

대괄호 출력문은 잘못된 key 가 들어가면 오류->종료 / get() 사용시 잘못된 키값 들어가면 다시 시도가능

get(key, default=None) 값이 없으면 None 으로 나옴 ( 사용자 문자열로 변경 가능 )

 

print(key in 딕셔너리명) -> 해당 키에 value 가 있는지 검사 ( True or False)

print(딕셔너리명.keys() ) -> value 가 있는 key를 출력해줌

 

값 추가 및 변경: 딕셔너리명[key] = value (key에 값이 없으면 추가 , 값이 있으면 변경)

 

- 튜플 : 리스트와 유사하지만 값의 수정 , 추가 , 삭제드이 불가능 , 순서 못바꿈 / 리스트보다 속도가 빠름

튜플명 = ( 값1 , 값2 .... ) 으로 표현

똑같이 인덱스로 값을 확인 할 수 있다.

 

- 세트 : 집합을 표시 / 세트명 = {값1 , 값2 ......} // set()으로도 정의 가능 set( [값1,값2........] )

값에 중복값을 허용하지 않음 (중복값 있을시 한개만 저장)

 

add() 함수로 값 추가 가능 -> 세트명. add(값)

remove() 함수로 값 제거 가능 -> 세트명.remove(값)

 

집합이므로

세트명1 & 세트명2 <두개 세트의 교집합 ( 세트명1. intersection(세트명2) 로 표현가능 )

세트명1 | 세트명2 <두개 세트의 합집합 ( 세트명1.union(세트명2) 로 표현 가능 )

세트명1 - 세트명2 <두개 세트의 차집합 (세트명1.difference(세트명2) 로 표현 가능 )

 

세트는 출력 순서를 보장하지 않는다.

 

자료구조들 간 type 변환이 가능하다.

- 예) 세트명 = list(세트명) - 세트를 리스트로 변환 ,

튜플명 = set(튜플명) - 튜플을 세트로 변환

리스트명 = set(리스트명) -리스트를 세트로 변환

 

5.6 실습문제

 

당첨자에서 치킨을 제외시킬 방법을 한참 고민해서 풀었는데

솔루션은 4명을 뽑고 인덱스 0부터 차례대로 순서 매기는거 였네요 ㅠ

 

 

 
#5.6 실습문제 : 당첨자 뽑기
#당첨자 총 4명 / 1명은 치킨 쿠폰 , 3명은 커피쿠폰
from random import *

#1. 아이디 1~20
user = range(1,21)
#리스트로 변환
user = list(user)

print(f"{user}\n 무작위로 섞습니다") # 유저 1~20 확인 성공

#2. 무작위로 추첨하되 중복은 허용하지 않는다.

#3. random module 의 shuffle() , sample() 활용

shuffle(user)
print(f"{user}\n섞었습니다.")
chicken = sample(user,1)

print(f"-- 당첨자 발표 -- \n치킨 당첨자 : {chicken}")
chicken = set(chicken)
user = set(user)
# 두리스트를 세트로 변환해 User 에서 Chicken 제외
user = list(user-chicken)

coffee = sample(user,3)
print(f"커피 당첨자 : {coffee} \n-- 축하합니다! --")
728x90
반응형

댓글()