Created
April 3, 2015 12:24
-
-
Save Xiphe/33edf417d5f92c551f2f to your computer and use it in GitHub Desktop.
Elevator Saga
This file contains hidden or 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) { | |
function unique(arr) { | |
var a = arr.concat(); | |
for(var i=0; i<a.length; ++i) { | |
for(var j=i+1; j<a.length; ++j) { | |
if(a[i] === a[j]) | |
a.splice(j--, 1); | |
} | |
} | |
return a; | |
}; | |
var upDown = ['up', 'down']; | |
var floorsWithPeople = { | |
up: [], | |
down: [] | |
} | |
floors.forEach(function(floor) { | |
upDown.forEach(function(direction) { | |
floor.on(direction + '_button_pressed', function() { | |
var floorNum = floor.floorNum(); | |
if (!peopleOnFloor(floorNum, direction)) { | |
floorsWithPeople[direction].push(floorNum); | |
} | |
}); | |
}); | |
}); | |
function waitForNextFloor(elevator) { | |
var nextFloor = unique(floorsWithPeople.up.concat(floorsWithPeople.down))[0]; | |
if (nextFloor !== undefined) { | |
goToFloor(elevator, nextFloor); | |
} else { | |
window.setTimeout(function() { | |
waitForNextFloor(elevator); | |
}, 100); | |
} | |
} | |
function getDirection(from, to) { | |
return from > to ? 'down' : 'up'; | |
} | |
function peopleOnFloor(floorNum, direction) { | |
return floorsWithPeople[direction].indexOf(floorNum) >= 0; | |
} | |
function goToFloor(elevator, floorNum, force) { | |
var direction = getDirection(elevator.currentFloor(), floorNum); | |
var i = floorsWithPeople[direction].indexOf(floorNum); | |
if (i >= 0) { | |
floorsWithPeople[direction].splice(i, 1); | |
} | |
cleanupQueue(elevator); | |
elevator.goToFloor(floorNum, force); | |
cleanupQueue(elevator); | |
} | |
function cleanupQueue(elevator) { | |
elevator.destinationQueue.forEach(function(floorNum, i) { | |
var people = false; | |
upDown.forEach(function(dir) { | |
if (floorsWithPeople[dir].indexOf(floorNum) >= 0) { | |
people = true; | |
} | |
}); | |
if (!people && elevator.getPressedFloors().indexOf(floorNum) == -1) { | |
elevator.destinationQueue.splice(i, 1); | |
} | |
}); | |
elevator.checkDestinationQueue(); | |
}; | |
elevators.forEach(function(elevator) { | |
elevator.on("idle", function() { | |
waitForNextFloor(elevator); | |
}); | |
elevator.on('floor_button_pressed', function(floorNum) { | |
goToFloor(elevator, floorNum); | |
}); | |
elevator.on('passing_floor', function(floorNum, direction) { | |
if (peopleOnFloor(floorNum, direction)) { | |
goToFloor(elevator, floorNum, true); | |
} | |
}); | |
}); | |
}, | |
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