public void init() { if (initComplete == false) { //set ref gridScript = Ref.getGridScript(); visibleObstManager = GetComponent <VisibleObstManager>(); managerScript = Ref.getManagerGO().GetComponent <Manager>(); recalculateTime = GetComponent <AgentProps>().cooperationLenght; spatialAStarScript = GetComponent <SpatialAStar>(); spaceTimeAStarScript = GetComponent <SpaceTimeAStar>(); agent = transform; followPathScript = agent.GetComponent <FollowPath>(); //saves initial grid in grid var saveInitalGrid(); spaceTimeAStarScript.init(); spatialAStarScript.init(grid); spaceTimeAStarScript.setSpacialAStarScript(spatialAStarScript); managerScript.increaseFrameCount(); //here we switch the role of target and agent spatialAStarScript.FindPathSpatial(target.position, agent.position, true, null); path = spaceTimeAStarScript.FindPath(agent.position, target.position, true); followPathScript.init(); followPathScript.setNewPath(path); } initComplete = true; }
public static MovementPath AStar(Point start, Point end, Stage stage = null) { MovementPath newPath = new MovementPath(null); if (stage == null) { stage = Stage.CurrentStage; } // setup grid with walls //MyPathNode[,] grid = new MyPathNode[(int)stage.Width, (int)stage.Height]; MyPathNode[][] grid = new MyPathNode[(int)stage.Width][]; for (int x = 0; x < (int)stage.Width; x++) { grid[x] = new MyPathNode[(int) stage.Height]; for (int y = 0; y < (int)stage.Height; y++) { grid[x][y] = new MyPathNode() { IsWall = stage.GetTileAt(x, y).GetWalkable(), X = x, Y = y, }; } } SpatialAStar<MyPathNode, Object> aStar = new SpatialAStar<MyPathNode, Object>(grid); LinkedList<MyPathNode> path = aStar.Search(new Point(0, 0), new Point(stage.Width - 2, stage.Height - 2), null); return null; }
void Awake() { // setup grid with walls MyPathNode[,] grid = new MyPathNode[Width, Height]; for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { bool isWall = ((y % 2) != 0) && (Random.Range(0, 10) != 8); grid[x, y] = new MyPathNode() { IsWall = isWall, X = x, Y = y, }; } } // second generic parameter should be the argument type for IsWalkable (I'm using GameObject) SpatialAStar <MyPathNode, Object> aStar = new SpatialAStar <MyPathNode, Object>(grid); // start point, desired end point, // the third parameter is the value passed to IsWalkable (eg, the GameObject of the NPC doing the walking) // if not path is found, null is returned LinkedList <MyPathNode> path = aStar.Search(new Point(0, 0), new Point(Width - 2, Height - 2), null); }
private void CreateSolver() { m_Solver = new SpatialAStar <WalkableNode, object>(m_Nav.grid); m_Solver.allowsDiagonals = m_AllowsDiagonals; m_PreviousStep = position; m_NextStep = position; }
private LinkedList <Cell> TestIfMapIsSolveable() { SpatialAStar <Cell, Object> aStar = new SpatialAStar <Cell, Object>(grid.Cells); LinkedList <Cell> path = aStar.Search(new Point((int)player.Position.X / 20, (int)player.Position.Y / 20), new Point((int)Goal.Position.X / 20, (int)Goal.Position.Y / 20), null); return(path); }
// 构建寻路器 void BuildPathFinder() { pathNodes = new PathNode[Width, Height]; FC.For2(Width, Height, (x, y) => pathNodes[x, y] = new PathNode(x, y, CheckSpareSpace)); pathFinder = new SpatialAStar <PathNode, KeyValuePair <int, int> >(pathNodes) { Only4Adjacent = true }; }
public NavigationController() { //Debug.Log("Creating navigation grid..."); _navGrid = new GridPoint[GRID_HEIGHT, GRID_WIDTH]; for (int h = 0; h < GRID_HEIGHT; h++) for (int w = 0; w < GRID_WIDTH; w++) _navGrid[h, w] = new GridPoint(h, w); _pather = new SpatialAStar<GridPoint, UnitMoverType>(_navGrid); }
public PathToNearestStreetFromBuildingFinder( IMap map, BuildingOnMapLocator buildingOnMapLocator, ClosestStreetFinder closestStreetFinder) { _map = map; _astar = new SpatialAStar <ITile>(_map.GetTilesArray()); _buildingOnMapLocator = buildingOnMapLocator; _closestStreetFinder = closestStreetFinder; }
public void InitializeAlgorithms(IOsnowaContext newContext) { _jps = new Jps(newContext.PathfindingData.WallMatrixForJps); _jpsTightDiagonal = new JpsTightDiagonal(newContext.PathfindingData.WallMatrixForJps); _jpsStrictWalk = new JpsStrictWalk(newContext.PathfindingData.WallMatrixForJps); _spatialAStar = new SpatialAStar <MyPathNode, Position>(newContext.PathfindingData.PathNodeMatrixForSpatialAStar); _ready = true; }
public IEnumerable<ILocation> GetWalkPoints (ILocation from, ILocation to) { if (_pathMask == null) yield break; int fromX = (int)from.X; int fromY = (int)from.Y; int toX = (int)to.X; int toY = (int)to.Y; SpatialAStar<PathNode, object> finder = new SpatialAStar<PathNode, object> (_pathMask); var paths = finder.Search (new Point (fromX, fromY), new Point ((int)to.X, (int)to.Y), null); if (paths == null) yield break; if (!SmoothPath) { foreach (var node in paths) { yield return new AGSLocation (node.X, node.Y, to.Z); } } int currentDirX = paths.First.Value.X - fromX; int currentDirY = paths.First.Value.Y - fromY; PathNode prevNode = null; PathNode prevAcceptedNode = paths.First.Value; foreach (var node in paths) { if (prevNode != null) { int dirX = node.X - prevNode.X; int dirY = node.Y - prevNode.Y; if (dirX != currentDirX || dirY != currentDirY) { if (Math.Abs (prevAcceptedNode.X - node.X) <= 10 && Math.Abs (prevAcceptedNode.Y - node.Y) <= 10 && (node.X != toX || node.Y != toY)) continue; //smoothing the path currentDirX = dirX; currentDirY = dirY; prevAcceptedNode = node; yield return new AGSLocation (node.X, node.Y, to.Z); } } prevNode = node; } }
public AStar(Tile[,] tiles) { var width = tiles.GetLength(0); var height = tiles.GetLength(1); var nodes = new PathNode[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { nodes[x, y] = new PathNode { pos = new Vector2Int(x, y), tile = tiles[x, y] }; } } aStar = new SpatialAStar <PathNode, object>(nodes); }
void Start() { managerScript = Ref.getManagerGO().GetComponent <Manager>(); gridScript = Ref.getGridScript(); visibleObstManagerScript = GetComponent <VisibleObstManager>(); agentPropsScript = GetComponent <AgentProps>(); saveInitalGrid(); agent = transform; spatialAStarScript = GetComponent <SpatialAStar>(); spatialAStarScript.init(grid); managerScript.increaseFrameCount(); path = spatialAStarScript.FindPathSpatial(agent.position, target.position, true, null); followPathScript = agent.GetComponent <FollowPath>(); followPathScript.init(); followPathScript.setNewPath(path); }
public void RefreshMap() { MyPathNode[,] grid = new MyPathNode[100, 100]; for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { Boolean isWall = ((y % 2) != 0) && (UnityEngine.Random.Range(0, 10) != 8); grid[x, y] = new MyPathNode() { IsWall = false, X = x, Y = y, }; } } aStar = new SpatialAStar <MyPathNode, System.Object>(grid); }
private void setupWalls() { if (isEntrance) { placeExteriorWallsAndInitializeGrid(); placeStairWalls(); return; } // Create rooms until a valid one is complete bool allPathsArePossible = true; do { placeExteriorWallsAndInitializeGrid(); placeStairWalls(); placeInteriorWalls(); SpatialAStar <Tile, System.Object> aStar = new SpatialAStar <Tile, System.Object>(grid); allPathsArePossible = true; // Check to make sure all paths are possible RoomConnection connection = roomConnections[0]; // if all can connect to this connection, then they can all connect to each other foreach (RoomConnection otherConnection in roomConnections) { if (connection == otherConnection) { continue; } LinkedList <Tile> path = aStar.Search(PositionOfRoomConnection(connection), PositionOfRoomConnection(otherConnection), null); bool pathIsPossible = path != null; if (!pathIsPossible) { allPathsArePossible = false; } } } while (!allPathsArePossible); }
public GameModeBase() { myId = 0; idSet = false; map = new TileMap(); alerts = new List<HUDAlert>(); entities = new Dictionary<ushort, EntityBase>(); players = new Dictionary<byte, Player>(); Effects = new List<EffectBase>(); pathFinding = null; Fog = null; deathSound_Cliff = new Sound(ExternalResources.GSoundBuffer("Resources/Audio/Death/0.wav")); unitCompleteSound_Worker = new Sound(ExternalResources.GSoundBuffer("Resources/Audio/UnitCompleted/0.wav")); useSound_Cliff = new Sound(ExternalResources.GSoundBuffer("Resources/Audio/UseCommand/0.wav")); gatherResourceSound_Cliff = new Sound(ExternalResources.GSoundBuffer("Resources/Audio/GetResources/0.wav")); attackSound_Cliff = new Sound(ExternalResources.GSoundBuffer("Resources/Audio/OnAttack/0.wav")); }
// 构建寻路器 void BuildPathFinder() { pathNodes = new PathNode[w, h]; FC.For2(w, h, (x, y) => pathNodes[x, y] = new PathNode(x, y, CheckSpareSpace)); pathFinder = new SpatialAStar <PathNode, KeyValuePair <int, T[]> >(pathNodes); }
public void ParseData(MemoryStream stream) { var reader = new BinaryReader(stream); var signature = (Gamemode.Signature) reader.ReadByte(); switch (signature) { case Gamemode.Signature.Custom: ParseCustom(stream); break; case Gamemode.Signature.Entity: { ushort id = reader.ReadUInt16(); if (entities.ContainsKey(id)) entities[id].ParseData(stream); } break; case Gamemode.Signature.MapLoad: ParseMap(stream); break; case Gamemode.Signature.TiledMapLoad: { var tiledMap = new TiledMap(); tiledMap.Load(stream); map.ApplyLevel(tiledMap); pathFinding = new SpatialAStar<PathNode, object>(map.GetPathNodeMap()); Fog = new FogOfWar(map.MapSize.X, map.MapSize.Y); for (int x = 0; x < map.MapSize.X; x++) { for (int y = 0; y < map.MapSize.Y; y++) { Fog.Grid[x, y].Blocker = map.Tiles[x, y].Solid; } } } break; case Gamemode.Signature.Handshake: ParseHandshake(stream); break; case Gamemode.Signature.EntityAdd: { ushort id = reader.ReadUInt16(); byte entityType = reader.ReadByte(); EntityBase entity = EntityBase.EntityFactory(entityType); entity.Type = (Entity.EntityType) entityType; entity.WorldEntities = entities; entity.WorldId = id; entity.MyGameMode = this; entity.LoadFromBytes(stream); AddEntity(entity, id); entity.SetTeam(reader.ReadByte()); } break; case Gamemode.Signature.EntityLoad: { ushort count = reader.ReadUInt16(); for (int i = 0; i < count; i++) { ushort entId = reader.ReadUInt16(); byte entType = reader.ReadByte(); EntityBase entAdd = EntityBase.EntityFactory(entType); entAdd.Type = (Entity.EntityType) entType; entAdd.WorldEntities = entities; entAdd.LoadFromBytes(stream); entAdd.WorldId = entId; entAdd.MyGameMode = this; AddEntity(entAdd, entId); entAdd.SetTeam(reader.ReadByte()); } } break; case Gamemode.Signature.PlayerData: { byte playerId = reader.ReadByte(); if (players.ContainsKey(playerId)) { players[playerId].Load(stream); } } break; case Gamemode.Signature.PlayersLoad: { byte count = reader.ReadByte(); for (int i = 0; i < count; i++) { var playerAdd = new Player(); playerAdd.Load(stream); if (players.ContainsKey(playerAdd.ClientId) == false) { players.Add(playerAdd.ClientId, playerAdd); } } } break; case Gamemode.Signature.RemoveEntity: { ushort id = reader.ReadUInt16(); if (entities.ContainsKey(id)) { entities[id].OnDeath(); entities.Remove(id); } } break; case Gamemode.Signature.GroupMovement: { float x = reader.ReadSingle(); float y = reader.ReadSingle(); bool reset = reader.ReadBoolean(); bool attack = reader.ReadBoolean(); byte count = reader.ReadByte(); for (int i = 0; i < count; i++) { ushort id = reader.ReadUInt16(); if (!entities.ContainsKey(id)) continue; if (reset) entities[id].ClearRally(); Vector2f startPos = entities[id].Position; if (!reset && entities[id].rallyPoints.Count > 0) { startPos = new Vector2f(entities[id].rallyPoints[entities[id].rallyPoints.Count - 1].X, entities[id].rallyPoints[entities[id].rallyPoints.Count - 1].Y); } PathFindReturn path = PathFindNodes(startPos.X, startPos.Y, x, y); if (path.List == null) continue; foreach (PathNode pathNode in path.List) { if (pathNode == path.List.First.Value) continue; var pos = new Vector2f(pathNode.X*path.MapSize.X + (path.MapSize.X/2), pathNode.Y*path.MapSize.Y + (path.MapSize.Y/2)); entities[id].Move(pos.X, pos.Y, attack); } } } break; case Gamemode.Signature.SetCamera: { SetCamera(reader.ReadByte(), new Vector2f(reader.ReadSingle(), reader.ReadSingle())); } break; case Gamemode.Signature.UpdatePosition: { ushort unitId = reader.ReadUInt16(); float posX = reader.ReadSingle(); float posY = reader.ReadSingle(); if (entities.ContainsKey(unitId)) { entities[unitId].Position = new Vector2f(posX, posY); } } break; } }
protected void SetMap(string file) { TiledMap.Load(file); map.ApplyLevel(TiledMap); pathFinding = new SpatialAStar<PathNode, object>(map.GetPathNodeMap()); foreach (Vector2f apples in TiledMap.AppleResources) { var resourceAdd = new Resources(Server, null); resourceAdd.ResourceType = ResourceTypes.Apple; resourceAdd.Position = apples; AddEntity(resourceAdd); } foreach (Vector2f wood in TiledMap.WoodResources) { var resourceAdd = new Resources(Server, null); resourceAdd.ResourceType = ResourceTypes.Tree; resourceAdd.Position = wood; AddEntity(resourceAdd); } }
protected virtual void ParseMap(MemoryStream memory) { map.LoadFromBytes(memory); pathFinding = new SpatialAStar<PathNode, object>(map.GetPathNodeMap()); }
public void InstantiateAStar(GameManager.SpecialPathNode[,] board) { aStar = new SpatialAStar <GameManager.SpecialPathNode, System.Object>(board); }
public void InstantiateAStar(GameManager.SpecialPathNode[,] board) { aStar = new SpatialAStar<GameManager.SpecialPathNode, System.Object>(board); }
public override void doTurn(GameState state) { try { if (state.TimeRemaining < 5) return; if (turn == 0) { Log("my team: player " + (state.MyAnts.First().Team + 1)); Log("map " + state.Width+"x"+state.Height); Log("turn time " + state.TurnTime); } Log(""); Log("Turn " + (turn++)); Log("My Ants: " + state.MyAnts.Count); SetTurnStrategy(state); string stratstring = ""; foreach (var v in Enum.GetValues(typeof(Strategy))) { stratstring += Enum.GetName(typeof(Strategy), v) + ":" + strategies[(int)v] + ";"; } Log("Strategy: " + stratstring); this.Destinations.Clear(); astar = new SpatialAStar<Tile, object>(state.Map); foreach (var goal in Goals) goal.AntExists = false; //need to check these each turn and clean up if ant gone foreach (AntLoc ant in state.MyAnts) { Log("ant: " + ant); Goal goal = this.Goals.FirstOrDefault(g => g.CurrentPoint.Equals(ant)); if (goal != null && (goal.CurrentPath.Count==0 || goal.IsTerminated(state))) { if (goal.CurrentPath.Count == 0) Log("ant goal complete"); else Log("ant goal terminated"); Goals.Remove(goal); goal = null; } if (goal != null) { goal.AntExists = true; Log("ant existing goal: " + String.Join(";", goal.CurrentPath.Select(p => p.Location.ToString()).ToArray()) + " " + Enum.GetName(typeof(Strategy), goal.CurrentStrategy)); } else { if (state.TimeRemaining < 50) // choose a fast strategy { Log("short on time ("+state.TimeRemaining+") - choose scatter"); goal = Scatter(ant, state); } else { goal = ChooseStrategy(ant, state); if (!goal.CurrentPath.Any()) { Log("bad goal/path - scatter instead"); goal = Scatter(ant, state); } } Goals.Add(goal); Log("new ant goal: " + String.Join(";", goal.CurrentPath.Select(p => p.Location.ToString()).ToArray()) + " " + Enum.GetName(typeof(Strategy), goal.CurrentStrategy)); } if (goal != null) { var loc = goal.CurrentPath.Dequeue(); var directions = ant.GetDirections(loc.Location); foreach (var d in directions) { var newLoc = ant.GetDestination(d); if (state.IsUnoccupied(newLoc) && state.IsPassable(newLoc) && !Destinations.Contains(newLoc)) { ant.Move(d); goal.CurrentPoint = newLoc; goal.CurrentStep++; Destinations.Add(newLoc); break; } } } } int removed = Goals.RemoveAll(g => !g.AntExists);//clean up goals for missing ants Log("ant goals(" + Goals.Count + ", "+removed+" removed): " + String.Join(";", Goals.Select(g => "["+Enum.GetName(typeof(Strategy),g.CurrentStrategy)+"]"+g.CurrentPoint.ToString()+"->"+g.EndPoint.ToString()).ToArray())); if (removed > 0) // losing fights - condense { AlterStrategy(Strategy.Condense, Preference.StronglyEncourage); AlterStrategy(Strategy.Condense, Preference.StronglyEncourage); AlterStrategy(Strategy.Condense, Preference.StronglyEncourage); } } catch (Exception exc) { Log(exc.Message); Log(exc.StackTrace); } }
private IEnumerable <PathNode> PathFinding(Point a, Point b) { var aStar = new SpatialAStar <PathNode, Object>(_court.ToWallGrid()); return(aStar.Search(a, b, null)); }
//getter and setters public void setSpacialAStarScript(SpatialAStar _spatialAStarScript) { spatialAStarScript = _spatialAStarScript; }