본문 바로가기
개발 노트 꾸러미/스파르타 코딩 교육 AI웹 개발노트

AI웹개발 TIL 2주차 수요일 [2021-12-23] Updated

by 괴짜코더 2021. 12. 23.

스파르타 코딩 클럽 AI웹개발 교육 프로그램< Daily Note 2 Weeks Day 3 >

< 2 주차 수요일 >

오늘도 *준태 튜터님께서 재밌는 프로젝트를 주셨다. 바로 게임을 만드는것이였는데 용사1명과 몬스터3명이 싸워서 이기는 룰을 가진 게임이였다. 입력값으로 물리 또는 마법공격을 진행하여 자신만의 게임을 창작하듲이 코드를 소화하는것을 바라셨었다. 필자는 원래 인디 게임 개발자였음으로 이해도가 높았다. 어느정도 게임의 프롤로그 해피엔딩 로그 굿엔딩로그등 실제 윈도우96 텍스트기반 게임비슷 하게 만들었고 발표까지했었다. 부끄럽게도 많은분들이 프레젠테이션과 프로젝트물을 좋아해주셔서 고마웠다. 제일 감사한것은 스파르타 교육기간동안 이런 프로젝트를 주신 *준태 튜터님께 더욱 감사하다 아래에 ▼ 수요일날 만들었던 용사 vs 3 몬스터 코드를 적어놓았다.

* 게더타운 강당에서 프레젠테이션중 AI웹개발 학우님들의 호응에 너무 감사했다. 

[ 이터니티의 수호자 용자 히맨 게임 ]

# 턴제 RPG 게임 만들기
# 자신의 턴에서 플레이어는 공격, 마법 쓸수있다.
# 몬스터는 자신의 턴이 오면, 플레이어를 상대로 공격 할수있고그냥 자신의 체력을 회복할 수있고 그냥 아무 행동도 안할수 있습니다.
# 현재 상황은 전사 와 미니 고블린, 슈퍼 고블린이 1대 3으로 대치하는 상황입니다. 위 설명을 기반을, 플레이어가 전사를 조작해서 3마리의 몬스터와 싸우도록 게임을 구현해보세요.

import random
import time
########################################################################################################################
# Base_Form_Unit 클래스

class Base_Form_Unit:
        def __init__(self, Name, Hp, Moving_Speed):
                self.Unit_Name = Name
                self.Unit_Hp = Hp
                self.Unit_Moving_Speed = Moving_Speed
                #print(F"{self.Unit_Name} 유닛이 월드에 스폰되었습니다.")

        def move(self, location):
            print("[지상 유닛 이동]")
            print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"   \
                .format(self.Unit_Name, location, self.Unit_Moving_Speed))

        Dead = False

########################################################################################################################
 # 어택 폼 상속 클래스 베이스 폼

class Attack_Unit(Base_Form_Unit): # class Attck_Unit()안에는 부모의 정보를 상속 받을수있다.

        # Attack_Unit_Moving_Speed 는 움직임 속도와 공격속도가 비례하다.
        def __init__(self, name, hp, Damage, Attack_Unit_Moving_Speed):
            Base_Form_Unit.__init__(self, name, hp, Attack_Unit_Moving_Speed)
            self.Unit_Damage = Damage
            #print(F"{self.Unit_Name}의 능력치 : 체력 {self.Unit_Hp}, 공격력 {self.Unit_Damage}, 공격속도 {self.Unit_Moving_Speed}")

        # 정확한 location으로 공격하지 못할 경우 미스가 뜰수있다.
        def Attack(self, location):
            print(F"{self.Unit_Name}가 {location} 방향으로 적군을 공격 합니다. [공격력 {self.Unit_Damage}]")

########################################################################################################################
 # 몬스터 상속 클래스 베이스 폼

class Monster(Base_Form_Unit): # class Attck_Unit()안에는 부모의 정보를 상속 받을수있다.

        # Attack_Unit_Moving_Speed 는 움직임 속도와 공격속도가 비례하다.
        def __init__(self, name, hp, Damage, Attack_Unit_Moving_Speed):
            Base_Form_Unit.__init__(self, name, hp, Attack_Unit_Moving_Speed)
            self.Unit_Damage = Damage
            #print(F"{self.Unit_Name}의 능력치 : 체력 {self.Unit_Hp}, 공격력 {self.Unit_Damage}, 공격속도 {self.Unit_Moving_Speed}")

        # 정확한 location으로 공격하지 못할 경우 미스가 뜰수있다.
        def Attack(self, location):
            print(F"{self.Unit_Name}가 {location} 방향으로 적군을 공격 합니다. [공격력 {self.Unit_Damage}]")

        def healing_Factor(self):
            self.Unit_Hp + 10
            print(F'{self.Unit_Name}가 10만큼의 체력을 치유하였습니다.')

        def waiting(self):
            print(F"{self.Unit_Name}가 이번 한턴을 쉽니다.")
            # Monster.healing_Factor(self)

########################################################################################################################
 # 히맨 상속 클래스 Attack_Unit

class heeman(Attack_Unit):
    Rage_Mode_Activate = True
    Magic_Damage = 50

    def __init__(self):
        Attack_Unit.__init__(self, "우주의 용자 히맨!", 100, 10, 5)

    def Magic(self):
        self.Magic_Damage
        print(F"{self.Unit_Name} : {self.Magic_Damage} 데미지를 입었습니다.")
        self.Unit_Hp -= self.Magic_Damage
        print(F"{self.Unit_Name}의 현재 체력은 {self.Unit_Hp} 입니다")
        if self.Unit_Hp <= 0:
            print(F"{self.Unit_Name} : 죽었습니다.")

        elif 10 < self.Unit_Hp < 15:
            print(F"{self.Unit_Name} : 과도한 출혈을 입었습니다. 상처를 치료해야합니다.")

########################################################################################################################
 # 혈귀 궁병 상속 클래스 Monster

class Blood_Archer(Monster):

    def __init__(self):
        Attack_Unit.__init__(self, "혈귀궁병", 10, 10, 10)

########################################################################################################################
 # 혈귀 도끼전사 상속 클래스 Monster

class Blood_Axe(Monster):

    def __init__(self):
        Attack_Unit.__init__(self, "혈귀도끼전사", 30, 30, 5)

########################################################################################################################
 # 혈귀 예언자 상속 클래스 Monster

class Blood_Overseer(Monster):

    def __init__(self):
        Attack_Unit.__init__(self, "혈귀예언자", 50, 25, 5)

SpaceWarrior = heeman()

Spwaned_B_Archer = Blood_Archer()
Spwaned_B_Axe = Blood_Axe()
Spwaned_B_Overseer = Blood_Overseer()

Monster_List = []

Monster_List.append(Spwaned_B_Archer)
Monster_List.append(Spwaned_B_Axe)
Monster_List.append(Spwaned_B_Overseer)

print()

print('-' * 30 + ' 저 먼 은하계의 이터니아.. ' + '-' * 30)

def Prologue():
    '''
    스켈레토가 정예용병을 이끌고 그레이스컬을 침공했습니다! 도와줘요 히맨!!
    아담 : 안돼! 그레이스컬의 수호자께서 위험하다. !!
    아담은 전집중 호흡으로 칼을 하늘을 가리켰다.. 우르릉,.... 쾅쾅!!!!
    그레이 스컬의 이름으로.. 힘이여 솟아라!
    [뿌리링 빵뽕!] 아담은 히맨이 되었습니다.
    '''
    pass

# 굿 엔딩
def Good_Ending():
    '''
    스켈레토과 그의 무리를 무찌르고 이터니아를 수호하였습니다.
    어둠은 잠시나마 잠식 되었습니다.히맨! 우주의 수호자여 영원하라!
    '''
    # print(Good_Ending.__doc__)

    pass

# 배드 엔딩
def Bad_Ending():
    '''
    스켈레토가 이터니아를 파괴하였습니다.
    우주의 균열이 깨지고 어둠의 시대가 도래했습니다...
    우주의 용사 히맨.. 꺠어진 우주의 균열을 다시 일으켜세우시겠습니까?
    Shit + F10으로 다시 실행하시면 됩니다.
    '''
    pass

# 게임 재시도
def Retry():

    while True:
        try:
            Suggest_Value = str(input(" 다시 시작 하시겠습니까? : [ y / n ] "))
            if Suggest_Value == 'y':
                break
            elif Suggest_Value == 'n':
                print("게임 오버")
                quit()
            else:
                raise ValueError
        except ValueError:
            print("y 또는 n 만 눌러 주세요.")


print(Prologue.__doc__)
phase = 1
while True:
    if phase == 6:
        print(Bad_Ending.__doc__)
        quit()

    print(F"현재 게임의 페이즈는 {phase}입니다.")
    print()
    print("스켈레토의 군단의 턴입니다!")
    print()
    for Monster_instance in Monster_List:
        if Monster_instance.Unit_Hp > 0:
            if Monster_instance.Unit_Name.__len__() == 4:
                print("%10s"%F'{Monster_instance.Unit_Name}',"%11s"%F' 체력 : {Monster_instance.Unit_Hp}')
                Archer = Monster_instance
            elif Monster_instance.Unit_Name.__len__() == 5:
                print("%11s"%F'{Monster_instance.Unit_Name}',"%9s"%F' 체력 : {Monster_instance.Unit_Hp}')
                Overseer = Monster_instance
            else:
                print("%12s"%F'{Monster_instance.Unit_Name}',"%4s"%F' 체력 : {Monster_instance.Unit_Hp}')
                Axe = Monster_instance

    print() #줄 바꿈
    print() #줄 바꿈
    print("%16s" % F'{SpaceWarrior.Unit_Name}', "%4s" % F' 체력 : {SpaceWarrior.Unit_Hp}')

    print() #줄 바꿈
    Waiting_timer = random.randint(2,5)
    # 카운트 증가로 몬스터들의 상태를 변화시켜 print 시켜줌.
    counter = 0
    for x in range(1,Waiting_timer):
        if x == 0:
            break
        else:
            if counter == 0:
                print("몬스터가 행동을 선택중입니다!.")
                counter += 1
            elif counter == 1:
                print("[ 도움말 요정 ] :플레이어님은 다음 공격을 어떻게 하실건가요?")
                counter += 1
            elif counter == 2:
                print("몬스터가 우주의 용자 히맨의 주위를 위협하고 있습니다!")
                counter += 1
            else:
                print("적이 괜찮은 묘안이 떠올랐습니다 플레이어님 단단히 준비하세요!")
                counter += 1
        time.sleep(Waiting_timer)

    #몹들의 공격
    Random_Attack = random.randint(1,3)
    if Random_Attack == 1 and Archer.Dead == False:
        SpaceWarrior.Unit_Hp -= Archer.Unit_Damage
        print(F'{Archer.Unit_Name}가 {SpaceWarrior.Unit_Name}에게 {Archer.Unit_Damage}만큼 데미지를 줬습니다!')
    elif Archer.Dead == False:
        Archer.waiting()

    if Random_Attack == 2 and Archer.Dead == False:
        SpaceWarrior.Unit_Hp -= Axe.Unit_Damage
        print(F'{Axe.Unit_Name}가 {SpaceWarrior.Unit_Name}에게 {Axe.Unit_Damage}만큼 데미지를 줬습니다!')
    elif Axe.Dead == False:
        Axe.waiting()
    if Random_Attack == 3 and Archer.Dead == False:
        SpaceWarrior.Unit_Hp -= Axe.Unit_Damage
        print(F'{Overseer.Unit_Name}가 {SpaceWarrior.Unit_Name}에게 {Overseer.Unit_Damage}만큼 데미지를 줬습니다!')
    elif Overseer.Dead == False:
        Overseer.waiting()

    # 3초후 플레이어의 턴
    time.sleep(3)
    print()
    print('플레이어의 턴입니다!')
    while True:
        try:
            Player_AttackType =input("공격 방식을 선택하세요! : [물리], [마법] : ")
            if Player_AttackType == "물리":
                Player_AttackType = int(input("공격 타겟을 선택하세요! : [ 혈귀궁병 : 1 ], [ 혈귀 도끼전사 : 2 ], [ 혈귀 예언자 : 3] : "))
                if Player_AttackType == 1:
                    Archer.Unit_Hp -= SpaceWarrior.Unit_Damage
                    break
                elif Player_AttackType == 2:
                    Axe.Unit_Hp -= SpaceWarrior.Unit_Damage
                    break
                elif Player_AttackType == 3:
                    Overseer.Unit_Hp -= SpaceWarrior.Unit_Damage - 5
                    break
            if Player_AttackType == "마법":
                Player_AttackType = int(input("공격 타겟을 선택하세요! : [ 혈귀궁병 : 1 ], [ 혈귀 도끼전사 : 2 ], [ 혈귀 예언자 : 3] : "))
                if Player_AttackType == 1:
                    Archer.Unit_Hp -= SpaceWarrior.Magic_Damage
                    break
                elif Player_AttackType == 2:
                    Axe.Unit_Hp -= SpaceWarrior.Magic_Damage
                    break
                elif Player_AttackType == 3:
                    Overseer.Unit_Hp -= SpaceWarrior.Magic_Damage - 5
                    break
            else:
                raise ValueError
        except ValueError:
            print("잘못된 값을 입력했습니다. 물리 또는 마법을 선택해주세요.")

    # 만약 몹들이 죽었다면 상단부에서 플레이어 공격 불가능.
    if Archer.Unit_Hp <= 0:
        Archer.Dead = True
    if Axe.Unit_Hp <= 0:
        Axe.Dead = True
    if Overseer.Unit_Hp <= 0:
        Overseer.Dead = True

    # 리겜? 아니면 종료 리겜일시 죽었던 몬스터들 부활 체력 회복 주인공은 체력 +20만 증가
    if Archer.Unit_Hp < 0 and Overseer.Unit_Hp < 0 and Axe.Unit_Hp < 0:
        print(Good_Ending.__doc__)
        Retry()
        Archer.Unit_Hp = 10
        Overseer.Unit_Hp = 50
        Axe.Unit_Hp = 30
        Archer.Dead = False
        Axe.Dead = False
        Overseer.Dead = False
        SpaceWarrior.Unit_Hp += 20
        phase = 0

    phase += 1

 

댓글