상세 컨텐츠

본문 제목

Study_005

C#/수업내용

by McRobbin 2020. 4. 8. 18:33

본문

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
350
351
352
353
354
355
356
357
358
359
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_005
{
    class App
    {
        //열거형 enum Days 선언.
        public enum Days
        {
            Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
        }
 
        public App()
        {
            Console.WriteLine("2020-04-08\n---------------------------------------------------------=n");
 
 
 
 
            /*
            //줄넘기 하기 while문
            int totalCount = 0;
            int currentCount = 0;
 
            while (true)
            {
                Console.Write("줄넘기를 몇 회 하시겠습니까? ");
                currentCount = int.Parse(Console.ReadLine());
                if(currentCount > 0)
                {
                    for(int i = 1; i <= currentCount; i++)
                    {
                        Console.WriteLine("줄넘기를 {0}회 했습니다. ", i);
                        totalCount++;
                    }
 
                }
 
                else if(currentCount == -1)
                {
                    Console.WriteLine("줄넘기를 총 {0}회 했습니다. ", totalCount);
                    break;
                }
 
                else
                {
                    Console.WriteLine("줄넘기 횟수는 {0} 보다 커야합니다. ", 0);
                }
            }
            Console.WriteLine("줄넘기를 종료합니다.");
            */
 
 
 
 
 
 
 
            /*
            //캐릭터 애니메이션 while
            Console.Write("캐릭터 이름 : ");
            string heroName = Console.ReadLine();
            Console.Write("애니메이션1 이름 : ");
            string animationName1 = Console.ReadLine();
            Console.Write("애니메이션1 총 프레임 : ");
            int animationTotalFrame1 = int.Parse(Console.ReadLine());
 
            Console.Write("애니메이션2 이름 : ");
            string animationName2 = Console.ReadLine();
            Console.Write("애니메이션2 총 프레임 : ");
            int animationTotalFrame2 = int.Parse(Console.ReadLine());
 
            Console.WriteLine("");
 
            while (true)
            {
 
                Console.Write("\n애니메이션을 실행하시려면 애니메이션 이름을 입력하세요. ");
                string inputAnimationName = Console.ReadLine();
 
                if (inputAnimationName == animationName1 || inputAnimationName == animationName2)
                {
                    int currentFrame = 0;
 
                    if (inputAnimationName != "idle")
                    {
                        currentFrame = 0;
                        while (true)
                        {
                            Console.WriteLine("{0}_{1}_{2:D3}", heroName, animationName2, ++currentFrame);
                            if (currentFrame == animationTotalFrame2)
                            {
                                Console.WriteLine("{0}_{1} animation complete\n", heroName, inputAnimationName);
                                break;
                            }
                        }
                    }
                    currentFrame = 0;
                    while (true)
                    {
                        Console.WriteLine("{0}_{1}_{2:D3}", heroName, animationName1, ++currentFrame);
                        if (currentFrame == animationTotalFrame1)
                        {
                            break;
                        }
                    }
 
                    Console.WriteLine("{0}_{1} animation complete", heroName, inputAnimationName);
 
                }
 
                else
                {
                    Console.WriteLine("해당 애니메이션이 없습니다.\n");
                }
            }
            */
 
 
 
 
 
 
 
 
            /*
            //SCV이동 장검 획득.
            int xPos = 0;
            int yPos = 0;
            int zPos = 0;
            int currentMoveCount = 0;
 
            int swordX = -4;
            int swordY = 2;
            int swordZ = 0;
            bool getSword = false;
 
            Console.Write("유닛 명 : ");
            string unitName = Console.ReadLine();
 
            Console.WriteLine("이동 명령어 : left 횟수, right 횟수, up 횟수, down 횟수, near 횟수, far 횟수");
            Console.WriteLine("유닛의 초기 위치 : (0, 0, 0)");
            Console.WriteLine("장검의 위치 : ({0}, {1}, {2})", swordX, swordY, swordZ);
 
            while (true) {
                Console.Write("\n유닛을 이동하려면 명령어를 입력 하세요. ");
                string[] input = Console.ReadLine().Split(' ');
                
                if(input.Length != 2)
                {
                    Console.WriteLine("올바르지 않은 명령어 입니다.");
                    continue;
                }
                currentMoveCount = 0;
                int moveDistance = int.Parse(input[1]);
 
                Console.WriteLine("({0}, {1}, {2})", xPos, yPos, zPos);
 
                while (true)
                {
                    if(input[0] == "left")
                    {
                        Console.WriteLine("({0}, {1}, {2})", --xPos, yPos, zPos);
                    }
                    else if (input[0] == "right")
                    {
                        Console.WriteLine("({0}, {1}, {2})", ++xPos, yPos, zPos);
                    }
                    else if (input[0] == "up")
                    {
                        Console.WriteLine("({0}, {1}, {2})", xPos, ++yPos, zPos);
                    }
                    else if (input[0] == "down")
                    {
                        Console.WriteLine("({0}, {1}, {2})", xPos, --yPos, zPos);
                    }
                    else if (input[0] == "near")
                    {
                        Console.WriteLine("({0}, {1}, {2})", xPos, yPos, --zPos);
                    }
                    else if (input[0] == "far")
                    {
                        Console.WriteLine("({0}, {1}, {2})", xPos, yPos, ++zPos);
                    }
                    else
                    {
                        Console.WriteLine("이동할 수 없습니다.");
                        break;
                    }
 
                    if (++currentMoveCount >= moveDistance)
                    {
                        break;
                    }
                    
                }
 
                if (xPos == swordX && yPos == swordY && zPos == swordZ)
                {
                    if (getSword)
                        Console.WriteLine("이미 장검을 획득했습니다.");
                    else
                    {
                        getSword = true;
                        Console.WriteLine("장검을 획득 했습니다.");
                    }
                }
 
            }
            */
 
 
 
 
 
 
 
 
 
            /*
            //switch 무기 구매.
            Console.WriteLine("Switch문 버전\n");
            while (true)
            {
                Console.WriteLine("상품 목록\n('장검', '단검', '활', '도끼', '종료')\n");
 
                Console.Write("구매하고자 하는 무기를 입력해 주세요.");
                string weapon = Console.ReadLine();
 
                switch (weapon)
                {
                    case "장검":
                        Console.WriteLine("장검을 구매했습니다.\n");
                        break;
 
                    case "단검":
                        Console.WriteLine("단검을 구매했습니다.\n");
                        break;
 
                    case "활":
                        Console.WriteLine("활을 구매했습니다.\n");
                        break;
 
                    case "도끼":
                        Console.WriteLine("도끼를 구매했습니다.\n");
                        break;
 
                    case "종료":
                        Console.WriteLine("종료합니다.");
                        break;
 
                    default:
                        Console.WriteLine("그런 무기는 없습니다.\n");
                        break;
                }
 
                if (weapon == "종료")
                    break;
            }
 
            Console.WriteLine("\n\nif - else문 버전");
            while (true)
            {
                Console.WriteLine("상품 목록\n('장검', '단검', '활', '도끼', '종료')\n");
 
                Console.Write("구매하고자 하는 무기를 입력해 주세요.");
                string weapon = Console.ReadLine();
            
                if(weapon == "종료")
                {
                    Console.WriteLine("종료합니다.");
                    break;
                }
 
                else if(weapon == "장검")
                {
                    Console.WriteLine("장검을 구매했습니다.\n");
                }
                else if (weapon == "단검")
                {
                    Console.WriteLine("단검을 구매했습니다.\n");
                }
                else if (weapon == "활")
                {
                    Console.WriteLine("활을 구매했습니다.\n");
                }
                else if (weapon == "도끼")
                {
                    Console.WriteLine("도끼을 구매했습니다.\n");
                }
                else
                {
                    Console.WriteLine("그런 무기는 없습니다.\n");
                }
            }
            */
 
 
 
 
 
 
 
 
            /*
            //월화수목금토일 출력.
            while (true)
            {
                Console.WriteLine("0 : 월, 1 : 화, 2 : 수, 3 : 목, 4 : 금, 5 : 토, 6 : 일");
                Console.Write("요일을 입력해 주세요.");
                int day = int.Parse(Console.ReadLine());
 
                switch (day)
                {
                    case 0:
                        Console.WriteLine("\n===> {0}, 월요일", day);
                        break;
 
                    case 1:
                        Console.WriteLine("\n===> {0}, 화요일", day);
                        break;
 
                    case 2:
                        Console.WriteLine("\n===> {0}, 수요일", day);
                        break;
 
                    case 3:
                        Console.WriteLine("\n===> {0}, 목요일", day);
                        break;
 
                    case 4:
                        Console.WriteLine("\n===> {0}, 금요일", day);
                        break;
 
                    case 5:
                        Console.WriteLine("\n===> {0}, 토요일", day);
                        break;
 
                    case 6:
                        Console.WriteLine("\n===> {0}, 일요일", day);
                        break;
 
                    default:
                        Console.WriteLine("\n없는 요일입니다. ");
                        break;
 
                }
            }
            */
 
 
        }
    }
}
 
 
 

while문 , switch문 사용 예제.

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_005
{
    class EnumEx
    {//열거형 enum Days 선언.
        public enum Days
        {
            Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
        }
 
        public enum Weapons
        {
            Sword, Bow, Axe
        }
 
        public enum Grade
        {
            Normal, Rare, Legend
        }
 
        public enum ClassesType
        {
            Human, Dwarf, NightElf
        }
 
        public enum Human
        {
            Warrior, Rogue
        }
 
        public enum Dwarf
        {
            Hunter, Priest
        }
 
        public enum NightElf
        {
            Mage, Monk
        }
 
 
        public EnumEx()
        {
            Console.WriteLine("2020-04-08\n---------------------------------------------------------=n");
 
 
 
 
            /*
            //enum 열거형 예제.
            var day = 0;
            var day2 = (Days)day;
 
            Console.WriteLine("{0}. {1}", day, day2);
            */
 
 
 
 
 
 
 
 
 
            /*
            //열거형 예제 무기 착용.
            while (true)
            {
                Console.WriteLine("{0}: {1}, {2}: {3}, {4}: {5}", (int)Weapons.Sword, Weapons.Sword, (int)Weapons.Bow, Weapons.Bow, (int)Weapons.Axe, Weapons.Axe);
                Console.Write("착용하시려는 아이템을 입력 하세요.");
                Weapons weapon = (Weapons)int.Parse(Console.ReadLine());
 
                switch (weapon)
                {
                    case Weapons.Sword:
 
                    case Weapons.Bow:
 
                    case Weapons.Axe:
                        Console.WriteLine("{0}을 착용했습니다.\n", weapon);
                        break;
 
                    default:
                        Console.WriteLine("해당 무기는 없습니다.\n");
                        break;
                }
            }
            */
 
 
 
 
 
 
 
            /*
            //열거형 예제
            while (true) {
                Console.Write("아이템의 타입은 무엇입니까? (0 ~ 2) ");
                Weapons weaponType = (Weapons)int.Parse(Console.ReadLine());
 
                Console.Write("생성할 아이템의 이름을 입력하세요. ");
                string weaponName = Console.ReadLine();
 
                Console.Write("아이템의 등급은 무엇입니까?(0 ~ 2) ");
                Grade weaponGrade = (Grade)int.Parse(Console.ReadLine());
 
                Console.Write("아이템의 공격력은 몇입니까? ");
                float weaponDamage = float.Parse(Console.ReadLine());
 
                Console.WriteLine("\n아이템이 생성되었습니다.\n==================================================");
                Console.WriteLine("아이템명 : {0}", weaponName);
                switch (weaponType)
                {
                    case Weapons.Sword:
                    case Weapons.Axe:
                    case Weapons.Bow:
                        Console.WriteLine("아이템 타입 : {0}", weaponType);
                        break;
                    default:
                        Console.WriteLine("아이템 타입이 없습니다. ");
                        break;
                }
 
                switch (weaponGrade)
                {
                    case Grade.Legend:
                    case Grade.Normal:
                    case Grade.Rare:
                        Console.WriteLine("아이템 등급 : {0}", weaponGrade);
                        break;
                    default:
                        Console.WriteLine("아이템 등급이 없습니다. ");
                        break;
                }
 
                Console.WriteLine("아이템 공격력 : {0}\n", weaponDamage);
            }
            */
 
 
 
 
 
 
 
 
 
            /*
            //열거형 예제 weapon3
            while (true)
            {
                Console.Write("착용할 아이템의 이름을 입력하세요. ");
                Weapons inputWeapon = (Weapons)Enum.Parse(typeof(Weapons), Console.ReadLine());
                
                switch (inputWeapon)
                {
                    case Weapons.Sword:
                        Console.WriteLine("{0}을 착용했습니다.", inputWeapon);
                        break;
                    case Weapons.Axe:
                        Console.WriteLine("{0}을 착용했습니다.", inputWeapon);
                        break;
                    case Weapons.Bow:
                        Console.WriteLine("{0}을 착용했습니다.", inputWeapon);
                        break;
                    default:
                        Console.WriteLine("없습니다.");
                        break;
                }
            }
            */
 
 
 
 
 
 
 
 
 
            //워크래프트 열거형 예제.
            //(0:Human, 1:Dwarf, 2:NightElf)
            //종족을 선택 해주세요. 0
 
            //Human을 선택 했습니다.
 
            //(0:Warrior, 1:Rogue)
            //직업을 선택 해주세요. 1
 
            //케릭터(Human, Rogue)가 생성되었습니다.
 
            while (true)
            {
                Console.WriteLine("(0:Human, 1:Dwarf, 2:NightElf)");
                Console.Write("종족을 선택 해주세요. for the 호드. ");
                ClassesType userClass = (ClassesType)int.Parse(Console.ReadLine());
                int subClass = 0;
 
                switch (userClass)
                {
                    case ClassesType.Human:
                        Console.WriteLine("{0}을 선택했습니다. for the 호드\n ", userClass);
                        Console.WriteLine("0 : Warrior, 1 : Rogue");
                        Console.Write("직업을 선택해 주세요.");
                        subClass = int.Parse(Console.ReadLine());
                        Console.WriteLine("캐릭터 ({0} {1})가 생성되었습니다. for the 호드", userClass, (Human)subClass);
                        break;
                    case ClassesType.Dwarf:
                        Console.WriteLine("{0}을 선택했습니다. for the 호드\n ", userClass);
                        Console.WriteLine("0 : Hunter, 1 : Priest");
                        Console.Write("직업을 선택해 주세요.");
                        subClass = int.Parse(Console.ReadLine());
                        Console.WriteLine("캐릭터 ({0} {1})가 생성되었습니다. for the 호드", userClass, (Dwarf)subClass);
                        break;
                    case ClassesType.NightElf:
                        Console.WriteLine("{0}을 선택했습니다. for the 호드\n ", userClass);
                        Console.WriteLine("0 : Mage, 1 : Monk");
                        Console.Write("직업을 선택해 주세요.");
                        subClass = int.Parse(Console.ReadLine());
                        Console.WriteLine("캐릭터 ({0} {1})가 생성되었습니다. for the 호드", userClass, (NightElf)subClass);
                        break;
                    default:
                        Console.WriteLine("없는 클래스 입니다. for the 호드\n");
                        break;
                }
            }
 
 
        }
 
    }
}
 
 
 

 

Enum 열거형 예제.

 

1. Enum 열거형의 선언

Enum 열거형의 선언은 enum Weapons = {Sword, Bow, Axe}와 같이 선언 가능.

이렇게 선언시 Sword = 0, Bow = 1, Axe = 2와 같이 0부터 자동으로 값이 할당 됨.

또한 자동으로 할당되는 값은 enum Weapons = {Sword = 1, Bow = 6, Axe = 7}과 같이

직접 할당할 수 있음.

 

2. 다른 타입을 Enum으로

public static object Parse (Type enumType, string value);

Type에 enum의 타입, value에 string 값을 넣으면 해당 enum의 값으로 변환.

 

ex) enum Weapons = {Sword, Axe, Bow}

Weapons parsed = (Weapons)Enum.Parse(typeof(Weapons), "Sword");

Console.WriteLine("{0}", parsed); ====> Sword가 출력되며 이는 parsed.ToString()임.

 

입력받는 string value의 값이 열거된 enum안에 없거나 null일 경우 오류 발생. 이런 상황 방지를 위해

Enum.TryParse(string inputEnum, out TEnum outputEnum); 을 사용할 수 있음.

 

ex) enum Weapons \ {Sword, Axe, Bow}

Weapons result; ==> TryParse의 결과로 받을 Enum타입 변수.

string input = "Sword" ==> Enum타입으로 변경할 string 문자.

bool parseable = Enum.TryParse(input, out result);

지정한 Enum타입으로 변환 가능하다면 true를, 아니라면 자동으로 false리턴.

결과가 true라면 out result변수에 변환된 Enum값이 반환됨.

 

Weapons weapon = (Weapons)Weapons.Sword

이와 같이 Parse의 함수가 아닌 명시적 형변환으로 변환 가능.

 

3. 선언의 위치에 따른 차이.

enum Weapons{Sword, Bow, Axe}의 선언을 클래스 내부와 클래스 외부에(namespace 안에) 선언 가능.

클래스 내부에 선언시 App 클래스 안에 선언했다면 App.Weapons.Sword와 같이 사용 가능.

클래스 외부에 선언시 Weapons.Sword만으로 사용 가능.

'C# > 수업내용' 카테고리의 다른 글

Study_008 클래스 예제  (0) 2020.04.13
Study_006-1  (0) 2020.04.09
Study004  (0) 2020.04.08
Study003-01  (0) 2020.04.06
Study_002-2  (0) 2020.04.03

관련글 더보기