하나의 틀- 변수와 함수의 집합
마린: 공격 유닛, 군인, 총을 쏠 수 있음
name = "마린" # 유닛의 이름
hp = 40 # 유닛의 체력
damage = 5 # 유닛의 공격력
print("{} 유닛이 생성되었습니다.".format(name))
print("체력: {0}, 공격력: {1}\n".format(hp, damage))
탱크: 공격 유닛, 탱크, 포를 솔 수 있는데 일반모드와 시즈모드(탱크고정)
tank_name = "탱크"
tank_hp = 150
tank_damage = 35
print("{} 유닛이 생성되었습니다.".format(tank_name))
print("체력: {0}, 공격력: {1}\n".format(tank_hp, tank_damage))
tank2_name = "탱크"
tank2_hp = 150
tank2_damage = 35
print("{} 유닛이 생성되었습니다.".format(tank2_name))
print("체력: {0}, 공격력: {1}\n".format(tank2_hp, tank2_damage))
attack 함수 생성
def attack(name, location, damage):
print("{0}: {1} 방향으로 적군을 공격합니다. (공격력: {2})".format(
name, location, damage))
attack(name, "10시", damage)
attack(tank_name, "4시", tank_damage)
attack(tank2_name, "4시", tank2_damage)
class가 없으면 unit이 계속 생길 때 불편함!!
class Unit:
def __init__(self, name, hp, damage): # init함수는 기본적으로 만듦
self.name = name
self.hp = hp
self.damage = damage
print("{0}유닛이 생성 되었습니다.".format(self.name))
print("체력:{0}, 공격력: {1}".format(self.hp, self.damage))
마린과 탱크는 unit 클래스의 인스턴스
marine1 = Unit("마린", 50, 5)
marine2 = Unit("마린", 40, 5)
tank = Unit("탱크", 150, 30)
init : 객체가 만들어질 때 자동으로 호출되는 생성자
레이스 unit: 공중 유닛, 비행기, 클로킹(상대방에게 안보임)
wraith1 = Unit("레이스", 80, 5)
.으로 맴버 변수에 접근 가능
print("유닛이름: {0}, 공격력: {1}".format(wraith1.name, wraith1.damage))
마인드 컨트롤: 상대방 유닛을 내 것으로 만드는 것(뺏는 것)
wraith2 = Unit("빼앗은 레이스", 80, 5)
클로킹 외부에서 객체에 변수 추가 할당 가능 (해당 변수만 가능)
wraith2.clocking = True if wraith2.clocking == True: print("{0} 는 현재 클로킹 상태입니다.".format(wraith2.name))
예제) 일반유닛(부모 클래스)
class Unit: #부모 클래스
def __init__(self, name, hp):
self.name = name
self.hp = hp
class 안에서 매소드 앞에는 self 를 항상 적어줌
상속을 위해 (Unit) 사용
공격유닛(자식클래스)
class AttackUnit(Unit): #자식 클래스
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp) #Unit 상속
self.damage = damage
def attack(self, location):
print("{0}: {1} 방향으로 적군을 공격합니다. [공격력 {2}]"
.format(self.name, location, self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
self.hp -= damage
print("{0}: 현재 체력은 {1}입니다.".format(self.name, self.hp))
if self.hp <= 0:
print("{0}: 파괴되었습니다.".format(self.name))
print)
# 파이어뱃: 공격 유닛, 화염방사기,
firebat1 = AttackUnit("파이어뱃", 50, 16)
# 파이어뱃으로 공격
firebat1.attack("10시")
# 파이어뱃 공격받음
firebat1.damaged(40)
firebat1.damaged(10)
다중상속은 class내에 여러개의 class를 상속받는 것이다.
다중상속의 예를 들기 위해 날 수 있는 기능을 가진 클래스를 만들어보자
날 수 있는 기능을 가진 클래스
class Flyable(Unit):
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)
Flyable.__init__(self, flying_speed)
발키리 변수 추가!!
발키리는 날면서 공격이 가능한 완전 짱인 캐릭터
valkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시") // "발키리: 3시 방향으로 날아갑니다. [속도 5]"
class를 통해서 변수 선언이 간단해지고, 복잡성을 줄여주는 것을 배웠다!!