Created
August 25, 2023 23:57
-
-
Save silashansen/34c5c493ff0866db33ea40692c38318f to your computer and use it in GitHub Desktop.
Elevator Saga
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
init: function(elevators, floors) { | |
// helper function to check if a floor is already queued | |
function isFloorQueued(elevator, floorNum) { | |
return elevator.destinationQueue.indexOf(floorNum) > -1; | |
} | |
function isFloorQueuedForAnyElevator(floorNum) { | |
for (let e = 0; e < elevators.length; e++) { | |
if (isFloorQueued(elevators[e], floorNum)) | |
return true; | |
} | |
return false; | |
} | |
function getElevatorWithLeastQueue() { | |
let leastQueue = 999; | |
let leastQueueElevator = null; | |
for (let e = 0; e < elevators.length; e++) { | |
if (elevators[e].destinationQueue.length < leastQueue) { | |
leastQueue = elevators[e].destinationQueue.length; | |
leastQueueElevator = elevators[e]; | |
} | |
} | |
return leastQueueElevator; | |
} | |
for(let e = 0; e < elevators.length; e++) { | |
let elevator = elevators[e]; | |
elevator.on("floor_button_pressed", function(floorno) { | |
if (!isFloorQueued(elevator, floorno)) | |
//Check if the elevator is going in the same direction as the floor button pressed | |
if (elevator.goingUpIndicator() && floorno > elevator.currentFloor() || elevator.goingDownIndicator() && floorno < elevator.currentFloor()) | |
elevator.goToFloor(floorno, true); | |
else | |
elevator.goToFloor(floorno); | |
}) | |
// Whenever the elevator is idle (has no more queued destinations) ... | |
elevator.on("idle", function() { | |
}); | |
} | |
// iterate through all floors | |
for(let i = 0; i < floors.length; i++) { | |
var floor = floors[i]; | |
floor.on("up_button_pressed", function() { | |
if (!isFloorQueuedForAnyElevator(floors[i].floorNum())) | |
getElevatorWithLeastQueue().goToFloor(floors[i].floorNum()); | |
}); | |
floor.on("down_button_pressed", function() { | |
if (!isFloorQueuedForAnyElevator(floors[i].floorNum())) | |
getElevatorWithLeastQueue().goToFloor(floors[i].floorNum()); | |
}); | |
} | |
}, | |
update: function(dt, elevators, floors) { | |
// We normally don't need to do anything here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment