01. 클래스와 객체
용어 | 정의 | 쉬운 예시 |
---|
클래스 (Class) | 객체를 만들기 위한 설계도나 틀. 속성, 행동 정의 | 자동차 설계도 (바퀴, 색상, 달리기 기능 등) |
객체 (Object) | 클래스를 기반으로 실제로 만들어진 것 (실체). | 현실의 자동차 한 대 (설계도로 만들어진 실제 물건) |
속성 (Attribute) | 객체가 가진 데이터(변수). | 자동차의 색상 , 속도 , 브랜드 같은 정보 |
메서드 (Method) | 객체가 수행할 수 있는 행동(함수). | 달리다() , 멈추다() 같은 기능 |
생성자(Constructor) | 객체가 처음 만들어질 때 자동으로 실행되는 메서드. 초기값을 설정함. | 자동차 만들 때 색상이나 모델을 정해주는 역할 |
인스턴스 (Instance) | 클래스로부터 만들어진 객체. 객체 와 거의 같은 말인데, '클래스의 인스턴스'라는 맥락에서 주로 씀. | 자동차 객체는 Car 클래스의 인스턴스 |
02. 클래스 만들기
- 클래스 만들어보기
- 클래스, 객체, 속성, 메서드, 생성자, 인스턴스를 이해하기 위해
스타크래프트 유닛 중 일부를 가지고 클래스를 정의해 봄
- 일단 unit은 hp, mp, 공격력(attach)도 있지만 공격타입(일반, 폭발, 진동)
도 정의할 수 있음
- 마법 유닛의 능력, 마나 소모량에 대해서는 현재 상태에서는 고려안함
- 향후 python에서 활용하게 될 패키지, 모듈 등이 여러 class로 구성된 것임을 이해하는 것이 중요
DAMAGE_MODIFIERS = {
'NORMAL': {'SMALL': 1.0, 'MEDIUM': 1.0, 'LARGE': 1.0},
'CONCUSSIVE': {'SMALL': 1.0, 'MEDIUM': 0.5, 'LARGE': 0.25},
'EXPLOSIVE': {'SMALL': 0.5, 'MEDIUM': 0.75, 'LARGE': 1.0}
}
class Unit:
def __init__(self, name, race, hp, mp, attack, attack_type, defense_type, build_time, mineral_cost, gas_cost):
self.name = name
self.race = race
self.hp = hp
self.mp = mp
self.attack = attack
self.attack_type = attack_type
self.unit_size = unit_size
self.build_time = build_time
self.mineral_cost = mineral_cost
self.gas_cost = gas_cost
def attack_unit(self, target):
if self.attack_type == "NONE" or self.attack == 0:
print(f"{self.name}은(는) 공격할 수 없습니다.")
return
해, 정의 필요
modifier = DAMAGE_MODIFIERS.get(self.attack_type, {}).get(target.unit_size, 1.0)
actual_damage = int(self.attack * modifier)
target.hp -= actual_damage
target.hp = max(target.hp, 0)
print(f"{self.name}이(가) {target.name}에게 {actual_damage}의 데미지를 입혔습니다. (남은 HP: {target.hp})")
def use_ability(self, ability_name, target):
pass
class Upgrade:
def __init__(self, name, race, level, mineral_cost, gas_cost, research_time, effect_desc):
self.name = name
self.race = race
self.level = level
self.mineral_cost = mineral_cost
self.gas_cost = gas_cost
self.research_time = research_time
self.effect_desc = effect_desc
- 추가적인 정의(생산건물)
- 테란(배럭), 프로토스(게이트웨이), 저그(해처리) 등의 생산건물 정의
class ProductionBuilding:
def __init__(self, name, race, mineral_cost, gas_cost, build_time, produces):
self.name = name
self.race = race
self.mineral_cost = mineral_cost
self.gas_cost = gas_cost
self.build_time = build_time
self.produces = produces
self.queue = []
def produce_unit(self, unit_class):
if unit_class in self.produces:
self.queue.append({"unit": unit_class(), "progress": 0})
print(f"{self.name} - {unit_class.__name__} 생산 대기열에 추가됨")
else:
print(f"{unit_class.__name__}는 이 건물에서 생산할 수 없습니다.")
def update(self, delta_time):
if self.queue:
self.queue[0]["progress"] += delta_time
unit_obj = self.queue[0]["unit"]
if self.queue[0]["progress"] >= unit_obj.build_time:
print(f"{self.name} - {unit_obj.name} 생산 완료!")
self.queue.pop(0)
- class 사용 예시(1)
- 마린, 메딕, 질럿, 드라군 유닛 정의
- 기존 유닛(Unit) 클래스 상속 받음
class Marine(Unit):
def __init__(self):
super().__init__("Marine", "Terran", 40, 0, 6, "NORMAL", "SMALL", 15.2, 50, 0)
class Medic(Unit):
def __init__(self):
super().__init__("Medic", "Terran", 60, 200, 0, "NONE", "SMALL", 19.0, 50, 25)
class Zealot(Unit):
def __init__(self):
super().__init__("Zealot", "Protoss", 100, 60, 16, "NORMAL", "SMALL", 25.3, 100, 0)
class Dragoon(Unit):
def __init__(self):
super().__init__("Dragoon", "Protoss", 100, 80, 20, "EXPLOSIVE", "MEDIUM", 31.6, 125, 50)
- class 사용 예시(2)
- 생산 건물
- 테란 지상 유닛 생산건물(배럭), 프로토스 생산 건물(게이트웨이)
- 업그레이드
- 마린은 업그레이드 당 공격력 1씩 증가, 질럿은 2씩 증가
barracks = ProductionBuilding("Barracks", "Terran", 150, 0, 46, produces=[Marine, Medic])
gateway = ProductionBuilding("Gateway", "Protoss", 150, 0, 46, produces=[Zealot, Dragoon])
marine_upgrade_lv1 = Upgrade("Infantry Weapons Lv.1", "Marine", "attack", 1)
zealot_upgrade_lv1 = Upgrade("Ground Weapons Lv.1", "Zealot", "attack", 2)