public static UnitController CreateNewUnit(UnitDef def, FloatCoords topLeft, WorldController world, Faction_Controller factionController) { UnitController unitController = new UnitController(def) { UnitView = { Texture = def.Image, Width = def.Width, Height = def.Height }, UnitModel = { Speed = def.Speed, Faction = factionController } }; Location_Controller location = new Location_Controller(world, topLeft.x, topLeft.y) { LocationModel = { Parent = unitController } }; unitController.LocationController = location; return(unitController); }
protected GuiViewImage(FloatCoords location, ViewValues viewValues) { Coords = location; Width = viewValues.Width; Height = viewValues.Height; Texture = viewValues.Image; }
public void Test_ShouldReturnCorrectNeighbour_WhenGivenTwoPoints(int x1, int y1, int x2, int y2, int x3, int y3) { // Arrange FloatCoords floatCoords = new FloatCoords() { x = x1, y = y1 }; FloatCoords target = new FloatCoords() { x = x2, y = y2 }; FloatCoords expected = new FloatCoords() { x = x3, y = y3 }; CoordsCalculator coordsCalculator = new CoordsCalculator(floatCoords); // Act List <FloatCoords> actual = coordsCalculator.GetCommonNeighboursWith((Coords)target); // Assert Assert.IsTrue(actual.Any(neighbour => neighbour == expected)); }
// name explains this I guess public void ButtonPressed(FloatCoords mouseCoords) { //Save current mouse location/coords firstPoint = WorldPositionCalculator.DrawCoordsToCellFloatCoords(WorldPositionCalculator.TransformWindowCoords((Coords)mouseCoords, Game.Camera.GetViewMatrix()), Game.GameView.TileSize); //enable drawfunction of selectionbox active = true; }
//TODO find better name for this method. public void MoveTo(FloatCoords target, bool isQueueKeyPressed) //[Review] This can be a Lambda expression { pathfinderThread?.Abort(); ThreadStart threadStart = () => { List <FloatCoords> points; try { points = Pathfinder.FindPath(target, LocationModel); } catch (NoPathFoundException exception) { return; } if (isQueueKeyPressed) { points.ForEach(coords => Waypoints.Enqueue(coords)); } else { Waypoints = new Queue <FloatCoords>(points); } }; pathfinderThread = new Thread(threadStart); pathfinderThread.Start(); }
public GameActionTabModel(IGameAction[] gameActions, GameActionGuiController parent) { this.parent = parent; GameActionTabItems = new GameActionTabItem[GAME_ACTIONS_PER_TAB]; int column = 0; int row = 0; for (int i = 0; i < gameActions.Length; i++) { IGameAction gameAction = gameActions[i]; FloatCoords location = new FloatCoords() { x = column * (ItemWidth + HMoatSize) + HMoatSize, y = row * (ItemWidth + VMoatSize) + VMoatSize }; location += parent.View.Coords; ViewValues viewValues = new ViewValues(gameAction.IconValues.Image, ItemWidth, ItemWidth); gameAction.IconValues = viewValues; GameActionTabItems[i] = new GameActionTabItem(gameAction, location); column++; if (column < COLUMNS) { continue; } column = 0; row++; } }
/// <summary> /// Reduces amount of waypoints in a list, makes path smoother /// </summary> /// <param name="routeTemp"></param> /// <param name="unitLocationModel"></param> /// <returns></returns> private Queue <FloatCoords> ReduceWaypoints(IEnumerable <FloatCoords> routeTemp, LocationModel unitLocationModel) { Queue <FloatCoords> route = new Queue <FloatCoords>(routeTemp); FloatCoords target = route.Last(); Queue <FloatCoords> wayPoints = new Queue <FloatCoords>(); wayPoints.Enqueue(unitLocationModel.FloatCoords); // While not arrived at destination while (wayPoints.Last() != target) { FloatCoords currentCoords = wayPoints.Last(); CoordsCalculator coordsCalculator = new CoordsCalculator(currentCoords); List <Coords> rayCells; FloatCoords nextCoords; do { nextCoords = route.Dequeue(); rayCells = coordsCalculator.GetCoordsOnRayWith(nextCoords); } while (route.Count > 0 && AreAllCellsLegal(rayCells, unitLocationModel)); wayPoints.Enqueue(nextCoords); } return(wayPoints); }
//standardices coords to topleft and bottomright public void SetCoords(FloatCoords firstCoords, FloatCoords secondCoords) { topLeft.x = firstCoords.x < secondCoords.x ? firstCoords.x : secondCoords.x; topLeft.y = firstCoords.y < secondCoords.y ? firstCoords.y : secondCoords.y; bottomRight.x = firstCoords.x > secondCoords.x ? firstCoords.x : secondCoords.x; bottomRight.y = firstCoords.y > secondCoords.y ? firstCoords.y : secondCoords.y; }
public ActionBoxTextView(FloatCoords loc) { Coords = loc; SpriteFont = "BuildingTimer"; Text = "Raichu"; Colour = Color.LightGreen; ZIndex = 501; }
/// <summary> /// <para>Returns all of the coords' neighbours, diagonal and not diagonal</para> /// <para>r | r | r</para> /// <para>r | c | r</para> /// <para>r | r | r</para> /// </summary> /// <returns>Array of coords' neighbouring coords</returns> public FloatCoords[] GetNeighbours() { FloatCoords[] returnArray = new FloatCoords[8]; GetNonDiagonalNeighbours().CopyTo(returnArray, 0); GetDiagonalNeighbours().CopyTo(returnArray, 4); return(returnArray); }
public ActionBoxView(FloatCoords loc) { Coords = loc; Width = 2; Height = 1; Texture = "unittrainbalkje"; Colour = Color.White; ZIndex = 500; }
//constructor public Selection_View() { Coords = new FloatCoords() { x = -1, y = -1 }; Width = 0; Height = 0; Texture = "PurpleLine"; Colour = Color.White; ZIndex = 1000; }
/// <summary> /// Returns all of the coords' diagonal neighbours, diagonal and not /// r | | r /// | c | /// r | | r /// </summary> /// <returns></returns> public FloatCoords[] GetDiagonalNeighbours() { FloatCoords[] diagonalNeighbours = new FloatCoords[4] { NorthEastNeighbour, SouthEastNeighbour, SouthWestNeighbour, NorthWestNeighbour }; return(diagonalNeighbours); }
/// <summary> /// Returns all of the coords' diagonal neighbours, diagonal and not /// | r | /// r | c | r /// | r | /// </summary> /// <returns></returns> public FloatCoords[] GetNonDiagonalNeighbours() { FloatCoords[] horizontalNeighbours = new FloatCoords[4] { NorthNeighbour, EastNeighbour, SouthNeighbour, WestNeighbour }; return(horizontalNeighbours); }
// sets the weight-values of all the neighbours of a cell private Dictionary <Coords, CellWeightValues> CalculateNeighboursWeights(Coords currentCell, Coords targetCoords, LocationModel unit) { CoordsCalculator coordsCalculator = new CoordsCalculator((FloatCoords)currentCell); FloatCoords[] neighbours = new FloatCoords[8]; coordsCalculator.GetNeighbours().CopyTo(neighbours, 0); return((from neighbour in neighbours where worldController.GetCellFromCoords((Coords)neighbour) != null && !IsCellImpassable(worldController.GetCellFromCoords((Coords)neighbour).worldCellModel, unit) let cellWeights = CalculateCellWeights((Coords)neighbour, unit.Coords, targetCoords) select new KeyValuePair <Coords, CellWeightValues>((Coords)neighbour, cellWeights)).ToDictionary(pair => pair.Key, pair => pair.Value)); }
// give movecommand to all units in selection public void move(bool isQueueKeyPressed) { MouseState temp = Mouse.GetState(); Coords tempcoords = new Coords { x = temp.X, y = temp.Y }; FloatCoords target = WorldPositionCalculator.DrawCoordsToCellFloatCoords(WorldPositionCalculator.TransformWindowCoords(tempcoords, Game.Camera.GetViewMatrix()), Game.GameView.TileSize); foreach (IGameActionHolder unit in SelectedItems) { if (unit is IMoveable moveable) { moveable.MoveTo(target, isQueueKeyPressed); } } }
public void Update(object sender, OnTickEventArgs eventArgs) { if (!Waypoints.Any()) { return; } float speed = LocationModel.Parent.UnitModel.Speed; if (DistanceCalculator.DiagonalDistance(Waypoints.Peek(), LocationModel.FloatCoords) < speed) { // Arrived near destination LocationModel.FloatCoords = Waypoints.Dequeue(); if (!Waypoints.Any()) { MoveComplete?.Invoke(this, new EventArgsWithPayload <FloatCoords>(LocationModel.FloatCoords)); } return; } float xDifference = (float)DistanceCalculator.CalcDistance(LocationModel.FloatCoords.x, Waypoints.Peek().x); float yDifference = (float)DistanceCalculator.CalcDistance(LocationModel.FloatCoords.y, Waypoints.Peek().y); // calculate new coords float diagonalDifference = (float)DistanceCalculator.Pythagoras(xDifference, yDifference); float v = diagonalDifference / speed; FloatCoords difference = new FloatCoords { x = xDifference / v, y = yDifference / v }; difference.x = Waypoints.Peek().x < LocationModel.FloatCoords.x ? -difference.x : difference.x; difference.y = Waypoints.Peek().y < LocationModel.FloatCoords.y ? -difference.y : difference.y; LocationModel.FloatCoords = new FloatCoords() { x = LocationModel.FloatCoords.x + difference.x, y = LocationModel.FloatCoords.y + difference.y }; }
public void Test_ShouldGiveChunkCoords_WhenGivenCellCoords(int tileX, int tileY, int expectedChunkX, int expectedChunkY) { // Arrange FloatCoords cellCoords = new FloatCoords { x = tileX, y = tileY }; // Act Coords actual = WorldPositionCalculator.ChunkCoordsOfCellCoords(cellCoords); // Assert Coords expectedCoords = new Coords { x = expectedChunkX, y = expectedChunkY }; Assert.AreEqual(expectedCoords, actual); }
public void Update(object sender, OnTickEventArgs eventArgs) { if (!active) { return; } MouseState temp = Mouse.GetState(); Coords tempcoords = new Coords { x = temp.X, y = temp.Y }; // saves current mouse location FloatCoords SecondPoint = WorldPositionCalculator.DrawCoordsToCellFloatCoords(WorldPositionCalculator.TransformWindowCoords(tempcoords, Game.Camera.GetViewMatrix()), Game.GameView.TileSize); //standardices coords to topleft and bottomright SetCoords(firstPoint, SecondPoint); RegisterDrawBox(); }
/// <summary> /// sets everything within viewrange from the coords to the specified viewmode /// </summary> /// <param name="mode"></param> /// <param name="viewrange"></param> /// <param name="coords"></param> public void UpdateViewMode(ViewMode mode, int viewrange, FloatCoords coords) { // loop from -viewrange to + viewrange for (int x = (viewrange) * -1; x <= viewrange; x++) { for (int y = (viewrange) * -1; y <= viewrange; y++) { // set coords relative to the given coords Coords tempcoords = (Coords) new FloatCoords { x = x + coords.x, y = y + coords.y }; // check if the coords are within viewrange if (!(DistanceCalculator.DiagonalDistance((FloatCoords)tempcoords, coords) < viewrange)) { continue; } // get the cell from the tempcoords WorldCellController cellController = worldController.GetCellFromCoords(tempcoords); // check if the cellcontroller exists if (cellController == null) { continue; } // set the viewmode cellController.ChangeViewMode(mode); // check if there is a building in the cell if (cellController.worldCellModel.BuildingOnTop == null) { continue; } // set viewmode of the building on the cell if (cellController.worldCellModel.BuildingOnTop.GetType() == typeof(BuildingController)) { ((BuildingController)cellController.worldCellModel.BuildingOnTop).BuildingView.ViewMode = mode; } // set viewmode of the ConstructingBuilding on the cell if (cellController.worldCellModel.BuildingOnTop.GetType() == typeof(ConstructingBuildingController)) { ((ConstructingBuildingController)cellController.worldCellModel.BuildingOnTop).ConstructingBuildingView.ViewMode = mode; } } } }
public void Test_ShouldReturnCorrectDistance_WhenGivenTwoPoints(int x1, int y1, int x2, int y2, double expectedDistance) { // Arrange FloatCoords floatCoords = new FloatCoords() { x = x1, y = y1 }; FloatCoords target = new FloatCoords() { x = x2, y = y2 }; CoordsCalculator coordsCalculator = new CoordsCalculator(floatCoords); // Act double actual = coordsCalculator.DistanceToFloatCoords(target); // Assert Assert.AreEqual(expectedDistance, actual); }
public void GuiOrMap(FloatCoords mouseCoords, MouseState mouseState, MouseButton activeButton) { List <IGuiViewImage> clickedGuiItems = (from item in game.GameModel.GuiItemList where mouseCoords.x >= item.Coords.x && mouseCoords.y >= item.Coords.y && mouseCoords.x <= item.Coords.x + item.Width && mouseCoords.y <= item.Coords.y + item.Height orderby item.ZIndex descending select item).ToList(); switch (activeButton) { case MouseButton.Left: switch (mouseState.LeftButton) { //TODO LeftButtonPressed?.Invoke() //TODO LeftButtonReleased?.Invoke() case ButtonState.Pressed: if (clickedGuiItems.Any()) { if (PreviousMouseState.LeftButton != ButtonState.Released) { return; } clickedGuiItems.First().Click(); return; } Selection.ButtonPressed(mouseCoords); break; case ButtonState.Released: game.MapActionSelector.Clear(); Selection.ButtonRelease(Keyboard.GetState().IsKeyDown(Keys.LeftShift)); break; } break; case MouseButton.Right: switch (mouseState.RightButton) { //TODO RightButtonPressed?.Invoke() //TODO RightButtonReleased?.Invoke() case ButtonState.Pressed: Selection.move(Keyboard.GetState().IsKeyDown(Keys.LeftShift)); break; case ButtonState.Released: { FloatCoords cellCoords = WorldPositionCalculator.DrawCoordsToCellFloatCoords((FloatCoords)WorldPositionCalculator.TransformWindowCoords((Coords)mouseCoords, game.Camera.GetViewMatrix()), game.GameView.TileSize); if (PreviousMouseState.RightButton == ButtonState.Pressed) { game.SelectedMapAction?.Execute(game.GameModel.World.GetCellFromCoords((Coords)cellCoords)); } break; } } break; } }
/// <summary> /// Calculates diagonal distance between two coordinates. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns>Positive distance</returns> public static double DiagonalDistance(FloatCoords a, FloatCoords b) => Pythagoras(CalcDistance(a.x, b.x), CalcDistance(a.y, b.y));
/// <summary> /// Calculates chunk-coords from cell-coords /// </summary> /// <param name="cellCoords">Cell-coords relative to center of the World</param> /// <returns>Chunk-coords relative to center of the World</returns> public static Coords ChunkCoordsOfCellCoords(FloatCoords cellCoords) => new Coords { x = (int)Math.Floor((double)cellCoords.x / WorldChunkModel.ChunkSize), y = (int)Math.Floor((double)cellCoords.y / WorldChunkModel.ChunkSize) };
public static FloatCoords DrawCoordsToCellFloatCoords(FloatCoords drawCoords, int tileSize) => new FloatCoords { x = drawCoords.x / tileSize - (drawCoords.x < 0 ? 1 : 0), y = drawCoords.y / tileSize - (drawCoords.y < 0 ? 1 : 0) };
/// <summary> /// returns a path to the target that avoids obstacles /// </summary> /// <param name="targetCoords">Target</param> /// <param name="unit">Model containing info about the unit's location</param> /// <returns>Path</returns> /// <exception cref="NoPathFoundException">Throws exception when no path found</exception> public List <FloatCoords> FindPath(FloatCoords targetCoords, LocationModel unit) { if (IsCellImpassable(worldController.GetCellFromCoords((Coords)targetCoords).worldCellModel, unit)) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } CoordsCalculator unitCoordsCalculator = new CoordsCalculator(unit.FloatCoords); CoordsCalculator targetCoordsCalculator = new CoordsCalculator(targetCoords); LinkedList <FloatCoords> currentPath = new LinkedList <FloatCoords>(); List <Coords> visitedCoords = new List <Coords>(); FloatCoords currentCoords = unit.FloatCoords; bool IsPreviousNode(Coords target) => currentPath.Last?.Previous != null && (Coords)currentPath.Last.Previous.Value == target; while ((Coords)currentCoords != (Coords)targetCoords) { Dictionary <Coords, CellWeightValues> currentNeighbours = CalculateNeighboursWeights((Coords)currentCoords, (Coords)targetCoords, unit); // Find most probable cell, // WHERE: // 1. NOT Cell has been visited and isn't the previous node List <FloatCoords> mostProbableCandidates = ( from KeyValuePair <Coords, CellWeightValues> pair in currentNeighbours where !(visitedCoords.Contains(pair.Key) && !IsPreviousNode(pair.Key)) && !IsDiagonalPathBlocked((Coords)currentCoords, pair.Key, unit) let cellWeightValues = pair.Value orderby cellWeightValues.Weight, cellWeightValues.AbsoluteDistanceToTarget select(FloatCoords) pair.Key).ToList(); if (!mostProbableCandidates.Any()) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } FloatCoords mostProbableCoords = mostProbableCandidates.First(); if (ENABLE_ANIMATION) { worldController.GetCellFromCoords((Coords)currentCoords).worldCellView.Colour = Color.Red; worldController.GetCellFromCoords((Coords)mostProbableCoords).worldCellView.Colour = Color.Blue; Thread.Sleep(ANIMATION_DELAY_MILLIS); } if (!visitedCoords.Contains((Coords)mostProbableCoords)) { visitedCoords.Add((Coords)mostProbableCoords); } // Add to list if mostProbableCoords: // 1. The path is empty // 2. OR the node isn't in the path AND it isn't too far away // Else, if mostProbableCoords is already known, move to that node if (!currentPath.Any() || !currentPath.Contains(mostProbableCoords) && !(unitCoordsCalculator.DistanceToFloatCoords(mostProbableCoords) > SearchLimit || targetCoordsCalculator.DistanceToFloatCoords(mostProbableCoords) > SearchLimit)) { currentPath.AddLast(mostProbableCoords); } else if (currentPath.Contains(mostProbableCoords)) { while ((Coords)currentPath.Last.Value != (Coords)mostProbableCoords) { currentPath.RemoveLast(); } } currentCoords = currentPath.Last.Value; } if (!currentPath.Any()) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } Queue <FloatCoords> route = ReduceWaypoints(currentPath.ToList(), unit); return(route.ToList()); }
/// <summary> /// Returns absolute distance between target and coords /// </summary> /// <param name="target">Target-coords</param> /// <returns>Absolute distance as double</returns> public double DistanceToFloatCoords(FloatCoords target) => DistanceCalculator.DiagonalDistance(coords, target);
/// <summary> /// Gets all coords of cells on a ray with destination /// </summary> /// <param name="destination">Ray's end node</param> /// <returns>List of coords the ray passes through</returns> public List <Coords> GetCoordsOnRayWith(FloatCoords destination) { void AddCellsBetweenVerticalPoints(double startPoint, double endPoint, int xCoord, ref List <Coords> outputList) { // Switch start- and endpoints if necessary if (startPoint > endPoint) { startPoint = endPoint + startPoint; endPoint = Math.Ceiling(startPoint - endPoint); startPoint = Math.Floor(startPoint - endPoint); } for (int i = (int)startPoint - 1; i <= endPoint + 1; i++) { Coords currentPoint = new Coords() { x = xCoord, y = i }; CoordsCalculator coordsCalculator = new CoordsCalculator((FloatCoords)currentPoint); List <Coords> cells = new List <Coords> { currentPoint }; cells.AddRange(coordsCalculator.GetNeighbours().Select(neighbour => (Coords)neighbour)); foreach (Coords cell in cells) { if (outputList.Contains(cell)) { continue; } outputList.Add(cell); } } } List <Coords> coordsOnRay = new List <Coords>(); FloatCoords startCoords = this.coords; // Switch start- and endpoints if necessary if (startCoords.x > destination.x) { FloatCoords x = startCoords; startCoords = destination; destination = x; } double directionCoefficient = (double)destination.x > (double)startCoords.x ? ((double)destination.y - startCoords.y) / ((double)destination.x - startCoords.x) : (double)destination.y - startCoords.y; FloatCoords previousCoords; FloatCoords currentCoords = startCoords; while (currentCoords.x <= destination.x) { previousCoords = currentCoords; currentCoords.x++; currentCoords.y += (float)directionCoefficient; AddCellsBetweenVerticalPoints(previousCoords.y, currentCoords.y, (int)previousCoords.x, ref coordsOnRay); } return(coordsOnRay); }
public CoordsCalculator(FloatCoords worldCoordsController) { coords = worldCoordsController; }
public GameActionTabItem(IGameAction gameAction, FloatCoords location) : base(location, gameAction.IconValues) { this.GameAction = gameAction; }