스파르타코딩클럽 게임개발

엊그제는 스파르타 코딩 클럽 unity 게임 개발 과정 10일차(개인과제 텍스트 RPG)

코드천자문 2023. 11. 13. 00:47
반응형

생각해보니 ㅋㅋㅋㅋㅋㅋ 금요일에 글작성을 안했다..

 

까먹고있다가 지금 쓴다.. 

ㅠㅠ

 

 

개인과제는 텍스트 rpg 만들기다.

 

과제 개요

  1. 던전을 떠나기전 마을에서 장비를 구하는 게임을 텍스트로 구현합니다. (C# - Console App)
  2. 상점의 아이템 중에서 나만의 장비를 구성하는 부분이 포인트입니다.
  3. 장비는 여러개의 데이터가 함께 있는 만큼 객체나 구조체를 활용하는 편이 효율적 입니다. (이름, 가격, 효과, 설명 등…)
  4. 관련된 여러 데이터를 다루는 부분은 배열이 도움이 됩니다.

내용은 이러하고 나는 일단 클래스를 어떻게 만들까 생각했다.

 

일단 캐릭터 클래스는 기본으로 제공 되었다.

이 클래스를 보고 대충 이런식으로 만들라는 것인가! 하면서 다른 클래스도 만들었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Character
{
    public string Name { get; }
    public string Job { get; }
    public int Level { get; }
    public int Atk { get; }
    public int Def { get; }
    public int Hp { get; }
    public int Gold { get; }
 
    public Character(string name, string job, int level, int atk, int def, int hp, int gold)
    {
        Name = name;
        Job = job;
        Level = level;
        Atk = atk;
        Def = def;
        Hp = hp;
        Gold = gold;
    }
}
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
public class Item
{
        public static List<Item> MyItem = new List<Item>();
        public static List<Item> Store = new List<Item>();
        public string Name { get; set; }
        public int Akt { get; set; }
        public int Def { get; set; }
        public string ItemDescription { get; set; }
        public bool Stallation { get; set; }
        public bool Buy { get; set; }
        public int Gold { get; }
        public Item()
        {
                MyItem.Add(new Item("무쇠갑옷"02"무쇠로 만들어져 튼튼한 갑옷입니다."falsetrue200));
                MyItem.Add(new Item("낡은검"20"쉽게 볼 수 있는 낡은 검 입니다."falsetrue200));
                Store.Add(new Item("무쇠갑옷"02"무쇠로 만들어져 튼튼한 갑옷입니다."falsetrue200));
                Store.Add(new Item("낡은검"20"쉽게 볼 수 있는 낡은 검 입니다."falsetrue200));
                Store.Add(new Item("청동 도끼"05"어디선가 사용됐던거 같은 도끼입니다."falsefalse1500));
                Store.Add(new Item("스파르타의 창"07"스파르타의 전사들이 사용했다는 전설의 창입니다."falsefalse0));
                Store.Add(new Item("제우스의 번개"020"그리스 신 제우스의 무기로, 강력한 번개를 날릴 수 있습니다."falsefalse5000));
                Store.Add(new Item("아레스의 갑옷"200"전쟁의 신 아레스가 사용한 갑옷으로, 강력한 방어를 제공합니다."falsefalse4500));
                Store.Add(new Item("아테나의 방패"1010"지혜의 여신 아테나의 방패로, 공격과 방어에 모두 탁월한 효과를 줍니다."falsefalse4000));
                Store.Add(new Item("우키의 망치"015"북유럽 신화의 신 우키의 망치로, 강력한 공격 능력을 지닌 무기입니다."falsefalse4200));
                Store.Add(new Item("오닉스의 목걸이"55"그리스 신화의 오닉스의 눈을 상징하는 목걸이로, 공격과 방어를 동시에 향상시킵니다."falsefalse3800));
                Store.Add(new Item("히노카구타"128"일본 신화에서 나온 신기한 검으로, 화염을 뿜어내는 능력이 있습니다."falsefalse4600));
                Store.Add(new Item("용의 심장"812"한국 신화에서 나온 용을 상징하는 심장으로, 강력한 공격력을 부여합니다."falsefalse4300));
                Store.Add(new Item("해신의 투구"108"한국 신화의 바다 신, 해신의 투구로, 물 속에서 강력한 방어 능력을 발휘합니다."falsefalse4100));
        }
        public Item(string name, int atk, int def, string ItemDescription, bool stallation,bool buy, int gold)
        {
                this.Name = name;
                this.Akt = atk;
                this.Def = def;
                this.ItemDescription = ItemDescription;
                this.Stallation = stallation;
                this.Buy = buy;
                this.Gold = gold;
        }
        public void MyItemAdd(Item itme)
        {
                MyItem.Add(itme);
        }
        public void StoreAdd(Item itme)
        {
                Store.Add(itme);
        }
        public static void stallationReverse(Item itme)
        {
                itme.Stallation = itme.Stallation == true ? false : true;
        }
        public static void BuyReverse(Item itme)
        {
                itme.Buy = itme.Buy == true ? false : true;
        }
 
        public static string stallationManagement(Item itme)
        {
                return itme.Stallation == true ? "[E]" : "   ";
        }
        public static string BuyManagement(Item itme)
        {
                return itme.Buy == true ? "[구매완료]" : "   ";
        }
 
        public override string ToString()
        {
                return $"{this.Name} {this.Akt} {this.Def} {this.ItemDescription} {this.Stallation} {this.Gold}";
        }
}
 
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
public class Character
{
        public static List<Character> Characters = new List<Character>();
        public string Name { get; set; }
        public string Job { get; set; }
        public int Level { get; set; }
        public int Atk { get; set; }
        public int Def { get; set; }
        public int Hp { get; set; }
        public int Gold { get; set; }
 
        public Character(string name, string job, int level, int atk, int def, int hp, int gold)
        {
                Name = name;
                Job = job;
                Level = level;
                Atk = atk;
                Def = def;
                Hp = hp;
                Gold = gold;
        }
        public static void putStatIncrease(Item inventory)
        {
                if (inventory.Stallation)
                {
                        foreach (var character in Characters)
                        {
                                character.Atk += inventory.Akt;
                                character.Def += inventory.Def;
                        }
                }
        }
        public static void takeStatIncrease(Item inventory)
        {
                if (!inventory.Stallation)
                {
                        foreach (var character in Characters)
                        {
                                character.Atk -= inventory.Akt;
                                character.Def -= inventory.Def;
                        }
                }
        }
 
        public void Add()
        {
                Characters.Add(this);
        }
}
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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
using Microsoft.VisualBasic;
using System.Runtime.CompilerServices;
using TextRPG;
 
internal class Program
{
        static void Main(string[] args)
        {
                GameDataSetting();
                DisplayGameIntro();
        }
 
        static void GameDataSetting()
        {
                // 캐릭터 정보 세팅
                Character Mplayer = new Character("Chad""전사"11051001500);
                Mplayer.Add();
                // 아이템 정보 세팅
                Item inventory = new Item();
 
                Item.MyItem.Sort((a, b) => a.Name[0- b.Name[0]);
                Item.Store.Sort((a, b) => a.Name[0- b.Name[0]);
        }
 
        static void DisplayGameIntro()
        {
                Console.Clear();
 
                Console.WriteLine("스파르타 마을에 오신 여러분 환영합니다.");
                Console.WriteLine("이곳에서 전전으로 들어가기 전 활동을 할 수 있습니다.");
                Console.WriteLine();
                Console.WriteLine("1. 상태보기");
                Console.WriteLine("2. 인벤토리");
                Console.WriteLine("3. 상점");
                Console.WriteLine();
                Console.WriteLine("원하시는 행동을 입력해주세요.");
 
                int input = CheckValidInput(13);
                switch (input)
                {
                        case 1:
                                DisplayMyInfo();
                                break;
 
                        case 2:
                                DisplayInventory();
                                break;
                        case 3:
                                Displaystore();
                                break;
                }
        }
 
        static void DisplayMyInfo()
        {
                Console.Clear();
                foreach (var character in Character.Characters)
                {
                        Console.WriteLine("상태보기");
                        Console.WriteLine("캐릭터의 정보르 표시합니다.");
                        Console.WriteLine();
                        Console.WriteLine($"Lv.{character.Level}");
                        Console.WriteLine($"{character.Name}({character.Job})");
                        Console.Write($"공격력 :{character.Atk}");
                        Console.WriteLine($" (+{Item.MyItem.Where(x => x.Stallation).Select(x => x.Akt).Sum()})");
                        Console.Write($"방어력 : {character.Def}");
                        Console.WriteLine($"(+{Item.MyItem.Where(x => x.Stallation).Select(x => x.Def).Sum()})");
                        Console.WriteLine($"체력 : {character.Hp}");
                        Console.WriteLine($"Gold : {character.Gold} G");
                        Console.WriteLine();
                }
                Console.WriteLine("0. 나가기");
 
 
                int input = CheckValidInput(00);
                switch (input)
                {
                        case 0:
                                DisplayGameIntro();
                                break;
                }
        }
 
        static void DisplayInventory()
        {
                Console.Clear();
 
                Console.WriteLine("인벤토리");
                Console.WriteLine("보유 중인 아이템을 관리할 수 있습니다.");
                Console.WriteLine();
                Console.WriteLine($"[아이템 목록]");
                foreach (var item in Item.MyItem)
                {
                        Console.WriteLine($"- {Item.stallationManagement(item)} |" +
                                  $"{item.Name + new string(' ',10- item.Name.Length)}|" +
                                  $"{item.Akt} |" +
                                  $"{item.Def} |" +
                                  $"{item.ItemDescription}");
                }
                Console.WriteLine();
                Console.WriteLine("0. 나가기");
                Console.WriteLine("1. 장착관리");
 
                int input = CheckValidInput(01);
                switch (input)
                {
                        case 0:
                                DisplayGameIntro();
                                break;
                        case 1:
                                DisplayInventoryInstallationManagement();
                                break;
                }
        }
        static void DisplayInventoryInstallationManagement()
        {
                Console.Clear();
 
                Console.WriteLine("인벤토리 - 장착 관리");
                Console.WriteLine("보유 중인 아이템을 관리할 수 있습니다.");
                Console.WriteLine();
                Console.WriteLine($"[아이템 목록]");
                foreach (var item in Item.MyItem)
                {
                        Console.WriteLine($"- {Item.MyItem.IndexOf(item) + 1} " +
                                $"{Item.stallationManagement(item)} |" +
                                $"{item.Name + new string(' ', 10- item.Name.Length)}|" +
                                $"{item.Akt} |" +
                                $"{item.Def} |" +
                                $"{item.ItemDescription}");
                }
                Console.WriteLine();
                Console.WriteLine("0. 나가기");
                int input = CheckValidInput(0, Item.MyItem.Count);
                if (input == 0)
                {
                        DisplayInventory();
                }
                else
                {
                        foreach (var item in Item.MyItem)
                        {
                                if (input == Item.MyItem.IndexOf(item) + 1)
                                {
                                        Item.stallationReverse(item);
                                        item.MyItemAdd(item);
                                        Item.MyItem.RemoveAt(input - 1);
                                        Item.MyItem.Sort((a, b) => a.Name[0- b.Name[0]);
                                        Character.putStatIncrease(item);
                                        DisplayInventoryInstallationManagement();
                                }
                        }
                }
        }
        static void Displaystore()
        {
                Console.Clear();
 
                Console.WriteLine("상점");
                Console.WriteLine("구매하시겠습니까?.");
                Console.WriteLine("판매 하시겠습니까?.");
                Console.WriteLine();
                Console.WriteLine($"[소지 골드 : {Character.Characters.First().Gold}골드 ]");
                Console.WriteLine();
                Console.WriteLine($"[아이템 목록]");
                Console.WriteLine();
                foreach (var item in Item.Store)
                {
                        string a = ((Item.Store.IndexOf(item) + 1).ToString().Length) > 1 ? "" : " ";
                        Console.WriteLine($"- {Item.Store.IndexOf(item) + 1} " +
                                $"{a}" +
                                $"{Item.stallationManagement(item)}||" +
                                $"{item.Name + new string(' ', 10 - item.Name.Length)}|" +
                                $"{item.Akt} |" +
                                $"{item.Def} |" +
                                $"{item.Gold}G |" +
                                $"{item.ItemDescription}");
                }
                Console.WriteLine("0. 나가기");
                Console.WriteLine("1. 구매하기");
                Console.WriteLine("2. 판매하기");
 
                int input = CheckValidInput(02);
                switch (input)
                {
                        case 0:
                                DisplayGameIntro();
                                break;
                        case 1:
                                DisplaystoreBuyManagement();
                                break;
                        case 2:
                                DisplaystoreSaleManagement();
                                break;
                }
        }
        static void DisplaystoreBuyManagement()
        {
                Console.Clear();
 
                Console.WriteLine("구매하기");
                Console.WriteLine("판매 중인 아이템을 구매할 수 있습니다.");
                Console.WriteLine();
                Console.WriteLine($"[소지 골드 : {Character.Characters.First().Gold}골드 ]");
                Console.WriteLine();
                Console.WriteLine($"[아이템 목록]");
                Console.WriteLine();
                foreach (var item in Item.Store)
                {
                        string a = ((Item.Store.IndexOf(item) + 1).ToString().Length) > 1 ? "" : " ";
                        Console.WriteLine($"- {Item.Store.IndexOf(item) + 1}" +
                                $"{a}" +
                                $"{Item.stallationManagement(item)}||" +
                                $"{item.Name + new string(' ', 10 - item.Name.Length)}|" +
                                $"{item.Akt} |" +
                                $"{item.Def} |" +
                                $"{item.ItemDescription}" +
                                $"{item.Gold}G |" +
                                $"{Item.BuyManagement(item)}");
                }
                Console.WriteLine("0. 나가기");
 
                int input = CheckValidInput(0, Item.Store.Count);
 
                if (input == 0)
                {
                        Displaystore();
                }
                else
                {
                        foreach (var item in Item.Store)
                        {
                                if (Character.Characters.First().Gold < item.Gold)
                                {
                                        DisplaystorefailedBuy();
                                }
                                if (input == Item.Store.IndexOf(item) + 1 && !item.Buy)
                                {
                                        Item.BuyReverse(item);
                                        item.StoreAdd(item);
                                        Item.Store.RemoveAt(input - 1);
                                        Item.MyItem.Add(item);
                                        Character.Characters.First().Gold -= item.Gold;
                                        Item.Store.Sort((a, b) => a.Name[0- b.Name[0]);
                                        Character.putStatIncrease(item);
                                        DisplaystoreBuyManagement();
                                }
 
                        }
 
                        DisplaystorefailedBuy();
 
                }
        } static void DisplaystoreSaleManagement()
        {
                Console.Clear();
 
                Console.WriteLine("판매하기");
                Console.WriteLine("보유 중인 아이템을 판매 할 수 있습니다.");
                Console.WriteLine();
                Console.WriteLine($"[소지 골드 : {Character.Characters.First().Gold}골드 ]");
                Console.WriteLine();
                Console.WriteLine($"[아이템 목록]");
                Console.WriteLine();
                foreach (var item in Item.Store)
                {
                        string a = ((Item.Store.IndexOf(item) + 1).ToString().Length) > 1 ? "" : " ";
                        Console.WriteLine($"- {Item.Store.IndexOf(item) + 1}" +
                                $"{a}" +
                                $"{Item.stallationManagement(item)}||" +
                                $"{item.Name + new string(' ', 10 - item.Name.Length)}|" +
                                $"{item.Akt} |" +
                                $"{item.Def} |" +
                                $"{item.ItemDescription}" +
                                $"{item.Gold}G |" +
                                $"{Item.BuyManagement(item)}");
                }
                Console.WriteLine("0. 나가기");
 
                int input = CheckValidInput(0, Item.Store.Count);
 
                if (input == 0)
                {
                        Displaystore();
                }
                else
                {
                        foreach (var item in Item.Store)
                        {
                                if (input == Item.Store.IndexOf(item) + 1 &&!item.Buy)
                                {
                                    Console.WriteLine"ddddddddddddddddddddddddddddddddddddddd");
                                    DisplaystorefailedSale();
                                }
                                if (input == Item.Store.IndexOf(item) + 1 && item.Buy)
                                {
                                        Item.BuyReverse(item);
                                        item.StoreAdd(item);
                                        Item.Store.RemoveAt(input - 1);
                                        Item.MyItem.RemoveAll(x=> x.Name == item.Name);
                                        Character.Characters.First().Gold += Convert.ToInt16( item.Gold * 0.85f);
                                        Item.Store.Sort((a, b) => a.Name[0- b.Name[0]);
                                        Character.takeStatIncrease(item);
                                        DisplaystoreSaleManagement();
                                }
                        }
                        DisplaystorefailedSale();
                }
        }
        static void DisplaystorefailedBuy()
        {
                Console.WriteLine(Item.MyItem.Count+"개 는 있네 ㅣㅆ발");
                Console.WriteLine("불가능한 행동입니다.");
                Console.WriteLine("상점을 계속 이용하시려면 아무키나 눌러주세요.");
                Console.ReadLine();
                DisplaystoreBuyManagement();
        }
        static void DisplaystorefailedSale()
        {
                Console.WriteLine(Item.MyItem.Count + "개 는 있네 ㅣㅆ발");
                Console.WriteLine("불가능한 행동입니다.");
                Console.WriteLine("상점을 계속 이용하시려면 아무키나 눌러주세요.");
                Console.ReadLine();
                DisplaystoreSaleManagement();
        }
        static int CheckValidInput(int min, int max)
        {
                while (true)
                {
                        string input = Console.ReadLine() ?? " ";
 
                        bool parseSuccess = int.TryParse(input, out var ret);
                        if (parseSuccess)
                        {
                                if (ret >= min && ret <= max)
                                        return ret;
                        }
 
                        Console.WriteLine("잘못된 입력입니다.");
                }
        }
}
class MyClass
{
        public MyClass()
        {
        }
}
 
cs

 

 

지금 기능은 현재상태보기 , 인벤토리 . 인벤토리에서 장착관리 . 상점 , 상점 구매 , 상점 판매 , 판매시 장착해제. 골드없으면 구매 못함 , 판매할 물건없으면 판매 못함, 이미 구매한 아이템 구매 못함 등이 있는데 

 

하지 못한 기능은 콘솔에서 테이블을 만들어서 이쁘게 만들기나 글자 간격을 맞출려고 했지만 .. 

뭐.. 현생의 일로 조금 시간이 부족했다.

 

개인과제는 필수 조건은 다 채웠고 다른 조건도 조금 귀찮을 뿐이지 못할정도는 아닌 난이도 였다.

 

저장기능은 모르겠지만 ㅎㅎ 

 

내가 코드를 짜면서 문제가 생긴부분은 .. 

 

DisplayInventoryInstallationManagement의 스위치에서 CheckValidInput를 받는 인풋을 사용하면 
다른 아이템들을 유동적으로 추가 할 수 없어 어떻게 해야 할지 고민 

 

이 부분은 원래 스위치로 사용한 것을 이프문으로 변환 시켜 해결했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  if (input == 0)
  {
          DisplayGameIntro();
  }
  else
  {
          foreach (var item in Item.items)
          {
                  if (input == Item.items.IndexOf(item) + 1)
                  {
                          Item.stallationReverse(item);
                          item.Add(item);
                          Item.items.RemoveAt(input-1);
                          Item.items.Sort((a,b)=> a.Name[0- b.Name[0]);
                          DisplayInventoryInstallationManagement();
                  }
          }
  }
 
cs




이런식으로 바꾸어서 해결 이제 아이템을 추가해도 문제없음

 

 


아이템 설명란에서 칸 맞추는것을 해결하기 위해 

1
2
3
{
        Console.WriteLine($"- {Item.stallationManagement(item)} |{item.Name + new string(' ',5-item.Name.Length)}|      | {item.Def} | {item.ItemDescription}");
}
cs



이런 코드를 작성함 


캐릭터 정보에서 공격력 옆에 아이템 효과 보이게 하는 것이 장착해제해도 그냥 보임 

 Console.WriteLine($" (+{Inventory.MyItem.Select(x => x.Akt).Sum()})");

해결 보니까 조건이 없었음.
 Console.WriteLine($" (+{Inventory.MyItem.Where(x=> x.Stallation).Select(x => x.Akt).Sum()})");

코드를 이렇게 변경하여 해결함 


 이미 구매한 아이템입니다라는 글자가 안나오고 넘어가는 현상

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
if (input == 0)
  {
          Displaystore();
  }
  else
  {
          foreach (var item in Item.Store)
          {
                  if (input == Item.Store.IndexOf(item) + 1 && !item.Buy)
                  {
                          Item.BuyReverse(item);
                          item.StoreAdd(item);
                          Item.Store.RemoveAt(input - 1);
                          Item.Store.Sort((a, b) => a.Name[0- b.Name[0]);
                          Character.setStatIncrease(item);
                          DisplaystoreBuyManagement();
                  }
                  else
                  {
                          break;
                  }
          }
          Console.WriteLine("이미 구매하신 아이템입니다.");
          
          DisplaystoreBuyManagement();
 
  }
 
 
cs



판매가 안되는 현상

함수명이 비슷해 헷갈려서 그렇게 됨..

 

함수명을 좀 어떻게 해야되나 .. 아니면 비슷한 문제를 이르키지 않게 씬 매니저를 사용해야 할듯!

 

팀 과제에선 좀 더 잘하자!

 

반응형