コード例 #1
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        public void RequestCarTest(double gX, double gY, double eX, double eY, DirectionCar direction)
        {
            var road     = new Road(new Vector(0, 50), new Vector(100, 50), 10, 100);
            var garage1  = new Garage(new Vector(80, 20), 10);
            var garage2  = new Garage(new Vector(20, 80), 10);
            var building = new Building(new Vector(gX, gY), 1);

            var city = new CityBuilder()
                       .Road(road)
                       .Building(garage1)
                       .Building(garage2)
                       .Building(building)
                       .Build();

            var group = new CustomerGroup(1, building, building);

            GPSSystem.RequestCar(new Destination {
                Road = road, Location = building.Location
            }, group);

            Assert.IsNotEmpty(city.Cars);

            var car = city.Cars[0];

            Assert.AreEqual(eX, car.Location.X, 0.5);
            Assert.AreEqual(eY, car.Location.Y, 0.5);
            Assert.AreEqual(direction, car.Direction);
        }
コード例 #2
0
    void Start()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        Debug.Log("GPS Start");
        startGPSService();

        Point[] kmutt = new Point[] { new Point(13.650635, 100.491120),
                                      new Point(13.654107, 100.494285),
                                      new Point(13.652971, 100.4946793),
                                      new Point(13.650929, 100.496504),
                                      new Point(13.649295, 100.494114),
                                      new Point(13.650635, 100.491120) };

        //Debug.Log(IsInPolygon(kmutt,new Point(13.648325, 100.493218)));

        /*Debug.Log((100.4910347 - 100.491120) * (13.654107 - 13.650635) - (13.6505575 - 13.650635) * (100.494285 - 100.491120));
         * Debug.Log((100.4910347 - 100.491120) * (13.654107 - 13.650635) - (13.6505575 - 13.650635) * (100.494285 - 100.491120));
         * /*Point[] pts = new Point[] { new Point ( 1, 1 ),
         *                              new Point (1, 3 ),
         *                              new Point ( 3, 3 ),
         *                              new Point ( 3,0 ), new Point ( 1, 1 ),};
         * Debug.Log(IsInPolygon(pts, new Point(2, 0)));*/
        //Debug.Log(IsInPolygon(kmutt, new Point(13.652419d, 100.49368d)));
    }
コード例 #3
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        public void FindIntersectionTest(double tX, double tY, int expected, bool correct)
        {
            var intersections = new[]
            {
                new Intersection(new Vector(100, 100), 10),
                new Intersection(new Vector(100, 200), 10),
                new Intersection(new Vector(200, 200), 10),
                new Intersection(new Vector(200, 100), 10)
            };

            var city = new CityBuilder()
                       .Intersection(intersections[0])
                       .Intersection(intersections[1])
                       .Intersection(intersections[2])
                       .Intersection(intersections[3])
                       .Road(new Road(new Vector(100, 105), new Vector(100, 195), 10, 100))
                       .Road(new Road(new Vector(105, 100), new Vector(195, 100), 10, 100))
                       .Road(new Road(new Vector(105, 200), new Vector(195, 200), 10, 100))
                       .Road(new Road(new Vector(200, 105), new Vector(200, 195), 10, 100))
                       .Build();

            var intersection = GPSSystem.FindIntersection(new Vector(tX, tY));

            if (correct)
            {
                Assert.AreEqual(intersections[expected], intersection);
            }
            else
            {
                Assert.AreNotEqual(intersections[expected], intersection);
            }
        }
コード例 #4
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        public void FindNextIntersections(int start, int[] expected)
        {
            var intersections = new[]
            {
                new Intersection(new Vector(100, 100), 10),
                new Intersection(new Vector(100, 200), 10),
                new Intersection(new Vector(200, 200), 10),
                new Intersection(new Vector(200, 100), 10)
            };

            var city = new CityBuilder()
                       .Road(new Road(new Vector(100, 105), new Vector(100, 195), 10, 100))
                       .Road(new Road(new Vector(105, 100), new Vector(195, 100), 10, 100))
                       .Road(new Road(new Vector(105, 200), new Vector(195, 200), 10, 100))
                       .Road(new Road(new Vector(200, 105), new Vector(200, 195), 10, 100))
                       .Intersection(intersections[0])
                       .Intersection(intersections[1])
                       .Intersection(intersections[2])
                       .Intersection(intersections[3])
                       .Build();

            var result = GPSSystem.FindNextIntersections(intersections[start]).ToList();

            Assert.AreEqual(expected.Length, result.Count);

            foreach (var index in expected)
            {
                Assert.Contains(intersections[index], result);
            }
        }
コード例 #5
0
        public Destination Calculate(long callerId, Destination carDestination, Destination endDestination)
        {
            var network   = NodeNetwork.NodeNetwork.GetInstance();
            var startNode = new Node(GPSSystem.FindIntersection(carDestination.Location).Location);
            var endNodes  = AlgorithmTools.IntersectionTupleToNodeTuple(
                AlgorithmTools.GetIntersectionOrderForRoadSide(endDestination.Road, endDestination.Location));

            if (startNode.Equals(endNodes.Item1))
            {
                #if DEBUG
                AlgorithmDebuggerWindow.Instance.AddNetworkResult(_debuggerIndex++.ToString(), network,
                                                                  startNode, endNodes.Item2, endNodes);
                #endif
                return(endDestination);
            }

            AssignNodeValues(ref network, ref startNode);

            var nextNode = FindNextNodeOnBestRoute(ref network, endNodes.Item1);
            #if DEBUG
            AlgorithmDebuggerWindow.Instance.AddNetworkResult("DY" + _debuggerIndex++, network,
                                                              startNode, nextNode, endNodes);
            #endif
            var roadX = (startNode.PositionX - nextNode.PositionX) / 2.0 + nextNode.PositionX;
            var roadY = (startNode.PositionY - nextNode.PositionY) / 2.0 + nextNode.PositionY;
            return(new Destination
            {
                Location = new Vector(nextNode.PositionX, nextNode.PositionY),
                Road = GPSSystem.NearestRoad(new Vector(roadX, roadY))
            });
        }
コード例 #6
0
ファイル: CarController.cs プロジェクト: TheKoen/SE1d3-KBS2
        /// <summary>
        /// Makes the car approach the target and slow down.
        /// </summary>
        /// <param name="velocity">Current velocity of the car</param>
        /// <param name="yaw">Current relative yaw of the car</param>
        /// <param name="addedRotation">Amount of rotation (in degrees) to add</param>
        /// <param name="distanceToDestination">Distance to the destination</param>
        public void HandleApproachTarget(ref Vector velocity, ref double yaw, ref double addedRotation, ref double distanceToDestination)
        {
            // Get the current speed and rotation of the car.
            var speed    = velocity.Length;
            var rotation = MathUtil.VelocityToRotation(velocity);

            // Check if we're going too fast, have passengers or are near the destination.
            if (speed > maxTurningSpeed / 2d || Car.PassengerCount > 0 || distanceToDestination < 20)
            {
                // Check if we need to drop passengers off.
                if (Car.PassengerCount > 0 && /*speed < 0.05 && */ speed > 0)
                {
                    var distance = Car.DistanceTraveled - Car.PassengersBoardDistance;
                    var price    = GPSSystem.CalculatePrice(distance);
                    App.Console.Print($"[C{Car.Id}] Charged €{price:F2} for {distance:F1} units", Colors.Blue);

                    App.Console.Print($"[C{Car.Id}] Dropping customers", Colors.Blue);
                    var passenger = Car.Passengers[0];
                    TripEnd?.Invoke(this, new TripEventArgs(passenger.Group, passenger.Building.Location, Car.Location, Car));
                    Car.Passengers.Clear();
                    MainScreen.AILoop.Unsubscribe(Update);
                }

                // Slow down the car.
                velocity = speed > 0.05
                    ? Vector.Add(velocity, CalculateDeccelerationVector(velocity))
                    : new Vector();
            }

            // Get the target and current location.
            var destination = Car.Destination.Location;
            var location    = Car.Location;

            // Calculate the angle between the car and the target.
            var sub = new Vector(
                destination.X - location.X,
                destination.Y - location.Y
                );

            sub.Normalize();
            var angle = Vector.AngleBetween(rotation, sub);

            // If we need to go to the right and are able to, do so.
            if (angle > 0)
            {
                if (yaw > -maxInLaneRotation)
                {
                    addedRotation -= rotationSpeed;
                }
            }
            // If we need to go to the left and are able to, do so.
            else
            {
                if (yaw < maxInLaneRotation)
                {
                    addedRotation += rotationSpeed;
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Calculates the path to the customergroup using Dijkstra algorithm
        /// </summary>
        /// <param name="start">start path</param>
        /// <param name="group">group customers</param>
        /// <returns>list with the roads to take</returns>
        public static List <Road> CalculateRouteToCustomerGroup(Vector start, CustomerGroup group)
        {
            var startRoad = GPSSystem.NearestRoad(start);
            var endRoad   = GPSSystem.NearestRoad(group.Location);
            var hitEnd    = false;

            var listPaths = new List <Path>();

            // if the starroad equals to the endRoad
            if (startRoad == endRoad)
            {
                return(new List <Road> {
                    startRoad
                });
            }
            ;

            //add the first two intersections of the startRoad to the PathList;
            foreach (var item in GPSSystem.FindIntersectionsRoad(startRoad))
            {
                listPaths.Add(new Path(start, group.Location, item));
            }

            // loop until the end is found
            while (hitEnd == false)
            {
                var newListPaths = new List <Path>();
                foreach (var path in listPaths)
                {
                    // new found intersections
                    var lastIntersectionOfPath = path.Intersections.Last();

                    var newFoundIntersections = GPSSystem.FindNextIntersections(lastIntersectionOfPath);

                    // add the path of every new intersetion to the new ListPath
                    foreach (var intersection in newFoundIntersections)
                    {
                        var intersections = new List <Intersection>(path.Intersections);
                        intersections.Add(intersection);
                        var newPath = new Path(start, group.Location, intersection);
                        newListPaths.Add(newPath);

                        // check if endLocation is between these intersections

                        if ((endRoad.End == intersection.Location || endRoad.Start == intersection.Location) && (endRoad.End == lastIntersectionOfPath.Location || endRoad.Start == lastIntersectionOfPath.Location))
                        {
                            return(newPath.PathToRoadList());
                        }
                        else
                        {
                            throw new Exception("roads are not horizontal or vertical");
                        }
                    }
                }
                // set the new list
                listPaths = newListPaths;
            }
            return(null);
        }
コード例 #8
0
ファイル: AlgorithmAStar.cs プロジェクト: TheKoen/SE1d3-KBS2
        public Destination Calculate(long callerId, Destination carDestination, Destination endDestination)
        {
            var network   = NodeNetwork.NodeNetwork.GetInstance();
            var startNode = new Node(GPSSystem.FindIntersection(carDestination.Location).Location);
            var endNodes  = AlgorithmTools.IntersectionTupleToNodeTuple(
                AlgorithmTools.GetIntersectionOrderForRoadSide(endDestination.Road, endDestination.Location));

            Node   nextNode;
            double roadX, roadY;

            if (startNode.Equals(endNodes.Item1))
            {
                #if DEBUG
                AlgorithmDebuggerWindow.Instance.AddNetworkResult(_debuggerIndex++.ToString(), network,
                                                                  startNode, endNodes.Item2, endNodes);
                #endif
                return(endDestination);
            }

            if (_calculationCache.ContainsKey(callerId))
            {
                var tuple = _calculationCache[callerId];
                if (tuple.Item1.Equals(endDestination))
                {
                    var path     = tuple.Item2;
                    var thisNode = path.Single(n => n.Equals(startNode));
                    nextNode = thisNode.ConnectedTo;

                    #if DEBUG
                    AlgorithmDebuggerWindow.Instance.AddNetworkResult(_debuggerIndex++.ToString(), network,
                                                                      startNode, nextNode, endNodes);
                    #endif
                    roadX = (startNode.PositionX - nextNode.PositionX) / 2.0 + nextNode.PositionX;
                    roadY = (startNode.PositionY - nextNode.PositionY) / 2.0 + nextNode.PositionY;
                    return(new Destination
                    {
                        Location = new Vector(nextNode.PositionX, nextNode.PositionY),
                        Road = GPSSystem.NearestRoad(new Vector(roadX, roadY))
                    });
                }

                _calculationCache.Remove(callerId);
            }

            var endNode = endNodes.Item1;
            nextNode = CalculatePathNextNode(callerId, ref network, ref startNode, ref endNode, endDestination);

            #if DEBUG
            AlgorithmDebuggerWindow.Instance.AddNetworkResult("AS" + _debuggerIndex++, network,
                                                              startNode, nextNode, endNodes);
            #endif
            roadX = (startNode.PositionX - nextNode.PositionX) / 2.0 + nextNode.PositionX;
            roadY = (startNode.PositionY - nextNode.PositionY) / 2.0 + nextNode.PositionY;
            return(new Destination
            {
                Location = new Vector(nextNode.PositionX, nextNode.PositionY),
                Road = GPSSystem.NearestRoad(new Vector(roadX, roadY))
            });
        }
コード例 #9
0
        public CustomerGroupController(CustomerGroup group)
        {
            Group = group;
            var road = GPSSystem.NearestRoad(group.Location);

            MoveToNearestRoad(road);
            Group.RoadsNear = GPSSystem.GetRoadsInRange(Group.Location, GroupRadius);
        }
コード例 #10
0
ファイル: MainScreen.xaml.cs プロジェクト: TheKoen/SE1d3-KBS2
        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            SimulationControlHandler.ResetButtonClick();
            LabelSimulationTime.Content = "00:00:00";
            Stopwatch.Reset();

            CommandLoop.Register();
            WPFLoop.Register();
            AILoop.Register();
            GPSSystem.Setup();
        }
コード例 #11
0
ファイル: AStar.cs プロジェクト: TheKoen/SE1d3-KBS2
        public override List <Road> CalculatePath(Vector start, CustomerGroup group)
        {
            var startRoad = GPSSystem.NearestRoad(start);
            var endRoad   = GPSSystem.NearestRoad(group.Location);

            var listPaths = new List <Path>();

            // if the startroad equals to the endRoad
            if (startRoad == endRoad)
            {
                return(new List <Road> {
                    startRoad
                });
            }
            ;

            //add the first two intersections of the startRoad to the PathList;
            foreach (var item in GPSSystem.FindIntersectionsRoad(startRoad))
            {
                listPaths.Add(new Path(start, group.Location, item));
            }
            // order list
            orderListByPriority(ref listPaths);

            // loop until the end is found
            while (true)
            {
                // new found intersections
                var lastIntersectionOfPath = listPaths[0].Intersections.Last();

                var newFoundIntersections = GPSSystem.FindNextIntersections(lastIntersectionOfPath);

                // add the path of every new intersetion to the new ListPath
                foreach (var intersection in newFoundIntersections)
                {
                    var intersections = new List <Intersection>(listPaths[0].Intersections);
                    intersections.Add(intersection);
                    var newPath = new Path(start, group.Location, intersection);
                    listPaths.Add(newPath);

                    // check if endLocation is between these intersections

                    if ((endRoad.End == intersection.Location || endRoad.Start == intersection.Location) && (endRoad.End == lastIntersectionOfPath.Location || endRoad.Start == lastIntersectionOfPath.Location))
                    {
                        return(newPath.PathToRoadList());
                    }
                }
                listPaths.RemoveAt(0);
                orderListByPriority(ref listPaths);
            }
        }
コード例 #12
0
ファイル: CarController.cs プロジェクト: TheKoen/SE1d3-KBS2
        private static Vector GetClosestRoadPoint(Vector location)
        {
            var road = GPSSystem.GetRoad(location);

            if (road == null)
            {
                throw new ArgumentException("Location is not on a road!");
            }

            return(GPSSystem.CalculateDistance(location, road.Start) <
                   GPSSystem.CalculateDistance(location, road.End)
                ? road.Start
                : road.End);
        }
コード例 #13
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        public void NearestRoadTest(int x1b, int y1b, int x1e, int y1e, int x2b, int y2b, int x2e, int y2e, int ex,
                                    int ey)
        {
            var road1 = new Road(new Vector(x1b, y1b), new Vector(x1e, y1e), 20, 100);
            var road2 = new Road(new Vector(x2b, y2b), new Vector(x2e, y2e), 20, 100);

            var city = new CityBuilder()
                       .Road(road1)
                       .Road(road2)
                       .Build();

            var road = GPSSystem.NearestRoad(new Vector(ex, ey));

            Assert.AreEqual(road, road1);
        }
コード例 #14
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        /*[TestCase(35, 85, DirectionCar.North, 90, 60, 2, 3, 0, 90, 75)]
         * [TestCase(45, 5, DirectionCar.West, 45, 90, 5, 0, 3, 35, 70)]
         * [TestCase(35, 85, DirectionCar.North, 90, 60, 2, 2, 0, 102.5, 60)]*/
        public void GetDirectionTest(double cX, double cY, DirectionCar direction, double dX, double dY, int road,
                                     int destRoad, int intersection, double eX, double eY)
        {
            var roads = new[]
            {
                new Road(new Vector(35, 80), new Vector(35, 100), 10, 0),
                new Road(new Vector(0, 75), new Vector(30, 75), 10, 0),
                new Road(new Vector(40, 75), new Vector(90, 75), 10, 0),
                new Road(new Vector(95, 70), new Vector(95, 10), 10, 0),
                new Road(new Vector(40, 5), new Vector(90, 5), 10, 0),
                new Road(new Vector(35, 10), new Vector(35, 70), 10, 0)
            };

            var intersections = new[]
            {
                new Intersection(new Vector(35, 75), 10),
                new Intersection(new Vector(95, 75), 10),
                new Intersection(new Vector(95, 5), 10),
                new Intersection(new Vector(35, 5), 10)
            };

            var city = new CityBuilder()
                       .Road(roads[0])
                       .Road(roads[1])
                       .Road(roads[2])
                       .Road(roads[3])
                       .Road(roads[4])
                       .Road(roads[5])
                       .Intersection(intersections[0])
                       .Intersection(intersections[1])
                       .Intersection(intersections[2])
                       .Intersection(intersections[3])
                       .Build();

            var car = new Car(1, CarModel.GetModel("TestModel"), new Vector(cX, cY), new List <Sensor>(), null, direction, 5, 5);

            city.Cars.Add(car);

            car.Destination = new Destination {
                Location = new Vector(dX, dY), Road = roads[destRoad]
            };

            var carDestination = GPSSystem.GetDirection(car, intersections[intersection]);

            Assert.AreEqual(roads[road], carDestination.Road);
            Assert.AreEqual(eX, carDestination.Location.X, 0.01);
            Assert.AreEqual(eY, carDestination.Location.Y, 0.01);
        }
コード例 #15
0
ファイル: Path.cs プロジェクト: TheKoen/SE1d3-KBS2
        public List <Road> PathToRoadList()
        {
            var listRoads = new List <Road>();

            foreach (var road in City.Instance.Roads)
            {
                if (Intersections.FindAll(i => i.Location == road.Start)
                    .FindAll(i => i.Location == road.End).Count > 0)
                {
                    listRoads.Add(road);
                }
            }
            listRoads.Add(GPSSystem.NearestRoad(Start));
            listRoads.Add(GPSSystem.NearestRoad(End));

            return(listRoads);
        }
コード例 #16
0
        public void TestLookForNearestRoad(double groupX, double groupY, bool road)
        {
            var building = new Building(new Vector(groupX, groupY), 8);
            var road1    = new Road(new Vector(0, 50), new Vector(10, 50), 10, 100);
            var road2    = new Road(new Vector(0, 20), new Vector(10, 20), 10, 100);
            var city     = new CityBuilder()
                           .Road(road1)
                           .Road(road2)
                           .Building(building)
                           .Build();

            var group = new CustomerGroup(5, building, null);

            var result = GPSSystem.NearestRoad(group.Location);

            Assert.AreEqual(road ? road1 : road2, result);
        }
コード例 #17
0
ファイル: GPSSystemTest.cs プロジェクト: TheKoen/SE1d3-KBS2
        // get road location
        public void GetRoadTest(int x1b, int y1b, int x1e, int y1e, int x2b, int y2b, int x2e, int y2e, int sx, int sy)
        {
            var road1 = new Road(new Vector(x1b, y1b), new Vector(x1e, y1e), 20, 100);
            var road2 = new Road(new Vector(x2b, y2b), new Vector(x2e, y2e), 20, 100);

            var city = new CityBuilder()
                       .Road(road1)
                       .Road(road2)
                       .Build();

            if (GPSSystem.GetRoad(new Vector(x1b, y1b)).Equals(road1))
            {
                Assert.Pass();
            }
            else
            {
                Assert.Fail();
            }
        }
コード例 #18
0
ファイル: MainScreen.xaml.cs プロジェクト: TheKoen/SE1d3-KBS2
        private void Initialize()
        {
            GPSSystem.Setup();

            CityRenderHandler        = new CityRenderHandler(this, CanvasMain);
            CustomerRenderHandler    = new CustomerRenderHandler(CanvasMain, this);
            CarRenderHandler         = new CarRenderHandler(CanvasMain, this);
            SimulationControlHandler = new SimulationControlHandler(this);
            PropertyDisplayHandler   = new PropertyDisplayHandler(this);
            ZoomHandler = new ZoomHandler(this);

            DrawingLoop.Start();
            ZoomLoop.Start();

            WPFLoop.Subscribe(Update);

            CommandLoop.Subscribe(CmdUpdate);

            PreviewMouseWheel           += ZoomHandler.Scroll;
            ResultImport.ResultImported += ResultImportComplete;
        }
コード例 #19
0
ファイル: CarBuilder.cs プロジェクト: TheKoen/SE1d3-KBS2
        public Car Build()
        {
            if (location == null)
            {
                throw new ArgumentException("Location cannot be null");
            }

            var car = new Car(ID++, model, location, new List <Sensor>(), null, direction, width, length)
            {
                CurrentRoad = currentRoad
            };

            sensors.ForEach(creator => car.Sensors.Add(creator(car)));

            if (car.CurrentRoad == null)
            {
                car.CurrentRoad = GPSSystem.GetRoad(location);
            }

            return(car);
        }
コード例 #20
0
ファイル: CommandMap.cs プロジェクト: TheKoen/SE1d3-KBS2
        private static void PrintMap()
        {
            var builder = new StringBuilder();

            builder.Append('\n');

            for (var y = 0; y < 450; y += 10)
            {
                for (var x = 0; x < 800; x += 10)
                {
                    var vector = new Vector(x, y);
                    if (GPSSystem.FindIntersection(vector) != null)
                    {
                        builder.Append('%');
                    }
                    else if (GPSSystem.GetRoad(vector) != null)
                    {
                        builder.Append('#');
                    }
                    else if (IsCustomer(vector))
                    {
                        builder.Append('$');
                    }
                    else if (IsBuilding(vector))
                    {
                        builder.Append('@');
                    }
                    else
                    {
                        builder.Append(' ');
                    }
                }

                builder.Append('\n');
            }

            App.Console.Print(builder.ToString());
        }
コード例 #21
0
ファイル: NodeNetwork.cs プロジェクト: TheKoen/SE1d3-KBS2
        public static void GenerateNetwork(List <Road> roads, List <Intersection> intersections)
        {
            Nodes = new Node[intersections.Count];
            Links = new Link[roads.Count];

            // Adding Nodes using Intersections
            for (var i = 0; i < Nodes.Length; ++i)
            {
                var intersectionLocation = intersections[i].Location;
                Nodes[i] = new Node(intersectionLocation.X, intersectionLocation.Y);
            }

            // Adding Links using Roads
            for (var i = 0; i < Links.Length; ++i)
            {
                var endpointA = new Node(GPSSystem.FindIntersection(roads[i].Start).Location);
                var endpointB = new Node(GPSSystem.FindIntersection(roads[i].End).Location);
                var nodeA     = Nodes.Single(node => node.Equals(endpointA));
                var nodeB     = Nodes.Single(node => node.Equals(endpointB));

                Links[i] = new Link(ref nodeA, ref nodeB);
            }
        }
コード例 #22
0
        public void Update()
        {
            var buitenRange = Group.Customers.Any(c => MathUtil.Distance(c.Location, Group.Location) > GroupRadius);

            if (RequestedCar)
            {
                var car = City.Instance.Cars.Find(c => MathUtil.Distance(c.Location, Group.Location) < 20);
                if (car == null || car.Passengers.Count > 0)
                {
                    return;
                }


                Group.Customers.ForEach(customer => customer.Controller.Destroy());
                MainScreen.AILoop.Unsubscribe(Update);
                car.Passengers.AddRange(Group.Customers);
                var destination = Group.Destination.Location;
                App.Console.Print($"Passengers entered car {car.Id} with destination {destination}", Colors.Blue);
                car.Destination = new Destination {
                    Location = destination, Road = GPSSystem.NearestRoad(destination)
                };
                car.Controller.PassengersReady();
                return;
            }

            if (buitenRange)
            {
                return;
            }
            var road = GPSSystem.NearestRoad(Group.Destination.Location);

            GPSSystem.RequestCar(new CarSystem.Destination {
                Location = Group.Destination.Location, Road = road
            }, Group);
            RequestedCar = true;
        }
コード例 #23
0
ファイル: AlgorithmAStar.cs プロジェクト: TheKoen/SE1d3-KBS2
        private static Node CalculatePathNextNode(long callerId, ref NodeNetworkCopy network, ref Node startNode, ref Node endNode, Destination endDestination)
        {
            var openNodes = new List <ConnectedNode> {
                new ConnectedNode(endNode)
            };
            var           closedNodes = new List <ConnectedNode>();
            ConnectedNode lastNode    = null;

            var updateIndex = 0;

            while (true)
            {
                // propogate
                var thisNode = openNodes.First();
                openNodes.Remove(thisNode);
                closedNodes.Add(thisNode);

                var neighbours = network.Links
                                 .Where(l => l.NodeA.Equals(thisNode) || l.NodeB.Equals(thisNode))
                                 .Select(l => l.NodeA.Equals(thisNode) ? new ConnectedNode(l.NodeB) : new ConnectedNode(l.NodeA))
                                 .ToList();

                // calculate
                var foundEnd = false;
                foreach (var n in neighbours)
                {
                    if (closedNodes.SingleOrDefault(cn => cn.Equals(n)) != null)
                    {
                        continue;
                    }

                    if (n.Equals(startNode))
                    {
                        foundEnd = true;
                        lastNode = n;
                    }

                    n.ConnectedTo = thisNode;
                    n.Value       = Math.Sqrt(Math.Pow((n.PositionX - startNode.PositionX), 2) + Math.Pow((n.PositionY - startNode.PositionY), 2));
                    network.Nodes.Single(nn => nn.Equals(n)).Value = n.Value;
                    #if DEBUG
                    AlgorithmDebuggerWindow.Instance.AddNodeUpdateResult($"AS{_debuggerIndex}${updateIndex++}", network,
                                                                         n, thisNode);
                    #endif
                    openNodes.Add(n);
                }

                if (foundEnd)
                {
                    break;
                }

                // sort
                openNodes = openNodes.OrderBy(n => n.Value).ToList();

                // info
                #if DEBUG
                AlgorithmDebuggerWindow.Instance.AddNetworkResult($"AS{_debuggerIndex}#{openNodes.First().Value}", network,
                                                                  thisNode, openNodes.First());
                #endif
            }

            var roadX  = (startNode.PositionX - lastNode.ConnectedTo.PositionX) / 2.0 + lastNode.ConnectedTo.PositionX;
            var roadY  = (startNode.PositionY - lastNode.ConnectedTo.PositionY) / 2.0 + lastNode.ConnectedTo.PositionY;
            var result = new Destination
            {
                Location = new Vector(lastNode.ConnectedTo.PositionX, lastNode.ConnectedTo.PositionY),
                Road     = GPSSystem.NearestRoad(new Vector(roadX, roadY))
            };

            if (_calculationCache.ContainsKey(callerId))
            {
                _calculationCache.Remove(callerId);
            }
            _calculationCache.Add(callerId, new Tuple <Destination, List <ConnectedNode> >(endDestination, closedNodes));

            // find next node
            return(lastNode.ConnectedTo);
        }
コード例 #24
0
    public void DoCheckIn()
    {
        if (!PlayerStatus.Instance.CheckExistCheckin(placeID))
        {
            if (isLocationEnable)
            {
                GPSSystem gps = GPSSystem.Instance;
                if (!gps.dataReady)
                {
                    //if (false) {
                    Popup.Instance.showPopup("Checkin", "GPS ยังไม่พร้อมใช้งาน \r\nกรุณาลองใหม่อีกครั้งภายหลัง");
                    gps.startGPSService();
                }
                else
                {
                    if (GPSSystem.IsInPolygon(points, gps.getCurrentLocationPoint()))
                    {
                        PlayerStatus ps = PlayerStatus.Instance;
                        //if (true) {
                        // Get Special Item
                        //Debug.Log("You got item");
                        PlaceData pd = new PlaceData(placeID, title, detail, city, imgCollection);
                        pd.SetTimeNow();
                        ps.AddPlaceToList(pd);
                        DGTRemote.GetInstance().RequestSendCheckin(placeID, pd.time);
                        if (itemID != 0)
                        {
                            //Debug.Log("Give item by Checkin");
                            // OLD

                            /*GameObject reward = ItemManager.GetItemGameObject(itemID);
                             * Popup.Instance.showPopup("Checkin" , "Checkin ที่ " + title +
                             *  "สำเร็จ. \r\nคุณได้รับไอเท็ม " + reward.GetComponent<Item>().getItemName() );
                             * Inventory.Instance.CollectItemToInventory(reward, true);*/
                            Item reward = ItemManager.GetItemComponent(itemID);
                            Popup.Instance.showPopup("Checkin", "Checkin ที่ " + title +
                                                     "สำเร็จ. \r\nคุณได้รับไอเท็ม " + reward.GetItemName());
                            Inventory.Instance.CollectItemToInventory(reward);
                        }
                        else if (equipment)
                        {
                            Item equipmentReward = ItemManager.GetItemEquipmentBodyByEquipmentValue(equipmentValue, ps.gender, ps.job);
                            Popup.Instance.showPopup("Checkin", "Checkin ที่ " + title +
                                                     "สำเร็จ. \r\nคุณได้รับไอเท็ม " + equipmentReward.GetItemName());
                            Inventory.Instance.CollectItemToInventory(equipmentReward);
                        }
                    }
                    else
                    {
                        Popup.Instance.showPopup("Checkin", "Checkin ล้มเหลว \r\nคุณไม่ได้อยู่ในสถานที่ดังกล่าว");
                        // You not stay in this place :(
                        //Debug.Log("You not in this place :(");
                    }
                }
            }
            else
            {
                Popup.Instance.showPopup("Checkin " + title, "ยังไม่สามารถ Checkin สถานที่นี้ได้ \r\n ขออภัยในความไม่สะดวก");
            }
        }
        else
        {
            Popup.Instance.showPopup("Checkin " + title, "คุณเคย Checkin สถานที่นี้ไปแล้ว");
        }
    }
コード例 #25
0
        public Car SpawnCar(int id, Destination finalDestination)
        {
            if (!hasDirection)
            {
                var nearest = GPSSystem.NearestRoad(Location);
                Direction    = nearest.IsXRoad() ? DirectionCar.East : DirectionCar.North;
                hasDirection = true;
            }

            if (AvailableCars <= 0)
            {
                return(null);
            }

            foreach (var cityCar in City.Instance.Cars)
            {
                if (MathUtil.Distance(Location, cityCar.Location) < 100)
                {
                    var thread = new Thread(() =>
                    {
                        Thread.Sleep(1000);
                        SpawnCar(id, finalDestination);
                    });
                    thread.Start();
                    return(null);
                }
            }

            var road = GPS.GPSSystem.NearestRoad(Location);

            double x;
            double y;

            if (road.IsXRoad())
            {
                x = Location.X;
                y = Direction == DirectionCar.East ? road.Start.Y + road.Width / 3d : road.Start.Y - road.Width / 3d;
            }
            else
            {
                y = Location.Y;
                x = Direction == DirectionCar.South ? road.Start.X - road.Width / 3d : road.Start.X + road.Width / 3d;
            }

            var    location = new Vector(x, y);
            var    car      = Model.CreateCar(id, location, this, Direction);
            Vector destination;

            switch (Direction)
            {
            case DirectionCar.North:
                destination = new Vector(road.Start.X, Math.Min(road.Start.Y, road.End.Y));
                break;

            case DirectionCar.South:
                destination = new Vector(road.Start.X, Math.Max(road.Start.Y, road.End.Y));
                break;

            case DirectionCar.East:
                destination = new Vector(Math.Max(road.Start.X, road.End.X), road.Start.Y);
                break;

            case DirectionCar.West:
                destination = new Vector(Math.Min(road.Start.X, road.End.X), road.Start.Y);
                break;

            default:
                throw new ArgumentException("Unknown direction");
            }
            car.Destination = new Destination
            {
                Location = destination,
                Road     = road
            };
            car.CurrentTarget = destination;
            City.Instance.Cars.Add(car);
            AvailableCars--;
            car.Destination = finalDestination;
            return(car);
        }
コード例 #26
0
 public List <Road> GetRoads()
 {
     return(GPSSystem.GetRoadsInRange(Location, Size));
 }
コード例 #27
0
ファイル: CarController.cs プロジェクト: TheKoen/SE1d3-KBS2
        /// <summary>
        /// Runs the main car logic. Needs to be subscribed to the MainLoop.
        /// </summary>
        public void Update()
        {
            // If we're not initialized, initialize!
            if (!initialized)
            {
                Init();
            }

            // Update the passenger count.
            Car.PassengerCount = Car.Passengers.Count;

            // Update the current road with the road at our location.
            Car.CurrentRoad         = GPSSystem.GetRoad(Car.Location);
            Car.CurrentIntersection = GPSSystem.FindIntersection(Car.Location);

            if (Car.CurrentRoad == null && Car.CurrentIntersection == null)
            {
                if (!resetTarget)
                {
                    resetTarget = true;
                    var closestRoad = GPSSystem.NearestRoad(Car.Location);
                    if (closestRoad != null && Car != null)
                    {
                        Car.CurrentTarget =
                            MathUtil.Distance(closestRoad.End, Car.Location) >
                            MathUtil.Distance(closestRoad.Start, Car.Location)
                                ? closestRoad.Start
                                : closestRoad.End;
                        App.Console.Print($"[C{Car.Id}] Lost road, trying to get back on, targeting {Car.CurrentTarget}", Colors.Blue);
                    }
                    ;
                }
            }
            else if (resetTarget)
            {
                App.Console.Print($"[C{Car.Id}] Road found again", Colors.Blue);
                resetTarget = false;
            }

            // Calculate the distance to the local target (usually the next intersection).
            var distanceToTarget = MathUtil.Distance(Car.Location, Car.CurrentTarget);
            // Calculate the distance to the destination.
            var distanceToDestination = MathUtil.Distance(Car.Location, Car.Destination.Location);
            // Calculate the relative yaw (in degrees).
            var yaw = MathUtil.VectorToAngle(Car.Rotation, Car.Direction);
            // Get the current velocity of the car.
            var velocity = Car.Velocity;
            // Create a variable to store the added rotation in this update call.
            var addedRotation      = 0.0;
            var closeToDestination = CloseToDestination();

            // Check if we're close to our target but not the destination.
            if (distanceToTarget < 20 && !closeToDestination && !resetTarget)
            {
                // Check if we've not obtained a new target yet.
                if (!obtainedNewTarget)
                {
                    // Find the nearest intersection.
                    var intersection = GPSSystem.FindIntersection(GetClosestRoadPoint(Car.Location));
                    if (intersection == null)
                    {
                        return;
                    }

                    App.Console.Print($"[C{Car.Id}] Requesting new target from intersection {intersection.Location}...", Colors.Blue);

                    // Request the next target from the GPSSystem.
                    var target = GPSSystem.GetDirection(Car, intersection);

                    // Update our target.
                    newTarget         = target.Location;
                    obtainedNewTarget = true;

                    var distance = Math.Round(MathUtil.Distance(newTarget, Car.Location));
                    App.Console.Print($"[C{Car.Id}] Obtained a new target {newTarget} ({distance}m away)", Colors.Blue);
                }
            }
            else
            {
                obtainedNewTarget = false;
            }

            // Check if we are turning.
            if (turning > 0)
            {
                turning--;

                // Check if we locked on the new target yet.
                if (newTarget.X > -1)
                {
                    // Lock on the new target and reset newTarget.
                    Car.CurrentTarget = newTarget;
                    newTarget         = new Vector(-1, -1);
                    App.Console.Print($"[C{Car.Id}] Locked on to target", Colors.Blue);
                }

                // Call the handle function to turn.
                HandleTurn(ref velocity, ref yaw, ref addedRotation);
            }
            // Check if we're still turning around.
            else if (flipping)
            {
                // Stop turning around.
                flipping = false;
                App.Console.Print($"[C{Car.Id}] Turn-around done", Colors.Blue);
            }

            // Check if we're on an intersection.
            if (Car.CurrentIntersection != null)
            {
                // Reset our turn timer.
                turning = 20;
            }
            else
            {
                // Check if we're not close to the destination.
                if (!closeToDestination)
                {
                    // If we're still approaching, stop approaching.
                    if (approach)
                    {
                        approach = false;
                        App.Console.Print($"[C{Car.Id}] Approach done", Colors.Blue);
                    }

                    // Call the handle functions to stay in the lane and accelerate/deccelerate.
                    HandleStayInLane(ref velocity, ref yaw, ref addedRotation);
                    HandleAccelerate(ref velocity, ref distanceToTarget);
                }
                else
                {
                    // If we're not approaching, start approaching.
                    if (!approach)
                    {
                        approach = true;
                        App.Console.Print($"[C{Car.Id}] Initiating approach", Colors.Blue);
                    }

                    // Call the handle function to approach the target.
                    HandleApproachTarget(ref velocity, ref yaw, ref addedRotation, ref distanceToDestination);
                }
            }

            // Update the car's velocity with the result of the handle functions:
            // Temporarily store the current speed.
            var speed = velocity.Length;

            // Rotate the velocity based on the addedRotation this tick.
            velocity = MathUtil.RotateVector(velocity, -addedRotation);
            // Normalize the velocity and multiply with the speed to make sure it stays the same.
            velocity.Normalize();
            velocity = Vector.Multiply(velocity, speed);
            // Actually update the car's velocity.
            Car.Velocity = velocity;

            // Calculate the rotation by normalizing the velocity.
            var rotation = new Vector(velocity.X, velocity.Y);

            rotation.Normalize();

            // If the rotation vector is invalid or the car is not moving, set the rotation to the absolute direction.
            if (rotation.Length < 0.9 || double.IsNaN(rotation.Length) || velocity.Length < 0.1)
            {
                rotation = Car.Direction.GetVector();
            }

            // Actually update the rotation and update the absolute direction.
            Car.Rotation  = rotation;
            Car.Direction = DirectionCarMethods.Parse(rotation);

            // Update the car's location by adding the velocity to it.
            Car.Location          = Vector.Add(Car.Location, Car.Velocity);
            Car.DistanceTraveled += Car.Velocity.Length;
        }