<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]

: