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 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 __init__(self, plttable, counter, map, gamestates: typing.List[CompleteGameState] = []): self._GameStates = gamestates self._LosCalculator = LosCalculator() self._CurrentIndex = 0 self._the_table = plttable self._Counter = counter self._Player_1_Color = "red" self._Player_2_Color = "green" self._ThreatColor = "orange" self._map = map width, height = map.shape self._width = width self._height = height self._PreviousPlayer_1_Location = None self._PreviousPlayer_2_Location = None self._Player1StatDrawn = False self._Player2StatDrawn = False self._Player_1_threatenedTime = None self._Player_1_threateningTime = None self._Player_1_timeinposition = None self._Player_1_threatened = None self._Player_1_destroyed = None self._Player_1_score = None self._Player_2_threatenedTime = None self._Player_2_threateningTime = None self._Player_2_timeinposition = None self._Player_2_threatened = None self._Player_2_destroyed = None self._Player_2_score = None self._FinalScore = None self._Destruction = None if (len(gamestates) != 0): self._DrawState(self._GameStates[0]) self._PreviousPlayer_1_Location = self._GameStates[ 0].player_1_State.position self._PreviousPlayer_2_Location = self._GameStates[ 0].player_2_State.position
def __init__(self, filename): self._filename = filename self._Csvreader = CSVMatrixReader() self._Valid = self._Csvreader.parse(filename) self._Consts = Constants() self._LosCalculator = LosCalculator()
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
class Index(object): def __init__(self, plttable, counter, map, gamestates: typing.List[CompleteGameState] = []): self._GameStates = gamestates self._LosCalculator = LosCalculator() self._CurrentIndex = 0 self._the_table = plttable self._Counter = counter self._Player_1_Color = "red" self._Player_2_Color = "green" self._ThreatColor = "orange" self._map = map width, height = map.shape self._width = width self._height = height self._PreviousPlayer_1_Location = None self._PreviousPlayer_2_Location = None self._Player1StatDrawn = False self._Player2StatDrawn = False self._Player_1_threatenedTime = None self._Player_1_threateningTime = None self._Player_1_timeinposition = None self._Player_1_threatened = None self._Player_1_destroyed = None self._Player_1_score = None self._Player_2_threatenedTime = None self._Player_2_threateningTime = None self._Player_2_timeinposition = None self._Player_2_threatened = None self._Player_2_destroyed = None self._Player_2_score = None self._FinalScore = None self._Destruction = None if (len(gamestates) != 0): self._DrawState(self._GameStates[0]) self._PreviousPlayer_1_Location = self._GameStates[ 0].player_1_State.position self._PreviousPlayer_2_Location = self._GameStates[ 0].player_2_State.position def next(self, event): if len(self._GameStates) == 0: return self._CurrentIndex += 1 if (self._CurrentIndex > len(self._GameStates) - 1): self._CurrentIndex = len(self._GameStates) - 1 self._DrawState(self._GameStates[self._CurrentIndex]) self._PreviousPlayer_1_Location = self._GameStates[ self._CurrentIndex].player_1_State.position self._PreviousPlayer_2_Location = self._GameStates[ self._CurrentIndex].player_2_State.position def prev(self, event): if len(self._GameStates) == 0: return self._CurrentIndex -= 1 if (self._CurrentIndex < 0): self._CurrentIndex = 0 self._DrawState(self._GameStates[self._CurrentIndex]) self._PreviousPlayer_1_Location = self._GameStates[ self._CurrentIndex].player_1_State.position self._PreviousPlayer_2_Location = self._GameStates[ self._CurrentIndex].player_2_State.position def _ClearCellForColor(self, x, y): self._the_table._cells[(x, y)].set_facecolor('w') def _ClearOldColoring(self): for outeridx in range(self._width): for inneridx in range(self._height): self._ClearCellForColor(outeridx, inneridx) def _DrawState(self, gamestate: CompleteGameState): self._ClearOldColoring() self._Counter.set_text("Step: {0}".format(self._CurrentIndex)) self._the_table._cells[( gamestate.player_1_State.position.x, gamestate.player_1_State.position.y)].set_facecolor( self._Player_1_Color) self._the_table._cells[( gamestate.player_2_State.position.x, gamestate.player_2_State.position.y)].set_facecolor( self._Player_2_Color) if (gamestate.player_2_State.threatened or gamestate.player_1_State.threatened): pointlist = self._LosCalculator.getLosList( gamestate.player_1_State.position, gamestate.player_2_State.position) if (len(pointlist) > 2): lastindex = len(pointlist) - 2 for idx in range(0, lastindex): self._the_table._cells[ pointlist[idx].x, pointlist[idx].y].set_facecolor( self._ThreatColor) if (self._FinalScore == None): self._FinalScore = ax.text(0.1, 0.95, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color='Black', fontsize=15) self._FinalScore.visible = False self._FinalScore.set_text( "Player 1 [{0}] Player 2 [{1}]".format( gamestate.player_1_State.score, gamestate.player_2_State.score)) self._FinalScore.set_visible( self._CurrentIndex == len(self._GameStates) - 1) if (self._Destruction == None): self._Destruction = ax.text(0.1, 0.80, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color='Black', fontsize=20) self._Destruction.visible = False self._Destruction.set_visible(False) if gamestate.player_1_State.destroyed: self._Destruction.set_text("Player 1 Destroyed") self._Destruction.set_color(self._Player_1_Color) self._Destruction.set_visible(True) if gamestate.player_2_State.destroyed: self._Destruction.set_text("Player 2 Destroyed") self._Destruction.set_color(self._Player_2_Color) self._Destruction.set_visible(True) if (not self._Player1StatDrawn): self._Player1StatDrawn = True ax.text(0.1, 0.2, 'Player 1', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_threatenedTime = ax.text( 0.1, 0.17, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_threateningTime = ax.text( 0.1, 0.14, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_timeinposition = ax.text( 0.1, 0.11, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_threatened = ax.text( 0.1, 0.08, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_destroyed = ax.text( 0.1, 0.05, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) self._Player_1_score = ax.text(0.1, 0.02, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_1_Color, fontsize=6) if (not self._Player2StatDrawn): self._Player2StatDrawn = True ax.text(0.4, 0.2, 'Player 2', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_threatenedTime = ax.text( 0.4, 0.17, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_threateningTime = ax.text( 0.4, 0.14, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_timeinposition = ax.text( 0.4, 0.11, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_threatened = ax.text( 0.4, 0.08, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_destroyed = ax.text( 0.4, 0.05, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_2_score = ax.text(0.4, 0.02, '', verticalalignment='bottom', horizontalalignment='left', transform=ax.transAxes, color=self._Player_2_Color, fontsize=6) self._Player_1_threatenedTime.set_text( "threatenedTime: {0}".format( gamestate.player_1_State.threatenedTime)) self._Player_1_threateningTime.set_text( "threateningTime: {0}".format( gamestate.player_1_State.threateningTime)) self._Player_1_timeinposition.set_text( "timeinposition: {0}".format( gamestate.player_1_State.timeinposition)) self._Player_1_threatened.set_text("threatened: {0}".format( gamestate.player_1_State.threatened)) self._Player_1_destroyed.set_text("destroyed: {0}".format( gamestate.player_1_State.destroyed)) self._Player_1_score.set_text("score: {0}".format( gamestate.player_1_State.score)) self._Player_2_threatenedTime.set_text( "threatenedTime: {0}".format( gamestate.player_2_State.threatenedTime)) self._Player_2_threateningTime.set_text( "threateningTime: {0}".format( gamestate.player_2_State.threateningTime)) self._Player_2_timeinposition.set_text( "timeinposition: {0}".format( gamestate.player_2_State.timeinposition)) self._Player_2_threatened.set_text("threatened: {0}".format( gamestate.player_2_State.threatened)) self._Player_2_destroyed.set_text("destroyed: {0}".format( gamestate.player_2_State.destroyed)) self._Player_2_score.set_text("score: {0}".format( gamestate.player_2_State.score)) matplotlib.pyplot.draw()