-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartEnemy.cs
More file actions
102 lines (81 loc) · 2.9 KB
/
SmartEnemy.cs
File metadata and controls
102 lines (81 loc) · 2.9 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Maze1
{
public class SmartEnemy : Unit
{
private char[,] _map;
private Unit _target;
private int[] dx = { -1, 0, 1, 0 };
private int[] dy = { 0, 1, 0, -1 };
public SmartEnemy(int startX, int startY, char symbol, ConsoleRenderer renderer, char[,] map, Unit target) :
base(startX, startY, symbol, renderer)
{
_map = map;
_target = target;
}
public override void Update()
{
List<Node> path = FindPath();
if (path == null)
return;
Node nextPosition = path[1];
TryChangePosition(nextPosition.X, nextPosition.Y, _map);
}
public List<Node> FindPath()
{
Node startNode = new Node(X, Y);
Node targetNode = new Node(_target.X, _target.Y);
List<Node> openList = new List<Node> { startNode };
List<Node> closedList = new List<Node>();
while (openList.Count > 0)
{
Node currentNode = openList[0];
foreach (var node in openList)
{
if(node.Value < currentNode.Value)
currentNode = node;
}
openList.Remove(currentNode);
closedList.Add(currentNode);
if (currentNode.X == targetNode.X && currentNode.Y == targetNode.Y)
{
List<Node> path = new List<Node>();
while (currentNode != null)
{
path.Add(currentNode);
currentNode = currentNode.Parent;
}
path.Reverse();
return path;
}
for (int i = 0; i < dx.Length; i++)
{
int newX = currentNode.X + dx[i];
int newY = currentNode.Y + dy[i];
if (IsValid(newX, newY))
{
Node neighbor = new Node(newX, newY);
if (closedList.Contains(neighbor))
continue;
neighbor.Parent = currentNode;
neighbor.CalculateEstimate(targetNode.X, targetNode.Y);
neighbor.CalculateValue();
openList.Add(neighbor);
}
}
}
return null;
}
private bool IsValid(int x, int y)
{
bool containsX = x >= 0 && x < _map.GetLength(0);
bool containsY = y >= 0 && y < _map.GetLength(1);
bool isNotWall = _map[x, y] != '#';
return containsX && containsY && isNotWall;
}
}
}