Beispiel #1
0
        static void Main4()
        {
            var BaseImage = new Bitmap(Image.FromFile(@"C:\projects\talestra_tov\Tools\TOWNMAPFOR.U_MAP_EFOR.png"));
            {
                var Graphics2 = Graphics.FromImage(BaseImage);
                Graphics2.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                Graphics2.FillRectangle(new SolidBrush(Color.Transparent), new Rectangle(0, 38, 512, 190));
            }

            var PrivateFontCollection = new PrivateFontCollection();

            PrivateFontCollection.AddFontFile(@"C:\projects\talestra_tov\Fonts\Seagull.ttf");
            var Bitmap   = new Bitmap(512, 512);
            var graphics = Graphics.FromImage(Bitmap);
            var Font1    = new Font(PrivateFontCollection.Families[0].Name, 26, FontStyle.Regular);
            var Font2    = new Font(PrivateFontCollection.Families[0].Name, 40, FontStyle.Regular);

            //graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, 512, 512));
            graphics.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
            graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.TextRenderingHint  = TextRenderingHint.AntiAlias;

            graphics.DrawString("Fuerte de Deidon", Font2, new SolidBrush((ARGB_Rev)"#503c3c"), new PointF(-3, 97));
            //graphics.DrawString("The Imperial Capital", Font1, new SolidBrush((ARGB_Rev)"#503c3c"), new PointF(-2, 35.2f));

            var _DistanceMap = DistanceMap.GetDistanceMap(DistanceMap.GetMask(Bitmap));

            DistanceMap.DrawGlow(Bitmap, _DistanceMap, 6, "#fff0d3", 0.1f);
            graphics.DrawImage(BaseImage, Point.Empty);

            //Bitmap.Save(@"C:\projects\talestra_tov\test.png");
            //Console.WriteLine(.Name);
        }
Beispiel #2
0
        new public PatrolPath getShortestPath(IPoint src, IPoint dest, List <IPoint> availableTiles)
        {
            DistanceMap   distMap            = getDistanceMap(src);
            PatrolPath    reverse            = new PatrolPath();
            valuePoint    vPrevious          = new valuePoint();
            List <IPoint> availableTilesCopy = availableTiles.GetRange(0, availableTiles.Count);

            if (isPointInList(availableTiles, dest))
            {
                //Get last point, add to path,get next, add, etc
                reverse.MyWaypoints.Add(dest);
                vPrevious.p = dest;
                while (!vPrevious.p.equals(src))
                {
                    vPrevious = getPreviousInPath(getValuePoint(distMap.MyPoints, vPrevious.p),
                                                  availableTilesCopy, distMap.MyPoints);
                    if (vPrevious != null && vPrevious.p != null)
                    {
                        reverse.MyWaypoints.Add(vPrevious.p);
                        availableTilesCopy.Remove(availableTilesCopy.Find(delegate(IPoint p) { return(p.equals(vPrevious.p)); }));
                    }
                    else //Ran out of available points before reaching end
                    {
                        return(null);
                    }
                }
                //Reverse path
                reverse.MyWaypoints.Reverse();
            }
            return(reverse);
        }
Beispiel #3
0
        public IMap loadMap(XmlDocument myDoc)
        {
            myMap = new Map();

            #region READ DISTANCE MAPS
            XmlNodeList distanceMapNodes = myDoc.GetElementsByTagName("Distance_Map"), pointNodes;
            XmlNode     sourceNode, sourcePositionXNode, sourcePositionYNode, currentPointPositionNode,
                        currentPointPositionXNode, currentPointPositionYNode, currentPointValueNode;
            XmlNodeList        tester;
            List <DistanceMap> distanceMaps =
                new List <DistanceMap>();
            DistanceMap currentMap = new DistanceMap();
            int         test       = 0;

            foreach (XmlNode distanceMapNode in distanceMapNodes)
            {
                test = 0;
                //Get source
                sourceNode          = ((XmlElement)distanceMapNode).SelectNodes("Source_Point").Item(0);
                sourcePositionXNode = ((XmlElement)sourceNode).SelectNodes("Position_X").Item(0);
                sourcePositionYNode = ((XmlElement)sourceNode).SelectNodes("Position_Y").Item(0);
                pointNodes          = ((XmlElement)distanceMapNode).GetElementsByTagName("Distance_Point");
                currentMap          = new DistanceMap();

                foreach (XmlNode distancePointNode in pointNodes)
                {
                    if (test < 256)
                    {
                        test++;
                        //tester = ((XmlElement)distancePointNode).SelectNodes("Position");

                        currentPointPositionNode =
                            ((XmlElement)distancePointNode).SelectNodes("Position").Item(0);
                        currentPointPositionXNode =
                            ((XmlElement)currentPointPositionNode).SelectNodes("Position_X").Item(0);
                        currentPointPositionYNode =
                            ((XmlElement)currentPointPositionNode).SelectNodes("Position_Y").Item(0);
                        currentPointValueNode =
                            ((XmlElement)distancePointNode).SelectNodes("Value").Item(0);

                        //Create and add valuePoint
                        currentMap.Add(new valuePoint(new PointObj(
                                                          currentPointPositionXNode.InnerText.ToString(),
                                                          currentPointPositionYNode.InnerText.ToString(), "0"),
                                                      Int32.Parse(currentPointValueNode.InnerText)));
                    }
                }

                currentMap.MyOrigin = new PointObj(sourcePositionXNode.InnerText,
                                                   sourcePositionYNode.InnerText, "0");
                distanceMaps.Add(currentMap);
            }
            myMap.MyDistanceMaps = distanceMaps;
            #endregion

            return(myMap);
        }
Beispiel #4
0
    // Método alteranito que maximiza la distancia entre las dos bases
    void alternativePlacePlayerBase()
    {
        List<Vector3Int> keys = new List<Vector3Int>(mapTileDictionary.Keys);
        List<DistanceMap> distances = new List<DistanceMap>();

        foreach(Vector3Int tile1 in keys)
        {
            foreach (Vector3Int tile2 in keys)
            {
                if (mapTileDictionary[tile1].tileType == SpriteRepository.TileType.TILE_TYPE_GRASS /*||
                    mapTileDictionary[tile1].tileType == SpriteRepository.TileType.TILE_TYPE_FOREST*/)
                {
                    if (mapTileDictionary[tile2].tileType == SpriteRepository.TileType.TILE_TYPE_GRASS /*||
                    mapTileDictionary[tile2].tileType == SpriteRepository.TileType.TILE_TYPE_FOREST*/)
                    {
                        DistanceMap distanceMap = new DistanceMap();
                        distanceMap.mapTile1 = mapTileDictionary[tile1];
                        distanceMap.mapTile2 = mapTileDictionary[tile2];
                        distanceMap.distance = (tile1 - tile2).magnitude;
                        distances.Add(distanceMap);
                    }
                }
            }
        }

        distances.Sort((x, y) => y.distance.CompareTo(x.distance));
        DistanceMap maxDistance = distances[0];    

        List<MapTile> playerBases = new List<MapTile>();
        playerBases.Add(maxDistance.mapTile1);
        playerBases.Add(maxDistance.mapTile2);
        //Debug.Log("La distancia es " + maxDistance.distance);

        foreach (MapTile playerBase in playerBases)
        {
            List<Vector3Int> neis = getNeighbourList(playerBase.position, false, 3);
            List<MapTile> validNeis = new List<MapTile>();
            neis.Add(playerBase.position);

            foreach(Vector3Int nei in neis)
            {
                //Debug.Log("El tipo es " + mapTileDictionary[nei].tileType);
                if (mapTileDictionary[nei].tileType == SpriteRepository.TileType.TILE_TYPE_GRASS ||
                    mapTileDictionary[nei].tileType == SpriteRepository.TileType.TILE_TYPE_FOREST)
                    validNeis.Add(mapTileDictionary[nei]);
            }

            int randomIndex = Random.Range(0, validNeis.Count);
            //Debug.Log("el index random es " + randomIndex);
            updateMapTileType(validNeis[randomIndex].position, validNeis[randomIndex], SpriteRepository.TileType.TILE_TYPE_PLAYER_BASE);
        }

    }
Beispiel #5
0
        public Direction GoClosestCompteur(WorldState world)
        {
            // utiliser un MoveTo ou on ne se preoccupe pas de prendre une baffe
            this.Distances = new DistanceMap(world, this.Id, 2, this.LastPlayerAttacked);
            this.Distances.BuildAllPath();

            var cpt = this.FindClosestCompteur(world);

            Log.Info("Player {0} is going compteur {1}", this.Id, cpt);

            var direction = this.MoveToByShortestPath(world, world.Compteurs[cpt].Pos);
            return direction;
        }
Beispiel #6
0
        private Bitmap _TranslateZoneAnimationImage(Bitmap BaseImage, string Row1, string Row2)
        {
            var Bitmap = new Bitmap(512, 512);

            Patcher.PatcherGetFile("Font/Seagull.ttf", (FontStream) =>
            {
                {
                    var Graphics2             = Graphics.FromImage(BaseImage);
                    Graphics2.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                    Graphics2.FillRectangle(new SolidBrush(Color.Transparent), new Rectangle(0, 38, 512, 190));
                }

                var PrivateFontCollection = new PrivateFontCollection();
                var FontBytes             = FontStream.ReadAll();
                fixed(byte *FontPointer   = FontBytes)
                {
                    PrivateFontCollection.AddMemoryFont(new IntPtr(FontPointer), FontBytes.Length);
                }

                var graphics = Graphics.FromImage(Bitmap);
                var Font1    = new Font(PrivateFontCollection.Families[0].Name, 26, FontStyle.Regular);
                var Font2    = new Font(PrivateFontCollection.Families[0].Name, 40, FontStyle.Regular);
                //graphics.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, 512, 512));
                graphics.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceOver;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
                graphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.TextRenderingHint  = TextRenderingHint.AntiAlias;

                var SolidBrush = new SolidBrush((ARGB_Rev)"#503c3c");

                graphics.DrawString(Row1, Font1, SolidBrush, new PointF(-2, 35.2f));
                //graphics.DrawString(Row2, Font2, SolidBrush, new PointF(-3, 97));

                float Position = -3;
                for (int n = 0; n < Row2.Length; n++)
                {
                    graphics.DrawString(Row2.Substr(n, 1), Font2, SolidBrush, new PointF(Position, 97));
                    var Size  = graphics.MeasureString(Row2.Substr(n, 1), Font2);
                    Position += Size.Width - 2;
                }

                var _DistanceMap = DistanceMap.GetDistanceMap(DistanceMap.GetMask(Bitmap));

                DistanceMap.DrawGlow(Bitmap, _DistanceMap, 6, "#fff0d3", 0.1f);
                graphics.DrawImage(BaseImage, Point.Empty);
            });

            Bitmap.Save(@"C:\vesperia\vesperia\test.png");
            return(Bitmap);
        }
Beispiel #7
0
        public List <IPoint> getReachablePoints(IPoint source)
        {
            DistanceMap   wholeMap     = getDistanceMap(source);
            List <IPoint> reachableMap = new List <IPoint>();

            foreach (valuePoint vp in wholeMap.MyPoints)
            {
                if (vp.value > -1)
                {
                    reachableMap.Add(vp.p);
                }
            }
            return(reachableMap);;
        }
Beispiel #8
0
    protected override void DerivedDraw(MotionEditor editor)
    {
        DistanceMap sensor = GetDistanceMap(editor.GetCurrentFrame(), editor.Mirror);

        sensor.Draw(Color);
        if (DrawReferences)
        {
            sensor.DrawReferences();
        }
        if (DrawDistribution)
        {
            sensor.DrawDistribution(Color, Rect);
        }
    }
Beispiel #9
0
        static public Map getMap(XmlDocument myDoc)
        {
            Map newMap = new Map();

            #region READ DISTANCE MAPS
            XmlNodeList distanceMapNodes = myDoc.SelectNodes("Distance_Map"), pointNodes;
            XmlNode     sourceNode, sourcePositionXNode, sourcePositionYNode, currentPointPositionNode,
                        currentPointPositionXNode, currentPointPositionYNode, currentPointValueNode;
            List <DistanceMap> distanceMaps =
                new List <DistanceMap>();
            DistanceMap currentMap = new DistanceMap();
            foreach (XmlNode distanceMapNode in distanceMapNodes)
            {
                //Get source
                sourceNode          = ((XmlElement)distanceMapNode).SelectNodes("Source_Point").Item(0);
                sourcePositionXNode = ((XmlElement)sourceNode).SelectNodes("Position_X").Item(0);
                sourcePositionYNode = ((XmlElement)sourceNode).SelectNodes("Position_Y").Item(0);

                pointNodes = ((XmlElement)distanceMapNode).SelectNodes("Distance_Point");
                currentMap = new DistanceMap();
                foreach (XmlNode distancePointNode in pointNodes)
                {
                    currentPointPositionNode =
                        ((XmlElement)distancePointNode).SelectNodes("Position").Item(0);
                    currentPointPositionXNode =
                        ((XmlElement)currentPointPositionNode).SelectNodes("Position_X").Item(0);
                    currentPointPositionYNode =
                        ((XmlElement)currentPointPositionNode).SelectNodes("Position_Y").Item(0);
                    currentPointValueNode =
                        ((XmlElement)distancePointNode).SelectNodes("Value").Item(0);

                    //Create and add valuePoint
                    currentMap.Add(new valuePoint(new PointObj(
                                                      currentPointPositionXNode.InnerText.ToString(),
                                                      currentPointPositionYNode.InnerText.ToString(), "0"),
                                                  Int32.Parse(currentPointValueNode.InnerText)));
                }

                currentMap.MyOrigin = new PointObj(sourcePositionXNode.InnerText,
                                                   sourcePositionYNode.InnerText, "0");
                distanceMaps.Add(currentMap);
            }
            newMap.MyDistanceMaps = distanceMaps;
            #endregion
            return(newMap);
        }
Beispiel #10
0
    public DistanceMap GetDistanceMap(Frame frame, bool mirrored)
    {
        DistanceMap sensor = new DistanceMap(Resolution);
        RootModule  module = Data.GetModule <RootModule>();

        if (module != null)
        {
            Vector3    position = module.GetRootPosition(frame.Timestamp, mirrored);
            Quaternion rotation = module.GetRootRotation(frame.Timestamp, mirrored);
            sensor.Sense(Matrix4x4.TRS(position + new Vector3(0f, 0.5f * Size.y, 0f), rotation, Vector3.one), Mask, Size);
        }
        else
        {
            sensor.Sense(frame.GetBoneTransformation(0, mirrored), Mask, Size);
        }
        return(sensor);
    }
Beispiel #11
0
        private HandCollection CreateHandCollection(ShapeCollection shapes)
        {
            var map = new DistanceMap<HandData, Shape>(currentValue.Hands);
            map.Map(shapes.Shapes);

            var handData = new List<HandData>();
            foreach (var tupple in map.MappedItems) {
                handData.Add(this.Create(tupple.Item1, tupple.Item2));
            }
            foreach (var shape in map.UnmappedItems) {
                handData.Add(this.Create(shape));
            }
            foreach (var discontinuedHandData in map.DiscontinuedItems) {
                this.ReturnIdToPool(discontinuedHandData.Id);
            }

            return new HandCollection(handData);
        }
Beispiel #12
0
 public void Think(int turn, int maxTurn, int player, GameField field, ICommander commander)
 {
     if (field.GetPrepareResource(plan.Excavator, player, true) >= 4 && field[plan.Excavator].Terrain == Terrain.Wasteland)
     {
         disposition.AddBuildOrder(1000, plan.Excavator, Terrain.Excavator);
         disposition.AddMoveOrder(100, plan.Excavator, GameField.GetNeedRobot(Terrain.Excavator));
     }
     foreach (Point town in plan.Town)
     {
         if (field.GetPrepareResource(town, player, true) < 9) continue;
         disposition.AddBuildOrder(1000, town, Terrain.Town);
         disposition.AddMoveOrder(100, town, GameField.GetNeedRobot(Terrain.Town));
     }
     DistanceMap distance = new DistanceMap(field, player, InitialPoint);
     BuildPriority priority = new BuildPriority(field, player, InitialPoint, 99);
     foreach (Point point in field.Iterator())
     {
         if (field.GetPrepareResource(point, player, true) < 4) continue;
         if (!field.IsAdjoinTerritory(point, player)) continue;
         if (point == new Point { X = 6, Y = 6 }) continue;
         Terrain building;
         switch(field[point].Terrain)
         {
             case Terrain.Wasteland: building = Terrain.House; break;
             case Terrain.Hole: building = Terrain.Bridge; break;
             default: continue;
         }
         disposition.AddBuildOrder(priority[point] * 10, point, building);
         disposition.AddMoveOrder(priority[point], point, GameField.GetNeedRobot(building));
     }
     foreach (OrderBuild build in disposition.EnumerateOrder<OrderBuild>())
     {
         disposition.AddSecureResource(build.Priority / 10 - 1, build.Point, player, field);
     }
     disposition.AddSecureGround(150, 100, player, field);
     disposition.AddKamikaze(0, player, field);
     disposition.Dispose(field, commander);
 }
Beispiel #13
0
        public Direction Decide(WorldState world)
        {
            this.Distances = new DistanceMap(world, this.Id, 2, this.LastPlayerAttacked);
            this.Distances.BuildAllPath();

            var direction = this.InnerDecide(world);

            var next = world.Players[this.Id].Pos.Move(direction);
            int meId = world.Players[this.Id].Id;

            var adjacents = next.Adjacents();
            var baffedPlayers = world.Players.Where(p => p.Id != meId
                && adjacents.Any(adj => adj == p.Pos)).ToList();
            if (baffedPlayers.Count == 1)
            {
                this.LastPlayerAttacked = baffedPlayers[0].Id;
            }
            else if (baffedPlayers.Count > 0)
            {
                this.LastPlayerAttacked = null;
            }
            return direction;
        }
 private IList<FingerPoint> MapFingerPoints(IList<FingerPoint> oldFingerPoints, IList<FingerPoint> newFingerPoints)
 {
     var idGenerator = new IdGenerator();
     var distanceMap = new DistanceMap<FingerPoint, FingerPoint>(oldFingerPoints);
     distanceMap.Map(newFingerPoints);
     foreach (var tuple in distanceMap.MappedItems)
     {
         idGenerator.SetUsed(tuple.Item1.Id);
         tuple.Item2.Id = tuple.Item1.Id;
     }
     foreach (var newFinger in distanceMap.UnmappedItems)
     {
         newFinger.Id = idGenerator.GetNextId();
     }
     return distanceMap.MappedItems.Select(i => i.Item2).Union(distanceMap.UnmappedItems).ToList();
 }
        public RequestOutput GotoStart(State state, int player, byte allowedDirectionsMask, DistanceMap distanceMap)
        {
            var target = distanceMap.nearestOpponentOwned[player];

            if (target == ushort.MaxValue)
            {
                target = distanceMap.nearestEmpty[player];
                if (target == ushort.MaxValue)
                {
                    throw new InvalidOperationException("Couldn't find nearest to conquer");
                }
            }

            var next = target;

            for (var cur = target; cur != state.players[player].arrivePos; cur = (ushort)distanceMap.paths1[player, cur])
            {
                next = cur;
            }

            if (next != target && state.territory[next] == player)
            {
                var dirTo = state.players[player].arrivePos.DirTo(next);
                if ((allowedDirectionsMask & (1 << (int)dirTo)) != 0)
                {
                    return new RequestOutput {
                               Command = dirTo, Debug = $"Goto nearest {state.players[player].arrivePos}->{target}"
                    }
                }
                ;
            }

            return(null);
        }
    }
Beispiel #16
0
 private IList<FingerPoint> MapFingerPoints(IList<FingerPoint> oldFingerPoints, IList<FingerPoint> newFingerPoints)
 {
     var idGenerator = new IdGenerator();
     var distanceMap = new DistanceMap<FingerPoint, FingerPoint>(oldFingerPoints);
     distanceMap.Map(newFingerPoints);
     foreach (var tuple in distanceMap.MappedItems) {
         idGenerator.SetUsed(tuple.Item1.Id);
         tuple.Item2.Id = tuple.Item1.Id;
         tuple.Item2.FrameCount = tuple.Item1.FrameCount + 1;
     }
     foreach (var newFinger in distanceMap.UnmappedItems) {
         newFinger.Id = idGenerator.GetNextId();
     }
     foreach (var discontinuedFinger in distanceMap.DiscontinuedItems) {
         discontinuedFinger.NegativeFrameCount++;
     }
     return distanceMap.MappedItems.Select(i => i.Item2).Union(distanceMap.UnmappedItems).Union(distanceMap.DiscontinuedItems).Where(i => i.NegativeFrameCount <= this.settings.FramesForDiscontinuedFingerPoint).ToList();
 }
Beispiel #17
0
        static void Main(string[] args)
        {
            Uri            horizonUri = UriFromArg(args, 0);
            GeodysseyModel model      = new GeodysseyModel();

            LoaderController.Instance.Open(horizonUri, model);
            IRegularGrid2D horizon = model[0];

            //string pathOriginal = horizonUri.LocalPath.Replace(".dat", ".grd");
            //horizon.WriteSurfer6BinaryFile(pathOriginal);

            // TODO: Make IRegularGrid IEnumerable

            var           extentMap = new FastImage <bool>(horizon.SizeI, horizon.SizeJ, horizon.Select(item => item.HasValue));
            IImage <bool> faultMap  = Morphology.Invert(extentMap);

            IImage <double> distanceMap = DistanceMap.EuclideanTransform(extentMap);



            // Remove anything above a threshold distance from data
            const double threshold       = 50;
            var          clippedFaultMap = extentMap.CloneTransform((i, j) => distanceMap[i, j] < threshold &&
                                                                    faultMap[i, j]);

            Trace.WriteLine("Pepper filter");
            IImage <bool> filtered = Morphology.PepperFiltering(5, clippedFaultMap);

            Trace.WriteLine("Closing gaps");
            IImage <bool> closed = Morphology.Closing(filtered);

            Trace.WriteLine("Thinning until convergence");
            IImage <bool> thinned = Morphology.ThinUntilConvergence(closed);

            Trace.WriteLine("Thinning blocks until convergence");
            IImage <bool> blockthinned = Morphology.ThinBlockUntilConvergence(thinned);

            Trace.WriteLine("Filling");
            IImage <bool> filled = Morphology.Fill(blockthinned);

            WriteBinaryImageSurfer6Grid(horizon, filled, horizonUri.LocalPath.Replace(".grd", "_filled.grd"));

            //// Create a double valued 'binary' image showing the extent of the horizon data
            //FastImage<double> extentMap = new FastImage<double>(horizon.SizeI, horizon.SizeJ);
            //for (int i = 0; i < horizon.SizeI; ++i)
            //{
            //    for (int j = 0; j < horizon.SizeJ; ++j)
            //    {
            //        bool hasValue = horizon[i, j].HasValue;
            //        extentMap[i, j] = hasValue ? 1.0 : 0.0;
            //    }
            //}

            //int extent = extentMap.Where(v => v == 1.0).Count();
            //double extentProportion = (double) extent / (extentMap.Width * extentMap.Height);

            //IImage<double> scaledExtentMap = Scaler.Downscale(extentMap, 5);

            //IImage<double> smoothedExtentMap = scaledExtentMap.CloneSize();
            //Convolver.GaussianSmooth(scaledExtentMap, smoothedExtentMap, 3.0);

            //IRegularGrid2D smoothedGrid = horizon.CloneSize(smoothedExtentMap.Width, smoothedExtentMap.Height);

            //for (int i = 0 ; i < smoothedGrid.SizeI; ++i)
            //{
            //    for (int j = 0 ; j < smoothedGrid.SizeJ; ++j)
            //    {
            //        smoothedGrid[i, j] = smoothedExtentMap[i, j];
            //    }
            //}

            //PriorityQueue<double> orderedIntensities = PriorityQueue<double>.CreateHighFirstOut(smoothedExtentMap);
            //int k =  (int) (extentProportion * orderedIntensities.Count);
            //Debug.Assert(k >= 0);
            //for (int i = 0 ; i < k - 1; ++i)
            //{
            //    orderedIntensities.Dequeue();
            //}
            //double threshold = orderedIntensities.Dequeue();


            //string pathSmoothed = horizonUri.LocalPath.Replace(".grd", "_smoothed.grd");
            //smoothedGrid.WriteSurfer6BinaryFile(pathSmoothed);

            //IImage<bool> thresholdMap = BitImage.Analysis.Threshold(smoothedExtentMap, threshold * 2.0);

            //int actual = thresholdMap.Where(v => v).Count();
            //double actualProportion = (double) actual / (thresholdMap.Width * thresholdMap.Height);

            //IRegularGrid2D thresholdGrid = horizon.CloneSize(thresholdMap.Width, thresholdMap.Height);

            //for (int i = 0; i < smoothedGrid.SizeI; ++i)
            //{
            //    for (int j = 0; j < smoothedGrid.SizeJ; ++j)
            //    {
            //        thresholdGrid[i, j] = thresholdMap[i, j] ? 1.0 : 0.0;
            //    }
            //}

            //string pathThresholded = horizonUri.LocalPath.Replace(".grd", "_thresholded.grd");
            //thresholdGrid.WriteSurfer6BinaryFile(pathThresholded);

            //IImage<double> distanceMap = DistanceMap.EuclideanTransform(scaledExtentMap);



            // Convert the image back to a grid for convenient output
            IRegularGrid2D distanceGrid = horizon.CloneSize(distanceMap.Width, distanceMap.Height);

            for (int i = 0; i < distanceMap.Width; ++i)
            {
                for (int j = 0; j < distanceMap.Height; ++j)
                {
                    distanceGrid[i, j] = distanceMap[i, j];
                }
            }

            string pathDistance = horizonUri.LocalPath.Replace(".grd", "_distance.grd");

            distanceGrid.WriteSurfer6BinaryFile(pathDistance);
        }
Beispiel #18
0
        private static List<Direction> WhenMoving(
            WorldState world, Point depart, Point destination, out Point lastPosition, int cost = 0,
            int maxIteration = int.MinValue)
        {
            var distance = destination.Dist(depart);

            maxIteration = maxIteration < distance ? distance : maxIteration;

            var directions = new List<Direction>();
            int i = 0;
            lastPosition = depart;
            while (lastPosition != destination && i < maxIteration)
            {
                var map = new DistanceMap(world, 0, cost, null);
                map.BuildAllPath();
                var dir = map.MoveTo(destination);
                directions.Add(dir.Value);

                var next = lastPosition.Move(dir.Value);
                world.Players[0] = new Player(0, next.X, next.Y, 0, PlayerState.Playing);
                lastPosition = next;
                i++;
            }
            return directions;
        }
Beispiel #19
0
        public Direction GoHome(WorldState world)
        {
            Log.Info("Player {0} is going home", this.Id);

            // utiliser un MoveTo ou on se preoccupe de prendre une baffe
            this.Distances = new DistanceMap(world, this.Id, 3, this.LastPlayerAttacked);
            this.Distances.BuildAllPath();

            var home = world.Caddies[this.Id].Pos;
            var direction = this.MoveToByShortestPath(world, home);
            return direction;
        }
Beispiel #20
0
        public void Alphabeta(ITimeManager timeManager, State state, int player, PlayerPath[] skipPaths, DistanceMap distanceMap, InterestingFacts facts)
        {
            if (skipPaths != null && (skipPlayers == null || skipPlayers.Length < state.players.Length))
            {
                skipPlayers = new bool[state.players.Length];
            }

            bestScore   = double.MinValue;
            bestDepth   = 0;
            estimations = 0;
            bestAction  = default(Direction);

            for (int i = 0; i < 4; i++)
            {
                bestResultScores[i] = double.NegativeInfinity;
            }

            var depth = 1;

            while (!timeManager.IsExpired && depth <= maxDepth)
            {
                for (int i = 0; i < 4; i++)
                {
                    resultScores[i] = double.NegativeInfinity;
                }

                if (skipPaths != null)
                {
                    for (int i = 0; i < state.players.Length; i++)
                    {
                        skipPlayers[i] = true;
                        if (i == player || state.players[i].status == PlayerStatus.Eliminated || state.players[i].status == PlayerStatus.Broken)
                        {
                            continue;
                        }

                        var active = distanceMap.nearestOpponentActive[i, player];
                        if (active != ushort.MaxValue)
                        {
                            var dist = distanceMap.distances1[i, active];
                            if (dist != -1 && dist != int.MaxValue && dist <= 2 * depth)
                            {
                                skipPlayers[i] = false;
                                continue;
                            }
                            dist = distanceMap.distances2[i, active];
                            if (dist != -1 && dist != int.MaxValue && dist <= 2 * depth)
                            {
                                skipPlayers[i] = false;
                                continue;
                            }
                        }

                        if (facts.sawCollectDistance[i] != int.MaxValue)
                        {
                            if (facts.sawCollectDistance[i] <= depth)
                            {
                                skipPlayers[i] = false;
                                continue;
                            }
                        }
                    }
                }

                var score = Alphabeta(timeManager, state, player, depth, player, double.MinValue, double.MaxValue, resultScores, out var action, 0, skipPaths, facts);
                if (double.IsNegativeInfinity(score))
                {
                    break;
                }
                bestScore  = score;
                bestAction = action;
                bestDepth  = depth;
                for (int i = 0; i < 4; i++)
                {
                    bestResultScores[i] = resultScores[i];
                }
                depth++;
            }
        }
Beispiel #21
0
 private void UpdateInfo()
 {
     TurnInfo.Text = manager.GetTurnInfo();
     Player1Info.Text = manager.GetPlayerInfo(0);
     Player2Info.Text = manager.GetPlayerInfo(1);
     Player3Info.Text = manager.GetPlayerInfo(2);
     distance = new DistanceMap(manager.Field, manager.Player, new Common.Point { X = selectX, Y = selectY });
     priority = new BuildPriority(manager.Field, manager.Player, new Common.Point { X = selectX, Y = selectY }, 255);
     GameField field = manager.Field;
     int w = field.Width, h = field.Height;
     for (int x = 0; x < w; x++)
     {
         for (int y = 0; y < h; y++)
         {
             mass[x, y].UpdateSelected(x == selectX && y == selectY);
             mass[x, y].UpdateTerrain(field[x, y].Player, field[x, y].Terrain);
             mass[x, y].UpdateTextInfo(BuildMassInfo(x, y));
         }
     }
 }
        public byte GetAllowedDirectionsMask(ITimeManager timeManager, State state, int player, DistanceMap distanceMap, InterestingFacts facts)
        {
            var result = (byte)0;

            minimax.Alphabeta(timeManager, state, player, facts.pathsToOwned, distanceMap, facts);
            for (int i = 0; i < 4; i++)
            {
                if (minimax.bestResultScores[i] > 0)
                {
                    result = (byte)(result | (1 << i));
                }
            }

            return(result);
        }
Beispiel #23
0
        public RequestOutput GotoStart(State state, int player, byte allowedDirectionsMask, DistanceMap distanceMap)
        {
            var empty = distanceMap.nearestEmpty[player];

            if (empty == ushort.MaxValue)
            {
                throw new InvalidOperationException("Couldn't find nearest to conquer");
            }

            var next = empty;

            for (var cur = empty; cur != state.players[player].arrivePos; cur = (ushort)distanceMap.paths1[player, cur])
            {
                next = cur;
            }

            if (next != empty)
            {
                return new RequestOutput {
                           Command = state.players[player].arrivePos.DirTo(next), Debug = $"Goto nearest {state.players[player].arrivePos}->{empty}"
                }
            }
            ;

            return(null);
        }
    }