App
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft;
using Newtonsoft.Json;
namespace Game2048
{
internal class App
{
//생성자
public App()
{
//게임 시작 전 아이템 로드
DataManager.instance.LoadItemDatas();
if(File.Exists("./item_info.json"))
{
string json = File.ReadAllText("./item_info.json");
ItemInfo info = JsonConvert.DeserializeObject<ItemInfo>(json);
Item item = new Item(info);
int id = item.GetID();
string name = item.Name;
int damage = item.GetDamage();
Console.WriteLine("ID : {0}", id);
Console.WriteLine("이름 : {0}", name);
Console.WriteLine("공격력 : {0}", damage);
}
else
{
ItemData data = DataManager.instance.GetItemData(100);
ItemInfo info = new ItemInfo(data.id, data.damage);
Item item = new Item(info);
int id = item.GetID();
string name = item.Name;
int damage = item.GetDamage();
Console.WriteLine("ID : {0}", id);
Console.WriteLine("이름 : {0}", name);
Console.WriteLine("공격력 : {0}", damage);
//직렬화
string json = JsonConvert.SerializeObject(item.GetInfo());
File.WriteAllText("./item_info.json", json);
}
}
}
}
ItemInfo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game2048
{
public class ItemInfo
{
public int id;
public int damage;
//생성자
public ItemInfo(int id, int damage)
{
this.id = id;
this.damage = damage;
}
}
}
ItemData
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game2048
{
public class ItemData
{
public int id;
public string name;
public int damage;
}
}
Item
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Game2048
{
public class Item
{
public ItemInfo info;
public string Name
{
get
{
ItemData data = DataManager.instance.GetItemData(this.info.id);
return data.name;
}
}
//생성자
public Item(ItemInfo info)
{
this.info = info;
}
//ID 가져오기
public int GetID()
{
return info.id;
}
//Damage 가져오기
public int GetDamage()
{
return info.damage;
}
//아이템 정보 가져오기
public ItemInfo GetInfo()
{
return this.info;
}
}
}
DataManager
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft;
using Newtonsoft.Json;
namespace Game2048
{
public class DataManager
{
public static readonly DataManager instance = new DataManager();
Dictionary<int, ItemData> dicItemDatas = new Dictionary<int, ItemData>();
//생성자
private DataManager()
{
}
//아이템 로드
public void LoadItemDatas()
{
string json = File.ReadAllText("./item_data.json");
//역직렬화
ItemData[] arr = JsonConvert.DeserializeObject<ItemData[]>(json);
//가져온 아이템 담기
foreach(ItemData data in arr)
{
dicItemDatas.Add(data.id, data);
}
//dicItemDatas = arr.ToDictionary(x => x.id);
}
//아이템 가져오기
public ItemData GetItemData(int id)
{
return this.dicItemDatas[id];
}
}
}