-
Notifications
You must be signed in to change notification settings - Fork 0
/
LevelEditor.cs
401 lines (353 loc) · 12 KB
/
LevelEditor.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
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
/// <summary>
/// Редактор уровней, активно взаимодействует с NGUI
/// </summary>
public class LevelEditor : MonoBehaviour {
// Типы кистей в редакторе уровней
public enum PenType {
Clear=0, // Очистка
Wall, // Стена
PacmanSpawn, // Место респауна игрока
Point, // Точки
Energy, // Энергетик
Fruit, // Фрукты
BunkerCenter, // Бункер с привидениями (Центр)
BunkerBricks, // Бункер с привидениями (Стены)
BunkerClear, // Бункер с привидениями (Проход)
BunkerDoor, // Бункер с привидениями (Дверь)
BlinkySpawn, // Место респауна Блинки
PinkySpawn, // Место респауна Пинки
InkySpawn, // Место респауна Инки
ClydeSpawn // Место респауна Клайд
}
public Map CurrentMap; // Карта которая выбирается из списка карт
public UISprite GridSprite;
public GameObject CellPrefab;
public Cell [,] Cells = new Cell[8,8];
public GameObject MapPrefab;
public List<Map> Maps;
public UIInput InputMapTitle;
public UIPopupList WidthPopup;
public UIPopupList HeigthPopup;
// Элементы GUI в настройках
public PacmanGUIElement BlinkyButton;
public PacmanGUIElement PinkyButton;
public PacmanGUIElement InkyButton;
public PacmanGUIElement ClydeButton;
/// <summary>
/// Генерирует пустую карту
/// </summary>
public void GenerateClearMap ()
{
if (CurrentMap)
{
GridSprite.width = CurrentMap.width*25;
GridSprite.height = CurrentMap.height*25;
foreach (Cell c in Cells) {if (c) DestroyObject(c.gameObject);}
Cells = new Cell[CurrentMap.width, CurrentMap.height];
//Заполняем поле пустыми клетками
for (int x = 0; x<CurrentMap.width; x++)
{
for (int y = 0; y<CurrentMap.height; y++)
{
GameObject tempGO = Instantiate (CellPrefab) as GameObject;
Cells[x,y] = tempGO.GetComponent<Cell>();
tempGO.transform.parent = CellPrefab.transform.parent;
tempGO.transform.localScale = Vector3.one;
tempGO.SetActive(true);
tempGO.name = "Cell "+x.ToString()+" "+y.ToString();
Cells[x,y].Xpos = x;
Cells[x,y].Ypos = y;
Cells[x,y].UpdateCell(PenType.Clear);
}
}
//Добавляем бункер и место респауна игрока
Cells[(int) (CurrentMap.PacmanSpawn.x), (int) (CurrentMap.PacmanSpawn.y)].SetUpCell(PenType.PacmanSpawn);
Cells[(int) (CurrentMap.Ghosts.x), (int) (CurrentMap.Ghosts.y)].SetUpCell(PenType.BunkerCenter);
}
}
/// <summary>
/// Возвращает новый объект в списке карт
/// </summary>
Map GetNewMapItem (string _title, string _guid, int _width, int _height)
{
GameObject tempMap = Instantiate (MapPrefab) as GameObject;
CurrentMap = tempMap.GetComponent<Map>();
//prm.CurrentMap = CurrentMap;
Maps.Add (CurrentMap);
tempMap.transform.parent = MapPrefab.transform.parent;
tempMap.transform.localScale = Vector3.one;
MapPrefab.transform.parent.GetComponent<UIGrid>().repositionNow = true;
tempMap.SetActive(true);
tempMap.name = "Map "+(Maps.Count).ToString();
CurrentMap.title = _title;
CurrentMap.GUID = _guid;
CurrentMap.width = _width;
CurrentMap.height = _height;
return tempMap.GetComponent<Map>();
}
/// <summary>
/// Создать новую карту
/// </summary>
public void CreateMap ()
{
try
{
//Создаём объект в списке карт
prm.CurrentMap = GetNewMapItem (InputMapTitle.value, System.Guid.NewGuid().ToString(), int.Parse(WidthPopup.value), int.Parse(HeigthPopup.value));
//Генерируем пустую карту с расположенными бункером и местом респауна игрока
GenerateClearMap();
SaveMap ();
}
catch (UnityException ex)
{
NGUIDebug.print(ex.Message);
}
}
/// <summary>
/// Записываем редактируемую карту в выбранный Map-скрипт
/// </summary>
public void SaveMap ()
{
if (CurrentMap)
{
prm.CurrentMap = CurrentMap;
CurrentMap.width = Cells.GetUpperBound(0)+1;
CurrentMap.height = Cells.GetUpperBound(1)+1;
CurrentMap.map = new string[CurrentMap.height];
//Заполняем массив строк значениями клеток
for (int y = 0; y<CurrentMap.height; y++)
{
CurrentMap.map[y] = "";
for (int x = 0; x<CurrentMap.width; x++)
{
CurrentMap.map[y] += CellToChar(Cells[x,y].CellType);
}
}
}
SaveMapsToXML("maps.xml");
}
/// <summary>
/// Функция возвращает символ клетки
/// </summary>
public char CellToChar (PenType _CellType)
{
switch (_CellType)
{
case PenType.BunkerBricks:
return 'B';
case PenType.BunkerCenter:
return 'C';
case PenType.BunkerClear:
return '-';
case PenType.BunkerDoor:
return '=';
case PenType.Clear:
return '.';
case PenType.Energy:
return '+';
case PenType.Fruit:
return 'f';
case PenType.PacmanSpawn:
return 'P';
case PenType.Point:
return '*';
case PenType.Wall:
return 'W';
case PenType.BlinkySpawn:
return 'b';
case PenType.PinkySpawn:
return 'p';
case PenType.InkySpawn:
return 'i';
case PenType.ClydeSpawn:
return 'c';
default:
return '.';
}
}
/// <summary>
/// Функция возвращает тип клетки соответствующий символу
/// </summary>
public PenType CharToCell (char _CellChar)
{
switch (_CellChar)
{
case 'B':
return PenType.BunkerBricks;
case 'C':
return PenType.BunkerCenter;
case '-':
return PenType.BunkerClear;
case '=':
return PenType.BunkerDoor;
case '.':
return PenType.Clear;
case '+':
return PenType.Energy;
case 'f':
return PenType.Fruit;
case 'P':
return PenType.PacmanSpawn;
case '*':
return PenType.Point;
case 'W':
return PenType.Wall;
case 'b':
return PenType.BlinkySpawn;
case 'p':
return PenType.PinkySpawn;
case 'i':
return PenType.InkySpawn;
case 'c':
return PenType.ClydeSpawn;
default:
return PenType.Clear;
}
}
/// <summary>
/// Загрузить карту в редактор
/// </summary>
public void LoadMap ()
{
if (CurrentMap)
{
prm.CurrentMap = CurrentMap;
GridSprite.width = CurrentMap.width*25;
GridSprite.height = CurrentMap.height*25;
foreach (Cell c in Cells) {if (c) DestroyObject(c.gameObject);}
Cells = new Cell[CurrentMap.width, CurrentMap.height];
//Заполняем поле пустыми клетками
for (int x = 0; x<CurrentMap.width; x++)
{
for (int y = 0; y<CurrentMap.height; y++)
{
GameObject tempGO = Instantiate (CellPrefab) as GameObject;
Cells[x,y] = tempGO.GetComponent<Cell>();
tempGO.transform.parent = CellPrefab.transform.parent;
tempGO.transform.localScale = Vector3.one;
tempGO.SetActive(true);
tempGO.name = "Cell "+x.ToString()+" "+y.ToString();
Cells[x,y].Xpos = x;
Cells[x,y].Ypos = y;
Cells[x,y].UpdateCell(CharToCell(CurrentMap.map[y][x]));
}
}
//Обновляем состояние кнопок
BlinkyButton.GetComponent<UIToggle>().value = prm.CurrentMap.Blinky;
PinkyButton.GetComponent<UIToggle>().value = prm.CurrentMap.Pinky;
InkyButton.GetComponent<UIToggle>().value = prm.CurrentMap.Inky;
ClydeButton.GetComponent<UIToggle>().value = prm.CurrentMap.Clyde;
}
}
/// <summary>
/// Удалить карту
/// </summary>
public void DeleteMap ()
{
if (CurrentMap)
{
Maps.Remove(CurrentMap);
DestroyObject(CurrentMap.gameObject);
CurrentMap = null;
MapPrefab.transform.parent.GetComponent<UIGrid>().repositionNow = true;
SaveMapsToXML("maps.xml");
}
}
/// <summary>
/// Записываем карты в файл
/// </summary>
void SaveMapsToXML(string storage)
{
// Создаём файловое хранилище
XmlDocument xmlDoc = new XmlDocument ();
XmlNode rootNode = null;
rootNode = xmlDoc.CreateElement ("data");
xmlDoc.AppendChild (rootNode);
//XmlNodeList levelList = xmlDoc.GetElementsByTagName ("level");
foreach (Map m in Maps)
{
// Запись в файл
XmlElement elmNew = xmlDoc.CreateElement ("level");
XmlAttribute GUID = xmlDoc.CreateAttribute ("GUID");
XmlAttribute TITLE = xmlDoc.CreateAttribute ("TITLE");
XmlAttribute WIDTH = xmlDoc.CreateAttribute ("WIDTH");
XmlAttribute HEIGHT = xmlDoc.CreateAttribute ("HEIGHT");
XmlAttribute MAP = xmlDoc.CreateAttribute ("MAP");
XmlAttribute PacmanSpawnX = xmlDoc.CreateAttribute ("PacmanSpawnX");
XmlAttribute PacmanSpawnY = xmlDoc.CreateAttribute ("PacmanSpawnY");
XmlAttribute GhostsX = xmlDoc.CreateAttribute ("GhostsX");
XmlAttribute GhostsY = xmlDoc.CreateAttribute ("GhostsY");
XmlAttribute Blinky = xmlDoc.CreateAttribute ("Blinky");
XmlAttribute Pinky = xmlDoc.CreateAttribute ("Pinky");
XmlAttribute Inky = xmlDoc.CreateAttribute ("Inky");
XmlAttribute Clyde = xmlDoc.CreateAttribute ("Clyde");
GUID.Value = m.GUID;
TITLE.Value = m.title;
WIDTH.Value = m.width.ToString();
HEIGHT.Value = m.height.ToString();
MAP.Value = string.Join("/", m.map);
PacmanSpawnX.Value = ((int) (m.PacmanSpawn.x)).ToString();
PacmanSpawnY.Value = ((int) (m.PacmanSpawn.y)).ToString();
GhostsX.Value = ((int) (m.Ghosts.x)).ToString();
GhostsY.Value = ((int) (m.Ghosts.y)).ToString();
Blinky.Value = m.Blinky.ToString();
Pinky.Value = m.Pinky.ToString();
Inky.Value = m.Inky.ToString();
Clyde.Value = m.Clyde.ToString();
elmNew.SetAttributeNode (GUID);
elmNew.SetAttributeNode (TITLE);
elmNew.SetAttributeNode (WIDTH);
elmNew.SetAttributeNode (HEIGHT);
elmNew.SetAttributeNode (MAP);
elmNew.SetAttributeNode (PacmanSpawnX);
elmNew.SetAttributeNode (PacmanSpawnY);
elmNew.SetAttributeNode (GhostsX);
elmNew.SetAttributeNode (GhostsY);
elmNew.SetAttributeNode (Blinky);
elmNew.SetAttributeNode (Pinky);
elmNew.SetAttributeNode (Inky);
elmNew.SetAttributeNode (Clyde);
rootNode.AppendChild (elmNew);
}
xmlDoc.Save (Path.Combine(Application.dataPath, storage));
}
/// <summary>
/// Чтение карт из файла
/// </summary>
public void ReadMapsFromXML(string storage)
{
if (File.Exists(Path.Combine(Application.dataPath, storage)))
{
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.Load(Path.Combine(Application.dataPath, storage));
XmlNodeList levelList = xmlDoc.GetElementsByTagName ("level");
if (Maps.Count>0) {foreach (Map m in Maps) {if (m) DestroyObject(m.gameObject);}}
Maps.Clear();
for (int i = 0; i < levelList.Count; i++)
{
string _guid = levelList[i].Attributes[0].Value;
string _title = levelList[i].Attributes[1].Value;
int _width = XmlConvert.ToInt32(levelList[i].Attributes[2].Value);
int _height = XmlConvert.ToInt32 (levelList[i].Attributes[3].Value);
CurrentMap = GetNewMapItem (_title, _guid, _width, _height);
CurrentMap.map = levelList[i].Attributes[4].Value.Split ('/');
CurrentMap.PacmanSpawn = new Vector2(XmlConvert.ToInt32(levelList[i].Attributes[5].Value), XmlConvert.ToInt32(levelList[i].Attributes[6].Value));
CurrentMap.Ghosts = new Vector2(XmlConvert.ToInt32(levelList[i].Attributes[7].Value), XmlConvert.ToInt32(levelList[i].Attributes[8].Value));
CurrentMap.Blinky = levelList[i].Attributes[9].Value == "True";
CurrentMap.Pinky = levelList[i].Attributes[10].Value == "True";
CurrentMap.Inky = levelList[i].Attributes[11].Value == "True";
CurrentMap.Clyde = levelList[i].Attributes[12].Value == "True";
}
}
}
void OnEnable ()
{
// Считывает имеющиеся в файле карты
ReadMapsFromXML("maps.xml");
}
}