찾아볼것 리스트

Unity/찾아볼것 2019. 4. 12. 20:28

프리팹




게임오브젝트 검색하기!

Object.FindObjectOfType

https://tenlie10.tistory.com/90

'Unity > 찾아볼것' 카테고리의 다른 글

unity editor select list  (0) 2019.08.21
custom Inspector 겹치기 오류  (0) 2019.07.23
<uBMSC> 리듬게임  (0) 2019.05.09
Unity Editor확장입문 참고  (0) 2019.05.07
:

<죽어라돌덩이>

Unity/수업내용 2019. 4. 12. 01:40




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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public GameObject heroGo;
    public GameObject monsterGo;
    
    // Start is called before the first frame update
    void Start()
    {
        var hero = this.heroGo.GetComponent<Character>();
        var monster = this.monsterGo.GetComponent<Character>();
 
        hero.Init(new Vector3(101));
        monster.Init(new Vector3(505));
 
 
        hero.Move(monster);
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Character : MonoBehaviour
{
    private float speed = 1f;
    private float lange = 0.7f;
    private int hp = 10;
    private Vector3 targetPosition;
    private Vector3 attackTargetPosition;
    private float moveDis;
 
    private Character target;
 
    private bool isMoveComplete = false;
    private bool isMoveStart = false;
 
    private bool isAttackStart = false;
 
    private Animation anim;
 
    private float timer = 0.0f;
    private float waitingTime = 1.5f;
    // Start is called before the first frame update
    void Start()
    {
        this.anim = this.gameObject.GetComponent<Animation>();
    }
 
    public void Init(Vector3 initPosition)
    {
        this.gameObject.transform.position = initPosition;
    }
 
    public void Move(Character target)
    {
        this.target = target;
        this.targetPosition = target.gameObject.GetComponent<Character>().transform.position;
        this.moveDis = Vector3.Distance(this.targetPosition, this.gameObject.GetComponent<Character>().transform.position);
        this.isMoveStart = true;
    }
 
    public void MoveStart()
    {
        anim.Play("run@loop");
        var normVec = (this.targetPosition - this.gameObject.GetComponent<Character>().transform.position).normalized;
 
        if (isMoveComplete == false)
        {
            if (moveDis > this.lange)
            {
                //계속앞으로 이동
                moveDis -= speed * Time.deltaTime;
                this.gameObject.GetComponent<Character>().transform.position += this.speed * normVec * Time.deltaTime;
            }
            else
            {
                isMoveStart = false;
                isMoveComplete = true;
                isAttackStart = true;
                anim.Play("idle@loop");
            }
        }
    }
 
    public void AttackStart()
    {
        anim.Play("attack_sword_01");
        var normVec = (this.targetPosition - this.gameObject.GetComponent<Character>().transform.position).normalized;
        
        this.target.gameObject.GetComponent<Animation>().Play("Anim_Damage");
        this.hp--;
        
        Debug.Log(this.hp);
 
        if (this.hp <= -1)
        {
            Debug.Log("으앙쥬금");
            anim.Play("idle@loop");
            this.isAttackStart = false;
        }
    }
 
    // Update is called once per frame
    void Update()
    {
        if(this.hp<=-1)
        {
            this.target.gameObject.GetComponent<Animation>().Play("Anim_Death");
            this.hp = 0;
        }
        if (isMoveStart == true)
        {
            this.MoveStart();
        }
        this.timer += Time.deltaTime;
        if(this.timer>waitingTime)
        {
            if (isAttackStart == true)
            {
                this.AttackStart();
            }
            this.timer = 0;
        }
    }
}
 
cs


//고개돌리기, 타이밍싱크, 공격방식 바꾸면서 때리기

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

(1)BGLoop  (0) 2019.05.01
LayerMask  (0) 2019.05.01
자습서1(WASD이동, 마우스 포인트 Look, 라인렌더링  (0) 2019.04.30
<캐릭터 조작>화면 터치, WASD, 조이스틱  (0) 2019.04.25
HUDTest  (0) 2019.04.25
:

<바론과 애니비아 쌈박질>

C#/과제 2019. 4. 11. 01:37



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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Annivia : Champion, IMoveAble, IAttackable
    {
        public virtual void Move(Vector2 movePos)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
 
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, movePos);
            while (true)
            {
                if (dis > 0)
                {
                    System.Threading.Thread.Sleep(500);
                    var dir = (movePos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * data.speed;
 
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    dis -= data.speed;
                }
                else
                {
                    this.characterInfo.pos = movePos;
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})에 도착했습니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    break;
                }
            }
        }
 
        //기능구현 사정거리 안에 있는 놈 때리기
        public void Attack(Character target)
        {
            var thisData = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            var targetData = DataManager.GetInstance().dicCharacterData[target.characterInfo.id];
 
            //사거리 안에있으면 때림, 사거리 안에 없으면 이동함
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, target.characterInfo.pos);
            while (true)
            {
                System.Threading.Thread.Sleep(500);
                if (dis > thisData.range)
                {
                    var dir = (target.characterInfo.pos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * thisData.speed;
 
                    //움직임
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", thisData.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
 
                    dis -= thisData.speed;
                }
                else
                {
                    //멈춰서 때림
                    Console.WriteLine("{0}이(가) {1}을(를) 공격합니다.", thisData.name, targetData.name);
                    //때리면 데미지 들어감
                    target.TakeDamage(thisData.damage);
                    break;
                }
            }
        }
    }
}
 
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 TestBattle
{
    public class App
    {
        public App()
        {
 
        }
 
        public void Start()
        {
            new GameLauncher();
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public interface IAttackable
    {
        void Attack(Character target);
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Baron : Monster, IAttackable
    {
        //기능구현 사정거리 안에 있는 놈 때리기
        public void Attack(Character target)
        {
            var thisData = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            var targetData = DataManager.GetInstance().dicCharacterData[target.characterInfo.id];
 
            //사거리 안에있으면 때림, 사거리 안에 없으면 안때림, 바론은 이동모테
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, target.characterInfo.pos);
 
            System.Threading.Thread.Sleep(500);
            if (dis > thisData.range)
            {
                Console.WriteLine("{0}이(가) 사정거리:{1} 밖에 있습니다.", targetData.name, thisData.range);
            }
            else
            {
                System.Threading.Thread.Sleep(500);
                //사거리안에 들어오면 때림
                Console.WriteLine("{0}이(가) {1}을(를) 공격합니다.", thisData.name, targetData.name);
                //때리면 데미지 들어감
                target.TakeDamage(thisData.damage);
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Champion : Character
    {
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Character
    {
        public CharacterInfo characterInfo;
 
        //기본 생성자
        public Character()
        {
 
        }
 
        //인포받아 생성자
        public Character(CharacterInfo characterInfo)
        {
            this.characterInfo = characterInfo;
        }
 
        //기능구현 데미지 받기
        public virtual void TakeDamage(int damage)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
 
            if (this.characterInfo.hp > 0)
            {
                this.characterInfo.hp -= damage;
                if(this.characterInfo.hp <= 0)
                {
                    this.characterInfo.hp = 0;
                }
            }
            Console.WriteLine("{0}이(가) {1}의 피해를 입었습니다.\n남은체력:({2}/{3})", data.name, damage, this.characterInfo.hp, data.hp);
        }
    }
}
 
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 TestBattle
{
    public class CharacterData
    {
        public int id;
        public int type;
        public string name;
        public int hp;
        public int damage;
        public float range;
        public float speed;
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class CharacterInfo
    {
        public int id;
        public int hp;
        public Vector2 pos;
        public bool alive;
    }
}
 
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Newtonsoft.Json;
 
namespace TestBattle
{
    public class DataManager
    {
        private static DataManager Instance;
        public Dictionary<int, CharacterData> dicCharacterData;
 
        public DataManager()
        {
            this.dicCharacterData = new Dictionary<int, CharacterData>();
        }
 
        public static DataManager GetInstance()
        {
            if (DataManager.Instance == null)
            {
                DataManager.Instance = new DataManager();
            }
            return DataManager.Instance;
        }
 
        public void DataLoad(string path)
        {
            if (File.Exists(path))
            {
                //데이터 불러오기
                var json = File.ReadAllText(path);
                var CharacterDatas = JsonConvert.DeserializeObject<CharacterData[]>(json);
                foreach (var data in CharacterDatas)
                {
                    this.dicCharacterData.Add(data.id, data);
                }
                Console.WriteLine("데이터 로드 완료");
            }
            else
            {
                Console.WriteLine("데이터 파일이 없습니다.");
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Eggnnivia : Champion
    {
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class GameInfo
    {
        public List<CharacterInfo> characterInfos;
 
        public GameInfo()
        {
            this.characterInfos = new List<CharacterInfo>();
        }
    }
}
 
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
350
351
352
353
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class GameLauncher
    {
        //캐릭터들 전역변수
        private Baron baron = null;
        private Annivia annivia = null;
        private Eggnnivia eggnnivia = null;
 
        //스위치코드
        private int switchCode = 0;
 
        //유저인포
        private UserInfo userInfo;
        //캐릭터 리스트
        private List<Character> characters = new List<Character>();
 
        public GameLauncher()
        {
            //게임 시작 전 준비
            this.ReadyToStart();
 
            //게임시작
            this.GameStart();
 
            //유저인포 저장(싱크 맞추고 저장)
            this.SaveUserInfo();
            //런쳐 종료
        }
 
        private void ReadyToStart()
        {
            Console.WriteLine("게임 데이터 준비중입니다. 잠시만 기다려주세요.");
            //데이터 로드
            DataManager.GetInstance().DataLoad("./data/character_data.Json");
            //신구 유저 확인
            ExistsUserInfo("./info");
            //사전 준비완료
        }
 
        private void GameStart()
        {
            Console.WriteLine("게임이 시작되었습니다.");
 
            #region 캐릭터 생성
            if (this.userInfo.NewbieCheck == false)
            {
                //기존유저
                baron = (Baron)this.CreateCharacter<Baron>(this.userInfo.gameInfo.characterInfos[0]);
                annivia = (Annivia)this.CreateCharacter<Annivia>(this.userInfo.gameInfo.characterInfos[1]);
                eggnnivia = (Eggnnivia)this.CreateCharacter<Eggnnivia>(this.userInfo.gameInfo.characterInfos[2]);
            }
            else
            {
                //신규유저
                baron = this.CreateCharacter<Baron>(0);
                annivia = this.CreateCharacter<Annivia>(1);
                eggnnivia = this.CreateCharacter<Eggnnivia>(2);
            }
            baron.characterInfo.pos = new Vector2(1010);
            this.characters.Add(baron);
            this.characters.Add(annivia);
            this.characters.Add(eggnnivia);
            #endregion
 
            #region 게임진행
            if (annivia.characterInfo.alive == true)
            {
                switchCode = 0;
            }
            else
            {
                switchCode = 1;
            }
 
            while (true)
            {
                if (switchCode == 0)
                {
                    this.AnniviaGameStart();
                }
                else if (switchCode == 1)
                {
                    this.EggnniviaGameStart();
                }
                else if (switchCode==-1)
                {
                    break;
                }
            }
            #endregion
 
            //게임종료
        }
 
        //유저 정보 불러오기(신규 or 기존)
        private void ExistsUserInfo(string path)
        {
            if (Directory.Exists(path))
            {
                //기존 유저
                Console.WriteLine("기존 유저입니다.");
                //캐릭터 인포 불러오기
                this.userInfo = this.LoadUserInfo("./info/user_info.json");
                this.userInfo.NewbieCheck = false;
            }
            else
            {
                //신규 유저
                Console.WriteLine("신규 유저입니다.");
                //./info폴더 만들기
                Directory.CreateDirectory(path);
                //캐릭터 인포만들기
                this.CreateUserInfo();
                this.userInfo.NewbieCheck = true;
            }
        }
 
        //유저 정보 불러오기 - 1(기존 유저 인포 불러오기)
        private UserInfo LoadUserInfo(string path)
        {
            //./info/user_info.json불러오기
            var json = File.ReadAllText(path);
            return JsonConvert.DeserializeObject<UserInfo>(json);
        }
 
        //유저 정보 불러오기 - 2(신규 유저 인포 생성)
        private void CreateUserInfo(UserInfo userInfo = null)
        {
            if (this.userInfo == null)
            {
                if (userInfo == null)
                {
                    this.userInfo = new UserInfo();
                }
                else
                {
                    this.userInfo = userInfo;
                }
            }
        }
 
        //기존유저 캐릭터 인스턴스 생성(불러오기)
        private T CreateCharacter<T>(CharacterInfo characterInfo) where T : Character, new()
        {
            T character = new T();
            character.characterInfo = characterInfo;
            return character;
        }
 
        //신규유저 캐릭터 인스턴스 생성(새로만들기)
        private T CreateCharacter<T>(int id) where T : Character, new()
        {
            var data = DataManager.GetInstance().dicCharacterData[id];
            var info = new CharacterInfo();
            info.id = data.id;
            info.hp = data.hp;
            info.pos = new Vector2(00);
            info.alive = true;
 
            T character = new T();
            character.characterInfo = info;
 
            return character;
        }
 
        private void SaveUserInfo()//json
        {
            //현재의 유저인포(게임인포(캐릭터인포List)))를 유저인포에 저장
            var characterInfos = new List<CharacterInfo>();
            foreach (var character in this.characters)
            {
                characterInfos.Add(character.characterInfo);
            }
            this.userInfo.gameInfo.characterInfos = characterInfos;
 
            //파일 쓰기
            var json = JsonConvert.SerializeObject(this.userInfo);
            File.WriteAllText("./info/user_info.json", json, Encoding.UTF8);
            Console.WriteLine("저장완료");
        }
 
        private void AnniviaGameStart()
        {
            while (true)//애니비아버전
            {
                Console.WriteLine();
                Console.WriteLine("=============================================================================================");
                Console.Write("[바론의 위치({0}, {1})]\n1.애니비아(이동)/2.애니비아(공격)/3.바론(공격)/4.정보 보기/0.종료 후 저장(숫자 입력):", baron.characterInfo.pos.x, baron.characterInfo.pos.y);
                var input = Console.ReadLine();
 
                if (input == "0")
                {
                    //게임 종료
                    Console.WriteLine("게임을 종료합니다.");
                    switchCode = -1;
                    break;
                }
                else if (input == "1")
                {
                    Console.Write("(x, y)좌표 입력\nx좌표 : ");
                    var x = Console.ReadLine();
                    Console.Write("y좌표 : ");
                    var y = Console.ReadLine();
 
                    float resultX, resultY;
                    if (float.TryParse(x, out resultX) && float.TryParse(y, out resultY))
                    {
                        var movePos = new Vector2(resultX, resultY);
                        annivia.Move(movePos);
                    }
                    else
                    {
                        Console.WriteLine("잘못된 입력입니다.");
                    }
                }
                else if (input == "2")
                {
                    annivia.Attack(baron);
                    if (baron.characterInfo.hp <= 0)
                    {
                        Console.WriteLine("바론이 죽었습니다.10초후에 부활합니다.");
                        for (int i = 10; i > 0; i--)
                        {
                            System.Threading.Thread.Sleep(1000);
                            Console.WriteLine(i);
                        }
                        baron.characterInfo.hp = DataManager.GetInstance().dicCharacterData[0].hp;
                        Console.WriteLine("{0}:크와아아아아아앙({0}이 부활했습니다.) Hp:{1}/{2}", DataManager.GetInstance().dicCharacterData[0].name, baron.characterInfo.hp, DataManager.GetInstance().dicCharacterData[0].hp);
                    }
                }
                else if (input == "3")
                {
                    baron.Attack(annivia);
                    if (annivia.characterInfo.hp <= 0)
                    {
                        Console.WriteLine("애니비아가 죽었습니다.");
                        annivia.characterInfo.alive = false;
                        eggnnivia.characterInfo.alive = true;
                        eggnnivia.characterInfo.pos = annivia.characterInfo.pos;
                        annivia.characterInfo.hp = DataManager.GetInstance().dicCharacterData[1].hp;
                        eggnnivia.characterInfo.hp = DataManager.GetInstance().dicCharacterData[2].hp;
 
                        Console.WriteLine("에그니비아 : 아 정글차이");
                        switchCode = 1;
                        break;
                    }
                }
                else if(input == "4")
                {
                    var data = DataManager.GetInstance().dicCharacterData[0];
                    Console.WriteLine("=============================================================================================");
                    Console.WriteLine("{0}의 정보", DataManager.GetInstance().dicCharacterData[0].name);
                    Console.WriteLine("위치 : ({0}, {1}), 체력 : ({2}/{3})\n공격력 : {4}, 사거리 : {5}, 이동속도 : {6}", baron.characterInfo.pos.x, baron.characterInfo.pos.y, baron.characterInfo.hp, data.hp, data.damage, data.range, data.speed);
                    data = DataManager.GetInstance().dicCharacterData[1];
                    Console.WriteLine("=============================================================================================");
                    Console.WriteLine("{0}의 정보", DataManager.GetInstance().dicCharacterData[1].name);
                    Console.WriteLine("위치 : ({0}, {1}), 체력 : ({2}/{3})\n공격력 : {4}, 사거리 : {5}, 이동속도 : {6}", annivia.characterInfo.pos.x, annivia.characterInfo.pos.y, annivia.characterInfo.hp, data.hp, data.damage, data.range, data.speed);
                }
                else
                {
                    Console.WriteLine("잘못된 입력입니다.");
                }
            }
        }
 
        private void EggnniviaGameStart()
        {
            while (true)//에그니비아버전
            {
                Console.WriteLine();
                Console.WriteLine("=============================================================================================");
                Console.Write("[바론의 위치({0}, {1})]\n1.애그니비아(이동)/2.애그니비아(공격)/3.바론(공격)/4.애니비아(즉시부활)/5.정보 보기/0.종료 후 저장(숫자 입력):", baron.characterInfo.pos.x, baron.characterInfo.pos.y);
                var input = Console.ReadLine();
 
                if (input == "0")
                {
                    //게임 종료
                    Console.WriteLine("게임을 종료합니다.");
                    switchCode = -1;
                    break;
                }
                else if (input == "1")
                {
                    Console.WriteLine("{0}은(는) 이동할 수 없습니다.", DataManager.GetInstance().dicCharacterData[2].name);
                }
                else if (input == "2")
                {
                    Console.WriteLine("{0}은(는) 공격할 수 없습니다.", DataManager.GetInstance().dicCharacterData[2].name);
                }
                else if (input == "3")
                {
                    baron.Attack(eggnnivia);
                    if (eggnnivia.characterInfo.hp <= 0)
                    {
                        Console.WriteLine("에그니비아가 죽었습니다.");
                        eggnnivia.characterInfo.alive = false;
                        annivia.characterInfo.alive = true;
                        annivia.characterInfo.pos = new Vector2(00);
 
                        Console.WriteLine("10초후에 본진(0, 0)에서 부활합니다.");
                        for (int i = 10; i > 0; i--)
                        {
                            System.Threading.Thread.Sleep(1000);
                            Console.WriteLine(i);
                        }
                        Console.WriteLine("{0} : 자, 날아볼까요?", DataManager.GetInstance().dicCharacterData[1].name);
                        annivia.characterInfo.hp = DataManager.GetInstance().dicCharacterData[1].hp;
 
                        switchCode = 0;
                        break;
                    }
                }
                else if (input == "4")
                {
                    Console.WriteLine("애니비아가 즉시 부활합니다.");
                    eggnnivia.characterInfo.alive = false;
                    annivia.characterInfo.alive = true;
 
                    Console.WriteLine("{0} : 내 날개를 타고.", DataManager.GetInstance().dicCharacterData[1].name);
                    annivia.characterInfo.hp = eggnnivia.characterInfo.hp;
 
                    switchCode = 0;
                    break;
                }
                else if (input == "5")
                {
                    var data = DataManager.GetInstance().dicCharacterData[0];
                    Console.WriteLine("=============================================================================================");
                    Console.WriteLine("{0}의 정보", DataManager.GetInstance().dicCharacterData[0].name);
                    Console.WriteLine("위치 : ({0}, {1}), 체력 : ({2}/{3})\n공격력 : {4}, 사거리 : {5}, 이동속도 : {6}", baron.characterInfo.pos.x, baron.characterInfo.pos.y, baron.characterInfo.hp, data.hp, data.damage, data.range, data.speed);
                    data = DataManager.GetInstance().dicCharacterData[2];
                    Console.WriteLine("=============================================================================================");
                    Console.WriteLine("{0}의 정보", DataManager.GetInstance().dicCharacterData[2].name);
                    Console.WriteLine("위치 : ({0}, {1}), 체력 : ({2}/{3})\n공격력 : {4}, 사거리 : {5}, 이동속도 : {6}", eggnnivia.characterInfo.pos.x, eggnnivia.characterInfo.pos.y, eggnnivia.characterInfo.hp, data.hp, data.damage, data.range, data.speed);
                }
                else
                {
                    Console.WriteLine("잘못된 입력입니다.");
                }
            }
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Monster : Character
    {
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public interface IMoveAble
    {
        void Move(Vector2 movePos);
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
            app.Start();
            Console.ReadKey();
        }
    }
}
 
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 TestBattle
{
    public class UserInfo
    {
        public GameInfo gameInfo;
        public bool NewbieCheck;
 
        public UserInfo()
        {
            this.gameInfo = new GameInfo();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestBattle
{
    public class Vector2
    {
        public float x, y;
 
        public Vector2(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
 
        public static Vector2 operator +(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x + v2.x, v1.y + v2.y);
        }
 
        public static Vector2 operator -(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x - v2.x, v1.y - v2.y);
        }
 
        public static Vector2 operator *(Vector2 v1, float Value)
        {
            return new Vector2(v1.x * Value, v1.y * Value);
        }
 
        public static Vector2 operator /(Vector2 v1, float Value)
        {
            return new Vector2(v1.x / Value, v1.y / Value);
        }
 
        public float Dot(Vector2 v1, Vector2 v2)//스칼라 곱
        {
            return v1.x * v2.x + v1.y * v2.y;
        }
 
        public float GetDistance(Vector2 v1, Vector2 v2)
        {
            return (float)(Math.Sqrt(Math.Pow(v1.x - v2.x, 2+ Math.Pow(v1.y - v2.y, 2)));
        }
 
        public Vector2 Normalize()
        {
            var dis = (float)Math.Sqrt(Math.Pow(this.x, 2+ Math.Pow(this.y, 2));
 
            return new Vector2(this.x / dis, this.y / dis);
        }
    }
}
 
cs


:

<Overload, Override>, .json없이 .dat으로

C#/과제 2019. 4. 10. 01:41
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 _20190409
{
    public class Annivia : Champion
    {
        public Annivia()
        {
            this.speed = 3;
        }
    }
}
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class App
    {
        GameLauncher gameLauncher;
 
        public App()
        {
            this.gameLauncher = new GameLauncher();
        }
 
        public void Start()
        {
            Console.WriteLine("앱 실행");
            this.gameLauncher.Start();
        }
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class BaronNashor : Monster
    {
        public BaronNashor()
        {
            this.speed = 0;
        }
 
        public override void Move(Vector2 movePos)
        {
            Console.WriteLine("바론은 움직일 수 없습니다.");
        }
    }
}
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.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class BinaryManager
    {
        public BinaryManager()
        {
 
        }
 
        public void SerializeObject<T>(T obj, string path)
        {
            object saveInfo = obj;
 
            BinaryFormatter formatter = new BinaryFormatter();
            Stream str = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(str, saveInfo);
            str.Close();
        }
 
        public T DeSerializeObject<T>(string path)
        {
            var info = File.ReadAllText(path);
            BinaryFormatter formatter = new BinaryFormatter();
            Stream str = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            T obj = (T)formatter.Deserialize(str);
            str.Close();
            return obj;
        }
 
        public T DeSerializeDatas<T>(string path)
        {
            var info = File.ReadAllText(path);
            BinaryFormatter formatter = new BinaryFormatter();
            Stream str = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            var obj = formatter.Deserialize(str);
            str.Close();
            var temp = (T)obj;
            return temp;
        }
 
        //제이슨 파일만 있고, dat파일 없을때 Json으로 dat파일 만들기(Json필요함)
        #region
        /*public void JsonToDat<T>(Dictionary<int, T> data, string path) where T : CharacterData
        {
            object saveData = data;
            BinaryFormatter formatter = new BinaryFormatter();
            Stream str = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
            formatter.Serialize(str, saveData);
            str.Close();
        }*/
        #endregion
    }
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Champion : Character
    {
    }
}
 
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Character
    {
        public CharacterInfo characterInfo;
        public int speed;
 
        public Character()
        {
 
        }
 
        public Character(CharacterInfo characterInfo)
        {
            this.characterInfo = characterInfo;
        }
 
        public virtual void Move(Vector2 movePos)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
 
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, movePos);
            while (true)
            {
                if (dis > 0)
                {
                    System.Threading.Thread.Sleep(500);
                    var dir = (movePos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * speed;
 
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    dis -= speed;
                }
                else
                {
                    this.characterInfo.pos = movePos;
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})에 도착했습니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    break;
                }
            }
        }
 
        public virtual void Attack(Character target)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            var targetData = DataManager.GetInstance().dicCharacterData[target.characterInfo.id];
 
            //사거리 안에있으면 때림, 사거리 안에 없으면 이동함
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, target.characterInfo.pos);
            while (true)
            {
                System.Threading.Thread.Sleep(500);
                if (dis > data.range)
                {
                    var dir = (target.characterInfo.pos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * speed;
                    //움직임
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
 
                    dis -= this.speed;
                }
                else
                {
                    //멈춰서 때림
                    Console.WriteLine("{0}이(가) {1}을(를) 공격합니다.", data.name, targetData.name);
                    //때리면 데미지 들어감
                    target.TakeDamage(data.damage);
                    break;
                }
            }
        }
 
        public virtual void TakeDamage(int damage)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            this.characterInfo.hp -= damage;
            Console.WriteLine("{0}이(가) {1}의 피해를 입었습니다.\n남은체력:({2}/{3})", data.name, damage, this.characterInfo.hp, data.hp);
        }
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    [Serializable]
    public class CharacterData
    {
        public int id;
        public int type;
        public string name;
        public int hp;
        public int damage;
        public float range;
    }
}
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 _20190409
{
    [Serializable]
    public class CharacterInfo
    {
        public int id;
        public int hp;
        public Vector2 pos;
    }
}
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace _20190409
{
    public class DataManager
    {
        private static DataManager Instance;
        public Dictionary<int, CharacterData> dicCharacterData= new Dictionary<int, CharacterData>();
 
        private DataManager()
        {
            this.dicCharacterData = new Dictionary<int, CharacterData>();
        }
 
        public static DataManager GetInstance()
        {
            if (DataManager.Instance == null)
            {
                DataManager.Instance = new DataManager();
            }
            return DataManager.Instance;
        }
 
        public void LoadData(string path)
        {
            if (File.Exists(path))
            {
                var temp = new BinaryManager();
                var characterDatas = temp.DeSerializeDatas<Dictionary<int, CharacterData>>(path);
                this.dicCharacterData = characterDatas;
            }
            else
            {
                Console.WriteLine("파일 불러오기 실패, dat파일과 json파일이 없습니다.");
            }
 
            //제이슨 파일만 있고, dat파일 없을때 Json으로 dat파일 만들기(Json필요함)
            #region
            /*if (File.Exists("./data/character_data.json"))
            {
                Console.WriteLine("dat파일이 없습니다. json파일이 있으면 변환합니다.");
                var json = File.ReadAllText("./data/character_data.json");
                var characterDatas = JsonConvert.DeserializeObject<CharacterData[]>(json);
                foreach (var data in characterDatas)
                {
                    this.dicCharacterData.Add(data.id, data);
                }
                new BinaryManager().JsonToDat<CharacterData>(this.dicCharacterData, path);
            }*/
            #endregion
        }
    }
}
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 _20190409
{
    [Serializable]
    public class GameInfo
    {
        //캐릭터 인포(List)
        public List<CharacterInfo> characterInfos;
 
        public GameInfo()
        {
            this.characterInfos = new List<CharacterInfo>();
        }
    }
}
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
 
namespace _20190409
{
    public class GameLauncher
    {
        private UserInfo userInfo;
        private Dictionary<int, CharacterData> dicCharacterData = DataManager.GetInstance().dicCharacterData;
        private List<Character> characters;
 
        public GameLauncher()
        {
            this.characters = new List<Character>();
        }
 
        public void Start()
        {
            Console.WriteLine("게임 런쳐 실행");
            this.ReadyToStart();
        }
 
        private void ReadyToStart()
        {
            //게임 시작 준비
            Console.WriteLine("게임 시작을 준비중입니다.");
            //데이터 로드(data)
            DataManager.GetInstance().LoadData("./data/character_data.dat");
            //신구 유저 확인(info)
            this.ExistUserInfo("./info");
            //게임 시작
            this.StartGame();
        }
 
        private void StartGame()
        {
            Console.WriteLine("게임이 시작됐습니다.");
            //캐릭터 생성(신규 유저, 기존 유저 구분)
            BaronNashor baron = null;
            Annivia annivia = null;
 
            if (this.userInfo.NewbieCheck == false)
            {
                //기존 유저
                baron = (BaronNashor)this.CreateCharacter<BaronNashor>(this.userInfo.gameInfo.characterInfos[0]);
                annivia = (Annivia)this.CreateCharacter<Annivia>(this.userInfo.gameInfo.characterInfos[1]);
            }
            else
            {
                //신규유저
                baron = this.CreateCharacter<BaronNashor>(0);
                annivia = this.CreateCharacter<Annivia>(1);
 
                baron.characterInfo.pos = new Vector2(1010);
                annivia.characterInfo.pos = new Vector2(11);
            }
            this.characters.Add(baron);
            baron.characterInfo.pos = new Vector2(2020);
            this.characters.Add(annivia);
 
            //게임 진행
            //움직이고
            annivia.Move(new Vector2(1010));
            //움직여서 때리고
            annivia.Attack(baron);
            //원래 자리로 도망
            annivia.Move(new Vector2(11));
            //세이브//종료
            this.SaveUserInfo();
        }
 
        private void ExistUserInfo(string path)
        {
            if (Directory.Exists(path))
            {
                //기존 유저
                Console.WriteLine("기존 유저입니다.");
                //캐릭터 인포 불러오기
                //this.userInfo = this.LoadUserInfo("./info/user_info.json");
                this.userInfo = this.LoadUserInfo("./info/user_info.dat");
                this.userInfo.NewbieCheck = false;
            }
            else
            {
                //신규 유저
                Console.WriteLine("신규 유저입니다.");
                //./info폴더 만들기
                Directory.CreateDirectory(path);
                //캐릭터 인포만들기
                this.CreateUserInfo();
                this.userInfo.NewbieCheck = true;
            }
        }
 
        private UserInfo LoadUserInfo(string path)
        {
            //./info/user_info.dat불러오기
            return new BinaryManager().DeSerializeObject<UserInfo>("./info/user_info.dat");
        }
 
        //신규 유저, 유저인포 만들기
        private void CreateUserInfo(UserInfo userInfo = null)
        {
            if (this.userInfo == null)
            {
                if (userInfo == null)
                {
                    this.userInfo = new UserInfo();
                }
                else
                {
                    this.userInfo = userInfo;
                }
            }
        }
 
        //기존 유저, 인포 불러와서, 캐릭터 생성하기
        private T CreateCharacter<T>(CharacterInfo characterInfo) where T : Character, new()
        {
            T character = new T();
            character.characterInfo = characterInfo;
            return character;
        }
 
        //신규유저, 인포 생성해서, 캐릭터 생성하기
        private T CreateCharacter<T>(int id) where T : Character, new()
        {
            var data = DataManager.GetInstance().dicCharacterData[id];
            var info = new CharacterInfo();
 
            info.id = data.id;
            info.hp = data.hp;
            info.pos = new Vector2(11);
 
            T character = new T();
            character.characterInfo = info;
            return character;
        }
 
        private void SaveUserInfo()//dat
        {
            //현재의 유저인포(게임인포(캐릭터인포List)))를 유저인포에 저장
            this.SyncUserInfo();
 
            var info = this.userInfo;
            new BinaryManager().SerializeObject<UserInfo>(info,"./info/user_info.dat");
 
            Console.WriteLine("저장완료");
        }
 
        private void SyncUserInfo()
        {
            var characterInfos = new List<CharacterInfo>();
            foreach (var character in this.characters)
            {
                characterInfos.Add(character.characterInfo);
            }
            this.userInfo.gameInfo.characterInfos = characterInfos;
        }
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Monster : Character
    {
    }
}
 
 
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 _20190409
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
 
            app.Start();
 
            Console.ReadKey();
        }
    }
}
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 _20190409
{
    [Serializable]
    public class UserInfo
    {
        //게임인포, 뉴비체크
        public GameInfo gameInfo;
        public bool NewbieCheck;//기존유저일때 false, 신규유저일때 true
 
        public UserInfo()
        {
            this.gameInfo = new GameInfo();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    [Serializable]
    public class Vector2
    {
        public float x, y;
 
        public Vector2(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
 
        public static Vector2 operator +(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x + v2.x, v1.y + v2.y);
        }
 
        public static Vector2 operator -(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x - v2.x, v1.y - v2.y);
        }
 
        public static Vector2 operator *(Vector2 v1, float Value)
        {
            return new Vector2(v1.x * Value, v1.y * Value);
        }
 
        public static Vector2 operator /(Vector2 v1, float Value)
        {
            return new Vector2(v1.x / Value, v1.y / Value);
        }
 
        public float Dot(Vector2 v1, Vector2 v2)//스칼라 곱
        {
            return v1.x * v2.x + v1.y * v2.y;
        }
 
        public float GetDistance(Vector2 v1, Vector2 v2)
        {
            return (float)(Math.Sqrt(Math.Pow(v1.x - v2.x, 2+ Math.Pow(v1.y - v2.y, 2)));
        }
 
        public Vector2 Normalize()
        {
            var dis = (float)Math.Sqrt(Math.Pow(this.x, 2+ Math.Pow(this.y, 2));
 
            return new Vector2(this.x / dis, this.y / dis);
        }
    }
}
cs


찾아보기
.txt -> .dat컨버터 사이트 찾아보기


BinaryFormatter 
[Serializable]

:

<Overload, Override>, 싱글턴:데이터매니져

C#/수업내용 2019. 4. 10. 00:02


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Annivia:Champion
    {
        public Annivia()
        {
            this.speed = 3;
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class App
    {
        GameLauncher gameLauncher;
 
        public App()
        {
            this.gameLauncher = new GameLauncher();
        }
 
        public void Start()
        {
            Console.WriteLine("앱 실행");
            this.gameLauncher.Start();
        }
    }
}
 
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 _20190409
{
    public class BaronNashor:Monster
    {
        public BaronNashor()
        {
            this.speed = 0;
        }
 
        public override void Move(Vector2 movePos)
        {
            Console.WriteLine("바론은 움직일 수 없습니다.");
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Champion:Character
    {
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Character
    {
        public CharacterInfo characterInfo;
        public int speed;
 
        public Character()
        {
 
        }
 
        public Character(CharacterInfo characterInfo)
        {
            this.characterInfo = characterInfo;
        }
 
        public virtual void Move(Vector2 movePos)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
 
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, movePos);
            while (true)
            {
                if (dis > 0)
                {
                    System.Threading.Thread.Sleep(500);
                    var dir = (movePos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * speed;
 
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    dis -= speed;
                }
                else
                {
                    this.characterInfo.pos = movePos;
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})에 도착했습니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
                    break;
                }
            }
        }
 
        public virtual void Attack(Character target)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            var targetData = DataManager.GetInstance().dicCharacterData[target.characterInfo.id];
 
            //사거리 안에있으면 때림, 사거리 안에 없으면 이동함
            float dis = this.characterInfo.pos.GetDistance(this.characterInfo.pos, target.characterInfo.pos);
            while (true)
            {
                System.Threading.Thread.Sleep(500);
                if (dis > data.range)
                {
                    var dir = (target.characterInfo.pos - this.characterInfo.pos).Normalize();
                    this.characterInfo.pos += dir * speed;
                    //움직임
                    Console.WriteLine("{0}이(가) ({1:0.00},{2:0.00})로 이동합니다.", data.name, this.characterInfo.pos.x, this.characterInfo.pos.y);
 
                    dis -= this.speed;
                }
                else
                {
                    //멈춰서 때림
                    Console.WriteLine("{0}이(가) {1}을(를) 공격합니다.",data.name,targetData.name);
                    //때리면 데미지 들어감
                    target.TakeDamage(data.damage);
                    break;
                }
            }
        }
 
        public virtual void TakeDamage(int damage)
        {
            var data = DataManager.GetInstance().dicCharacterData[this.characterInfo.id];
            this.characterInfo.hp -= damage;
            Console.WriteLine("{0}이(가) {1}의 피해를 입었습니다.\n남은체력:({2}/{3})", data.name, damage,this.characterInfo.hp,data.hp);
        }
    }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class CharacterData
    {
        public int id;
        public int type;
        public string name;
        public int hp;
        public int damage;
        public float range;
    }
}
 
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 _20190409
{
    public class CharacterInfo
    {
        public int id;
        public int hp;
        public Vector2 pos;
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
 
namespace _20190409
{
    public class DataManager
    {
        private static DataManager Instance;
        public Dictionary<int, CharacterData> dicCharacterData;
 
        private DataManager()
        {
            this.dicCharacterData = new Dictionary<int, CharacterData>();
        }
 
        public static DataManager GetInstance()
        {
            if (DataManager.Instance == null)
            {
                DataManager.Instance = new DataManager();
            }
            return DataManager.Instance;
        }
 
        public void LoadData(string path)
        {
            if (File.Exists(path))
            {
                var json = File.ReadAllText(path);
                var characterDatas = JsonConvert.DeserializeObject<CharacterData[]>(json);
                foreach (var data in characterDatas)
                {
                    this.dicCharacterData.Add(data.id, data);
                }
            }
            else
            {
                Console.WriteLine("파일이 음슴.");
            }
        }
    }
}
 
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 _20190409
{
    public class GameInfo
    {
        //캐릭터 인포(List)
        public List<CharacterInfo> characterInfos;
 
        public GameInfo()
        {
            this.characterInfos = new List<CharacterInfo>();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
 
namespace _20190409
{
    public class GameLauncher
    {
        private UserInfo userInfo;
        private Dictionary<int, CharacterData> dicCharacterData = DataManager.GetInstance().dicCharacterData;
        private List<Character> characters;
 
        public GameLauncher()
        {
            this.characters = new List<Character>();
        }
 
        public void Start()
        {
            Console.WriteLine("게임 런쳐 실행");
            this.ReadyToStart();
        }
 
        private void ReadyToStart()
        {
            //게임 시작 준비
            Console.WriteLine("게임 시작을 준비중입니다.");
            //데이터 로드(data)
            DataManager.GetInstance().LoadData("./data/character_data.json");
            //신구 유저 확인(info)
            this.ExistUserInfo("./info");
            //게임 시작
            this.StartGame();
        }
 
        private void StartGame()
        {
            Console.WriteLine("게임이 시작됐습니다.");
            //캐릭터 생성(신규 유저, 기존 유저 구분)
            BaronNashor baron = null;
            Annivia annivia = null;
 
            if (this.userInfo.NewbieCheck == false)
            {
                //기존 유저
                baron = (BaronNashor)this.CreateCharacter<BaronNashor>(this.userInfo.gameInfo.characterInfos[0]);
                annivia = (Annivia)this.CreateCharacter<Annivia>(this.userInfo.gameInfo.characterInfos[1]);
            }
            else
            {
                //신규유저
                baron = this.CreateCharacter<BaronNashor>(0);
                annivia = this.CreateCharacter<Annivia>(1);
 
                baron.characterInfo.pos = new Vector2(1010);
                annivia.characterInfo.pos = new Vector2(11);
            }
            this.characters.Add(baron);
            baron.characterInfo.pos = new Vector2(2020);
            this.characters.Add(annivia);
 
            //게임 진행
            //움직이고
            annivia.Move(new Vector2(1010));
            //움직여서 때리고
            annivia.Attack(baron);
            //원래 자리로 도망
            annivia.Move(new Vector2(11));
            //세이브//종료
            this.SaveUserInfo();
        }
 
        private void ExistUserInfo(string path)
        {
            if (Directory.Exists(path))
            {
                //기존 유저
                Console.WriteLine("기존 유저입니다.");
                //캐릭터 인포 불러오기
                this.userInfo = this.LoadUserInfo("./info/user_info.json");
                this.userInfo.NewbieCheck = false;
            }
            else
            {
                //신규 유저
                Console.WriteLine("신규 유저입니다.");
                //./info폴더 만들기
                Directory.CreateDirectory(path);
                //캐릭터 인포만들기
                this.CreateUserInfo();
                this.userInfo.NewbieCheck = true;
            }
        }
 
        //기존 유저, 유저인포 불러오기
        private UserInfo LoadUserInfo(string path)
        {
            //./info/user_info.json불러오기
            var json = File.ReadAllText(path);
            return JsonConvert.DeserializeObject<UserInfo>(json);
        }
 
        //신규 유저, 유저인포 만들기
        private void CreateUserInfo(UserInfo userInfo = null)
        {
            if (this.userInfo == null)
            {
                if (userInfo == null)
                {
                    this.userInfo = new UserInfo();
                }
                else
                {
                    this.userInfo = userInfo;
                }
            }
        }
 
        //기존 유저, 인포 불러와서, 캐릭터 생성하기
        private T CreateCharacter<T>(CharacterInfo characterInfo) where T : Character, new()
        {
            T character = new T();
            character.characterInfo = characterInfo;
            return character;
        }
 
        //신규유저, 인포 생성해서, 캐릭터 생성하기
        private T CreateCharacter<T>(int id) where T : Character, new()
        {
            var data = dicCharacterData[id];
            var info = new CharacterInfo();
 
            info.id = data.id;
            info.hp = data.hp;
            info.pos = new Vector2(11);
 
            T character = new T();
            character.characterInfo = info;
            return character;
        }
 
        private void SaveUserInfo()//json
        {
            //현재의 유저인포(게임인포(캐릭터인포List)))를 유저인포에 저장
            var characterInfos = new List<CharacterInfo>();
            foreach (var character in this.characters)
            {
                characterInfos.Add(character.characterInfo);
            }
            this.userInfo.gameInfo.characterInfos = characterInfos;
 
            //파일 쓰기
            var json = JsonConvert.SerializeObject(this.userInfo);
            File.WriteAllText("./info/user_info.json", json, Encoding.UTF8);
            Console.WriteLine("저장완료");
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Monster:Character
    {
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
 
            app.Start();
 
            Console.ReadKey();
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class UserInfo
    {
        //게임인포, 뉴비체크
        public GameInfo gameInfo;
        public bool NewbieCheck;//기존유저일때 false, 신규유저일때 true
 
        public UserInfo()
        {
            this.gameInfo = new GameInfo();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190409
{
    public class Vector2
    {
        public float x, y;
        
        public Vector2(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
 
        public static Vector2 operator +(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x + v2.x, v1.y + v2.y);
        }
 
        public static Vector2 operator -(Vector2 v1, Vector2 v2)
        {
            return new Vector2(v1.x - v2.x, v1.y - v2.y);
        }
 
        public static Vector2 operator *(Vector2 v1, float Value)
        {
            return new Vector2(v1.x * Value, v1.y * Value);
        }
 
        public static Vector2 operator /(Vector2 v1, float Value)
        {
            return new Vector2(v1.x / Value, v1.y / Value);
        }
 
        public float Dot(Vector2 v1, Vector2 v2)//스칼라 곱
        {
            return v1.x * v2.x + v1.y * v2.y;
        }
 
        public float GetDistance(Vector2 v1, Vector2 v2)
        {
            return (float)(Math.Sqrt(Math.Pow(v1.x - v2.x, 2+ Math.Pow(v1.y - v2.y, 2)));
        }
 
        public Vector2 Normalize()
        {
            var dis = (float)Math.Sqrt(Math.Pow(this.x, 2+ Math.Pow(this.y, 2));
            
            return new Vector2(this.x / dis, this.y / dis);
        }
    }
}
 
cs



ps. 솔바론을 시도하는 애니비아가 있다고? ㄴㅇㄱ 뿌슝빠슝

:

<lol바론과 애니비아의 사투>미완성(에러에러에러)

C#/과제 2019. 4. 9. 09:58
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class Annivia : Champion
    {
        public Annivia(CharacterInfo characterInfo, int id):base(characterInfo,id)
        {
            this.id = id;
            this.characterInfo = characterInfo;
        }
 
        public override void Move(Vector2 targetPos, float speed)
        {
            var distance = this.characterInfo.myPos.GetDistance(targetPos, this.characterInfo.myPos);
            Console.WriteLine("{0}({1},{2})이(가) ({3},{4})로 이동합니다."this.dicCharacterData[this.id].name, this.characterInfo.myPos.x, this.characterInfo.myPos.y, targetPos.x, targetPos.y);
 
            while (true)
            {
                if (distance <= 0)
                {
                    this.characterInfo.myPos = targetPos;
 
                    break;
                }
                else//타겟좌표와 나의 거리가 0이 아닐때
                {
                    System.Threading.Thread.Sleep(1000);
                    distance -= speed;
 
                    Console.WriteLine("{0}이(가) 이동합니다.(거리:{1})"this.dicCharacterData[this.id].name, distance);
                }
            }
            Console.WriteLine("{0}이(가) ({1}, {2})에 도착했습니다."this.dicCharacterData[this.characterInfo.id].name, this.characterInfo.myPos.x, this.characterInfo.myPos.y);
        }
 
        public override void Attack(Character target)
        {
            var distance = this.characterInfo.myPos.GetDistance(target.characterInfo.myPos, this.characterInfo.myPos);
            
            while(true)
            {
                System.Threading.Thread.Sleep(1000);
 
                if (distance > this.dicCharacterData[this.characterInfo.id].attackLength)
                {
                    distance -= this.dicCharacterData[this.characterInfo.id].speed;
 
                    Console.WriteLine("{0}이(가) 이동합니다.(거리:{1})"this.dicCharacterData[this.characterInfo.id].name, distance);
                }
                else
                {
                    //Console.WriteLine("{0}이(가) {1}에게 기본공격을 합니다.", this.dicCharacterData[this.characterInfo.id].name, target.dicCharacterData[target.characterInfo.id].name);
                    Console.WriteLine("{0}이(가) {1}에게 기본공격을 합니다."this.dicCharacterData[this.id].name, target.dicCharacterData[target.id].name);
                    target.TakeDamage(this.dicCharacterData[this.id].attackDamage);
                    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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
using System.Collections;
 
namespace AttackTest
{
    public class App
    {
        public Dictionary<int, Character> dicCharacters = new Dictionary<int, Character>();
 
        public CharacterInfo characterInfo;
        public Dictionary<int, CharacterData> dicCharacterData = new Dictionary<int, CharacterData>();
 
        public App()
        {
            this.DataLoad("./data/character_data.json");
        }
 
        public void Start()
        {
            this.Infoload();
 
            var gameLauncher = new GameLauncher(this.dicCharacterData, this.characterInfo, this.dicCharacters);
            var newCharacterInfo = gameLauncher.Start();
 
            this.DataSave(newCharacterInfo);
        }
 
        public void DataLoad(string path)//데이터 불러오기
        {
            var json = File.ReadAllText(path);
 
            var arrCharacterData = JsonConvert.DeserializeObject<CharacterData[]>(json);
            foreach (var data in arrCharacterData)
            {
                dicCharacterData.Add(data.id, data);
            }
        }
 
        public void Infoload()
        {
            if (Directory.Exists("./info"))
            {
                Console.WriteLine("기존 유저 입니다.");
 
                var json = File.ReadAllText("./info/character_info.json");
 
                var characterInfo = JsonConvert.DeserializeObject<CharacterInfo>(json);
                this.characterInfo = characterInfo;
 
                this.dicCharacters[0= new Character(characterInfo, 0);
                this.dicCharacters[1= new Character(characterInfo, 1);
            }
            else
            {
                Console.WriteLine("신규 유저입니다.");
 
                Directory.CreateDirectory("./info");
                this.dicCharacters[0= new Character(new CharacterInfo(0,550), 0);
                this.dicCharacters[1= new Character(new CharacterInfo(1,1000), 1);
 
                var json = JsonConvert.SerializeObject(this.dicCharacters);
 
                File.WriteAllText("./info/character_info.json", json, Encoding.UTF8);
 
                //파일읽기, 역직렬화, dic생성
                json = File.ReadAllText("./info/character_info.json");
 
                var characterInfo = JsonConvert.DeserializeObject<CharacterInfo>(json);
                this.characterInfo = characterInfo;
            }
        }
 
        public void DataSave(CharacterInfo newInfos)
        {
            this.characterInfo = newInfos;
            var json = JsonConvert.SerializeObject(this.characterInfo);
            File.WriteAllText("./info/character_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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class BaronNasser : Monster
    {
        public BaronNasser(CharacterInfo characterInfo, int id) : base(characterInfo, id)
        {
            this.id = id;
            this.characterInfo = characterInfo;
        }
 
        public override void Move(Vector2 targetPos,float speed)
        {
            Console.WriteLine("{0}은 움직일 수 없습니다."this.dicCharacterData[this.characterInfo.id].name);
        }
 
        public override void Attack(Character target)
        {
            var distance = this.characterInfo.myPos.GetDistance(target.characterInfo.myPos, this.characterInfo.myPos);
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
 
                if (distance > this.dicCharacterData[this.characterInfo.id].attackLength)
                {
                    Console.WriteLine("사거리를 벗어나 공격 할 수 없습니다.");
                    break;
                }
                else
                {
                    Console.WriteLine("{0}이(가) {1}에게 기본공격을 합니다."this.dicCharacterData[this.characterInfo.id].name, target.dicCharacterData[this.characterInfo.id].name);
                    target.TakeDamage(this.dicCharacterData[this.characterInfo.id].attackDamage);
                    break;
                }
            }
        }
    }
}
 
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 AttackTest
{
    public class Champion : Character
    {
        public Champion(CharacterInfo characterInfo, int id) : base(characterInfo, id)
        {
            this.id = id;
            this.characterInfo = characterInfo;
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class Character
    {
        public int id;
        public CharacterInfo characterInfo;
        public Dictionary<int, CharacterData> dicCharacterData;
 
        public Character(CharacterInfo characterInfo,int id)
        {
            this.id = id;
            this.characterInfo = characterInfo;
        }
 
        public virtual void Move(Vector2 targetPos, float speed)
        {
 
        }
 
        public virtual void Attack(Character target)
        {
 
        }
 
        public virtual void TakeDamage(int damage)
        {
            this.characterInfo.hp -= damage;
            Console.WriteLine("{0}이(가) {1}의 피해를 받았습니다."this.dicCharacterData[this.id].name, damage);
            Console.WriteLine("{0}의 남은 Hp : {1}"this.dicCharacterData[this.id].name, this.characterInfo.hp);
        }
    }
}
 
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 AttackTest
{
    public class CharacterData
    {
        public int id;
        public string name;
        public int attackDamage;
        public float speed;
        public int attackLength;
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class CharacterInfo
    {
        public int id;
        public int hp;
        public Vector2 myPos = new Vector2(00);
 
        public List<Character> characters= new List<Character>();
 
        public CharacterInfo()
        {
 
        }
 
        public CharacterInfo(List<Character> characters)
        {
            this.characters = characters;
        }
        public CharacterInfo(int id, int hp)
        {
            this.id = id;
            this.hp = hp;
        }
    }
}
 
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class GameLauncher
    {
        public Dictionary<int, Character> dicCharacters;
        public CharacterInfo characterInfo;
        public Dictionary<int, CharacterData> dicCharacterData;
 
        
        public GameLauncher(Dictionary<int, CharacterData> dicCharacterData, CharacterInfo characterInfo, Dictionary<int, Character> dicCharacters)
        {
            this.characterInfo = characterInfo;
            this.dicCharacterData = dicCharacterData;
            this.dicCharacters = dicCharacters;
        }
 
        public CharacterInfo Start()
        {
            var annivia = new Annivia(this.characterInfo, 0);
            annivia.dicCharacterData = this.dicCharacterData;
            var baron = new BaronNasser(this.characterInfo, 1);
            baron.dicCharacterData = this.dicCharacterData;
 
            Console.WriteLine("{0} : {1}", characterInfo.id, characterInfo.hp);
 
            //이동
            //annivia.Move(new Vector2(10, 10), dicCharacterData[annivia.id].speed);
            //공격
            //annivia.Attack(baron);
 
            return this.characterInfo;//수정하기
        }
    }
}
 
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 AttackTest
{
    public class Monster : Character
    {
        public Monster(CharacterInfo characterInfo, int id) : base(characterInfo, id)
        {
            this.id = id;
            this.characterInfo = characterInfo;
        }
    }
}
 
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 AttackTest
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
            app.Start();
 
            Console.ReadKey();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace AttackTest
{
    public class Vector2
    {
        public float x, y;
 
        public Vector2(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
 
        public static Vector2 operator +(Vector2 v1, Vector2 v2)//벡터합
        {
            return new Vector2(v1.x + v2.x, v1.y + v2.y);
        }
 
        public static Vector2 operator -(Vector2 v1, Vector2 v2)//벡터차
        {
            return new Vector2(v1.x - v2.x, v1.y - v2.y);
        }
 
        public float GetDistance(Vector2 targetPos, Vector2 myPos)//벡터간의 거리구하기(float반환)
        {
            return (float)Math.Sqrt(Math.Pow(targetPos.x - myPos.x, 2+ Math.Pow(targetPos.y - myPos.y, 2));
        }
    }
}
 
cs


:

<인벤토리> 저장, 불러오기 기능

C#/과제 2019. 4. 8. 01:09



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TheLastInventory
{
    class Program
    {
        static void Main(string[] args)
        {
            new App().Start();
 
            Console.ReadKey();
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
 
namespace TheLastInventory
{
    public class App
    {
        public InventoryInfo inventoryInfo;
        public Inventory inventory;
 
        public Dictionary<int, ItemData> dicItemData = new Dictionary<int, ItemData>();//아이템 데이타 불러오기
 
        public App()
        {
            //아이템 데이터 가져오기
            DataLoad("./data/item_data.json");
        }
 
        public void Start()
        {
            //폴더 유무 확인
            //유:기존유저:파일읽기,역직렬화,사전에데이터올리기
            //무:신규유져:파일생성(inventory_info), 파일읽기,역직렬화,사전에데이터올리기
            ExistTest();
 
            //게임런쳐 호출
            var newInventoryInfo = new GameLauncher(this.dicItemData, this.inventoryInfo, this.inventory).StartGame();
            //종료했으므로 저장
            DataSave(newInventoryInfo);
        }
 
        public void ExistTest()
        {
            if (Directory.Exists("./info"))
            {
                Console.WriteLine("기존 유저입니다.");
 
                //여기서부턴 신규유저에 붙여 넣을 것
                //파일읽기, 역직렬화, dic생성
                var json = File.ReadAllText("./info/inventory_info.json");
 
                var inventoryInfo = JsonConvert.DeserializeObject<InventoryInfo>(json);
                this.inventoryInfo = inventoryInfo;
 
                this.inventory = new Inventory(inventoryInfo);
            }
            else
            {
                Console.WriteLine("신규 유저입니다.");
 
                //폴더 만들기
                Directory.CreateDirectory("./info");
                //인벤토리 생성하기  
                this.inventory = new Inventory(new InventoryInfo());
                //직렬화 
                var json = JsonConvert.SerializeObject(this.inventory);
                File.WriteAllText("./info/inventory_info.json", json, Encoding.UTF8);
 
                //파일읽기, 역직렬화, dic생성
                json = File.ReadAllText("./info/inventory_info.json");
 
                var inventoryInfo = JsonConvert.DeserializeObject<InventoryInfo>(json);
                this.inventoryInfo = inventoryInfo;
 
                this.inventory = new Inventory(inventoryInfo);
            }
        }
 
        public void DataLoad(string path)//데이터 불러오기
        {
            var json = File.ReadAllText(path);
            //Console.WriteLine("쮀이썬테스트:{0}",json);
 
            //역직렬화
            var arrItemData = JsonConvert.DeserializeObject<ItemData[]>(json);
            foreach (var data in arrItemData)
            {
                dicItemData.Add(data.id, data);
            }
        }
 
        public void DataSave(InventoryInfo newInventoryInfo)
        {
            this.inventoryInfo = newInventoryInfo;
            var json = JsonConvert.SerializeObject(this.inventoryInfo);
            File.WriteAllText("./info/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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TheLastInventory
{
    public class GameLauncher
    {
        Dictionary<int, ItemData> dicItemData;
        public InventoryInfo inventoryInfo;
        public Inventory inventory;
 
        public GameLauncher(Dictionary<int, ItemData>dicItemData,InventoryInfo inventoryInfo, Inventory inventory)
        {
            this.dicItemData = dicItemData;
            this.inventoryInfo = inventoryInfo;
            this.inventory = inventory;
        }
 
        public InventoryInfo StartGame()
        {
            //var inventory = new Inventory();
 
            
            //메뉴 [1:아이템생성 과 인벤추가 ,2:인벤목록출력 ,3: 아이템꺼내기 ,4:저장후 종료] : 1
            while (true)
            {
                Console.WriteLine("메뉴[1.목록출력/2.아이템생성/3.아이템버리기/0.저장후 종료({0}/{1})"this.inventoryInfo.inventoryVolume, this.inventory.inventoryVolumeMax);
                var input = Console.ReadLine();
 
                if (input == "0")
                {
                    //저장기능만들기
                    Console.WriteLine("종료합니다.");
                    return this.inventoryInfo;
                }
                else if (input == "1")
                {
                    //목록 출력
                    inventory.ViewList(dicItemData);
                }
                else if (input == "2")
                {
                    //아이템 생성
                    this.inventoryInfo = inventory.AddItem(dicItemData);
                }
                else if (input == "3")
                {
                    //아이템 버리기
                    this.inventoryInfo = inventory.RemoveItem(dicItemData);
                }
                else
                {
                    Console.WriteLine("잘못된 입력입니다.");
                }
            }
        }
    }
}
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TheLastInventory
{
    public class Inventory
    {
        public InventoryInfo inventoryInfo;
        public int inventoryVolumeMax = 100;
 
        public Inventory(InventoryInfo inventoryInfo)
        {
            this.inventoryInfo = inventoryInfo;
        }
 
        public InventoryInfo AddItem(Dictionary<int, ItemData> dic)//아이템 추가
        {
            Console.WriteLine("어떤 아이템을 만드시겠습니까?[1.롱소드/2.숏소드/3.빨간포션/4.파란포션](이름):");
            var input = Console.ReadLine();
            if (input == "롱소드")
            {
                //롱소드 생성
                Console.WriteLine("몇개의 {0}를 만드시겠습니까?", input);
                var inputNum = Console.ReadLine();
                if (int.Parse(inputNum) + this.inventoryInfo.inventoryVolume > this.inventoryVolumeMax - this.inventoryInfo.inventoryVolume)
                {
                    Console.WriteLine("남은 아이템 수용량을 초과합니다.");
                }
                else
                {
                    if (int.Parse(inputNum) >= 0)
                    {
                        Item founditem = null;
                        int i = 0;
 
                        foreach (var data in this.inventoryInfo.items)
                        {
                            if (data.itemInfo.id == 0)
                            {
                                founditem = data;
                                break;
                            }
                            i++;
                        }
                        if (founditem == null)
                        {
                            //아이템 객체 생성하고 카운트업
                            this.inventoryInfo.items.Add(new Item(new ItemInfo(0)));
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        else
                        {
                            //카운트만 업
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        Console.WriteLine("{0}가 {1}개 추가되었습니다.", input, inputNum);
                    }
                    else
                    {
                        Console.WriteLine("잘못된 입력 입니다.");
                    }
                }
            }
            else if (input == "숏소드")
            {
                Console.WriteLine("몇개의 {0}를 만드시겠습니까?", input);
                var inputNum = Console.ReadLine();
                if (int.Parse(inputNum) + this.inventoryInfo.inventoryVolume > this.inventoryVolumeMax - this.inventoryInfo.inventoryVolume)
                {
                    Console.WriteLine("남은 아이템 수용량을 초과합니다.");
                }
                else
                {
                    if (int.Parse(inputNum) >= 0)
                    {
                        Item founditem = null;
                        int i = 0;
                        foreach (var data in this.inventoryInfo.items)
                        {
                            if (data.itemInfo.id == 1)
                            {
                                founditem = data;
                                break;
                            }
                            i++;
                        }
                        if (founditem == null)
                        {
                            //아이템 객체 생성하고 카운트업
                            this.inventoryInfo.items.Add(new Item(new ItemInfo(1)));
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        else
                        {
                            //카운트만 업
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        Console.WriteLine("{0}가 {1}개 추가되었습니다.", input, inputNum);
                    }
                    else
                    {
                        Console.WriteLine("잘못된 입력 입니다.");
                    }
                }
            }
            else if (input == "빨간포션")
            {
                Console.WriteLine("몇개의 {0}를 만드시겠습니까?", input);
                var inputNum = Console.ReadLine();
                if (int.Parse(inputNum) + this.inventoryInfo.inventoryVolume > this.inventoryVolumeMax - this.inventoryInfo.inventoryVolume)
                {
                    Console.WriteLine("남은 아이템 수용량을 초과합니다.");
                }
                else
                {
                    if (int.Parse(inputNum) >= 0)
                    {
                        Item founditem = null;
                        int i = 0;
                        foreach (var data in this.inventoryInfo.items)
                        {
                            if (data.itemInfo.id == 2)
                            {
                                founditem = data;
                                break;
                            }
                            i++;
                        }
                        if (founditem == null)
                        {
                            //아이템 객체 생성하고 카운트업
                            this.inventoryInfo.items.Add(new Item(new ItemInfo(2)));
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        else
                        {
                            //카운트만 업
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        Console.WriteLine("{0}가 {1}개 추가되었습니다.", input, inputNum);
                    }
                    else
                    {
                        Console.WriteLine("잘못된 입력 입니다.");
                    }
                }
            }
            else if (input == "파란포션")
            {
                Console.WriteLine("몇개의 {0}를 만드시겠습니까?", input);
                var inputNum = Console.ReadLine();
                if (int.Parse(inputNum) + this.inventoryInfo.inventoryVolume > this.inventoryVolumeMax - this.inventoryInfo.inventoryVolume)
                {
                    Console.WriteLine("남은 아이템 수용량을 초과합니다.");
                }
                else
                {
                    if (int.Parse(inputNum) >= 0)
                    {
                        Item founditem = null;
                        int i = 0;
                        foreach (var data in this.inventoryInfo.items)
                        {
                            if (data.itemInfo.id == 3)
                            {
                                founditem = data;
                                break;
                            }
                            i++;
                        }
                        if (founditem == null)
                        {
                            //아이템 객체 생성하고 카운트업
                            this.inventoryInfo.items.Add(new Item(new ItemInfo(3)));
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        else
                        {
                            //카운트만 업
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack++;
                                this.inventoryInfo.inventoryVolume++;
                            }
                        }
                        Console.WriteLine("{0}가 {1}개 추가되었습니다.", input, inputNum);
                    }
                    else
                    {
                        Console.WriteLine("잘못된 입력 입니다.");
                    }
                }
            }
            else
            {
                Console.WriteLine("잘못된 입력입니다.");
            }
            return this.inventoryInfo;
        }
 
        public InventoryInfo RemoveItem(Dictionary<int, ItemData> dic)//아이템 지우기
        {
            if (this.inventoryInfo.inventoryVolume == 0)
            {
                Console.WriteLine("가방이 비었습니다.");
            }
            else
            {
                Console.WriteLine("어떤 아이템을 버리시겠습니까?[1.롱소드/2.숏소드/3.빨간포션/4.파란포션](이름):");
                var input = Console.ReadLine();
 
                if (input == "롱소드")
                {
                    Item founditem = null;
                    int i = 0;
                    foreach (var data in this.inventoryInfo.items)
                    {
                        if (data.itemInfo.id == 0)
                        {
                            founditem = data;
                            break;
                        }
                        i++;
                    }
                    if (founditem == null)//해당 아이템의 갯수가 0이면 해당 아이템이 없습니다. 출력
                    {
                        Console.WriteLine("해당 아이템이 가방에 없습니다.");
                    }
                    else
                    {
                        Console.WriteLine("{0} : {1}", dic[this.inventoryInfo.items[i].itemInfo.id].name, this.inventoryInfo.items[i].itemInfo.stack);
                        Console.Write("몇개나 버리시겠습니까?(숫자입력) : ");
                        var inputNum = Console.ReadLine();
                        if (int.Parse(inputNum) >= this.inventoryInfo.items[i].itemInfo.stack)
                        {
                            Console.WriteLine("{0}을 전부 버립니다.", dic[0].name);
                            this.inventoryInfo.inventoryVolume -= this.inventoryInfo.items[i].itemInfo.stack;
                            this.inventoryInfo.items[i].itemInfo.stack = 0;
                            this.inventoryInfo.items.Remove(founditem);
                        }
                        else
                        {
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack--;
                                this.inventoryInfo.inventoryVolume--;
                            }
                            Console.WriteLine("{0}을 {1}개 버렸습니다.", dic[0].name, inputNum);
                        }
                    }
                }
                else if (input == "숏소드")
                {
                    Item founditem = null;
                    int i = 0;
                    foreach (var data in this.inventoryInfo.items)
                    {
                        if (data.itemInfo.id == 1)
                        {
                            founditem = data;
                            break;
                        }
                        i++;
                    }
                    if (founditem == null)//해당 아이템의 갯수가 0이면 해당 아이템이 없습니다. 출력
                    {
                        Console.WriteLine("해당 아이템이 가방에 없습니다.");
                    }
                    else
                    {
                        Console.WriteLine("{0} : {1}", dic[1].name, this.inventoryInfo.items[i].itemInfo.stack);
                        Console.Write("몇개나 버리시겠습니까?(숫자입력) : ");
                        var inputNum = Console.ReadLine();
                        if (int.Parse(inputNum) >= this.inventoryInfo.items[i].itemInfo.stack)
                        {
                            Console.WriteLine("{0}을 전부 버립니다.", dic[1].name);
                            this.inventoryInfo.inventoryVolume -= this.inventoryInfo.items[i].itemInfo.stack;
                            this.inventoryInfo.items[i].itemInfo.stack = 0;
                            this.inventoryInfo.items.Remove(founditem);
                        }
                        else
                        {
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack--;
                                this.inventoryInfo.inventoryVolume--;
                            }
                            Console.WriteLine("{0}을 {1}개 버렸습니다.", dic[1].name, inputNum);
                        }
                    }
                }
                else if (input == "빨간포션")
                {
                    Item founditem = null;
                    int i = 0;
                    foreach (var data in this.inventoryInfo.items)
                    {
                        if (data.itemInfo.id == 2)
                        {
                            founditem = data;
                            break;
                        }
                        i++;
                    }
                    if (founditem == null)//해당 아이템의 갯수가 0이면 해당 아이템이 없습니다. 출력
                    {
                        Console.WriteLine("해당 아이템이 가방에 없습니다.");
                    }
                    else
                    {
                        Console.WriteLine("{0} : {1}", dic[2].name, this.inventoryInfo.items[i].itemInfo.stack);
                        Console.Write("몇개나 버리시겠습니까?(숫자입력) : ");
                        var inputNum = Console.ReadLine();
                        if (int.Parse(inputNum) >= this.inventoryInfo.items[i].itemInfo.stack)
                        {
                            Console.WriteLine("{0}을 전부 버립니다.", dic[2].name);
                            this.inventoryInfo.inventoryVolume -= this.inventoryInfo.items[i].itemInfo.stack;
                            this.inventoryInfo.items[i].itemInfo.stack = 0;
                            this.inventoryInfo.items.Remove(founditem);
                        }
                        else
                        {
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack--;
                                this.inventoryInfo.inventoryVolume--;
                            }
                            Console.WriteLine("{0}을 {1}개 버렸습니다.", dic[2].name, inputNum);
                        }
                    }
                }
                else if (input == "파란포션")
                {
                    Item founditem = null;
                    int i = 0;
                    foreach (var data in this.inventoryInfo.items)
                    {
                        if (data.itemInfo.id == 3)
                        {
                            founditem = data;
                            break;
                        }
                        i++;
                    }
                    if (founditem == null)//해당 아이템의 갯수가 0이면 해당 아이템이 없습니다. 출력
                    {
                        Console.WriteLine("해당 아이템이 가방에 없습니다.");
                    }
                    else
                    {
                        Console.WriteLine("{0} : {1}", dic[3].name, this.inventoryInfo.items[i].itemInfo.stack);
                        Console.Write("몇개나 버리시겠습니까?(숫자입력) : ");
                        var inputNum = Console.ReadLine();
                        if (int.Parse(inputNum) >= this.inventoryInfo.items[i].itemInfo.stack)
                        {
                            Console.WriteLine("{0}을 전부 버립니다.", dic[3].name);
                            this.inventoryInfo.inventoryVolume -= this.inventoryInfo.items[i].itemInfo.stack;
                            this.inventoryInfo.items[i].itemInfo.stack = 0;
                            this.inventoryInfo.items.Remove(founditem);
                        }
                        else
                        {
                            for (int j = 0; j < int.Parse(inputNum); j++)
                            {
                                this.inventoryInfo.items[i].itemInfo.stack--;
                                this.inventoryInfo.inventoryVolume--;
                            }
                            Console.WriteLine("{0}을 {1}개 버렸습니다.", dic[3].name, inputNum);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("잘못된 입력입니다.");
                }
            }
            return this.inventoryInfo;
        }
 
        public void ViewList(Dictionary<int, ItemData> dic)//목록보기
        {
            //if (this.inventoryInfo.items.Count <= 0)
            //{
            //    Console.WriteLine("인벤토리가 비었습니다.");
            //}
            if(this.inventoryInfo.inventoryVolume<=0)
            {
                Console.WriteLine("인벤토리가 비었습니다.");
            }
            else
            {
                Console.WriteLine("인벤토리를 확인합니다.({0}/{1})"this.inventoryInfo.inventoryVolume, this.inventoryVolumeMax);
                int i = 0;
                foreach (Item item in this.inventoryInfo.items)
                {
                    Console.WriteLine("{0} : {1}", dic[item.itemInfo.id].name, this.inventoryInfo.items[i].itemInfo.stack);
                    i++;
                }
            }
        }
    }
}
 
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 TheLastInventory
{   
    public class InventoryInfo
    {
        public int id;
        public List<Item> items = new List<Item>();
        public int inventoryVolume = 0;
    }
}
 
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 TheLastInventory
{
    public class Item
    {
        public int id;
        public ItemInfo itemInfo;
 
        public Item(ItemInfo itemInfo)
        {
            this.itemInfo = itemInfo;
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TheLastInventory
{
    public class ItemData
    {
        public int id;
        public string name;
 
        public ItemData(int id, string name)
        {
            this.id = id;
            this.name = name;
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TheLastInventory
{
    public class ItemInfo
    {
        public int id;
        public int stack;
 
        public ItemInfo()
        {
            //기본생성자
        }
 
        public ItemInfo(int id)
        {
            //아이템의 아이디와 이름을 받는 생성자
            this.id = id;
        }
    }
}
 
cs

item_data.json

[

  {

    "id": "0",

    "name": "롱소드"

  },

  {

    "id": "1",

    "name": "숏소드"

  },

  {

    "id": "2",

    "name": "빨간포션"

  },

  {

    "id": "3",

    "name": "파란포션"

  }

]


inventory_info.json
{"id":0,"items":[{"id":0,"itemInfo":{"id":0,"stack":3}},{"id":0,"itemInfo":{"id":1,"stack":30}},{"id":0,"itemInfo":{"id":2,"stack":3}}],"inventoryVolume":36}

:

<n+1번째 인벤토리> Json과 파일읽기.

C#/수업내용 2019. 4. 3. 19:00
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 _20190403
{
    class Program
    {
        static void Main(string[] args)
        {
            App app = new App();
            app.Start();
 
            Console.ReadKey();
        }
    }
}
 
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 _20190403
{
    public class Item
    {
        public ItemData itemData;
        public ItemInfo itemInfo;
        public Item(ItemInfo itemInfo)
        {
            this.itemInfo = itemInfo;
        }
 
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190403
{
    public class ItemData
    {
        public int id;
        public string name;
        public int max_level;
        public float damage_min;
        public float damage_max;
 
        public ItemData(int id, string name, int max_level, float damage_min, float damage_max)
        {
            this.id = id;
            this.name = name;
            this.max_level = max_level;
            this.damage_min = damage_min;
            this.damage_max = damage_max;
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace _20190403
{
    public class ItemInfo
    {
        public int id;
 
        public int level;
        public float damage;
 
        public ItemInfo(int id,int level,float damage)
        {
            this.id = id;
            this.level = level;
            this.damage = damage;
        }
    }
}
 
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
using Newtonsoft.Json;
 
namespace _20190403
{
    public class App
    {
        Dictionary<int, ItemData> dicItems = new Dictionary<int, ItemData>();
        public App()
        {
            var json = File.ReadAllText("weapon_data.json");
            Console.WriteLine(json);
            var arrItemData = JsonConvert.DeserializeObject<ItemData[]>(json);
            foreach (var item in arrItemData)
            {
                dicItems.Add(item.id, item);
            }
        }
        
        public void Start()
        {
            for (int i = 0; i<dicItems.Count;i++)
            {
                var item = CreateItem(i);
                var data = dicItems[item.itemInfo.id];
                Console.WriteLine("{0}, {1}:{2:0.0}~{3:0.0}", item.itemInfo.id, dicItems[i].name, dicItems[i].damage_min, dicItems[i].damage_max);
            }
        }
 
        public Item CreateItem(int id)
        {
            var itemData = dicItems[id];
            var damage = this.GetRandomNumber(itemData.damage_min, itemData.damage_max);
            return new Item(new ItemInfo(itemData.id, 1, (float)damage));
        }
 
        public double GetRandomNumber(double minimum, double maximum)
        {
            var random = new Random();
            return random.NextDouble() * (maximum - minimum) + minimum;
        }
    }
}
 
cs


: