class App
{
Dictionary<int, ItemData> dicItemData = new Dictionary<int, ItemData>();
Inventory inventory = new Inventory();
string dataPath = "./item_data.json";
string invenPath = "./inven_info.json";
public App()
{
string dataJson = File.ReadAllText(dataPath);
dicItemData = JsonConvert.DeserializeObject<ItemData[]>(dataJson).ToDictionary(x => x.id);
if (!File.Exists(invenPath))
{
Console.WriteLine("신규유저 특전 {0}, {1}. {2} 지급", dicItemData[100].name, dicItemData[101].name, dicItemData[102].name);
inventory.AddItem(new Item(dicItemData[100]), SaveInventory);
inventory.AddItem(new Item(dicItemData[101]), SaveInventory);
inventory.AddItem(new Item(dicItemData[102]), SaveInventory);
}
else
{
Console.WriteLine("재접속을 환영합니다");
LoadInventory();
Item item = inventory.GetItem(102, SaveInventory);
Console.WriteLine("id:{0}, name:{1}, damage:{2}", item.info.id, item.info.name, item.info.damage);
}
}
void LoadInventory()
{
string invenJson = File.ReadAllText(invenPath);
Item[] loadItem = JsonConvert.DeserializeObject<Item[]>(invenJson);
foreach (Item saveInfo in loadItem)
{
inventory.AddItem(saveInfo);
}
}
void SaveInventory(List<Item> itemList)
{
File.WriteAllText(invenPath, JsonConvert.SerializeObject(itemList));
}
}
class Item
{
public ItemData info;
public int reinforcement;
public Item(ItemData data)
{
this.info = data;
}
}
class ItemData
{
public int id;
public string name;
public float damage;
}
class Inventory
{
private List<Item> itemList = new List<Item>();
public delegate void Del(List<Item> itemList);
public Inventory()
{
}
public void AddItem(Item item)
{
itemList.Add(item);
Console.WriteLine("{0}을 가방으로 불러왔습니다.", item.info.name);
}
public void AddItem(Item item, Del callback)
{
itemList.Add(item);
Console.WriteLine("가방에 {0}이 추가되었습니다.", item.info.name);
callback(itemList);
}
public Item GetItem(int id, Del callback)
{
Item foundItem = itemList
.Where(x => x.info.id == id)
.First();
Console.WriteLine("가방에서 {0}을 꺼냈습니다.", foundItem.info.name);
itemList.Remove(foundItem);
callback(itemList);
return new Item(foundItem.info);
}
}
첫번째 실행

[
{
"info": {
"id": 100,
"name": "단검",
"damage": 1.5
},
"reinforcement": 0
},
{
"info": {
"id": 101,
"name": "장검",
"damage": 4.0
},
"reinforcement": 0
},
{
"info": {
"id": 102,
"name": "창",
"damage": 3.0
},
"reinforcement": 0
}
]
두번째 실행

[
{
"info": {
"id": 100,
"name": "단검",
"damage": 1.5
},
"reinforcement": 0
},
{
"info": {
"id": 101,
"name": "장검",
"damage": 4.0
},
"reinforcement": 0
}
]'C# > 수업 내용' 카테고리의 다른 글
| [C#] thread, lock (0) | 2021.09.12 |
|---|---|
| [C#] Iterator, yield (0) | 2021.09.10 |
| [C#] Newtonsoft.Json 파일 읽기, 역직렬화 (0) | 2021.09.08 |
| [C#] Newtonsoft.Json 설치 (0) | 2021.09.08 |
| [C#] 파일 시스템 text, json (0) | 2021.09.08 |