카테고리 없음

내일 배움 캠프 20일

하늘유니콘 2023. 3. 31. 20:57

class Job(Player):
    def __init__(self):
        self.job_name = "직업이름"
        self.strength = 7  # 스탯 힘
        self.intelligence = 7  # 스탯 지능
        self.agility = 7  # 스탯 민첩

    def __str__(self):
        return f"{self.job_name}(으)로 선택했습니다."


class Warrior(Job):
    def __init__(self):
        self.job_name = "전사"
        self.strength = 10
        self.intelligence = 5
        self.agility = 7
        self.job_skill = "파워스크라이크"


class Archer(Job):
    def __init__(self):
        self.job_name = "궁수"
        self.strength = 7
        self.intelligence = 10
        self.agility = 5
        self.job_skill = "홀리애로우"


class Wizard(Job):
    def __init__(self):
        self.job_name = "마법사"
        self.strength = 5
        self.intelligence = 10
        self.agility = 7
        self.job_skill = "썬더볼트"



class Thief(Job):
    def __init__(self):
        self.job_name = "도적"
        self.strength = 7
        self.intelligence = 7
        self.agility = 10
        self.job_skill = "쿼드스로우"

"먼저 플레이어 이름을 입력해주세요"라고 나옵니다.

취합문제점 : 다수의 풀더들이 많고 함수들을 다 불러와야되기 때문에 혼동이 있고 구글링해도 아는 정보도 없어서 실패로 돌아갔지만 팀원분 한 분이 다행히 함수를 이해를 하셔서 질문을 던졌더니 각 파일을 메인 파일에다가 import로 취합을 해주는거라고 말씀하셨습니다.

 

 

<기술스택>

 

 

 

여러py파일들을 메인페이지에가가 취합을 해주는게 관권이었습니다.

 

일단 이런건 해결되었고 팀원분 덕분에 나는 알아냈지 못했지만 팀원분들 덕분에 많이 알고 깨달은거 같습니다.

팀원분들이 제일 힘들어 했던게 취합과정이였는데요 성공적으로 하는것도 중요하지만 하나 하나 어러운것도

협업을 통해서 공부해나가는게 협업에 장점이 아닐까라고 생각이 듭니다.

 

<팀원이 만든 플레이어 객체> 생성 입니다.

class Job(Player):
    def __init__(self):
        self.job_name = "직업이름"
        self.strength = 7  # 스탯 힘
        self.intelligence = 7  # 스탯 지능
        self.agility = 7  # 스탯 민첩

    def __str__(self):
        return f"{self.job_name}(으)로 선택했습니다."


class Warrior(Job):
    def __init__(self):
        self.job_name = "전사"
        self.strength = 10
        self.intelligence = 5
        self.agility = 7
        self.job_skill = "파워스크라이크"


class Archer(Job):
    def __init__(self):
        self.job_name = "궁수"
        self.strength = 7
        self.intelligence = 10
        self.agility = 5
        self.job_skill = "홀리애로우"


class Wizard(Job):
    def __init__(self):
        self.job_name = "마법사"
        self.strength = 5
        self.intelligence = 10
        self.agility = 7
        self.job_skill = "썬더볼트"

        #     self.strength = job.strength - 2
        #     self.intelligence = job.intelligence + 3
        #     self.agility = job.agility + 2


class Thief(Job):
    def __init__(self):
        self.job_name = "도적"
        self.strength = 7
        self.intelligence = 7
        self.agility = 10
        self.job_skill = "쿼드스로우"

 

 

<직업선택> 생성

 

# 직업 선택, 생성


def create_job():
    print("직업을 선택해주세요")
    print("1. 전사(Warrior)")
    print("2. 궁수(Archer)")
    print("3. 마법사(Wizard)")
    print("4. 도적(Thief)")
    job_choice = input("> ")
    if job_choice == "1":
        player_job = Warrior()
        print(f"{player_job}")
    elif job_choice == "2":
        player_job = Archer()
        print(f"{player_job}")
    elif job_choice == "3":
        player_job = Wizard()
        print(f"{player_job}")
    elif job_choice == "4":
        player_job = Thief()
        print(f"{player_job}")
    return player_job

 

 

팀원 분이 캐릭터 객체를 위 코드처럼 작성을 했네요 보면서 공부를 하고 있습니다.

결과도 출력이 잘 나옵니다.

 

 

# 게임 실행 함수


def main():
    print("잡아보자...!")

    while True:
        print("=" * 20)
        print("무엇을 선택하시겠나요?")
        print("1. 모험")
        print("2. 포션 사용")
        print("3. 휴식")
        print("4. 상태창 보기")
        print("5. 상점 이용")
        print("6. Quit")
        choice = input("> ")
        if choice == "1":
            monster = mob.generate_monster()
            print(f"몬스터 {monster.name} 등장!")
            while monster.is_alive():
                print("-" * 20)
                print(f"{monster}")
                print(f"{player}")
                print("뭐할래?")
                print("1. 공격")
                print("2. 스킬")
                print("3. 포션사용")
                print("4. 도망")
                battle_choice = input("> ")
                if battle_choice == "1":
                    player.attack(monster)
                    if monster.is_alive():
                        monster.attack(player)
                        if not player.is_alive():
                            print("패배!")
                            quit()
                    elif not monster.is_alive():
                        mine.rewards(player)
                elif battle_choice == "2":
                    player.skill_attack(monster)
                    if monster.is_alive():
                        monster.attack(player)
                        if not player.is_alive():
                            print("패배!")
                            quit()
                elif battle_choice == "3":
                    player.heal()
                    monster.attack(player)
                elif battle_choice == "4":
                    print("도망간다.")
                    break
        elif choice == "2":
            player.heal()
        elif choice == "3":
            player.rest()
        elif choice == "4":
            player.view_stats()
        elif choice == "5":
            items.get_items(player)
        elif choice == "6":
            quit()

 

 

게임 실행 함수가 이렇게 복잡한 줄 몰랐네요 팀원분 작성해주신거 이해는 안 되지만 작성 잘 해주셔서 배울께 많습니다.

 

 

 

 

class Item:
    def __init__(self, item_num, name, price, weight, isdropable):
        self.name = name
        self.price = price
        self.weight = weight
        self.isdropable = isdropable
        self.item_num = item_num

    def show_item(self):
        print(f'{self.item_num} {self.name} {self.price} {self.weight}')

    def sale(self):
        print(f'[{self.name}] 판매 가격은 [{self.price}]')

    def discard(self):
        if self.isdropable:
            print(f'[{self.name}] 아이템을 버렸습니다.')
        else:
            print(f'[{self.name}] 아이템을 버릴 수 없습니다.')

    def __str__(self):
        return f'{self.name}'


class WearableItem(Item):
    def __init__(self, item_num, name, price, weight, isdropable, effect):
        super().__init__(item_num, name, price, weight, isdropable)
        self.effect = effect

    def wear(self):
        print(f'[{self.name}] 착용했습니다.{self.effect}')


class UsableItem(Item):
    def __init__(self, item_num, name, price, weight, isdropable, effect):
        super().__init__(item_num, name, price, weight, isdropable)
        self.effect = effect

    def use(self):
        print(f'[{self.name}] 사용했습니다.{self.effect}')


def make_item():
    sword = WearableItem(1, '강철검', 30000, 3.5, True, '체력 50 증가, 마력 3000 증가')
    armor = WearableItem(2, '철갑옷', 50000, 3.5, True, 'HP 50 증가, 마력 9000 증가')
    potion = UsableItem(3, 'HP포션', 1500000, 0.1, False, '효과 300초 지속 전부회복')
    potion2 = UsableItem(4, 'MP포션', 1500000, 0.1, False, '효과 300초 지속 전부회복')
    save_item = [sword, armor, potion, potion2]
    return save_item


def get_items(player):
    store = make_item()
    for i in range(len(store)):
        print(f"{store[i].item_num}. {store[i].name}, 가격: {store[i].price}")
    choice = input("> ")
    if player.money >= store[0].price and choice == "1":
        player.inventory.append(store[0].name)
        player.money -= store[0].price

        print(f'{store[0].name}을 구매했습니다.')

    elif player.money >= store[1].price and choice == "2":
        player.inventory.append(store[1].name)
        player.money -= store[1].price

        print(f'{store[1].name}을 구매했습니다.')

    elif player.money >= store[2].price and choice == "3":
        player.inventory.append(store[2].name)
        player.money -= store[2].price
        print(f'{store[2].name}을 구매했습니다.')

    elif player.money >= store[3].price and choice == "4":
        player.inventory.append(store[3].name)
        player.money -= store[3].price
        print(f'{store[3].name}을 구매했습니다.')
    else:
        print('골드가 부족합니다.')

클래스 아이템은 제가 코드를 짜보았는데요 여기서 취합한다고 팀원분이 코드를 바꿔놓았네요?

기존 코드에서 좀 바꿔워서 헷갈리긴 한데 핵심코드를 말하자면

 

 

 

class Item:
    def __init__(self, item_num, name, price, weight, isdropable):
        self.name = name
        self.price = price
        self.weight = weight
        self.isdropable = isdropable
        self.item_num = item_num

    def show_item(self):
        print(f'{self.item_num} {self.name} {self.price} {self.weight}')

    def sale(self):
        print(f'[{self.name}] 판매 가격은 [{self.price}]')

    def discard(self):
        if self.isdropable:
            print(f'[{self.name}] 아이템을 버렸습니다.')
        else:
            print(f'[{self.name}] 아이템을 버릴 수 없습니다.')

    def __str__(self):
        return f'{self.name}'

def show_item(self):
        print(f'{self.item_num} {self.name} {self.price} {self.weight}')

    def sale(self):
        print(f'[{self.name}] 판매 가격은 [{self.price}]')

    def discard(self):
        if self.isdropable:
            print(f'[{self.name}] 아이템을 버렸습니다.')
        else:
            print(f'[{self.name}] 아이템을 버릴 수 없습니다.')

    def __str__(self):
        return f'{self.name}'

 

클래스에서 인자들은 다 선언해주고 구글에서 아이템을 어떻게 선언하는 법이 있었습니다. 아이템을 self로 자신을 알려주는 코드로 넣어주고 아이템을 감싸주는 print(f'{self.item_num} {self.name} {self.price} {self.weight}')

문자열 안에다가 클로징하고 안에다가 변수를 삽입하는 형식입니다. self.item_num크게

의미는 없고 변수를 삽입했다라는 의미입니다.나머지도 똑같은 의미입니다.

 

나머지는 팀원분이 코드를 수정해버려서 설명하기 복잡은 코드가 있어서 설명은 더 못하겠네요 제가 친 코드하고 너무 틀려서요!