import random
class Character: #class 만들때에는 괄호 안적음 괄호 적으면 상속 받는 것
def __init__(self, name, hp, attack_p):
'''캐릭터 초기화'''
self.name = name
self.hp = hp
self.attack_p = attack_p
def attack(self, opponent):
'''상대방을 공격'''
damage = random.randint(2,self.attack_p)
opponent.hp -= damage
print(f'{self.name}가 {opponent.name}를 공격하여 {damage}데미지를 입혔습니다.')
def now_status(self):
'''현재 체력 상태 확인'''
return f'{self.name}의 체력: {self.hp}'
def is_alive(self):
'''캐릭터 생존 여부 확인'''
return self.hp > 0 # 부등호를 넣은 것은 참인지 거짓인지를 반환하는 것
# 히어로와 몬스터 생성
player = Character(hp=50,name='영웅',attack_p=15)
monster= Character('고블린', 60, 9)
# 전투진행
print('전투시작')
while player.is_alive() and monster.is_alive():
input('공격하려면 엔터를 치세요')
player.attack(monster)
if monster.is_alive():
monster.attack(player)
print(player.now_status(),' vs ',monster.now_status())
# 결과
if player.is_alive():
print('🎉당신이 승리하였습니다.🎉')
else:
print('😭패배하였습니다...to be continue...')
# 모듈 만들기 - mod1.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
이렇게 코드 작성하고 새 텍스트 파일 하나 생성해서 mod1.py로 이름 바꾸고 mod1.py 파일 안에
def add(a, b):
return a + b
def sub(a, b):
return a - b
이 코드를 복붙함
복붙한 후
처음 작성했던 코드는 주석처리 후 import 시켜서 print하면 출력
import mod1 # .py는 생략해야함
print(mod1.add(11,22))
print(mod1.sub(11,22))
with open('mod2.py','w') as f:
data = '''def mul(a,b):
return a*b
def div(a,b):
return a/b'''
f.write(data)
이렇게 하면 mod2.py 파일이 바로 생성됨
import mod1, mod2
print(mod1.add(11,22))
print(mod1.sub(11,22))
print(mod2.mul(3,4))
print(mod2.div(3,4))
import mod1 as m1
import mod2 as m2
print(m1.add(11,22))
print(m1.sub(11,22))
print(m2.mul(3,4))
print(m2.div(3,4))
import mod1 as m1, mod2 as m2
print(m1.add(11,22))
print(m1.sub(11,22))
print(m2.mul(3,4))
print(m2.div(3,4))
from mod1 import add, sub
print(add(33,44))