Unity 내일배움캠프 TIL 0822 | 인벤토리 및 상점 출력 정렬 | 개인 프로젝트 완성 화면

cheeseonrose·2023년 8월 22일
0

Unity 내일배움캠프

목록 보기
16/89
post-thumbnail

잠을 잘 못잤는지 어깨가 빠질거 같다 ;ㅁ;

견뎌~.. 견뎌...!

못견뎌..털썩 ㅇ<-<


개인 과제 - 스파르타 던전 게임 만들기

구현

인벤토리 및 상점 출력 정렬하기

  • 처음에는 모든 줄의 정렬을 맞추고 싶었는데 중간에 다른 색으로 출력하는 경우도 있어서 어떻게 할까 고민을 좀 했다.
    근데 딱히 해결 방법이 안 떠오름..!!!! Console.WriteLine으로 출력할 때 뭔가 문자별로 색상을 지정할 수 있으면 될 것 같은데, 딱히 방법이 없어보였다.
  • 그래서 그냥 항목별로 길이만 맞추기로 함 ~.~
  • Extension.AlignmentPrint
    • 전에 만들었던 Extension.MakeDivider 함수는 삭제했다.
    • 대신 string 배열을 받아와서 형식에 맞게 정렬 출력하는 AlignmentPrint 함수를 만들었다.
    • 아이템 목록을 출력할 일은 인벤토리를 열 때, 상점을 열 때, 상점에서 아이템을 판매할 때로 3가지가 있는데 (겹치는건 제외)
      인벤토리의 경우는 출력할 요소가 3가지 (아이템 이름, 아이템 효과, 아이템 설명)
      나머지 두 경우는 출력할 것이 인벤토리 요소 3가지 + 아이템 가격 이렇게 총 4가지이다.
    • 아이템 이름, 효과, 설명, 가격을 각각 0~3에 대입
      -> text[0] 이면 이름, text[1]이면 효과 이런 식
    • 인자로 받아오는 type 값은 해당 아이템이 방어템인지 공격템인지 여부
    • 기본적으로 요소들은 왼쪽 정렬이며, 아이템 설명의 경우 30칸이 기준, 나머지는 10칸이 기준이다.
    • 기존에 MakeDivider 함수로 만들었던 노란색 구분자 "|"는 switch 문 밑에 넣어주고, 마지막 요소가 아닌 경우 출력하도록 했다.
const int LENGTH10 = 10;
const int LENGTH30 = 30;

public static void AlignmentPrint(string[] text, int type)
{
	int idx = 0;
    while (idx < text.Length)
    {
    	string curStr = text[idx];
        switch (idx)
        {
        	case 0:
            	Console.Write($" {curStr, -LENGTH10}");
                break;
            case 1:
            	Console.Write("   ");
            	int length = curStr.Length + 8;
            	if (type == 0) Console.Write("방어력 "); else Console.Write("공격력 ");
            	("+").PrintWithColor(ConsoleColor.Yellow, false);
            	curStr.PrintWithColor(ConsoleColor.Magenta, false);
            	while (12 - length >= 0)
            	{
            		Console.Write(" ");
            		length++;
            	}
            break;
            case 2:
            	Console.Write($"     {curStr, -LENGTH30}");
            	break;
            case 3:
            	bool isSoldOut = (curStr == "구매 완료");
            	("   " + curStr).PrintWithColor(isSoldOut ? ConsoleColor.Yellow : ConsoleColor.Magenta, false);
            	if (!isSoldOut) Console.Write(" G");
            break;
        }
        if (idx != text.Length - 1) ("|").PrintWithColor(ConsoleColor.Yellow, false);
        idx++;
    }
}
  • Player.DisplayItemInventory
    • 위의 함수는 아래와 같이 적용하였다. Player.DisplayPurchasedItem과 Store.DisplayStore에서도 같은 방식으로 적용!
    • 콘솔 출력으로 지저분한 코드를 함수 안에 다 때려넣으니 훨씬 간결해졌다!
      마치 창고방에 짐 다 때려넣는 내 모습처럼
// 플레이어의 현재 아이템 인벤토리 상태를 보여주는 함수
// type이 0이면 인벤토리, type이 1이면 인벤토리 - 장착 관리 상태
public void DisplayItemInventory(int type)
{
	Console.WriteLine("[ 아이템 목록 ]");
    int idx = 1;
    foreach (Item item in itemList)
    {
    	// 아이템 이름
        (" -").PrintWithColor(ConsoleColor.Yellow, false);
        // 장착 관리 상태일 경우 번호 표시
        if (type == 1) (" " + idx.ToString()).PrintWithColor(ConsoleColor.Magenta, false);
        if (item.IsEquipped) Console.Write(" [E] ");
        
        Extension.AlignmentPrint(new string[] { item.Name, item.Value.ToString(), item.Description }, item.Type);
        Console.WriteLine();
        
        idx++;
    }
}



실행 화면

처음 시작시 닉네임 입력

시작 화면

상태 보기

인벤토리

인벤토리 - 장착 관리

인벤토리 - 아이템 정렬

  • 순서대로 이름, 장착, 공격력, 방어력순 정렬 결과

상점

상점 - 아이템 구매

상점 - 아이템 판매

던전 입장

던전 결과

휴식하기

게임 저장

  • UserDatabase - Player 정보 저장
  • ItemSoldStateDatabase - 상점 아이템 판매 현황 저장



알고리즘 문제 풀이

저녁 먹고 알고리즘 문제 쪼끔 풀어봤다
맨날 자바로 풀다가 C#으로 풀려니 약간 어색하려나 했는데 다행히도 둘이 비슷해서 딱히 어려움은 없었다
일단은 내배캠 노션에 있는 문제 리스트부터 다 풀어보기로 했는데 완전 기초부터 있어서 빨리 풀고 지나가는게 나을듯!!

몫 구하기

  • 이건 뭐 설명할게 없..
static class Solution
{
	public static int solution(int num1, int num2)
    {
    	return (int)(num1 / num2);
    }
}

최빈값 구하기

  • Dictionary를 이용해 풀었다.
    Dictionary<int, int> 형태로 선언하고 array를 순회하면서 array의 요소를 Key 값으로, 요소가 이미 존재하면 +1 해주고 없으면 Value를 1로 하여 새로 추가하는 방식
  • 이후에 Dictionary를 순회하면서 최대값을 만날 때마다 max와 최대값의 개수인 count를 갱신해줬다.
  • 만약 순회가 끝난 뒤 count가 0이라면 최빈값을, 아니라면 최빈값이 여러개이므로 -1을 리턴했다.
public class Solution
{
	public static int solution(int[] array)
    {
    	int answer = 0;
        Dictionary<int, int> countNum = new Dictionary<int, int>();
        
        foreach (int i in array)
        {
        	int num = 0;
            if (countNum.TryGetValue(i, out num))
            {
            	countNum[i] += 1;
            }
          	else countNum.Add(i, 1);
        }
        
        int count = 0;
        int max = -1;
        foreach(KeyValuePair<int, int> entry in countNum)
        {
        	if (entry.Value > max)
            {
            	max = entry.Value;
                answer = entry.Key;
                count = 0;
            }
            else if (entry.Value == max) count++;  
        }
        
        return (count == 0) ? answer : -1;
    }
}

배열 두 배 만들기

  • 이것도 설명할게 없다!! 그냥 배열 새로 하나 생성하고 numbers 순회하면서 값 2배 해서 넣어준 뒤 리턴 끗
public class Solution
{
	public static int[] solution(int[] numbers)
    {
    	int[] answer = new int[numbers.Length];
        
        for (int i = 0; i < numbers.Length; i++)
        {
        	answer[i] = numbers[i] * 2;
        }
        return answer;
    }
}

배열 뒤집기

  • C#도 아마 Collection을 뒤집는 함수가 있겠지?!
  • 그치만 찾기 귀찮으니까 그냥 직접 뒤집는다!
  • answer의 인덱스는 0부터, num_list의 인덱스는 num_list.Length-1부터 시작해서 answer에 num_list의 요소들을 거꾸로 넣어주었다.
public class Solution
{
	public static int[] solution(int[] num_list)
    {
    	int[] answer = new int[num_list.Length];
        
        for (int i = 0, j = num_list.Length - 1; i < num_list.Length; i++, j--)
        {
        	answer[i] = num_list[j];
        }
        return answer;
    }
}



오늘 공부는 여기까지!!!
더 하고싶지만 어깨가 바스라질거 같다 X_X

개인 과제로 Firebase 통신도 해보고 싶었는데 아직은 쫌 더 공부해야 될 것 같다!!!
난 왜 이렇게 이게 헷갈리지~~~

암튼 끗 ~.~

0개의 댓글