C#/과제

2020.04.30. 과제 - 시간 제한이 있는 상점 구현 연습하기(쿠키런 방랑박쥐 상점)

dev_sr 2020. 4. 30. 21:20

 

*사용한 이미지

 

비밀스러운 은빛 주머니 구매 가능 시간을 

아래 이미지의 불씨처럼 긴 날짜로 변경하여 해당 시간이 지날 때까지 

재구매 할 수 없게 구현해보았습니다.

 

 

*엑셀 테이블

 

1)상품 테이블

 

2)시간 테이블

 

각 엑셀 테이블에 해당하는 클래스 코드는 생략했습니다.

 

 

1. App class

 

 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_019_2
{
    class App
    {
        UserInfo userInfo;
        ProductInfo productInfo;
        public App()
        {
            DataManager dataManager = DataManager.GetInstance();
            dataManager.LoadData();
 
 
            //불러오기
            //기존 유저인가
            string path = "./data/save_data.json";
 
            if (File.Exists(path))
            {
                this.userInfo = new UserInfo();
 
                string loadJSon = File.ReadAllText(path);
                this.userInfo = JsonConvert.DeserializeObject<UserInfo>(loadJSon);
 
                if (this.userInfo.lastLoginTime.Date == DateTime.Now.Date.AddDays(-1))
                {
                    for (int i = 0; i < this.userInfo.userPurchaseList.Count; i++)
                    {
                        //재구매를 위해 리스트 비우기
// 매일 구매 상품인 것만 비움
 
                        this.userInfo.userPurchaseList.RemoveAll(x => x.time_type != 1);
 
 
 
                    }
                    this.userInfo.lastLoginTime = DateTime.Now;
                }
 
            }
 
            //신규 유저인가
            else
            {
                this.userInfo = new UserInfo();
                this.userInfo.Init();
            }
 
            //있는 목록 출력하기
            this.PrintShop();
 
            //구매하기
            this.Purchase(1000);
 
            //인벤토리 출력하기
            this.PrintInventory();
 
 
            //저장하기
            this.SaveData();
 
        }
 
        public void PrintShop()
        {
            List<ProductData> productlist = DataManager.GetInstance().GetProductData();
 
            //제한 시간 믄자열 표현만 저장할 변수
            string timeData = null;
 
            //현재시간
            DateTime now = DateTime.Now;
 
            //제한 시간 문자열을 시간타입으로 바꿔서 저장할 변수
            DateTime productTime;
 
            //바꾼 시간타입에서 현재 시간을 뺀 값을 저장할 변수
            TimeSpan resultDate;
 
            //매일판매 상품에 사용하는 오늘 자정 구하기
            DateTime todayMid = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
 
            //매일판매 상품에 사용하는 현재시간에서 내일 0시를 뺀 값
            TimeSpan resultTime = todayMid.AddDays(1- now;
 
 
            foreach (ProductData list in productlist)
            {
                timeData = DataManager.GetInstance().GetTimeDataBytype(list.time_type);
                productTime = Convert.ToDateTime(timeData);
                resultDate = productTime - now;
 
 
                int count = 0;
 
                //productData 리스트에서 이름이 같은 항목만 UserInfo 리스트에서 찾고
                var data = userInfo.userPurchaseList.Find(x => x.name == list.name);
 
                //비어있지 않으면 count에 할당
                if (data != null)
                {
                    count = data.purchaseCount;
                }
 
 
                if (list.daily_sell == false)
                {
 
                    //아이템이 1개이면  x N 으로 표시하지 않는다.
                    if (list.amount > 1)
                    {
                        Console.WriteLine("{0}\n{1}\nx{2}\n남은 시간: {3}일 {4}시간 {5}분\n{6} {7:N0}\n{8}({9}/{10})",
                            list.purchase_string, count, list.purchase_limit);
 
                        if (count == 1)
                        {
                            Console.WriteLine("재입고를 기다려주세요");
                        }
 
                        Console.WriteLine("-------------------------------------------------");
                    }
                    else
                    {
                        Console.WriteLine("{0}\n{1}\n남은 시간: {2}일 {3}시간 {4}분\n{5} {6:N0}\n{7}({8}/{9})",
                            list.purchase_string, count, list.purchase_limit);
 
                        if (count == 1)
                        {
                            Console.WriteLine("재입고를 기다려주세요");
                        }
 
                        Console.WriteLine("-------------------------------------------------");
                    }
 
                }
                else
                {
                    //아이템이 1개이면  x N 으로 표시하지 않는다.
                    if (list.amount > 1)
                    {
                        Console.WriteLine("{0}\n{1}\nx{2}\n남은 시간: {3}시간 {4}분 {5} {6:N0}초\n{7}\n{8}({9}/{10})",
                            list.purchase_string, count, list.purchase_limit);
 
                        if (count == 1)
                        {
                            Console.WriteLine("재입고를 기다려주세요");
                        }
 
                        Console.WriteLine("-------------------------------------------------");
                    }
                    else
                    {
                        Console.WriteLine("{0}\n{1}\n남은 시간: {2}시간 {3}분 {4}초\n{5} {6:N0}\n{7}({8}/{9})",
                            list.purchase_string, count, list.purchase_limit);
 
                        if (count == 1)
                        {
                            Console.WriteLine("재입고를 기다려주세요");
                        }
 
                        Console.WriteLine("-------------------------------------------------");
                    }
                }
 
 
 
            }
        }
 
        public void Purchase(int id)
        {
            Console.WriteLine("-------------------------------------------------");
 
            ProductData productData = DataManager.GetInstance().GetProductDataById(id);
 
            foreach (var list in this.userInfo.userPurchaseList)
            {
                if (list.name == productData.name)
                {
                    if (list.purchaseCount == productData.purchase_limit)
                    {
                        Console.WriteLine("더이상 구매할 수 없습니다.");
                        return;
                    }
                }
 
            }
 
            Console.WriteLine("{0} {1}개를 구매합니다"productData.name, productData.amount);
            productInfo = new ProductInfo();
            this.productInfo.AddInfo(productData.name, productData.amount, productData.time_type);
            this.userInfo.AddUserPurchaseList(productInfo);
        }
 
        public void PrintInventory()
        {
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine("***구매한 목록***");
            foreach (var list in this.userInfo.userPurchaseList)
            {
                Console.WriteLine("{0} {1}개"list.name, list.amount);
            }
        }
 
        public void SaveData()
        {
            Console.WriteLine("-------------------------------------------------");
            Console.WriteLine("데이터를 저장합니다.");
 
            string path = "./data/save_data.json";
            string saveJson = JsonConvert.SerializeObject(this.userInfo);
 
            File.WriteAllText(path, saveJson);
        }
    }
}
 
 

 

2. DataManager class

 

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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_019_2
{
    class DataManager
    {
        static private DataManager instance;
        Dictionary<int, ProductData> dicProductdatas;
        Dictionary<int, TimeData> dicTimeDatas;
        private DataManager()
        {
            this.dicProductdatas = new Dictionary<int, ProductData>();
            this.dicTimeDatas = new Dictionary<int, TimeData>();
        }
 
        public static DataManager GetInstance()
        {
            if(DataManager.instance==null)
            {
                DataManager.instance = new DataManager();
                return DataManager.instance;
            }
            return DataManager.instance;
        }
 
 
        public void LoadData()
        {
            string productJson = File.ReadAllText("./data/product_data.json");
            string timeJson = File.ReadAllText("./data/time_data.json");
 
            this.dicProductdatas = JsonConvert.DeserializeObject<ProductData[]>(productJson).ToDictionary(x => x.id, x => x);
            this.dicTimeDatas = JsonConvert.DeserializeObject<TimeData[]>(timeJson).ToDictionary(x => x.id, x => x);
 
        }
 
        public List<ProductData> GetProductData()
        {
            List<ProductData> data = new List<ProductData>();
 
            foreach(var pair in this.dicProductdatas)
            {
                data.Add(pair.Value);
            }
            return data;
        }
 
        public string GetTimeDataBytype(int type)
        {
            string data = null;
 
            foreach(KeyValuePair<int, TimeData> pair in this.dicTimeDatas)
            {
                if(pair.Value.time_limit!="null")
                {
                    if (pair.Value.type == type)
                    {
                        data = pair.Value.time_limit;
                    }
                }
               
            }
 
            return data;
        }
 
        public ProductData GetProductDataById(int id)
        {
            return this.dicProductdatas[id];
        }
    }
}
 
 

 

 

3. ProductInfo class

 

 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_019_2
{
    class ProductInfo
    {
        public string name;         //이름
        public int amount;          //갯수
        public int purchaseCount=0;   //구매한 횟수
        public int time_type;
 
        public ProductInfo()
        {
            this.purchaseCount = 0;
        }
 
        public void AddInfo(string name, int amount, int time_type)
        {
            this.name = name;
            this.amount = amount;
            this.purchaseCount++;
            this.time_type = time_type;
 
        }
    }
}
 
 

 

 

4. UserInfo class

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_019_2
{
    class UserInfo
    {
        public DateTime lastLoginTime;
        public List<ProductInfo> userPurchaseList;
 
        public UserInfo()
        {
            this.userPurchaseList = new List<ProductInfo>();
        }
 
        public void Init()
        {
            this.lastLoginTime = DateTime.Now;
            
        }
 
        public void AddUserPurchaseList(ProductInfo info)
        {
            this.userPurchaseList.Add(info);
            this.lastLoginTime = DateTime.Now;
        }
    }
}
 
 

 

5. 결과값

 

1)목록 출력하고 매일 판매 상품인 상품 구매하기

 

2) 같은 날에 같은 상품 구매하기

-더 이상 구매할 수 없고

-카운터가 1개 올라감

 

3) 다른 상품 구매하기(매일 판매 상품 X)

 

4) 다시 구매하기 위해 실행하면 구매하지 못하고 방금 구매했던 상품의 카운터가 1개 올라감

 

5) 다음 날로 바뀔 경우

은빛 주머니를 제외한 나머지 항목을 리스트에서 제거하여 구매한 목록 초기화