본문 바로가기

AI/Python

Python #파이썬의 대모험 02

용사 '파이썬'의 시스템 도우미 설계

당신은 이세계로 소환된 용사 '파이썬'의 시스템 도우미이다. 당신의 도움이 없다면 험난한 이세계에서 '파이썬'은 성장도 하지 못하고, 길을 잃고 쓰러지게 될 것이다.


문제 1

 

파이썬의 대모험 1에서 파이썬은 몬스터와 마주치기만 했다.

파이썬은 몬스터와 친구가 아니니 전투를 시켜보자.

 

파이썬은 dmg 와 health를 가진다. 몬스터는 dmg와 health를 가진다.

파이썬의 dmg는 100, health는 1000이다. 몬스터의 dmg와 health는 각 몬스터별로 고블린(50,100), 트롤(80,200), 늑대(40, 80)이다.

파이썬이 몬스터와 만나 전투를 하게 되면 서로 동시에 공격한다. 파이썬과 몬스터는 각각 데미지로 각각의 체력을 깎는다. 1라운드 전투 후 몬스터의 체력이 남아있으면 2라운드 전투가 진행된다. 몬스터의 체력이 0 이하가 되면 전투가 끝난다. 파이썬의 체력수치는 몬스터와 싸우면 입은 데미지 만큼 깎인다.

파이썬이 랜덤하게 몬스터와 조우했을 경우를 버튼을 만들어 설계해보자.


import random #랜덤 함수를 사용하기 위해 모듈 임포트
from tkinter import* #tkinter모듈의 모든 클래스와 함수 포함


python_stat = { 'dmg': 100 , 'health': 1000 }
fighting_log = { 'round': 0 }

#파이썬이 몬스터를 만났을 때
def meetMonster():
    conjunction = ('과', '와')
    monster = ('고블린', '트롤', '늑대')
    mon_name = random.choice(monster)
    mon_stat = {  }
    
    
    if mon_name == '고블린':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 50
        mon_stat['health'] = 100
        
    elif mon_name == '트롤':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 80
        mon_stat['health'] = 200
        
    else:
        conjunction = conjunction[1]
        mon_stat['dmg'] = 40
        mon_stat['health'] = 80
        
    #파이썬 전투 로그
    def pythonFight(): 
        if(mon_stat['health']>=100):
            round = mon_stat['health']//python_stat['dmg'] #몫만 출력, 파이썬이 몬스터와 전투한 횟수(때린 횟수만큼 몬스터에세 맞는다)
        else:
            round = 1 #파이썬이 몬스터와 전투한 횟수
        python_stat['health'] -= mon_stat['dmg']*round #파이썬의 체력 - 몬스터 데미지*몬스터가 때린 횟수
        fighting_log['round'] = round
        
    pythonFight() # 파이썬 전투
    print("'파이썬'이 '%s'%s 조우했습니다." %(mon_name, conjunction) + "전투 끝에 '파이썬'의 체력은 %s 남았습니다." %(python_stat['health']) )
    print("'%s'의 데미지는 %s 이고, 총 %s 라운드의 전투가 일어났습니다." %(mon_name, mon_stat['dmg'], fighting_log['round'] ))


#파이썬을 운명으로 들이미는 버튼

window = Tk() #윈도우 생성
label = Label(window, text = '파이썬의 대모험')#윈도우 레이블 위젯 생성 뒤 텍스트 지정
label.pack() #pack이 호출되어야만 위젯이 화면에 나타난다

b1 = Button(window, text = '진행', command = meetMonster) # command = 함수 실행
b1.pack(padx = 100, pady = 20) # 버튼 상하좌우 여백
window.mainloop() #사용자가 윈도우를 닫을 때 까지 창의 이벤트를 반복한다.

 

 


문제 2

 

 

파이썬과 몬스터의 전투를 문제 1번과 같이 표현해봤다.

전투를 예시와 같이 좀 더 디테일 하게 표현해 보자.

예)

파이썬과 몬스터가 조우했습니다.

파이썬의 데미지: , 파이썬의 현재 체력: 몬스터의 데미지: , 몬스터의 현재 체력:

1라운드 결과 파이썬이 몬스터에게 00 데미지를 입혔습니다. 몬스터가 파이썬에게 00 데미지를 입혔습니다. -> 몬스터의 체력이 0이하가 됐다면 승리!, 파이썬의 체력이 0이하가 됐다면 패배!, 몬스터의 체력이 1이상이고, 파이썬의 체력이 1이상이면 2라운드로

2라운드 결과 파이썬이 몬스터에게 00 데미지를 입혔습니다. 몬스터가 파이썬에게 00 데미지를 입혔습니다. -> 몬스터의 체력이 0이하가 됐다면 승리!, 파이썬의 체력이 0이하가 됐다면 게임 오버!

 


import random #랜덤 함수를 사용하기 위해 모듈 임포트
from tkinter import* #tkinter모듈의 모든 클래스와 함수 포함


python_stat = { 'dmg': 100 , 'health': 500 }
fighting_log = { 'round': 0 }

#파이썬이 몬스터를 만났을 때
def meetMonster():
    conjunction = ('과', '와')
    monster = ('고블린', '트롤', '늑대')
    mon_name = random.choice(monster)
    mon_stat = {  }
    
    
    if mon_name == '고블린':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 50
        mon_stat['health'] = 100
        
    elif mon_name == '트롤':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 80
        mon_stat['health'] = 200
        
    else:
        conjunction = conjunction[1]
        mon_stat['dmg'] = 40
        mon_stat['health'] = 80
    
    
    
    #파이썬 전투 로그
    def pythonFight():    
        round = 0
        while mon_stat['health'] > 0 and python_stat['health'] > 0 :            
            python_stat['health'] -= mon_stat['dmg']
            mon_stat['health'] -= python_stat['dmg']
            fighting_log['round'] = round          
            if(round > 1):
                print("'파이썬'의 현재 체력은 %s남았습니다." %(python_stat['health']))    
            round += 1
            print("%s 라운드 결과 '파이썬'은 몬스터에게 %s의 데미지를 주었습니다. \n 몬스터는 파이썬에게 %s의 데미지를 주었습니다." %(round, python_stat['dmg'], mon_stat['dmg']))

    # 파이썬 전투
    #print("'파이썬'의 데미지: %s,현재 체력: %s, '%s'의 데미지: %s, 현재 체력: %s" %(python_stat['dmg'],python_stat['health'],mon_name, mon_stat['dmg'], mon_stat['health']))
    print("'파이썬'이 '%s'%s 조우했습니다. \n '파이썬'의 공격력: %s 체력: %s , '%s'의 공격력: %s 체력: %s" %(mon_name, conjunction,python_stat['dmg'],python_stat['health'],mon_name,mon_stat['dmg'],mon_stat['health'] ) )
    pythonFight()
    
    if(python_stat['health'] > 0):
        print("전투 끝에 '파이썬'의 체력은 %s 남았습니다." %(python_stat['health']) + "---- 승리!! ----\n")
    else:
        print("전투 끝에 '파이썬'이 죽었습니다." + "---- 게임 오버!! ----\n")
   
    
    
    
#파이썬을 운명으로 들이미는 버튼

window = Tk() #윈도우 생성
label = Label(window, text = '파이썬의 대모험')#윈도우 레이블 위젯 생성 뒤 텍스트 지정
label.pack() #pack이 호출되어야만 위젯이 화면에 나타난다

b1 = Button(window, text = '진행', command = meetMonster) # command = 함수 실행
b1.pack(padx = 100, pady = 20) # 버튼 상하좌우 여백
window.mainloop() #사용자가 윈도우를 닫을 때 까지 창의 이벤트를 반복한다.


세상 일은 항상 변수가 존재한다.

파이썬과 몬스터가 싸울 때도 변수가 없다면 재미가 없을 것이다.

 

문제 3

 

파이썬과 몬스터가 서로 주고 받는 데미지는 설정 공격력의 80% 부터 100% 까지 랜덤하게 적중된다.
전투 시스템에 위의 조건을 추가하자

 


import random #랜덤 함수를 사용하기 위해 모듈 임포트
from tkinter import* #tkinter모듈의 모든 클래스와 함수 포함


python_stat = { 'dmg': 100 , 'health': 1000 }
fighting_log = { 'round': 0 }

#파이썬이 몬스터를 만났을 때
def meetMonster():
    conjunction = ('과', '와')
    monster = ('고블린', '트롤', '늑대')
    mon_name = random.choice(monster)
    mon_stat = {  }
     
    
    if mon_name == '고블린':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 50
        mon_stat['health'] = 100
        
    elif mon_name == '트롤':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 80
        mon_stat['health'] = 200
        
    else:
        conjunction = conjunction[1]
        mon_stat['dmg'] = 40
        mon_stat['health'] = 80
                
        
    #파이썬 전투 로그
    def pythonFight():    
        round = 0
        while mon_stat['health'] > 0 and python_stat['health'] > 0 :    
            mon_realdmg = mon_stat['dmg'] - random.randint(0,mon_stat['dmg']*20/100) #몬스터의 데미지 보정값
            python_realdmg = python_stat['dmg'] - random.randint(0,python_stat['dmg']*20/100) #파이썬의 데미지 보정값   
           
            python_stat['health'] -= mon_realdmg
            mon_stat['health'] -=  python_realdmg
            fighting_log['round'] = round          
            if(python_stat['health'] < 0):
                print("'파이썬'의 현재 체력은 %s남았습니다." %(python_stat['health']))    
            round += 1
            print("%s 라운드 결과 '파이썬'은 몬스터에게 %s의 데미지를 주었습니다. \n 몬스터는 파이썬에게 %s의 데미지를 주었습니다." %(round, python_realdmg, mon_realdmg))

    # 파이썬 전투
    #print("'파이썬'의 데미지: %s,현재 체력: %s, '%s'의 데미지: %s, 현재 체력: %s" %(python_stat['dmg'],python_stat['health'],mon_name, mon_stat['dmg'], mon_stat['health']))
    print("'파이썬'이 '%s'%s 조우했습니다. \n '파이썬'의 공격력: %s 체력: %s , '%s'의 공격력: %s 체력: %s" %(mon_name, conjunction,python_stat['dmg'],python_stat['health'],mon_name,mon_stat['dmg'],mon_stat['health'] ) )
    pythonFight()
    
    if(python_stat['health'] > 0):
        print("전투 끝에 '파이썬'의 체력은 %s 남았습니다." %(python_stat['health']) + "---- 승리!! ----\n")
    else:
        print("전투 끝에 '파이썬'이 죽었습니다." + "---- 게임 오버!! ----\n")


#파이썬을 운명으로 들이미는 버튼

window = Tk() #윈도우 생성
label = Label(window, text = '파이썬의 대모험')#윈도우 레이블 위젯 생성 뒤 텍스트 지정
label.pack() #pack이 호출되어야만 위젯이 화면에 나타난다

b1 = Button(window, text = '진행', command = meetMonster) # command = 함수 실행
b1.pack(padx = 100, pady = 20) # 버튼 상하좌우 여백
window.mainloop() #사용자가 윈도우를 닫을 때 까지 창의 이벤트를 반복한다.

 

 


 

문제 4

 

전투에 변수를 하나 더 추가해보자.

 

파이썬과 몬스터는 각각 기본 회피율은 10%로 설정, 전투시 자신이 회피가 발동하면 상대의 데미지를 반만 받는다.

적용해보자.

 


import random #랜덤 함수를 사용하기 위해 모듈 임포트
from tkinter import* #tkinter모듈의 모든 클래스와 함수 포함


python_stat = { 'dmg': 100 , 'health': 500 }
fighting_log = { 'round': 0 }

#파이썬이 몬스터를 만났을 때
def meetMonster():
    conjunction = ('과', '와')
    monster = ('고블린', '트롤', '늑대')
    mon_name = random.choice(monster)
    mon_stat = {  }#몬스터 스탯 기본 빈값 
    
    
    if mon_name == '고블린':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 50
        mon_stat['health'] = 100
        
    elif mon_name == '트롤':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 80
        mon_stat['health'] = 200
        
    else:
        conjunction = conjunction[1]
        mon_stat['dmg'] = 40
        mon_stat['health'] = 80
                
        
    #파이썬 전투 로그
    def pythonFight():    
        round = 0
        while mon_stat['health'] > 0 and python_stat['health'] > 0 :    
            mon_realdmg = mon_stat['dmg'] - random.randint(0,mon_stat['dmg']*20/100) #몬스터의 데미지 보정값
            python_realdmg = python_stat['dmg'] - random.randint(0,python_stat['dmg']*20/100) #파이썬의 데미지 보정값   
            
            f_evasion_late = random.randint(0,10) #파이썬의 기본 회피수치
            m_evasion_late = random.randint(0,10) #몬스터의 기본 회피 수치
            
            f_evasion = False #퍼이썬의 기본 회피값 
            m_evasion = False #몬스터의 기본 회피값
            
            #회피율 적용(10분의 1확율)
            if(m_evasion_late == 1):
                m_evasion = True #회피 발동
            
            if(f_evasion_late == 1):
                f_evasion = True #회피 발동
            
            #회피율 적용 데미지 파이썬
            if(f_evasion == False):
                python_stat['health'] -= mon_realdmg
            elif(f_evasion == True):
                python_stat['health'] -= mon_realdmg/2  
                print("'파이썬'이 공격을 회피했습니다.")
                
            #회피율 적용 데미지 몬스터
            if(m_evasion == False):
                mon_stat['health'] -=  python_realdmg
            elif(m_evasion == True):
                mon_stat['health'] -=  python_realdmg/2   
                print("몬스터가 공격을 회피했습니다.")
                        
            fighting_log['round'] = round          
            round += 1
            
            #회피가 발생할 경우 출력로그 업데이트
            if(m_evasion == True):
                python_realdmg = python_realdmg/2
            
            if(f_evasion == True):
                mon_realdmg = mon_realdmg/2
            
            print("%s 라운드 결과 '파이썬'은 몬스터에게 %s의 데미지를 주었습니다. \n 몬스터는 파이썬에게 %s의 데미지를 주었습니다.\n" %(round, python_realdmg, mon_realdmg))

            if(python_stat['health'] < 0):
                print("'파이썬'이 단말마를 지릅니다. 살려줘!")
                break
            
            
            
    # 파이썬 전투
    #print("'파이썬'의 데미지: %s,현재 체력: %s, '%s'의 데미지: %s, 현재 체력: %s" %(python_stat['dmg'],python_stat['health'],mon_name, mon_stat['dmg'], mon_stat['health']))
    print("'파이썬'이 '%s'%s 조우했습니다. \n '파이썬'의 공격력: %s 체력: %s , '%s'의 공격력: %s 체력: %s\n" %(mon_name, conjunction,python_stat['dmg'],python_stat['health'],mon_name,mon_stat['dmg'],mon_stat['health'] ) )
    pythonFight()
    
    if(python_stat['health'] > 0):
        print("전투 끝에 '파이썬'의 체력은 %s 남았습니다." %(python_stat['health']) + "---- 승리!! ----\n\n")
    else:
        print("전투 끝에 '파이썬'이 죽었습니다." + "---- 게임 오버!! ----\n")


#파이썬을 운명으로 들이미는 버튼

window = Tk() #윈도우 생성
label = Label(window, text = '파이썬의 대모험')#윈도우 레이블 위젯 생성 뒤 텍스트 지정
label.pack() #pack이 호출되어야만 위젯이 화면에 나타난다

b1 = Button(window, text = '진행', command = meetMonster) # command = 함수 실행
b1.pack(padx = 100, pady = 20) # 버튼 상하좌우 여백
window.mainloop() #사용자가 윈도우를 닫을 때 까지 창의 이벤트를 반복한다.

 

 


 

문제 5

 

파이썬이 시스템에 묻는다.

"나는 죽어라 싸우는데 몇마리나 잡아야 오늘 전투가 끝나는 거요?"

파이썬이 궁금해한다. 현재 파이썬이 몬스터를 죽인 횟수를 전투가 끝나면 다음과 같이 정수로 출력해보자.
파이썬이 몬스터를 00마리 죽였습니다.
파이썬이 만약 싸우다 죽는다면 
파이썬이 00마리의 몬스터를 잡다가 죽었습니다.  애도~ 로 출력하자.

 


import random #랜덤 함수를 사용하기 위해 모듈 임포트
from tkinter import* #tkinter모듈의 모든 클래스와 함수 포함


python_stat = { 'dmg': 100 , 'health': 500 }
fighting_log = { 'round': 0 }

kill_log = 0 #파이썬의 몬스터 킬수


#파이썬이 몬스터를 만났을 때
def meetMonster():
    conjunction = ('과', '와')
    monster = ('고블린', '트롤', '늑대')
    mon_name = random.choice(monster)
    mon_stat = {  }#몬스터 스탯 기본 빈값 
      
    global kill_log
    kill_log += 1
    
    if mon_name == '고블린':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 50
        mon_stat['health'] = 100
        
    elif mon_name == '트롤':
        conjunction = conjunction[0]
        mon_stat['dmg'] = 80
        mon_stat['health'] = 200
        
    else:
        conjunction = conjunction[1]
        mon_stat['dmg'] = 40
        mon_stat['health'] = 80
                
        
    #파이썬 전투 로그
    def pythonFight():    
        round = 0
        while mon_stat['health'] > 0 and python_stat['health'] > 0 :    
            mon_realdmg = mon_stat['dmg'] - random.randint(0,mon_stat['dmg']*20/100) #몬스터의 데미지 보정값
            python_realdmg = python_stat['dmg'] - random.randint(0,python_stat['dmg']*20/100) #파이썬의 데미지 보정값   
            
            f_evasion_late = random.randint(0,10) #파이썬의 기본 회피수치
            m_evasion_late = random.randint(0,10) #몬스터의 기본 회피 수치
            
            f_evasion = False #퍼이썬의 기본 회피값 
            m_evasion = False #몬스터의 기본 회피값
            
            #회피율 적용(10분의 1확율)
            if(m_evasion_late == 1):
                m_evasion = True #회피 발동
            
            if(f_evasion_late == 1):
                f_evasion = True #회피 발동
            
            #회피율 적용 데미지 파이썬
            if(f_evasion == False):
                python_stat['health'] -= mon_realdmg
            elif(f_evasion == True):
                python_stat['health'] -= mon_realdmg/2  
                print("'파이썬'이 공격을 회피했습니다.")
                
            #회피율 적용 데미지 몬스터
            if(m_evasion == False):
                mon_stat['health'] -=  python_realdmg
            elif(m_evasion == True):
                mon_stat['health'] -=  python_realdmg/2   
                print("몬스터가 공격을 회피했습니다.")
                        
            fighting_log['round'] = round          
            round += 1
            
            
            #회피가 발생할 경우 출력로그 업데이트
            if(m_evasion == True):
                python_realdmg = python_realdmg/2
            
            if(f_evasion == True):
                mon_realdmg = mon_realdmg/2
            
            print("%s 라운드 결과 '파이썬'은 몬스터에게 %s의 데미지를 주었습니다. \n 몬스터는 파이썬에게 %s의 데미지를 주었습니다.\n" %(round, python_realdmg, mon_realdmg))

            if(python_stat['health'] < 0):
                print("'파이썬'이 단말마를 지릅니다. 살려줘!")
                break
            
            
            
    # 파이썬 전투
    #print("'파이썬'의 데미지: %s,현재 체력: %s, '%s'의 데미지: %s, 현재 체력: %s" %(python_stat['dmg'],python_stat['health'],mon_name, mon_stat['dmg'], mon_stat['health']))
    print("'파이썬'이 '%s'%s 조우했습니다. \n '파이썬'의 공격력: %s 체력: %s , '%s'의 공격력: %s 체력: %s\n" %(mon_name, conjunction,python_stat['dmg'],python_stat['health'],mon_name,mon_stat['dmg'],mon_stat['health'] ) )
    pythonFight()
    
    if(python_stat['health'] > 0):
        print("'파이썬'이 몬스터를 총 %s 마리 죽였습니다." %kill_log)
        print("전투 끝에 '파이썬'의 체력은 %s 남았습니다." %(python_stat['health']) + "---- 승리!! ----\n\n")
    else:
        print("전투 끝에 '파이썬'이 죽었습니다." + "---- 게임 오버!! ----\n")


#파이썬을 운명으로 들이미는 버튼

window = Tk() #윈도우 생성
label = Label(window, text = '파이썬의 대모험')#윈도우 레이블 위젯 생성 뒤 텍스트 지정
label.pack() #pack이 호출되어야만 위젯이 화면에 나타난다

b1 = Button(window, text = '진행', command = meetMonster) # command = 함수 실행
b1.pack(padx = 100, pady = 20) # 버튼 상하좌우 여백
window.mainloop() #사용자가 윈도우를 닫을 때 까지 창의 이벤트를 반복한다.

 

반응형

'AI > Python' 카테고리의 다른 글

Python #데이터 전처리  (0) 2021.09.29
Python #정규식 #정규 표현식  (0) 2021.09.25
Python #파이썬의 대모험 01  (2) 2021.08.31
Python #실습 #반복문 활용 #조건문  (0) 2021.08.31
Python Basic #12 module  (0) 2021.07.26