오늘은 어제에 이어서 C#을 공부하고, C#을 이용한 TextRPG를 구상해 볼 예정이다.
[접근 제한자] [리턴 타입] [메서드 이름]([매개변수)]
{
//메서드 실행 코드
}
public int AddNumbers(int a, int b)
{
int sum = a + b;
return sum;
}
AddNumbers(10,20) // 호출
public,private,protected 등)void 사용){}안에 메서드가 수행하는 작업을 구현하는 코드 작성void PrintMessage(string message)
{
Console.WriteLine("Message: " + message);
}
void PrintMessage(int number)
{
Console.WriteLine("Number: " + number);
}
// 메서드 호출
PrintMessage("Hello, World!"); // 문자열 매개변수를 가진 메서드 호출
PrintMessage(10); // 정수 매개변수를 가진 메서드 호출
void CountDown(int n)
{
if (n <= 0)
{
Console.WriteLine("Done");
}
else
{
Console.WriteLine(n);
CountDown(n - 1); // 자기 자신을 호출
}
}
// 메서드 호출
CountDown(5);
struct 키워드를 사용하여 선언. 접근할 때 .연산자를 사용한다.struct Person
{
public string Name;
public int Age;
public void PrintInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
Person person1;
person1.Name = "John";
person1.Age = 25;
person1.PrintInfo();
배운 C#문법을 토대로 C#을 이용한 TRPG를 구성해보겠다. 과제의 필수 기능부터 어떻게 구현하면 좋을지 구상해보겠다.
Console.WriteLine()을 이용해 출력한다.input 변수를 선언하고 플레이어가 입력하는 문자를 숫자로 변환 후 inputNumber에 저장한다.while문 안에 숫자를 입력받고 실행하는 스크립트를 작성한다. if문을 사용하여 해당하지 않는 숫자나 문자 입력 시 "잘못된 입력입니다"라는 텍스트를 출력한다.Console.WriteLine("스파르타 마을에 오신 여러분 환영합니다.");
Console.WriteLine("이곳에서 던전으로 들어가기 전 활동을 할 수 있습니다.\n");
Console.WriteLine("1. 상태 보기");
Console.WriteLine("2. 인벤토리");
Console.WriteLine("3. 상점");
Console.WriteLine("\n원하시는 행동을 입력해주세요");
string input = Console.ReadLine();
int inputNumber;
if (int.TryParse(input, out inputNumber))
{
Console.WriteLine("입력하신 번호는: " + inputNumber);
}
if문과 while문을 사용한다. 이 스크립트를 추가하였다. if (int.TryParse(input, out inputNumber))
{
if (inputNumber >= 1 && inputNumber <= 3)
{
Console.WriteLine($"입력하신 숫자는 {inputNumber]입니다.")
}
else
{
Console.WriteLine("1~3 사이의 숫자를 입력해주세요.");
}
}
else
{
Console.WriteLine("잘못된 입력입니다. 숫자를 입력해주세요.");
}
Player.cs라는 하나의 파일에서 관리할 예정이다.//Player.cs
public class Player
{
public string Name = "Chad";
public string Job = "전사";
public int Level = 1;
public int Hp = 100;
public int Atk = 10;
public int Def = 5;
public int Gold = 1500;
}
상태, 인벤토리 등의 화면으로 넘어가기 위해 switch 문이 적절할 것이라 생각한다.inputNumber에 따라 다른 화면으로 넘어가고, 각 화면은 서로 다른 항목에서 클래스로 관리하는 방식이 편할 것이라 생각했다.MainScene에서 각 항목으로 넘어가기 위한 switch문을 작성하겠다.//MainScene.cs
if (int.TryParse(input, out inputNumber))
{
switch (inputNumber)
{
case 1:
Status.Show(); // 상태 보기 화면
break;
case 2:
Inventory.Show(); // 인벤토리 화면
break;
case 3:
Shop.Show(); // 상점 화면
break;
default:
Console.WriteLine("1~3 사이의 숫자를 입력해주세요.");
break;
}
}
else
{
Console.WriteLine("잘못된 입력입니다. 숫자를 입력해주세요.");
}
Show()함수를 생성하여 각 화면으로 넘어갈 수 있도록 만들겠다. Status.cs를 예시로 작성해보겠다.//Status.cs
public class Status
{
private Player player;
public void Show()
{
while (true)
{
Console.Clear();
Console.WriteLine("상태 보기");
Console.WriteLine("캐릭터의 정보가 표시됩니다.\n");
Console.WriteLine($"Lv. {player.Level.ToString("D2")}");
Console.WriteLine($"{player.Name} ( {player.Job} )");
Console.WriteLine($"공격력 : {player.Atk}");
Console.WriteLine($"방어력 : {player.Def}");
Console.WriteLine($"체 력 : {player.Hp}");
Console.WriteLine($"Gold : {player.Gold} G\n");
Console.WriteLine("0. 나가기");
Console.WriteLine("\n원하시는 행동을 입력해주세요.");
Console.Write(">> ");
string input = Console.ReadLine();
if (input == "0")
break;
else
Console.WriteLine("\n잘못된 입력입니다. 다시 시도해주세요.");
}
Console.Clear();
}
}
//MainScene
{
private Player player;
private Status status;
private Inventory inventory;
private Shop shop;
public MainScene(Player player)
{
this.player = player;
this.status = new Status(player);
this.inventory = new Inventory(player);
this.shop = new Shop(player);
}
//Status.cs 예시
public class Status
{
private Player player;
public Status(Player player)
{
this.player = player;
}
프로그램에는 진입점에 적합한 정적 'Main' 메서드가 포함되어 있지 않습니다.static 키워드를 사용하는 예를 보며 static 키워드의 개념에 대해 좀 더 자세히 배워보기로 했다.static 키워드의 개념과 활용static 키워드는 객체를 불러오지 않아도 뒤에 수식하는 메서드를 활용할 수 있게 해주는 키워드이다.new 키워드를 통해 생성하고 불러왔는데, static 키워드를 사용하면 그러지 않고도 쉽게 공유 및 접근이 가능해진다.static이란?static 키워드는 클래스의 인스턴스(객체)를 생성하지 않아도 클래스 자체에서 접근할 수 있도록 만들어주는 키워드다. 쉽게 말해, new 없이 클래스 이름만으로 변수나 메서드에 접근할 수 있게 된다.public static class Game
{
public static void PrintLine()
{
Console.WriteLine("============");
}
}
// 호출
Game.PrintLine(); // new 없이 바로 호출 가능
static은 클래스, 메서드, 변수, 속성 등 다양한 곳에 사용할 수 있으며, 프로그램 전역에서 공유되어야 하는 값이나 기능에 자주 사용된다.static의 대표적인 사용 사례static void Main(string[] args)
{
// 프로그램 실행 시작
}
내가 static에 대해 자세히 배우게 된 계기이다. Main() 메서드는 C# 프로그램의 진입점이다. 이 메서드는 static으로 선언되어야만 컴파일러가 프로그램을 시작할 수 있다. 이 구조 덕분에 객체를 생성하지 않아도 프로그램이 실행될 수 있다.
public static class MathUtil
{
public static int Add(int a, int b)
{
return a + b;
}
}
int sum = MathUtil.Add(10, 20); // 객체 없이 직접 호출
public class GameManager
{
public static int TotalGold = 0;
}
static의 장점사실 나는 Unity 프로젝트를 진행하면서도 무심코 static을 써왔지만, 이번 텍스트 RPG 프로젝트를 하며 static의 개념을 명확히 이해하게 되었다. "언제 어떻게 static키워드를 써야 하는가?"를 알고 설계하는 것이 중요하다고 생각한다.
이후 나는 지금까지 제작한 프로젝트를 static 키워드를 사용한 형태로 갈아엎기로 결정했다.
Main() 메서드를 실행하는 스크립트를 작성한다.using System;
public class Program
{
static void Main(string[] args)
{
// 게임 시작
MainScene.Start();
}
}
public static class MainScene
{
public static void Start()
{
int inputNumber = 0;
while (true)
{
Console.WriteLine("스파르타 마을에 오신 여러분 환영합니다.");
Console.WriteLine("이곳에서 던전으로 들어가기 전 활동을 할 수 있습니다.\n");
Console.WriteLine("1. 상태 보기");
Console.WriteLine("2. 인벤토리");
Console.WriteLine("3. 상점");
Console.WriteLine("\n원하시는 행동을 입력해주세요");
Console.Write(">> ");
string input = Console.ReadLine();
if (int.TryParse(input, out inputNumber))
{
switch (inputNumber)
{
case 1:
Status.Show();
break;
case 2:
Inventory.Show();
break;
case 3:
Shop.Show();
break;
default:
Console.WriteLine("1~3 사이의 숫자를 입력해주세요.");
break;
}
}
else
{
Console.WriteLine("잘못된 입력입니다. 숫자를 입력해주세요.");
}
Console.WriteLine();
}
}
}
Player.cs를 수정했다.public static class Player
{
public static string Name = "Chad";
public static string Job = "전사";
public static int Level = 1;
public static int Hp = 100;
public static int MaxHp = 100;
public static int Atk = 10;
public static int Def = 5;
public static int Gold = 1500;
}
public static class Status
{
public static void Show()
{
while (true)
{
Console.Clear();
Console.WriteLine("상태 보기");
Console.WriteLine("캐릭터의 정보가 표시됩니다.\n");
Console.WriteLine($"Lv. {Player.Level.ToString("D2")}");
Console.WriteLine($"{Player.Name} ( {Player.Job} )");
Console.WriteLine($"공격력 : {Player.Atk}");
Console.WriteLine($"방어력 : {Player.Def}");
Console.WriteLine($"체 력 : {Player.Hp} / {Player.MaxHp}");
Console.WriteLine($"Gold : {Player.Gold} G\n");
Console.WriteLine("0. 나가기");
Console.WriteLine("\n원하시는 행동을 입력해주세요.");
Console.Write(">> ");
string input = Console.ReadLine();
if (input == "0")
break;
else
Console.WriteLine("\n잘못된 입력입니다. 다시 시도해주세요.");
}
Console.Clear();
}
}
public static class Inventory
{
public static void Show()
{
while (true)
{
Console.Clear();
Console.WriteLine("인벤토리");
Console.WriteLine("보유 중인 아이템을 관리할 수 있습니다.\n");
Console.WriteLine("0. 나가기");
Console.WriteLine("\n원하시는 행동을 입력해주세요.");
Console.Write(">> ");
string input = Console.ReadLine();
if (input == "0")
break;
else
Console.WriteLine("\n잘못된 입력입니다. 다시 시도해주세요.");
}
Console.Clear();
}
}
public static class Shop
{
public static void Show()
{
while (true)
{
Console.Clear();
Console.WriteLine("상점");
Console.WriteLine("필요한 아이템을 얻을 수 있는 상점입니다.\n");
Console.WriteLine("0. 나가기");
Console.WriteLine("\n원하시는 행동을 입력해주세요.");
Console.Write(">> ");
string input = Console.ReadLine();
if (input == "0")
break;
else
Console.WriteLine("\n잘못된 입력입니다. 다시 시도해주세요.");
}
Console.Clear();
}
}
수정 이후 실행했더니 의도한대로 화면이 실행됨을 확인했다.

이후 나는 처음 플레이를 할 때 플레이어의 이름을 직접 입력받는 기능을 구현하고 오늘의 실습을 마치기로 했다.
PlayerSetup.cs를 생성하고, 입력받은 이름을 Player.Name에 저장하는 스크립트를 작성했다.using System;
public static class PlayerSetup
{
public static void Start()
{
Console.Clear();
Console.WriteLine("원하시는 이름을 입력해주세요:");
Console.Write(">> ");
string input = Console.ReadLine();
Player.Name = input;
Console.WriteLine($"\n환영합니다, {Player.Name}님!");
Console.WriteLine("아무 키나 눌러 스파르타 마을로 이동합니다...");
Console.ReadKey();
Console.Clear();
}
}
이후 Program.cs에서 PlayerSetup.Start()가 먼저 실행되도록 수정했다.
실행 후, 의도한 대로 작동되고 있음을 확인했다.
이후 이 스크립트를 통해서 초기 값(ex: 직업, 능력치 분배 등)을 조정할 수 있을 것이다.
static 키워드를 제대로 배우고 나니 지금까지 썼던 스크립트들에 대한 막연한 이해가 조금 더 명확해졌다.