> 구조

- 좌표를 가지는 구조체 백터

- 게임 오브젝트가 구조체 멤버로 가짐

- 캐릭터와 타일은 게임오브젝트를 상속받고 캐릭터는 좌표값을 받아 위치 값을 설정 할 수 있다.

 


내용 추가

 


> 맵 좌표

 

 

> 튜플 (인덱스 <=> 포지션)

 

> 매개변수 한정자

더보기

 

해설 코드

int initializeInMethod;
OutArgExample(out initializeInMethod);
Console.WriteLine(initializeInMethod);     // value is now 44

void OutArgExample(out int number)
{
    number = 44;
}

※ out 키워드를 사용하면 참조를 통해 인수를 전달할 수 있습니다.

 

 

1. Year 활용

 System.DateTime endDate = new System.DateTime(2020, 4, 30);
 //endDate 원하는 년,월,일 생성
 	TimeSpan ddayDate = endDate - DateTime.Now;
 // 현재데이터와 연산하여 TimeSpan에 남은 day를 알 수 있다.
 
 /*
   ddayDate.Days 일
   ddayDate.Hours 시간 
   ddayDate.Minutes 분  
   ddayDate.Seconds 초 남음
 */

2. 문자열 -> DateTime

-  년,월,일 구분값은 [스페이스값],[/],[-] 으로만 구분가능하다. 

public void ToDateTimeTest1()
{
    DateTime dti01 = Convert.ToDateTime("2015 11 13");      //변환 가능 (2015년 11월 13일 오후 12:00:00)
    DateTime dti02 = Convert.ToDateTime("2015-11-13");      //변환 가능 (2015년 11월 13일 오후 12:00:00)
    DateTime dti03 = Convert.ToDateTime("2015/11/13");      //변환 가능 (2015년 11월 13일 오후 12:00:00)
    DateTime dti04 = Convert.ToDateTime("2015-11/13");      //변환 가능 (2015년 11월 13일 오후 12:00:00)
    DateTime dti05 = Convert.ToDateTime("2015/11 13");      //변환 가능 (2015년 11월 13일 오후 12:00:00)
    DateTime dti06 = Convert.ToDateTime("20151113");        //에러 (구분값 없음)
    DateTime dti07 = Convert.ToDateTime("2015_11_13");      //에러 (구분값 에러)
    DateTime dti08 = Convert.ToDateTime("2015:11:13");      //에러 (구분값 에러 :는 시간에서 사용가능)
}

3. 데이터 보기 좋게 가공

        public void test()
        {
            var result = DateTime.Now.ToString("yyyy-MM-dd HH:mm:s");
            Console.WriteLine(result);
        }


 

2. Timer 는 테스트 후 다시 기록하기로 한다.

 

 

1. 라이브러리로 생각되긴하는데, C#에서의 솔루션용 Nuget 패키지 의미를 잘모르겠다.

 

using Newtonsoft.Json;

 


2. File 클래스를 사용하려면 추가

using System.IO;

> 읽기 활용

1. 바로 해당 인스턴스 Dictionary로 전환

 try
            {
                path = "./data/hero_data.json";
                if (File.Exists(path))
                {
                    json = File.ReadAllText(path);
                    this.dicHeroData = JsonConvert
                        .DeserializeObject<HeroData[]>(json)
                        .ToDictionary(x => x.id, x => x);
                }
                //Newtonsoft.Json 축약가능 using Newtonsoft.Json; 하면

 

2. 배열타입 인스턴스에서 다시 Dictionary로 전환

  var json = File.ReadAllText("./achievement_data.json");
            var arrAchievementDatas = JsonConvert.DeserializeObject<AchievementData[]>(json);
            foreach (var data in arrAchievementDatas) {
                this.dicAchievementDatas.Add(data.id, data);
            }

 


> 쓰기

        public void Save()
        {
            try
            {
                var json = JsonConvert.SerializeObject(this);
                File.WriteAllText("./info/info.json", json);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }

 


> 폴더 생성

            DirectoryInfo folder = new DirectoryInfo("./info");
            if (!folder.Exists)
            {
                folder.Create();
            }

'c# 강의 > 수업내용(문법 관련)' 카테고리의 다른 글

20200505 - 2차원 배열 (캐릭터 이동)  (0) 2020.05.06
DateTime / Timer 활용  (0) 2020.04.29
20200428 - 문자열 콤마 찍기  (0) 2020.04.28
20200427 - 싱글톤  (0) 2020.04.28
20200423 - Achievement  (0) 2020.04.23
 string money = String.Format("{0:#,###}", data[key].price);


- 맴버로 private static 자신 타입 변수 준비(인스턴스) 

 class DataManager
    {
        private static DataManager singleTone;
        
        private Dictionary<int, HeroData> dicHeroData;
        private Dictionary<int, CurrencyData> dicCurrencyData;
        private Dictionary<int, ItemData> dicItemData;


- 생성자 private 으로 선언 및  컬렉션 초기화

 private DataManager()
        {
            this.dicCurrencyData = new Dictionary<int, CurrencyData>();
            this.dicItemData =  new Dictionary<int, ItemData>();
            this.dicHeroData = new Dictionary<int, HeroData>();
        }

 

- GetInstance 메소드 준비

        public static DataManager GetInstance()
        {
            if (DataManager.singleTone == null)
            {
                DataManager.singleTone = new DataManager();
                return DataManager.singleTone;
            }
            else
            {
                return DataManager.singleTone;
            }
        }

JSON Data

 

 

 


 

 

> AchievementInfo.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200423
{
    class AchievementInfo
    {
        public int id;
        public int count;

        public AchievementInfo() { }

        public AchievementInfo(int id, int count)
        {
            this.id = id;
            this.count = count;
        }
    }
}

 

> AchievementData.cs

더보기
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _20200423
{
    class AchievementData
    {
        public int id;
        public string name;
        public int reward_type;
        public int reward_amount;
        public int goal;
        public string desc;
    }
}

 

> App.cs

더보기
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace _20200423
{
    class App
    {
        Dictionary<int, AchievementData> dicAchievementDatas;
        Dictionary<int, AchievementInfo> dicAchievementInfos;

        public App()
        {
            this.dicAchievementDatas = new Dictionary<int, AchievementData>();
            this.dicAchievementInfos = new Dictionary<int, AchievementInfo>();
            // data 파일 로드
            this.DataFileLoad();

            this.DoAchievement(1000);
            this.PrintAllActhievement();
            this.SaveAchievements();
            this.PrintAllActhievement();
        }

        public void DataFileLoad()
        {
            string json = "";
            string dataPath = "./data/achievement_data3.json";

            if (File.Exists(dataPath))
            {
                Console.WriteLine("data 파일있음");
                try
                {
                    json = File.ReadAllText(dataPath);
                    Console.WriteLine(json);

                    AchievementData[] achievementDatas = JsonConvert.DeserializeObject<AchievementData[]>(json);

                    foreach (var data in achievementDatas)
                    {
                        this.dicAchievementDatas.Add(data.id, data);
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("achievement_data3.json 파일 불러오기 실패");
                    throw;
                }
                InfoFileLoad();
            }
            else
            {
                Console.WriteLine("data 파일 없음");
            }
            Console.WriteLine();
        }

        public void InfoFileLoad()
        {
            string infoJson = "";
            string infoPath = "./info/achievement_info.json";

            if (File.Exists(infoPath))
            {
                Console.WriteLine("info 파일 있음");
                Console.WriteLine("ㅡㅡㅡ 기존유저 ㅡㅡㅡ");
                try
                {
                    infoJson = File.ReadAllText(infoPath);
                }
                catch (Exception)
                {
                    Console.WriteLine("achievement_info.json 파일 불러오기 실패");
                    throw;
                }

                // 문자열 -> 객체 (역직렬화)
                AchievementInfo[] arrInfos = JsonConvert.DeserializeObject<AchievementInfo[]>(infoJson);

                foreach (var info in arrInfos)
                {
                    this.dicAchievementInfos.Add(info.id, info);
                }
                Console.WriteLine(infoJson);
            }
            else
            {
                Console.WriteLine("info 파일 없음");
                Console.WriteLine("ㅡㅡㅡ 신규유저 ㅡㅡㅡ");

                // info 객체 생성하고 사전에 추가
                foreach (var pair in this.dicAchievementDatas)
                {
                    Console.WriteLine($"{pair.Key} / {pair.Value}");

                    AchievementData data = pair.Value;

                    AchievementInfo info = new AchievementInfo(data.id, 0);
                    this.dicAchievementInfos.Add(info.id, info);
                } //forEach end
                // 업적 저장하기
                this.SaveAchievements();
            }
            Console.WriteLine();
        }

        public void DoAchievement(int id)
        {
            var data = this.dicAchievementDatas[id];
            Console.WriteLine($"{this.dicAchievementDatas[id].name} 업적을 1개 했습니다.");

            var info = this.dicAchievementInfos[id];

            if (info.count >= data.goal)
            {
                Console.WriteLine("해당 업적은 완료되었습니다.");
                return;
            }

            info.count += 1;
            //info객체의 count값을 출력한다.
            Console.WriteLine("id: {0} name: {1} goal: {2}/{3}", data.id, data.name, info.count, data.goal);
            Console.WriteLine();
        }


        // 업적 저장
        public void SaveAchievements()
        {
            // 사전에 있는 info 객체 배열에 담는다.
            var length = this.dicAchievementInfos.Count;

            AchievementInfo[] arr = new AchievementInfo[length];
            int index = 0;
            foreach (var pair in this.dicAchievementInfos)
            {
                arr[index++] = pair.Value;
            }

            // 배열 확인
            foreach (var info in arr)
            {
                var format = string.Format($"id: {info.id} count: {info.count}");
                Console.WriteLine(format);
            }

            // 객체 -> json 형식의 문자열로 반환
            string json = JsonConvert.SerializeObject(arr);
            Console.WriteLine("json 으로 변환");
            Console.WriteLine(json);

            //파일 저장
            string path = "./info/achievement_info.json";

            try
            {
                File.WriteAllText(path, json);
            }
            catch (Exception)
            {
                Console.WriteLine("info 파일쓰기 에러");
                throw;
            }
            Console.WriteLine();
        }

        public void PrintAllActhievement()
        {
            Console.WriteLine("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
            var data = this.dicAchievementDatas;
            var info = this.dicAchievementInfos;

            foreach (var item in data)
            {
                var completMsg = info[item.Key].count >= item.Value.goal ? "완료" : "미완료";
                Console.WriteLine($"[{item.Key}] / [{item.Value.name}] / [{item.Value.desc}] / [({info[item.Key].count}/{item.Value.goal})] / {completMsg}");
            }
            Console.WriteLine();
        }
    }
}

 

> 일반배열

   string[] testList = new string[10];
            testList[0] = "일";
            testList[1] = "이";

            foreach (string item in testList)
            {
                int index = Array.IndexOf( testList, item ); 
            }

 

> 나중에 분명히 잊고 찾을 것 같아 기록해둔다. 

        public App()
        {
            int result = (int)Enum.Parse(typeof(Days), "Friday");
            Console.WriteLine(result);

            var result2 = Enum.Parse(typeof(Days), "Friday");
            Console.WriteLine(result2);
            Console.WriteLine(result2.ToString());

        }

 

 

 enum Days { Monday, Tuesday, Wedneday, Thursday, Friday, Saturday, Sunday }

> Enum.GetValues() 받는 타입을 int 줄경우 인덱스를 출력 할 수 있다. 

            foreach (int r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine(r);
            }

 

> Enum 타입이나, var 타입으로 받아 출력 할 수 있다.

            foreach (Days r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine(r);
            }

 

 


 

> GetNames() , GetValues() 둘다 콘솔에 리스트 문자열은 같으나,  확인해보니 리턴 받는 타입이 다르다.

 


 

> Enum의 Length (Get.Names() 도 Length 확인가능)

            foreach (var r in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine( Enum.GetValues( typeof(Days) ).Length );
            }

 

> 선언 및 리스트 출력

enum days
{
	Monday, Tuesday, Wedneday, Thursday, Friday, Saturday, Sunday
}

public void enumTest()
{
	foreach (days i in Enum.GetValues(typeof(days)))
	{
		Console.WriteLine(i);
	}
}

 


 

> 형변환(int) switch  활용

    	public void enumTest()
        {
            Console.WriteLine("( 0: sword, 1: bow, 2: axe )");
            Console.Write("아이템 번호 입력: ");
            var inputNum = int.Parse(Console.ReadLine());

            switch (inputNum)
            {
                case (int)Weapons.Sword:
                    Console.WriteLine($"{Weapons.Sword} 를 착용");
                    break;
                case (int)Weapons.Bow:
                    Console.WriteLine($"{Weapons.Bow} 를 착용");
                    break;
                case (int)Weapons.Axe:
                    Console.WriteLine($"{Weapons.Axe} 를 착용");
                    break;
                default:
                    Console.WriteLine("입력 번호 오류");
                    break;
            }
        }

 


> 형변환(enum선언타입) - 입력받은 string데이터로 활용(문자열 출력시 .toToString()) 

        enum Weapons { Sword, Bow, Axe }
        public void enumCheang()
        {
            Console.Write("아이템 입력: ");
            var input = Console.ReadLine();
            Weapons getName = (Weapons)Enum.Parse(typeof(Weapons), input);
            Console.WriteLine($"{ getName }를 착용했습니다.");
        }

Action

 Console.WriteLine("[ '장검', '단검', '활', '도끼' ]");
 Console.Write("구매하고자 하는 아이템 이름 입력: ");
 
 var checkInput = Console.ReadLine();
 
   // 함수내부에 action 선언 return이 없음 - void형
   // 제네릭 명시 필요 
   Action<string> msg = (inputMsg) =>
   {
   		Console.WriteLine($"{inputMsg}를 구매하셨습니다.");
   };
switch (checkInput)
                {
                    case "장검":
                        msg(checkInput);
                        break;

 

 

Func

  // 함수내부에 Func 제네릭<인자,리턴타입> 후 화살표 함수 사용 후 return  
  Func<string, string> msgFunc = (inputMsg) =>
  	{
    	return $"{inputMsg}를 구매하셨습니다.";
    };
 switch (checkInput)
 	{
    	case "단검":
        	var str = msgFunc(checkInput);
        	Console.WriteLine(str);
        	break;

Replace - 앞 인자를 뒷 인자로 대체 후 리턴

string str = "할머니";

string temp = str.Replace("머",""); // temp = 할니;



 

Contains - 포함하고 있는 문자열 여부

string str = "할머니";
bool result = str.Contains("머"); // true 리턴

 

Split - 문자열 기준 잘라 배열로 리턴

 var input = Console.ReadLine();
 var arr = input.Split(' '); // char 타입 배열로 리턴
          
 int a = int.Parse(arr[0]);
 int b = int.Parse(arr[1]);
// 입력 java로는 - scanner
string input = Console.ReadLine(); 

// 출력
Console.WriteLine("output");

// 콘솔 삭제
Console.Clear();

 

 

 

 


 

 

 

 

 

+ Recent posts