Пример #1
0
        public void DoOperationOnNonRunningGameShouldReturnEmptyList()
        {
            var field = new Field(_size);

            field.DoOperation(new PointI(0, 0), FieldMode.Open);
            for (var x = 0; x < _size.X; x++)
            {
                for (var y = 0; y < _size.Y; y++)
                {
                    if (field.Cells[x, y].Value != CellValue.Mine)
                    {
                        field.DoOperation(new PointI(x, y), FieldMode.Open);
                    }
                }
            }

            field.GameStatus.Should().Be(GameStatus.Won);
            var minePoint = default(PointI);

            for (var x = 0; x < _size.X; x++)
            {
                for (var y = 0; y < _size.Y; y++)
                {
                    if (field.Cells[x, y].Value == CellValue.Mine)
                    {
                        minePoint = new PointI(x, y);
                    }
                }
            }

            field.DoOperation(minePoint, FieldMode.Open).Should().BeEmpty();
        }
Пример #2
0
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics graphics = e.Graphics;

            //  Draw AdditionLogos before foreground render
            if (!Canvas.ShouldDrawBackground)
            {
                DrawAdditionLogos(graphics);
            }


            //
            m_FPSCounter.Tick();

            if (m_IntervalTimer.IsTimeOver)
            {
                m_ExamplesHolder.FPS = FPS;
            }


            base.OnPaint(e);


            //  Need to process system redraw needs (like window overlapping etc.)
            if (Size != SizeI.Empty)
            {
                //  Draw Main Logo
                Bitmap logo     = GUI.Config.Logo;
                RectI  logoRect = m_ExamplesHolder.LogoArea;
                PointI logoPos  = new PointI(logoRect.Right - logo.PixelWidth - 10, logoRect.Top + 15);
                graphics.DrawImage(logo, logoPos);
            }
        }
Пример #3
0
        /// <summary>
        /// Handles the <see cref="UIElement.MouseDown"/> event for the hosted <see
        /// cref="MapView"/>.</summary>
        /// <param name="sender">
        /// The <see cref="Object"/> where the event handler is attached.</param>
        /// <param name="args">
        /// A <see cref="MouseButtonEventArgs"/> object containing event data.</param>
        /// <remarks><para>
        /// <b>OnMapMouseDown</b> changes the selected <see cref="Site"/> on left button clicks and
        /// selects the corresponding item in the "Site" list view if it exists.
        /// </para><para>
        /// Left clicks outside the map area deselect the currently selected <see cref="Site"/> and
        /// the selected item in the "Site" list view instead.</para></remarks>

        private void OnMapMouseDown(object sender, MouseButtonEventArgs args)
        {
            args.Handled = true;

            // left mouse button moves selection
            if (args.ChangedButton == MouseButton.Left)
            {
                // select site clicked on, if any
                PointI site = this._mapView.MouseToSite(args);
                this._mapView.SelectedSite = site;

                // clear list view selection
                SiteList.SelectedIndex = -1;
                if (site == Site.InvalidLocation)
                {
                    return;
                }

                // select corresponding item in Site list view
                for (int i = 0; i < SiteList.Items.Count; i++)
                {
                    SiteListItem item = (SiteListItem)SiteList.Items[i];

                    if (item.Item3 == site)
                    {
                        SiteList.SelectedIndex = i;
                        SiteList.ScrollIntoView(item);
                        break;
                    }
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Clips the bounds of an image tile to the specified display location and clipping region.
        /// </summary>
        /// <param name="dest"><para>
        /// On input, the location within the entire <see cref="MapView"/> where the upper-left
        /// corner of an image tile should appear.
        /// </para><para>
        /// On output, the location within and relative to the specified <paramref name="region"/>
        /// where the upper-left corner of the returned image tile portion should be drawn.
        /// </para></param>
        /// <param name="region"><para>
        /// On input, the display region within the entire <see cref="MapView"/> to which drawing is
        /// clipped.
        /// </para><para>
        /// On output, the portion of the image tile that should be drawn at the adjusted <paramref
        /// name="dest"/> location when returning <c>true</c>; otherwise, unchanged.</para></param>
        /// <returns>
        /// <c>true</c> if <paramref name="region"/> contains the portion of the image tile to draw;
        /// <c>false</c> if nothing should be drawn.</returns>
        /// <remarks>
        /// The specified <paramref name="region"/> should indicate the portion of the entire <see
        /// cref="MapView"/> that is covered by the current contents of the paint buffer.</remarks>

        private bool ClipTile(ref PointI dest, ref RectI region)
        {
            // shift destination to clipping region
            dest -= region.Location;

            /*
             * We draw at most the area of one image tile. If the destination
             * is negative, we actually draw only the lower and/or right part
             * of an image tile, and reduce the returned bounds accordingly.
             */

            // negative offset to clipping region
            PointI neg = new PointI(Math.Max(0, -dest.X), Math.Max(0, -dest.Y));

            // reduce destination to positive offset
            dest = new PointI(Math.Max(0, dest.X), Math.Max(0, dest.Y));

            // clip image tile to destination and clipping region
            int width  = Math.Min(MapView.TileWidth - neg.X, region.Width - dest.X);
            int height = Math.Min(MapView.TileHeight - neg.Y, region.Height - dest.Y);

            // check if there is anything to draw
            if (width <= 0 || height <= 0)
            {
                return(false);
            }
            region = new RectI(neg.X, neg.Y, width, height);
            return(true);
        }
Пример #5
0
        /// <summary>
        /// Draws an image frame that is centered within, masked and outlined by the specified <see
        /// cref="RegularPolygon"/>.</summary>
        /// <param name="context">
        /// The <see cref="DrawingContext"/> for the drawing.</param>
        /// <param name="brush">
        /// The <see cref="Brush"/> used to draw the <paramref name="polygon"/> outline.</param>
        /// <param name="target">
        /// The region within <paramref name="context"/> on which the copied image frame is
        /// centered.</param>
        /// <param name="sourceBitmap">
        /// A <see cref="WriteableBitmap"/> containing the image frame to copy.</param>
        /// <param name="source">
        /// The region within <paramref name="sourceBitmap"/> that covers the image frame to copy.
        /// </param>
        /// <param name="polygon">
        /// The <see cref="RegularPolygon"/> whose <see cref="RegularPolygon.Vertices"/> provide the
        /// clipping region and outline for the copied frame.</param>
        /// <param name="scalingX">
        /// An <see cref="ImageScaling"/> value indicating the horizontal scaling of the <paramref
        /// name="source"/> region to fit the specified <paramref name="polygon"/>.</param>
        /// <param name="scalingY">
        /// An <see cref="ImageScaling"/> value indicating the vertical scaling of the <paramref
        /// name="source"/> region to fit the specified <paramref name="polygon"/>.</param>
        /// <param name="colorShift">
        /// An optional <see cref="ColorVector"/> applied to all pixels within the drawing. Specify
        /// <see cref="ColorVector.Empty"/> if colors should remain unchanged.</param>
        /// <param name="offset">
        /// An optional pixel offset that is added to the centered location within the <paramref
        /// name="target"/> region.</param>
        /// <param name="scalingVector">
        /// An optional scaling vector that is applied to the transformation matrix of the specified
        /// <paramref name="context"/> object. Specify <see cref="PointI.Empty"/> if no scaling
        /// vector should be applied.</param>
        /// <returns>
        /// <c>true</c> if <see cref="CheckFrame"/> succeeded with the specified arguments;
        /// otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> or <paramref name="polygon"/> is a null reference.
        /// </exception>
        /// <remarks>
        /// <b>DrawOutlineFrame</b> always masks off the specified <paramref name="context"/> with
        /// the specified <paramref name="polygon"/>, and superimposes its outline on the drawn
        /// frame using the specified <paramref name="brush"/>.</remarks>

        public static bool DrawOutlineFrame(DrawingContext context,
                                            Brush brush, Rect target, WriteableBitmap sourceBitmap, RectI source,
                                            RegularPolygon polygon, ImageScaling scalingX, ImageScaling scalingY,
                                            ColorVector colorShift, PointI offset, PointI scalingVector)
        {
            // check drawing parameters
            if (!CheckFrame(sourceBitmap, source, polygon))
            {
                return(false);
            }

            // compute frame bounds centered on target region
            RectD frameTarget = new RectD(
                target.X + (target.Width - polygon.Bounds.Width) / 2.0,
                target.Y + (target.Height - polygon.Bounds.Height) / 2.0,
                polygon.Bounds.Width, polygon.Bounds.Height);

            // mask off region outside polygon outline
            MaskOutline(context, target, polygon);

            // draw frame with specified display parameters
            DrawFrame(null, context, frameTarget, sourceBitmap, source,
                      scalingX, scalingY, colorShift, offset, scalingVector);

            // draw polygon outline around frame
            context.Pop();
            DrawOutline(context, brush, target, polygon);

            return(true);
        }
Пример #6
0
        static int currentY;//0-based

        static public void MoveNext()
        {
            if (b1stTime)
            {
                b1stTime = false;
                curr.x   = currentX + 1;
                curr.y   = currentY + 1;
                mainBoard.SetIndex(curr, 1);
                writexyC(curr, 1, true);//highlight color
                IsAlive = true;
                return;
            }

            int poss_num   = mainBoard.GetPossibleMovesCount(curr);
            int boardindex = mainBoard.GetIndex(curr);

            if (poss_num != 0 && boardindex <= 64)
            {
                writexyC(curr, boardindex, false);   //reset color
                mainBoard.UpdateAccessibility(curr); //update current position accessibility

                curr = mainBoard.DetermineNextMove(curr);
                mainBoard.SetIndex(curr, ++boardindex);
                writexyC(curr, boardindex, true);//highlight color

                if (boardindex == 64)
                {
                    IsAlive = false;
                }
            }
            else
            {
                IsAlive = false;
            }
        }
Пример #7
0
        internal CitizenView(string name, Vector2 position, Alignment positionAlignment, SettlementView settlementView, string textureAtlas) :
            base(name)
        {
            Size = new PointI(100, 30);
            PositionAlignment = positionAlignment;
            Position          = position.ToPointI();

            SettlementView = settlementView;

            var kvps = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("position1", $"{Convert.ToInt32(position.X + Bounds.X)};{Convert.ToInt32(position.Y + Bounds.Y)}"),
                new KeyValuePair <string, string>("position2", $"{Convert.ToInt32(position.X + Bounds.X + 20)};{Convert.ToInt32(position.Y + Bounds.Y)}"),
                new KeyValuePair <string, string>("position3", $"{Convert.ToInt32(position.X + Bounds.X)};{Convert.ToInt32(position.Y + Bounds.Y + 30)}"),
                new KeyValuePair <string, string>("position4", $"{Convert.ToInt32(position.X + Bounds.X + 20)};{Convert.ToInt32(position.Y + Bounds.Y + 30)}"),
                new KeyValuePair <string, string>("textureName1", $"{textureAtlas}.Citizen_{settlementView.Settlement.Race.Name}_Farmer"),
                new KeyValuePair <string, string>("textureName2", $"{textureAtlas}.Citizen_{settlementView.Settlement.Race.Name}_Worker"),
                new KeyValuePair <string, string>("textureName3", $"{textureAtlas}.Citizen_{settlementView.Settlement.Race.Name}_Rebel")
            };

            var spec = ResourceReader.ReadResource("PhoenixGamePresentation.Views.SettlementViewComposite.CitizenViewControls.txt", Assembly.GetExecutingAssembly());

            Controls = ControlCreator.CreateFromSpecification(spec, kvps);
            Controls.SetOwner(this);
        }
Пример #8
0
        /// <summary>
        /// Calculate the distance between two points.
        /// </summary>
        /// <param name="p1">
        /// The first point.
        /// </param>
        /// <param name="p2">
        /// The second point.
        /// </param>
        /// <returns>
        /// The distance.
        /// </returns>
        public static double DistanceTo(PointI p1, PointI p2)
        {
            double dx = p1.X - p2.X;
            double dy = p1.Y - p2.Y;

            return(Math.Sqrt((dx * dx) + (dy * dy)));
        }
Пример #9
0
        /// <summary>
        /// On scene load.
        /// </summary>
        protected override void Load()
        {
            // set assets root and load config
            if (IsFirstScene)
            {
                Assets.AssetsRoot = "../../../../TestAssets";
                Game.LoadConfig("config.ini");
            }

            // load assets
            _cursor    = Assets.LoadImage("gfx/cursor.png", ImageFilterMode.Nearest);
            _treeImage = Assets.LoadImage("gfx/tree.png", ImageFilterMode.Nearest);
            _dirtImage = Assets.LoadImage("gfx/dirt.png", ImageFilterMode.Nearest);
            _font      = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 22, false);
            _fontBig   = Assets.LoadFont("gfx/OpenSans-Regular.ttf", 42, false);

            // get window size
            _windowSize = Gfx.WindowSize;

            // create empty texture to draw on
            _targetTexture = Assets.CreateEmptyImage(_windowSize);

            // create trees
            for (var i = 0; i < 55; ++i)
            {
                CreateTestSprite();
            }

            // sort trees by y position so it will look like there's depth
            _sprites.Sort((Sprite a, Sprite b) => (int)(a.Position.Y - b.Position.Y));
        }
Пример #10
0
        /// <summary>
        /// Shows projected losses for attacking and defending units.</summary>
        /// <param name="target">
        /// The coordinates of the <see cref="Site"/> that is the target of the attack.</param>
        /// <remarks><para>
        /// <b>ShowLosses</b> invokes <see cref="Unit.EstimateLosses"/> with all selected units and
        /// updates the "Projected Losses" message with the resulting percentage losses.
        /// </para><para>
        /// <b>ShowLosses</b> shows two zeroes if no units are selected, and a notification if the
        /// specified <paramref name="target"/> is an invalid map location.</para></remarks>

        private void ShowLosses(PointI target)
        {
            // show notification for invalid selection
            if (!this._mapView.InSelectedRegion(target))
            {
                LossesInfo.Visibility     = Visibility.Collapsed;
                LossesInfoNone.Visibility = Visibility.Visible;
                return;
            }

            CombatResults results = new CombatResults();

            LossesInfo.Visibility     = Visibility.Visible;
            LossesInfoNone.Visibility = Visibility.Collapsed;

            // compute estimated combat losses
            if (this._selected.Count > 0)
            {
                Unit unit = (Unit)this._selected[0];
                results = unit.EstimateLosses(
                    Session.Instance.WorldState, this._selected, target, true);
            }

            // show attacker & defender losses
            LossesInfo.Content = String.Format(ApplicationInfo.Culture,
                                               this._lossesFormat, results.AttackerPercent, results.DefenderPercent);
        }
Пример #11
0
        internal void MoveTo(PointI locationToMoveTo)
        {
            var world = CallContext <World> .GetData("GameWorld");

            var cellToMoveTo = world.OverlandMap.CellGrid.GetCell(locationToMoveTo);
            var movementCost = Helpers.MovementCosts.GetCostToMoveInto(cellToMoveTo, MovementTypes, MovementPoints);

            foreach (var unit in Units)
            {
                var updatedStack = new StackRecord(_stackRecord, new LocationHex(locationToMoveTo));
                _gameDataRepository.Update(updatedStack);
                unit.SetSeenCells(LocationHex);

                //var newMovementPoints = unit.MovementPoints - movementCost.CostToMoveInto;
                //var unitRecord = gameDataRepository.GetUnitById(unit.Id);
                //var updatedUnit = new UnitRecord(updatedUnit, updatedUnit.Stackid, newMovementPoints);
                //gameDataRepository.Update(updatedUnit);
                //if (unit.MovementPoints <= 0.0f)
                //{
                //    unit.MovementPoints = 0.0f;
                //    updatedStack = new StackRecord(_stackRecord, _stackRecord.LocationHex, _stackRecord.Status, true);
                //    gameDataRepository.Update(updatedStack);
                //}
            }
        }
Пример #12
0
        internal void HandleMouseMove(MouseEventArgs args)
        {
            // determine element at cursor
            Point cursor = args.GetPosition(this);

            cursor = new Point(cursor.X - _border.Width, cursor.Y - _border.Height);
            PointI element = PolygonGridTest.Instance.Grid.DisplayToGrid(cursor.X, cursor.Y);

            // quit if current element unchanged
            if (_showElement == element)
            {
                return;
            }

            // show current element coordinates
            PolygonGridTest.Instance.CursorBox.Text = String.Format(
                CultureInfo.CurrentCulture, "{0},{1}", element.X, element.Y);

            // clear old element, neighbors & distances
            if (_showElement != PolygonGrid.InvalidLocation)
            {
                _showDistances = false;
                _showNeighbors = 0;
            }

            // highlight current element
            _showElement = element;
            InvalidateVisual();
        }
Пример #13
0
        private void DrawElement(DrawingContext dc,
                                 PointI element, Brush brush, int distance)
        {
            // translate origin to center of current polygon
            PolygonGridTest dialog = PolygonGridTest.Instance;
            PointD          center = dialog.Grid.GridToDisplay(element);

            dc.PushTransform(new TranslateTransform(center.X, center.Y));

            // draw inset polygon with specified brush
            if (brush != null)
            {
                dc.DrawGeometry(brush, new Pen(Brushes.Black, 1), dialog.InsetGeometry);
            }

            // draw distance if desired
            if (distance > 0)
            {
                Typeface typeface = dialog.FontFamily.GetTypefaces().ElementAt(0);

                FormattedText text = new FormattedText(distance.ToString(),
                                                       CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight,
                                                       typeface, dialog.FontSize, Brushes.Black);

                dc.DrawText(text, new Point(-text.Width / 2.0, -text.Height / 2.0));
            }

            dc.Pop();
        }
Пример #14
0
        /// <summary>
        /// Handles the <see cref="UIElement.MouseDown"/> event for the hosted <see
        /// cref="MapView"/>.</summary>
        /// <param name="sender">
        /// The <see cref="Object"/> where the event handler is attached.</param>
        /// <param name="args">
        /// A <see cref="MouseButtonEventArgs"/> object containing event data.</param>
        /// <remarks><para>
        /// <b>OnMapMouseDown</b> performs the following actions, depending on the specified
        /// <paramref name="args"/>:
        /// </para><list type="bullet"><item>
        /// On <see cref="MouseButton.Left"/> clicks, change the <see
        /// cref="Graphics.MapView.SelectedSite"/> to the clicked site, if valid; otherwise, to <see
        /// cref="Site.InvalidLocation"/>.
        /// </item><item>
        /// On double <see cref="MouseButton.Left"/> clicks, display the "Terrain" tab page of a
        /// <see cref="Dialog.ChangeSite"/> dialog.
        /// </item><item>
        /// On <see cref="MouseButton.Right"/> clicks, display the "Other" tab page of a <see
        /// cref="Dialog.ChangeSite"/> dialog.
        /// </item><item>
        /// On <see cref="MouseButton.Middle"/> clicks, forward to <see
        /// cref="MainWindow.OnMapMouseDown"/>.</item></list></remarks>

        private void OnMapMouseDown(object sender, MouseButtonEventArgs args)
        {
            args.Handled = true;
            if (MapView == null)
            {
                return;
            }

            switch (args.ChangedButton)
            {
            case MouseButton.Left:
            case MouseButton.Right:

                // select site clicked on, if any
                PointI site = MapView.MouseToSite(args);
                SetSelection(site, false);

                if (args.ChangedButton == MouseButton.Right)
                {
                    // change non-terrain stacks on right-click
                    OnChangeSite(ChangeSiteButton, new EventArgs <Boolean>(true));
                }
                else if (args.ClickCount >= 2)
                {
                    // change terrain stack on left double-click
                    OnChangeSite(ChangeSiteButton, new EventArgs <Boolean>(false));
                }
                break;

            case MouseButton.Middle:
                // let main window handle zooming
                MainWindow.Instance.OnMapMouseDown(sender, args);
                break;
            }
        }
Пример #15
0
        /// <summary>
        /// 计算(R-P)和(Q-P)的叉积
        /// </summary>
        /// <param name="P">点P</param>
        /// <param name="Q">点Q</param>
        /// <param name="R">点R</param>
        /// <returns>返回叉积值</returns>
        /// <remarks>
        /// 返回值 大于0 R在矢量PQ的逆时针方向
        /// 返回值 等于0 R,P,Q 三点共线
        /// 返回值 小于0 R在矢量PQ的顺时针方向
        /// </remarks>
        public static Int32 Multiple(PointI P, PointI Q, PointI R)
        {
            PointI RP = PointAlgorithm.Substract(R, P); //R-P
            PointI QP = PointAlgorithm.Substract(Q, P); //Q-P

            return(PointAlgorithm.Multiple(RP, QP));
        }
Пример #16
0
        /// <summary>
        /// Finds the total range of values for the specified <see cref="VariableClass"/> across all
        /// map sites.</summary>
        /// <param name="variable">
        /// The <see cref="VariableClass"/> whose values to examine.</param>
        /// <param name="sample">
        /// A current sample value for the specified <paramref name="variable"/>.</param>
        /// <remarks>
        /// <b>FindValueRange</b> separately determines the minimum and maximum for both the basic
        /// and modifier values of the specified <paramref name="variable"/>. Before returning
        /// <b>FindValueRange</b> clears the <see cref="ValueRangeChanged"/> flag.</remarks>

        private void FindValueRange(VariableClass variable, PointI sample)
        {
            int minX = sample.X, maxX = sample.X;
            int minY = sample.Y, maxY = sample.Y;

            WorldState world = this._renderer.MapView.WorldState;

            foreach (Site site in world.Sites)
            {
                PointI value = site.AddVariables(world, variable);

                if (minX > value.X)
                {
                    minX = value.X;
                }
                if (minY > value.Y)
                {
                    minY = value.Y;
                }
                if (maxX < value.X)
                {
                    maxX = value.X;
                }
                if (maxY < value.Y)
                {
                    maxY = value.Y;
                }
            }

            this._minimum     = new PointI(minX, minY);
            this._maximum     = new PointI(maxX, maxY);
            ValueRangeChanged = false;
        }
Пример #17
0
 public override void _Process(float delta)
 {
     if (shouldCalcNew && ((int)walkedDistance < (int)(walkedDistance + delta * MovementSpeed) || path == null))
     {
         shouldCalcNew = false;
         float  gridSize = this.grid3d.GetGridSize();
         PointI nextGrid = new PointI((int)(Translation.x / gridSize), (int)(Translation.z / gridSize));
         if (pathFinder.FindPath(out points, nextGrid))
         {
             if (points.Length > 1)
             {
                 path = new SplinePath(points, grid3d.GetGridSize(), InterpolationType.Qubic);
             }
             Blocked = false;
             exclamationInst.Visible = false;
         }
         else
         {
             Blocked                 = true;
             path                    = null;
             walkedDistance          = 0;
             exclamationInst.Visible = true;
         }
         walkedDistance = 0;
     }
     if (path != null)
     {
         Vector2 pos = path.GetPoint(walkedDistance);
         walkedDistance  += delta * MovementSpeed;
         this.Translation = new Vector3(pos.x, 0, pos.y);
     }
 }
Пример #18
0
        // Finding obstacles
        PointI GetObstacle(PointI Start, Bitmap Map, int Inc, int AngleOffset)
        {
            PointI p = new PointI(Start.X, Start.Y);

            double rad    = ((Angle + 90 + AngleOffset) * Math.PI) / 180;
            int    IncX   = 0;
            int    IncY   = 0;
            int    Offset = 0;

            while ((p.X + IncX >= 0) && (p.X + IncX < Map.PixelWidth) && (p.Y + IncY >= 0) && (p.Y + IncY < Map.PixelHeight))
            {
                Color Map_GetPixel = Map.GetPixel(p.X + IncX, p.Y + IncY);
                if ((Map_GetPixel.R == 0) && (Map_GetPixel.G == 0) && (Map_GetPixel.B == 0))
                {
                    break;
                }
                Offset += Inc;
                IncX    = Convert.ToInt32(Offset * Math.Cos(rad));
                IncY    = Convert.ToInt32(Offset * Math.Sin(rad));
            }
            p.X += IncX;
            p.Y += IncY;

            return(p);
        }
Пример #19
0
        internal static (bool startMovement, PointI hexToMoveTo) CheckForUnitMovementFromKeyboardInitiation(Stack stack, object args)
        {
            var key = (Keys)args;

            var direction = key switch
            {
                Keys.NumPad1 => Direction.SouthWest,
                Keys.NumPad2 => Direction.South,
                Keys.NumPad3 => Direction.SouthEast,
                Keys.NumPad4 => Direction.West,
                Keys.NumPad6 => Direction.East,
                Keys.NumPad7 => Direction.NorthWest,
                Keys.NumPad8 => Direction.North,
                Keys.NumPad9 => Direction.NorthEast,
                _ => throw new ArgumentOutOfRangeException()
            };

            var neighbor    = HexLibrary.GetNeighbor(new HexOffsetCoordinates(stack.LocationHex.X, stack.LocationHex.Y), direction);
            var hexToMoveTo = new PointI(neighbor.Col, neighbor.Row);

            if (stack.LocationHex == hexToMoveTo)
            {
                return(false, new PointI(0, 0));
            }

            var costToMoveIntoResult = MovementCosts.GetCostToMoveInto(hexToMoveTo, stack.MovementTypes, stack.MovementPoints);

            return(costToMoveIntoResult.CanMoveInto ? (true, hexToMoveTo) : (false, new PointI(0, 0)));
        }
 public RectI(PointI pos, SizeI size) : this(IronSightEnginePINVOKE.new_RectI__SWIG_3(PointI.getCPtr(pos), SizeI.getCPtr(size)), true)
 {
     if (IronSightEnginePINVOKE.SWIGPendingException.Pending)
     {
         throw IronSightEnginePINVOKE.SWIGPendingException.Retrieve();
     }
 }
Пример #21
0
        private Block DeterminateOre(PointB point, PointI chunkPosition)
        {
            const float coeff      = 0.9f;
            var         noiseValue = Get3DNoise(
                point.X * coeff + chunkPosition.X * Chunk <Block> .XLength,
                point.Y * coeff,
                point.Z * coeff + chunkPosition.Z * Chunk <Block> .ZLength);

            if (noiseValue >= 0.7 && noiseValue < 0.72)
            {
                return(new Block(BaseBlocks.CoalOre, point));
            }

            if (noiseValue >= 0.01 && noiseValue < 0.015 && point.Y <= 60)
            {
                return(new Block(BaseBlocks.GoldOre, point));
            }

            if (noiseValue >= 0.8 && noiseValue < 0.82)
            {
                return(new Block(BaseBlocks.IronOre, point));
            }

            if (noiseValue >= -0.307 && noiseValue < -0.3 && point.Y <= 35)
            {
                return(new Block(BaseBlocks.DiamondOre, point));
            }

            return(null);
        }
Пример #22
0
        internal CommodityView(Vector2 position, Alignment positionAlignment, SettlementView settlementView, string imageTextureName1, string imageTextureName2, string name) :
            base(name)
        {
            Size = new PointI(100, 30);
            PositionAlignment = positionAlignment;
            Position          = position.ToPointI();

            SettlementView = settlementView;

            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("textureName1", $"Icons_1.{imageTextureName1}"),
                new KeyValuePair <string, string>("textureName2", $"Icons_1.{imageTextureName2}")
            };

            Controls = ControlCreator.CreateFromSpecification(
                @"
image1 : Image
{
  TextureNormal: '%textureName1%'
  Size: [30;30]
}

image2 : Image
{
  TextureNormal: '%textureName2%'
  Size: [20;20]
}", pairs);
            Controls.SetOwner(this);
        }
Пример #23
0
 /// <summary>
 /// 计算点P-Q的值
 /// </summary>
 /// <param name="P">点P</param>
 /// <param name="Q">点Q</param>
 /// <returns>返回P-Q的值</returns>
 public static PointI Substract(PointI P, PointI Q)
 {
     //formula
     //x1-x2,y1-y2
     //P - Q = ( x1 - x2 , y1 - y2 )
     return(new PointI(P.X - Q.X, P.Y - Q.Y));
 }
Пример #24
0
        internal static (bool startMovement, PointI hexToMoveTo) CheckForUnitMovementFromMouseInitiation(Stack stack, object args)
        {
            var(cellGrid, mouseLocation, camera) = (ValueTuple <CellGrid, Point, Camera>)args;

            if (!camera.GetViewport.Contains(mouseLocation))
            {
                return(false, new PointI(0, 0));
            }

            var screenPixelToWorldHex = camera.ScreenPixelToWorldHex(mouseLocation);
            var hexToMoveTo           = new PointI(screenPixelToWorldHex.Col, screenPixelToWorldHex.Row);

            if (hexToMoveTo.Equals(stack.LocationHex))
            {
                return(false, new PointI(0, 0));
            }
            var cellToMoveTo = cellGrid.GetCell(hexToMoveTo);

            if (cellToMoveTo.SeenState == SeenState.NeverSeen)
            {
                return(false, new PointI(0, 0));
            }

            var costToMoveIntoResult = MovementCosts.GetCostToMoveInto(cellToMoveTo, stack.MovementTypes, stack.MovementPoints);

            return(costToMoveIntoResult.CanMoveInto ? (true, hexToMoveTo) : (false, new PointI(0, 0)));
        }
Пример #25
0
        public TextPatternRange RangeFromPoint(PointI screenLocation)
        {
            var    num = (int)ActionHandler.Invoke(sender: UIObject, actionInfo: ActionEventArgs.GetDefault(action: "WaitForReady"));
            object overridden;

            return(ActionHandler.Invoke(sender: UIObject, actionInfo: new ActionEventArgs(action: nameof(RangeFromPoint), screenLocation), overridden: out overridden) == ActionResult.Handled ? (TextPatternRange)overridden : Pattern.RangeFromPoint(screenLocation: new Point(x: screenLocation.X, y: screenLocation.Y)));
        }
        protected override void OnMouseMove(MouseMoveEventArgs e)
        {
            base.OnMouseMove(e);

            PointI mp = new PointI(e.X, e.Y);

            int xrel = mp.X - Video.LastMousePosition.X;
            int yrel = mp.Y - Video.LastMousePosition.Y;

            if (Video.video_get_grab() == 1)
            {
                if (mp == Video.LastMousePosition)
                {
                    return;
                }

                xrel = e.XDelta;
                yrel = e.YDelta;
            }

            Video.LastMousePosition = mp;

            State.st_point(+mp.X,
                           -mp.Y + Config.config_get_d(Config.CONFIG_HEIGHT),
                           +xrel,
                           Config.config_get_d(Config.CONFIG_MOUSE_INVERT) != 0
                     ? +yrel : -yrel);

            if (Video.video_get_grab() == 1)
            {
                Video.CenterMousePosition();
            }
        }
Пример #27
0
        /// <summary>
        /// Selects the specified map location in the map view and shows its data in the "Site" <see
        /// cref="GroupBox"/>.</summary>
        /// <param name="location">
        /// The coordinates of the <see cref="Site"/> to select.</param>
        /// <param name="isPlace">
        /// <c>true</c> if the "Site" <see cref="ListView"/> contains a <see cref="SiteListItem"/>
        /// for the specified <paramref name="location"/>; otherwise, <c>false</c>.</param>
        /// <remarks><para>
        /// <b>SelectSite</b> enables or disables the controls related to the selected <see
        /// cref="Site"/>, depending on the specified arguments.
        /// </para><para>
        /// <b>SelectSite</b> also centers the <see cref="MapView"/> on the specified <paramref
        /// name="location"/> if <paramref name="isPlace"/> is <c>true</c>.</para></remarks>

        private void SelectSite(PointI location, bool isPlace)
        {
            // (de)select site in map view
            if (isPlace)
            {
                this._mapView.CenterAndSelect(location);
            }
            else
            {
                this._mapView.SelectedSite = location;
            }

            // show coordinates in Site group box
            Site site = this._mapView.WorldState.GetSite(location);

            SiteGroup.IsEnabled = (site != null);
            SiteGroup.Header    = Site.FormatLabel(location);

            // show site owner in Owner text box
            if (site == null || site.Owner == null)
            {
                OwnerBox.Text = Global.Strings.LabelOwnerNone;
            }
            else
            {
                OwnerBox.Text = site.Owner.Id;
            }

            // enable or disable Capture check box
            CaptureToggle.IsChecked = (site != null && site.CanCapture);

            // enable or disable Add/Remove buttons
            AddSiteButton.IsEnabled    = (site != null && !isPlace);
            RemoveSiteButton.IsEnabled = (site != null && isPlace);
        }
Пример #28
0
        /// <summary>
        /// 点是否在区域内
        /// </summary>
        /// <param name="Rect">矩形区域</param>
        /// <param name="P">点P</param>
        /// <returns>
        /// 返回True表示点P在区域内,返回False则不在区域内.
        /// </returns>
        public static Boolean InRectangle(RectangleI Rect, PointI P)
        {
            MinMax <Int32> MX = new MinMax <Int32>(Rect.Left, Rect.Right);
            MinMax <Int32> MY = new MinMax <Int32>(Rect.Top, Rect.Bottom);

            return(MX.InRange(P.X) && MY.InRange(P.Y));
        }
Пример #29
0
        public Cell GetClosestUnexploredCell(PointI location)
        {
            var closestCells = new List <Cell>();
            var max          = Math.Max(NumberOfColumns, NumberOfRows);

            for (int i = 1; i < max; i++)
            {
                var world = CallContext <World> .GetData("GameWorld");

                var ring = world.HexLibrary.GetSingleRing(new HexOffsetCoordinates(location.X, location.Y), i);
                foreach (var coordinates in ring)
                {
                    var cell = GetCell(coordinates.Col, coordinates.Row);
                    if (!cell.Equals(Cell.Empty) && cell.SeenState == SeenState.NeverSeen)
                    {
                        closestCells.Add(cell);
                    }
                }

                if (closestCells.Count > 0)
                {
                    break;
                }
            }

            if (closestCells.Count == 0)
            {
                return(Cell.Empty);
            }

            var random = RandomNumberGenerator.Instance.GetRandomInt(0, closestCells.Count - 1);

            return(closestCells[random]);
        }
Пример #30
0
        private bool CanSettleOnTerrain(PointI thisLocationHex)
        {
            // if terrain is settle-able
            var world = CallContext <World> .GetData("GameWorld");

            var cell    = world.OverlandMap.CellGrid.GetCell(thisLocationHex);
            var terrain = _gameConfigCache.GetTerrainConfigById(cell.TerrainId);

            if (!terrain.CanSettleOn)
            {
                return(false);
            }

            // and not within 4 distance from another settlement
            var settlements = world.Settlements;

            foreach (var settlement in settlements)
            {
                var distance = world.HexLibrary.GetDistance(new HexOffsetCoordinates(thisLocationHex.X, thisLocationHex.Y), new HexOffsetCoordinates(settlement.Location.X, settlement.Location.Y));
                if (distance >= 4)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #31
0
        /// <summary>
        /// ワールドマップ初期化
        /// </summary>
        /// <param name="mapFname">ワールドBMPファイル名</param>
        public WorldMap( string mapFname )
        {
            WldOffset = new PointI();
            AreaGridSize = new SizeI();
            mapBmp = new Bitmap(mapFname);

            WorldSize.w = mapBmp.Width;
            WorldSize.h = mapBmp.Height;
        }
Пример #32
0
        public void Interact(EntityBase entity, StructBlock block)
        {
            Player player = entity as Player;
            if (player == null)
                return;
            if (player.CurrentInterface != null)
                return;

            if (!block.World.BlockHelper.Instance(block.World.GetBlockId(block.X, block.Y, block.Z)).IsAir)
            {
                // Cannot open a chest if no space is above it
                return;
            }

            Chunk chunk = player.World.GetBlockChunk(block.X, block.Y, block.Z);

            // Double chest?
            // TODO: simplify chunk API so that no bit shifting is required
            if (chunk.IsNSEWTo(block.X & 0xf, block.Y, block.Z & 0xf, block.Type))
            {
                // Is this chest the "North or East", or the "South or West"
                BlockData.Blocks[] nsewBlocks = new BlockData.Blocks[4];
                PointI[] nsewBlockPositions = new PointI[4];
                int nsewCount = 0;
                chunk.ForNSEW(block.X & 0xf, block.Y, block.Z & 0xf, (x1, y1, z1) =>
                {
                    nsewBlocks[nsewCount] = (BlockData.Blocks)block.World.GetBlockId(x1, y1, z1);
                    nsewBlockPositions[nsewCount] = new PointI(x1, y1, z1);
                    nsewCount++;
                });

                if ((byte)nsewBlocks[0] == block.Type) // North
                {
                    player.CurrentInterface = new LargeChestInterface(block.World, nsewBlockPositions[0], new PointI(block.X, block.Y, block.Z));
                }
                else if ((byte)nsewBlocks[2] == block.Type) // East
                {
                    player.CurrentInterface = new LargeChestInterface(block.World, nsewBlockPositions[2], new PointI(block.X, block.Y, block.Z));
                }
                else if ((byte)nsewBlocks[1] == block.Type) // South
                {
                    player.CurrentInterface = new LargeChestInterface(block.World, new PointI(block.X, block.Y, block.Z), nsewBlockPositions[1]);
                }
                else if ((byte)nsewBlocks[3] == block.Type) // West
                {
                    player.CurrentInterface = new LargeChestInterface(block.World, new PointI(block.X, block.Y, block.Z), nsewBlockPositions[3]);
                }
            }
            else
            {
                player.CurrentInterface = new SmallChestInterface(block.World, block.X, block.Y, block.Z);
            }

            player.CurrentInterface.Associate(player);
            player.CurrentInterface.Open();
        }
Пример #33
0
 public static void Region(PointI[] points)
 {
     if (points == null || points.Length < 3) {
         return;
     }
     iluRegioni(points, (uint)points.Length);
 }
Пример #34
0
Файл: G.cs Проект: 0x53A/Mvvm
        public PointI Get(Position preset)
        {
            PointI ret = new PointI() { X = 0, Y = 0 };

            if (preset.Y.HasValue)
            {
                nextRow = preset.Y.Value;
                nextColumn = 0;
            }
            if (preset.X.HasValue)
                nextColumn = preset.X.Value;

            ret = new PointI() { X = nextColumn, Y = nextRow };

            for (int x = 0; x < preset.Width; x++)
                for (int y = 0; y < preset.Height; y++)
                    usedCells[nextColumn + x, nextRow + y] = true;
            MoveNext();
            return ret;
        }
Пример #35
0
 private static void iluRegioni(PointI[] points, uint num)
 {
     _iluRegioni(points, num);
 }
Пример #36
0
 private static extern void iluRegioni_x32(PointI[] points, uint num);
Пример #37
0
    private List<PointI> findSimilarityPatches(PointI cPatchPoint, float[,] pixels, PointI[] subSstackP, int searchRadius, int imgW, int imgH, int L, int LL, int maxStackSize, float maxDistance)
    {
        List<PointI> stackP = new List<PointI>();
        stackP.Add(cPatchPoint);

        List<NumDist> numDist = new List<NumDist>();

        int kkNum = 0;//number of patch in subSstackP associate with distance in numDist

        for (int x = cPatchPoint.X - searchRadius; x < cPatchPoint.X + searchRadius && x <= imgW - L; x++)
        {
            for (int y = cPatchPoint.Y - searchRadius; y < cPatchPoint.Y + searchRadius && y <= imgH - L; y++)
            {
                if (x < 0) x = 0;
                if (y < 0) y = 0;
                if (x == cPatchPoint.X && y == cPatchPoint.Y) continue;

                double distance = 0;

                for (int m = 0; m < L; m++)
                {
                    for (int n = 0; n < L; n++)
                    {
                        double subDistance = (pixels[cPatchPoint.X + m, cPatchPoint.Y + n] - pixels[x + m, y + n]);

                        distance += subDistance * subDistance;
                    }
                }
                distance = distance / LL;
                //take only 'maxStackSize' closest patches
                if (distance < maxDistance)
                {
                    subSstackP[kkNum] = new PointI(x, y);
                    numDist.Add(new NumDist(kkNum++, (float)distance));
                }
            }
        }

        numDist.Sort(comparerNumDist);

        for (int i = 0; i < maxStackSize && i < numDist.Count; i++)
        {
            stackP.Add(subSstackP[numDist[i].Number]);
        }

        return stackP;
    }
Пример #38
0
    private float[,] hosvd(float[,] pixels, int imgW, int imgH, int patchSize, int maxStackSize, double sigma, double reEstimatednoiseVarRoot)
    {
        int P = patchSize;
        int PP = P * P;
        int searchRadius = 15;

        int P2 = P / 2;

        pixWeight[,] pixelsWeights = new pixWeight[imgW, imgH];

        float maxDistance = (float)(3 * sigma * sigma * P * P);

        Parallel.For(0, (imgW - P + 1), new ParallelOptions { MaxDegreeOfParallelism = 4 }, (x) =>
        {
            if (x % P2 != 0)
                if (x != imgW - P) return;

            //using in 'findSimilarityPatches', defenited here to optimize memory usage (reuse array)
            PointI[] subSstackP = new PointI[searchRadius * searchRadius * 4];

            double[,] u1;
            double[,] u2;
            double[,] u3;

            for (int y = 0; y <= imgH - P; y++)
            {
                if (y % P2 != 0)
                    if (y != imgH - P) continue;

                //search similarity to current patch (top right point of each patch)
                List<PointI> simularPatches = findSimilarityPatches(new PointI(x, y), pixels, subSstackP, searchRadius, imgW, imgH, P, PP, maxStackSize, maxDistance);

                int K = simularPatches.Count;
                int KP = K * P;

                HOSVDdecompos(pixels, simularPatches, out u1, out u2, out u3, P, K, KP, PP);

                var tensorCore = CalculateCore(pixels, simularPatches, u1, u2, u3, P, K, KP, PP);

                //apply threshold and take weight, which represent how many noise filtered
                double weight = ApplyThreshold(tensorCore, P, K, reEstimatednoiseVarRoot);

                float[, ,] restoredPatchesArray = RestoreTensor(tensorCore, u1, u2, u3, P, K, KP, PP);

                //this part is need for averaging overlapping patches
                for (int k = 0; k < K; k++)
                {
                    for (int m = 0; m < P; m++)
                    {
                        for (int n = 0; n < P; n++)
                        {
                            int cX = simularPatches[k].X + m;
                            int cY = simularPatches[k].Y + n;

                            pixelsWeights[cX, cY].grayLevel += weight * restoredPatchesArray[k, m, n];
                            pixelsWeights[cX, cY].weight += weight;
                        }
                    }
                }
            }
        });


        float[,] pixelsX1 = new float[imgW, imgH];
        //make average
        for (int x = 0; x < imgW; x++)
        {
            for (int y = 0; y < imgH; y++)
            {
                pixelsX1[x, y] = (float)(pixelsWeights[x, y].grayLevel / pixelsWeights[x, y].weight);
            }
        }

        return pixelsX1;
    }
Пример #39
0
        public override void Place(EntityBase entity, StructBlock block, StructBlock targetBlock, BlockFace face)
        {
            // Load the blocks surrounding the position (NSEW) not diagonals
            BlockData.Blocks[] nsewBlocks = new BlockData.Blocks[4];
            PointI[] nsewBlockPositions = new PointI[4];
            int nsewCount = 0;
            block.Chunk.ForNSEW(block.X & 0xf, block.Y, block.Z & 0xf, (x1, y1, z1) =>
            {
                nsewBlocks[nsewCount] = (BlockData.Blocks)block.World.GetBlockId(x1, y1, z1);
                nsewBlockPositions[nsewCount] = new PointI(x1, y1, z1);
                nsewCount++;
            });

            // Count chests in list
            if (nsewBlocks.Where((b) => b == BlockData.Blocks.Chest).Count() > 1)
            {
                // Cannot place next to two chests
                return;
            }

            for (int i = 0; i < 4; i++)
            {
                PointI p = nsewBlockPositions[i];
                if (nsewBlocks[i] == BlockData.Blocks.Chest && block.Chunk.IsNSEWTo(p.X & 0xf, p.Y, p.Z & 0xf, (byte)BlockData.Blocks.Chest))
                {
                    // Cannot place next to a double chest
                    return;
                }
            }
            base.Place(entity, block, targetBlock, face);
        }