def test_DrawNoData(self): RealPath = os.path.join(os.path.dirname(__file__), '../Maps/TestMap/Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) drawMatch = GameDrawing(csvreader.Matrix) self.assertTrue(csvreader.fileLoaded, "error")
def test_DrawAll_FinalState_Destruction(self): RealPath = os.path.join(os.path.dirname(__file__), '../Maps/TestMap/Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) game1 = CompleteGameState(100) game1.player_1_State.position = Point(0, 0) game1.player_2_State.position = Point(9, 9) game2 = CompleteGameState(100) game2.player_1_State.position = Point(1, 1) game2.player_2_State.position = Point(2, 4) game3 = CompleteGameState(100) game3.player_1_State.position = Point(2, 7) game3.player_2_State.position = Point(9, 3) game3.player_1_State.score = 10 game3.player_2_State.score = 20 game3.player_2_State.destroyed = True games = [] games.append(game1) games.append(game2) games.append(game3) drawMatch = GameDrawing(csvreader.Matrix, games) self.assertTrue(csvreader.fileLoaded, "error")
def test_IsLos_Fail_SameCol_UpMovment(self): RealPath = os.path.join(os.path.dirname(__file__), '..\Maps\ChallangeMap\Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) p1 = Point(7, 4) p2 = Point(7, 2) calc = LosCalculator() isLos = calc.IsLos(p1, p2, csvreader.Matrix) self.assertFalse(isLos)
def test_IsLos_Success_SameRow_LeftMovment(self): RealPath = os.path.join(os.path.dirname(__file__), '..\Maps\ChallangeMap\Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) p1 = Point(1, 1) p2 = Point(0, 1) calc = LosCalculator() isLos = calc.IsLos(p1, p2, csvreader.Matrix) self.assertTrue(isLos)
def test_DrawRandomData(self): RealPath = os.path.join(os.path.dirname(__file__), '../Maps/TestMap/Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) games = [] for idx in range(100): game = CompleteGameState(100) self._RandomizeGame(game) game.playingtime = idx games.append(game) drawMatch = GameDrawing(csvreader.Matrix, games) self.assertTrue(csvreader.fileLoaded, "error")
def Play(self): if (self._Valid): csvreader = CSVMatrixReader() csvreader.parse(self._gamemetadata.infrapath) if (csvreader.fileLoaded): drawMatch = GameDrawing(csvreader.Matrix, self._gamestates)
class InfraPrepMode(object): def __init__(self, filename): self._filename = filename self._Csvreader = CSVMatrixReader() self._Valid = self._Csvreader.parse(filename) self._Consts = Constants() self._LosCalculator = LosCalculator() def Prep(self, destfolder) -> bool: if (self._Valid): filename = Path(self._filename).name try: #copy CSV destfilename = os.path.join(destfolder, filename) if (destfilename != self._filename): shutil.copy2(self._filename, destfilename) #build Graph self._buildGraph() self._SaveGraph(destfolder) # build Controllpoints self._LoadControlledPoints() self._SaveControllingPoints(destfolder) # build Controllpoints self._LoadSafePoints() self._SaveSafePoints(destfolder) except: print(sys.exc_info()) return False return False def _LoadControlledPoints(self): self._PointsControl = {} dim = self._getMapDim() for RowIndex in range(0, dim.width): self._PointsControl[RowIndex] = {} for ColIndex in range(0, dim.height): self._GetControllingPointsForPoint(RowIndex, ColIndex) def _LoadSafePoints(self): self._SafePoints = [] dim = self._getMapDim() goodvalues = [self._Consts.SafePointValue] safepointsindexes = np.isin(self._Csvreader.Matrix, goodvalues) Y, X = np.where(safepointsindexes) for i in range(len(Y)): self._SafePoints.append(Point(X[i], Y[i])) print(safepointsindexes) def _GetControllingPointsForPoint(self, x, y): dim = self._getMapDim() point = Point(x, y) pointcontrol = PointsControl(point) for ColIndex in range(0, dim.height): for RowIndex in range(0, dim.width): targetpoint = Point(RowIndex, ColIndex) if (targetpoint != point): if (self._LosCalculator.IsLos(point, targetpoint, self._Csvreader.Matrix)): pointcontrol.controlledpoints.append(targetpoint) if not self._LosCalculator.IsSafePoint( targetpoint, self._Csvreader. Matrix) and self._LosCalculator.IsLos( targetpoint, point, self._Csvreader.Matrix): pointcontrol.controllingpoints.append(targetpoint) self._PointsControl[x][y] = pointcontrol def _SaveSafePoints(self, destfolder): safepoints = jsonpickle.encode(self._SafePoints) filedir = os.path.join(destfolder, self._Consts.SafePointsFileName) with io.open(filedir, 'w') as f: f.write(safepoints) def _SaveControllingPoints(self, destfolder): controllingpoints = jsonpickle.encode(self._PointsControl) filedir = os.path.join(destfolder, self._Consts.ControllingPointsFileName) with io.open(filedir, 'w') as f: f.write(controllingpoints) def _SaveGraph( self, destfolder, ): data = json_graph.node_link_data(self._Graph) graph = json.dumps(data) filedir = os.path.join(destfolder, self._Consts.MovementGraphFileName) with io.open(filedir, 'w') as f: f.write(graph) def _getMapDim(self): dim = Dimensions(0, 0) if self._Csvreader.fileLoaded: dim.width, dim.height = self._Csvreader.Matrix.shape return dim def _buildGraph(self): dim = self._getMapDim() labels = {} self._Graph = nx.Graph() for colIndex in range(0, dim.width): for rowIndex in range(0, dim.height): cord = Point.ToGridNode(colIndex, rowIndex, dim.height) self._UpdateWeight(cord, colIndex, rowIndex, dim, 0, 0) self._UpdateWeight(cord, colIndex, rowIndex, dim, 0, 1) self._UpdateWeight(cord, colIndex, rowIndex, dim, 0, -1) self._UpdateWeight(cord, colIndex, rowIndex, dim, -1, 0) self._UpdateWeight(cord, colIndex, rowIndex, dim, -1, 1) self._UpdateWeight(cord, colIndex, rowIndex, dim, -1, -1) self._UpdateWeight(cord, colIndex, rowIndex, dim, 1, 0) self._UpdateWeight(cord, colIndex, rowIndex, dim, 1, -1) self._UpdateWeight(cord, colIndex, rowIndex, dim, 1, 1) self._Graph.nodes[cord]["X"] = colIndex self._Graph.nodes[cord]["Y"] = rowIndex labels[cord] = "({0}-{1})".format(rowIndex, colIndex) nx.relabel_nodes(self._Graph, labels) def _UpdateWeight(self, cord, colIndex, rowIndex, dim, xFactor, yFactor): newColIndex = colIndex + xFactor newRowIndex = rowIndex + yFactor if (newColIndex) >= dim.width: return if (newColIndex) < 0: return if (newRowIndex) >= dim.height: return if (newRowIndex) < 0: return # we try to go to Cover -not connected NextCord = Point.ToGridNode(newColIndex, newRowIndex, dim.height) if self._Csvreader.Matrix.item( (colIndex, rowIndex )) == self._Consts.SafePointValue or self._Csvreader.Matrix.item( (newColIndex, newRowIndex)) == self._Consts.SafePointValue: # we set connectivity self._Graph.add_edge( NextCord, cord, weight=self._Consts.ConnectedGraphVertexWeight) else: # Alt Diff Issue AltDiff = abs( self._Csvreader.Matrix.item((colIndex, rowIndex)) - self._Csvreader.Matrix.item((newColIndex, newRowIndex))) if AltDiff >= self._Consts.MaximumAltDif: return # we set connectivity self._Graph.add_edge( NextCord, cord, weight=self._Consts.ConnectedGraphVertexWeight) @property def valid(self) -> bool: return self._Valid
class MapHolder: def __init__(self,configProvider): self._GraphLoaded = False self._Consts=Constants() self._ConfigProvider=configProvider self._MovementCalculator=MovementCalculator(configProvider) self._Csvreader=CSVMatrixReader() self._LosCalculator = LosCalculator() self._GraphLoaded=False self._DrawGraphs=bool(self._ConfigProvider.getValue('Game.Config', 'DrawMapHolderGraph').lower() in ("true")) def loadMap(self,mapname): self._Csvreader.parse(mapname) if self._Csvreader.fileLoaded: self._GraphLoaded =self._LoadData(mapname) self._Mapname = mapname return self._Csvreader.fileLoaded and self._GraphLoaded def _LoadData(self,mapname): try: self._PointsControl= {} controllingPointsfile=os.path.join(os.path.dirname(mapname), self._Consts.ControllingPointsFileName) print("Attempting to load {} form controllingpoints".format(controllingPointsfile)) with io.open(controllingPointsfile, 'r') as f: controllingpoints_frozenstate = f.read() tempDict = jsonpickle.decode(controllingpoints_frozenstate) dim=self.getMapDim() for RowIndex in range(0, dim.width): self._PointsControl[RowIndex] = {} for ColIndex in range(0, dim.height): self._PointsControl[RowIndex][ColIndex]=tempDict['{}'.format(RowIndex)]['{}'.format(ColIndex)] movementgraphname = os.path.join(os.path.dirname(mapname), self._Consts.MovementGraphFileName) print("Attempting to load {} form movementgraphname".format(movementgraphname)) with io.open(movementgraphname, 'r') as f: movementgraph_frozenstate = f.read() dumps=jsonpickle.decode(movementgraph_frozenstate) self._Graph = json_graph.node_link_graph(dumps) safepointsfilename = os.path.join(os.path.dirname(mapname), self._Consts.SafePointsFileName) print("Attempting to load {} form safepointsfilename".format(safepointsfilename)) self._SafePoints = [] with io.open(safepointsfilename, 'r') as f: safepoints_frozenstate = f.read() self._SafePoints = jsonpickle.decode(safepoints_frozenstate) return True except: print(sys.exc_info()) return False def drawGraph(self): if self._GraphLoaded: graph_pos = nx.shell_layout(self._Graph) nx.draw_networkx_nodes(self._Graph, graph_pos, node_size=1000, node_color='blue', alpha=0.3) nx.draw_networkx_edges(self._Graph, graph_pos) labels = {} for Idx in range(0,len(self._Graph.nodes().keys())): labels[Idx] = "({0}-{1})".format(self._Graph.nodes[Idx]["X"], self._Graph.nodes[Idx]["Y"]) nx.draw_networkx_labels(self._Graph, graph_pos,labels=labels, font_size=12, font_family='sans-serif') plt.show() def getMapDim(self): dim=Dimensions(0,0) if self._Csvreader.fileLoaded: dim.width,dim.height=self._Csvreader.Matrix.shape return dim def mayMove(self,pFrom:Point,pTo:Point): if not self._Csvreader.fileLoaded: return False if not self._GraphLoaded: return False dim=self.getMapDim() if dim.IsPointInDim(pFrom)==False: return False if dim.IsPointInDim(pTo)==False: return False NodeFrom = Point.ToGridNodeFromPoint(pFrom, dim.height) NodeTo = Point.ToGridNodeFromPoint(pTo, dim.height) return self._MovementCalculator.mayMove(NodeFrom,NodeTo,self._Graph) def isLOS(self,pFrom:Point,pTo:Point): if not self._Csvreader.fileLoaded: return False if not self._GraphLoaded: return False dim=self.getMapDim() if dim.IsPointInDim(pFrom)==False: return False if dim.IsPointInDim(pTo)==False: return False return self._LosCalculator.IsLos(pFrom,pTo,self._Csvreader.Matrix) def getPath(self,pFrom:Point,pTo:Point): if not self._Csvreader.fileLoaded: return PathResult([],False) if not self._GraphLoaded: return PathResult([],False) dim=self.getMapDim() if dim.IsPointInDim(pFrom)==False: return PathResult([],False) if dim.IsPointInDim(pTo)==False: return PathResult([],False) if(pFrom==pTo): return PathResult(pTo,True) NodeFrom = Point.ToGridNodeFromPoint(pFrom, dim.height) NodeTo = Point.ToGridNodeFromPoint(pTo, dim.height) path=self._MovementCalculator.getPath(NodeFrom,NodeTo,self._Graph) if self._DrawGraphs and path.valid: # we set connectivity drawingGraph=nx.Graph() for idx in range(len(path.nodelist)): drawingGraph.add_node(idx) drawingGraph.nodes[idx]["X"] = path.points[idx].x drawingGraph.nodes[idx]["Y"] = path.points[idx].y drawingGraph.nodes[idx]["RealID"] = path.nodelist[idx] for idx in range(len(path.nodelist)): for inneridx in range(len(path.nodelist)): if(idx!=inneridx and self._Graph.has_edge(path.nodelist[idx],path.nodelist[inneridx])): drawingGraph.add_edge(idx,inneridx, weight=self._Consts.ConnectedGraphVertexWeight) graph_pos = nx.shell_layout(drawingGraph) nx.draw_networkx_nodes(drawingGraph, graph_pos, node_size=1000, node_color='blue', alpha=0.3) nx.draw_networkx_edges(drawingGraph, graph_pos) labels = {} for Idx in range(0, len(drawingGraph.nodes().keys())): labels[Idx] = "({0}-{1})".format(drawingGraph.nodes[Idx]["X"],drawingGraph.nodes[Idx]["Y"]) nx.draw_networkx_labels(drawingGraph, graph_pos, labels=labels, font_size=12, font_family='sans-serif') plt.show() return path def getAlt(self,location:Point): dim = self.getMapDim() if dim.IsPointInDim(location) == False: return self._Consts.InValidAlt nodeloc = Point.ToGridNodeFromPoint(location, dim.height) return self._Csvreader.Matrix[location.y,location.x] def isCloseToSafty(self, location: Point): for safty in self._SafePoints: pathresult=self.getPath(location,safty) if pathresult.valid and pathresult.length<=self._Consts.SafetypointCloseRange: return True return False def isSafePoint(self, location: Point): for safty in self._SafePoints: if safty==location: return True return False @property def mapLoaded(self): return self._Csvreader.fileLoaded @property def graphLoaded(self): return self._GraphLoaded @property def map(self): return self._Csvreader.Matrix @property def pointscontrol(self): return self._PointsControl @property def saftypoints(self): return self._SafePoints
def test_Parse_Fail_TooManyItems(self): RealPath = os.path.join(os.path.dirname(__file__), '..Maps/TooManyCollsTestMap/Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) self.assertFalse(csvreader.fileLoaded, "error")
def test_Parse_OK(self): RealPath = os.path.join(os.path.dirname(__file__), '../Maps/TestMap/Map.csv') csvreader = CSVMatrixReader() csvreader.parse(RealPath) self.assertTrue(csvreader.fileLoaded, "error")