Topic:   Fun Elevator Puzzle Game   (Read 1615 times)


0 Members and 1 Guest are viewing this topic.

Gan


  • Administrator

  • ^ This guy is amazing.

  • *****


  • Posts: 4408
    • View Profile
Fun Elevator Puzzle Game
« on: January 23, 2015, 01:38:52 AM »
http://play.elevatorsaga.com/

I'm up to challenge 6. The goal is to code the elevator to move and pick up and drop off passengers.

Here's my code so far:
Code: [Select]
{
    init: function(elevators, floors) {
        var elevatorNum = 0;
        _.each(elevators, function(elevator) {
            elevator.elevatorNumber = elevatorNum++;
            elevator.on("idle", function() {
                elevator.isIdle = true;
            });
            elevator.on("floor_button_pressed", function(floorNum) { elevator.goToFloor(floorNum); } );
           
            elevator.on("passing_floor", function(floorNum, direction) {
                var floor = floors[floorNum];
                if ((floor.upButtonPressed || floor.downButtonPressed) && elevator.loadFactor() <= 0.75) {
                    floor.upButtonPressed = false; floor.downButtonPressed = false;
                    //var temp = elevator.destinationQueue.slice(0);
                    elevator.stop();
                    //elevator.destinationQueue = temp;
                    //elevator.checkDestinationQueue();
                }
            });
            /*
            elevator.on("stopped_at_floor", function(floorNum) {
                // Maybe decide where to go next?
            });*/
        });
        _.each(floors, function(floor) {
            floor.on("up_button_pressed", function(event) { floor.upButtonPressed = true; } );
            floor.on("down_button_pressed", function(event) { floor.downButtonPressed = true; } );
        });
    },
    update: function(dt, elevators, floors) {
    var getClosestIdleElevator = function(elevators, floorNum) {
        var chosenElevator = null;
        var dist = 100;
        _.each(elevators, function(elevator) {
            if (Math.abs(elevator.currentFloor() - floorNum) < dist && elevator.isIdle == true) {
                chosenElevator = elevator;
                dist = Math.abs(elevator.currentFloor() - floorNum);
            }
        });
        return chosenElevator;
    };
       
       
        // We normally don't need to do anything here
        _.each(floors, function(floor) {
            if (floor.upButtonPressed || floor.downButtonPressed) {
                var elevator = getClosestIdleElevator(elevators, floor.floorNum());
                if (elevator != null) {
                    floor.upButtonPressed = false; floor.downButtonPressed = false;
                    elevator.goToFloor(floor.floorNum());
                    elevator.isIdle = false;
                }
            }
        });
    }
}