내일배움캠프/프로젝트

개인프로젝트 - 텍스트 RPG : 시작화면과 인벤토리 시스템

서보훈 2024. 9. 20. 20:18

오늘은 게임 시작화면과 인벤토리 시스템을 제작하였습니다.

 


게임 시작화면

TextCreater("게임 시작   ");
playerChar.GetItem(itemDb.items[0]);

Console.Clear();
int input;
string anyInput;
//본 게임
while(true)
{
    TextCreater("마을에 오신것을 환영합니다.\n어떤 행동을 할지 선택해주세요.\n\n");
    TextCreater("1.상태창\n2.인벤토리\n3.상점\n4.던전입장\n\n");

    TextCreater("행동 입력");
    input = InputInt(Console.ReadLine());

    if(input == 1)
    {
        ViewStatus();
        anyInput = Console.ReadLine();
        Console.Clear();

    }
    else if(input == 2)
    {
        ViewInven();
    }
}

 

캐릭터 생성을 진행한 메인 함수에서 이어집니다.

 

이전에 만들어준 텍스트를 천천히 발생시키는 TextCreater를 사용하여 메인화면의 연출을 발생시킵니다.

현재는 상태창과 인벤토리 1, 2번만 구현된 상태입니다.

또한 인벤토리 확인을 위해 시작과 동시에 아이템 하나를 지급하는중입니다.

 

스텟을 보여주는 함수, ViewStatus() 함수입니다.

//스텟을 보여주는 함수
private static void ViewStatus()
{
    Console.Clear();
    TextCreater("상태창\n\n");
    TextCreater($"Lv.{playerChar.Level} / 경험치 : {playerChar.Exp}");
    TextCreater($"{playerChar.UserName} ({playerChar.KorJobName})");
    TextCreater($"공격력 : {playerChar.AttackPoint}");
    TextCreater($"방어력 : {playerChar.DefencePoint}");
    TextCreater($"체력 : {playerChar.HealthPoint}/{playerChar.MaxHealth}");
    TextCreater($"Gold : {playerChar.PlayerGold}");
    Console.WriteLine();

    TextCreater("아무거나 입력하여 나가기");
}

이전에 Character 클래스를 객체로 만들어 playerChar 로 만들었습니다.

이 클래스에서 모든 데이터를 얻어와서 플레이어의 정보를 표기합니다.

 

인벤토리를 보여주는 ViewInven() 함수입니다.

//인벤토리를 보여주는 함수
private static void ViewInven()
{
    Console.Clear();
    TextCreater("인벤토리\n");
    TextCreater("보유 중인 아이템을 관리할 수 있습니다.\n");
    
    for(int i = 0; i < playerChar.inventory.Length; i++)
    {
        if (playerChar.inventory[i] == null)
        {
            string itemText = "-" + (i + 1) + " ";
            TextCreater(itemText);
        }
        else
        {
            string itemStat = "";
            if (playerChar.inventory[i].type == ItemType.Weapon)
            {
                itemStat = "공격력 +" + playerChar.inventory[i].itemAttack; 
            }
            else
            {
                itemStat = "방어력 +" + playerChar.inventory[i].itemDefence;
            }

            string itemText ="-" + (i + 1) + " " + playerChar.inventory[i].name + " | " + itemStat + " | " + playerChar.inventory[i].description;
            TextCreater(itemText);
        }
    }
}

보유한 아이템을 보여주는 함수 입니다.

인벤토리 슬롯은 10칸이며 슬롯에 아이템이 없을경우 숫자만 표기되고 슬롯은 비어있게 됩니다.

또한 장비의 타입에 따라서 공격력, 방어력이 표기될지 결정됩니다.


Item 클래스

TIL에서 서술했듯이, null 관련 문제가 발생하여 아이템을 클래스로 변경하였습니다.

그에 맞추어 필드 이름을 코딩스타일에 따라 변경해주었습니다.

namespace TextRPG_SBH
{
    public enum ItemType
    {
        Weapon = 0,
        Armor = 1
    }

    public class Item
    {
        public string name;
        public string description;
        public ItemType type;
        public float itemAttack;
        public float itemDefence;
        public int itemId;

        public Item(int _id, string _itemName, string _itemDescription, ItemType _type, int _attck, int _defence)
        {
            itemId = _id;
            name = _itemName;
            description = _itemDescription;
            type = _type;
            itemAttack = _attck;
            itemDefence = _defence;
        }
    }

    internal class ItemDatabase
    {
        public List<Item> items = new List<Item>();

        public void ResetItemList()
        {
            items.Add(new Item(1, "시작의 검", "처음 만들어진 검", ItemType.Weapon, 1, 0));
        }
    }
}

현재 itemId 의 역할을 리스트의 순서가 해줄 수 있기 때문에 삭제를 고려하는중입니다

 


캐릭터 스텟 관련

public void SetBaseStatus(string name, Jobs job)
{
    UserName = name;

    switch (job)
    {
        case Jobs.Warrior:
            baseAttack = 10;
            baseDefence = 7;
            baseHealth = 120;
            KorJobName = "전사";
            break;
        case Jobs.Wizard:
            baseAttack = 17;
            baseDefence = 4;
            baseHealth = 80;
            KorJobName = "마법사";
            break;
        case Jobs.Theif:
            baseAttack = 13;
            baseDefence = 6;
            baseHealth = 100;
            KorJobName = "도적";
            break;
        case Jobs.Archer:
            baseAttack = 15;
            baseDefence = 5;
            baseHealth = 90;
            KorJobName = "궁수";
            break;
    }

    AttackPoint = baseAttack;
    DefencePoint = baseDefence;
    maxHealth = baseHealth;
    HealthPoint = baseHealth;
}

현재 외부에서 참조 가능한 AttackPoint 등의 속성 변수가 초기화되지 않은 상태이기 때문에, 캐릭터의 직업을 고를때 속성 변수에 기본값을 넣어주게 되었습니다.

 


인벤토리 관련

인벤토리는 Character 클래스에 포함되어있으며, 고정된 크기로 구현할 예정이기 때문에 배열을 통해 구현하였습니다.

//캐릭터 인벤토리(10칸)
public Item[] inventory = new Item[10];
//캐릭터 장비 칸
public Item[] equipSlot = new Item[2];

 

아이템 획득 함수 입니다.

public void GetItem(Item item)
{
    //아이템 인벤토리의 빈칸에 아이템 등록
    for(int i = 0; i < inventory.Length; i++)
    {
        //
        if (inventory[i] == null)
        {
            inventory[i] = item;
            break;
        }

        //만약, 빈칸이 없을경우(빈칸이 있으면 break를 통해 for문을 종료함)
        if(i == inventory.Length)
        {
            Console.WriteLine("인벤토리가 가득차 아이템 획득에 실패했습니다.");
        }
    }
}

아이템을 획득할 때, 매개변수를 통하여 아이템을 획득하게 되며 현재는 아이템창에 빈칸이 없을경우 아이템이 획득할 수 없도록 만들어주었습니다.

 

아직 사용되지 않은 아이템 장착 함수입니다.

//아이템 장착 함수
public void EquipItem(Item item)
{
    //아이템 타입이 무기일경우
    if (item.type == ItemType.Weapon)
    {
        //장비칸 배열 0번에 등록
        if (equipSlot[0] == null)
        {
            equipSlot[0] = item;
            AttackPoint += equipSlot[0].itemAttack;
        }
        else
        {
            AttackPoint -= equipSlot[0].itemAttack;
            equipSlot[0] = item;
            AttackPoint += equipSlot[0].itemAttack;
        }
    }
    //아이템 타입이 방어구일경우
    else
    {
        //장비칸 배열 1번에 등록
        if (equipSlot[1] == null)
        {
            equipSlot[1] = item;
            AttackPoint += equipSlot[1].itemDefence;
        }
        else
        {
            AttackPoint -= equipSlot[1].itemDefence;
            equipSlot[0] = item;
            AttackPoint += equipSlot[1].itemDefence;
        }
    }
}

다음 작업때 아이템 장착 시스템을 만들어줄 예정입니다.

해당 함수에서는 타입이 무기면 장비 슬롯 배열의 0번슬롯에 추가,

타입이 방어구면 슬롯 배열의 1번 슬롯에 추가하도록 만들어주었습니다.

 

또한 아이템이 이미 장착되어있는경우 아이템을 해제하고 장착하며 장착과 해제를 할 때 스텟이 변경되도록 생성해주었습니다.


다음 작업때는 아이템 장착과 해제, 상점 시스템을 만들어볼 예정입니다.