/// <summary> /// Compute the projection of a point onto the line determined /// by this line segment. /// Note that the projected point may lie outside the line segment. /// If this is the case, the projection factor will lie outside the range [0.0, 1.0]. /// </summary> /// <param name="p"></param> /// <returns></returns> public static Point Project(Point p, Point LineSegFrom, Point LineSegTo) { if (p.Equals(LineSegFrom) || p.Equals(LineSegTo)) return new Point(p.X, p.Y); var r = ProjectionFactor(p, LineSegFrom, LineSegTo); Point coord = new Point (LineSegFrom.X + r * (LineSegTo.X - LineSegFrom.X), LineSegFrom.Y + r * (LineSegTo.Y - LineSegFrom.Y) ); return coord; }
public void EqualsThrowsInvalidCastExceptionBugFix() { Point point = new Point(1.0, 1.0); Coordinate coordinate = new Coordinate(-1.0, -1.0); bool condition = point.Equals(coordinate); Assert.IsFalse(condition); }
public LineSegment(Point start, Point end) { if (start.Equals(end)) { throw new ArgumentException("lenght can not be zero"); } this.start = start; this.end = end; }
static void Main() { Point p1 = new Point(5, 7); p1.Print(); Printer pr = p1; // box; pr.Print(); Point p2 = new Point(5, 7); Console.WriteLine(p1.Equals(p2)); }
public void Equals() { var p1 = new Point(1, 2); var p2 = new Point(3, 4); Assert.AreNotEqual(p1, p2); Assert.AreEqual(p1, new Point(1, 2)); Assert.IsTrue(p1 == new Point(1, 2)); Assert.IsTrue(p1 != p2); Assert.IsTrue(p1.Equals((object)new Point(1, 2))); }
public bool isAdjacentTile(int x, int y) { bool val = false; foreach (Zone z in adjacentAreas) { Point p = z.convertToLocal(x, y); if (!p.Equals(new Point(-1, -1))) { //also check whether we can actually enter the tile if (z.tile[p.X, p.Y].isClear()) { val = true; break; } } } return(val); }
public virtual void SetPosition(Point p) { if (p == null) { return; } Point prev = this.Position; _Position = p; if (prev.Equals(_Position)) { return; } this.ParentLayer?.UpdateControlPosition(this); this.RaisePositionChangeEvent(new QGPositionChangeEventArgs(prev, _Position)); }
public CollisionType CheckCollision(Point foodPoint) { Point movesTo; switch (CurrentDirection) { case Direction.Up: { movesTo = new Point(Head.X, Head.Y - 10); break; } case Direction.Down: { movesTo = new Point(Head.X, Head.Y + 10); break; } case Direction.Left: { movesTo = new Point(Head.X - 10, Head.Y); break; } case Direction.Right: { movesTo = new Point(Head.X + 10, Head.Y); break; } default: return(CollisionType.NoCollision); } if (Body.Contains(movesTo)) { return(CollisionType.WithBody); } if (foodPoint.Equals(movesTo)) { return(CollisionType.WithFood); } return(CollisionType.NoCollision); }
public void principal() { var punteo = 0; var velocidad = 100; //modificar estos valores y ver qué pasa var posiciónComida = Point.Empty; var tamañoPantalla = new Size(60, 20); var culebrita = new Bicola(); var longitudCulebra = 3; //modificar estos valores y ver qué pasa var posiciónActual = new Point(0, 9); //modificar estos valores y ver qué pasa culebrita.insertar(posiciónActual); var dirección = Direction.Derecha; //modificar estos valores y ver qué pasa DibujaPantalla(tamañoPantalla); MuestraPunteo(punteo); while (MoverLaCulebrita(culebrita, posiciónActual, longitudCulebra, tamañoPantalla)) { Thread.Sleep(velocidad); dirección = ObtieneDireccion(dirección); posiciónActual = ObtieneSiguienteDireccion(dirección, posiciónActual); if (posiciónActual.Equals(posiciónComida)) { posiciónComida = Point.Empty; longitudCulebra++; //modificar estos valores y ver qué pasa punteo += 10; //modificar estos valores y ver qué pasa MuestraPunteo(punteo); Console.Beep(1000, 200); } if (posiciónComida == Point.Empty) //entender qué hace esta linea { posiciónComida = MostrarComida(tamañoPantalla, culebrita); } } Console.ResetColor(); Console.SetCursorPosition(tamañoPantalla.Width / 2 - 4, tamañoPantalla.Height / 2); Console.Write("Fin del Juego"); Thread.Sleep(2000); Console.ReadKey(); }
public static double FindAngle(this Point s, Point e) { if (s.Equals(e)) { return(0d); } Point r = new Point(e.X, s.Y); double sr = s.FindLength(r); double re = r.FindLength(e); double es = e.FindLength(s); double ang = Math.Asin(re / es); if (double.IsNaN(ang)) { ang = 0; } ang = ang * 180 / Math.PI; if (s.X < e.X) { if (s.Y < e.Y) { } else { ang = 360 - ang; } } else { if (s.Y < e.Y) { ang = 180 - ang; } else { ang = 180 + ang; } } return(ang); }
/// <summary> /// Perform paint of the html in the control. /// </summary> protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); if (_htmlContainer != null) { e.Graphics.TextRenderingHint = _textRenderingHint; e.Graphics.SetClip(ClientRectangle); _htmlContainer.Location = new PointF(Padding.Left, Padding.Top); _htmlContainer.ScrollOffset = AutoScrollPosition; _htmlContainer.PerformPaint(e.Graphics); if (!_lastScrollOffset.Equals(_htmlContainer.ScrollOffset)) { _lastScrollOffset = _htmlContainer.ScrollOffset; InvokeMouseMove(); } } }
public void UTShift() { Line RO = new Line(); UTDraw(RO); Point p = new Point(10, 10); Point p1 = new Point(5, 8); RO.Hit_testing(p); RO.Shift(p1); if (p1.Equals(RO.LeftTop)) { Assert.AreEqual(p1, RO.LeftTop); } else { Assert.AreEqual(p1, RO.RightBottom); } }
// JUEGO SNAKE static void Main2() { var score = 0; var speed = 100; var foodPosition = Point.Empty; var screenSize = new Size(60, 20); var snake = new Queue <Point>(); var snakeLength = 3; var currentPosition = new Point(0, 9); snake.Enqueue(currentPosition); var direction = Direction.Right; DrawScreen(screenSize); ShowScore(score); while (MoveSnake(snake, currentPosition, snakeLength, screenSize)) { Thread.Sleep(speed); direction = GetDirection(direction); currentPosition = GetNextPosition(direction, currentPosition); if (currentPosition.Equals(foodPosition)) { foodPosition = Point.Empty; snakeLength++; score += 10; ShowScore(score); } if (foodPosition == Point.Empty) { foodPosition = ShowFood(screenSize, snake); } } Console.ResetColor(); Console.SetCursorPosition(screenSize.Width / 2 - 4, screenSize.Height / 2); Console.Write("Perdiste :( "); Thread.Sleep(2000); Console.ReadKey(); }
public static IEnumerable <Point> MakeIncedentCells(Field field, Point point) { for (var dy = -1; dy <= 1; dy++) { for (var dx = -1; dx <= 1; dx++) { var newPoint = new Point(point.X + dx, point.Y + dy); if ((dx != 0 && dy != 0) || newPoint.X < 0 || newPoint.Y < 0 || newPoint.X >= field.Width || newPoint.Y >= field.Height || point.Equals(newPoint)) { continue; } yield return(newPoint); } } }
public Triangle(Point pointA, Point pointB, Point pointC) { if (pointA.Equals(pointB)) { throw new ArgumentException("A same as B"); } if (pointB.Equals(pointC)) { throw new ArgumentException("B same as C"); } if (pointC.Equals(pointA)) { throw new ArgumentException("C same as A"); } VertexAB = new Vertex(pointA, pointB); VertexBC = new Vertex(pointB, pointC); VertexCA = new Vertex(pointC, pointA); }
public void TestMinMax2() { Matrix <Single> matrix = new Matrix <Single>(10, 10); matrix.SetValue(5); matrix[5, 5] = 10; matrix[3, 3] = 0; double minVal = 5; double maxVal = 5; Point minLoc = new Point(); Point maxLoc = new Point(); matrix.MinMax(out minVal, out maxVal, out minLoc, out maxLoc); EmguAssert.IsTrue(minVal == 0); EmguAssert.IsTrue(maxVal == 10); EmguAssert.IsTrue(minLoc.Equals(new Point(3, 3))); EmguAssert.IsTrue(maxLoc.Equals(new Point(5, 5))); }
public void EndMove(Point p) { if (_guiStartPosition.Equals(p)) { ViewModel.Model.Selected = true; } if (!ViewModel.Model.Moving) { return; } Presenter.BackgoundGrid.Children.Remove(_anchorsCanvas); _anchorsCanvas = null; ViewModel.Model.Moving = false; ViewModel.Model.Config.Compact(); //Todo : Plugin.ActivateConfig(); }
public static void Main() { const int TimesToCompare = 10000000; var stopwatch = Stopwatch.StartNew(); var point1 = new Point { X = 1, Y = 2 }; var point2 = new Point { X = 1, Y = 2 }; for (var i = 0; i < TimesToCompare; i++) { point1.Equals(point2); } Console.WriteLine("Point with value members: {0}", stopwatch.Elapsed); stopwatch = Stopwatch.StartNew(); var pointWithName1 = new PointWithName { X = 1, Y = 2, Name = "Point with name 1" }; var pointWithName2 = new PointWithName { X = 1, Y = 2, Name = "Point with name 2" }; for (var i = 0; i < TimesToCompare; i++) { pointWithName1.Equals(pointWithName2); } Console.WriteLine("Point with reference member: {0}", stopwatch.Elapsed); stopwatch = Stopwatch.StartNew(); var pointWithNameAndEquals1 = new PointWithNameAndEquals { X = 1, Y = 2, Name = "Point with name and Equals() 1" }; var pointWithNameAndEquals2 = new PointWithNameAndEquals { X = 1, Y = 2, Name = "Point with name and Equals() 2" }; for (var i = 0; i < TimesToCompare; i++) { pointWithNameAndEquals1.Equals(pointWithNameAndEquals2); } Console.WriteLine("Point with reference member and equals: {0}", stopwatch.Elapsed); }
public Line(Point _pointStart, Point _pointEnd, Line lastLine = null, int?offsetPixelForOuterLine = null) { if (_pointStart == null) { throw new ArgumentNullException(nameof(_pointStart)); } if (_pointEnd == null) { throw new ArgumentNullException(nameof(_pointEnd)); } if (_pointStart.Equals(_pointEnd)) { throw new NotSupportedException($"{nameof(_pointStart)} and {nameof(_pointEnd)} must differ!"); } PointStart = _pointStart; PointEnd = _pointEnd; if (offsetPixelForOuterLine != null && offsetPixelForOuterLine > 0) { //generate points of offseted line var x1p = _pointStart.X + offsetPixelForOuterLine * (_pointEnd.Y - _pointStart.Y) / Length; var x2p = _pointEnd.X + offsetPixelForOuterLine * (_pointEnd.Y - _pointStart.Y) / Length; var y1p = _pointStart.Y + offsetPixelForOuterLine * (_pointStart.X - _pointEnd.X) / Length; var y2p = _pointEnd.Y + offsetPixelForOuterLine * (_pointStart.X - _pointEnd.X) / Length; Point outerLineStart = new Point((int)(x1p ?? 0), (int)(y1p ?? 0)); Point outerLineEnd = new Point((int)(x2p ?? 0), (int)(y2p ?? 0)); if (lastLine != null && lastLine.OuterLine != null) { outerLineStart = lastLine.OuterLine.PointEnd; } if (outerLineStart != outerLineEnd) { OuterLine = new Line(outerLineStart, outerLineEnd); OuterLine.RelatedPoint = _pointStart; } } }
protected void CalculateMerged() { if (ComboBoxAreas.SelectedItem is not AreaDto area) { return; } bool calcScore = false; Point offset = Offset; if (!area.Offset.HasValue || !offset.Equals(area.Offset)) { calcScore = true; } AreaDto mergeArea = new(area) { Type = Enum.AreaType.Preview, Path = String.Empty, Directory = String.Empty }; foreach (var sourceTile in SourceArea.TileList) { TileDto tile = new(sourceTile); Point coord = tile.Coordinate; coord.Offset(offset); tile.Coordinate = coord; if (area.Tiles.ContainsKey(tile.Key)) { var orgTile = area.Tiles[tile.Key]; if (!calcScore && orgTile.Score.HasValue) { tile.Score = orgTile.Score; } else { tile.Score = TileComparator.Compare(sourceTile, orgTile); } } mergeArea.AddTile(tile); } CanvasMerge.SetArea(mergeArea); CanvasMerge.CenteredTile = offset; }
// Get the neighbours of a given node. Paving decides whether or not to include non-walkable tiles as neighbours. private List <Point> get_neighbours(Point node, Point destination, float[,] map_data, bool paving) { var neighbours = new List <Point>(); if (node.x != 0) // get upper neighbour { var n_point = new Point(node.x - 1, node.y); var neighbour_value = map_data[node.x - 1, node.y]; if ((is_walkable(neighbour_value) || n_point.Equals(destination) || (paving && neighbour_value == 0.0f))) { neighbours.Add(n_point); } } if (node.x != map_height - 1) // get bottom neighbour { var n_point = new Point(node.x + 1, node.y); var neighbour_value = map_data[node.x + 1, node.y]; if ((is_walkable(neighbour_value) || n_point.Equals(destination) || (paving && neighbour_value == 0.0f))) { neighbours.Add(n_point); } } if (node.y != 0) // get left neighbour { var n_point = new Point(node.x, node.y - 1); var neighbour_value = map_data[node.x, node.y - 1]; if ((is_walkable(neighbour_value) || n_point.Equals(destination) || (paving && neighbour_value == 0.0f))) { neighbours.Add(n_point); } } if (node.y != map_width - 1) // get right neighbour { var n_point = new Point(node.x, node.y + 1); var neighbour_value = map_data[node.x, node.y + 1]; if ((is_walkable(neighbour_value) || n_point.Equals(destination) || (paving && neighbour_value == 0.0f))) { neighbours.Add(n_point); } } return(neighbours); }
public static SearchResult AStarSearch(Grid grid, Point startPos, Point endPos) { List <Point> openSet = new List <Point>(); Dictionary <Point, float> costSoFar = new Dictionary <Point, float>(); Dictionary <Point, float> priorityMap = new Dictionary <Point, float>(); Dictionary <Point, Point> cameFrom = new Dictionary <Point, Point>(); openSet.Add(startPos); priorityMap.Add(startPos, 0); costSoFar.Add(startPos, 0); cameFrom.Add(startPos, null); while (openSet.Count > 0) { Point current = GetClosestVertex(openSet, priorityMap); openSet.Remove(current); if (current.Equals(endPos)) { return(new SearchResult { Path = GeneratePath(cameFrom, current), Visited = new List <Point>(cameFrom.Keys) }); } foreach (Point neighbour in grid.GetAdjacentCells(current)) { float newCost = costSoFar[current] + grid.GetCostOfEnteringCell(neighbour); if (!costSoFar.ContainsKey(neighbour) || newCost < costSoFar[neighbour]) { costSoFar[neighbour] = newCost; float priority = newCost + Heuristic(endPos, neighbour); openSet.Add(neighbour); priorityMap[neighbour] = priority; cameFrom[neighbour] = current; } } } return(new SearchResult()); }
private void Waypoint_MouseUp(object sender, MouseEventArgs e) { PictureBox pb = (PictureBox)sender; Waypoint wp = map.GetWaypoint(pb.Location); this.Cursor = Cursors.Arrow; if (e.Button == MouseButtons.Left && mapBoxLoc.Equals(pb.Parent.Location)) { var frm = new WaypointDetails(wp); frm.StartPosition = FormStartPosition.Manual; frm.Location = new Point(Cursor.Position.X, Cursor.Position.Y); frm.ShowDialog(this); } else if (e.Button == MouseButtons.Right) { if (btnNoIsland.Checked && btnNoMarker.Checked) { DeleteWaypoint(pb); } else if (btnStamp.Checked) { AddStamp(new Point(pb.Location.X + e.Location.X, pb.Location.Y + e.Location.Y)); } else if (btnTwoByTwo.Checked) { return; } else { IslandType island = ActiveIsland(); MarkerType marker = ActiveMarker(); if (wp.Island != island || wp.Marker != marker) { wp.Island = island; wp.Marker = marker; pb.Image = wp.GetImage(); } } } }
private void Draw(Bitmap image, int x, int y) { for (int i = 0; i < image.Height; i++) { int c = 0; for (int j = 0; j < image.Width; j++) { Color oc = image.GetPixel(j, i); uint xx = GetActiveProcess(); if ((_lastPoint.X != -1 && !_lastPoint.Equals(MousePosition)) || _pid != xx) { return; } if ((int)((oc.R * 0.3) + (oc.G * 0.59) + (oc.B * 0.11)) < 110) { if (j == image.Width - 1 && c > 0) { int x1 = x + j; int y1 = y + i; LeftMouseClick(x1 - c, y1, x1, y1); c = 0; Thread.Sleep(10); } else { c++; } } else if (c > 0) { int x1 = x + j - 1; int y1 = y + i - 1; LeftMouseClick(x1 - c, y1, x1, y1); c = 0; Thread.Sleep(10); } } } }
public void DifferentPointsWithDifferentHashcode() { Point a = new Point(0, 0); Point b = new Point(0, 5); Point c = new Point(5, 0); Point d = new Point(5, 5); Assert.AreNotEqual(a.GetHashCode(), b.GetHashCode()); Assert.AreNotEqual(a.GetHashCode(), c.GetHashCode()); Assert.AreNotEqual(a.GetHashCode(), d.GetHashCode()); Assert.AreNotEqual(b.GetHashCode(), c.GetHashCode()); Assert.AreNotEqual(b.GetHashCode(), d.GetHashCode()); Assert.AreNotEqual(c.GetHashCode(), d.GetHashCode()); Assert.IsFalse(a.Equals(b)); Assert.IsFalse(a.Equals(c)); Assert.IsFalse(a.Equals(d)); Assert.IsFalse(b.Equals(c)); Assert.IsFalse(b.Equals(d)); Assert.IsFalse(c.Equals(d)); }
public void dropPiece() { if (moving == null) { return; } Debug.Log("Dropado"); FindObjectOfType <AudioManager>().Play("Swap"); //Audio Queue if (!newIndex.Equals(moving.index)) { game.flipPieces(moving.index, newIndex, true); } else { game.resertPiece(moving); } moving = null; }
/// <summary> /// Handles the MouseFilterMove event of the mudmFilter control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e"> /// The <see cref="MouseFilterEventArgs" /> instance containing the event data. /// </param> private void mouseFilter_MouseFilterMove(object sender, MouseFilterEventArgs e) { if (e.Button == MouseButtons.Left) { if (!_mouseStartPoint.Equals(Point.Empty)) { int dx = (e.X - _mouseStartPoint.X); int dy = (e.Y - _mouseStartPoint.Y); if (_doTouchScroll) { yourScrollablePanel.AutoScrollPosition = new Point(_yourScrollablePanelStartPoint.X - dx, _yourScrollablePanelStartPoint.Y - dy); } else if (Math.Abs(dx) > 10 || Math.Abs(dy) > 10) { _doTouchScroll = true; } } } }
public void DropPiece() { if (moving == null) { return; } //Debug.Log("Dropped"); if (!newIndex.Equals(moving.index)) { game.FlipPieces(moving.index, newIndex, true); } else { game.ResetPiece(moving); } moving = null; }
public void DropPiece() { if (moving == null) { return; } Debug.Log("Dropped"); if (!newIndex.Equals(moving.index)) { // Flip the pieces around in the game board game.FlipPieces(moving.index, newIndex, true); } else { // Reset the place back to the original spot game.ResetPiece(moving); } moving = null; }
private void printScaffold(Robot robot) { var(low, high) = getBounds(robot.scaffold); for (var row = low.y; row <= high.y; row += 1) { for (var col = low.x; col <= high.x; col += 1) { var pt = new Point(col, row); var ch = robot.scaffold.ContainsKey(pt) ? robot.scaffold[pt] : Cell.SPACE; if (pt.Equals(robot.loc)) { ch = (char)robot.dir; } System.Console.Write((char)ch); } System.Console.WriteLine(); } }
public void SetVirtualBoundsNew(Point sp, Point dp) { if (sp.Equals(dp)) { dp += new Size(Zoom, Zoom); } //sp.X = Convert.ToInt32(sp.X); //sp.Y = Convert.ToInt32(sp.Y); //dp.X = Convert.ToInt32(dp.X); //dp.Y = Convert.ToInt32(dp.Y); CreateObjects(sp, dp); Rectangle adjRect = Rectangle.Round(areaPath.GetBounds()); adjRect = ExtendBoundsByZoom(adjRect, Zoom); _virtualBounds = adjRect; }
/// <summary> /// Popup上でマウスを移動 /// </summary> /// <param name="sender">Popup</param> /// <param name="e">マウスイベントデータ</param> private void OnMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { var position = MousePosition.Get(); if (_MousePoint.Equals(_InitializePoint)) { _MousePoint = position; } var point = _MousePoint - position; if (sender is Popup popup) { popup.HorizontalOffset = -10d - point.X; popup.VerticalOffset = -10d - point.Y; } } }
bool IMessageFilter.PreFilterMessage(ref Message m) { switch (m.Msg) { case WM_MOUSEMOVE: // you WILL get phantom WM_MOUSEMOVE messages, when the mouse has NOT moved! Point curPoint = Cursor.Position; if (!curPoint.Equals(lastPoint)) { lastPoint = curPoint; if (MouseMoved != null) { MouseMoved(); } tmr.Stop(); tmr.Start(); } break; } return(false); // handle messages normally }
private void UpdateRect() { if (_bendDown == 0 || !groundPosition.Equals(Position)) { Rect[0] = new Rectangle(new Point(Position.X + 40, Position.Y), new Size(40, 28)); Rect[1] = new Rectangle(new Point(Position.X + 6, Position.Y + 29), new Size(54, 32)); Rect[2] = new Rectangle(new Point(Position.X + 24, Position.Y + 62), new Size(26, 24)); } else if (_bendDown == 1 && groundPosition.Equals(Position)) { Rect[0] = new Rectangle(new Point(Position.X, Position.Y + 42), new Size(109, 28)); Rect[1] = new Rectangle(new Point(Position.X, Position.Y + 42), new Size(54, 32)); Rect[2] = new Rectangle(new Point(Position.X + 24, Position.Y + 62), new Size(26, 24)); } }
public static SearchResult BreadthFirstSearch(Grid grid, Point startPos, Point endPos) { if (startPos.Equals(endPos)) { return(new SearchResult()); } Dictionary <Point, Point> visitedMap = new Dictionary <Point, Point>(); Queue <Point> queue = new Queue <Point>(); queue.Enqueue(startPos); while (queue.Count > 0) { Point node = queue.Dequeue(); foreach (Point adj in grid.GetAdjacentCells(node)) { if (!visitedMap.ContainsKey(adj)) { visitedMap.Add(adj, node); queue.Enqueue(adj); if (adj.Equals(endPos)) { return(new SearchResult { Path = GeneratePath(visitedMap, adj), Visited = new List <Point>(visitedMap.Keys) }); } } } if (!visitedMap.ContainsKey(node)) { visitedMap.Add(node, null); } } return(new SearchResult()); }
public static List <Point> AStarSearch(Grid grid, Point startPosition, Point endPosition, bool isAgent = false) // get path betweeen 2 points in grid { List <Point> path = new List <Point>(); List <Point> positionsTocheck = new List <Point>(); Dictionary <Point, float> costDictionary = new Dictionary <Point, float>(); Dictionary <Point, float> priorityDictionary = new Dictionary <Point, float>(); Dictionary <Point, Point> parentsDictionary = new Dictionary <Point, Point>(); positionsTocheck.Add(startPosition); priorityDictionary.Add(startPosition, 0); costDictionary.Add(startPosition, 0); parentsDictionary.Add(startPosition, null); while (positionsTocheck.Count > 0) { Point current = GetClosestVertex(positionsTocheck, priorityDictionary); // find closest pos from the distanceMap positionsTocheck.Remove(current); if (current.Equals(endPosition)) { path = GeneratePath(parentsDictionary, current); return(path); } foreach (Point neighbour in grid.GetAdjacentCells(current, isAgent)) // loop though surround pos { float newCost = costDictionary[current] + grid.GetCostOfEnteringCell(neighbour); if (!costDictionary.ContainsKey(neighbour) || newCost < costDictionary[neighbour]) { costDictionary[neighbour] = newCost; float priority = newCost + ManhattanDiscance(endPosition, neighbour); positionsTocheck.Add(neighbour); priorityDictionary[neighbour] = priority; parentsDictionary[neighbour] = current; } } } return(path); }
/// <summary> /// Computes the distance from a point p to a line segment AB. /// Note: NON-ROBUST! /// </summary> /// <param name="p">The point to compute the distance for.</param> /// <param name="A">One point of the line.</param> /// <param name="B">Another point of the line (must be different to A).</param> /// <returns> The distance from p to line segment AB.</returns> public static double DistancePointLine(Point p, Point A, Point B) { // if start == end, then use pt distance if (A.Equals(B)) return p.Distance(A); // otherwise use comp.graphics.algorithms Frequently Asked Questions method /*(1) AC dot AB r = --------- ||AB||^2 r has the following meaning: r=0 Point = A r=1 Point = B r<0 Point is on the backward extension of AB r>1 Point is on the forward extension of AB 0<r<1 Point is interior to AB */ double r = ((p.X - A.X) * (B.X - A.X) + (p.Y - A.Y) * (B.Y - A.Y)) / ((B.X - A.X) * (B.X - A.X) + (B.Y - A.Y) * (B.Y - A.Y)); if (r <= 0.0) return p.Distance(A); if (r >= 1.0) return p.Distance(B); /*(2) (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) s = ----------------------------- Curve^2 Then the distance from C to Point = |s|*Curve. */ double s = ((A.Y - p.Y) * (B.X - A.X) - (A.X - p.X) * (B.Y - A.Y)) / ((B.X - A.X) * (B.X - A.X) + (B.Y - A.Y) * (B.Y - A.Y)); return Math.Abs(s) * Math.Sqrt(((B.X - A.X) * (B.X - A.X) + (B.Y - A.Y) * (B.Y - A.Y))); }
public void EqualityTest(int x, int y) { Point p1 = new Point(x, y); Point p2 = new Point(x / 2 - 1, y / 2 - 1); Point p3 = new Point(x, y); Assert.True(p1 == p3); Assert.True(p1 != p2); Assert.True(p2 != p3); Assert.True(p1.Equals(p3)); Assert.False(p1.Equals(p2)); Assert.False(p2.Equals(p3)); Assert.Equal(p1.GetHashCode(), p3.GetHashCode()); }
private void ReplacePoints(Point p1, Point p2, Point midPoint) { // Replace points in front this.Front.ReplacePoints(p1, p2, midPoint); // Replace points in mesh // Add midpoint to output points this.Points.Add(midPoint); // Replace points in triangles foreach (Triangle triangle in this.Triangles) { for (int i = 0; i < 3; i++) { if (p1.Equals(triangle.Points[i])) triangle.Points[i] = midPoint; if (p2.Equals(triangle.Points[i])) triangle.Points[i] = midPoint; } } // Remove p1 and p2 this.Points.Remove(p1); this.Points.Remove(p2); }
/// <summary> /// Computes the distance from a line segment AB to a line segment CD. /// Note: NON-ROBUST! /// </summary> /// <param name="A">A point of one line.</param> /// <param name="B">The second point of the line (must be different to A).</param> /// <param name="C">One point of the line.</param> /// <param name="D">Another point of the line (must be different to A).</param> /// <returns>The distance from line segment AB to line segment CD.</returns> public static double DistanceLineLine(Point A, Point B, Point C, Point D) { // check for zero-length segments if (A.Equals(B)) return DistancePointLine(A, C, D); if (C.Equals(D)) return DistancePointLine(D, A, B); // AB and CD are line segments /* from comp.graphics.algo Solving the above for r and s yields (Ay-Cy)(Dx-Cx)-(Ax-Cx)(Dy-Cy) r = ----------------------------- (eqn 1) (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) (Ay-Cy)(Bx-Ax)-(Ax-Cx)(By-Ay) s = ----------------------------- (eqn 2) (Bx-Ax)(Dy-Cy)-(By-Ay)(Dx-Cx) Let Point be the position vector of the intersection point, then Point=A+r(B-A) or Px=Ax+r(Bx-Ax) Py=Ay+r(By-Ay) By examining the values of r & s, you can also determine some other limiting conditions: If 0<=r<=1 & 0<=s<=1, intersection exists r<0 or r>1 or s<0 or s>1 line segments do not intersect If the denominator in eqn 1 is zero, AB & CD are parallel If the numerator in eqn 1 is also zero, AB & CD are collinear. */ double r_top = (A.Y - C.Y) * (D.X - C.X) - (A.X - C.X) * (D.Y - C.Y); double r_bot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X); double s_top = (A.Y - C.Y) * (B.X - A.X) - (A.X - C.X) * (B.Y - A.Y); double s_bot = (B.X - A.X) * (D.Y - C.Y) - (B.Y - A.Y) * (D.X - C.X); if ((r_bot == 0) || (s_bot == 0)) return Math.Min(DistancePointLine(A, C, D), Math.Min(DistancePointLine(B, C, D), Math.Min(DistancePointLine(C, A, B), DistancePointLine(D, A, B)))); double s = s_top / s_bot; double r = r_top / r_bot; if ((r < 0) || (r > 1) || (s < 0) || (s > 1)) //no intersection return Math.Min(DistancePointLine(A, C, D), Math.Min(DistancePointLine(B, C, D), Math.Min(DistancePointLine(C, A, B), DistancePointLine(D, A, B)))); return 0.0; //intersection exists }
static void exemplo1() { Point p1 = new Point(5, 7); Point p2 = new Point(5, 7); Point p3 = new Point(9, 11); /* * Estamos a testar o Equals herdado de ValueType (cmp Igualdade entre campos). * !!!!!! Esta implementação de Euals recorre a Reflexão !!!! * Porque o Point não tem uma implementação de Equals. */ Console.WriteLine("{0}.Equals({1}) = {2}", p1, p2, p1.Equals(p2)); Console.WriteLine("{0}.Equals({1}) = {2}", p1, p3, p1.Equals(p3)); PointRef r1 = new PointRef(5, 7); PointRef r2 = new PointRef(5, 7); PointRef r3 = new PointRef(9, 11); /* * Estamos a testar o Equals redefinido em PointRef. */ Console.WriteLine("{0}.Equals({1}) = {2}", r1, r2, r1.Equals(r2)); Console.WriteLine("{0}.Equals({1}) = {2}", r1, r3, r1.Equals(r3)); Console.WriteLine("{0} == {1} = {2}", r1, r2, r1 == r2); Console.WriteLine("{0} == {1} = {2}", r1, r3, r1 == r3); Console.WriteLine("{0} == {1} = {2}", r1, r2, Object.ReferenceEquals(r1, r2)); Console.WriteLine("{0} == {1} = {2}", r1, r3, Object.ReferenceEquals(r1, r3)); }
public void IntersectionAll() { IList results = session.CreateCriteria(typeof(County)) .SetProjection(SpatialProjections.Intersection("Boundaries")) .List(); Assert.AreEqual(1, results.Count); IGeometry aggregated = (IGeometry)results[0]; IGeometry expected = new Point(2, 1); Assert.IsTrue(expected.Equals(aggregated)); }
public void TestDefaultEqual() { var pnt1 = new Point(1, 2); var pnt2 = new Point(1, 2); Assert.AreEqual(pnt1, pnt2); Assert.IsTrue(pnt1.Equals(pnt2)); // Assert.IsTrue(pnt1 == pnt2);// chekanote: "==" cannot be applied var pnt3 = new Point(100, 200); Assert.AreNotEqual(pnt1, pnt3); Assert.IsFalse(pnt1.Equals(pnt3)); }
public void Point_Equals_compares_two_Points_successfully() { var m1 = new Point(1.0f, 1.2f, 1.9f); var m2 = new Point(1.0f, 1.2f, 1.9f); bool eqeq = m1.Equals(m2); Assert.IsTrue(eqeq); }
/// <summary> /// Converts a point to SGF move format (e.g. 2,3 to "cd"). /// </summary> /// <param name="pnt">The coordinates.</param> /// <returns>The point in SGF format.</returns> public static string ConvertToSGF(Point pnt) { if (pnt.Equals(Game.PassMove)) return ""; return ConvertToSGF(pnt.x, pnt.y); }
public void Point_Equals_returns_false_given_non_material() { var p = new Point(1.0f, 1.2f, 1.9f); var m = new Material() { Colour = System.Drawing.Color.Green, Reflectance = 0.3f, SpecularPower = 50, SpecularTerm = 1.2f }; bool eqeq = p.Equals(m); Assert.IsFalse(eqeq); }
private static bool notSeen(Point start, List<Path> seenPaths, Point dest) { if (start.Equals(dest)) { return false; } foreach (Path p in seenPaths) { Point pd = p.destination(); if (pd.Equals(dest)) { return false; } } return true; }
/// <summary> /// The recursive pathfinding-method. /// </summary> /// <param name="targetPoint">The target point.</param> /// <param name="currentPoint">The current point in the grid.</param> /// <param name="playerPosition">The position of the player in the grid.</param> /// <param name="way"></param> /// <param name="shortestWayLength">The length of the best found path to the target.</param> /// <param name="failedTriesToBeatPath"></param> /// <param name="maximumTries">The maximum amount of tries the algorithm has to beat the best found path.</param> /// <returns></returns> public List<Point> CalculateShortestWayToTarget(Point targetPoint, Point currentPoint, Point playerPosition, List<Point> way, ref int shortestWayLength, ref int failedTriesToBeatPath, int maximumTries, ref int recursionStep) { recursionStep++; //do not add the current point if it equals the player's position if (!playerPosition.Equals(currentPoint)) { way.Add(currentPoint); } //returns an empty list if the current way is already longer than the best found way. //True if no tries are left. //True if the recursion step is too high --> emergency exit if (recursionStep > 150 || failedTriesToBeatPath >= maximumTries || (shortestWayLength > -1 && way.Count > shortestWayLength)) { failedTriesToBeatPath++; return new List<Point>(); } //true if the current point equals the target point or if the target point is unreachable. if (currentPoint.Equals(targetPoint) || (!IsValidPosition(targetPoint) && ArePointsNeighbors(currentPoint, targetPoint)) || GetValidNeighborPoints(targetPoint).Count == 0) { //returns the way and sets the shortest way length if this way is shorter than the currently best way if (shortestWayLength == -1 || way.Count < shortestWayLength) { shortestWayLength = way.Count; List<Point> pointList = new List<Point>(); pointList.Add(currentPoint); return pointList; } else { failedTriesToBeatPath++; return new List<Point>(); } } else { //get current point's neighbors List<Point> neighbors = GetValidNeighborPoints(currentPoint); Point nearestPoint = new Point(); List<Point> bestWaypoints = new List<Point>(); List<Point> newWaypoints = new List<Point>(); //test all directions while(neighbors.Count > 0) { nearestPoint = GetNearestPointToTarget(neighbors, targetPoint); if (!way.Contains(nearestPoint)) { newWaypoints = CalculateShortestWayToTarget(targetPoint, nearestPoint, playerPosition, new List<Point>(way), ref shortestWayLength, ref failedTriesToBeatPath, maximumTries, ref recursionStep); /* Adds the found waypoints to the way if the recursive method returns waypoints. * Remember: It returns waypoints if it finds the target. * Additionally the new way must be shorter than the current saved test way. */ if (newWaypoints.Count > 0 && (bestWaypoints.Count == 0 || newWaypoints.Count < bestWaypoints.Count)) { bestWaypoints = new List<Point>(newWaypoints); } } neighbors.Remove(nearestPoint); } /* Returns the bestWay-list if it's longer than 0. Remember: It's longer if a deeper recursive-method found the target. * Otherwise an empty list. */ if (bestWaypoints.Count > 0) { if (!currentPoint.Equals(playerPosition)) { bestWaypoints.Insert(0, currentPoint); } return bestWaypoints; } else { return new List<Point>(); } } }
/// <summary> /// Compute the projection factor for the projection of the point p /// onto this <c>LineSegment</c>. The projection factor is the constant k /// by which the vector for this segment must be multiplied to /// equal the vector for the projection of p. /// </summary> /// <param name="p"></param> /// <returns></returns> public static double ProjectionFactor(Point p, Point LineSegFrom, Point LineSegTo) { if (p.Equals(LineSegFrom)) return 0.0; if (p.Equals(LineSegTo)) return 1.0; // Otherwise, use comp.graphics.algorithms Frequently Asked Questions method /* AC dot AB r = ------------ ||AB||^2 r has the following meaning: r=0 Point = A r=1 Point = B r<0 Point is on the backward extension of AB r>1 Point is on the forward extension of AB 0<r<1 Point is interior to AB */ var dx = LineSegTo.X - LineSegFrom.X; var dy = LineSegTo.Y - LineSegFrom.Y; var len2 = dx * dx + dy * dy; var r = ((p.X - LineSegFrom.X) * dx + (p.Y - LineSegFrom.Y) * dy) / len2; return r; }
public static void EqualityTest_NotPoint() { var point = new Point(0, 0); Assert.False(point.Equals(null)); Assert.False(point.Equals(0)); Assert.False(point.Equals(new PointF(0, 0))); }
public void PointEquals() { var pt1 = new Point(0, 0); var pt2 = new Point(0, 0); Assert.IsTrue(pt1.Equals(pt2)); }
public void Point_Equals_returns_false_given_null_rhs() { var m1 = new Point(1.0f, 1.2f, 1.9f); Point m2 = null; bool eqeq = m1.Equals(m2); Assert.IsFalse(eqeq); }
protected override void OnUpdateFrame(FrameEventArgs e) { base.OnUpdateFrame(e); //float[] lightPos = l.getPosition(); //if (Keyboard[Key.Plus]) //{ // l.setPosition(lightPos[0], lightPos[1]+0.1f, lightPos[2], lightPos[3]); //} //else if (Keyboard[Key.Minus]) //{ // l.setPosition(lightPos[0], lightPos[1] - 0.1f, lightPos[2], lightPos[3]); //} if (map.isEnemyDefeated() || map.isFriendlyDefeated()) { string statement = map.isEnemyDefeated() ? "YOU WON! Replay a new game? (Y/N)" : "YOU LOST! Replay a new game?"; if (this.WindowState == WindowState.Fullscreen) { Console.WriteLine(statement); string answer = ""; while (!(string.Compare(answer, "Y") == 0) || !(string.Compare(answer, "N") == 0) || !(string.Compare(answer, "y") == 0) || !(string.Compare(answer, "n") == 0)) { answer = Console.ReadLine(); if (string.Compare(answer, "Y") == 0 || string.Compare(answer, "y") == 0) { instance.LoadMap(mapFile); break; } else if (string.Compare(answer, "N") == 0 || string.Compare(answer, "n") == 0) { Exit(); Console.WriteLine("GAME OVER!"); break; } } } else { gameOver = true; } } if (Keyboard[Key.Escape]) Exit(); if (Keyboard[Key.F4]) ReferencePlane.setVisibleAxis(ReferencePlane.XYZ); else if (Keyboard[Key.F5]) ReferencePlane.setVisibleAxis(ReferencePlane.XZ); else if (Keyboard[Key.F6]) ReferencePlane.setVisibleAxis(ReferencePlane.XY); else if (Keyboard[Key.F7]) ReferencePlane.setVisibleAxis(ReferencePlane.NONE); else if (Keyboard[Key.F11]) cameraEnabled = false; else if (Keyboard[Key.F12]) cameraEnabled = true; mousePosition = new Point(Mouse.X, Mouse.Y); mouseDelta = new Point(mousePosition.X - PointToClient(WindowCenter).X, mousePosition.Y - PointToClient(WindowCenter).Y); if (!mouseDelta.Equals(nullDelta)) { if (camera.MouseDeltaMotion(mouseDelta.X, mouseDelta.Y)) { mouseDelta.X = mouseDelta.Y = 0; System.Windows.Forms.Cursor.Position = WindowCenter; } } if (cameraEnabled && (camera != rmcUnitCamera)) { Camera.Action action = Camera.Action.NONE; if (Keyboard[Key.Up]) action |= Camera.Action.MOVE_UP; if (Keyboard[Key.Down]) action |= Camera.Action.MOVE_DOWN; if (Keyboard[Key.Left]) action |= Camera.Action.MOVE_LEFT; if (Keyboard[Key.Right]) action |= Camera.Action.MOVE_RIGHT; if (Keyboard[Key.W]) action |= Camera.Action.ROTATE_UP; if (Keyboard[Key.S]) action |= Camera.Action.ROTATE_DOWN; if (Keyboard[Key.D]) action |= Camera.Action.ROTATE_RIGHT; if (Keyboard[Key.A]) action |= Camera.Action.ROTATE_LEFT; if (Keyboard[Key.Q]) action |= Camera.Action.ROLL_LEFT; if (Keyboard[Key.E]) action |= Camera.Action.ROLL_RIGHT; if (action != Camera.Action.NONE) camera.PerformActions(action); else camera.IdleAction(); } else if (camera == rmcUnitCamera) { if (Keyboard[Key.Space]) map.HoverRemoteControlUnit(); if (Keyboard[Key.Left]) map.MoveRemoteControlUnitLeft(); if (Keyboard[Key.Right]) map.MoveRemoteControlUnitRight(); if (Keyboard[Key.Up]) map.MoveRemoteControlUnitUp(); if (Keyboard[Key.Down]) map.MoveRemoteControlUnitDown(); if (Keyboard[Key.ShiftLeft]) map.GrabRobot(); if (Keyboard[Key.AltLeft]) map.FireProjectileFromRobot(); float[] rmcUnitPos = map.GetRemoteControlUnitPosition(); rmcUnitCamera.LookAt(rmcUnitPos[0], 6.0f, 8.0f - rmcUnitPos[1], rmcUnitPos[0], 3.0f, 4.0f - rmcUnitPos[1], 0.0f, 1.0f, 0.0f); } }
public void Point_Equals_returns_true_given_same_object_twice() { var m1 = new Point(1.0f, 1.2f, 1.9f); var m2 = m1; bool eqeq = m1.Equals(m2); Assert.IsTrue(eqeq); }
public void Point_Equals_differentiates_two_Points_successfully_on_x() { var m1 = new Point(1.0f, 1.2f, 1.9f); var m2 = new Point(-1.0f, 1.2f, 1.9f); bool eqeq = m1.Equals(m2); Assert.IsFalse(eqeq); }
void DecideChunk(Point parentPoint, Point currentPoint, double chamberProbability, List<Point> ramificationPoints) { Debug.Log("Deciding Chunk at " + currentPoint); var chunk = map[currentPoint]; switch (ramificationPoints.Count) { case 0: if (chunk == null) { chunk = PutChamber(currentPoint, parentPoint); } break; case 1: if (chunk == null) { chunk = PutTwoWayChunk(currentPoint, parentPoint, ramificationPoints[0], chamberProbability); } else { chunk = PutThreeWayChunkOnTrivialPath(chunk, currentPoint, ramificationPoints); } break; case 2: if (chunk == null) { chunk = PutThreeWayChunk(currentPoint, parentPoint, ramificationPoints[0], ramificationPoints[1], chamberProbability); } else if (currentPoint.Equals(startPoint) || currentPoint.Equals(endPoint)) { chunk = PutThreeWayChunkOnTrivialPath(chunk, currentPoint, ramificationPoints); } else { RemoveChunk(currentPoint, chunk); chunk = PutFourWayChunk(chamberProbability, currentPoint); } break; case 3: if (chunk != null) { RemoveChunk(currentPoint, chunk); } chunk = PutFourWayChunk(chamberProbability, currentPoint); break; } map[currentPoint] = chunk; }