-
Notifications
You must be signed in to change notification settings - Fork 0
/
ControllerFirstVersion
320 lines (307 loc) · 10.7 KB
/
ControllerFirstVersion
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
public class QueueItem<T>
{
public T Item;
public QueueItem<T> Next;
}
public class Queue<T>
{
//отдельный класс нужен для очереди:
//сделав всего несколько манипуляций мы сможем превратить её в стек,
//и таким образом сделать обход в глубину
//на самом деле, это понадобится тогда, когда мы захотим искать путь во взвешенном графе
//т.е. в таком, где проход по ребру имеет стоимость (например длину переезда от вершины в вершину)
public QueueItem<T> Head { get; set; }
public QueueItem<T> Tail { get; set; }
public bool IsEmpty
{
get
{
return Head == null;
}
}
public Queue ()
{
Head = null;
Tail = null;
}
public void Push(T item)
{
if (IsEmpty)
Tail = Head = new QueueItem<T> { Item = item, Next = null };
else
{
var newItem = new QueueItem<T> { Item = item, Next = null };
Tail.Next = newItem;
Tail = newItem;
}
}
public T Pop()
{
if (this.IsEmpty) throw new InvalidOperationException();
var result = Head.Item;
Head = Head.Next;
if (Head == null)
Tail = null;
return result;
}
}
public class LabyrinthCoordinates
{
public readonly int X;
public readonly int Y;
public LabyrinthCoordinates()
{
X = 0;
Y = 0;
}
public LabyrinthCoordinates(int x, int y)
{
X = x;
Y = y;
}
public override bool Equals(object obj)
{
if (!(obj is LabyrinthCoordinates))
return false;
var otherCoordinates = obj as LabyrinthCoordinates;
return this.X == otherCoordinates.X && this.Y == otherCoordinates.Y;
}
public override int GetHashCode()
{
return X*31+Y*17;
}
public override string ToString()
{
return string.Format("X:{0} Y:{1}", X, Y);
}
}
public class LabyrinthCeil
{
public LabyrinthCoordinates Coordinates;
public List<LabyrinthCeil> IncidentNodes;
public LabyrinthCeil(LabyrinthCoordinates coordinates)
{
Coordinates = coordinates;
IncidentNodes = new List<LabyrinthCeil>();
}
public IEnumerable<LabyrinthCeil> GetIncidentNodes()
{
foreach (var node in IncidentNodes)
yield return node;
}
//протестить:
//берём лист, создаем объект LabyrinthCeil
//потом меняем лист
//изменится ли при этом readlonly поле?
//пока будем считать, что нет
}
public class Labyrinth
{
//Проблема - индексация по координатам понадобится:
//все объекты, напарник, детальки - имеют координаты
//на будущее - не забудем, что напарник-бот может стырить детальку, и тогда расстояние до неё считать не надо -
//ато ещё побежим за ним
public Dictionary<LabyrinthCoordinates,LabyrinthCeil> Nodes;
public Labyrinth()
{
Nodes = new Dictionary<LabyrinthCoordinates, LabyrinthCeil>();
}
public void AddEdge(LabyrinthCoordinates first, LabyrinthCoordinates second)
{
LabyrinthCeil firstNode;
if (Nodes.ContainsKey(first))
firstNode = Nodes[first];
else
{
firstNode = new LabyrinthCeil(first);
Nodes[first] = firstNode;
}
LabyrinthCeil secondNode;
if (Nodes.ContainsKey(second))
secondNode = Nodes[second];
else
{
secondNode = new LabyrinthCeil(second);
Nodes[second] = secondNode;
}
if (!firstNode.IncidentNodes.Contains(secondNode))
{
firstNode.IncidentNodes.Add(secondNode);
secondNode.IncidentNodes.Add(firstNode);
}
}
internal void AddEdge()
{
throw new NotImplementedException();
}
}
public class Node
{
public int ShortestPathLength { get; set; }
public bool IsUsed { get; set; }
public LabyrinthCeil Ceil;
public Node LastVisited;
}
public class PathFinder
{
const int infinity = 1000000000;
public Labyrinth Labyrinth;
private Dictionary<LabyrinthCoordinates,Node> nodes;
public LabyrinthCoordinates StartNode { get; set; }
public void SetNodesUnvisited()
{
nodes = this.Labyrinth.Nodes
.ToDictionary(item => item.Key, item => new Node
{
Ceil = item.Value,
IsUsed = false,
ShortestPathLength = infinity,
LastVisited = null
});
}
public void SetMinimalDistances(LabyrinthCoordinates startNode)
{
StartNode = startNode;
var nodesQueue = new Queue<Node>();
nodesQueue.Push(nodes[startNode]);
nodes[startNode].IsUsed = true;
nodes[startNode].ShortestPathLength = 0;
nodes[startNode].LastVisited = null;
while (!nodesQueue.IsEmpty)
{
var currentNode = nodesQueue.Pop();
foreach (var incident in currentNode.Ceil.GetIncidentNodes())
{
var currentIncidentNode = nodes[incident.Coordinates];
if (!currentIncidentNode.IsUsed)
{
nodesQueue.Push(currentIncidentNode);
currentIncidentNode.ShortestPathLength = currentNode.ShortestPathLength + 1;
currentIncidentNode.IsUsed = true;
currentIncidentNode.LastVisited = currentNode;
}
}
}
}
public PathFinder(Labyrinth labyrinth)
{
this.Labyrinth = labyrinth;
}
public List<LabyrinthCoordinates> GetPath(LabyrinthCoordinates destinateCeil)
{
var current = nodes[destinateCeil];
var result = new List<LabyrinthCoordinates>();
while (current != null)
{
result.Add(current.Ceil.Coordinates);
current = current.LastVisited;
}
result.Reverse();
return result;
}
public void SetDistances(LabyrinthCoordinates from)
{
SetNodesUnvisited();
SetMinimalDistances(from);
}
public List<LabyrinthCoordinates> GetDistanceFromStartNode(LabyrinthCoordinates destinateCeil)
{
return GetPath(destinateCeil);
}
public List<LabyrinthCoordinates> GetShortestWay(LabyrinthCoordinates from, LabyrinthCoordinates to)
{
SetDistances(from);
//случай, когда из from нельзя попасть в to пока не рассмотрен
return GetPath(to);
}
}
public enum UnitColor
{
Red,
Green,
Blue
}
public class BrokenDetail
{
public UnitColor Color;
public LabyrinthCoordinates Coordinates;
public BrokenDetail(UnitColor color, LabyrinthCoordinates coordinates)
{
Color = color;
Coordinates = coordinates;
}
}
public class BrokenTube
{
public UnitColor Color;
public List<LabyrinthCoordinates> AdjacentCeils;
//Adjacent - смежный
public BrokenTube(UnitColor color, List<LabyrinthCoordinates> adjacentCeils)
{
Color = color;
AdjacentCeils = adjacentCeils;
}
}
public enum BotCondition
{
RunForDetail,
RunForTube
}
public class ControllerInstruction
{
public readonly BotCondition Condition;
public readonly LabyrinthCoordinates NextCeil;
public readonly bool IsHoldDetail;
public ControllerInstruction(BotCondition condition, LabyrinthCoordinates nextCeil, bool isHoldDetail)
{
this.Condition = condition;
this.NextCeil = nextCeil;
this.IsHoldDetail = isHoldDetail;
}
}
public class WayController
{
public Labyrinth labyrinth;
public WayController(Labyrinth labyrinth)
{
this.labyrinth = labyrinth;
}
public IEnumerable<ControllerInstruction> GetPath(LabyrinthCoordinates botPosition, List<LabyrinthCoordinates> brokenDetails)
{
var finder = new PathFinder(this.labyrinth);
finder.SetDistances(botPosition);
var pathToDetails = new List<List<LabyrinthCoordinates>>(brokenDetails.Capacity);
var minDistance = 1000000000;
var minPath = -1;
for (int i=0;i<brokenDetails.Count;i++)
{
pathToDetails[i] = finder.GetDistanceFromStartNode(brokenDetails[i]);
if (pathToDetails[i].Count < minDistance)
{
minDistance = pathToDetails[i].Count;
minPath = i;
}
}
if (minPath == -1)
{
yield return new ControllerInstruction(BotCondition.RunForDetail, botPosition, false);
yield break;
}
/*
List<LabyrinthCoordinates> way = new List<LabyrinthCoordinates>(1) { botPosition };
for (int i = 0; i < brokenDetails.Count; i++)
{
finder.SetDistances(brokenDetails[i]);
}*/
foreach (var step in pathToDetails[minPath])
yield return new ControllerInstruction(BotCondition.RunForDetail, step, false);
}
}
}