Ejemplo n.º 1
0
        private void InitializeBoardBackgroundStandard()
        {
            Color c = new Color();

            c.R = 15;
            c.G = 15;
            c.B = 15;
            c.A = 255;
            SolidColorBrush s = new SolidColorBrush(c);

            // The top gray Dark gray section
            IEnumerable <Point> ps = null;

            for (int i = 0; i < 19; i++)
            {
                double  j       = 9f - i;
                Point[] topSide = new Point[] {
                    new Point(4f, j),
                    new Point(3f, j),
                    new Point(2f, j),
                    new Point(1f, j),
                    new Point(0f, j),
                    new Point(-1, j),
                    new Point(-2, j),
                    new Point(-3f, j),
                    new Point(-4f, j)
                };

                if (ps == null)
                {
                    ps = topSide.ToList();
                }
                else
                {
                    ps = ps.Concat(topSide.ToList());
                }
            }

            List <TetrisPoint> tl = new List <TetrisPoint>();

            foreach (Point p in ps)
            {
                System.Windows.Shapes.Rectangle e = new Rectangle();
                e.Width  = 16;
                e.Height = 16;

                e.Fill = s;
                e.SetValue(Canvas.LeftProperty, p.X);
                e.SetValue(Canvas.TopProperty, p.Y);
                TetrisPoint tp = new TetrisPoint(p, e);
                tl.Add(tp);
            }
            TetrisShape ts = new TetrisShape(tl);

            _boardBackground = ts;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 初级机器智力
        /// </summary>
        /// <param name="pt">输入点</param>
        /// <param name="flg">输入点标志</param>
        /// <returns></returns>
        public Point PrimaryAI()
        {
            Point returnPt = new Point();

            //遍历所有黑子的落点,查找形成的评分最高的棋型,在棋型中找个要落子的空位,使得新棋型评分最高
            Dictionary <int, Point> bDict = myMethod.GetMaxScoreAndPos(Chess.blackPtsLst, Chess.TypeScore, 1);

            //遍历所有白子的落点,查找形成的评分最高的棋型,在棋型中找个要落子的空位,使得新棋型评分最高
            Dictionary <int, Point> wDictold = myMethod.GetMaxScoreAndPos(Chess.whitePtsLst, Chess.TypeScore, 2);

            Point[] pts = new Point[Chess.whitePtsLst.Count];
            Chess.whitePtsLst.CopyTo(pts);
            List <Point> newWhitePtsLst = pts.ToList();

            newWhitePtsLst.Add(wDictold.Values.FirstOrDefault());

            Dictionary <int, Point> wDict = myMethod.GetMaxScoreAndPos(newWhitePtsLst, Chess.TypeScore, 2);

            if (wDict.Keys.FirstOrDefault() >= Chess.LIVE5)
            {
                return(wDict.Values.FirstOrDefault());
            }
            else if (wDict.Keys.FirstOrDefault() >= Chess.SPRT4)
            {
                returnPt = bDict.Keys.FirstOrDefault() >= Chess.SPRT4 ? bDict.Values.FirstOrDefault() : wDict.Values.FirstOrDefault();
            }
            else
            {
                returnPt = bDict.Keys.FirstOrDefault() > wDict.Keys.FirstOrDefault() || bDict.Keys.FirstOrDefault() >= Chess.LIVE3 ? bDict.Values.FirstOrDefault() : wDict.Values.FirstOrDefault();
            }


            return(returnPt);
        }
Ejemplo n.º 3
0
        private static void divide_conquer(IList <Point> point, ICollection <Point> hup, line _line)
        {
            if (point.Count < 1)
            {
                return;
            }
            Point[] temp = new Point[point.Count];
            point.CopyTo(temp, 0);
            point = temp.ToList();

            Point p;

            p.X = -1;
            p   = divide_conquer(point, _line, p);

            if (p.X < 0)
            {
                return;
            }

            hup.Add(p);
            line dy = new line()
            {
                x = _line.x,
                y = p
            };

            divide_conquer(point, hup, dy);
            dy = new line()
            {
                x = p,
                y = _line.y
            };
            divide_conquer(point, hup, dy);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Hides the snake in its current position,
        /// calculates the co-ordinates of the the new positions for the parts of the snake
        /// Shows the snake at the new position
        /// </summary>
        public void update()
        {
            hide();

            Point[] newPositions = new Point[parts.Count];//temp array

            //move each part into the space of the next part, apart from the head
            for (int i = parts.Count - 1; i > 0; i--)
            {
                newPositions[i] = parts[i - 1];
            }

            //move the head
            newPositions[0] = getNewHeadPosition();

            addNewHere = parts[parts.Count - 1];//saves the bit on the end where a new part should be added
            parts      = newPositions.ToList();

            //check if fruit is eaten, in which case add new part at end of snake
            if (parts[0] == board.fruit)
            {
                parts.Add(addNewHere);
                board.showFruit();
            }

            //check if snake has eaten itself
            if (isDead())
            {
                dead = true;
            }

            show();
        }
Ejemplo n.º 5
0
        public void Update(Point startP, Point endP)
        {
            Point[] pointsArray = new Point[2];
            pointsArray[0] = startP;
            startPoint     = startP;
            pointsArray[1] = endP;
            secondPoint    = endP;

            pointsList = pointsArray.ToList();
        }
Ejemplo n.º 6
0
        ///// <summary>
        ///// смещение все точек на -х и -у
        ///// </summary>
        ///// <param name="arr"></param>
        ///// <param name="p"></param>
        //public void shiftArray2(ref Point[] arr, Point p)
        //{

        //    for (int i = 0; i < curentN; i++)
        //    {
        //        arr[i].X -= p.X; ;// p.X;
        //        arr[i].Y -= p.Y; ;
        //    }
        //    // arr[curentN].X = 0; // p.X;
        //    //arr[curentN].Y =0 ;
        //}
        #endregion
        #region для рисования

        public void drawOfIndex(int index)
        {
            scaleCurentFigure();
            Point[] temp = new Point[mainColections[index].Length];
            temp = mainColections[index].ToArray();
            scaleCurentFigure2(ref temp);
            shiftArray(ref temp, new Point(-200, -200));
            //   shiftArray2(ref mainPoins2, new Point(-200, -200));
            StreamGeometryTriangleExample(temp.ToList());
        }
Ejemplo n.º 7
0
        public void Update(Point startPoint, Point endPoint)
        {
            Point[] pointsArray = new Point[3];

            pointsArray[0] = startPoint;
            pointsArray[1] = secondPoint;
            pointsArray[2] = new Point((secondPoint.X - (secondPoint.X - startPoint.X) * 2), secondPoint.Y);

            pointsList = new List <Point> {
            };
            pointsList = pointsArray.ToList();
        }
Ejemplo n.º 8
0
        public void Update(Point startPoint, Point endPoint)
        {
            //double hpt = Math.Sqrt(Math.Pow(radius, 2) + Math.Pow(radius, 2));
            int   radius             = endPoint.X - startPoint.X;
            Point startRectangleHere = new Point(secondPoint.X, startPoint.Y + radius);

            Point[] pointsArray = new Point[3];
            pointsArray[0] = startRectangleHere;
            pointsArray[1] = startPoint;
            pointsArray[2] = endPoint;

            pointsList = pointsArray.ToList();
        }
Ejemplo n.º 9
0
        public static List <Point> TwoOptSwap(List <Point> lstPoints, int from, int to)
        {
            Point[] arrPoints = new Point[lstPoints.Count];

            lstPoints.CopyTo(0, arrPoints, 0, from);
            for (int nIndex = to; nIndex >= from; nIndex--)
            {
                arrPoints[from + to - nIndex] = lstPoints[nIndex];
            }
            lstPoints.CopyTo(to + 1, arrPoints, to + 1, lstPoints.Count - to - 1);

            return(arrPoints.ToList());
        }
Ejemplo n.º 10
0
        public void Update(Point startPoint, Point endPoint)
        {
            Point[] pointsArray = new Point[4];


            pointsArray[0] = startPoint;
            pointsArray[1] = new Point(startPoint.X, endPoint.Y);
            pointsArray[2] = endPoint;
            pointsArray[3] = new Point(endPoint.X, startPoint.Y);

            pointsList = new List <Point> {
            };
            pointsList = pointsArray.ToList();
        }
Ejemplo n.º 11
0
        private void button2_Click(object sender, EventArgs e)
        {
            Point[] points = new Point[HPts.Count];
            HPts.CopyTo(points);
            List <Point> PathPoint = points.ToList <Point>();

            var watch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                while (PathPoint.Count < Maincounter)
                {
                    PathPoint = FindThePath(PathPoint);
                }
                watch.Stop();
                points = new Point[PathPoint.Count];
                PathPoint.CopyTo(points);

                Pen p = new Pen(Color.Red, 2);
                using (Graphics g = Graphics.FromImage(img))
                {
                    g.DrawPolygon(p, points);
                }

                Bitmap pic = new Bitmap(pictureBox1.Image);
                pictureBox1.Image = img;
            }
            catch
            {
                MessageBox.Show("Plase make sure you select point on map first!");
            }
            MessageBox.Show("Done!");

            int FainlDist = 0;

            for (int i = 0; i < PathPoint.Count; i++)
            {
                if (i == PathPoint.Count - 1)
                {
                    FainlDist += dist(PathPoint[i], PathPoint[0]);
                }
                else
                {
                    FainlDist += dist(PathPoint[i], PathPoint[i + 1]);
                }
            }
            Time_MyAlgorthem = watch.ElapsedMilliseconds.ToString();
            Dist_MyAlgorthem = FainlDist.ToString();
        }
Ejemplo n.º 12
0
        public void Update(Point startPoint, Point endPoint)
        {
            Point[] pointsArray = new Point[3];
            Point[] points      = new Point[3];
            for (int i = 0; i == 3; i++)
            {
                points[0] = startPoint;
                points[1] = secondPoint;
                points[2] = new Point();

                pointsList = new List <Point> {
                };
                pointsList = pointsArray.ToList();
            }
        }
Ejemplo n.º 13
0
Archivo: Core.cs Proyecto: Sadikk/TPE
        private Path Breed(Path father, Path mother)
        {
            Random rand = new Random();

            Point[] genes           = new Point[father.Locations.Count];
            Point[] map             = new Point[father.Locations.Count + 1];    //create a map to map the indices
            int     crossoverPoint1 = rand.Next(1, father.Locations.Count - 2); //select 2 crossoverpoints, without the first and last nodes, cuz they are always the same
            int     crossoverPoint2 = rand.Next(1, father.Locations.Count - 2);

            father.Locations.CopyTo(genes, 0);     //give child all genes from the father
            for (int i = 0; i < genes.Length; i++) //create the map
            {
                map[i] = genes[i];
            }
            //int[] genesToCopy = new int[Math.Abs(crossoverPoint1 - crossoverPoint2)]; //allocate space for the mother genes to copy
            if (crossoverPoint1 > crossoverPoint2) //if point 1 is bigger than point 2 swap them
            {
                int temp = crossoverPoint1;
                crossoverPoint1 = crossoverPoint2;
                crossoverPoint2 = temp;
            }
            //Console.WriteLine("copy mother genes into father genes from {0} to {1}", crossoverPoint1, crossoverPoint2);
            for (int i = crossoverPoint1; i <= crossoverPoint2; i++) //from index one to the 2nd
            {
                Point value = mother.Locations[i];
                Point t     = genes[map.ToList().IndexOf(value)]; //swap the genes in the child
                genes[map.ToList().IndexOf(value)] = genes[i];
                genes[i] = t;
                t        = map[genes.ToList().IndexOf(map[map.ToList().IndexOf(value)])]; //swap the indices in the map
                map[genes.ToList().IndexOf(map[map.ToList().IndexOf(value)])] = map[genes.ToList().IndexOf(map[i])];
                map[genes.ToList().IndexOf(map[i])] = t;
            }
            Path child = new Path(genes.ToList());

            return(child);
        }
Ejemplo n.º 14
0
            public Point Minimum(Expression <Func <double, double> > expression, double A, double B, int itersCount)
            {
                var fun = expression.Compile();

                double F(double x) => fun.Invoke(x);

                var points   = new Point[itersCount + 1].Select(xv => new Point()).ToArray();
                var minimums = new Point[itersCount].Select(xv => new Point()).ToArray();

                points[0] = new Point(A, F(A));
                points[1] = new Point(B, F(B));

                minimums[0] = CalculateNext(points[0], points[1]);

                int indexOfMinimum = 0, iter, stepi;

                for (iter = 2; iter <= itersCount; iter++)
                {
                    var ymin = minimums.Min(t => t.Y);
                    indexOfMinimum = minimums.ToList().Select(xv => xv.Y).ToList().IndexOf(ymin);

                    for (stepi = 1; stepi <= (iter - indexOfMinimum - 1); stepi++)
                    {
                        points[iter - stepi + 1] = points[iter - stepi].Copy();
                    }

                    points[indexOfMinimum + 1].X = minimums[indexOfMinimum].X;

                    points[indexOfMinimum + 1].Y = F(points[indexOfMinimum + 1].X);

                    for (stepi = 1; stepi <= (iter - indexOfMinimum - 1); stepi++)
                    {
                        minimums[iter - stepi] = minimums[iter - stepi - 1].Copy();
                    }

                    minimums[indexOfMinimum] = CalculateNext(points[indexOfMinimum], points[indexOfMinimum + 1]);

                    minimums[indexOfMinimum + 1] = CalculateNext(points[indexOfMinimum + 1], points[indexOfMinimum + 2]);
                    if (points[indexOfMinimum].X == 0.0)
                    {
                    }
                    Console.WriteLine($"[{iter}] {points[indexOfMinimum]}");
                }
                return(points[indexOfMinimum]);
            }
Ejemplo n.º 15
0
        public void Update(Point startPoint, Point endPoint)
        {
            Point[] pointstoArray = new Point[4];

            int a = Math.Abs(startPoint.X - endPoint.X);

            if (startPoint.Y > endPoint.Y)
            {
                a = -a;
            }

            pointstoArray[0] = startPoint;
            pointstoArray[1] = new Point(startPoint.X, startPoint.Y + a);
            pointstoArray[2] = new Point(endPoint.X, startPoint.Y + a);
            pointstoArray[3] = new Point(endPoint.X, startPoint.Y);

            pointsList = pointstoArray.ToList();
        }
        public override void PrepareConsole()
        {
            Console.CursorVisible = false;
            Point[] points = new Point[] { GetPosition(StandartTrafficLightController.RED_COLOR),
                                           GetPosition(StandartTrafficLightController.YELLOW_COLOR),
                                           GetPosition(StandartTrafficLightController.GREEN_COLOR) };
            Console.BackgroundColor = defaultColor;

            points.ToList().ForEach(point =>
            {
                for (int i = 0; i < 3; i++)
                {
                    Console.SetCursorPosition(point.X, point.Y);
                    Console.WriteLine("   ");
                    point.Y++;
                }
            });
        }
Ejemplo n.º 17
0
        private static void hexagono(Info_forma informacion, PictureBox pintura)
        {
            informacion.g = Graphics.FromImage((Bitmap)pintura.Image);
            Point[] shape = new Point[6];
            Pen     borde = new Pen(Color.Black, informacion.grosor_pared);

            int[] array = { informacion.ancho_forma, informacion.alto_forma };
            int   r     = array.Min() * 100;

            //Create 6 points
            for (int a = 0; a < 6; a++)
            {
                shape[a] = new Point(
                    (int)(informacion.po.X + r * (float)Math.Cos(a * 60 * Math.PI / 180)),
                    (int)(informacion.po.Y + r * (float)Math.Sin(a * 60 * Math.PI / 180)));
            }
            informacion.contorno = shape.ToList();
            informacion.g.FillPolygon(Brocha, shape);
            informacion.g.DrawPolygon(borde, shape);
        }
Ejemplo n.º 18
0
        public void Update(Point startPoint, Point endPoint)
        {
            Point[] pointsArray = new Point[_anglesNumber];

            double externalRadius;               //радиус описанной окружности
            double fullRoundInRad = Math.PI * 2; //Число Пи умноженное на два

            double sector = fullRoundInRad / _anglesNumber;


            externalRadius = Math.Sqrt(Math.Pow(Math.Abs(secondPoint.X - startPoint.X), 2) + Math.Pow(Math.Abs(secondPoint.Y - startPoint.Y), 2));

            for (int i = 0; i < _anglesNumber; i++)
            {
                pointsArray[i] = new Point(startPoint.X + (int)((Math.Round(externalRadius, 0)) * Math.Sin(sector * (i + 1))), startPoint.Y + (int)((Math.Round(externalRadius, 0)) * Math.Cos(sector * (i + 1))));
            }

            pointsList = new List <Point> {
            };
            pointsList = pointsArray.ToList();
        }
Ejemplo n.º 19
0
        private void CreateRandomPoints()
        {
            ResetVars();
            Point[] pointArr = new Point[numberOfPoints];
            pointArr[0] = new Point(rnd.Next(2, canvas.Width - 2), rnd.Next(2, canvas.Height - 2));
            const int multiplier = 3;
            const int amplitude  = 100;
            const int offset     = 70;

            for (int i = 1; i < numberOfPoints; i++)
            {
                double x = pointArr[i - 1].X;
                double y = pointArr[i - 1].Y;
                double w = canvas.Width;
                double h = canvas.Height;
                pointArr[i] = new Point(ReturnRange(rnd.Next((int)(x - multiplier * (amplitude * Math.Log10(x) - offset)), (int)(x + multiplier * (amplitude * Math.Log10(-x + w) - offset))), 5, w - 5),
                                        ReturnRange(rnd.Next((int)(y - multiplier * (amplitude * Math.Log10(y) - offset)), (int)(y + multiplier * (amplitude * Math.Log10(-y + h) - offset))), 5, h - 5));
            }
            points = pointArr.ToList();
            hash   = points.GetHashCode();
        }
Ejemplo n.º 20
0
        public static Output <List <int>, List <double>, List <Point> > ClosestPoints(List <Point> clouds, Point samplePoint, int nPoints)
        {
            Point[] cloud = clouds.ToArray();
            // For each cloud point, get the distance to the sample point and populate the indices
            int[]    nearPointIndices   = new int[cloud.Length];
            double[] nearPointDistances = new double[cloud.Length];
            for (int i = 0; i < cloud.Length; i++)
            {
                nearPointIndices[i]   = i;
                nearPointDistances[i] = cloud[i].Distance(samplePoint);
            }

            // Sort the arrays based on distance
            Array.Sort(nearPointDistances, nearPointIndices);

            // Get the closest n-Point indices and distances
            int[]    sampleIndices   = new int[nPoints];
            double[] sampleDistances = new double[nPoints];
            for (int i = 0; i < nPoints; i++)
            {
                sampleIndices[i]   = nearPointIndices[i];
                sampleDistances[i] = nearPointDistances[i];
            }

            // Get the closest n-Points
            Point[] nearPoints = new Point[nPoints];
            for (int i = 0; i < sampleIndices.Length; i++)
            {
                nearPoints[i] = cloud[sampleIndices[i]];
            }

            // Return the n-closest cloud Points to the samplePoint
            return(new Output <List <int>, List <double>, List <Point> >
            {
                Item1 = sampleIndices.ToList(),
                Item2 = sampleDistances.ToList(),
                Item3 = nearPoints.ToList()
            });
        }
Ejemplo n.º 21
0
        private IEnumerable<Shape> _addSeriesAsPolyline(Point[] points, Brush color, double storkeThickness,
            bool animate = true)
        {
            if (points.Length < 2) return Enumerable.Empty<Shape>();
            var addedFigures = new List<Shape>();

            var l = 0d;
            for (var i = 1; i < points.Length; i++)
            {
                var p1 = points[i - 1];
                var p2 = points[i];
                l += Math.Sqrt(
                    Math.Pow(Math.Abs(p1.X - p2.X), 2) +
                    Math.Pow(Math.Abs(p1.Y - p2.Y), 2)
                    );
            }

            var f = points.First();
            var p = points.Where(x => x != f);
            var g = new PathGeometry
            {
                Figures = new PathFigureCollection(new List<PathFigure>
                {
                    new PathFigure
                    {
                        StartPoint = f,
                        Segments = new PathSegmentCollection(
                            p.Select(x => new LineSegment {Point = new Point(x.X, x.Y)}))
                    }
                })
            };

            var path = new Path
            {
                Stroke = color,
                StrokeThickness = storkeThickness,
                Data = g,
                StrokeEndLineCap = PenLineCap.Round,
                StrokeStartLineCap = PenLineCap.Round,
                StrokeDashOffset = l,
                StrokeDashArray = new DoubleCollection { l, l },
                ClipToBounds = true
            };

            var sp = points.ToList();
            sp.Add(new Point(points.Max(x => x.X), ToPlotArea(Chart.Min.Y, AxisTags.Y)));

            Chart.Canvas.Children.Add(path);
            addedFigures.Add(path);

            var draw = new DoubleAnimationUsingKeyFrames
            {
                BeginTime = TimeSpan.FromSeconds(0),
                KeyFrames = new DoubleKeyFrameCollection
                {
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(1),
                        Value = l
                    },
                    new SplineDoubleKeyFrame
                    {
                        KeyTime = TimeSpan.FromMilliseconds(750),
                        Value = 0
                    }
                }
            };
            Storyboard.SetTarget(draw, path);
            Storyboard.SetTargetProperty(draw, new PropertyPath(Shape.StrokeDashOffsetProperty));
            var sbDraw = new Storyboard();
            sbDraw.Children.Add(draw);
            var animated = false;
            if (!Chart.DisableAnimation)
            {
                if (animate)
                {
                    sbDraw.Begin();
                    animated = true;
                }
            }
            if (!animated) path.StrokeDashOffset = 0;
            return addedFigures;
        }
Ejemplo n.º 22
0
 public static List<List<Point>> BorderPoints(List<Point> points)
 {
     var dictionary = new List<KeyValuePair<double, List<Point>>>();
     var border = new List<List<Point>>();
     var tmp = points.ToList();
     tmp.Sort((t1, t2) => Math.Sign(t1.Y - t2.Y));
     while (tmp.Count > 0) {
         var v = tmp[0];
         var near = tmp.TakeWhile(t => Math.Abs(t.Y - v.Y) < 20).ToList();
         foreach (var n in near) {
             tmp.Remove(n);
         }
         //near.Sort((n1, n2) => Math.Sign(n1.GetVector3().sqrMagnitude - n2.GetVector3().sqrMagnitude));
         if (near.Count > 1) {
             var lengthes = new List<double>();
             var tmp2 = new Point[near.Count];
             near.CopyTo(tmp2);
             var max = Math.Sqrt(near.Count);
             for (int i = 0; i < max && near.Count > 0; i++) {
                 var first = near.First();
                 var last = near.Last();
                 near.Remove(first);
                 near.Remove(last);
                 lengthes.Add((first.GetColor() - last.GetColor()).SqrLength());
             }
             var median = lengthes.Median();
             dictionary.Add(new KeyValuePair<double, List<Point>>(median, tmp2.ToList()));
         }
     }
     for (int i = 0; i < dictionary.Count; i++) {
         var nears = dictionary[i].Value;
         var distance = dictionary.Min(d => {
             if (d.Value == nears) {
                 return double.MaxValue;
             } else {
                 var col1 = Functions.AverageColor(d.Value.Select(s => s.GetColor()).ToList());
                 var col2 = Functions.AverageColor(nears.Select(s => s.GetColor()).ToList());
                 return (col1 - col2).SqrLength();
             }
         });
         if (distance > 0.001) {
             border.Add(dictionary[i].Value);
         }
     }
     return border;
 }
        /// <summary>
        /// This clips the subject polygon against the clip polygon (gets the intersection of the two polygons)
        /// </summary>
        /// <remarks>
        /// Based on the psuedocode from:
        /// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman
        /// </remarks>
        /// <param name="subjectPoly">Can be concave or convex</param>
        /// <param name="clipPoly">Must be convex</param>
        /// <returns>The intersection of the two polygons (or null)</returns>
        public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly)
        {
            if (subjectPoly.Length < 3 || clipPoly.Length < 3)
            {
                throw new ArgumentException(string.Format("The polygons passed in must have at least 3 points: subject={0}, clip={1}", subjectPoly.Length.ToString(), clipPoly.Length.ToString()));
            }

            List<Point> outputList = subjectPoly.ToList();

            //	Make sure it's clockwise
            if (!IsClockwise(subjectPoly))
            {
                outputList.Reverse();
            }

            //	Walk around the clip polygon clockwise
            foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly))
            {
                List<Point> inputList = outputList.ToList();		//	clone it
                outputList.Clear();

                if (inputList.Count == 0)
                {
                    //	Sometimes when the polygons don't intersect, this list goes to zero.  Jump out to avoid an index out of range exception
                    break;
                }

                Point S = inputList[inputList.Count - 1];

                foreach (Point E in inputList)
                {
                    if (IsInside(clipEdge, E))
                    {
                        if (!IsInside(clipEdge, S))
                        {
                            Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
                            if (point == null)
                            {
                                throw new ApplicationException("Line segments don't intersect");		//	may be colinear, or may be a bug
                            }
                            else
                            {
                                outputList.Add(point.Value);
                            }
                        }

                        outputList.Add(E);
                    }
                    else if (IsInside(clipEdge, S))
                    {
                        Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);
                        if (point == null)
                        {
                            throw new ApplicationException("Line segments don't intersect");		//	may be colinear, or may be a bug
                        }
                        else
                        {
                            outputList.Add(point.Value);
                        }
                    }

                    S = E;
                }
            }

            //	Exit Function
            return outputList.ToArray();
        }
        private void CreateScene()
        {
            // Create material with 10 x 10 numbers grid
            var imageBrush = new ImageBrush(new BitmapImage(new Uri(@"pack://application:,,,/Resources/10x10-texture.png")));

            var material = new DiffuseMaterial(imageBrush);
            //var material = new DiffuseMaterial(Brushes.Silver);


            // Create box with 10 x 10 x 10 cells
            var boxVisual3D = new BoxVisual3D()
            {
                UseCachedMeshGeometry3D = false, // This will generate a new MeshGeometry3D for this BoxVisual3D,
                FreezeMeshGeometry3D    = false, // This will allow us to change the TextureCoordinates
                CenterPosition          = new Point3D(-150, 0, -50),
                Size        = new Size3D(60, 60, 60),
                XCellsCount = 10,
                YCellsCount = 10,
                ZCellsCount = 10,
                Material    = material,
            };

            MainViewport.Children.Add(boxVisual3D);


            var cylinderVisual3D = new CylinderVisual3D()
            {
                BottomCenterPosition = new Point3D(-50, -30, -50),
                Radius   = 30,
                Height   = 60,
                Segments = 10,
                IsSmooth = false,
                Material = material
            };

            MainViewport.Children.Add(cylinderVisual3D);


            var sphereVisual3D = new SphereVisual3D()
            {
                UseCachedMeshGeometry3D = false, // This will generate a new MeshGeometry3D for this BoxVisual3D,
                FreezeMeshGeometry3D    = false, // This will allow us to change the TextureCoordinates
                CenterPosition          = new Point3D(50, 0, -50),
                Radius   = 30,
                Material = material
            };

            MainViewport.Children.Add(sphereVisual3D);


            // Add dragon model
            string fileName         = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\ObjFiles\\dragon_vrip_res3.obj");
            var    objModelVisual3D = new ObjModelVisual3D()
            {
                Source          = new Uri(fileName, UriKind.Absolute),
                SizeX           = 70,
                Position        = new Point3D(-150, 0, 100),
                PositionType    = ObjModelVisual3D.VisualPositionType.Center,
                DefaultMaterial = material,
            };

            Ab3d.Utilities.ModelUtils.ChangeMaterial(objModelVisual3D.Content, material, newBackMaterial: null);

            MainViewport.Children.Add(objModelVisual3D);


            // Add simple extruded shape
            var extrudePositions = new Point[]
            {
                new Point(-1, 54),
                new Point(13, 35),
                new Point(8, 32),
                new Point(18, 13),
                new Point(11, 9),
                new Point(23, -13),
                new Point(6, -14),
                new Point(6, -29),
                new Point(-8, -30),
                new Point(-7, -13),
                new Point(-25, -9),
                new Point(-12, 9),
                new Point(-25, 16),
                new Point(-8, 31),
                new Point(-16, 38)
            };

            var extrudedMesh = Mesh3DFactory.CreateExtrudedMeshGeometry(positions: extrudePositions.ToList(),
                                                                        isSmooth: false,
                                                                        modelOffset: new Vector3D(-50, -15, 100),
                                                                        extrudeVector: new Vector3D(0, 30, 0),
                                                                        shapeYVector: new Vector3D(0, 0, -1),
                                                                        textureCoordinatesGenerationType: ExtrudeTextureCoordinatesGenerationType.AddAdditionalPositions);

            var geometryModel3D = new GeometryModel3D(extrudedMesh, material);

            var modelVisual3D = new ModelVisual3D();

            modelVisual3D.Content = geometryModel3D;

            MainViewport.Children.Add(modelVisual3D);
        }
Ejemplo n.º 25
0
        public int[,] CalcSecondMaxNumber(int m, int n, int r, int[,] inputArray)
        {
            if (inputArray == null || inputArray.Length < 2 || inputArray.Length > 300 || n < 2 || n > 300 ||
                r < 1 || r > 1000000000)
            {
                throw new Exception("Length of input parameters is not correct.");
            }

            if (Math.Min(m, n) % 2 != 0)
            {
                throw new Exception("Math.Min(m, n) % 2 != 0");
            }

            var result = new int[n, m];

            for (int y = 0; y < m; y++)
            {
                for (int x = 0; x < n; x++)
                {
                    result[x, y] = -1;
                }
            }

            var requiredNumberOfDisplacements = GetRequiredNumberOfDisplacements(m, n, r);

            if (requiredNumberOfDisplacements == 0)
            {
                return(inputArray);
            }

            var frameList     = new List <Frame>();
            var countOfFrames = Math.Min(m, n) / 2;


            // create all frames frameList from mattrix:
            for (int i = 0; i < countOfFrames; i++)
            {
                //We go diagonally and if we have not yet exhausted the frames, than we create the frame:
                if (i < m && i < n)
                {
                    var frWidth  = n - (i * 2);
                    var frLength = m - (i * 2);
                    var frame    = new Frame()
                    {
                        M = frLength, N = frWidth, FrameNum = i + 1,
                        RequiredNumberOfDisplacements = GetRequiredNumberOfDisplacements(frLength, frWidth, r)
                    };
                    frameList.Add(frame);
                }
            }

            foreach (var frame in frameList)
            {
                var points    = new List <Point>();
                var addNumber = frame.FrameNum == 1 ? 0 : 1;
                // go along the left vertical side of the frame:
                for (var y = frame.FrameNum - 1; y < frame.FrameNum - 1 + frame.M; y++)
                {
                    var x     = frame.FrameNum - 1;
                    var point = new Point()
                    {
                        X = x, Y = y, Value = inputArray[x, y]
                    };
                    points.Add(point);
                }

                // go along the bottom horizontal side of the frame:
                for (var x = frame.FrameNum; x < frame.FrameNum - 1 + frame.N; x++)
                {
                    var y     = frame.FrameNum + frame.M - 2;
                    var point = new Point()
                    {
                        X = x, Y = y, Value = inputArray[x, y]
                    };
                    points.Add(point);
                }

                // go along the right vertical side of the frame:
                for (var y = frame.FrameNum + frame.M - 3; y >= frame.FrameNum - 1; y--)
                {
                    var x     = frame.FrameNum + frame.N - 2;
                    var point = new Point()
                    {
                        X = x, Y = y, Value = inputArray[x, y]
                    };
                    points.Add(point);
                }

                // go along the upper horizontal side of the frame:
                for (var x = frame.FrameNum + frame.N - 3; x >= frame.FrameNum; x--)
                {
                    var y     = frame.FrameNum - 1;
                    var point = new Point()
                    {
                        X = x, Y = y, Value = inputArray[x, y]
                    };
                    points.Add(point);
                }

                frame.Points = points;
            }

            // move the elements in the frames to requiredNumberOfDisplacements places:
            foreach (var frame in frameList)
            {
                var displacedPoints = new Point[frame.Points.Count];
                for (var i = 0; i < frame.Points.Count; i++)
                {
                    if (i + frame.RequiredNumberOfDisplacements < frame.Points.Count)
                    {
                        var newPositIndex = i + frame.RequiredNumberOfDisplacements;
                        displacedPoints[newPositIndex] =
                            new Point()
                        {
                            X     = frame.Points[newPositIndex].X,
                            Y     = frame.Points[newPositIndex].Y,
                            Value = frame.Points[i].Value
                        };
                    }
                    else
                    {
                        var newPositIndex = i + frame.RequiredNumberOfDisplacements - frame.Points.Count;
                        displacedPoints[newPositIndex] =
                            new Point()
                        {
                            X     = frame.Points[newPositIndex].X,
                            Y     = frame.Points[newPositIndex].Y,
                            Value = frame.Points[i].Value
                        };
                    }
                }

                frame.Points = displacedPoints.ToList();
            }
            // fill out the output array and frames:
            foreach (var frame in frameList)
            {
                foreach (var point in frame.Points)
                {
                    result[point.X, point.Y] = point.Value;
                }
            }
            return(result);
        }
Ejemplo n.º 26
0
		//Allow the user to import an array of points to be used to draw a signature in the view, with new
		//lines indicated by a PointF.Empty in the array.
		public void LoadPoints (Point [] loadedPoints)
		{
			if (loadedPoints == null || loadedPoints.Count () == 0)
				return;

			var startIndex = 0;
			var emptyIndex = loadedPoints.ToList ().IndexOf (new Point (-10000, -10000));

			if (emptyIndex == -1)
				emptyIndex = loadedPoints.Count ();

			//Clear any existing paths or points.
			strokes = new List<Stroke> ();
			points = new List<Point []> ();

			do {
				//Create a new path and set the line options
				currentStroke = new Stroke ();
				currentStroke.DrawingAttributes.Color = strokeColor;
				currentStroke.DrawingAttributes.Width = lineWidth;
				currentStroke.DrawingAttributes.Height = lineWidth;

				currentPoints = new List<Point> ();

				//Move to the first point and add that point to the current_points array.
				currentStroke.StylusPoints.Add (GetPoint (loadedPoints [startIndex]));
				currentPoints.Add (loadedPoints [startIndex]);

				//Iterate through the array until an empty point (or the end of the array) is reached,
				//adding each point to the current_path and to the current_points array.
				for (var i = startIndex + 1; i < emptyIndex; i++) {
					currentStroke.StylusPoints.Add (GetPoint  (loadedPoints [i]));
					currentPoints.Add (loadedPoints [i]);
				}

				//Add the current_path and current_points list to their respective Lists before
				//starting on the next line to be drawn.
				strokes.Add (currentStroke);
				points.Add (currentPoints.ToArray ());

				//Obtain the indices for the next line to be drawn.
				startIndex = emptyIndex + 1;
				if (startIndex < loadedPoints.Count () - 1) {
					emptyIndex = loadedPoints.ToList ().IndexOf (new Point (-10000, -10000), startIndex);

					if (emptyIndex == -1)
						emptyIndex = loadedPoints.Count ();
				} else
					emptyIndex = startIndex;
			} while (startIndex < emptyIndex);

			//Obtain the image for the imported signature and display it in the image view.
			image.Source = GetImage (false);
			//Display the clear button.
			btnClear.Visibility = Visibility.Visible;
		}
Ejemplo n.º 27
0
        /// <summary>
        /// This clips the subject polygon against the clip polygon (gets the intersection of the two polygons).
        /// </summary>
        /// <remarks>
        /// Based on the psuedocode from: http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman
        /// </remarks>
        /// <param name="subjectPoly">Can be concave or convex.</param>
        /// <param name="clipPoly">Must be convex.</param>
        /// <returns>The intersection of the two polygons (or null).</returns>
        public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly)
        {
            if (subjectPoly.Length < 3 || clipPoly.Length < 3)
            {
                throw new ArgumentException($"The polygons passed in must have at least 3 points: Subject: {subjectPoly.Length}, Clip: {clipPoly.Length}");
            }

            List<Point> outputList = subjectPoly.ToList();

            // Make sure it's clockwise;
            if (!IsClockwise(subjectPoly))
            {
                outputList.Reverse();
            }

            // Walk around the clip polygon clockwise;
            foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly))
            {
                List<Point> inputList = outputList.ToList(); //	clone it;
                outputList.Clear();

                if (inputList.Count == 0)
                {
                    break;
                }

                Point s = inputList[inputList.Count - 1];

                foreach (Point e in inputList)
                {
                    if (IsInside(clipEdge, e))
                    {
                        if (!IsInside(clipEdge, s))
                        {
                            Point? point = GetIntersect(s, e, clipEdge.From, clipEdge.To);

                            if (point == null)
                            {
                                throw new ApplicationException("Line segments don't intersect"); //	may be colinear, or may be a bug;
                            }
                            else
                            {
                                outputList.Add(point.Value);
                            }
                        }

                        outputList.Add(e);
                    }
                    else if (IsInside(clipEdge, s))
                    {
                        Point? point = GetIntersect(s, e, clipEdge.From, clipEdge.To);
                        if (point == null)
                        {
                            throw new ApplicationException("Line segments don't intersect");
                            // may be colinear, or may be a bug;
                        }
                        else
                        {
                            outputList.Add(point.Value);
                        }
                    }

                    s = e;
                }
            }

            return outputList.ToArray();
        }
Ejemplo n.º 28
0
        private void button2_Click(object sender, EventArgs e)
        {
            int max           = 0;
            int thefirstpoint = 0;

            for (int i = 0; i < random_point.Length; i++)//获取初始点
            {
                if (max <= random_point[i].Y)
                {
                    max           = random_point[i].Y;
                    thefirstpoint = i;
                }
            }
            for (int i = 0; i < random_point.Length; i++)//获取极角数组
            {
                if (Polar_angle(random_point[i], random_point[thefirstpoint]) > 0)
                {
                    m[i] = Polar_angle(random_point[i], random_point[thefirstpoint]);
                }
                else
                {
                    m[i] = Polar_angle(random_point[i], random_point[thefirstpoint]) + Math.PI;
                }
                n[i] = Polar_angle(random_point[i], random_point[thefirstpoint]);
            }
            int length = 10;

            for (int i = 0; i < m.Length - 1; i++)//排序
            {
                for (int j = 0; j < m.Length - 1; j++)
                {
                    if (m[j] > m[j + 1])
                    {
                        double k = m[j];
                        m[j]     = m[j + 1];
                        m[j + 1] = k;
                    }
                }
                if (m[i] == m[i + 1])
                {
                    length--;
                }
            }
            Point[] new_point = new Point[10];
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < random_point.Length; j++)
                {
                    if (m[i] == Polar_angle(random_point[j], random_point[thefirstpoint]))
                    {
                        new_point[i] = random_point[j];
                    }
                    if (m[i] == Polar_angle(random_point[j], random_point[thefirstpoint]) + Math.PI)
                    {
                        new_point[i] = random_point[j];
                    }
                }
            }
            List <Point> list = new_point.ToList();

            for (int i = 0; i < new_point.Length; i++)
            {
                if (new_point[i] == random_point[thefirstpoint])
                {
                    list.RemoveAt(i);
                }
            }
            final_point = list.ToArray();
            g.DrawLine(pen, final_point[8], random_point[thefirstpoint]);
            g.DrawLine(pen, final_point[0], random_point[thefirstpoint]);
            for (int i = 0; i < list.Count - 2; i++)
            {
                Point  point_a         = list [i];
                Point  point_b         = list [i + 1];
                Point  point_c         = list [i + 2];
                double topointb        = (point_a.X - point_b.X) * (point_c.Y - point_b.Y) - (point_a.Y - point_b.Y) * (point_c.X - point_b.X);
                double tothefirstpoint = (point_a.X - random_point[thefirstpoint].X) * (point_c.Y - random_point[thefirstpoint].Y) - (point_a.Y - random_point[thefirstpoint].Y) * (point_c.X - random_point[thefirstpoint].X);
                if (topointb * tothefirstpoint > 0)//如果在同侧,就将该点从list中去除掉
                {
                    list.RemoveAt(i + 1);
                    i = 0;
                }
            }
            for (int i = 0; i < list.Count - 1; i++)//根据list中剩余的点依次画出凸闭包
            {
                g.DrawLine(pen, list[i], list[i + 1]);
            }
        }
Ejemplo n.º 29
0
 public DirectedGraph(Point[] points)
     : this()
 {
     Vertices = points.ToList();
     BuildEdges();
 }
Ejemplo n.º 30
0
        private List<Point> ConvertCorner(Point ptCorner, Corner corner, bool bLeftToRight)
        {
            Dictionary<string, Point> news = new Dictionary<string, Point>(4);
            news.Add("top", new Point(ptCorner.X, ptCorner.Y - CornerGap));
            news.Add("bottom", new Point(ptCorner.X, ptCorner.Y + CornerGap));
            news.Add("left", new Point(ptCorner.X - CornerGap, ptCorner.Y));
            news.Add("right", new Point(ptCorner.X + CornerGap, ptCorner.Y));

            Point[] retConner = new Point[2];

            switch (corner)
            {
                case Corner.LeftTop:
                    retConner[0] = news["left"];
                    retConner[1] = news["top"];
                    break;
                case Corner.RightTop:
                    retConner[0] = news["top"];
                    retConner[1] = news["right"];
                    break;
                case Corner.RightBottom:
                    retConner[0] = news["bottom"];
                    retConner[1] = news["right"];
                    break;
                case Corner.LeftBottom:
                    retConner[0] = news["left"];
                    retConner[1] = news["bottom"];
                    break;
                default:
                    return null;
            }

            if (!bLeftToRight)
                Swap(ref retConner[0], ref retConner[1]);

            return retConner.ToList();
        }