C# 절차지향 TextRPG 만들기 02

Mr.Seo·2025년 12월 18일

C# 기초문법

목록 보기
13/15

TextRPG 캐릭터 생성하기 02

enum ClassType
{
    None = 0,
    Knight,
    Archer,
    Mage,
}

struct Player // 계속 능력치를 늘려줄수 없으니 구조체를 만들어서 관리를 한다.
{
    public string job;
    public int hp;
    public int attack;
    public int def;
}
static ClassType ChooseClass()
{
    Console.WriteLine("직업을 선택하세요!");
    Console.WriteLine("[1] 기사");
    Console.WriteLine("[2] 궁수");
    Console.WriteLine("[3] 법사");

    ClassType choice = ClassType.None;
    string input = Console.ReadLine();
    switch (input)
    {
        case "1":
            choice = ClassType.Knight;
            break;
        case "2":
            choice = ClassType.Archer;
            break;
        case "3":
            choice = ClassType.Mage;
            break;
    }
    return choice;
}



static void CreatePlayer(ClassType choice, out Player player) 
{
    // 기사 hp : 100 attack : 10  defence : 10 
    // 궁수 hp : 75  attack : 12  defence : 7 
    // 법사 hp : 50  attack : 15  defence : 5 

    switch (choice)
    {
        case ClassType.Knight:
            player.job = "바바리안";
            player.hp = 100;
            player.attack = 10;
            player.def = 10;
            break;
        case ClassType.Archer:
            player.job = "아마존";
            player.hp = 75;
            player.attack = 12;
            player.def = 7;
            break;
        case ClassType.Mage:
            player.job = "소서리스";
            player.hp = 50;
            player.attack = 15;
            player.def = 5;
            break;
        default:
            player.job = "일반인";
            player.hp = 0;
            player.attack = 0;
            player.def = 0;
            break;
    }
}
static void Main(string[] args)
{
    while (true)
    {
        ClassType choice = ChooseClass(); // 리턴값을 받아야함!
        if (choice != ClassType.None)
        {
            // 캐릭터 생성
            Player player;
            CreatePlayer(choice, out player);

            Console.WriteLine($"직업 : {player.job} " +
                              $"체력 : {player.hp} " +
                              $"공격력 : {player.attack}" +
                              $" 방어력 : {player.def}");

            // 필드로 가서 몬스터랑 싸운다
        }
        else
            Console.Clear();
    }
}
  • 앞서 제작한 방식에서 Player 구조체를 추가하여 그 안에서 직업, 공격력, 체력, 방어력 을 생성했다.

  • 이렇게 제작하면 플레이어의 스탯을 일일히 하나씩 받을 필요가 없고 구조체 묶인 형태로 그 구조체 자체를 포함하여 out으로 넘겨서 출력하면 전에 작업한 코드와 동일하게 동작하게 된다.

  • 저기서 struct(복사 값)을 넘기기 때문에 원래 본체의 값을 수정하기 위해 out을 사용했는데 본체 자체를 수정하며 값을 넣기 위해서는 class 참조로 수정하여 작업을 하면 된다.

profile
프로그래머 취준생

0개의 댓글