
무한 강의 시청으로 몽롱한 상태에서, 아침부터 Text RPG 던전 게임 만들기라는 과제를 시작했다.
클래스, 객체, 프로퍼티, get & set, 필드 선언, 접근자, 제한자 기타 등등 이런 문법적인 개념이 아직도 긴가민가한 나로써는 너무 어지럽다.
동기 한 분이 구현 안되는 부분이 있다고 하셨는데 나도 크게 도움이 되거나 제대로 설명해주지 못해 미안할 따름.
내 방식이 완벽하고 정확한 정보가 아니다보니 선뜻 알려 드리기 힘들다.
같은 조에서 완성하신 분 코드와 이야기를 들어보니 특정 클래스를 만들고 아이템 같은 경우 구조체를 만들어서 그걸 불러오는 식으로 깔끔하게 구현 하셨는데 봐도 모르겠다 아직 😂
일단 게임의 큰 틀을 다시 생각해보면..
플레이어
아이템
몬스터 (가능 하다면)
internal class Program
{
// 플레이어 정보
static int Level = 1;
static string PlayerName;
static string Job = "백수";
static int Att = 10;
static int Def = 5;
static int Hp = 100;
static int Gold = 1500;
일단 가장 위에 만들어 주었음, 아직 따로 클래스를 만들지는 않았음..
현재는 상태창에 불려가서 사용되는 중
public class Item // 아이템 클래스
{
public string ItemName { get; set; } // 아이템 이름
public string ToolTip { get; set; } // 아이템 설명
public int Attack { get; set; } // 공격력
public int Defense { get; set; } // 방어력
public int Price { get; set; } // 템 가격
public bool Purchase { get; set; } // 구매 여부 bool
public Item(string itemName, string toolTip, int attack, int defense, int price) // 아이템 클래스 생성자
{
ItemName = itemName;
ToolTip = toolTip;
Attack = attack;
Defense = defense;
Price = price;
Purchase = false;
}
아이템 클래스와 생성자를 만들어 주는 중.
상점 아이템 목록에 쓰이고는 있는데
아직 제대로 된 활용은 못하는 중
static void Main(string[] args)
{
Console.WriteLine("맨땅에 헤딩 마을에 오신 것을 환영합니다.\n");
Console.Write("당신의 이름은 무엇입니까? : ");
PlayerName = Console.ReadLine();
Console.WriteLine();
Stage stage = new Stage(); // Stage 클래스 안에 getSelect()를 호출
stage.getSelect();
}
메인 화면,
이름을 입력하여 기억하고 stage.getSelect();를 통해
다음 선택 페이지 (.4 참고) 로 넘어감
public class Stage
{
public void getSelect() // 플레이어 행동 선택
{
while (true) // 선택 루프 시작
{
Console.Clear();
Console.WriteLine($"안녕하세요, {PlayerName}님!\n");
Console.WriteLine();
Console.WriteLine("1. 상태 보기\n");
Console.WriteLine("2. 인벤토리\n");
Console.WriteLine("3. 상점\n");
Console.WriteLine("4. 던전 입장\n");
Console.WriteLine("5. 휴식하기 \n");
Console.WriteLine("6. 게임 저장\n");
Console.WriteLine();
Console.WriteLine("원하시는 행동을 입력해주세요.\n");
if (int.TryParse(Console.ReadLine(), out int selectInput)) // out = selectinput 변수 선언
{
switch (selectInput)
{
case 1:
PlayerInfo();
break;
case 2:
Inventory();
break;
case 3:
Store();
break;
case 4:
Dungeon();
break;
case 5:
Rest();
break;
case 6:
SaveGame();
break;
}
if (selectInput >= 1 && selectInput <= 6) // 1이상 6이하면 루프 종료
break;
}
else
{
Console.WriteLine("잘못된 입력입니다. '1' 에서 '6' 사이의 숫자를 입력하세요.");
// 안돼 돌아가 다시 선택
}
}
}
메인에서 이름을 정한 후 플레이어의 행동을 정할 수 있는 함수, while문을 사용하여 선택지에 없으면 화면을 다시 갱신되게 함.
if Switch문을 사용해 각 메뉴까지는 어떻게 진입하게는 했음.
public void BackSelect() // 각 옵션에서 0. 나가기 , 다만 userInput때문에 0을 한 번 더 입력해야해서 추후 수정해야 함.
{
while (true)
{
if (int.TryParse(Console.ReadLine(), out int userInput))
{
if (userInput == 0)
{
getSelect();
break;
}
else
{
Console.WriteLine("잘못된 입력입니다. 숫자만 입력하세요.");
}
}
}
}
선택지가 하나만 있을 때 (나가기) 할 수 있도록 함수를 만들었는데 현재 쓰일 일이 적음.
그리고 각 기능 페이지에 이 함수를 각각 넣어놨더니 나가기를 하려해도 0 + enter(입력)을 두 번 해야하는 문제가 발생해서 그 부분을 수정하거나 개선해야 함.
원인은 기능 페이지의 마지막 나가기에도,
이 함수 안에도 readline으로 입력해야 하는 값이 있어서.. 2번 작동한다고 보면 되는듯.
public void PlayerInfo() // 1. 플레이어 상태창
{
Console.Clear(); // 텍스트 초기화 한 번
Console.WriteLine("\n[ 플레이어 스탯 ]\n");
Console.WriteLine($" Lv. {Level:D2}\n"); //level 옆에 D2 -> 1이 아닌 01로 표시 (두 자릿수)
Console.WriteLine($" 이름 : {PlayerName} ({Job})\n");
Console.WriteLine($" 공격력 : {Att}\n");
Console.WriteLine($" 방어력 : {Def}\n");
Console.WriteLine($" 체력 : {Hp}\n");
Console.WriteLine($" Gold : {Gold} G\n");
Console.WriteLine(" 원하시는 행동을 입력해주세요.\n");
Console.WriteLine(" 0. 나가기\n");
BackSelect(); // 다시 메인 화면
}
정보만 표시되고 있고 현재 아이템 장착으로 인한 스테이터스 변동은 미구현
public void Inventory() // 2. 인벤토리
{
Console.Clear();
Console.WriteLine("[ 인벤토리 ]\n보유 중인 아이템을 관리 할 수 있습니다.\n");
Console.WriteLine("[아이템 목록]\n");
Console.WriteLine(" 원하시는 행동을 입력해주세요.\n");
Console.WriteLine(" 0. 나가기\n 1. 장착 관리\n");
while (true)
{
if (int.TryParse(Console.ReadLine(), out int invenInput)) // 0,1 중에 택1
{
if (invenInput == 0)
{
getSelect(); // 0. 나가기
break;
}
else if (invenInput == 1)
{
WearItem(); // 1. 장착 관리
break;
}
else
{
Console.WriteLine("잘못된 입력입니다. 숫자만 입력하세요.");
}
}
}
}
public void WearItem() // 2-1 인벤토리 아이템 장착
{
Console.Clear();
Console.WriteLine("test");
}
상점부터 완성해야 하는데 막힌 부분이 있어 현재 미완성
아이템 장착 기능 및 정보 표시를 구현해야 함.
public void Store() // 3. 상점
{
Console.Clear();
Console.WriteLine("[ 상점 ]\n보유 중인 아이템을 관리 할 수 있습니다.\n");
Console.WriteLine("[보유 골드]");
Console.WriteLine($"{Gold} G\n");
List<Item> items = new List<Item> // 아이템 리스트
{
new Item(" 너덜너덜한 갑옷 ", "방어력 +3, 너무 오래 되서 다 뜯어져 있다.", 0 , 2, 1000),
new Item(" 평범한 갑옷 ", "방어력 +6, 그럭저럭 입을만해 보인다.", 0, 6, 1500),
new Item(" 고오급 갑옷 ", "방어력 +10, 그나마 괜찮아보이는 갑옷이다.", 0, 10, 3000),
new Item(" 나뭇가지 ", "공격력 +2, 회초리로는 쓸만한 것 같다.", 2, 0, 500),
new Item(" 살짝 휜 목검 ", "공격력 +5, 몇 번 휘두르면 부러질 것 같다 .", 5, 0, 1000),
new Item(" 날카로운 죽창 ", "공격력 +7, 너도 나도 한 방에 갈 것 같은 대나무 창이다.", 7, 0, 2000)
};
Console.WriteLine("[ 아이템 목록 ]");
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"{i + 1}. {items[i].ItemName} | {items[i].ToolTip} | {items[i].Price}G{(items[i].Purchase ? " - 구매 완료" : "")}");
}
foreach (var item in items) // purchase 구매 기능 초기화
{
item.Purchase = false;
}
Console.WriteLine();
Console.WriteLine(" 원하시는 행동을 입력해주세요.\n");
Console.WriteLine(" 0. 나가기\n 1. 아이템 구매\n");
while (true)
{
if (int.TryParse(Console.ReadLine(), out int storeInput)) // 0,1 중에 택1
{
switch (storeInput)
{
case 0:
getSelect(); // 0. 나가기
break;
case 1:
BuyItem(items); // 3-1. 아이템 구매 ()에 items 넣어줌
break;
default:
Console.WriteLine("잘못된 입력입니다. 유효한 번호를 입력하세요.\n");
continue; // 다시 루프
}
}
}
}
public void BuyItem(List<Item> items) // 3-1. 아이템 구매
{
while (true)
{
Console.Clear();
Console.Clear();
Console.WriteLine("[ 상점아이템 구매 ]\n보유하신 골드로 아이템을 구매 할 수 있습니다.\n");
Console.WriteLine("[보유 골드]");
Console.WriteLine($"{Gold} G\n");
Console.WriteLine("[ 아이템 목록 ]");
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"{i + 1}. {items[i].ItemName} | {items[i].ToolTip} | {items[i].Price}G{(items[i].Purchase ? " - 구매 완료" : "")}");
}
Console.WriteLine("\n구매하실 아이템의 번호를 입력하세요. 0은 뒤로 가기 입니다.");
if (int.TryParse(Console.ReadLine(), out int itemInput) && itemInput >= 0 && itemInput <= items.Count)
{
if (itemInput == 0)
{
Store(); // 나가기
break;
}
else
{
Item buyItems = items[itemInput - 1]; // 1번 선택 = 0번 인덱스
if (buyItems.Purchase)
{
Console.WriteLine("이미 구매한 아이템입니다.\n");
}
else if (Gold >= buyItems.Price)
{
Console.WriteLine("구매를 완료했습니다.\n");
Gold -= buyItems.Price;
buyItems.Purchase = true;
}
else
{
Console.WriteLine("골드가 부족합니다.\n");
}
}
Console.WriteLine("\n아무 키나 누르면 돌아갑니다. ");
Console.ReadKey(); // 키를 누를 때까지 대기, 글자가 자꾸 사라져서..
}
else
{
Console.WriteLine("잘못된 입력입니다. 아무 키나 누르면 돌아갑니다.");
Console.ReadKey();
}
}
}
오늘 가장 시간을 많이 갈아넣은 구역,
무지성 조건문들을 활용하다보니 갓 시골 상경한 시골 사람이 지하철 처음타는 것처럼 아찔하다.
구매완료까지는 잘 표시가 되지만, 상점 창으로 돌아가거나 구매 페이지로 다시 돌아가면 구매 완료가 사라지고 있다.
이 부분은 클래스 화 해둔 아이템을 어떻게 잘 하면 될 듯 한데..
아니면 bool을 써야 하나? 뭐든 다 해보고 있다.
public void Dungeon() // 4. 던전
{
Console.Clear();
BackSelect();
}
public void Rest() // 5. 휴식
{
Console.Clear();
}
public void SaveGame() // 6. 게임 저장
{
Console.Clear();
BackSelect();
}
현재 미구현된 녀석들, 휴식하기 기능은 가능 할 것 같은데 던전이랑 게임 저장은 내일까지 마칠 수 있을지 미지수지만 끝까지 최선을 다 해야겠다..
오늘 switch나 break;, if else등 조건문들은 어느 정도 활용법을 익히게 된 듯 한데 아직 클래스를 만들어서 인스턴스를 생성하고 이걸 어떻게 활용하는지 코드가 길어질 수록 쉽게 감이 잡히지 않는다.
아이템 리스트를 만들고 어찌저찌 불러왔는데 디테일한 부분의 변경과 데이터의 보존에서 애를 먹고 있다.
내일은 9시간 밖에 시간이 없으니 기본 기능 + 추가 기능을 1개 이상 완성하여 제출하는 것을 목표로 해야겠다.
다른 동기분들께 도움도 드릴 수 있도록.