-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNode.py
292 lines (241 loc) · 9.97 KB
/
Node.py
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
from __future__ import annotations
from copy import deepcopy
from typing import Callable, Any
import numpy as np
from glm import ivec3
import globals
from Connector import Connector
from StructureBase import Structure
import worldTools
import vectorTools
class Node:
structure: Structure
cost: float
rewardFunction: Callable[[Node], float] | None
terminationFunction: Callable[[Node], bool] | None
actionFilter: Callable[[Structure], bool] | None
settlementType: str | None
bookKeepingProperties: dict[str, Any]
bookKeeper: Callable[[Node], None] | None
rng: np.random.Generator
parentNode: Node | None
incomingConnector: Connector | None
connectorSlots: set[Connector]
routeNames: set[str]
possibleActions: set[Action]
hasPossibleActionsCache: bool
_bookKeeper: Callable[[Node], None] | None
def __init__(
self,
structure: Structure = None,
cost: float = 0.0,
parentNode: Node | None = None,
parentConnector: Connector | None = None,
rewardFunction: Callable[[Node], float] = None,
terminationFunction: Callable[[Node], bool] = None,
actionFilter: Callable[[Structure], bool] = None,
settlementType: str = None,
bookKeepingProperties: dict[str, Any] = None,
bookKeeper: Callable[[Node], None] = None,
rng: np.random.Generator = np.random.default_rng(),
):
self.structure = structure
self.cost = cost
self.rewardFunction = rewardFunction
self.terminationFunction = terminationFunction
self.actionFilter = actionFilter
self.settlementType = settlementType
self.bookKeepingProperties = deepcopy(bookKeepingProperties if bookKeepingProperties else dict())
self.bookKeeper = bookKeeper
self.rng = rng
self.parentNode = parentNode
self.incomingConnector = None
self.connectorSlots = set()
if parentConnector:
self.incomingConnector = parentConnector
rearFacingConnector = structure.rearFacingConnector
rearFacingConnector.finalNode = parentNode
self.connectorSlots.add(rearFacingConnector)
self.routeNames = set()
self.possibleActions = set()
self.hasPossibleActionsCache = False
@property
def bookKeeper(self):
return self._bookKeeper
@bookKeeper.setter
def bookKeeper(self, bookKeeper: Callable[[Node], None]):
if bookKeeper is None:
self._bookKeeper = None
else:
self._bookKeeper = bookKeeper
bookKeeper(self)
def finalize(self, nextNode: Node = None, routeName: str = None, clearActionCache: bool = False):
if clearActionCache:
self.possibleActions.clear()
self.hasPossibleActionsCache = False
elif self.hasPossibleActionsCache and nextNode:
for possibleAction in self.possibleActions.copy():
if possibleAction.connector == nextNode.incomingConnector:
self.possibleActions.remove(possibleAction)
if nextNode:
nextNode.incomingConnector.finalNode = nextNode
self.connectorSlots.add(nextNode.incomingConnector)
if routeName:
self.routeNames.add(routeName)
globals.nodeList.add(self)
def doPreProcessingSteps(self):
self.structure.doPreProcessingSteps(self)
def place(self):
self.structure.place()
def doPostProcessingSteps(self):
self.structure.doPostProcessingSteps(self)
@property
def hasOpenSlot(self) -> bool:
for connector in self.structure.connectors:
if connector not in self.connectorSlots:
return True
return False
def evaluateCandidateNextStructure(self, candidateStructure: Structure = None) -> float:
if self.actionFilter and self.actionFilter(candidateStructure) is False:
return 0.0
if worldTools.isStructureInsideBuildArea(candidateStructure) is False:
return 0.0
if worldTools.isStructureTouchingSurface(candidateStructure):
return 0.0
for otherNode in globals.nodeList:
if candidateStructure.isIntersection(otherNode.structure):
return 0.0
cost = 0.0
cost += candidateStructure.evaluateStructure()
return cost
@staticmethod
def getCurrentPlayer() -> int:
return 1
def getPossibleActions(self) -> list[Action]:
for connector in self.structure.connectors:
# Check if slot isn't already occupied by other node
if connector in self.connectorSlots:
# Use existing node instead of creating a new one
matchingConnector = None
for connectorSlot in self.connectorSlots:
if connectorSlot == connector:
matchingConnector = connectorSlot
break
if matchingConnector.finalNode and matchingConnector.finalNode != self.parentNode:
self.possibleActions.add(Action(
existingNode=matchingConnector.finalNode,
connector=matchingConnector,
))
continue
if self.hasPossibleActionsCache:
return list(self.possibleActions)
for connector in self.structure.connectors:
# Check if slot isn't already occupied by other node
if connector in self.connectorSlots:
continue
connectionRotation: int = (connector.facing + self.structure.facing) % 4
nextStructures = connector.nextStructure
for candidateStructureName in nextStructures:
if candidateStructureName not in globals.structureFolders:
print(f'Structure file {candidateStructureName} does not exist')
continue
structureFolder = globals.structureFolders[candidateStructureName]
# noinspection PyCallingNonCallable
candidateStructure: Structure = structureFolder.structureClass(
facing=connectionRotation,
position=ivec3(0, 0, 0),
settlementType=self.settlementType,
)
nextPosition = vectorTools.getNextPosition(
facing=connectionRotation,
currentBox=self.structure.box,
nextBox=candidateStructure.box,
offset=connector.offset,
) + self.structure.position
candidateStructure.position = nextPosition
candidateStructureCost = self.evaluateCandidateNextStructure(candidateStructure)
if candidateStructureCost > 0:
self.possibleActions.add(Action(
structure=candidateStructure,
cost=candidateStructureCost,
connector=connector,
))
self.hasPossibleActionsCache = True
return list(self.possibleActions)
def takeAction(self, action: Action) -> Node:
if action.existingNode:
action.existingNode.cost = action.cost
action.existingNode.rewardFunction = self.rewardFunction
action.existingNode.terminationFunction = self.terminationFunction
# Only invalidate possibleActions cache if a different actionFilter is used
if action.existingNode.actionFilter != self.actionFilter:
action.existingNode.actionFilter = self.actionFilter
action.existingNode.possibleActions = None
action.existingNode.settlementType = self.settlementType
return action.existingNode
return Node(
structure=action.structure,
cost=action.cost,
parentNode=self,
parentConnector=action.connector,
rewardFunction=self.rewardFunction,
terminationFunction=self.terminationFunction,
actionFilter=self.actionFilter,
settlementType=self.settlementType,
bookKeepingProperties=self.bookKeepingProperties,
bookKeeper=self.bookKeeper,
rng=self.rng,
)
def isTerminal(self) -> bool:
if self.terminationFunction and self.terminationFunction(self):
return True
if len(self.getPossibleActions()) == 0:
return True
return False
def getReward(self) -> float:
# only needed for terminal states
return self.rewardFunction(self)
def __hash__(self):
return hash(self.structure)
def __eq__(self, other):
return hash(self) == hash(other)
def __repr__(self):
return f'{__class__.__name__}; ' \
f'{self.structure}; ' \
f'{self.bookKeepingProperties}; {self.rewardFunction(self)}; {self.routeNames}'
class Action:
structure: Structure
cost: float
connector: Connector
existingNode: Node | None
def __init__(
self,
structure: Structure = None,
cost: float = 0.0,
connector: Connector = None,
existingNode: Node = None,
):
self.connector = connector
if existingNode:
self.structure = existingNode.structure
self.cost = 0
self.existingNode = existingNode
else:
self.structure = structure
self.cost = cost
self.existingNode = None
@property
def structureFileName(self):
return self.structure.structureFile.name[:-4]
def __add__(self, other):
if isinstance(other, Action):
return self.cost + other.cost
return self.cost + other
def __radd__(self, other):
return self + other
def __eq__(self, other):
return hash(self) == hash(other)
def __hash__(self):
return hash((self.connector, self.structureFileName))
def __repr__(self):
return f'{__class__.__name__} {self.cost} {self.structure}'