Inheritance: MonoBehaviour
        /// <summary>
        /// Generates the bounding waypoints of the acceptable U-Turn area given Rndf Hazards and specified exit and entry waypoints
        /// </summary>
        /// <returns></returns>
        public static Polygon uTurnBounds(Coordinates exit, ArbiterSegment segment)
        {
            // initialize the bounding box
            List<Coordinates> boundingBox = new List<Coordinates>();

            // put in coords for every available lane
            foreach (ArbiterLane al in segment.Lanes.Values)
            {
                PointOnPath? pop = null;

                if (!al.IsInside(exit))
                {
                    ArbiterWaypoint aw = al.GetClosestWaypoint(exit, 10.0);
                    if (aw != null)
                        pop = al.PartitionPath.GetClosest(aw.Position);
                }
                else
                    pop = al.PartitionPath.GetClosest(exit);

                if(pop != null)
                {
                    ArbiterLanePartition alp = al.GetClosestPartition(exit);
                    Coordinates vector = alp.Vector().Normalize(15);
                    Coordinates back = pop.Value.pt - vector;
                    vector = vector.Normalize(30);
                    boundingBox.AddRange(InflatePartition(back, vector, alp.Lane.Width));
                }
            }

            // return the box
            return GeneralToolkit.JarvisMarch(boundingBox);
        }
        public NavigableEdge GetClosestNavigableEdge(Coordinates c)
        {
            try
            {
                int i = this.RecommendedPath.GetClosestPoint(c).Index;
                Coordinates rpi = this.RecommendedPath[i];
                for (int j = 0; j < PathNodes.Count; j++)
                {
                    INavigableNode inn = PathNodes[j];
                    if (inn.Position.Equals(rpi))
                    {
                        foreach (NavigableEdge ne in inn.OutgoingConnections)
                        {
                            if (ne.End.Equals(PathNodes[j + 1]))
                                return ne;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return null;
        }
Exemplo n.º 3
0
 public Rectangle(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy)
 {
     A = new Coordinates { X = ax, Y = ay };
     B = new Coordinates { X = bx, Y = by };
     C = new Coordinates { X = cx, Y = cy };
     D = new Coordinates { X = dx, Y = dy };
 }
 public LocalMapCluster(Coordinates position, double speed, Coordinates heading, double width)
 {
     this.position = position;
     this.speed = speed;
     this.heading = heading;
     this.width = width;
 }
        public static void ComputeMeanCovariance(IList<Coordinates> pts, out Coordinates mean, out Matrix2 cov)
        {
            // for better numerical stability, use a two-pass method where we first compute the mean
            double sum_x = 0, sum_y = 0;
            for (int i = 0; i < pts.Count; i++) {
                sum_x += pts[i].X;
                sum_y += pts[i].Y;
            }

            double avg_x = sum_x/(double)pts.Count;
            double avg_y = sum_y/(double)pts.Count;

            // now compute variances and covariances
            double sum_x2 = 0, sum_y2 = 0, sum_xy = 0;
            for (int i = 0; i < pts.Count; i++) {
                double dx = pts[i].X - avg_x;
                double dy = pts[i].Y - avg_y;

                sum_x2 += dx*dx;
                sum_y2 += dy*dy;
                sum_xy += dx*dy;
            }

            double var_x = sum_x2/(double)pts.Count;
            double var_y = sum_y2/(double)pts.Count;
            double cov_xy = sum_xy/(double)pts.Count;

            mean = new Coordinates(avg_x, avg_y);
            cov = new Matrix2(var_x, cov_xy, cov_xy, var_y);
        }
Exemplo n.º 6
0
 public Track(string id, Coordinates coords, TimeStamp[] whens, Orientation[] angles)
 {
     this.id = id;
     this.coords = coords;
     this.whens = whens;
     this.angles = angles;
 }
Exemplo n.º 7
0
        public static Rover CreateRover(string definition)
        {
            if (string.IsNullOrEmpty(definition)) throw new WrongRoverDefinitionException("Definition of rover is empty.");

            var coordinatesAndOrientation = definition.Split(' ');

            if(coordinatesAndOrientation.Length != 3) throw new WrongRoverDefinitionException("Definition of rover doesn't have the proper format.");

            Coordinates coordinates;
            IOrientation orientation;

            try
            {
                coordinates = new Coordinates(Convert.ToInt32(coordinatesAndOrientation[0]),
                                                  Convert.ToInt32(coordinatesAndOrientation[1]));

                orientation = OrientationFactory.GenerateOrientation(coordinatesAndOrientation[2]);
            }
            catch (Exception ex)
            {
                throw new WrongRoverDefinitionException("Bad definition.", ex);
            }

            var rover = new Rover();

            rover.Init(coordinates, orientation);

            return rover;
        }
Exemplo n.º 8
0
 public Goblin(string name,Coordinates position)
 {
     this.Name = name;
     this.Position = position;
     this.Health = 50;
     this.Damage = 5;
 }
    private bool WillCollideWith(GameObject obj, Coordinates direction, GameObject cur)
    {
        Coordinates first = new Coordinates(
            Math.Max(obj.Position.Row + direction.Row,
                     cur.Position.Row),

            Math.Max(obj.Position.Col + direction.Col,
                     cur.Position.Col)
        );

        Coordinates last = new Coordinates(
            Math.Min(obj.Position.Row + obj.Rows + direction.Row,
                     cur.Position.Row + cur.Rows),

            Math.Min(obj.Position.Col + obj.Cols + direction.Col,
                     cur.Position.Col + cur.Cols)
        );

        for (int row = first.Row; row < last.Row; row++)
            for (int col = first.Col; col < last.Col; col++)
                if (obj[row - obj.Position.Row - direction.Row, col - obj.Position.Col - direction.Col] != '\0' &&
                    cur[row - cur.Position.Row, col - cur.Position.Col] != '\0')
                        return true;

        return false;
    }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="position"></param>
 /// <param name="waypointId"></param>
 public ArbiterParkingSpotWaypoint(Coordinates position, ArbiterParkingSpotWaypointId waypointId,
     ArbiterParkingSpot parkingSpot)
 {
     this.position = position;
     this.WaypointId = waypointId;
     this.outgoingConnections = new List<NavigableEdge>();
 }
Exemplo n.º 11
0
        public static SqlGeography CreatePolygon(Coordinates[] coordinates, int srid)
        {
            var list = coordinates.Distinct().ToList();
            
            var b = new SqlGeographyBuilder();
            b.SetSrid(srid);
            b.BeginGeography(OpenGisGeographyType.Polygon);
            b.BeginFigure(list[0].Latitude, list[0].Longitude);

            for (var i = 1; i < list.Count; i++)
                b.AddLine(list[i].Latitude, list[i].Longitude);

            b.AddLine(list[0].Latitude, list[0].Longitude);
            b.EndFigure();
            b.EndGeography();

            //Fix left-hand rule. We always want left-hand.
            var g = b.ConstructedGeography;
            if (!g.STIsValid())
                throw new SisoDbException(ExceptionMessages.NotAValidPolygon.Inject(g.IsValidDetailed()));

            if (g.EnvelopeAngle() > 90)
                g = g.ReorientObject(); 

            return g;
        }
Exemplo n.º 12
0
        public Amusements(Coordinates c, GameRecords m, int prize, int fee, int capacity, int runningTime, string name, bool hasEntranceExit, Color color, int typeId, int workingPrice, int attractiveness)
            : base(m, c, prize, typeId)
        {
            this.zIndex = 0;
            this.originalFee = fee;
            this.currFee = fee;
            this.capacity = capacity;
            this.WorkingCost = workingPrice;
            this.attractiveness = attractiveness;

            this.fixedRunningTime = runningTime;
            this.maxWaitingTime = (int)(runningTime*1.5);
            this.name = name;
            this.hasSeparatedEnterExit = hasEntranceExit;
            this.color = color;
            //this.typeId = typeId;
            peopleInList = new List<Person>(capacity);

               model.LastBuiltAmus = this;
            if(hasEntranceExit) model.mustBeEnter = true;
            this.Id = model.amusList.GetFreeID();
            model.amusList.Add(this);
            model.maps.AddAmus(this);
            model.CheckCheapestFee(this.CurrFee);

               // mimoProvoz = true;
               // zacatek = true;
        }
        private static double EvaluateGoalUtility(double curvature, Coordinates relativeGoalPoint)
        {
            // get the angle to the goal point
            double angle = relativeGoalPoint.ArcTan;

            const double angleMax = 45*Math.PI/180.0;
            double scaledAngle = angle/angleMax;
            if (scaledAngle > 1) scaledAngle = 1;
            if (scaledAngle < -1) scaledAngle = -1;

            // calculate the target curvature to hit the goal
            double targetCurvature = scaledAngle*max_curvature;

            // calculate a matching scale factor
            double scaleFactor = Math.Pow((curvature - targetCurvature)/0.01, 2);

            // calculate a distance weighting factor
            double distMin = 20;
            double distMax = 70;
            double distFactor = (relativeGoalPoint.Length - distMin)/(distMax - distMin);
            if (distFactor > 0.3) distFactor = 0.3;
            if (distFactor < 0) distFactor = 0;
            distFactor = 1-distFactor;

            double turnFactor = (1-scaleFactor*0.1);
            if (turnFactor < -1) turnFactor = -1;

            return turnFactor*distFactor;
        }
Exemplo n.º 14
0
        static void Main()
        { 
            var startPosition = new Coordinates(0, 0);

            string[,] matrix =
           {
                { "1","3" ,"2", "2", "2" ,"4" },
                { "3","3" ,"3", "2", "4" ,"4" },
                { "4","3" ,"1", "2", "3" ,"3" },
                { "4","3" ,"1", "3", "3" ,"1" },
                { "4","3" ,"3", "3", "1" ,"1" },
            };

            var largestAreaCount = 0;
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    if (matrix[i, j] != "V")
                    {
                        var currentAreaCount=FindMostAdjacentCells(matrix, i, j, matrix[i, j]);

                        if (largestAreaCount < currentAreaCount)
                        {
                            largestAreaCount = currentAreaCount;
                        }

                        counter = 0;
                    }
                }
            }

            Console.WriteLine(largestAreaCount);
        }
Exemplo n.º 15
0
        public Map(PhysicsEngine physicsEngine)
        {
            physicsEngine.AddItem(this);
            this.physicsEngine = physicsEngine;
            RequeredTicksToMove = 3;
            Position = new Coordinates();
            Content = new Dictionary<Coordinates, char>();
            for (int i = 0; i < mapFences.Length; i++)
            {
                mapFences[i] = new char[Globals.Y_MAX_BOARD_SIZE];
                for (int j = 0; j < mapFences[i].Length; j++)
                {
                    mapFences[i][j] = j % 3 == 1 ? Globals.BACKGROUND_DEFAULT_VALUE : '+';
                }
            }
            var jsonText = File.ReadAllText(Globals.MODELS_PATH + "asd" + Globals.MODELS_FILES_EXTENSION);
            var deserializeObject = JsonConvert.DeserializeObject<MapStructure>(jsonText);
            Width = deserializeObject.MapWidth;
            Height = deserializeObject.MapLength;
            foreach (var mapObject in deserializeObject.map)
            {

                switch (mapObject.ClassType)
                {
                    case "Services.Services.Objects.Obsticle":
                        TakeObject(obsticlesFactory, mapObject);
                        break;
                    default:
                        return;
                }
            }
            RecreateFences();
        }
 public void ExploredSparesRepresentedByO()
 {
     var minefield = Minefield.Unexplored(2, 3);
     var coordinates = new Coordinates(1, 2);
     var newMinefield = minefield.Explore(coordinates);
     Assert.AreEqual("XX\nXX\nXO\n", MinefieldRenderer.Render(newMinefield));
 }
        /// <summary>
        /// Checks if hte opposing lane is clear to pass an opposing vehicle
        /// </summary>
        /// <param name="lane"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public bool ClearForDisabledVehiclePass(ArbiterLane lane, VehicleState state, double vUs, Coordinates minReturn)
        {
            // update the forward vehicle
            this.ForwardVehicle.Update(lane, state);

            // check if the rear vehicle exists and is moving along with us
            if (this.ForwardVehicle.ShouldUseForwardTracker && this.ForwardVehicle.CurrentVehicle != null)
            {
                // distance from other to us
                double currentDistance = lane.DistanceBetween(this.ForwardVehicle.CurrentVehicle.ClosestPosition, state.Front) - (2 * TahoeParams.VL);
                double minChangeDist = lane.DistanceBetween(minReturn, state.Front);

                // check if he's within min return dist
                if(currentDistance > minChangeDist)
                {
                    // params
                    double vOther = this.ForwardVehicle.CurrentVehicle.StateMonitor.Observed.speedValid ? this.ForwardVehicle.CurrentVehicle.Speed : lane.Way.Segment.SpeedLimits.MaximumSpeed;

                    // get distance of envelope for him to slow to our speed
                    double xEnvelope = (Math.Pow(vUs, 2.0) - Math.Pow(vOther, 2.0)) / (2.0 * -0.5);

                    // check to see if vehicle is outside of the envelope to slow down for us after 3 seconds
                    double xSafe = currentDistance - minChangeDist - (xEnvelope + (vOther * 15.0));
                    return xSafe > 0 ? true : false;
                }
                else
                    return false;
            }
            else
                return true;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets a Coordinate from a address.
        /// </summary>
        /// <param name="appFullyQualifiedDomainName">The application fully qualified domain name.
        /// <remarks>
        /// <example>http://webservices.geneva3.webvisible.com</example>
        /// </remarks>
        /// </param>
        /// <param name="address">An address.
        /// <remarks>
        /// <example>1600 Amphitheatre Parkway Mountain View, CA 94043</example>
        /// </remarks>
        /// </param>
        /// <returns>A spatial coordinate that contains the latitude and longitude of the address.</returns>
        public static Coordinates GetCoordinates(string appFullyQualifiedDomainName, string address)
        {
            Coordinates coordinate = new Coordinates();
            coordinate = GetGeoCoordinates(appFullyQualifiedDomainName, address);

            if (coordinate != null)
            {
                if (!string.IsNullOrEmpty(coordinate.ErrorMessage))
                {
                    throw new Exception(coordinate.ErrorMessage);
                }
                else
                {
                    if (coordinate.AccuracyLevel >= 0 && coordinate.AccuracyLevel <= 3)
                    {
                        throw new Exception(coordinate.AccuracyDescription);
                    }
                }
            }
            else
            {
                throw new Exception("Request could not be processed");
            }

            return coordinate;
        }
 public HitTestResult(IHittable target, bool hit, Coordinates snapPoint, object data)
 {
     this.target = target;
     this.hit = hit;
     this.snapPoint = snapPoint;
     this.data = data;
 }
Exemplo n.º 20
0
 //Constructors:
 public TerrainTile(Vector3 vec, TerrainType type, Topper top)
 {
     terrainType = type;
     topper = top;
     var battlespud = f*g;
     Coordinates coords = new Coordinates (vec);
 }
Exemplo n.º 21
0
 public TerrainTile SetTerrainTile(Vector3 vec)
 {
     Coordinates coords = new Coordinates (vec);
     topper = Topper.Empty;
     terrainType = TerrainType.Stone;
     return this;
 }
        /// <summary>
        /// Add blockage to partition
        /// </summary>
        /// <param name="partition"></param>
        /// <param name="c"></param>
        public void AddBlockage(IConnectAreaWaypoints partition, Coordinates c, bool acrossSegment)
        {
            partition.Blockage.BlockageExists = true;
            partition.Blockage.BlockageCoordinates = c;
            partition.Blockage.SecondsSinceObserved = 0.0;
            partition.Blockage.BlockageTimeCost = 1800;

            if (partition.Blockage.BlockageHasExisted)
                partition.Blockage.BlockageLifetime = partition.Blockage.BlockageLifetime * 4.0;

            if (acrossSegment && partition is ArbiterLanePartition)
            {
                foreach (ArbiterLanePartition alp in ((ArbiterLanePartition)partition).NonLaneAdjacentPartitions)
                {
                    if (alp.IsInside(c))
                    {
                        alp.Blockage.BlockageExists = true;
                        alp.Blockage.BlockageCoordinates = c;
                        alp.Blockage.SecondsSinceObserved = 0.0;
                        alp.Blockage.BlockageTimeCost = 1800;

                        if (alp.Blockage.BlockageHasExisted)
                            alp.Blockage.BlockageLifetime = partition.Blockage.BlockageLifetime * 4.0;
                    }
                }
            }

            // reset navigation costs
            this.currentTimes = new KeyValuePair<int, Dictionary<ArbiterWaypointId, DownstreamPointOfInterest>>();
        }
Exemplo n.º 23
0
        public Block getBlockAt(Coordinates coordinates)
        {
            int x = (int)Math.Floor(coordinates.getX());
               int y = (int)Math.Floor(coordinates.getY());

               if(!blocks.ContainsKey(x.ToString() + "," + y.ToString())){
               if (coordinates.getY() > -1) {
                   blocks.Add(x.ToString() + "," + y.ToString(), new Block(new Air()));
               }
               else if (coordinates.getY() == -1) {
                   blocks.Add(x.ToString() + "," + y.ToString(), new Block(new Grass()));
               }
               else if (coordinates.getY() == -2) {
                   Random rnd = new Random();

                   if (rnd.Next(0, 2) == 0) {
                       blocks.Add(x.ToString() + "," + y.ToString(), new Block(new Dirt()));
                   }
                   else {
                       blocks.Add(x.ToString() + "," + y.ToString(), new Block(new Stone()));
                   }
               }
               else if (coordinates.getY() < -2) {
                   blocks.Add(x.ToString() + "," + y.ToString(), new Block(new Stone()));
               }
               blocks[x.ToString() + "," + y.ToString()].setCoordinates(coordinates);
               }

               return blocks[x.ToString() + "," + y.ToString()];
        }
Exemplo n.º 24
0
 public void WhenACoordinateHasBeenExploredThenIsExploredIsTrue()
 {
     var minefield = Minefield.Empty(2, 3);
     var coordinate = new Coordinates(0, 1);
     var exploredMinefield = minefield.Explore(coordinate);
     Assert.AreEqual(true, exploredMinefield.IsExplored(coordinate.RowIndex, coordinate.ColumnIndex));
 }
Exemplo n.º 25
0
 public WorldCell getCell(Coordinates cell_coords)
 {
     if (checkCoordinateIntegrity (cell_coords)) {
         return cells[cell_coords.x, cell_coords.y];
     }
     return null;
 }
 public LinePathSegment(Coordinates start, Coordinates end, double? endSpeed, bool? stopline)
 {
     this.start = start;
     this.end = end;
     this.endSpeed = endSpeed;
     this.stopline = stopline;
 }
Exemplo n.º 27
0
 public bool isEqual(Coordinates coordinate)
 {
     if(coordinate.x == x && coordinate.y == y) {
         return true;
     }
     return false;
 }
Exemplo n.º 28
0
        public JsonResult GetCoordinates(string street, string number)
        {
            var reguestGET =
                WebRequest.Create("http://nominatim.openstreetmap.org/search?q=" + number + "+" + street +
                                  ",+Донецк, Украина&format=xml&addressdetails=1");

            reguestGET.Proxy = null;

            var webResponse = reguestGET.GetResponse();

            var stream = webResponse.GetResponseStream();

            if (stream == null)
            {
                throw new Exception("Can't get response from server.");
            }

            var xmlDoc = new XmlDocument();
            xmlDoc.Load(stream);

            var tagPlace = (XmlElement) xmlDoc.GetElementsByTagName("place")[0];

            if (tagPlace == null)
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }

            var lat = Convert.ToSingle(tagPlace.GetAttribute("lat"), new CultureInfo("en-US"));
            var lon = Convert.ToSingle(tagPlace.GetAttribute("lon"), new CultureInfo("en-US"));

            var coord = new Coordinates { Lat = lat, Lon = lon };

            return Json(coord, JsonRequestBehavior.AllowGet);
        }
 public LinePathSegment(Coordinates start, Coordinates end)
 {
     this.start = start;
     this.end = end;
     endSpeed = null;
     stopline = null;
 }
Exemplo n.º 30
0
        public ActionResult Coordinates_Destroy([DataSourceRequest]DataSourceRequest request, Coordinates coordinate)
        {
            var coordinateToDelete = this.coordinates.GetAll().Where(x => x.Id == coordinate.Id).FirstOrDefault();
            this.coordinates.Delete(coordinateToDelete);

            return this.Json(new[] { coordinateToDelete }.ToDataSourceResult(request, this.ModelState));
        }
Exemplo n.º 31
0
 public Coordinates MoveForward(Coordinates currentCoordinates)
 {
     return(new Coordinates(currentCoordinates.XCoordinate - 1, currentCoordinates.YCoordinate));
 }
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
 }
 public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 34
0
        private bool IsCancelled(IEntityManager entityManager)
        {
            if (!entityManager.EntityExists(EventArgs.User) || EventArgs.Target is {} target&& !entityManager.EntityExists(target))
            {
                return(true);
            }

            //https://github.com/tgstation/tgstation/blob/1aa293ea337283a0191140a878eeba319221e5df/code/__HELPERS/mobs.dm
            if (EventArgs.CancelToken.IsCancellationRequested)
            {
                return(true);
            }

            // TODO :Handle inertia in space.
            if (EventArgs.BreakOnUserMove && !entityManager.GetComponent <TransformComponent>(EventArgs.User).Coordinates.InRange(
                    entityManager, UserGrid, EventArgs.MovementThreshold))
            {
                return(true);
            }

            if (EventArgs.BreakOnTargetMove && !entityManager.GetComponent <TransformComponent>(EventArgs.Target !.Value).Coordinates.InRange(
                    entityManager, TargetGrid, EventArgs.MovementThreshold))
            {
                return(true);
            }

            if (EventArgs.BreakOnDamage && TookDamage)
            {
                return(true);
            }

            if (EventArgs.ExtraCheck != null && !EventArgs.ExtraCheck.Invoke())
            {
                return(true);
            }

            if (EventArgs.BreakOnStun &&
                entityManager.HasComponent <StunnedComponent>(EventArgs.User))
            {
                return(true);
            }

            if (EventArgs.NeedHand)
            {
                if (!entityManager.TryGetComponent(EventArgs.User, out HandsComponent? handsComponent))
                {
                    // If we had a hand but no longer have it that's still a paddlin'
                    if (_activeHand != null)
                    {
                        return(true);
                    }
                }
                else
                {
                    var currentActiveHand = handsComponent.ActiveHand;
                    if (_activeHand != currentActiveHand)
                    {
                        return(true);
                    }

                    var currentItem = handsComponent.GetActiveHand;
                    if (_activeItem != currentItem)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 35
0
 public PlayerAssault(redd096.StateMachine stateMachine, Coordinates coordinates) : base(stateMachine, coordinates)
 {
 }
Exemplo n.º 36
0
 public virtual Coordinates CalculateCoordinates()
 => (from visit in Visits
     orderby visit.Visited
         where visit.Coordinates.IsSpecified
     select visit.Coordinates)
 .LastOrDefault() ?? Coordinates.Null();
Exemplo n.º 37
0
 void Output(Coordinates loc)
 {
     Debug.Log("World Location: " + loc.InWorld.X + " " + loc.InWorld.Y);
     Debug.Log("Chunk Location: " + loc.InChunks.X + " " + loc.InChunks.Y + " " + loc.InChunks.I + " " + loc.InChunks.J);
     Debug.Log("\n");
 }
Exemplo n.º 38
0
 public Wall(Coordinates coordinates) : base(coordinates, '#')
 {
 }
Exemplo n.º 39
0
 public static void MoveTo(this Entity e, Coordinates coords, float speed)
 {
 }
Exemplo n.º 40
0
 // Checking for no change, so exact equality is fine
 public static bool HasChanged(Coordinates a, Coordinates b)
 {
     return(a.X != b.X || a.Y != b.Y || a.Z != b.Z);
 }
Exemplo n.º 41
0
 /// <summary>
 /// This API crops a region of the screen buffer. In this example
 /// this functionality is not needed so the method throws a
 /// NotImplementException exception.
 /// </summary>
 /// <param name="source">The region of the screen to be scrolled.</param>
 /// <param name="destination">The region of the screen to receive the
 /// source region contents.</param>
 /// <param name="clip">The region of the screen to include in the operation.</param>
 /// <param name="fill">The character and attributes to be used to fill all cell.</param>
 public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 42
0
 public new IQueryable <ContentPage> GetQuery(string query, string scope, string language, Coordinates center, string site, out string indexName)
 {
     language = Context.Language.Name;
     return(base.GetQuery(query, scope, language, center, site, out indexName));
 }
Exemplo n.º 43
0
 public static Vector3f ToSpatialVector3f(this Coordinates coordinates)
 {
     return(new Vector3f((float)coordinates.x, (float)coordinates.y, (float)coordinates.z));
 }
Exemplo n.º 44
0
        public bool AddWorkableUnitToQueue(Type model, string name, Coordinates park, Coordinates work)
        {
            StorageFreeSlots = StorageCapacity - Storage.Count;   // Storage slots left
            QueueFreeSlots   = QueueCapacity - Queue.Count;       // Queue slots left
            int freeSlotsLeft = StorageFreeSlots - Queue.Count;   // Slots that can still be taken

            if ((StorageFreeSlots <= 0) || (QueueFreeSlots <= 0) || (freeSlotsLeft <= 0))
            {
                FactoryProgress(this, new StatusChangedEventArgs("ERROR : No more free slots."));
                return(false);
            }
            else
            {
                Queue.Add(new FactoryQueueElement(name, model, park, work));
                FactoryProgress(Queue.First(), new StatusChangedEventArgs("New robot was added to Queue."));

                tryBuild();

                return(true);
            }
        }
Exemplo n.º 45
0
        public static void FindParkingInterval(IList <Obstacle> obstacles, LineSegment projectionLine, double offDistMax, double offDistMin, double maxBottomDist, double maxTopDist, ref Coordinates topPoint, ref Coordinates bottomPoint)
        {
            List <double> projectedDists = new List <double>(1000);

            Coordinates vec     = projectionLine.UnitVector;
            Coordinates startPt = projectionLine.P0;
            double      len     = projectionLine.Length;

            foreach (Obstacle obs in obstacles)
            {
                foreach (Coordinates pt in obs.AvoidancePolygon)
                {
                    double projDist = vec.Dot(pt - startPt);
                    double offDist  = vec.Cross(pt - startPt);

                    if (projDist < 0 || projDist > len)
                    {
                        continue;
                    }

                    if (offDist < offDistMin || offDist > offDistMax)
                    {
                        continue;
                    }

                    // add to the list
                    projectedDists.Add(projDist);
                }
            }

            // sort the list
            projectedDists.Sort();

            // find the max dist between two adjacent projected distance
            double bestDist       = -1;
            double bestProjBottom = 0;
            double bestProjTop    = maxTopDist;

            for (int i = 0; i < projectedDists.Count - 1; i++)
            {
                if (projectedDists[i] > maxBottomDist)
                {
                    if (bestDist < 0)
                    {
                        bestDist = bestProjTop = projectedDists[i];
                    }
                    break;
                }
                double dist = projectedDists[i + 1] - projectedDists[i];
                if (dist > bestDist)
                {
                    bestDist       = dist;
                    bestProjBottom = projectedDists[i];
                    bestProjTop    = projectedDists[i + 1];
                }
            }

            bottomPoint = projectionLine.P0 + vec * bestProjBottom;
            topPoint    = projectionLine.P0 + vec * bestProjTop;
        }
Exemplo n.º 46
0
 /// <summary>
 /// Valeur de la position de la pièce.
 /// </summary>
 /// <returns>La valeur.</returns>
 /// <param name="king">Coordonnées du roi ennemi.</param>
 /// <param name="board">Tableau de jeu.</param>
 public override int positionValue(Coordinates king, Board board)
 {
     return(positionValueGoldPattern(king));
 }
Exemplo n.º 47
0
 public int setNextWaypoint(Coordinates pto)
 {
     nextCoordinates = pto;
     return(0);
 }
Exemplo n.º 48
0
        // obstacles - list of obstacles to avoid near the parking spot
        // projectionLine - P1 is the place where the front bumper of the vehicle should end up; P0 is where the rear bumper of the vehicle should end up
        // zonePerimiter - list of points specifying the perimiter of the parking zone
        // vehiclePosition - current position of the vehicle
        // vehicleHeading - heading of the car, in radians

        // corner1 and corner2 are always set to the corners of the rectangle, however if the function returns FALSE then
        // the rectangle is the minimum 8x8 box containing the vehicle's back axis whether or not the box contains obstacles or crosses the zone perimiter
        public static bool FindParkingInterval(IList <Obstacle> obstacles, LineSegment projectionLine, Polygon zonePerimeter, Coordinates vehiclePosition, double vehicleHeading, ref Coordinates[] corners)
        {
            const double expansion_step = .25;
            bool         ret            = true;

            // transform everything into "parking coordinates":
            // 0,0 is where the center of the rear bumper should end up when parking is finished
            // the vehicle should be parallel to (and on top of) the Y axis when parking has finished (positive Y)
            List <Polygon> pcObstacles = new List <Polygon>(obstacles.Count);

            for (int i = 0; i < obstacles.Count; i++)
            {
                Polygon p = obstacles[i].AvoidancePolygon.Inflate(Math.Max(obstacles[i].minSpacing, .5));
                for (int j = 0; j < p.points.Count; j++)
                {
                    p.points[j] -= projectionLine.P0;
                    p.points[j]  = p.points[j].Rotate(-projectionLine.UnitVector.RotateM90().ArcTan);
                }
                pcObstacles.Add(p);
            }

            Polygon pcPerimeter = new Polygon(zonePerimeter);

            for (int i = 0; i < pcPerimeter.points.Count; i++)
            {
                pcPerimeter.points[i] -= projectionLine.P0;
                pcPerimeter.points[i]  = pcPerimeter.points[i].Rotate(-projectionLine.UnitVector.RotateM90().ArcTan);
            }

            Coordinates pcVehPos = vehiclePosition;

            pcVehPos -= projectionLine.P0;
            pcVehPos  = pcVehPos.Rotate(-projectionLine.UnitVector.RotateM90().ArcTan);

            double       leftBound, rightBound;
            double       lowBound; // highbound is always 0
            const double highBound = 0;

            leftBound  = Math.Min(-TahoeParams.T / 2.0 - 1, pcVehPos.X - TahoeParams.T / 2.0 * 1.2);
            rightBound = Math.Max(TahoeParams.T / 2.0 + 1, pcVehPos.X + TahoeParams.T / 2.0 * 1.2);
            lowBound   = Math.Min(0, pcVehPos.Y - TahoeParams.T / 2.0 * 1.2);

            bool canExpandDown  = true;
            bool canExpandLeft  = true;
            bool canExpandRight = true;

            // initial expansion... lower boundary
            while (lowBound > -8 && canExpandDown)
            {
                LineSegment l = new LineSegment(new Coordinates(leftBound, lowBound), new Coordinates(rightBound, lowBound));
                if (ExpansionViolatesConstraints(l, pcPerimeter, pcObstacles))
                {
                    canExpandDown = false;
                    break;
                }
                lowBound -= expansion_step;
            }

            // initial expansion... left & right boundary
            while ((rightBound - leftBound) < 8 && (canExpandRight || canExpandLeft))
            {
                LineSegment ls;

                ls = new LineSegment(new Coordinates(leftBound, lowBound), new Coordinates(leftBound, highBound));
                if (ExpansionViolatesConstraints(ls, pcPerimeter, pcObstacles))
                {
                    canExpandLeft = false;
                }
                else
                {
                    leftBound -= expansion_step;
                }

                ls = new LineSegment(new Coordinates(rightBound, lowBound), new Coordinates(rightBound, highBound));
                if (ExpansionViolatesConstraints(ls, pcPerimeter, pcObstacles))
                {
                    canExpandRight = false;
                }
                else
                {
                    rightBound += expansion_step;
                }
            }

            // move boundaries out to make at least an 8x8 m box, even if this violates the perimiter/includes obstacles
            if (rightBound - leftBound < 8)
            {
                double tmp = (rightBound + leftBound) / 2;
                leftBound  = tmp - 4;
                rightBound = tmp + 4;
                ret        = false;
            }
            if (lowBound > -8)
            {
                ret      = false;
                lowBound = -8;
            }

            bool lastExpandLeft = false;

            while ((canExpandDown || canExpandLeft || canExpandRight) && (lowBound > -30) && (rightBound - leftBound) < 30)
            {
                if (!(canExpandLeft || canExpandRight) || (-lowBound < (rightBound - leftBound) && canExpandDown))
                {
                    LineSegment l = new LineSegment(new Coordinates(leftBound, lowBound - .5), new Coordinates(rightBound, lowBound - .5));
                    if (ExpansionViolatesConstraints(l, pcPerimeter, pcObstacles))
                    {
                        canExpandDown = false;
                    }
                    else
                    {
                        lowBound -= expansion_step;
                    }
                }
                else if (!(canExpandDown || canExpandRight) || (canExpandLeft && !(lastExpandLeft && canExpandRight)))
                {
                    LineSegment l = new LineSegment(new Coordinates(leftBound - .5, lowBound), new Coordinates(leftBound - .5, highBound));
                    if (ExpansionViolatesConstraints(l, pcPerimeter, pcObstacles))
                    {
                        canExpandLeft = false;
                    }
                    else
                    {
                        leftBound -= expansion_step;
                    }
                    lastExpandLeft = true;
                }
                else // canExpandRight
                {
                    LineSegment l = new LineSegment(new Coordinates(rightBound + .5, lowBound), new Coordinates(rightBound + .5, highBound));
                    if (ExpansionViolatesConstraints(l, pcPerimeter, pcObstacles))
                    {
                        canExpandRight = false;
                    }
                    else
                    {
                        rightBound += expansion_step;
                    }
                    lastExpandLeft = false;
                }
            }

            corners = new Coordinates[4];

            corners[0] = new Coordinates(leftBound, lowBound);
            corners[1] = new Coordinates(leftBound, highBound);
            corners[2] = new Coordinates(rightBound, highBound);
            corners[3] = new Coordinates(rightBound, lowBound);

            Random r = new Random();

            for (int i = 0; i < 4; i++)
            {
                corners[i]  = corners[i].Rotate(projectionLine.UnitVector.RotateM90().ArcTan);
                corners[i] += projectionLine.P0;
            }

            return(ret);

            /*Line pll = new Line(projectionLine.P0,projectionLine.P1);
             * Coordinates offVec = projectionLine.UnitVector.Rotate90();
             * // find the leftmost boundary (looking into the parking spot)
             * for (int i = 0; i < 20; i++)
             * {
             * Line tl = new Line(pll);
             * tl.P0 = tl.P0 + offVec * i;
             * tl.P1 = tl.P1 + offVec * i;
             *
             * Coordinates[] ipts;
             * zonePerimeter.Intersect(tl, out ipts);
             *
             * obstacles[0].AvoidancePolygon
             *
             * if (ipts.Length < 2) break; // the test line is completely outside of the zone perimiter
             * if (ipts.Length == 2)
             * {
             *
             * }
             * }*/
        }
Exemplo n.º 49
0
 public MonsterCard(Coordinates coords, int manaCost, string name, string description, int damage, int hitPoints)
     : base(coords, manaCost, name, description)
 {
     this.Damage    = damage;
     this.HitPoints = hitPoints;
 }
Exemplo n.º 50
0
 public float setHomeWaypoint(Coordinates pto)
 {
     homeCoordinates = pto;
     return(0);
 }
Exemplo n.º 51
0
 public AbsolutePose(Coordinates xy, double heading, CarTimestamp timestamp)
 {
     this.xy        = xy;
     this.heading   = heading;
     this.timestamp = timestamp;
 }
Exemplo n.º 52
0
        public int doNavigation(int waypointRadius)
        {
            busyNavigation = true;

            float maxDroneSpeedToDestination = 0.5f;
            float maxDroneSpeedRotation      = 0.01f;
            float angleToWaypoint            = 0;

            currCoordinates = new Coordinates(mDrone.iDroneCup_Read_Longitude(),
                                              mDrone.iDroneCup_Read_Latitude());


            // DEGUB //
            //currCoordinates.latitude = 41.536955;
            //currCoordinates.longitude = -8.627266;
            //homeCoordinates = currCoordinates;
            // DEGUB //


            // Check: is out of range? in wrong direction?
            dist2waypoint = calculateDistance(currCoordinates, homeCoordinates);
            if (dist2waypoint > SAFE_GPS_RANGE)
            {
                this.runNavigation = false;

                mDrone.iDroneCup_Hover();
                mDrone.iDroneCup_Land();
                System.Threading.Thread.Sleep(10);

                System.Diagnostics.Debug.WriteLine("doNavigation -> Check: is out of range? : " + dist2waypoint.ToString());
            }

            // Check: is at waypoint?
            else if (isAtWaypoint(waypointRadius))
            {
                // Disable navigation OR do something else: Next waypoint? Action? Land?
                this.runNavigation = false;

                mDrone.iDroneCup_Hover();
                System.Threading.Thread.Sleep(10);

                System.Diagnostics.Debug.WriteLine("doNavigation -> Check: is at waypoint?");
            }

            // Action: Navigation
            else
            {
                // Read Drone Heading
                float trueNorthHeading = mDrone.iDroneCup_Read_Heading(0);
                droneHeading = trueNorthHeading;

                // Check: Rotation Error
                float bearing   = calculateBearing(currCoordinates, nextCoordinates);
                float angleDiff = bearing - trueNorthHeading;
                angleToWaypoint = (float)(Math.Atan2(Math.Sin(angleDiff * DEG2RAD), Math.Cos(angleDiff * DEG2RAD)) * RAD2DEG);
                droneBearing    = bearing;

                // Check: Distance Error
                float distanceToWaypoint = calculateDistance(currCoordinates, nextCoordinates);

                // Compute: Rotation Correction
                float yawSpeedDesired = angleToWaypoint * maxDroneSpeedRotation;
                yawSpeedDesired = KeepInRange(yawSpeedDesired, -0.25f, 0.25f);

                // Compute: Motion Correction
                float tmpsin            = (float)Math.Sin(angleToWaypoint * DEG2RAD);
                float tmpcos            = (float)Math.Cos(angleToWaypoint * DEG2RAD);
                float pitchSpeedDesired = (maxDroneSpeedToDestination * tmpcos);
                float rollSpeedDesired  = (maxDroneSpeedToDestination * tmpsin);

                rollSpeedDesired  = KeepInRange(rollSpeedDesired, -0.25f, 0.25f);
                pitchSpeedDesired = KeepInRange(pitchSpeedDesired, -0.25f, 0.25f);

                // Optional: Initial yaw correction
                if (angleToWaypoint > 40.0f || angleToWaypoint < -40.0f)
                {
                    // Apply only Rotation Correction
                    //mDrone.iDroneCup_MoveAdvanced(0,0,0,yawSpeedDesired);
                }
                else
                {
                    // Apply Global Correction
                    //mDrone.iDroneCup_MoveAdvanced(pitchSpeedDesired,rollSpeedDesired,0,yawSpeedDesired);
                }
            }

            // DEBUG //

            float tickDiff = System.Environment.TickCount - lastTick;

            lastTick = System.Environment.TickCount;
            fps      = (int)Math.Round(1000.0f / tickDiff);
            System.Diagnostics.Debug.WriteLine("doNavigation -> Navigation done... " + "FPS: " + fps.ToString() + "angle: " + angleToWaypoint.ToString());

            // DEBUG //

            busyNavigation = false;

            return(0);
        }
Exemplo n.º 53
0
 public void Setup()
 {
     _coordinates = new Coordinates(x, y);
 }
 public void ReportOponentsLastShotResult(Coordinates coordinates, ShotResult result)
 {
 }
Exemplo n.º 55
0
 public int GetHeightAt(Coordinates coords)
 {
     return(_grid[coords.Y, coords.X]);
 }
Exemplo n.º 56
0
        IEnumerator SonarWave(Coordinates userCoords)
        {
            Captas4Feedback waveFeedback = feedbackBehavior as Captas4Feedback;

            Coordinates detectableCoords;
            float       distance;
            float       waveRange = 0;
            float       waveTime  = 0;
            float       padding   = 0;

            //If Captas4 is set on global mode, deffine range of Captas4 to the distance with the farthest map angle
            if (!partialMode)
            {
                float tempDistance = 0;
                range = 0;

                foreach (Vector2 anglePos in mapAnglesPos)
                {
                    tempDistance = Mathf.Abs(Vector2.Distance(userCoords.position, anglePos));
                    if (tempDistance > range)
                    {
                        range = tempDistance;
                    }
                }
            }

            waveFeedback.StartWave(range, waveDuration);

            while (waveTime < waveDuration)
            {
                //looping through all detectable on the map
                foreach (DetectableOceanEntity detectable in levelManager.submarineEntitiesInScene)
                {
                    detectableCoords = new Coordinates(detectable.transform.position, Vector2.zero, 0f);
                    distance         = Mathf.Abs(Vector2.Distance(userCoords.position, detectableCoords.position));

                    //if current tested detectable is in range place a point on his pos
                    //there is a security (padding) if object pos is at a position beetween two tested distance increasing at each frame (depend on the progression of the timer)
                    if (distance <= waveRange && distance >= waveRange + padding)
                    {
                        if (availableDetectionPoints.Count > 0)
                        {
                            availableDetectionPoints[0].ActivatePoint(detectable, pointFadeDuration, this);
                            usedDetectionPoints.Add(availableDetectionPoints[0]);
                            availableDetectionPoints.RemoveAt(0);
                        }
                        else
                        {
                            Debug.Log("Not Enough object in pool");
                        }
                    }
                }

                waveTime += Time.deltaTime;
                padding   = waveRange - (range * (waveTime / waveDuration));
                waveRange = range * (waveTime / waveDuration);
                yield return(new WaitForFixedUpdate());
            }

            readyToUse = true;
        }
Exemplo n.º 57
0
    public bool IsCheckmate(ChessPiece king)
    {
        List <ChessPiece>  dangers  = new List <ChessPiece>();
        List <Coordinates> allMoves = new List <Coordinates>();
        ChessPiece         ownKing;
        Coordinates        kingLoc;

        foreach (ChessPiece piece in pieceLocations)
        {
            if ((piece != null) && (piece.gameObject.tag == king.gameObject.tag))
            {
                allMoves.AddRange(piece.GetMoves(false));
            }
        }

        if (king.gameObject.tag == "Team1")
        {
            ownKing = team1_king;
        }
        else
        {
            ownKing = team2_king;
        }

        kingLoc = new Coordinates(ownKing.currentPos.x, ownKing.currentPos.z);
        dangers = ownKing.isCheck(ownKing.currentPos);

        if (dangers.Count != 0)
        {
            List <ChessPiece> tempDangers = new List <ChessPiece>(dangers);

            foreach (ChessPiece badPiece in tempDangers)
            {
                foreach (Coordinates move in allMoves)
                {
                    if (move == badPiece.currentPos)
                    {
                        dangers.Remove(badPiece);
                        continue;
                    }
                }

                if (badPiece is Rook || badPiece is Queen)
                {
                    if (kingLoc.x == badPiece.currentPos.x)
                    {
                        if (kingLoc.z > badPiece.currentPos.z)
                        {
                            for (int i = kingLoc.z - 1; i > badPiece.currentPos.z; i--)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (int i = kingLoc.z + 1; i < badPiece.currentPos.z; i++)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (kingLoc.x > badPiece.currentPos.x)
                        {
                            for (int i = kingLoc.x - 1; i > badPiece.currentPos.x; i--)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                        else
                        {
                            for (int i = kingLoc.x + 1; i < badPiece.currentPos.x; i++)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
                if (badPiece is Bishop || badPiece is Queen)
                {
                    if (kingLoc.x - badPiece.currentPos.x > 0)
                    {
                        if (kingLoc.z - badPiece.currentPos.z > 0)
                        {
                            int j = kingLoc.z - 1;
                            for (int i = kingLoc.x - 1; i < badPiece.currentPos.x; i++, j++)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                        else
                        {
                            int j = kingLoc.z + 1;
                            for (int i = kingLoc.x - 1; i < badPiece.currentPos.x; i++, j--)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        if (kingLoc.z - badPiece.currentPos.z > 0)
                        {
                            int j = kingLoc.z - 1;
                            for (int i = kingLoc.x + 1; i > badPiece.currentPos.x; i--, j++)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                        else
                        {
                            int j = kingLoc.z + 1;
                            for (int i = kingLoc.x + 1; i > badPiece.currentPos.x; i--, j--)
                            {
                                foreach (Coordinates move in allMoves)
                                {
                                    if (move == badPiece.currentPos)
                                    {
                                        dangers.Remove(badPiece);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        bool saveFlag = false;

        if (dangers.Count != 0)
        {
            for (int x = -1; x <= 1; x++)
            {
                for (int z = -1; z <= 1; z++)
                {
                    Coordinates tempCoord = new Coordinates(x, z);
                    if (ownKing.isCheck(kingLoc + tempCoord).Count == 0)
                    {
                        saveFlag = true;
                    }
                }
            }
        }

        return(dangers.Count != 0 && !saveFlag);
    }
Exemplo n.º 58
0
    private static Action DecideActionToTake(List <Action> actions)
    {
        Action        bestAction         = null;
        List <Action> moveActions        = actions.Where(a => a.Type == MoveAndBuild).ToList();
        List <Action> pushActions        = actions.Where(a => a.Type == PushAndBuild).ToList();
        int           maxMoveHeight      = -1;
        int           maxBuildHeight     = -1;
        bool          ignoredBuildToFour = false;
        Action        ignoredAction      = null; //TODO - make this a set an then optimise!! For example you might choose one that traps you
        //when you could actually escape to a whole load of 3s

        bool             ignoreBuildTooBig         = false;
        HashSet <Action> ignoredBuildTooBigActions = new HashSet <Action>();

        foreach (Action action in moveActions)
        {
            Unit        theUnit                       = MyUnits[action.Index];
            Coordinates unitCo                        = new Coordinates(theUnit.X, theUnit.Y);
            Coordinates moveCo                        = unitCo.GetCoordinateInDirection(action.MoveDirection);
            int         heightOfMoveSquare            = TheGrid.GetHeightAt(moveCo.X, moveCo.Y);
            Coordinates buildCo                       = moveCo.GetCoordinateInDirection(action.BuildDirection);
            int         heightOfBuildSquareAfterBuild = TheGrid.GetHeightAt(buildCo.X, buildCo.Y) + 1;
            //the unit that can perform this action
            if (heightOfMoveSquare == 3)
            {
                //we're done, move to that square
                if ((theUnit.Height == 3 || theUnit.Height == 2) && heightOfBuildSquareAfterBuild == 4)
                {
                    DebugWriteLine("Setting ignore build to 4 true");
                    ignoredBuildToFour = true;
                    ignoredAction      = action;
                    //don't build on our own threes
                    continue;
                }
                if (heightOfBuildSquareAfterBuild == 3 &&
                    EnemyCanReachCoordinatesAtHeight(buildCo, heightOfBuildSquareAfterBuild))
                {
                    //don't give enemy a point
                    continue;
                }
                //if we get here then we're getting on a 3 without having to build to 4 - don't overwrite this
                //with a worse "3 and build to 4" move
                ignoredBuildToFour = false;
                bestAction         = action;
                break;
            }
            else
            {
                if (heightOfBuildSquareAfterBuild > heightOfMoveSquare + 1)
                {
                    ignoreBuildTooBig = true;
                    ignoredBuildTooBigActions.Add(action);
                    //why build something that we can't move to?
                    continue;
                }

                if (heightOfBuildSquareAfterBuild == 3 &&
                    EnemyCanReachCoordinatesAtHeight(buildCo, heightOfBuildSquareAfterBuild))
                {
                    //don't give enemy a point
                    continue;
                }

                if (maxMoveHeight < heightOfMoveSquare)
                {
                    maxMoveHeight  = heightOfMoveSquare;
                    maxBuildHeight = heightOfBuildSquareAfterBuild;
                    bestAction     = action;
                }
                else if (maxMoveHeight == heightOfMoveSquare)
                {
                    //same move height, check build height
                    if (maxBuildHeight < heightOfBuildSquareAfterBuild)
                    {
                        maxMoveHeight  = heightOfMoveSquare;
                        maxBuildHeight = heightOfBuildSquareAfterBuild;
                        bestAction     = action;
                    }
                }
            }
        }

        //certain cases just push as not enough to gain by moving
        foreach (Action action in pushActions)
        {
            Unit        theUnit            = MyUnits[action.Index];
            Coordinates unitCo             = new Coordinates(theUnit.X, theUnit.Y);
            Coordinates enemyCoords        = unitCo.GetCoordinateInDirection(action.MoveDirection);
            Unit        enemyUnit          = EnemyUnits.First(e => e.Coords.Equals(enemyCoords));
            Coordinates enemyFinalLocation = enemyCoords.GetCoordinateInDirection(action.BuildDirection);
            if (theUnit.Height == 0 || theUnit.Height == 1)
            {
                //we're low down
                if (enemyUnit.Height >= 2 && TheGrid.GetHeightAt(enemyFinalLocation) < 2)
                {
                    //knock them off
                    if (TheGrid.GetHeightAt(enemyFinalLocation) == 0)
                    {
                        //knock them straight to ground
                        bestAction = action;
                        break;
                    }
                    else
                    {
                        Action betterAction = GetBetterPushActionIfPossible(actions, enemyFinalLocation);
                        bestAction = betterAction ?? action;
                        break;
                    }
                }
            }
            else
            {
                //how good is the best action move?
                if (bestAction == null)
                {
                    DebugWriteLine("Best action is null");
                    continue;
                }
                Unit        ourBestUnit = MyUnits[bestAction.Index];
                Coordinates bestUnitCo  = new Coordinates(ourBestUnit.X, ourBestUnit.Y);
                Coordinates bestMoveCo  = bestUnitCo.GetCoordinateInDirection(bestAction.MoveDirection);
                DebugWriteLine($"About to get height with ({bestMoveCo.X}, {bestMoveCo.Y})");
                int heightOfMoveSquare = TheGrid.GetHeightAt(bestMoveCo.X, bestMoveCo.Y);
                DebugWriteLine($"Height of move square is  {heightOfMoveSquare}");
                if (heightOfMoveSquare == 0 || heightOfMoveSquare == 1)
                {
                    //we're high, but have to go all the way down... see if we can hurt them at least a bit
                    if (enemyUnit.Height >= 2 && TheGrid.GetHeightAt(enemyFinalLocation) < 2)
                    {
                        //knock them off
                        if (TheGrid.GetHeightAt(enemyFinalLocation) == 0)
                        {
                            //knock them straight to ground
                            bestAction = action;
                            break;
                        }
                        else
                        {
                            Action betterAction = GetBetterPushActionIfPossible(actions, enemyFinalLocation);
                            bestAction = betterAction ?? action;
                            break;
                        }
                    }
                }
                else if (heightOfMoveSquare == 3)
                {
                    //so I'm on a high square, but I want to see if I can knock them down to 0
                    //there are often groups of 3 squares which we can remove them from so they can't get back on
                    if (enemyUnit.Height == 3 && TheGrid.GetHeightAt(enemyFinalLocation) < 2)
                    {
                        //knock them off
                        if (TheGrid.GetHeightAt(enemyFinalLocation) == 0)
                        {
                            //knock them straight to ground
                            bestAction = action;
                            break;
                        }
                        else
                        {
                            Action betterAction = GetBetterPushActionIfPossible(actions, enemyFinalLocation);
                            bestAction = betterAction ?? action;
                            break;
                        }
                    }
                }
            }
        }

        if (ignoredBuildToFour)
        {
            DebugWriteLine("Inside ignored build to four");
            if (bestAction == null)
            {
                DebugWriteLine("USING IGNORED ACTION");
                bestAction = ignoredAction;
            }
            else if (bestAction.Type == MoveAndBuild)
            {
                DebugWriteLine("Action type check");

                Unit        theUnit                       = MyUnits[bestAction.Index];
                Coordinates unitCo                        = new Coordinates(theUnit.X, theUnit.Y);
                Coordinates moveCo                        = unitCo.GetCoordinateInDirection(bestAction.MoveDirection);
                int         heightOfMoveSquare            = TheGrid.GetHeightAt(moveCo.X, moveCo.Y);
                Coordinates buildCo                       = moveCo.GetCoordinateInDirection(bestAction.BuildDirection);
                int         heightOfBuildSquareAfterBuild = TheGrid.GetHeightAt(buildCo.X, buildCo.Y) + 1;
                if (heightOfMoveSquare < 2 && heightOfBuildSquareAfterBuild <= 2)
                {
                    //note we know height will be four so don't worry about giving enemy a point case
                    //moving down and not building particularly tall, worth taking ignored action
                    bestAction = ignoredAction;
                    DebugWriteLine("USING IGNORED ACTION");
                }
            }
        }

        if (bestAction == null)
        {
            if (ignoreBuildTooBig)
            {
                //nothing chosen, really struggling for options - try to build on a 4
                //for now just take first one
                bestAction = ignoredBuildTooBigActions.First();
                DebugWriteLine("Using ignored action for building too big");
                //foreach (Action action in ignoredBuildTooBigActions)
                //{
                //    bestAction = action;
                //    break;
                //}
            }
        }

        return(bestAction);
    }
Exemplo n.º 59
0
 public static void RemovePieceAt(Coordinates pos)
 {
     pieceLocations[pos.x, pos.z] = null;
 }
Exemplo n.º 60
0
 public override void InteracteOn(Entity user, Coordinates pos)
 {
     Action.Invoke(user, pos);
 }