TIL 0102 C#객체지향 / TextRPG - 1(개인)

강성원·2024년 1월 2일
0

TIL 오늘 배운 것

목록 보기
7/69
post-thumbnail

프로퍼티

C++에서는 멤버 변수에 간접 접근하게 해주기 위해서 Get과 Set함수를 선언, 정의해준다.
C#에서는 프로퍼티로 그 역할을 대신한다.

class Person
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

프로퍼티의 기본적인 형태이다.
내부에 로직을 추가 함으로써 데이터 유효성 검사 등의 기능을 추가할 수 있다.

자동 프로퍼티

프로퍼티를 좀 더 짧고 간단하게 사용할 수 있음.
(맨 앞 글자를 대문자로 해주면 좋다.)

class Person
{
    public string Name { get; set; }
}

Person person = new Person();
person.Name = "삼순이";

Console.WriteLine($"Name: {person.Name}); 

상속

virtual 키워드

public class Parent
{
    public virtual void Move()
    {
        Console.WriteLine("부모가 걷는다.");
    }
}

public class Child
{
	public override void Move()
    {
        Console.WriteLine("자식이 걷는다.");
    }
}
Parent temp = new Child();
temp.Move() // virtual 키워드를 사용해서 Child의 Move가 호출된다.

원래라면 자식 인스턴스를 부모 형태의 참조 변수로 참조하면 부모의 메서드가 호출되지만, virtual 키워드를 명시해주면 자식의 메서드를 호출한다.

추상 클래스와 메서드

  • 추상 클래스는 직접적으로 인스턴스를 생성할 수 없다.
  • 추상 클래스는 abstract 키워드를 사용하여 선언되며, 추상 메서드를 포함할 수 있다.
  • 추상 메서드는 구현부가 없고, 자식 클래스에서 반드시 구현하도록 강제한다.
abstract class Parent
{
    public abstract void Move()
}

public class Child
{
	public override void Move()
    {
        Console.WriteLine("자식이 걷는다.");
    }
}
Parent temp = new Child();
temp.Move() // 자식 클래스의 메서드 호출

Child temp = new Child();
temp.Move() 

오늘 개발한 내용

TextRPG

필수 요구사항 중 지금 상황에서 제일 완벽한 2개만 포스팅한다.

  • 게임 시작 화면
  • 상태보기

일단 전체 흐름을 담당하는 코드부터 만들었다.

enum Scenes
{
    None,
    Town,
    Status,
    Inventory,
    EquipManagement,
    Store,
}

internal class Program
{
    static void Main(string[] args)
    {
        Game game = new Game();
        while(true)
        {
            game.Process();
        }
    }
}

우선 Game 클래스를 만들어주고 게임의 process 함수를 Program클래스에서 무한 호출해준다.

class Game
{
    Scenes scenes = Scenes.Town;
    Player player = new Player();

    public void Process()
    {
        //현재 씬에 따라서 호출
        switch (scenes)
        {
            case Scenes.None:
                break;

            case Scenes.Town:
                Town();
                break;

            case Scenes.Status:
                Status();
                break;

            case Scenes.Inventory:
                Inventory();
                break;

            case Scenes.EquipManagement:
                EquipManagement();
                break;
        }
    }
}

현재의 Scenes가 열거형의 어떤 값인지에 따라서 각 씬의 함수를 호출한다.

1. 게임 시작 화면

게임 시작화면의 함수는 Town으로 이름지었다.

private void Town()
{
    //데이터
    string playerInput = "";

    //출력
    Console.Clear();
    Console.WriteLine("                      ..:::.                      ");
    Console.WriteLine("                     #@@@@@@%.                    ");
    Console.WriteLine("                      *@@@@%                      ");
    Console.WriteLine("                       %%%%.                      ");
    Console.WriteLine("                       *@@#                       ");
    Console.WriteLine("                      .=##+.                      ");
    Console.WriteLine("                   .+%@@%%@@@*:                   ");
    Console.WriteLine("                  -@@@@*#%#@@@@+                  ");
    Console.WriteLine("                  @@%##@@@@%#%@@:                 ");
    Console.WriteLine("                 =##@@@@@@@@@@%%*                 ");
    Console.WriteLine("                 -@*-=+#@@%+=-*@+                 ");
    Console.WriteLine("                 -@@#=. @@. -*@@=                 ");
    Console.WriteLine("                 %@@@@+.@@:-@@@@@.                ");
    Console.WriteLine("                 =@@@@+ #%.-@@@@*                 ");
    Console.WriteLine("            =*#   #@@@+    -@@@#  =.:-            ");
    Console.WriteLine("       ::---@@==.  *@@+    -@@#  --  %  :-.       ");
    Console.WriteLine("    :=++*#@#@@@=.   -%+    -@-  .  -*: :-.  .:    ");
    Console.WriteLine(" .*@@@@@@@@@@@*+#+:   :    .   .:--.     .:--=%+  ");
    Console.WriteLine(" #+-...:-=+*###=  .:.         .    .:--==-:...:=* ");

    Console.WriteLine("====================스파르타마을====================");
    Console.WriteLine("스파르타 마을에 오신 것을 환영합니다.");
    Console.WriteLine("던전으로 들어가기전 활동을 할 수 있습니다.");
    Console.WriteLine("===================================================");

    Console.WriteLine("1. 상태 보기");
    Console.WriteLine("2. 인벤토리");
    Console.WriteLine("3. 상점");

    Console.WriteLine("원하시는 행동을 입력해주세요.");
    Console.Write(">>");
            
    playerInput = Console.ReadLine();
    switch (playerInput)
    {
        case "1":
            scenes = Scenes.Status;
            break;

        case "2":
            scenes = Scenes.Inventory;
            break;

        case "3":
            scenes = Scenes.Store;
            break;

        default:
            Console.Clear();
            Console.WriteLine("잘못된 입력입니다.");
            Console.ReadLine();
            break;
    }

}

특별한 기능은 없고 선택한 번호에 따라서 현재 씬을 변경해준다.
그리고 Game 클래스의 Process 함수가 반환되고 다시 Program 클래스에서는 Process를 호출한다.
변경된 씬 값에 맞춰서 함수를 호출하도록 했다.

2. 상태 보기

private void Status()
{
    //데이터
    string playerInput = "";

    //출력
    Console.Clear();
    Console.WriteLine(
        "                                        \r\n" +
        "                -+#@@#+:                \r\n" +
        "               -@@@@@@@@.               \r\n" +
        "                *@@@@@@=                \r\n" +
        "                .@@@@@@                 \r\n" +
        "               :=@@@@@%=-               \r\n" +
        "            -#@@@@@@@@@@@@%=            \r\n" +
        "          .#@@@@@@@@@@@@@@@@%.          \r\n" +
        "          %@@%#@@@@@@@@@@@@@@%          \r\n" +
        "         =@%%@%@@@@@@@@@@@@@@@+         \r\n" +
        "         *@@@@@@@@@@@@@#@@@@@@#         \r\n" +
        "         :#@**%@@@@@@@@++%*+@#-         \r\n" +
        "           ==  :=%@@@@@+.  -+           \r\n" +
        "           %@#=   *@@#   ==%%           \r\n" +
        "           *@@@%. :@@= .%@@#*           \r\n" +
        "           =@@@@# -@@= #@@@@=           \r\n" +
        "           -@@@@@   .  @%@@@-           \r\n" +
        "            -%@@@.    .@%#%-            \r\n" +
        "              +@@-    -@@:              \r\n" +
        "               .**    **.               \r\n" +
        "                 :    :                ");
    Console.WriteLine("================ 상태창 ================");
    Console.WriteLine("캐릭터의 정보가 표시됩니다.");
    Console.WriteLine("========================================");

    Console.WriteLine($"Lv. {player.Level}");
    Console.WriteLine($"{player.Name} ({player.PlayerClass})");
    Console.WriteLine($"공격력 : {player.Attack}");
    Console.WriteLine($"방어력 : {player.Defence}");
    Console.WriteLine($"체력 : {player.Hp}");
    Console.WriteLine($"Gold : {player.Gold}");

    Console.WriteLine("\n0. 나가기");
    Console.WriteLine("원하시는 행동을 입력해주세요.");
    Console.Write(">>");
    playerInput = Console.ReadLine();
    switch (playerInput)
    {
        case "0":
            scenes = Scenes.Town;
            break;
    }
}

현재 플레이어의 상세 정보를 출력한다.
플레이어 클래스는 아래와 같다.

internal class Player
{
    public int Level { get; set; }
    public string Name { get; set; }
    public PlayerClass PlayerClass { get; set; }
    public float Attack { get; set; }
    public float Defence { get; set; }
    public float Hp { get; set; }
    public int Gold { get; set; }
    
    public List<Item> Inventory { get; set; }
    
    public Player()
    {
        Level = 1;
        Gold = 1500;
        Inventory = new List<Item>();
        
        SetInfo();
    }

    public void SetInfo()//지금은 하드 코딩이지만 나중에는 캐릭터 생성 창에서 정보 받아옴
    {
        Name = "레오니다스";
        PlayerClass = PlayerClass.Worrior;
        Attack = 10;
        Defence = 5;
        Hp = 100;
    }
}

나중에 캐릭터 생성, 저장 등의 기능을 위해서 SetInfo 함수를 만들어놨다.

일단 이 2개 정도만 확실히 만들어놨고 아이템 관리와 상점도 구현해야한다.
아이템을 어떤 식으로 구현할지에 대해서 오늘 시간을 너무 많이 썼는데 딱히 좋은 답이 나오지는 않았다.,, 너무 오래 고민하는 것도 좋지 않으니 로우하게 구현을 빨리 해야겠다.

profile
개발은삼순이발

0개의 댓글