def IsDestinationVisible( self, coordsDebut, coordsFin): # Fonction testée, elle fonctionne inchallah incrX = coordsFin.x - coordsDebut.x if incrX != 0: incrX = int(incrX / abs(incrX)) #sens du déplacement en X : 1 ou -1 incrY = coordsFin.y - coordsDebut.y if incrY != 0: incrY = int(incrY / abs(incrY)) #sens du déplacement en Y : 1 ou -1 # Si on arrive à la case voulue, il existe un moyen de voir cette case à partir de caseDebut : on retourne True if coordsDebut == coordsFin: return True # Sinon, si on est pas sur la même colonne, qu'il n'y a pas d'objet bloquant la vision sur la colonne d'à côté, on teste la fonction en se plaçant sur la colonne d'à côté # Don't touch this, c'est dégueu mais ça fonctionne #j'adore le récursif if incrX != 0 and \ ((Point(coordsDebut.x + incrX, coordsDebut.y) == coordsFin ) or \ (self.layerSolid[coordsDebut.x + incrX, coordsDebut.y] is None and \ self.IsDestinationVisible(Point(coordsDebut.x + incrX, coordsDebut.y), coordsFin))): return True elif incrY != 0 and \ ((Point(coordsDebut.x, coordsDebut.y + incrY) == coordsFin) or \ (self.layerSolid[coordsDebut.x, coordsDebut.y + incrY] is None and \ self.IsDestinationVisible(Point(coordsDebut.x, coordsDebut.y + incrY), coordsFin))): return True return False
def __getitem__(self, key): if not isinstance(key, Point): key = Point(key[0], key[1]) if key.InRange(len(self.grid), len(self.grid[0])): return self.grid[key.x][key.y] LogsManager.Warning("Out of range exception caught: " + str(key)) return ("Sel stopped kidding us")
def __setitem__(self, key, value): if not isinstance(key, Point): key = Point(key[0], key[1]) if key.InRange(len(self.grid), len(self.grid[0])): self.grid[key.x][key.y] = value if self.viewGrid is not None: self.viewGrid.Update(key.x, key.y) return LogsManager.Warning("Out of range exception caugth: " + str(key))
class Queen: SPAWN1 = Point(0, -1) SPAWN2 = Point(1, -1) SPAWN3 = Point(-1, 0) SPAWN4 = Point(2, 0) SPAWN5 = Point(-1, 1) SPAWN6 = Point(2, 1) SPAWN7 = Point(0, 2) SPAWN8 = Point(1, 2) SPAWNS = [SPAWN1, SPAWN2, SPAWN3, SPAWN4, SPAWN5, SPAWN6, SPAWN7, SPAWN8] def __init__(self, team): #property self._team = team self._order = Cfg.SLEEP self._positionOrder = None self._spawnType = None self._nameSpawn = "" def SpawnAnt(self, name, type, position): self._order = Cfg.QUEEN_SPAWN_ANT self._positionOrder = position self._spawnType = type self._nameSpawn = name def newTurn(self, FOV): pass
def GetXYByRef(self, ref): """ Get position of an entity by reference (ref)""" for i in range(self.GetWidth()): for j in range(self.GetHeight()): if self[i, j]==ref: coord = Point(i, j) return coord
def GetFOV(self, ref): """Renvoie deux arrays, le premier concerne les floor entities le second les solid""" coords = self.layerSolid.GetXYByRef(ref) fov = Cfg.FOV size = fov * 2 + 1 FOVSolid = [[0 for i in range(size)] for i in range(size)] FOVFloor = [[0 for i in range(size)] for i in range(size)] for i in range(-fov, fov + 1): for j in range(-fov, fov + 1): distance = abs(i) + abs(j) if coords[0] + i < 0 or coords[0] + i >= self.layerSolid.GetWidth() or\ coords[1] + j < 0 or coords[1] + j >= self.layerSolid.GetHeight(): FOVSolid[i + fov][j + fov] = Cfg.ROCK FOVFloor[i + fov][j + fov] = Cfg.UNKNOWN elif distance <= fov and self.IsDestinationVisible( coords, Point(coords.x + i, coords.y + j)): FOVSolid[i + fov][j + fov] = Cfg.EntityToType( self.layerSolid[coords[0] + i, coords[1] + j]) FOVFloor[i + fov][j + fov] = Cfg.EntityToType( self.layerFloor[coords[0] + i, coords[1] + j]) else: FOVSolid[i + fov][j + fov] = Cfg.UNKNOWN FOVFloor[i + fov][j + fov] = Cfg.UNKNOWN return [FOVSolid, FOVFloor]
def GenerateQueenPosition(self): partCircle = 2 * math.pi / self.nbQueen radius = random.randrange( Cfg.MIN_SPAWN_QUEEN_RADIUS, round(self.mapManager.map.width / 2 * (1 - 1 / 4))) increment = random.random() * 2 * math.pi #Si bug : diviser par 10 for i in range(self.nbQueen): yield Point( round(self.mapManager.map.width // 2 + radius * math.cos(i * partCircle + increment)), round(self.mapManager.map.height // 2 + radius * math.sin(i * partCircle + increment)))
def SpawnAnt(self, queens, map): for q in queens.keys(): point = Point.StringToPoint(q) + queens[q]._positionOrder if map.layerSolid.IsNone(point) and isinstance( map.layerFloor[point], Bread): map.layerSolid.Append( queens[q]._spawnType(map.layerSolid.GetNewId(), queens[q]._nameSpawn, queens[q]._team), point) map.layerFloor[point] = None queens[q]._order = Cfg.SLEEP queens[q]._positionOrder = None queens[q]._spawnType = None queens[q]._nameSpawn = ""
def FOVQueen(self, team, map): pos = Point.StringToPoint(self.GetQueenPosition(team)) FOVSolid = [] FOVFloor = [] for spawn in Queen.SPAWNS: if not (map.layerSolid[pos.x + spawn.x, pos.y + spawn.y] is None): FOVSolid.append(spawn) else: FOVSolid.append(None) if not (map.layerFloor[pos.x + spawn.x, pos.y + spawn.y] is None): FOVFloor.append(spawn) else: FOVFloor.append(None) return (FOVSolid, FOVFloor)
def Steps(self, obstacleClass=(Rock, Dirt, Ant)): matrix = [] for i in range(len(self.maps[0])): matrix.append([]) for j in range(len(self.maps[0][0])): matrix.append(0 if any( [isinstance(m[i][j], obstacleClass) for m in self.maps]) else 1) grid = Grid(matrix=matrix) start = grid.node(self.start.x, self.start.y) end = grid.node(self.dest.x, self.dest.y) finder = AStarFinder(diagonal_movement=DiagonalMovement.never) path, runs = finder.find_path(start, end, grid) return [Point(n.x, n.y) for n in path]
while len( colliding ) > 0 and iter < 100: #Peut-être faire un nombre d'itération max pour éviter que des petits bugs deviennt gros #Ajouter la liste des fourmis qui se cognent dans celles à PUNIR for i in colliding: if not (i in punished): punished.append(i) #Nouvelle tentative, en annulant le déplacement de celles qui se cognent nextTry = [] for index in range(0, len(dest)): if index in colliding: nextTry.append(pos[index]) else: nextTry.append(dest[index]) colliding = MoveManager.checkPauli(nextTry, other) iter = iter + 1 return punished if __name__ == '__main__': _pos = [Point(0, 0), Point(0, 1), Point(1, 1)] _dest = [Point(0, 1), Point(0, 0), Point(1, 0)] #(MoveManager.calculateAntsMove(_pos,_dest))print
for i in range(self.map.layerFloor.GetWidth()): for j in range(self.map.layerFloor.GetHeight()): self.Update(i, j) if __name__ == "__main__": from Sentiant.Model.Point import Point from Sentiant.Model.Ant import Ant from Sentiant.Model.QueenTile import QueenTile from Sentiant.Model.MapManager import MapManager import os os.chdir("..\\..\\") print(os.getcwd()) root = Tk() mapGen = MapManager(width=16, height=16) mapGen.RegisterQueen(QueenTile(1, "team"), Point(4, 4)) map = mapGen.Generate() map.layerSolid.Append(Ant(1, "name", "team"), Point(6, 7)) map.layerSolid.Append(Ant(1, "name", "team"), Point(5, 3)) grid = Grid(boss=root, map=map, size=(480, 480)) grid.pack() root.mainloop()
coords = self.Map.layerSolid.GetXYByRef(ref) if not (self[coords.x, coords.y] is None): return True return False if __name__ == '__main__': from Sentiant.Model.Map import Map from Sentiant.Model.Ant import Ant from Sentiant.Model.Point import Point from Sentiant.Model.Bread import Bread map = Map(10, 10) ant = Ant(1, "", "") point = Point(5, 5) bread = Bread(0) map.layerSolid.Append(ant, point) map.layerFloor.Append(bread, point) map.layerFloor.Gather(ant) print(ant) map.layerFloor.Drop(ant) print(ant)
if __name__ == '__main__': from Sentiant.Model import MapManager, Ant from Sentiant.View import MainView import os from tkinter import Button class QueenTest(Queen): def newTurn(self): self.SpawnAnt("test", Ant, self.SPAWN1) def SpawnRess(map, position): map.layerFloor[position] = Bread(map.layerFloor.GetNewId()) os.chdir("..\\..\\") mapGen = MapManager() qM = QueensManager(3, ["1", "2", "3"], [QueenTest, QueenTest, QueenTest], mapGen) map = mapGen.Generate() view = MainView(map, size=(500, 500)) position = Point.StringToPoint(qM.GetQueenPosition()[0]) + Queen.SPAWN1 Button(view, command=lambda: SpawnRess(map, position)).pack() Button(view, text="NextTurn", command=lambda: qM.NextTurn(1, map)).pack() view.Run()
finder = AStarFinder(diagonal_movement=DiagonalMovement.never) path, runs = finder.find_path(start, end, grid) return [Point(n.x, n.y) for n in path] def __len__(self): return len(self.Steps()) if __name__ == '__main__': table = [[0] * 12 for k in range(12)] table[1][2] = 'v' def tprint(t): for row in t: for it in row: print(it, end="") print() tprint(table) print() path = Pathfind(table, Point(10, 10), Point(1, 1)) for point in path.Steps(str): table[point.x][point.y] = 1 tprint(table) print()
def __init__(self, FOV, relativeDest, relativeStart=Point(0, 0)): self.start = relativeStart self.dest = relativeDest self.maps = FOV # = `[FOVSolid, FOVFloor]` from `Map.GetFOV`
from Sentiant.Model.LogsManager import LogsManager if __name__ == '__main__': from Sentiant.Model.Entity import Entity from Sentiant.Model.Point import Point layer = Layer(10, 10) print(layer.GetHeight()) print(layer.GetWidth()) entity = Entity() layer.Append(entity, Point(0,0)) print(layer[Point(0,0)]) print(layer[0,0]) print(layer.Append(entity, Point(0,0))) layer.Append(Entity(2), Point(5,5)) print(layer.ToList()) print(layer.GetXYByRef(entity).x) print(layer.GetXYByRef(entity).y) layer.Remove(entity) print(layer.ToList())
coordsPhéro.y) if distance <= phéro.hpRadius: phéros.append(phéro) return phéros if __name__ == '__main__': from Sentiant.Model.Map import Map from Sentiant.Model.Ant import Ant from Sentiant.Model.Point import Point map = Map(10, 10) ant = Ant(0, "", "") point = Point(5, 5) map.layerSolid.Append(ant, point) map.layerPheromone.Place(ant, 0) print(map.layerPheromone.DetectFromPos(ant)) ant2 = Ant(1, "", "") map.layerSolid.Append(ant2, Point(0, 0)) print(map.layerPheromone.DetectFromPos(ant2)) ant2 = Ant(2, "", "") map.layerSolid.Append(ant2, Point(3, 2))
def DoAttack(): #print(a1) a2.Attack(Cfg.RIGHT) tm.NextTurn() #print(a1) def DoMove(): a1.Move(Cfg.LEFT) a2.Move(Cfg.RIGHT) os.chdir("..\\..\\") Cfg.NEST_RADIUS = 20 mapGen = MapManager(width=16, height=16, breadAmount=0, rockRatio=0) mapGen.RegisterQueen(QueenTile(1, "team"), Point(8, 8)) map = mapGen.Generate() a1, a2 = Ant(1, "name", "team"), Ant(2, "name", "team") map.layerSolid.Append(a1, Point(5, 5)) map.layerSolid.Append(a2, Point(5, 4)) tm = TurnManager(map) view = MainView(map, tm, (500, 500)) Button(view, text="Attaque", command=lambda : DoAttack()).pack() Button(view, text="Move", command=lambda: DoMove()).pack() view.Run()
def GetQueenTiles(self, team): for i in range(self.GetWidth()): for j in range(self.GetHeight()): if (type(self[i, j]) is QueenTile and self[i, j].team == team): if (type(self[i + 1, j]) is QueenTile): if (type(self[i, j + 1]) is QueenTile): return [ Point(i, j), Point(i + 1, j), Point(i, j + 1), Point(i + 1, j + 1) ] else: return [ Point(i, j - 1), Point(i + 1, j - 1), Point(i, j), Point(i + 1, j) ] else: if (type(self[i, j + 1]) is QueenTile): return [ Point(i - 1, j), Point(i, j), Point(i - 1, j + 1), Point(i, j + 1) ] else: return [ Point(i - 1, j - 1), Point(i, j - 1), Point(i - 1, j), Point(i, j) ] pass
from Sentiant.Model.Layer.LayerPheromone import LayerPheromone from Sentiant.Model.Layer.LayerSolid import LayerSolid if __name__ == '__main__': from Sentiant.Model.Ant import Ant from Sentiant.Model.MapManager import MapManager from Sentiant.View.MainView import MainView from Sentiant.Model.QueenTile import QueenTile import os from Sentiant.Model import Cfg ant = Ant(0, "name", "team") Cfg.NEST_RADIUS = 20 Cfg.FOV = 2 os.chdir("..\\..\\") mapGen = MapManager(width=10, height=10) mapGen.RegisterQueen(QueenTile(1, "team1"), Point(5, 5)) map = mapGen.Generate() map.layerSolid.Append(ant, Point(3, 3)) #print(map.IsDestinationVisible(antCoords, Point(4, 3))) #print(map.IsDestinationVisible(antCoords, Point(7, 7))) #print(map.IsDestinationVisibe(antCoords, Point(2, 5))) print(map.GetFOV(ant)) view = MainView(map, size=(500, 500)) view.Run()
class Cfg: def __init__(self): pass HPMAX = 2 FOV = 3 HPRADIUS = 5 WIDTH = 25 HEIGHT = 25 #pas en dessous de 15 UP = Point(-1, 0) DOWN = Point(1, 0) RIGHT = Point(0, 1) LEFT = Point(0, -1) STAY = Point(0, 0) DIRECTIONS = (UP, DOWN, RIGHT, LEFT) NULL = None MOVE = "move" DIG = "dig" DROP = "drop" PICKUP = "pickup" ATTACK = "attack" SLEEP = "sleep" PHERO = "phero" # Attention à ne pas faire phero sur un rocher mdr ACTIONS = (MOVE, DIG, DROP, PICKUP, ATTACK, SLEEP, PHERO) ANT = "ant" QUEEN = "queen" DIRT = "dirt" ROCK = "rock" BREAD = "bread" COOKIE = "cookie" UNKNOWN = "X" EMPTY = " " NEST_RADIUS = 3 #rayon du cercle libéré (pas de terre) autour de la reine MIN_SPAWN_QUEEN_RADIUS = 5 #distance minimale éloignée du cookie par rapport à laquelle la reine peut spawn QUEEN_SLEEP = "sleep" QUEEN_SPAWN_ANT = "spawn" @staticmethod def ParseDirection(direction): if isinstance(direction, Point) and direction.StepDistance() <= 1: return direction direction = direction.lower() if direction == "up": return Cfg.UP elif direction == "down": return Cfg.DOWN elif direction == "right": return Cfg.RIGHT elif direction == "left": return Cfg.LEFT return Cfg.NULL @staticmethod def AddDirection(coords, direction): direction = Cfg.parseDirection(direction) if direction in [Cfg.UP, Cfg.DOWN, Cfg.RIGHT, Cfg.LEFT]: nextPos = coords + direction return nextPos return Cfg.NULL @staticmethod def EntityToType(ref): if isinstance(ref, Ant): return Cfg.ANT if isinstance(ref, QueenTile): return Cfg.QUEEN if isinstance(ref, Dirt): return Cfg.DIRT if isinstance(ref, Rock): return Cfg.ROCK if isinstance(ref, Bread): return Cfg.BREAD if isinstance(ref, Cookie): return Cfg.COOKIE return Cfg.EMPTY