Get the Play/Pause and Quit buttons working nicely
[cs356-p1-elevator.git] / elevatorcontroller.cpp
index 2baea64..034d4d9 100644 (file)
@@ -10,7 +10,7 @@ ElevatorController::ElevatorController (int floors, int elevators)
 
        /* Create and add all of the elevators */
        for (int i=0; i<number_of_elevators_; i++)
-               elevators_.push_back (Elevator());
+               elevators_.push_back (Elevator(i));
 }
 
 static int choose_random_number_in_range (int low, int high)
@@ -33,10 +33,44 @@ void ElevatorController::call_elevator_to (int floor, Direction direction)
        /* Find all idle Elevators */
        for (it = elevators_.begin(); it != elevators_.end(); it++)
                if (it->is_idle ())
+               {
+                       /* If we have an IDLE elevator that is currently sitting at the
+                        * requested floor, we should obviously send that. */
+                       if (it->distance_from (requested_stop) == 0)
+                       {
+                               it->stop_at (requested_stop);
+                               return;
+                       }
+
+                       /* Was not at the right floor, but still is a good cantidate */
                        idle_elevators.push_back (&(*it));
+               }
 
        if (idle_elevators.size() > 0)
        {
+               std::vector<Elevator*>::iterator idle_it;
+               bool found = false;
+               float distance = INT_MAX;
+               Elevator *e;
+
+               /* Try to send the closest IDLE elevator */
+               for (idle_it=idle_elevators.begin(); idle_it!=idle_elevators.end(); idle_it++)
+               {
+                       if ((*idle_it)->distance_from (requested_stop) < distance)
+                       {
+                               found = true;
+                               distance = (*idle_it)->distance_from (requested_stop);
+                               e = *idle_it;
+                       }
+               }
+
+               if (found)
+               {
+                       e->stop_at (requested_stop);
+                       return;
+               }
+
+               /* No closest IDLE elevator was found, so choose one randomly */
                int num = choose_random_number_in_range (0, idle_elevators.size());
 
                idle_elevators.at (num) -> stop_at (requested_stop);