1. 스타크래프트로 보는 OOP
1# 보병: 공격 유닛, 군인, 총을 쏠 수 있음2name = "보병" # 이름3hp = 40 # 체력4damage = 5 # 공격력56print("{} 유닛을 생성했습니다.".format(name))7print("체력 {0}, 공격력 {1}\n".format(hp, damage))89# 탱크: 공격 유닛, 포를 쏠 수 있음, 두 가지 모드(일반/시지 모드)10tank_name = "탱크"11tank_hp = 15012tank_damage = 351314print("{} 유닛을 생성했습니다.".format(tank_name))15print("체력 {0}, 공격력 {1}\n".format(tank_hp, tank_damage))1617# 새로 탱크2 추가18tank2_name = "탱크"19tank2_hp = 15020tank2_damage = 352122print("{} 유닛을 생성했습니다.".format(tank2_name))23print("체력 {0}, 공격력 {1}\n".format(tank2_hp, tank2_damage))242526# 공격 함수27def attack(name, location, damage):28print("{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(name, location, damage))293031attack(name, "1시", damage) # 보병 공격 명령32attack(tank_name, "1시", tank_damage) # 탱크 공격 명령33attack(tank2_name, "1시", tank2_damage) # 탱크2 공격 명령
2. 클래스와 객체 생성
2.1 생성자 - init
1class Unit:2# __init__ 생성자 : 한 객체(보병, 탱크 1개)가 만들어질 떄 자동으로 호출되는 함수3# self는 자기자신을 의미, python의 클래스 안에서 메소드들은 모두 self를 작성함4def __init__(self, name, hp, damage):5self.name = name # 인스턴스 변수 name에 전달값 name 저장6self.hp = hp # 인스턴스 변수 hp에 전달값 hp 저장7self.damage = damage # 인스턴스 변수 damage에 전달값 damage 저장8print("{0} 유닛을 생성했습니다.".format(self.name))9print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))101112soldier1 = Unit("보병", 40, 5) # 보병1 생성, 전달값으로 이름/체력/공격력 전달13soldier2 = Unit("보병", 40, 5) # 보병2 생성, 전달값으로 이름/체력/공격력 전달14tank = Unit("탱크", 150, 35) # 탱크 생성, 전달값으로 이름/체력/공격력 전달
2.2
1class Unit:2def __init__(self, name, hp, damage): # 생성자, self 외 전달값 3개3self.name = name4self.hp = hp5self.damage = damage6print("{0} 유닛을 생성했습니다.".format(self.name))7print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))8910soldier1 = Unit("보병", 40, 5) # 객체 생성11soldier2 = Unit("보병", 40, 5) # 객체 생성12tank = Unit("탱크", 150, 35) # 객체 생성13# soldier3 = Unit("보병") # 전달값 3개 중 1개만 넘김, TypeError 발생14# soldier3 = Unit("보병", 40) # 전달값 3개 중 2개만 넘김, TypeError 발생
2.3 멤버(인스턴스) 변수
1class Unit:2def __init__(self, name, hp, damage): # 생성자, 전달값 3개3self.name = name # 인스턴스 변수 name4self.hp = hp # 인스턴스 변수 hp5self.damage = damage # 인스턴스 변수 damage6print("{0} 유닛을 생성했습니다.".format(self.name))7print("체력 {0}, 공격력 {1}".format(self.hp, self.damage))8910# 전투기: 공중 유닛, 은폐 불가11stealth1 = Unit("전투기", 80, 5) # 객체 생성, 체력 80, 공격력 512print("유닛 이름 : {0}, 공격력 : {1}".format(stealth1.name, stealth1.damage)) # 인스턴스 변수 접근1314# 은폐 가능15stealth2 = Unit("업그레이드한 전투기", 80, 5)16stealth2.cloaking = True # 업그레이드한 전투기만을 위한 특별한 인스턴스 변수 정의, 은폐 상태1718if stealth2.cloaking == True: # 은폐 상태라면19print("{0}는 현재 은폐 상태입니다.".format(stealth2.name))2021# 오류 발생22# if stealth1.cloaking == True: # 다른 전투기의 은폐 여부23# print("{0}는 현재 은폐 상태입니다.".format(stealth1.name))
2.4
1class AttackUnit: # 공격 유닛2# self는 자기자신을 의미, python의 클래스 안에서 메소드들은 모두 self를 작성함3def __init__(self, name, hp, damage):4self.name = name5self.hp = hp6self.damage = damage78def attack(self, location): # 전달받은 방향으로 공격9print(10"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)11) # 공간이 좁아서 2줄로 나눔1213def damaged(self, damage): # damage만큼 유닛 피해14# 피해 정보 출력15print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))16self.hp -= damage # 유닛의 체력에서 전달받은 damage만큼 감소17# 남은 체력 출력18print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))19if self.hp <= 0: # 남은 체력이 0 이하이면20print("{0} : 파괴됐습니다.".format(self.name)) # 유닛 파괴 처리212223# 화염방사병: 공격 유닛, 화염방사기를 사용함24flamethrower1 = AttackUnit("화염방사병", 50, 16) # 객체 생성, 체력 50, 공격력 1625flamethrower1.attack("5시") # 5시 방향으로 공격 명령2627# 25만큼의 공격을 2번 받음28flamethrower1.damaged(25) # 남은 체력 2529flamethrower1.damaged(25) # 남은 체력 0
3. 클래스 상속
3.1
1class Unit:2def __init__(self, name, hp):3self.name = name4self.hp = hp567class AttackUnit(Unit): # Unit 클래스 상속8def __init__(self, name, hp, damage):9Unit.__init__(self, name, hp) # 부모 클래스의 생성자 호출10self.damage = damage1112def attack(self, location): # 전달받은 방향으로 공격13print(14"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)15) # 공간이 좁아서 2줄로 나눔1617def damaged(self, damage): # damage만큼 유닛 피해18# 피해 정보 출력19print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))20self.hp -= damage # 유닛의 체력에서 전달받은 damage만큼 감소21# 남은 체력 출력22print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))23if self.hp <= 0: # 남은 체력이 0 이하이면24print("{0} : 파괴됐습니다.".format(self.name)) # 유닛 파괴 처리252627flamethrower1 = AttackUnit("화염방사병", 50, 16)28flamethrower1.attack("5시") # 5시 방향으로 공격 명령2930# 25만큼의 공격을 2번 받음31flamethrower1.damaged(25) # 남은 체력 2532flamethrower1.damaged(25) # 남은 체력 0
3.2 다중 상속
1class Unit:2def __init__(self, name, hp):3self.name = name4self.hp = hp567class AttackUnit(Unit): # Unit 클래스 상속8def __init__(self, name, hp, damage):9Unit.__init__(self, name, hp) # 부모 클래스의 생성자 호출10self.damage = damage1112def attack(self, location): # 전달받은 방향으로 공격13print(14"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)15) # 공간이 좁아서 2줄로 나눔1617def damaged(self, damage): # damage만큼 유닛 피해18# 피해 정보 출력19print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))20self.hp -= damage # 유닛의 체력에서 전달받은 damage만큼 감소21# 남은 체력 출력22print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))23if self.hp <= 0: # 남은 체력이 0 이하이면24print("{0} : 파괴됐습니다.".format(self.name)) # 유닛 파괴 처리252627# 비행 기능28class Flyable:29def __init__(self, flying_speed): # 비행 속도30self.flying_speed = flying_speed3132def fly(self, name, location): # 유닛 이름, 비행 방향33print(34"{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed)35)363738# 공중 공격 유닛39class FlyableAttackUnit(AttackUnit, Flyable):40def __init__(self, name, hp, damage, flying_speed): # 유닛 이름, 체력, 공격력, 비행 속도41AttackUnit.__init__(self, name, hp, damage) # 유닛 이름, 체력, 공격력42Flyable.__init__(self, flying_speed) # 비행 속도434445# 요격기: 공중 공격 유닛, 미사일 여러 발을 한 번에 발사46interceptor = FlyableAttackUnit("요격기", 200, 6, 5) # 유닛 이름, 체력, 공격력, 비행 속도47interceptor.fly(interceptor.name, "3시") # 3시 방향으로 이동
3.3 메소드 오버라이딩
1# 일반 유닛2class Unit:3def __init__(self, name, hp, speed): # speed 추가4self.name = name5self.hp = hp6self.speed = speed # 지상 이동 속도78def move(self, location): # 이동 동작 정의9print("[지상 유닛 이동]")10print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))111213# 공격 유닛14class AttackUnit(Unit): # Unit 클래스 상속15def __init__(self, name, hp, damage, speed): # speed 추가16Unit.__init__(self, name, hp, speed) # speed 추가17self.damage = damage1819def attack(self, location): # 전달받은 방향으로 공격20print(21"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)22) # 공간이 좁아서 2줄로 나눔2324def damaged(self, damage): # damage만큼 유닛 피해25# 피해 정보 출력26print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))27self.hp -= damage # 유닛의 체력에서 전달받은 damage만큼 감소28# 남은 체력 출력29print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))30if self.hp <= 0: # 남은 체력이 0 이하이면31print("{0} : 파괴됐습니다.".format(self.name)) # 유닛 파괴 처리323334# 비행 기능35class Flyable:36def __init__(self, flying_speed): # 비행 속도37self.flying_speed = flying_speed3839def fly(self, name, location): # 유닛 이름, 비행 방향40print(41"{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed)42)434445# 공중 공격 유닛46class FlyableAttackUnit(AttackUnit, Flyable):47def __init__(self, name, hp, damage, flying_speed):48AttackUnit.__init__(self, name, hp, damage, 0) # 지상 이동 속도 049Flyable.__init__(self, flying_speed) # 비행 속도5051def move(self, location): # ⭐️ Unit 클래스의 move() 메서드를 오버라이딩 📌52print("[공중 유닛 이동]")53self.fly(self.name, location)545556# 호버 바이크: 지상 유닛, 기동성 좋음57hoverbike = AttackUnit("호버 바이크", 80, 20, 10) # 지상 이동 속도 105859# 우주 순양함: 공중 유닛, 체력도 굉장히 좋음, 공격력도 좋음60spacecruiser = FlyableAttackUnit("우주 순양함", 500, 25, 3) # 비행 속도 36162hoverbike.move("11시")63# spacecruiser.fly(spacecruiser.name, "9시")64spacecruiser.move("9시") # 오버라이딩한 move() 메서드 호출
4. 동작없이 넘어가기 - pass
1class Unit:2def __init__(self, name, hp, speed): # speed 추가3self.name = name4self.hp = hp5self.speed = speed # 지상 이동 속도67def move(self, location): # 이동 동작 정의8print("[지상 유닛 이동]")9print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))101112# 건물 유닛13class BuildingUnit(Unit):14def __init__(self, name, hp, location):15pass # pass : 아무것도 안하고 넘어간다161718# 보급고: 건물 유닛, 1개 건물 유닛 = 8유닛19supply_depot = BuildingUnit("보급고", 500, "7시") # 체력 500, 생성 위치 7시202122def game_start():23print("[알림] 새로운 게임을 시작합니다.")242526def game_over():27pass282930game_start()31game_over()
5. 부모 클래스 - super
1class Unit:2def __init__(self, name, hp, speed): # speed 추가3self.name = name4self.hp = hp5self.speed = speed # 지상 이동 속도67def move(self, location): # 이동 동작 정의8print("[지상 유닛 이동]")9print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))101112# 건물 유닛13class BuildingUnit(Unit):14def __init__(self, name, hp, location):15# Unit.__init__(self, name, hp, 0) # 지상 이동 속도 0, 건물은 지상 이동 불가16super().__init__(name, hp, 0) # 부모 클래스 접근, self 없이 사용17self.location = location
6. 게임완성
1# 9.6.12# 일반 유닛3class Unit:4def __init__(self, name, hp, speed):5self.name = name6self.hp = hp7self.speed = speed8print("{0} 유닛을 생성했습니다.".format(name)) # 안내 문구 출력910def move(self, location):11# print("[지상 유닛 이동]") # 출력문 삭제12print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))1314def damaged(self, damage): # AttackUnit 클래스에서 Unit 클래스로 이동15print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))16self.hp -= damage17print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))18if self.hp <= 0:19print("{0} : 파괴됐습니다.".format(self.name))202122# 공격 유닛23class AttackUnit(Unit):24def __init__(self, name, hp, damage, speed):25Unit.__init__(self, name, hp, speed)26self.damage = damage2728def attack(self, location):29print(30"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)31)3233"""34def damaged(self, damage): # Unit 클래스로 이동35print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))36self.hp -= damage37print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))38if self.hp <= 0:39print("{0} : 파괴됐습니다.".format(self.name))40"""414243# 보병 유닛44class Soldier(AttackUnit): # AttackUnit 클래스 상속45def __init__(self):46AttackUnit.__init__(self, "보병", 40, 5, 1) # 이름, 체력, 공격력, 이동 속도4748# 강화제 : 일정 시간 동안 이동 속도와 공격 속도 증가, 체력 10 감소49def booster(self): # 강화제 기능 메서드로 정의50if self.hp > 10:51self.hp -= 10 # 체력 10 소모52print("{0} : 강화제를 사용합니다. (HP 10 감소)".format(self.name))53else:54print("{0} : 체력이 부족해 기술을 사용할 수 없습니다".format(self.name))555657# 탱크 유닛58class Tank(AttackUnit): # AttackUnit 클래스 상속59# 시즈 모드 : 탱크를 지상에 고정, 이동 불가, 공격력 증가60siege_developed = False # 시지 모드 개발 여부, 클래스 변수로 정의6162def __init__(self):63AttackUnit.__init__(self, "탱크", 150, 35, 1) # 이름, 체력, 공격력, 이동 속도64self.siege_mode = False # 시지 모드(해제 상태), 인스턴스 변수로 정의6566# 시즈 모드 설정67def set_siege_mode(self):68if Tank.siege_developed == False: # 시지 모드가 개발되지 않았으면 바로 반환69return70# 현재 일반 모드일 때71if self.siege_mode == False: # 시지 모드 여부 확인72print("{0} : 시지 모드로 전환합니다.".format(self.name)) # 시지 모드 전환73self.damage *= 2 # 공격력 2배 증가74self.siege_mode = True # 시지 모드 설정75# 현재 시지 모드일 때76else:77print("{0} : 시지 모드를 해제합니다.".format(self.name)) # 일반 모드 전환78self.damage //= 2 # 공격력 절반으로 감소79self.siege_mode = False # 시지 모드 해제808182# 나는 기능83class Flyable:84def __init__(self, flying_speed):85self.flying_speed = flying_speed8687def fly(self, name, location):88print(89"{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed)90)919293# 공중 공격 유닛94class FlyableAttackUnit(AttackUnit, Flyable):95def __init__(self, name, hp, damage, flying_speed):96AttackUnit.__init__(self, name, hp, damage, 0)97Flyable.__init__(self, flying_speed)9899def move(self, location):100# print("[공중 유닛 이동]") # 출력문 삭제101self.fly(self.name, location)102103104# 전투기 유닛105class Stealth(FlyableAttackUnit): # FlyableAttackUnit 클래스 상속106def __init__(self):107FlyableAttackUnit.__init__(self, "전투기", 80, 20, 5) # 부모 클래스 생성자로 기본 정보 설정108self.cloaked = False # 은폐 모드(해제 상태), 인스턴스 변수 정의109110def cloaking(self): # 은폐 모드를 메서드로 정의111# 현재 은폐 모드일 때112if self.cloaked == True:113print("{0} : 은폐 모드를 해제합니다.".format(self.name))114self.cloaked = False # 은폐 모드 해제115# 현재 은폐 모드가 아닐 때116else:117print("{0} : 은폐 모드를 설정합니다.".format(self.name))118self.cloaked = True # 은폐 모드 설정119120121# 9.6.2122# 게임 시작123def game_start():124print("[알림] 새로운 게임을 시작합니다.")125126127# 게임 종료128def game_over():129print("Player : Good Game")130print("[Player] 님이 게임에서 퇴장했습니다.")131132133# 게임 시작134game_start()135136# 보병 3기 생성137so1 = Soldier()138so2 = Soldier()139so3 = Soldier()140141# 탱크 2기 생성142ta1 = Tank()143ta2 = Tank()144145# 전투기 1기 생성146st1 = Stealth()147148# 유닛 일괄 관리(생성된 모든 유닛 추가)149attack_units = []150attack_units.append(so1)151attack_units.append(so2)152attack_units.append(so3)153attack_units.append(ta1)154attack_units.append(ta2)155attack_units.append(st1)156157# 전군 이동158for unit in attack_units:159unit.move("1시")160161# 탱크 시지 모드 개발162Tank.siege_developed = True163print("[알림] 탱크의 시지 모드 개발이 완료됐습니다.")164165# 공격 모드 준비(보병: 강화제, 탱크: 시지 모드, 전투기: 은폐 모드)166for unit in attack_units:167if isinstance(unit, Soldier): # Soldier 클래스의 인스턴스이면 강화제168unit.booster()169elif isinstance(unit, Tank): # Tank 클래스의 인스턴스이면 시지 모드170unit.set_siege_mode()171elif isinstance(unit, Stealth): # Stealth 클래스의 인스턴스이면 은폐 모드172unit.cloaking()173174# 전군 공격175for unit in attack_units:176unit.attack("1시")177178from random import *179180# 전군 피해181for unit in attack_units:182unit.damaged(randint(5, 20)) # 피해는 무작위로 받음(5~20)183184# 게임 종료185game_over()
6.1 게임 완성 리뷰
1from random import *234# 일반 유닛5class Unit:6def __init__(self, name, hp, speed):7self.name = name8self.hp = hp9self.speed = speed10print("{0} 유닛을 생성했습니다.".format(name))1112def move(self, location):13print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))1415def damaged(self, damage):16print("{0} : {1}만큼 피해를 입었습니다.".format(self.name, damage))17self.hp -= damage18print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))19if self.hp <= 0:20print("{0} : 파괴됐습니다.".format(self.name))212223# 공격 유닛24class AttackUnit(Unit):25def __init__(self, name, hp, damage, speed):26Unit.__init__(self, name, hp, speed)27self.damage = damage2829def attack(self, location):30print(31"{0} : {1} 방향 적군을 공격합니다. [공격력 {2}]".format(self.name, location, self.damage)32)333435# 보병 유닛36class Soldier(AttackUnit):37def __init__(self):38AttackUnit.__init__(self, "보병", 40, 5, 1) # 이름, 체력, 공격력, 이동 속도3940# 강화제: 일정 시간 동안 이동 속도와 공격 속도 증가, 체력 10 감소41def booster(self):42if self.hp > 10:43self.hp -= 10 # 체력 10 소모44print("{0} : 강화제를 사용합니다. (HP 10 감소)".format(self.name))45else:46print("{0} : 체력이 부족해 기술을 사용할 수 없습니다".format(self.name))474849# 탱크 유닛50class Tank(AttackUnit):51# 시지 모드 : 탱크를 지상에 고정, 이동 불가, 공격력 증가52siege_developed = False # 시지 모드 개발 여부5354def __init__(self):55AttackUnit.__init__(self, "탱크", 150, 35, 1) # 이름, 체력, 공격력, 이동 속도56self.siege_mode = False # 시지 모드(해제 상태)5758# 시지 모드 설정59def set_siege_mode(self):60if Tank.siege_developed == False: # 시지 모드가 개발되지 않았으면 바로 반환61return62# 현재 일반 모드일 때63if self.siege_mode == False:64print("{0} : 시지 모드로 전환합니다.".format(self.name))65self.damage *= 2 # 공격력 2배 증가66self.siege_mode = True # 시지 모드 설정67# 현재 시지 모드일 때68else:69print("{0} : 시지 모드를 해제합니다.".format(self.name))70self.damage //= 2 # 공격력 절반으로 감소71self.siege_mode = False # 시지 모드 해제727374# 비행 기능75class Flyable:76def __init__(self, flying_speed):77self.flying_speed = flying_speed7879def fly(self, name, location):80print(81"{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed)82)838485# 공중 공격 유닛86class FlyableAttackUnit(AttackUnit, Flyable):87def __init__(self, name, hp, damage, flying_speed):88AttackUnit.__init__(self, name, hp, damage, 0)89Flyable.__init__(self, flying_speed)9091def move(self, location):92self.fly(self.name, location)939495# 전투기 유닛96class Stealth(FlyableAttackUnit):97def __init__(self):98FlyableAttackUnit.__init__(self, "전투기", 80, 20, 5)99self.cloaked = False # 은폐 모드(해제 상태)100101# 은폐 모드102def cloaking(self):103# 현재 은폐 모드일 때104if self.cloaked == True:105print("{0} : 은폐 모드를 해제합니다.".format(self.name))106self.cloaked = False107# 현재 은폐 모드가 아닐 때108else:109print("{0} : 은폐 모드를 설정합니다.".format(self.name))110self.cloaked = True111112113# 게임 시작114def game_start():115print("[알림] 새로운 게임을 시작합니다.")116117118# 게임 종료119def game_over():120print("Player : Good Game")121print("[Player] 님이 게임에서 퇴장했습니다.")122123124# 실제 게임 진행125game_start() # 게임 시작126127# 보병 3기 생성128so1 = Soldier()129so2 = Soldier()130so3 = Soldier()131132# 탱크 2기 생성133ta1 = Tank()134ta2 = Tank()135136# 전투기 1기 생성137st1 = Stealth()138139# 유닛 일괄 관리(생성된 모든 유닛 추가)140attack_units = []141attack_units.append(so1)142attack_units.append(so2)143attack_units.append(so3)144attack_units.append(ta1)145attack_units.append(ta2)146attack_units.append(st1)147148# 전군 이동149for unit in attack_units:150unit.move("1시")151152# 탱크 시지 모드 개발153Tank.siege_developed = True154print("[알림] 탱크의 시지 모드 개발이 완료됐습니다.")155156# 공격 모드 준비(보병: 강화제, 탱크: 시지 모드, 전투기: 은폐 모드)157for unit in attack_units:158if isinstance(unit, Soldier): # Soldier 클래스의 인스턴스이면 강화제159unit.booster()160elif isinstance(unit, Tank): # Tank 클래스의 인스턴스이면 시지 모드161unit.set_siege_mode()162elif isinstance(unit, Stealth): # Stealth 클래스의 인스턴스이면 은폐 모드163unit.cloaking()164165# 전군 공격166for unit in attack_units:167unit.attack("1시")168169# 전군 피해170for unit in attack_units:171unit.damaged(randint(5, 20)) # 피해는 무작위로 받음(5~20)172173# 게임 종료174game_over()
7. 퀴즈. 부동산 프로그램
1"""2Quiz) 주어진 코드를 활용하여 부동산 프로그램을 작성하시오.34(출력 예제)5총 3대의 매물이 있습니다.6강남 아파트 매매 10억 2010년7마포 오피스텔 전세 5억 2007년8송파 빌라 월세 500/50 2000년9"""101112class House:13# 매물 초기화 : 위치, 건물 종류, 매물 종류, 가격, 준공연도14def __init__(self, location, house_type, deal_type, price, completion_year):15self.location = location16self.house_type = house_type17self.deal_type = deal_type18self.price = price19self.completion_year = completion_year2021# 매물 정보 표시22def show_detail(self):23print(24self.location,25self.house_type,26self.deal_type,27self.price,28self.completion_year,29)303132houses = []33house1 = House("강남", "아파트", "매매", "10억 원", "2010년")34house2 = House("마포", "오피스텔", "전세", "5억 원", "2007년")35house3 = House("송파", "빌라", "월세", "500/50만 원", "2000년")3637houses.append(house1)38houses.append(house2)39houses.append(house3)4041print("총 {0}가지 매물이 있습니다.".format(len(houses)))42for house in houses:43house.show_detail()