Ejemplo n.º 1
0
    // Update is called once per frame
    void Update()
    {
        if (targetLight.isGreen == false)
        {
            targetTransform = spawner.lights[Random.Range(0, spawner.lights.Length)].transform;
            targetLight     = targetTransform.GetComponent <TrafficLights>();
        }
        if (Vector3.Distance(this.transform.position, targetTransform.transform.position) < 0.5)
        {
            targetTransform = spawner.lights[Random.Range(0, spawner.lights.Length)].transform;
            targetLight     = targetTransform.GetComponent <TrafficLights>();
        }
        if (targetTransform != null)
        {
            target = targetTransform.position;
        }
        force = CalculateForce();
        acc   = force / mass;
        vel  += acc * Time.deltaTime;

        transform.position += vel * Time.deltaTime;
        speed = vel.magnitude;

        if (speed > 0)
        {
            Vector3 tempUp = Vector3.Lerp(transform.up, Vector3.up + acc, Time.deltaTime * 3.0f);
            transform.LookAt(transform.position + vel, tempUp);
            vel -= (damping * vel * Time.deltaTime);
        }
    }
Ejemplo n.º 2
0
        public bool TrafficLightWork()
        {
            if (_time != _switchTime && _trafficLights != TrafficLights.Yellow) { _time++; }

            if (_trafficLights == TrafficLights.Yellow)
            {
                _trafficLights = TrafficLights.Red;
                if (_trafficLightDelegate != null)
                {
                    _trafficLightDelegate.Invoke();
                }
                _switchTime = _randomSwitchTime.Next(20);
                _time = -1;
                return true;
            }
            else if (_time == _switchTime)
            {
                _trafficLights = TrafficLights.Yellow;
                if (_trafficLightDelegate != null)
                {
                    _trafficLightDelegate.Invoke();
                }
                _switchTime = _randomSwitchTime.Next(20);
                return true;
            }
            else
            {
                _trafficLights = TrafficLights.Green;
            }
            return false;
        }
Ejemplo n.º 3
0
 public TrafficLight(TrafficLightDelegate trafficLightDelegate)
 {
     _trafficLightDelegate = trafficLightDelegate;
     _switchTime = _randomSwitchTime.Next(20);
     _time = -1;
     _trafficLights = TrafficLights.Green;
 }
Ejemplo n.º 4
0
		public void Initialize()
		{
			var lightBarrier1 = new LightBarrier(position: 200);
			var lightBarrier2 = new LightBarrier(position: 400);

			var detectorLeft = new OverheadDetector(Lane.Left, position: 400);
			var detectorRight = new OverheadDetector(Lane.Right, position: 400);
			var detectorFinal = new OverheadDetector(Lane.Left, position: 600);

			var trafficLights = new TrafficLights();

			var preControl = new OriginalPreControl(lightBarrier1);
			var mainControl = new OriginalMainControl(lightBarrier2, detectorLeft, detectorRight, timeout: 30);
			var endControl = new OriginalEndControl(detectorFinal, timeout: 10);

			var vehicle1 = new Vehicle(VehicleKind.OverheightTruck);
			var vehicle2 = new Vehicle(VehicleKind.Truck);
			var vehicle3 = new Vehicle(VehicleKind.OverheightTruck);

			var heightControl = new HeightControl(preControl, mainControl, endControl, trafficLights);
			var vehicles = new VehicleCollection(vehicle1, vehicle2, vehicle3);

			_model = new Model();
			_model.AddRootComponents(heightControl, vehicles);

			Bind(vehicles, lightBarrier1);
			Bind(vehicles, lightBarrier2);
			Bind(vehicles, detectorLeft);
			Bind(vehicles, detectorRight);
			Bind(vehicles, detectorFinal);

			_model.Bind(vehicles.RequiredPorts.IsTunnelClosed = trafficLights.ProvidedPorts.IsRed);
		}
Ejemplo n.º 5
0
        public void ShouldNotPermitTrafficLightsToParticipateInMultipleTetheredClusters()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight();
            var l2 = new TrafficLight();
            var l3 = new TrafficLight();
            var l4 = new TrafficLight();
            var l5 = new TrafficLight();

            var t1 = new TetheredTrafficLightCluster {l1, l2}; //l1 assigned to Tethered Cluster
            var t2 = new TetheredTrafficLightCluster {l3, l4};
            var t3 = new TetheredTrafficLightCluster {l5, l1}; //l1 already assigned to Tethered Cluster

            Assert.IsTrue(lights.Add(t1));
            Assert.IsTrue(lights.Add(t2));
            Assert.IsFalse(lights.Add(t3));

            Assert.IsNull(lights.GetClusterFor(l5.Id).TetheredLights);

            Assert.AreEqual(4, lights.Count()); //l5 not added due to invalid cluster
            Assert.AreEqual(2, lights.AllTetheredClusters.Count());  

            Assert.AreEqual(lights.GetClusterFor(l5.Id), (null, null));
        }
        private static void HandleChangeTrafficLightsClick(UIMouseEventParameter evt, TrafficLights.ChangeMode mode, bool requiresControl)
        {
            if (evt.buttons != UIMouseButton.Left)
            {
                return;
            }
            if (requiresControl && !(Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)))
            {
                return;
            }

            var currentTime = Time.time;

            if (currentTime - _lastChangeTime >= MinTimeBetweenChanges)
            {
                _lastChangeTime = currentTime;
            }
            else
            {
                //not enough time passed
                DebugLog.Info("Not enough time passed for another update");
                return;
            }

            DebugLog.Info($"Change all intersections: {mode} all");
            TrafficLights.ChangeAllFast(mode);
//      var stats = TrafficLights.ChangeAll(mode);
            //todo: handle stats?
        }
Ejemplo n.º 7
0
        public void ShouldNotPermitTrafficLightsToParticipateInMultiplePolarClusters()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight { Name = "TL-1" };
            var l2 = new TrafficLight { Name = "TL-2" };
            var l3 = new TrafficLight { Name = "TL-3" };
            var l4 = new TrafficLight { Name = "TL-4" };
            var l5 = new TrafficLight { Name = "TL-5" };
            var l6 = new TrafficLight { Name = "TL-6" };

            var t1 = new PolarTrafficLightCluster(l3) {l1, l2}; 
            t1.Name = "Polar Cluster 1";

            var t2 = new PolarTrafficLightCluster(l5) {l4};
            t2.Name = "Polar Cluster 2";

            var t3 = new PolarTrafficLightCluster(l5) {l6}; //l5 already assigned to Polar Cluster
            t3.Name = "Polar Cluster 3";

            Assert.IsTrue(lights.Add(t1));
            Assert.IsTrue(lights.Add(t2));
            Assert.IsFalse(lights.Add(t3));

            Assert.AreEqual(5, lights.Count()); //Traffic lights in invalid clusters not added
            Assert.AreEqual(2, lights.AllPolarClusters.Count());  //l3 & l5 Polar Clusters
        }
        private static void TimeChange(TrafficLights.ChangeMode mode)
        {
            var numberOfTests = 1000;

            TrafficLights.ChangeAll(mode);
            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < numberOfTests; i++)
            {
                TrafficLights.ChangeAll(mode);
            }
            sw.Stop();
            var stats = sw.Elapsed;

            sw.Reset();
            sw.Start();
            for (var i = 0; i < numberOfTests; i++)
            {
                TrafficLights.ChangeAllFast(mode);
            }
            sw.Stop();
            var fast = sw.Elapsed;

            DebugLog.Info($"Stats: {stats}, Fast: {fast}");

            //Add: (small map, 1000 iterations)
            //  Stats: 00:00:47.1062748
            //  Fast : 00:00:02.5574887
        }
Ejemplo n.º 9
0
    public void Change()
    {
        this.TraficLight++;

        if ((int)this.TraficLight > 2)
        {
            this.TraficLight = 0;
        }
    }
Ejemplo n.º 10
0
    public void Change()
    {
        this.RtLight += 1;

        if ((int)this.RtLight > 2)
        {
            this.RtLight = 0;
        }
    }
Ejemplo n.º 11
0
        public void Cycle()
        {
            this.Light += 1;

            if ((int)this.Light > 2)
            {
                this.Light = 0;
            }
        }
Ejemplo n.º 12
0
		/// <summary>
		///   Initializes a new instance.
		/// </summary>
		/// <param name="preControl">The pre-control step of the height control.</param>
		/// <param name="mainControl">The main-control step of the height control.</param>
		/// <param name="endControl">The end-control step of the height control.</param>
		/// <param name="trafficLights">The traffic lights that are used to signal that the tunnel is closed.</param>
		public HeightControl(IPreControl preControl, IMainControl mainControl, IEndControl endControl, TrafficLights trafficLights)
		{
			_preControl = preControl;
			_mainControl = mainControl;
			_endControl = endControl;
			_trafficLights = trafficLights;

			Bind(_mainControl.RequiredPorts.GetNumberOfEnteringVehicles = _preControl.ProvidedPorts.GetNumberOfEnteringVehicles);
			Bind(_endControl.RequiredPorts.ActivationRequested = _mainControl.ProvidedPorts.IsVehicleLeavingOnRightLane);
		}
Ejemplo n.º 13
0
 static void Main(string[] args)
 {
     try
     {
         TrafficLights TrafficLights = ReadInputFile(path + fileName);
         OutPutFile    outPutFile    = new OutPutFile();
         outPutFile = ScheduleIntersection(TrafficLights);
         WriteOutputFile(outPutFile);
     }
     catch (Exception exc) { Console.WriteLine(exc.Message); }
 }
    void Start()
    {
        current      = gameObject.GetComponent <Transform>();
        trafficLight = traffic.GetComponent <TrafficLights>();
        agent        = GetComponent <NavMeshAgent>();

        // Disabling auto-braking allows for continuous movement
        // between points (ie, the agent doesn't slow down as it
        // approaches a destination point).
        agent.autoBraking = false;
    }
Ejemplo n.º 15
0
        public void ShouldStartTrafficLightCycle()
        {
            var configuration = new TrafficLightConfig();

            configuration.Add(TrafficLightState.Go, 4);
            configuration.Add(TrafficLightState.Stop, 4);
            SetTrafficLightConfiguration(configuration);

            var lights = new TrafficLights {
                _l1, _l2, _l3, _l4
            };
            var timer = new TrafficLightTimer();

            var tc1 = new TetheredTrafficLightCluster {
                _l1, _l2
            };

            tc1.Name = "TC-1";

            var pc1 = new PolarTrafficLightCluster(_l3)
            {
                { _l4 }
            };

            pc1.Name = "TC-2";

            Assert.IsTrue(lights.Add(tc1));
            Assert.IsTrue(lights.Add(pc1));

            var controller = new TrafficLightController(lights, timer);

            //Assert initial state is where expected
            Assert.AreEqual(TrafficLightState.StopThenGo, _l1.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l2.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l3.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l4.State);

            controller.Start();  //Will trigger traffic light state changes

            Thread.Sleep(2000);
            Assert.AreEqual(TrafficLightState.Go, _l1.State);
            Assert.AreEqual(TrafficLightState.Go, _l2.State);
            Assert.AreEqual(TrafficLightState.Go, _l3.State);
            Assert.AreEqual(TrafficLightState.Stop, _l4.State);

            Thread.Sleep(5000);
            Assert.AreEqual(TrafficLightState.Stop, _l1.State);
            Assert.AreEqual(TrafficLightState.Stop, _l2.State);
            Assert.AreEqual(TrafficLightState.Stop, _l3.State);
            Assert.AreEqual(TrafficLightState.Go, _l4.State);

            controller.Stop();
        }
Ejemplo n.º 16
0
        public void ShouldNotAcceptDuplicateTrafficLights()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight();
            var l2 = new TrafficLight();

            Assert.IsTrue(lights.Add(l1));
            Assert.IsTrue(lights.Add(l2));
            Assert.IsFalse(lights.Add(l1));

            Assert.AreEqual(2, lights.Count());
        }
Ejemplo n.º 17
0
    // Start is called before the first frame update
    void Start()
    {
        mass            = 1;
        maxForce        = 20;
        maxSpeed        = 10;
        spawner         = (Spawner)FindObjectOfType(typeof(Spawner));
        targetTransform = spawner.lights[Random.Range(0, spawner.lights.Length)].transform;
        targetLight     = targetTransform.GetComponent <TrafficLights>();
        var renderer = this.GetComponent <Renderer>();

        renderer.material.SetColor("_Color", Color.blue);
        CalculateForce();
    }
Ejemplo n.º 18
0
        public void ShouldNotPermitPolarSubjectsToBelongToTethers()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight { Name = "TL-1" };
            var l2 = new TrafficLight { Name = "TL-2" };
            var l3 = new TrafficLight { Name = "TL-3" };
            var l4 = new TrafficLight { Name = "TL-4" };

            var t1 = new PolarTrafficLightCluster(l1) { l2, l3, }; 
            var t2 = new TetheredTrafficLightCluster { l1, l4 };  
            Assert.IsTrue(lights.Add(t1));
            Assert.IsFalse(lights.Add(t2));
        }
 // Use this for initialization
 void Start()
 {
     lights1 = GameObject.FindGameObjectsWithTag("TrafficLight1");
     TrafficLights[] traffic1dummy = new TrafficLights[lights1.Length];
     lights2 = GameObject.FindGameObjectsWithTag("TrafficLight2");
     TrafficLights[] traffic2dummy = new TrafficLights[lights2.Length];
     for (int i = 0; i < lights1.Length; i++)
     {
         traffic1dummy[i] = lights1[i].GetComponent <TrafficLights>();
         traffic2dummy[i] = lights2[i].GetComponent <TrafficLights>();
     }
     traffic1 = traffic1dummy;
     traffic2 = traffic2dummy;
 }
Ejemplo n.º 20
0
        public void ShouldNotPermitPolarSubjectsToBeMembersOfOtherPolarClusters()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight { Name = "TL-1" };
            var l2 = new TrafficLight { Name = "TL-2" };
            var l3 = new TrafficLight { Name = "TL-3" };
            var l4 = new TrafficLight { Name = "TL-4" };
            var l5 = new TrafficLight { Name = "TL-5" };

            var t1 = new PolarTrafficLightCluster(l1) { l2, l3, };
            var t2 = new PolarTrafficLightCluster(l4) { l1, l5, };
            Assert.IsTrue(lights.Add(t1));
            Assert.IsFalse(lights.Add(t2));
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            TrafficLights x = TrafficLights.Red;

            switch (x)
            {
            case TrafficLights.Green:
                Console.WriteLine("Go!");
                break;

            case TrafficLights.Red:
                Console.WriteLine("Stop!");
                break;

            case TrafficLights.Yellow:
                Console.WriteLine("Caution!");
                break;
            }
        }
Ejemplo n.º 22
0
        public void ShouldPermitTrafficLightToBelongToTetherAndPolarClusters()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight { Name = "TL-1" };
            var l2 = new TrafficLight { Name = "TL-2" };
            var l3 = new TrafficLight { Name = "TL-3" };
            var l4 = new TrafficLight { Name = "TL-4" };

            var t1 = new TetheredTrafficLightCluster {{l1, l2}};      //l1 belongs to 
            var t2 = new PolarTrafficLightCluster(l1) { l3, l4 };   //  both clusters.

            Assert.IsTrue(lights.Add(t1));
            Assert.IsTrue(lights.Add(t2));

            Assert.AreEqual(4, lights.Count()); //All unique traffic lights added
            Assert.AreEqual(1, lights.AllTetheredClusters.Count());
            Assert.AreEqual(1, lights.AllPolarClusters.Count());
        }
Ejemplo n.º 23
0
        public void ShouldSynchronizedAllPolarLights()
        {
            var lights = new TrafficLights {
                _l1, _l2, _l3, _l4
            };
            var timer = new TrafficLightTimer();

            var tc1 = new PolarTrafficLightCluster(_l3)
            {
                { _l1, _l2 }
            };

            tc1.Name = "TC-1";

            var tc2 = new PolarTrafficLightCluster(_l5)
            {
                { _l4 }
            };

            tc2.Name = "TC-2";

            Assert.IsTrue(lights.Add(tc1, tc2));

            var controller = new TrafficLightController(lights, timer);

            //Assert initial state is where expected
            Assert.AreEqual(TrafficLightState.StopThenGo, _l1.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l2.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l3.State);
            Assert.AreEqual(TrafficLightState.StopThenGo, _l4.State);

            controller.Start();  //Will trigger traffic light state changes
            Thread.Sleep(2500);

            Assert.AreEqual(TrafficLightState.Go, _l3.State);
            Assert.AreEqual(TrafficLightState.Go, _l5.State);
            Assert.AreEqual(TrafficLightState.Stop, _l1.State);
            Assert.AreEqual(TrafficLightState.Stop, _l2.State);
            Assert.AreEqual(TrafficLightState.Stop, _l4.State);

            controller.Stop();
        }
Ejemplo n.º 24
0
        public static void Main()
        {
            List <TrafficLight> alltrafiLights = new List <TrafficLight>();
            var input            = Console.ReadLine().Split();
            int stateChangeCount = int.Parse(Console.ReadLine());

            foreach (var signal in input)
            {
                TrafficLights initialColorState = (TrafficLights)Enum.Parse(typeof(TrafficLights), signal);
                alltrafiLights.Add(new TrafficLight(initialColorState));
            }
            for (int i = 0; i < stateChangeCount; i++)
            {
                foreach (var trafficLight in alltrafiLights)
                {
                    trafficLight.ChangeState();
                }
                Console.WriteLine(string.Join(" ", alltrafiLights));
            }
        }
Ejemplo n.º 25
0
        public void ShouldNotPermitConflictingTetheredAndPolarClusters()
        {
            var lights = new TrafficLights();

            var l1 = new TrafficLight();
            var l2 = new TrafficLight();
            var l3 = new TrafficLight();
            var l4 = new TrafficLight();
            var l5 = new TrafficLight();
            var l6 = new TrafficLight();

            var t1 = new TetheredTrafficLightCluster { l2, l3 };  // I2 is Tethered to I3, but 
            var t2 = new PolarTrafficLightCluster(l3) { l1, l2, };    // also defined as a l3 Polar -- illogical
            Assert.IsTrue(lights.Add(t1));
            Assert.IsFalse(lights.Add(t2));

            var t3 = new TetheredTrafficLightCluster { l3, l4, l5 };    // Overlapping Traffic Lights,
            var t4 = new PolarTrafficLightCluster(l6) { l4, l5, };          //  this is not allowed.

            Assert.IsTrue(lights.Add(t4));  //Polar cluster first
            Assert.IsFalse(lights.Add(t3)); //  to ensure validation works regardless of order
        }
Ejemplo n.º 26
0
 public void CheckTrafficLight(object pictureBox)//регулирование цветов
 {
     bitmap = new Bitmap(((PictureBox)pictureBox).Width, ((PictureBox)pictureBox).Height);
     g      = Graphics.FromImage(bitmap);
     Light  = TrafficLights.Green;
     if (Light == TrafficLights.Green)
     {
         g.FillRectangle(Brushes.Black, new Rectangle(0, 0, ((PictureBox)pictureBox).Width, ((PictureBox)pictureBox).Height));
         g.FillEllipse(Brushes.Black, new Rectangle((((PictureBox)pictureBox).Width / 6), 22, ((PictureBox)pictureBox).Width * 4 / 6, 80));
         g.FillEllipse(Brushes.Green, new Rectangle((((PictureBox)pictureBox).Width / 6), 110, ((PictureBox)pictureBox).Width * 4 / 6, 80));
         ((PictureBox)pictureBox).Image = bitmap;
         Thread.Sleep(7000);
     }
     Light = TrafficLights.Red;
     if (Light == TrafficLights.Red)
     {
         g.FillRectangle(Brushes.Black, new Rectangle(0, 0, ((PictureBox)pictureBox).Width, ((PictureBox)pictureBox).Height));
         g.FillEllipse(Brushes.Black, new Rectangle((((PictureBox)pictureBox).Width / 6), 110, ((PictureBox)pictureBox).Width * 4 / 6, 80));
         g.FillEllipse(Brushes.Red, new Rectangle((((PictureBox)pictureBox).Width / 6), 22, ((PictureBox)pictureBox).Width * 4 / 6, 80));
         ((PictureBox)pictureBox).Image = bitmap;
         Thread.Sleep(4000);
     }
     CheckTrafficLight(pictureBox);
 }
Ejemplo n.º 27
0
        private static TrafficLights ReadInputFile(string fileName)
        {
            var lines = File.ReadAllLines(fileName);

            var           line         = lines[0];
            var           fline        = line.Split(' ');
            TrafficLights trafficLight = new TrafficLights();

            trafficLight.durationinSec         = int.Parse(fline[0]);
            trafficLight.NumOfIntersection     = int.Parse(fline[1]);
            trafficLight.NumOfStreets          = int.Parse(fline[2]);
            trafficLight.NumOfCars             = int.Parse(fline[3]);
            trafficLight.BonusPointsBeforeTime = int.Parse(fline[4]);

            for (var i = 1; i < trafficLight.NumOfStreets + 1; i++)
            {
                var    otherLines = lines[i].Split(' ');
                Street street     = new Street();
                street.IntersectionStartStreet = int.Parse(otherLines[0]);
                street.IntersectionEndStreet   = int.Parse(otherLines[1]);
                street.StreetName         = otherLines[2];
                street.TimeStartEndStreet = int.Parse(otherLines[3]);
                trafficLight.streets.Add(street);
            }

            for (var i = trafficLight.streets.Count + 1; i < trafficLight.streets.Count + trafficLight.NumOfCars + 1; i++)
            {
                var     otherLines = lines[i].Split(' ');
                CarPath carPath    = new CarPath();
                carPath.NumOfStreet = int.Parse(otherLines[0]);
                carPath.StreetName  = otherLines.Skip(1).ToList();
                trafficLight.carPaths.Add(carPath);
            }
            trafficLight.carPaths = trafficLight.carPaths.OrderBy(p => p.NumOfStreet).ToList();
            return(trafficLight);
        }
 public TrafficLight(TrafficLights color)
 {
     this.color = color;
 }
 public void ChangeState()
 {
     this.color = (TrafficLights)((int)(this.color + 1) % Enum.GetNames(typeof(TrafficLights)).Length);
 }
Ejemplo n.º 30
0
 public DangerOfCrossing(TrafficLights light)
 {
     _danger = light;
 }
Ejemplo n.º 31
0
        //Main----------------------------------------------------------
        static void Main(string[] args)
        {
            //struct
            book b;

            b.title  = "Test";
            b.price  = 6.95;
            b.author = "David";
            Console.WriteLine(b.title); //returns Test
            //struct using parameter-taking constructor
            point p = new point(10, 15);

            Console.WriteLine(p.x); //returns 10

            //enum
            int day = (int)Days.Mon; //narrowing conversion (data potentially lost)

            Console.WriteLine(day);
            //
            TrafficLights x = TrafficLights.Red;

            switch (x)
            {
            case TrafficLights.Green:
                Console.WriteLine("Go!");
                break;

            case TrafficLights.Red:
                Console.WriteLine("Stop!");
                break;

            case TrafficLights.Yellow:
                Console.WriteLine("Caution!");
                break;

            default:
                break;
            } //returns Stop!
              //This is great for a restricted list, or to improve readability
              //over using values, or having to use a narrowing conversion and casting INT

            //Exception handling
            try {
                int [] arr = new int[] { 4, 5, 8 };
                Console.WriteLine(arr[8]);
            }
            catch (Exception e) {
                Console.WriteLine("An error occurred.\n", e); //catch block executes without stopping program
            }
            finally {
                Console.WriteLine("All done."); //finally block runs always, even if return statement exists in catch block
            }
            //Mutliple exceptions
            try {
                x = Convert.ToInt32(Console.Read());
                y = Convert.ToInt32(Console.Read());
                Console.WriteLine(x / y);
            }
            //Common exception types: FileNotFoundException, FormatException, IndexOutOfRangeException, InvalidOperationException, OutOfMemoryException
            //Use exception handling if the error is rare.  If it's common, build code to avoid it.
            catch (DivideByZeroException e) {
                Console.WriteLine("Cannot divide by zero");
                return;
            }
            catch (Exception e) {
                Console.WriteLine("An error occurred.\n", e);
                return;
            }
            finally {
                Console.WriteLine("Completed.");
            }  //One need for a finally block is to close a file, whether an exception occurred or not.

            //Working with files (System.IO namespace)
            //Write
            string str = "Some text";

            File.WriteAllText("Test.txt", str); //Creates file (or overwrites whole file) and adds the text.
            //Read
            string str2 = File.ReadAllText("test.txt");

            Console.WriteLine(str2);
            //Also:  AppendAllText(), Create(), Delete(), Exists(), Copy(), and Move()
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            Book b;

            b.title  = "It's my book";
            b.price  = 5.99;
            b.author = "David";

            Console.WriteLine("The title of the book is: " + b.title);
            Console.WriteLine("It costs: " + b.price);
            Console.WriteLine("Written by: " + b.author);
            //For some strange reason I cannot put all the variables into a single Console.WriteLine

            //======================================================================================================================

            /* Structs can contain methods, properties, indexers, and so on.
             * Structs cannot contain default constructors (a constructor without parameters), but they can have constructors that take parameters.
             * In that case the new keyword is used to instantiate a struct object, similar to class objects */

            Point p = new Point(10, 15);

            Console.WriteLine(p.x);
            // Outputs 10
            Console.WriteLine(p.y);

            /* -- Structs vs Classes --
             * In general, classes are used to model more complex behavior, or data, that is intended to be modified after a class object is created.
             * Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
             * Consider defining a struct instead of a class if you are trying to represent a simple set of data. */
            //======================================================================================================================
            Console.WriteLine("========================     Enums      =====================================");

            int x = (int)Days.Tue;                      // The Enum declaration is outside the Main

            Console.WriteLine(x);
            //Outputs 2


            TrafficLights z = TrafficLights.Red;        // The Enum declaration is outside the Main

            switch (z)
            {
            case TrafficLights.Green:
                Console.WriteLine("Go!");
                break;

            case TrafficLights.Red:
                Console.WriteLine("Stop!");
                break;

            case TrafficLights.Yellow:
                Console.WriteLine("Caution!");
                break;
            }
            //Outputs "Stop!"

            //======================================================================================================================
            Console.WriteLine("=====================     Exceptions 1      ===================================");

            try
            {
                int[] arr = new int[] { 4, 5, 8 };
                Console.Write(arr[8]);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred");         //  My own message
                Console.WriteLine(e.Message);                   //  The original error message (e.Message)
            }
            //Outputs "An error occurred"

            Console.WriteLine("=====================     Exceptions 2      ===================================");

            int w = 12;
            int v = 0;

            try
            {
                int t = w / v;
                Console.WriteLine(t);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error - Cant divide by zero");
            }


            // ===========      Dont really get taht example  -  I do know what is going on but it seems like it meant to give me a different answer     ==============
            //int f;
            //int g;
            //try
            //{
            //    f = Convert.ToInt32(Console.Read());
            //    g = Convert.ToInt32(Console.Read());
            //    Console.WriteLine(f / g);
            //}
            //catch (DivideByZeroException e)
            //{
            //    Console.WriteLine("Cannot divide by 0");
            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine("An error occurred");
            //}

            // ===========      Yet again it didnt really worked    ==============

            //int[] arr = { 2, 5, 3 };
            //int x = 0;
            //try
            //{
            //    x = arr[5];
            //}
            //catch (Exception e)
            //{
            //    x = arr[x];
            //}

            Console.WriteLine("=====================     Exceptions 3      ===================================");

            int result = 0;
            int num1   = 8;
            int num2   = 4;

            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Calculation Error => Cannot divide by zero");
            }
            finally
            {
                Console.WriteLine("The result is : " + result);
            }
        }
Ejemplo n.º 33
0
        private static OutPutFile ScheduleIntersection(TrafficLights trafficLights)
        {
            OutPutFile outPutFile = new OutPutFile();
            List <IntersectionSchedule> intersectionScheduleList = new List <IntersectionSchedule>();
            int intersections       = trafficLights.NumOfIntersection;
            int streets             = trafficLights.NumOfStreets;
            int cars                = trafficLights.NumOfCars;
            var UniqueIntersections = trafficLights.streets.Select(p => p.IntersectionEndStreet).Distinct().ToList();

            for (int i = 0; i < UniqueIntersections.Count; i++)
            {
                bool intersectionNotUsed = false;
                int  currentIntersection = UniqueIntersections[i];
                var  allcarPaths         = trafficLights.carPaths;

                var allStreets = trafficLights.streets.Where(p => p.IntersectionEndStreet == currentIntersection).ToList();

                IntersectionSchedule intersectionSchedule = new IntersectionSchedule();

                intersectionSchedule.NumberncomingOfStreets = 0;
                intersectionSchedule.NumberncomingOfStreets = allStreets.Count;
                intersectionSchedule.IntersectionID         = currentIntersection;
                foreach (var street in allStreets)
                {
                    var beginStreet = allcarPaths.Where(p => p.StreetName.IndexOf(street.StreetName) == 0).ToList();
                    var endStreet   = allcarPaths.Where(p => p.StreetName.IndexOf(street.StreetName) == p.StreetName.Count - 1).ToList();
                    if (beginStreet.Count == 0 &&
                        endStreet.Count == allStreets.Count)
                    {
                        intersectionNotUsed = true;
                    }

                    if (intersectionNotUsed)
                    {
                        intersectionSchedule = null; continue;
                    }

                    //for (int j = 0; j < cars; j++)
                    //{
                    //    var path = trafficLights.carPaths[j];
                    //    var firstStreetName = path.StreetName[0];
                    var currentStreet = street;// trafficLights.streets.Where(p => p.StreetName == firstStreetName).FirstOrDefault();
                    //var intersectionStreets = trafficLights.streets.Where(p => p.IntersectionEndStreet == intersectionSchedule.IntersectionID).ToList(); // || p.IntersectionStartStreet == intersectionSchedule.IntersectionID
                    //foreach (var istreet in intersectionStreets)
                    {
                        OrderNDurationGreenLight orderNDurationGreenLight = new OrderNDurationGreenLight();
                        orderNDurationGreenLight.StreetName = currentStreet.StreetName;
                        //second + 1 for car passing
                        int isStartofPath = 0;
                        foreach (var carPath in allcarPaths)
                        {
                            if (carPath.StreetName[0] == currentStreet.StreetName)
                            {
                                isStartofPath = 1;
                            }
                        }
                        //orderNDurationGreenLight.GreenSeconds = currentStreet.TimeStartEndStreet + isStartofPath;
                        orderNDurationGreenLight.GreenSeconds = 1 + isStartofPath;
                        intersectionSchedule.orderNDurationGreenLights.Add(orderNDurationGreenLight);
                    }
                    //}
                }
                if (intersectionSchedule != null)
                {
                    intersectionSchedule.orderNDurationGreenLights = intersectionSchedule.orderNDurationGreenLights.OrderByDescending(p => p.GreenSeconds).ToList();
                    intersectionScheduleList.Add(intersectionSchedule);
                    intersectionScheduleList = intersectionScheduleList.OrderByDescending(p => p.NumberncomingOfStreets).ToList();

                    decimal IntersectionPercentage = (decimal)intersectionScheduleList.Count / (decimal)UniqueIntersections.Count;
                    Console.WriteLine(intersectionScheduleList.Count + " / " + UniqueIntersections.Count +
                                      " = " + IntersectionPercentage);
                }
            }
            outPutFile.intersectionSchedules      = intersectionScheduleList;
            outPutFile.NumIntersectionHasSchedule = intersectionScheduleList.Count;
            return(outPutFile);
        }
        static void Main(string[] args)
        {
            Book b;

            b.title  = "Test";
            b.price  = 6.99;
            b.author = "David";

            Point p = new Point(10, 15); //Used New to activate the struct's contructor.

            Console.WriteLine(p.x);      //outputs 10

            int x = (int)Days.Tue;       //in order to asign Enum values to int variables you have to specify the type in parentheses in the declaration, like this.

            Console.WriteLine(x);

            TrafficLights t = TrafficLights.Red;

            switch (t)
            {
            case TrafficLights.Green:
                Console.WriteLine("Go!");
                break;

            case TrafficLights.Red:
                Console.WriteLine("Stop!");
                break;

            case TrafficLights.Yellow:
                Console.WriteLine("Caution!");
                break;
            } //outputs "Stop!"

            try
            {
                int[] arr = new int[] { 4, 5, 8 };
                Console.Write(arr[8]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            } // Index was outside the bounds of the array.

            //Try blocks can have multiple catch blocks based on different exceptions.

            /* Common exceptions are:
             * FileNotFoundException
             * FormatException
             * IndexOutOfRangeException
             * InvalidOperationException
             * OutOfMemoryException
             */

            int z;
            int y;

            try
            {
                Console.WriteLine("Enter numbers to divide");
                z = Convert.ToInt32(Console.ReadLine());
                y = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(z / y);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Cannot divide by 0");
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occured");
            }

            int result = 0;
            int num1   = 8;
            int num2   = 4;

            try
            {
                result = num1 / num2;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Error");
            }
            finally
            {
                Console.WriteLine(result);
            } //The finally code block executes whether or not the try block throws an exception.

            string str = "Some text";

            File.WriteAllText("Test.txt", str); //The WriteAllText() method saves the text from the variable to the file location written in ""'s. File reading is local to the application file.

            try
            {
                string txt = File.ReadAllText("test.txt"); //The ReadAllText() method returns a string containing the text of the file path.
                Console.WriteLine(txt);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            //Other System.OI.File methods include:

            /*
             * AppendAllText() - appends text to the end of the file (Useful for error logs i guess)
             * Create() - creates a file in the specified location.
             * Delete() - Deleted the specified file.
             * Exists() - Determines whether the specified file exists.
             * Copy() - Copies a file to a new location.
             * Move() - Moves a specified file to a new location.
             */
        }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            /*
             * A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.
             * The following example shows a simple struct declaration:
             *
             * struct Book {
             * public string title;
             * public double price;
             * public string author;
             * }
             *
             *
             * Structs share most of the same syntax as classes, but are more limited than classes.
             * Unlike classes, structs can be instantiated without using a new operator.
             *
             *
             * Book b;
             * b.title = "Test";
             * b.price = 5.99;
             * b.author = "David";
             *
             *
             * Structs do not support inheritance and cannot contain virtual methods.
             *
             */



            /*
             * Structs can contain methods, properties, indexers, and so on. Structs cannot contain default constructors (a constructor without parameters), but they can have constructors that take parameters.
             * In that case the new keyword is used to instantiate a struct object, similar to class objects.
             *
             *
             *
             *
             *       struct Point {
             *          public int x;
             *          public int y;
             *          public Point(int x, int y) {
             *              this.x = x;
             *              this.y = y;
             *          }
             *      }
             *      static void Main(string[] args)
             *      {
             *          Point p = new Point(10, 15);
             *          Console.WriteLine(p.x);
             *      }
             *
             *
             * In general, classes are used to model more complex behavior, or data, that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
             * Consider defining a struct instead of a class if you are trying to represent a simple set of data.
             *
             *
             *
             * All standard C# types (int, double, bool, char, etc.) are actually structs.
             *
             */



            /*
             * The enum keyword is used to declare an enumeration: a type that consists of a set of named constants called the enumerator list.
             * By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
             * For example, in the following enumeration, Sun is 0, Mon is 1, Tue is 2, and so on:
             *
             *
             * enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
             *
             * You can also assign your own enumerator values:
             *
             * enum Days {Sun, Mon, Tue=4, Wed, Thu, Fri, Sat};
             *
             *
             *
             * In the example above, the enumeration will start from 0, then Mon is 1, Tue is 4, Wed is 5, and so on. The value of the next item in an Enum is one increment of the previous value.
             * Note that the values are comma separated.
             * You can refer to the values in the Enum with the dot syntax.
             * In order to assign Enum values to int variables, you have to specify the type in parentheses:
             *
             *
             *       enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
             *      static void Main(string[] args)
             *      {
             *          int x = (int)Days.Tue;
             *          Console.WriteLine(x);
             *      }
             *
             *
             * Basically, Enums define variables that represent members of a fixed set.
             * Some sample Enum uses include month names, days of the week, cards in a deck, etc.
             *
             */


            // Enums are often used with switch statements.

            TrafficLights x = TrafficLights.Red;

            switch (x)
            {
            case TrafficLights.Green:
                Console.WriteLine("Go!");
                break;

            case TrafficLights.Red:
                Console.WriteLine("Stop!");
                break;

            case TrafficLights.Yellow:
                Console.WriteLine("Caution!");
                break;
            }



            /*
             * An exception is a problem that occurs during program execution. Exceptions cause abnormal termination of the program.
             *
             *
             * An exception can occur for many different reasons. Some examples:
             * - A user has entered invalid data.
             * - A file that needs to be opened cannot be found.
             * - A network connection has been lost in the middle of communications.
             * - Insufficient memory and other issues related to physical resources.
             *
             * For example, the following code will produce an exception when run because we request an index which does not exist:
             *
             *          int[] arr = new int[] { 4, 5, 8 };
             *          Console.Write(arr[8]); // error
             *
             *
             * As you can see, exceptions are caused by user error, programmer error, or physical resource issues.
             * However, a well-written program should handle all possible exceptions.
             *
             */



            /*
             * C# provides a flexible mechanism called the try-catch statement to handle exceptions so that a program won't crash when an error occurs.
             * The try and catch blocks are used similar to:
             *
             *              try {
             *                  int[] arr = new int[] { 4, 5, 8 };
             *                  Console.Write(arr[8]);
             *              }
             *              catch(Exception e) {
             *                  Console.WriteLine("An error occurred");
             *              }
             *
             * The code that might generate an exception is placed in the try block. If an exception occurs, the catch blocks is executed without stopping the program.
             * The type of exception you want to catch appears in parentheses following the keyword catch.
             * We use the general Exception type to handle all kinds of exceptions. We can also use the exception object e to access the exception details, such as the original error message (e.Message):
             *
             *
             *          try {
             *              int[] arr = new int[] { 4, 5, 8 };
             *              Console.Write(arr[8]);
             *          }
             *          catch(Exception e) {
             *              Console.WriteLine(e.Message);
             *          }
             *
             *
             * You can also catch and handle different exceptions separately.
             *
             *
             */


            /*
             * A single try block can contain multiple catch blocks that handle different exceptions separately.
             * Exception handling is particularly useful when dealing with user input.
             * For example, for a program that requests user input of two numbers and then outputs their quotient, be sure that you handle division by zero, in case your user enters 0 as the second number.
             *
             *  int x, y;
             *  try {
             *    x = Convert.ToInt32(Console.Read());
             *    y = Convert.ToInt32(Console.Read());
             *    Console.WriteLine(x / y);
             *  }
             *  catch (DivideByZeroException e) {
             *    Console.WriteLine("Cannot divide by 0");
             *  }
             *  catch(Exception e) {
             *    Console.WriteLine("An error occurred");
             *  }
             *
             * The above code handles the DivideByZeroException separately. The last catch handles all the other exceptions that might occur. If multiple exceptions are handled, the Exception type must be defined last.
             * Now, if the user enters 0 for the second number, "Cannot divide by 0" will be displayed.
             * If, for example, the user enters non-integer values, "An error occurred" will be displayed.
             *
             *
             * The following exception types are some of the most commonly used: FileNotFoundException, FormatException, IndexOutOfRangeException, InvalidOperationException, OutOfMemoryException.
             *
             */



            /*
             * An optional finally block can be used after the catch blocks.
             * The finally block is used to execute a given set of statements, whether an exception is thrown or not.
             *
             *              int result=0;
             *              int num1 = 8;
             *              int num2 = 4;
             *              try {
             *                  result = num1 / num2;
             *              }
             *              catch (DivideByZeroException e) {
             *                  Console.WriteLine("Error");
             *              }
             *              finally {
             *                  Console.WriteLine(result);
             *              }
             *
             * The finally block can be used, for example, when you work with files or other resources.
             * These should be closed or released in the finally block, whether an exception is raised or not.
             */


            /*
             *
             * The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file, and more.
             * The File class is one of them.
             *
             *
             * string str = "Some text";
             * File.WriteAllText("test.txt", str);
             *
             * The WriteAllText() method creates a file with the specified path and writes the content to it. If the file already exists, it is overwritten.
             * The code above creates a file test.txt and writes the contents of the str string into it.
             *
             *
             * To use the File class you need to use the System.IO namespace: using System.IO;
             *
             */

            /*
             * You can read the content of a file using the ReadAllText method of the File class:
             *
             *      string str = "Some text";
             *      File.WriteAllText("test.txt", str);
             *
             *      string txt = File.ReadAllText("test.txt");
             *      Console.WriteLine(txt);
             *
             * This will output the content of the test.txt file.
             *
             *
             * The following methods are available in the File class:
             * AppendAllText() - appends text to the end of the file.
             * Create() - creates a file in the specified location.
             * Delete() - deletes the specified file.
             * Exists() - determines whether the specified file exists.
             * Copy() - copies a file to a new location.
             * Move() - moves a specified file to a new location
             *
             * All methods automatically close the file after performing the operation.
             *
             * Check if names.txt exists, add David to the end of the file
             *
             * if (File.Exists(names.txt)) {
             *  File.AppendAllText("names.txt", David);
             * }
             *
             */
        }