Inventory + Singleton

C#/과제 2019. 4. 7. 21:16



Inventory 저장 및 불러오기 기능 + DataStorage Singleton 패턴으로 구현


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class WeaponData
    {
        public int id;
        public int count;
        public string name;
        public int damage;
        public WeaponData(int id, int count, string name, int damage)
        {
            this.id = id;
            this.count = 1;
            this.name = name;
            this.damage = damage;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class WeaponInfo : ItemInfo
    {
        public WeaponInfo(int id) : base(id)
        {
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class WeaponItem : Item
    {
        new public WeaponInfo info;
        public WeaponItem(WeaponInfo info) : base(info)
        {
            this.info = info;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class ItemInfo
    {
        public int id;
        public int count;
        public ItemInfo(int id)
        {
            this.id = id;
            this.count = 1;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class Item
    {
        public ItemInfo info;
        public Item(ItemInfo info)
        { 
            this.info = info;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class InventoryInfo
    {
        private List<WeaponItem> itemList;
        public InventoryInfo(List<WeaponItem> list)
        {
            itemList = list;
        }
        public List<WeaponItem> ReturnList()
        {
            return this.itemList;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
 
namespace _0407
{
    public class Inventory
    { 
        private List<WeaponItem> itemList;
        private DataStorage storage;
        public InventoryInfo info;
        public Inventory(InventoryInfo info)
        {
            this.info = info;
            this.itemList = info.ReturnList();
            this.storage = DataStorage.MakeDataStorage();
        }
 
        //추가 메서드
        public bool AddItem(string name)
        {
            var index = FindIndex(name);
            if (index != -1)
            {
                foreach(var item in itemList)
                {
                    if(item.info.id == index)
                    {
                        item.info.count++;
                        return true;
                    }
                }
                var weapon = new WeaponItem(new WeaponInfo(index));
                this.itemList.Add(weapon);
                Console.WriteLine("{0}이 인벤토리에 등록되었습니다.", name);
                return true;
            }
            Console.WriteLine("존재하지 않는 아이템입니다.");
            return false;
        }
        //dictionary key찾는메서드
        public int FindIndex(string name)
        {
            for (int index = 0; index < storage.dicWeaponData.Count; index++)
            {
                if (storage.dicWeaponData[index].name == name)
                {
                    return index;
                }
            }
            return -1;
        }
 
        //출력메서드
        public void PrintInventory()
        {
            foreach(var item in itemList)
            {
                Console.WriteLine("{0}x{1}",storage.dicWeaponData[item.info.id].name, item.info.count);
            }
        }
        //삭제메서드
        public bool RemoveItem(string name, int count)
        {
            var dicKey = FindIndex(name);
            int index = 0;
            if(dicKey != -1)
            {
                foreach (var item in itemList)
                {
                    if (item.info.id == dicKey)
                    {
                        if(item.info.count<=count)
                        {
                            Console.WriteLine("{0}를 {1}개 버렸습니다.", name, item.info.count);
                            itemList.RemoveAt(index);
                            return true;
                        }
                        Console.WriteLine("{0}를 {1}개 버렸습니다.", name, count);
                        item.info.count -= count;
                        return true;
                    }
                    index++;
                }
            }
            return false;
        }
        public void SaveInventory()
        {
            var json = JsonConvert.SerializeObject(this.itemList);
            File.WriteAllText("./inventory_info.json", json, Encoding.UTF8);
        }
    }
 
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class GameLauncher
    {
        private Inventory inventory;
        public GameLauncher(Inventory inventory)
        {
            this.inventory = inventory;
        }
 
        public void GameStart()
        {
            var menuKey = ConsoleKey.D5;
            while (menuKey!=ConsoleKey.D6)
            {
                Console.WriteLine("1.아이템제작  2.인벤토리보기  3.아이템꺼내기  4.저장후 종료");
                menuKey = Console.ReadKey().Key;
                switch (menuKey)
                {
                    case ConsoleKey.D1:
                        Console.WriteLine("프람베르그 / 무라마사 / 다마스커스 / 슈팅스타 / 등뒤를 베는자");
                        Console.Write("제작하실 아이템 이름을 입력하세요 : ");
                        var inputName = Console.ReadLine();
                        int createCount;
                        Console.Write("몇개 제작하시겠습니까?");
                        Int32.TryParse(Console.ReadLine(), out createCount);
                        for(int count=0; count<createCount; count++)
                        {
                           inventory.AddItem(inputName);
                        }
                        break;
                    case ConsoleKey.D2:
                        inventory.PrintInventory();
                        break;
                    case ConsoleKey.D3:
                        Console.Write("버리실 아이템 이름을 입력하세요 : ");
                        var dropItemName = Console.ReadLine();
                        int dropCount;
                        Console.Write("몇개 버리시겠습니까?");
                        Int32.TryParse(Console.ReadLine(), out dropCount);
                        var success = inventory.RemoveItem(dropItemName, dropCount);
                        if (success == false)
                        {
                            Console.WriteLine("인벤토리에 {0}이 존재하지 않습니다.", dropItemName);
                        }
                        break;
                    case ConsoleKey.D4:
                        inventory.SaveInventory();
                        Console.WriteLine("저장이 완료되었습니다.");
                        Console.WriteLine("프로그램을 종료합니다.");
                        menuKey = ConsoleKey.D6;
                        break;
                }
            }
        }
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _0407
{
    public class DataStorage
    {
        private static DataStorage instance;
        public Dictionary<int, WeaponData> dicWeaponData = new Dictionary<int, WeaponData>();
        protected DataStorage()
        {
 
        }
        public static DataStorage MakeDataStorage()
        {
            if(instance == null)
            {
                instance = new DataStorage();
            }
            return instance;
        }
    }
 
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
 
namespace _0407
{
    public class App
    {
        private GameLauncher gameLauncher;
        private DataStorage storage;
        public App()
        {
            this.gameLauncher = new GameLauncher(CreateInventory());
        }
 
        //시작 메서드
        public void Start()
        {
            this.LoadData();
            this.GameStart();
        }
 
        //데이터로드 메서드
        public void LoadData()
        {
            this.storage = DataStorage.MakeDataStorage();
            var str = File.ReadAllText("./weapon_item_data.json");
            var arrJson = JsonConvert.DeserializeObject<WeaponData[]>(str);
            foreach(var addJson in arrJson)
            {
                storage.dicWeaponData.Add(addJson.id, addJson);
            }
        }
 
        //인벤토리 제작 메서드
        public Inventory CreateInventory()
        {
            var isExist = File.Exists("./inventory_info.json");
            if (isExist)
            {
                var str = File.ReadAllText("./inventory_info.json");
                var arrJson = JsonConvert.DeserializeObject<List<WeaponItem>>(str);
                return new Inventory(new InventoryInfo(arrJson));
            }
            else
            {
                List<WeaponItem> list = new List<WeaponItem>();
                return new Inventory(new InventoryInfo(list));
            }
        }
        
        //런쳐시작 메서드
        public void GameStart()
        {
            this.gameLauncher.GameStart();
        }
    }
}
 
cs


'C# > 과제' 카테고리의 다른 글

롤 구현하기  (0) 2019.04.10
Character의 Move, Attack, MoveAttack 구현  (0) 2019.04.08
Hash란?  (0) 2019.04.04
13. 인벤토리 구현하기  (0) 2019.03.27
12. WoW 캐릭터 생성 과제 (2단계+α 까지 완료)  (0) 2019.03.27
: