<commit_before>function importPanel(container) {
    container.html('');
    var wrap = container.append('div').attr('class', 'pad1');

    var importSupport = !!(window.FileReader);

    wrap.append('p')
        .attr('class', 'intro')
        .text('Make a map! To start, draw with the tools on the left or import your own data.');

    wrap.append('div')
        .attr('class', 'modal-message')
        .text('Drop files to map!');

    function over() {
        d3.event.stopPropagation();
        d3.event.preventDefault();
        d3.event.dataTransfer.dropEffect = 'copy';
        d3.select('body').classed('dragover', true);
    }

    function exit() {
        d3.event.stopPropagation();
        d3.event.preventDefault();
        d3.event.dataTransfer.dropEffect = 'copy';
        d3.select('body').classed('dragover', false);
    }

    function toDom(x) {
        return (new DOMParser()).parseFromString(x, 'text/xml');
    }

    function trackImport(format, method) {
        analytics.track('Imported Data / ' + method + ' / ' + format);
    }

    function readFile(f, method) {
        var reader = new FileReader();
        import_landing.classed('dragover', false);

        reader.onload = function(e) {
            var gj;
            var filename = f.name ? f.name.toLowerCase() : '';
            function ext(_) {
                return filename.indexOf(_) !== -1;
            }
            if (f.type === 'application/vnd.google-earth.kml+xml' || ext('.kml')) {
                gj = toGeoJSON.kml(toDom(e.target.result));
                trackImport('KML', method);
            } else if (ext('.gpx')) {
                gj = toGeoJSON.gpx(toDom(e.target.result));
                trackImport('GPX', method);
            } else if (ext('.geojson') || ext('.json')) {
                try {
                    gj = JSON.parse(e.target.result);
                    trackImport('GeoJSON', method);
                } catch(err) {
                    alert('Invalid JSON file: ' + err);
                    analytics.track('Uploaded invalid JSON');
                    return;
                }
            } else if (f.type === 'text/csv' || ext('.csv')) {
                gj = csv2geojson.csv2geojson(e.target.result);
                if (gj.type === 'Error') {
                    return handleGeocode(container.append('div'), e.target.result);
                }
                trackImport('CSV', method);
            } else {
                analytics.track('Failed to upload a file with type ' + f.type);
                return alert('Sorry, that file type is not supported');
            }
            if (gj) {
                updates.update_editor(gj);
                updates.zoom_extent();
            }
        };

        reader.readAsText(f);
    }

    if (importSupport) {

        d3.select('body')
            .attr('dropzone', 'copy')
            .on('drop.localgpx', function() {
                d3.event.stopPropagation();
                d3.event.preventDefault();
                d3.select('body').classed('dragover', false);
                var f = d3.event.dataTransfer.files[0];
                readFile(f, 'drag');
            })
            .on('dragenter.localgpx', over)
            .on('dragexit.localgpx', exit)
            .on('dragover.localgpx', over);

        var import_landing = wrap.append('div')
            .attr('class', 'pad fillL');

        var message = import_landing
            .append('div')
            .attr('class', 'message');

        message.append('span').attr('class', 'icon-arrow-down');
        message.append('span').text(' Drop a GeoJSON, KML, CSV, or GPX file or ');
        message.append('button').text('Choose a file to upload')
            .on('click', function() {
                fileInput.node().click();
            });
        var fileInput = message
            .append('input')
            .attr('type', 'file')
            .style('visibility', 'hidden')
            .style('position', 'absolute')
            .style('height', '0')
            .on('change', function() {
                if (this.files && this.files[0]) readFile(this.files[0], 'click');
            });
    } else {
        wrap.append('p')
            .attr('class', 'blank-banner')
            .text('Sorry, geojson.io supports importing GeoJSON, GPX, KML, and CSV files, but ' +
                  'your browser isn\'t compatible. Please use Google Chrome, Safari 6, IE10, Firefox, or Opera for an optimal experience.');
    }
    wrap.append('p')
        .attr('class', 'intro')
        .style('text-align', 'center')
        .style('color', '#888')
        .html('Submit feedback or get help');

    if (window.chrome) wrap.append('p')
        .attr('class', 'intro-hint')
        .style('color', '#888')
        .html('Use GitHub? The geojson.io chrome extension lets you edit map data in your repositories!');

    wrap.append('div')
        .attr('class', 'geocode-ui');
}

function handleGeocode(container, text) {

    analytics.track('A CSV Required Geocoding');

    var list = csv2geojson.csv(text);

    var button = container.append('div')
        .attr('class', 'bucket-actions')
        .append('button')
        .attr('class', 'major')
        .attr('disabled', true)
        .text('At least one field required to geocode');

    var join = container.append('div')
        .attr('class', 'bucket-deposit')
        .append('div')
        .attr('class', 'bucket-join');

    var buckets = join.selectAll('.bucket')
        .data(['City', 'State', 'ZIP', 'Country'])
        .enter()
        .append('div')
        .attr('class', 'bucket')
        .text(String);

    var example = container.append('div')
        .attr('class', 'example');

    var store = container.append('div')
       .attr('class', 'bucket-store');

    var sources = store.selectAll('bucket-source')
       .data(Object.keys(list[0]))
       .enter()
       .append('div')
       .attr('class', 'bucket-source')
       .text(String);

    function transformRow(fields) {
        return function(obj) {
           return d3.entries(obj)
               .filter(function(e) { return fields.indexOf(e.key) !== -1; })
               .map(function(e) { return e.value; })
               .join(', ');
        };
    }

    function showExample(fields) {
        var i = 0;
        return function() {
            if (++i > list.length) i = 0;
            example.html('');
            example.text(transformRow(fields)(list[i]));
        };
    }

    var ti;
    var broker = bucket();
    buckets.call(broker.deposit());
    sources.call(broker.store().on('chosen', onChosen));

    function onChosen(fields) {
         if (ti) window.clearInterval(ti);
         if (fields.length) {
             button.attr('disabled', null)
                .text('Geocode');
             button.on('click', function() {
                 analytics.track('Ran a Geocode batch');
                 runGeocode(container, list, transformRow(fields));
             });
             var se = showExample(fields);
             se();
             ti = window.setInterval(se, 2000);
         } else {
             button.attr('disabled', true)
                .text('At least one field required to geocode');
             example.text('');
         }
     }
}

function runGeocode(container, list, transform) {
    container.html('');

    var wrap = container.append('div').attr('class', 'pad1');

    var doneBtn = wrap.append('div')
        .style('text-align', 'center')
        .style('padding', '10px')
        .append('button')
        .attr('class', 'major')
        .text('Close')
        .on('click', function() {
            container.html('');
            if (task) task();
        });

    var chartDiv = wrap.append('div');
    var failedDiv = wrap.append('div');

    var geocode = geocodemany('tmcw.map-u4ca5hnt');

    function progressChart(elem, w, h) {
        var c = elem.appendChild(document.createElement('canvas'));
        c.width = w;
        c.height = h;
        var ctx = c.getContext('2d');
        var gap;
        var fill = {
            success: '#e3e4b8',
            error: '#E0A990'
        };

        return function(e) {
            if (!gap) gap = ((e.done) / e.todo * w) - ((e.done - 1) / e.todo * w);
            ctx.fillStyle = fill[e.status];
            ctx.fillRect((e.done - 1) / e.todo * w, 0, gap, h);
        };
    }

    var chart = progressChart(chartDiv.node(), chartDiv.node().offsetWidth, 50);

    function progress(e) {
        chart(e);
    }

    function printObj(o) {
        return '(' + d3.entries(o)
            .map(function(_) {
                return _.key + ': ' + _.value;
            }).join(',') + ')';
    }

    function done(failed, completed) {

        failedDiv
            .selectAll('.fail')
            .data(failed)
            .enter()
            .append('div')
            .attr('class', 'fail')
            .text(function(d) {
                return 'failed: ' + transform(d.data) + ' / ' + printObj(d.data);
            });

        updates.update_editor(csv2geojson.csv2geojson(completed));
    }

    var task = geocode(list, transform, progress, done);
}
<commit_msg>Link to web store<commit_after>function importPanel(container) {
    container.html('');
    var wrap = container.append('div').attr('class', 'pad1');

    var importSupport = !!(window.FileReader);

    wrap.append('p')
        .attr('class', 'intro')
        .text('Make a map! To start, draw with the tools on the left or import your own data.');

    wrap.append('div')
        .attr('class', 'modal-message')
        .text('Drop files to map!');

    function over() {
        d3.event.stopPropagation();
        d3.event.preventDefault();
        d3.event.dataTransfer.dropEffect = 'copy';
        d3.select('body').classed('dragover', true);
    }

    function exit() {
        d3.event.stopPropagation();
        d3.event.preventDefault();
        d3.event.dataTransfer.dropEffect = 'copy';
        d3.select('body').classed('dragover', false);
    }

    function toDom(x) {
        return (new DOMParser()).parseFromString(x, 'text/xml');
    }

    function trackImport(format, method) {
        analytics.track('Imported Data / ' + method + ' / ' + format);
    }

    function readFile(f, method) {
        var reader = new FileReader();
        import_landing.classed('dragover', false);

        reader.onload = function(e) {
            var gj;
            var filename = f.name ? f.name.toLowerCase() : '';
            function ext(_) {
                return filename.indexOf(_) !== -1;
            }
            if (f.type === 'application/vnd.google-earth.kml+xml' || ext('.kml')) {
                gj = toGeoJSON.kml(toDom(e.target.result));
                trackImport('KML', method);
            } else if (ext('.gpx')) {
                gj = toGeoJSON.gpx(toDom(e.target.result));
                trackImport('GPX', method);
            } else if (ext('.geojson') || ext('.json')) {
                try {
                    gj = JSON.parse(e.target.result);
                    trackImport('GeoJSON', method);
                } catch(err) {
                    alert('Invalid JSON file: ' + err);
                    analytics.track('Uploaded invalid JSON');
                    return;
                }
            } else if (f.type === 'text/csv' || ext('.csv')) {
                gj = csv2geojson.csv2geojson(e.target.result);
                if (gj.type === 'Error') {
                    return handleGeocode(container.append('div'), e.target.result);
                }
                trackImport('CSV', method);
            } else {
                analytics.track('Failed to upload a file with type ' + f.type);
                return alert('Sorry, that file type is not supported');
            }
            if (gj) {
                updates.update_editor(gj);
                updates.zoom_extent();
            }
        };

        reader.readAsText(f);
    }

    if (importSupport) {

        d3.select('body')
            .attr('dropzone', 'copy')
            .on('drop.localgpx', function() {
                d3.event.stopPropagation();
                d3.event.preventDefault();
                d3.select('body').classed('dragover', false);
                var f = d3.event.dataTransfer.files[0];
                readFile(f, 'drag');
            })
            .on('dragenter.localgpx', over)
            .on('dragexit.localgpx', exit)
            .on('dragover.localgpx', over);

        var import_landing = wrap.append('div')
            .attr('class', 'pad fillL');

        var message = import_landing
            .append('div')
            .attr('class', 'message');

        message.append('span').attr('class', 'icon-arrow-down');
        message.append('span').text(' Drop a GeoJSON, KML, CSV, or GPX file or ');
        message.append('button').text('Choose a file to upload')
            .on('click', function() {
                fileInput.node().click();
            });
        var fileInput = message
            .append('input')
            .attr('type', 'file')
            .style('visibility', 'hidden')
            .style('position', 'absolute')
            .style('height', '0')
            .on('change', function() {
                if (this.files && this.files[0]) readFile(this.files[0], 'click');
            });
    } else {
        wrap.append('p')
            .attr('class', 'blank-banner')
            .text('Sorry, geojson.io supports importing GeoJSON, GPX, KML, and CSV files, but ' +
                  'your browser isn\'t compatible. Please use Google Chrome, Safari 6, IE10, Firefox, or Opera for an optimal experience.');
    }
    wrap.append('p')
        .attr('class', 'intro')
        .style('text-align', 'center')
        .style('color', '#888')
        .html('Submit feedback or get help');

    if (window.chrome) wrap.append('p')
        .attr('class', 'intro-hint')
        .style('color', '#888')
        .html('Use GitHub? The geojson.io chrome extension lets you edit map data in your repositories!');

    wrap.append('div')
        .attr('class', 'geocode-ui');
}

function handleGeocode(container, text) {

    analytics.track('A CSV Required Geocoding');

    var list = csv2geojson.csv(text);

    var button = container.append('div')
        .attr('class', 'bucket-actions')
        .append('button')
        .attr('class', 'major')
        .attr('disabled', true)
        .text('At least one field required to geocode');

    var join = container.append('div')
        .attr('class', 'bucket-deposit')
        .append('div')
        .attr('class', 'bucket-join');

    var buckets = join.selectAll('.bucket')
        .data(['City', 'State', 'ZIP', 'Country'])
        .enter()
        .append('div')
        .attr('class', 'bucket')
        .text(String);

    var example = container.append('div')
        .attr('class', 'example');

    var store = container.append('div')
       .attr('class', 'bucket-store');

    var sources = store.selectAll('bucket-source')
       .data(Object.keys(list[0]))
       .enter()
       .append('div')
       .attr('class', 'bucket-source')
       .text(String);

    function transformRow(fields) {
        return function(obj) {
           return d3.entries(obj)
               .filter(function(e) { return fields.indexOf(e.key) !== -1; })
               .map(function(e) { return e.value; })
               .join(', ');
        };
    }

    function showExample(fields) {
        var i = 0;
        return function() {
            if (++i > list.length) i = 0;
            example.html('');
            example.text(transformRow(fields)(list[i]));
        };
    }

    var ti;
    var broker = bucket();
    buckets.call(broker.deposit());
    sources.call(broker.store().on('chosen', onChosen));

    function onChosen(fields) {
         if (ti) window.clearInterval(ti);
         if (fields.length) {
             button.attr('disabled', null)
                .text('Geocode');
             button.on('click', function() {
                 analytics.track('Ran a Geocode batch');
                 runGeocode(container, list, transformRow(fields));
             });
             var se = showExample(fields);
             se();
             ti = window.setInterval(se, 2000);
         } else {
             button.attr('disabled', true)
                .text('At least one field required to geocode');
             example.text('');
         }
     }
}

function runGeocode(container, list, transform) {
    container.html('');

    var wrap = container.append('div').attr('class', 'pad1');

    var doneBtn = wrap.append('div')
        .style('text-align', 'center')
        .style('padding', '10px')
        .append('button')
        .attr('class', 'major')
        .text('Close')
        .on('click', function() {
            container.html('');
            if (task) task();
        });

    var chartDiv = wrap.append('div');
    var failedDiv = wrap.append('div');

    var geocode = geocodemany('tmcw.map-u4ca5hnt');

    function progressChart(elem, w, h) {
        var c = elem.appendChild(document.createElement('canvas'));
        c.width = w;
        c.height = h;
        var ctx = c.getContext('2d');
        var gap;
        var fill = {
            success: '#e3e4b8',
            error: '#E0A990'
        };

        return function(e) {
            if (!gap) gap = ((e.done) / e.todo * w) - ((e.done - 1) / e.todo * w);
            ctx.fillStyle = fill[e.status];
            ctx.fillRect((e.done - 1) / e.todo * w, 0, gap, h);
        };
    }

    var chart = progressChart(chartDiv.node(), chartDiv.node().offsetWidth, 50);

    function progress(e) {
        chart(e);
    }

    function printObj(o) {
        return '(' + d3.entries(o)
            .map(function(_) {
                return _.key + ': ' + _.value;
            }).join(',') + ')';
    }

    function done(failed, completed) {

        failedDiv
            .selectAll('.fail')
            .data(failed)
            .enter()
            .append('div')
            .attr('class', 'fail')
            .text(function(d) {
                return 'failed: ' + transform(d.data) + ' / ' + printObj(d.data);
            });

        updates.update_editor(csv2geojson.csv2geojson(completed));
    }

    var task = geocode(list, transform, progress, done);
}
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function () {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
        //sets velocity
        this.body.setVelocity(5, 20);

        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        //makes screen follow player
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        //adds animations for name, frames and speed
        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
        //sets current animation for game start
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        this.now = new Date().getTime();
        //control for moving right
        if (me.input.isKeyPressed("right")) {
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }
        //control for moving left
        else if (me.input.isKeyPressed("left")) {
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.facing = "left";
            this.flipX(false);
        }
        //for when mario stands still
        else {
            this.body.vel.x = 0;
        }
        //control for jumping
        if (me.input.isKeyPressed('jump')) {
            // make sure we are not already jumping or falling
            if (!this.body.jumping && !this.body.falling) {
                // set current vel to the maximum defined value
                this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
                this.body.jumping = true;
            }

        }

        if (me.input.isKeyPressed('attack')) {
            if (!this.renderable.isCurrentAnimation("attack")) {
                //sets animation to attack than to idle
                this.renderable.setCurrentAnimation("attack", "idle");
                //begin from first animation
                this.renderable.setAnimationFrame();
            }

        } else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
                this.renderable.setAnimationFrame();
            }
        } else if (!this.renderable.isCurrentAnimation("attack")) {
            this.renderable.setCurrentAnimation("idle");
        }
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    collideHandler: function (response) {
        //collisions with the enemy base
        if (response.b.type === 'EnemyBaseEntity') {
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x - response.b.pos.x;

            //collision from the top
            if (ydif < -40 && xdif > 70 && xdif < -35) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            //collision from the left
            else if (xdif > -35 && this.facing === "right" && (xdif < 0) && ydif > -50) {
                this.body.vel.x = 0;
                this.pos.x = this.pos.x - 1;
                //collision from the right
            } else if (xdif < 70 && this.facing === "left" && (xdif > 0) && ydif > -50) {
                this.body.vel.x = 0;
                this.pos.x = this.pos.x + 1;
            }
            //collision from the top
            else if (ydif < -40) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }

            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= 1000) {
                console.log('towerhit');
                this.lastHit = this.now;
                response.b.loseHealth();
            }
        }
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function () {
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "PlayerBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    loseHealth: function (damage) {
        this.health = this.health - damage;
    },
    onCollision: function () {

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function () {
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function () {

    },
    loseHealth: function () {
        this.health--;
    }

});

game.EnemyCreep = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "creep1",
                width: 32,
                height: 64,
                spritewidth: "32",
                spriteheight: "64",
                getShape: function () {
                    return(new me.Rect(0, 0, 32, 64)).toPolygon();
                }
            }]);
        this.health = 10;
        this.alwaysUpdate = true;
        //if enemy is attacking or not
        this.attacking = false;
        //keeps track of creep attacks
        this.lastAtacking = new Date().getTime();
        // last time creep hit anything
        this.lastHit = new Date().getTime();
        this.now = new Date().getTime();
        this.body.setVelocity(3, 20);

        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");
    },
    update: function (delta) {

        this.now = new Date().getTime();

        this.body.vel.x -= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true);

        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);

        return true;
    },
    collideHandler: function (response) {
        if (response.b.type === "PlayerBase") {
            console.log("attack");
            this.attacking = true;
            this.lastAtacking = this.now;
            this.body.vel.x = 0;
            this.pos.x = this.pos.x + 1;
            if (this.now - this.lastHit >= 1000) {
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }
    }
});

game.GameManager = Object.extend({
    init: function (x, y, settings) {
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;
    },
    update: function () {
        this.now = new Date().getTime();

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1400, 0, {});
            me.game.world.addChild(creepe, 5);
        }

        return true;
    }
});<commit_msg>can now attack creeps<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function () {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);
        //sets velocity
        this.body.setVelocity(5, 20);
        this.health = 20;
        this.type = "PlayerEntity";
        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        //makes screen follow player
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        //adds animations for name, frames and speed
        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
        //sets current animation for game start
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {

        if (this.health <= 0) {
            me.game.world.removeChild(this);
        }
        this.now = new Date().getTime();
        //control for moving right
        if (me.input.isKeyPressed("right")) {
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }
        //control for moving left
        else if (me.input.isKeyPressed("left")) {
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.facing = "left";
            this.flipX(false);
        }
        //for when mario stands still
        else {
            this.body.vel.x = 0;
        }
        //control for jumping
        if (me.input.isKeyPressed('jump')) {
            // make sure we are not already jumping or falling
            if (!this.body.jumping && !this.body.falling) {
                // set current vel to the maximum defined value
                this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
                this.body.jumping = true;
            }

        }

        if (me.input.isKeyPressed('attack')) {
            if (!this.renderable.isCurrentAnimation("attack")) {
                //sets animation to attack than to idle
                this.renderable.setCurrentAnimation("attack", "idle");
                //begin from first animation
                this.renderable.setAnimationFrame();
            }

        } else if (this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
                this.renderable.setAnimationFrame();
            }
        } else if (!this.renderable.isCurrentAnimation("attack")) {
            this.renderable.setCurrentAnimation("idle");
        }
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    loseHealth: function (damage) {
        this.health = this.health - damage;
        console.log(this.health);
    },
    collideHandler: function (response) {
        //collisions with the enemy base
        if (response.b.type === 'EnemyBaseEntity') {
            var ydif = this.pos.y - response.b.pos.y;
            var xdif = this.pos.x - response.b.pos.x;

            //collision from the top
            if (ydif < -40 && xdif > 70 && xdif < -35) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            //collision from the left
            else if (xdif > -35 && this.facing === "right" && (xdif < 0) && ydif > -50) {
                this.body.vel.x = 0;
                this.pos.x = this.pos.x - 1;
                //collision from the right
            } else if (xdif < 70 && this.facing === "left" && (xdif > 0) && ydif > -50) {
                this.body.vel.x = 0;
                this.pos.x = this.pos.x + 1;
            }
            //collision from the top
            else if (ydif < -40) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }

            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= 1000) {
                console.log('towerhit');
                this.lastHit = this.now;
                response.b.loseHealth();
            }
            //player collisions with creeps
        } else if (response.b.type === "EnemyCreep") {
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.x;
            if (xdif > 0) {
                this.pos.x = this.pos.x + 1;
                if (this.facing === "left") {
                    this.body.vel.x = 0;
                }
            } else {
                this.pos.x = this.pos.x - 1;
                if (this.facing === "right") {
                    this.body.vel.x = 0;
                }
            }

            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= 1000
                    && (Math.abs(ydif) <= 40) &&
                    (((xdif > 0) && this.facing === "left") || ((xdif < 0) && this.facing === "right"))
                    ) {
                response.b.loseHealth(1);
                this.lastHit = this.now;
            }
        }
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function () {
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "PlayerBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    loseHealth: function (damage) {
        this.health = this.health - damage;
    },
    onCollision: function () {

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function () {
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function () {

    },
    loseHealth: function () {
        this.health--;
    }

});

game.EnemyCreep = me.Entity.extend({
    init: function (x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "creep1",
                width: 32,
                height: 64,
                spritewidth: "32",
                spriteheight: "64",
                getShape: function () {
                    return(new me.Rect(0, 0, 32, 64)).toPolygon();
                }
            }]);
        this.health = 10;
        this.alwaysUpdate = true;
        //if enemy is attacking or not
        this.attacking = false;
        //keeps track of creep attacks
        this.lastAtacking = new Date().getTime();
        // last time creep hit anything
        this.lastHit = new Date().getTime();
        this.now = new Date().getTime();
        this.body.setVelocity(3, 20);

        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");
    },
    loseHealth: function (damage) {
        this.health = this.health - damage;
    },
    update: function (delta) {
        console.log(this.health);
        if (this.health <= 0) {
            me.game.world.removeChild(this);
        }
        this.now = new Date().getTime();

        this.body.vel.x -= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true);

        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);

        return true;
    },
    collideHandler: function (response) {

        if (response.b.type === "PlayerBase") {
            this.attacking = true;
            this.lastAtacking = this.now;
            this.body.vel.x = 0;
            this.pos.x = this.pos.x + 1;
            if (this.now - this.lastHit >= 1000) {
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        } else if (response.b.type === "PlayerEntity") {
            var xdif = this.pos.x - response.b.pos.x;

            this.attacking = true;
            //this.lastAtacking = this.now;

            //keeps moving creep to right to maintain position
            if (xdif > 0) {
                this.pos.x = this.pos.x + 1;
                this.body.vel.x = 0;
            }
            if (this.now - this.lastHit >= 1000 && xdif > 0) {
                this.lastHit = this.now;
                //makes player lose health
                response.b.loseHealth(1);
            }
        }
    }
});

game.GameManager = Object.extend({
    init: function (x, y, settings) {
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;
    },
    update: function () {
        this.now = new Date().getTime();

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1600, 0, {});
            me.game.world.addChild(creepe, 5);
        }

        return true;
    }
});<|endoftext|>


<commit_before>/*-------------------
a player entity
-------------------------------- */
game.PlayerEntity = me.ObjectEntity.extend({

    /* -----

    constructor

    ------ */

    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);

        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(3, 15);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

    },

    /* -----
update the player pos
------ */
update: function(dt) {

    if (me.input.isKeyPressed('left'))
    {
        // flip the sprite on horizontal axis
        this.flipX(true);
        // update the entity velocity
        this.vel.x -= this.accel.x * me.timer.tick;
    }
    else if (me.input.isKeyPressed('right'))
    {
        // unflip the sprite
        this.flipX(false);
        // update the entity velocity
        this.vel.x += this.accel.x * me.timer.tick;

    }else
    {
        this.vel.x = 0;
    }
    if (me.input.isKeyPressed('jump'))
    {
        if (!this.jumping && !this.falling)
        {
            // set current vel to the maximum defined value
            // gravity will then do the rest
            this.vel.y = -this.maxVel.y * me.timer.tick;
            // set the jumping flag
            this.jumping = true;
        }
    }

    if (me.input.isKeyPressed('shot')) {
	// Create a new laser object
	var myShot = me.pool.pull("ShotEntity", this.pos.x, this.pos.y, { image: "bullet", spritewidth: 16, spriteheight: 16 }, false);
	// Add the laser to the game manager with z value 3
	me.game.world.addChild(myShot, 3);

	console.log("shot added to the world!")

    }
    // check & update player movement
    this.updateMovement();

    // check for collision
    var res = me.game.world.collide(this);

    if (res) {
        // if we collide with an enemy
        if (res.obj.type == me.game.ENEMY_OBJECT) {
            // check if we jumped on it
            if ((res.y > 0) && ! this.jumping) {
                // bounce (force jump)
                this.falling = false;
                this.vel.y = -this.maxVel.y * me.timer.tick;
                // set the jumping flag
                this.jumping = true;

            } else {
                // let's flicker in case we touched an enemy
                this.renderable.flicker(750);
            }
        }
    }

    // update animation if necessary
    if (this.vel.x!=0 || this.vel.y!=0) {
        // update object animation
        this.parent(dt);
        return true;
    }
    // else inform the engine we did not perform
    // any update (e.g. position, animation)
    return false;

}

});

/*----------------
 a Shot entity
------------------------ */
game.ShotEntity = me.CollectableEntity.extend({
    // extending the init function is not mandatory
    // unless you need to add some extra initialization
    init: function(x, y, settings, left) {

	// call the parent constructor
        this.parent(x, y, settings);

	// set the walking & jumping speed
        this.setVelocity(5, 20);

    },

    // this function is called by the engine, when
    // an object is touched by something (here collected)
    onCollision : function () {
		// do something when there is collision
		console.log("Hit!")
		// make sure it cannot be collected "again"
		this.collidable = false;
		// remove it
		me.game.world.removeChild(this);
	},

update: function(dt) {
 	this.flipX(this.left);
        this.vel.x += (this.left)? - this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
        this.updateMovement();
        return true;
}

});

/*----------------
 a Coin entity
------------------------ */
game.CoinEntity = me.CollectableEntity.extend({
    // extending the init function is not mandatory
    // unless you need to add some extra initialization
    init: function(x, y, settings) {

	// call the parent constructor
        this.parent(x, y, settings);
    },

    // this function is called by the engine, when
    // an object is touched by something (here collected)
    onCollision : function () {
		// do something when collected

		// give some score
		game.data.score += 250;

		// make sure it cannot be collected "again"
		this.collidable = false;
		// remove it
		me.game.world.removeChild(this);
	}

});

/* --------------------------
an enemy Entity
------------------------ */
game.EnemyEntity = me.ObjectEntity.extend({
    init: function(x, y, settings) {
        // define this here instead of tiled
        settings.image = "wheelie_right";

        // save the area size defined in Tiled
        var width = settings.width;
        var height = settings.height;;

        // adjust the size setting information to match the sprite size
        // so that the entity object is created with the right size
        settings.spritewidth = settings.width = 64;
        settings.spritewidth = settings.height = 64;

        // call the parent constructor
        this.parent(x, y , settings);

        // set start/end position based on the initial area size
        x = this.pos.x;
        this.startX = x;
        this.endX   = x + width - settings.spritewidth
        this.pos.x  = x + width - settings.spritewidth;

        // walking & jumping speed
        this.setVelocity(2, 6);

        // make it collidable
        this.collidable = true;
        this.type = me.game.ENEMY_OBJECT;
    },

    // call by the engine when colliding with another object
    // obj parameter corresponds to the other object (typically the player) touching this one
    onCollision: function(res, obj) {

        // res.y >0 means touched by something on the bottom
        // which mean at top position for this one
        if (this.alive && (res.y > 0) && obj.falling) {
            this.renderable.flicker(750);
        }
    },

    // manage the enemy movement
    update: function(dt) {
        // do nothing if not in viewport
        if (!this.inViewport)
            return false;

        if (this.alive) {
            if (this.walkLeft && this.pos.x <= this.startX) {
                this.walkLeft = false;
            } else if (!this.walkLeft && this.pos.x >= this.endX) {
                this.walkLeft = true;
            }
            // make it walk
            this.flipX(this.walkLeft);
            this.vel.x += (this.walkLeft) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;

        } else {
            this.vel.x = 0;
        }

        // check and update movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x!=0 || this.vel.y!=0) {
            // update object animation
            this.parent(dt);
            return true;
        }
        return false;
    }
});

/**
 * a HUD container and child items
 */

game.HUD = game.HUD || {};

game.HUD.Container = me.ObjectContainer.extend({

    init: function() {
        // call the constructor
        this.parent();

        // persistent across level change
        this.isPersistent = true;

        // non collidable
        this.collidable = false;

        // make sure our object is always draw first
        this.z = Infinity;

        // give a name
        this.name = "HUD";

        // add our child score object at the right-bottom position
        this.addChild(new game.HUD.ScoreItem(630, 440));
    }
});

/**
 * a basic HUD item to display score
 */
game.HUD.ScoreItem = me.Renderable.extend( {
    /**
     * constructor
     */
    init: function(x, y) {

        // call the parent constructor
        // (size does not matter here)
        this.parent(new me.Vector2d(x, y), 10, 10);

        // create a font
        this.font = new me.BitmapFont("32x32_font", 32);
        this.font.set("right");

        // local copy of the global score
        this.score = -1;

        // make sure we use screen coordinates
        this.floating = true;
    },

    /**
     * update function
     */
    update : function (dt) {
        // we don't draw anything fancy here, so just
        // return true if the score has been updated
        if (this.score !== game.data.score) {
            this.score = game.data.score;
            return true;
        }
        return false;
    },

    /**
     * draw the score
     */
    draw : function (context) {
        this.font.draw (context, game.data.score, this.pos.x, this.pos.y);
    }
});
<commit_msg>this doesnt work for crap<commit_after>/*-------------------
a player entity
-------------------------------- */
game.PlayerEntity = me.ObjectEntity.extend({

    /* -----

    constructor

    ------ */

    init: function(x, y, settings) {
        // call the constructor
        this.parent(x, y, settings);

        // set the default horizontal & vertical speed (accel vector)
        this.setVelocity(3, 15);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

    },

    /* -----
update the player pos
------ */
update: function(dt) {

    if (me.input.isKeyPressed('left'))
    {
        // flip the sprite on horizontal axis
        this.flipX(true);
        // update the entity velocity
        this.vel.x -= this.accel.x * me.timer.tick;
    }
    else if (me.input.isKeyPressed('right'))
    {
        // unflip the sprite
        this.flipX(false);
        // update the entity velocity
        this.vel.x += this.accel.x * me.timer.tick;

    }else
    {
        this.vel.x = 0;
    }
    if (me.input.isKeyPressed('jump'))
    {
        if (!this.jumping && !this.falling)
        {
            // set current vel to the maximum defined value
            // gravity will then do the rest
            this.vel.y = -this.maxVel.y * me.timer.tick;
            // set the jumping flag
            this.jumping = true;
        }
    }

    if (me.input.isKeyPressed('shot')) {
	// Create a new laser object
	console.log("person location: " + this.pos.x + ", " + this.pos.y)
	var myShot = me.pool.pull("ShotEntity", this.pos.x, this.pos.y, { image: "bullet", spritewidth: 16, spriteheight: 16 }, false);
	// Add the laser to the game manager with z value 3
	me.game.world.addChild(myShot, 3);
    }
    // check & update player movement
    this.updateMovement();

    // check for collision
    var res = me.game.world.collide(this);

    if (res) {
        // if we collide with an enemy
        if (res.obj.type == me.game.ENEMY_OBJECT) {
            // check if we jumped on it
            if ((res.y > 0) && ! this.jumping) {
                // bounce (force jump)
                this.falling = false;
                this.vel.y = -this.maxVel.y * me.timer.tick;
                // set the jumping flag
                this.jumping = true;

            } else {
                // let's flicker in case we touched an enemy
                this.renderable.flicker(750);
            }
        }
    }

    // update animation if necessary
    if (this.vel.x!=0 || this.vel.y!=0) {
        // update object animation
        this.parent(dt);
        return true;
    }
    // else inform the engine we did not perform
    // any update (e.g. position, animation)
    return false;

}

});

/*----------------
 a Shot entity
------------------------ */
game.ShotEntity = me.ObjectEntity.extend({
    // extending the init function is not mandatory
    // unless you need to add some extra initialization
    init: function(x, y, settings, left) {

	// call the parent constructor
        this.parent(x, y, settings);

	this.pos.x = x;
	this.pos.y = y;

	this.left = left;
	this.collidable = true;
	console.log("shot created");

    },

    // this function is called by the engine, when
    // an object is touched by something (here collected)
    	onCollision : function () {
		// do something when there is collision
		console.log("Hit!")
		// make sure it cannot be collected "again"
		this.collidable = false;
		// remove it
		me.game.world.removeChild(this);
	},

	update: function() {
		console.log("update function called")

		this.flipX(this.left);
		this.vel.x += (this.left)? - this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
		this.updateMovement();
		return true;
	}
});

/*----------------
 a Coin entity
------------------------ */
game.CoinEntity = me.CollectableEntity.extend({
    // extending the init function is not mandatory
    // unless you need to add some extra initialization
    init: function(x, y, settings) {

	// call the parent constructor
        this.parent(x, y, settings);
    },

    // this function is called by the engine, when
    // an object is touched by something (here collected)
    onCollision : function () {
		// do something when collected

		// give some score
		game.data.score += 250;

		// make sure it cannot be collected "again"
		this.collidable = false;
		// remove it
		me.game.world.removeChild(this);
	}

});

/* --------------------------
an enemy Entity
------------------------ */
game.EnemyEntity = me.ObjectEntity.extend({
    init: function(x, y, settings) {
        // define this here instead of tiled
        settings.image = "wheelie_right";

        // save the area size defined in Tiled
        var width = settings.width;
        var height = settings.height;;

        // adjust the size setting information to match the sprite size
        // so that the entity object is created with the right size
        settings.spritewidth = settings.width = 64;
        settings.spritewidth = settings.height = 64;

        // call the parent constructor
        this.parent(x, y , settings);

        // set start/end position based on the initial area size
        x = this.pos.x;
        this.startX = x;
        this.endX   = x + width - settings.spritewidth
        this.pos.x  = x + width - settings.spritewidth;

        // walking & jumping speed
        this.setVelocity(2, 6);

        // make it collidable
        this.collidable = true;
        this.type = me.game.ENEMY_OBJECT;
    },

    // call by the engine when colliding with another object
    // obj parameter corresponds to the other object (typically the player) touching this one
    onCollision: function(res, obj) {

        // res.y >0 means touched by something on the bottom
        // which mean at top position for this one
        if (this.alive && (res.y > 0) && obj.falling) {
            this.renderable.flicker(750);
        }
    },

    // manage the enemy movement
    update: function(dt) {
        // do nothing if not in viewport
        if (!this.inViewport)
            return false;

        if (this.alive) {
            if (this.walkLeft && this.pos.x <= this.startX) {
                this.walkLeft = false;
            } else if (!this.walkLeft && this.pos.x >= this.endX) {
                this.walkLeft = true;
            }
            // make it walk
            this.flipX(this.walkLeft);
            this.vel.x += (this.walkLeft) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;

        } else {
            this.vel.x = 0;
        }

        // check and update movement
        this.updateMovement();

        // update animation if necessary
        if (this.vel.x!=0 || this.vel.y!=0) {
            // update object animation
            this.parent(dt);
            return true;
        }
        return false;
    }
});

/**
 * a HUD container and child items
 */

game.HUD = game.HUD || {};

game.HUD.Container = me.ObjectContainer.extend({

    init: function() {
        // call the constructor
        this.parent();

        // persistent across level change
        this.isPersistent = true;

        // non collidable
        this.collidable = false;

        // make sure our object is always draw first
        this.z = Infinity;

        // give a name
        this.name = "HUD";

        // add our child score object at the right-bottom position
        this.addChild(new game.HUD.ScoreItem(630, 440));
    }
});

/**
 * a basic HUD item to display score
 */
game.HUD.ScoreItem = me.Renderable.extend( {
    /**
     * constructor
     */
    init: function(x, y) {

        // call the parent constructor
        // (size does not matter here)
        this.parent(new me.Vector2d(x, y), 10, 10);

        // create a font
        this.font = new me.BitmapFont("32x32_font", 32);
        this.font.set("right");

        // local copy of the global score
        this.score = -1;

        // make sure we use screen coordinates
        this.floating = true;
    },

    /**
     * update function
     */
    update : function (dt) {
        // we don't draw anything fancy here, so just
        // return true if the score has been updated
        if (this.score !== game.data.score) {
            this.score = game.data.score;
            return true;
        }
        return false;
    },

    /**
     * draw the score
     */
    draw : function (context) {
        this.font.draw (context, game.data.score, this.pos.x, this.pos.y);
    }
});
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend ({
	// constructer function to set us up
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			// what amount of space to preserve
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function () {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		this.type = "PlayerEntity";
		// chooses velocity for our player
		this.health = 20;
		this.body.setVelocity(5, 20);
		// keeps track of which direction your character is going
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
		// no matter where the player goes it will will follow him
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this is the standing animation
		this.renderable.addAnimation("idle", [78]);
		//this is to add the walking animation.
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		// to set the walking animation.
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta) {
		this.now = new Date().getTime();
		// to see if right key is pressed
		if(me.input.isKeyPressed("right")){
			// adds to the postion of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//to face right
			this.facing = "right";
			// to flip the character the right way
			this.flipX(true);
			// to see if left key is pressed
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			// same things goes for the comments for right
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			// to not flip the character
			this.flipX(false);
		}else{
			// if youre not pressing the right key then the player wont move
			this.body.vel.x = 0;
		}
		// makes the player jump and fall back down
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}
		// hold down attack button
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")) {
				console.log(!this.renderable.isCurrentAnimation("attack"));
				//sets the current animation to attack and once that is over
				// goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence
				//from the first animation, not wherever we left off or when we
				//switched to the other animation
				this.renderable.setAnimationFrame();
			}
		}

		// no attack animation going on
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
		if(!this.renderable.isCurrentAnimation("walk")) {
			this.renderable.setCurrentAnimation("walk");
		}
		// if not attacking nothing will work
	}else if(!this.renderable.isCurrentAnimation("attack")) {
		this.renderable.setCurrentAnimation("idle");
	}

		// to collide with the base
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// delta is change in time
		this.body.update(delta);
		// this is to update our animation
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
		console.log(this.health);
	},

	// info about the handler
	collideHandler: function(response) {
		// to see whatever were colliding with
		if(response.b.type==='EnemyBaseEntity') {
			//to see what we are dealing with
			// the difference between the player and the y position
			var ydif = this.pos.y - response.b.pos.y;
			// same for x as above
			// to keep track of both objects
			var xdif = this.pos.x - response.b.pos.x;
			// to collide to the top of the base
			// y var to come first
			// not to walk on the base first
			if(ydif<-40 && xdif< 70 && xdif>-35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			// if i gone far from 35 it will stop the character from moving
			else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				// stop my player from moving
				this.body.vel.x = 0;
				// move the player backwards
				this.pos.x = this.pos.x -1;
				// keeping me from walking to the left and the right
			}else if(xdif<70 && this.facing==='left'&& (xdif>0)) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

			}
			// if attacking
			// see if its 400 mili seconds since last hit
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000) {
				// then we lose health
				console.log("Tower Hit");
				this.lastHit = this.now;
				response.b.loseHealth();
			}

		}

	}
});

game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		// the tower has not been destroyed
		this.broken = false;
		// 10 health
		this.health = 10;
		//this updates the game
		this.alwaysUpdate = true;
		// if someone runs into the tower it will collide with it
		this.body.onCollision = this.onCollision.bind(this);
		// type that i can see what im running into things
		this.type = "PlayerBase";
		// 0 is the not buring animation
		this.renderable.addAnimation("idle", [0]);
		// breaks our animations
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		// if my health is less than or equal to 0,
		if(this.health<=0) {
			//then we are dead
			this.broken = true;
			this.renderable.setCurrentAnimation("broken")
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	onCollision: function() {

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
		// not a buring tower
		this.renderable.addAnimation("idle", [0]);
		// buring animation will break
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta) {
		if(this.health<=0) {
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},

	onCollision: function() {

	},
	loseHealth: function() {
		// to make the health go down one
		this.health--;
	}

});

game.EnemyCreep = me.Entity.extend ({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "creep1",
			width: 32,
			height: 64,
			spritewidth: "32",
			spriteheight: "64",
			getShape: function() {
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
			}
		}]);
		// 10 health
		this.health = 10;
		// to always move on screen
		this.alwaysUpdate = true;
		//lets us know if the enemy is currently attacking
		this.attacking = false;
		//keeps track of when our creep is last attacking anything
		this.lastAttacking = new Date().getTime();
		// keeps track of the last time we hit anything
		this.lastHit = new Date().getTime();
		this.now = new Date().getTime();
		// velocity to start
		this.body.setVelocity(3, 20);
		// enemey creep
		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);
		this.renderable.setCurrentAnimation("walk");
	},
	// represents time
	update: function(delta) {
		this.now = new Date().getTime();

		this.body.vel.x -= this.body.accel.x * me.timer.tick;

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// update the creep
		this.body.update(delta);

		// this is to update our animation
		this._super(me.Entity, "update", [delta]);

		return true;

	},

	collideHandler: function(response) {
		if(response.b.type==='PlayerBase') {
			this.attacking=true;
			this.lastAttacking=this.now;
			this.body.vel.x = 0;
			//keeps moving the creep to the right to maintain its position
			this.pos.x = this.pos.x + 1;
			//checks that it has been at least 1 second since this creep hit a base
			if((this.now-this.lastHit >= 1000)) {
				//updates the lasthit timer
				this.lastHit = this.now;
				//makes the player base call its losehealth function and passes it a
				//damage of 1
				response.b.loseHealth(1);
			}
		}else if(response.b.type==='PlayerEntity') {
			var xdif = this.pos.x - response.b.pos.x;

			this.attacking=true;
			//this.lastAttacking=this.now;

			if(xdif>0) {
				//keeps moving the creep to the right to maintain its position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
		}
			//checks that it has been at least 1 second since this creep hit something
			if((this.now-this.lastHit >= 1000) && xdif>0) {
				//updates the lasthit timer
				this.lastHit = this.now;
				//makes the player base call its losehealth function and passes it a
				//damage of 1
				response.b.loseHealth(1);
			}
		}
	}

});

game.GameManager = Object.extend({
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();

		this.alwaysUpdate = true;
	},

	update: function() {
		this.now = new Date().getTime();

		if(Math.round(this.now/1000) % 10 ===0 && (this.now - this.lastCreep >= 1000)) {
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			me.game.world.addChild(creepe, 5);
		}

		return true;
	}
});<commit_msg>vid 23 killin the creeps<commit_after>game.PlayerEntity = me.Entity.extend ({
	// constructer function to set us up
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			// what amount of space to preserve
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function () {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		this.type = "PlayerEntity";
		// chooses velocity for our player
		this.health = 20;
		this.body.setVelocity(5, 20);
		// keeps track of which direction your character is going
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
		// no matter where the player goes it will will follow him
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this is the standing animation
		this.renderable.addAnimation("idle", [78]);
		//this is to add the walking animation.
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		// to set the walking animation.
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta) {
		this.now = new Date().getTime();
		// to see if right key is pressed
		if(me.input.isKeyPressed("right")){
			// adds to the postion of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//to face right
			this.facing = "right";
			// to flip the character the right way
			this.flipX(true);
			// to see if left key is pressed
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			// same things goes for the comments for right
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			// to not flip the character
			this.flipX(false);
		}else{
			// if youre not pressing the right key then the player wont move
			this.body.vel.x = 0;
		}
		// makes the player jump and fall back down
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}
		// hold down attack button
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")) {
				console.log(!this.renderable.isCurrentAnimation("attack"));
				//sets the current animation to attack and once that is over
				// goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence
				//from the first animation, not wherever we left off or when we
				//switched to the other animation
				this.renderable.setAnimationFrame();
			}
		}

		// no attack animation going on
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
		if(!this.renderable.isCurrentAnimation("walk")) {
			this.renderable.setCurrentAnimation("walk");
		}
		// if not attacking nothing will work
	}else if(!this.renderable.isCurrentAnimation("attack")) {
		this.renderable.setCurrentAnimation("idle");
	}

		// to collide with the base
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// delta is change in time
		this.body.update(delta);
		// this is to update our animation
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
		console.log(this.health);
	},

	// info about the handler
	collideHandler: function(response) {
		// to see whatever were colliding with
		if(response.b.type==='EnemyBaseEntity') {
			//to see what we are dealing with
			// the difference between the player and the y position
			var ydif = this.pos.y - response.b.pos.y;
			// same for x as above
			// to keep track of both objects
			var xdif = this.pos.x - response.b.pos.x;
			// to collide to the top of the base
			// y var to come first
			// not to walk on the base first
			if(ydif<-40 && xdif< 70 && xdif>-35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			// if i gone far from 35 it will stop the character from moving
			else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				// stop my player from moving
				this.body.vel.x = 0;
				// move the player backwards
				this.pos.x = this.pos.x -1;
				// keeping me from walking to the left and the right
			}else if(xdif<70 && this.facing==='left'&& (xdif>0)) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

			}
			// if attacking
			// see if its 400 mili seconds since last hit
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000) {
				// then we lose health
				console.log("Tower Hit");
				this.lastHit = this.now;
				response.b.loseHealth();
			}

		}else if(response.b.type==='EnemyCreep') {
			var xif = this.pos.x - response.b.pos.x;
			var ydif = this.posy - response.b.pos.y;

			if(xdif>0) {
				this.pos.x = this.pos.x + 1;
				if(this.facing==="left") {
					this.body.vel.x = 0;
				}
			}else {
				this.pos.x = this.pos.x - 1;
				if(this.facing==="right") {
					this.body.vel.x = 0;
				}
			}
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000
				&& (Math.abs(ydif) <=40) &&
				(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				) {
				this.lastHit = this.now;
				response.b.loseHealth(1);
			}
		}

	}
});

game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		// the tower has not been destroyed
		this.broken = false;
		// 10 health
		this.health = 10;
		//this updates the game
		this.alwaysUpdate = true;
		// if someone runs into the tower it will collide with it
		this.body.onCollision = this.onCollision.bind(this);
		// type that i can see what im running into things
		this.type = "PlayerBase";
		// 0 is the not buring animation
		this.renderable.addAnimation("idle", [0]);
		// breaks our animations
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		// if my health is less than or equal to 0,
		if(this.health<=0) {
			//then we are dead
			this.broken = true;
			this.renderable.setCurrentAnimation("broken")
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	onCollision: function() {

	}

});

game.EnemyBaseEntity = me.Entity.extend({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
		// not a buring tower
		this.renderable.addAnimation("idle", [0]);
		// buring animation will break
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta) {
		if(this.health<=0) {
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;

	},

	onCollision: function() {

	},
	loseHealth: function() {
		// to make the health go down one
		this.health--;
	}

});

game.EnemyCreep = me.Entity.extend ({
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "creep1",
			width: 32,
			height: 64,
			spritewidth: "32",
			spriteheight: "64",
			getShape: function() {
				return (new me.Rect(0, 0, 32, 64)).toPolygon();
			}
		}]);
		// 10 health
		this.health = 10;
		// to always move on screen
		this.alwaysUpdate = true;
		//lets us know if the enemy is currently attacking
		this.attacking = false;
		//keeps track of when our creep is last attacking anything
		this.lastAttacking = new Date().getTime();
		// keeps track of the last time we hit anything
		this.lastHit = new Date().getTime();
		this.now = new Date().getTime();
		// velocity to start
		this.body.setVelocity(3, 20);
		// enemey creep
		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	// represents time
	update: function(delta) {
		console.log(this.health);
		if(this.health <= 0) {
			me.game.world.removeChild(this);
		}

		this.now = new Date().getTime();

		this.body.vel.x -= this.body.accel.x * me.timer.tick;

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// update the creep
		this.body.update(delta);

		// this is to update our animation
		this._super(me.Entity, "update", [delta]);

		return true;

	},

	collideHandler: function(response) {
		if(response.b.type==='PlayerBase') {
			this.attacking=true;
			this.lastAttacking=this.now;
			this.body.vel.x = 0;
			//keeps moving the creep to the right to maintain its position
			this.pos.x = this.pos.x + 1;
			//checks that it has been at least 1 second since this creep hit a base
			if((this.now-this.lastHit >= 1000)) {
				//updates the lasthit timer
				this.lastHit = this.now;
				//makes the player base call its losehealth function and passes it a
				//damage of 1
				response.b.loseHealth(1);
			}
		}else if(response.b.type==='PlayerEntity') {
			var xdif = this.pos.x - response.b.pos.x;

			this.attacking=true;
			//this.lastAttacking=this.now;

			if(xdif>0) {
				//keeps moving the creep to the right to maintain its position
				this.pos.x = this.pos.x + 1;
				this.body.vel.x = 0;
		}
			//checks that it has been at least 1 second since this creep hit something
			if((this.now-this.lastHit >= 1000) && xdif>0) {
				//updates the lasthit timer
				this.lastHit = this.now;
				//makes the player base call its losehealth function and passes it a
				//damage of 1
				response.b.loseHealth(1);
			}
		}
	}

});

game.GameManager = Object.extend({
	init: function(x, y, settings) {
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();

		this.alwaysUpdate = true;
	},

	update: function() {
		this.now = new Date().getTime();

		if(Math.round(this.now/1000) % 10 ===0 && (this.now - this.lastCreep >= 1000)) {
			this.lastCreep = this.now;
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			me.game.world.addChild(creepe, 5);
		}

		return true;
	}
});<|endoftext|>


<commit_before>import { fakeEruptionDataset } from './data/fake-data'
import { processEruptionAPIResponse, copyAndShiftEruptionLng, concatenateEruptionData } from './data/helpers'
import { wrapTileX, lngDiff, tile2LatLngBounds } from './map-tile-helpers'
import Cache from './cache'
import config from './config'

const CONCORD_API = 'https://e401fd4io0.execute-api.us-east-1.amazonaws.com/production/seismic-explorer-eruptions'
const CLOUDFRONT_CONCORD_API = 'https://d876rjgss4hzs.cloudfront.net/production/seismic-explorer-eruptions'

function getAPIHost () {
  if (config.cache) {
    return CLOUDFRONT_CONCORD_API
  } else {
    return CONCORD_API
  }
}

function getAPIPath (tile) {
  const bb = tile2LatLngBounds(tile)
  const startTime = (new Date(config.startTime)).toISOString()
  const endTime = (new Date(config.endTime)).toISOString()
  const requestPath = `${getAPIHost()}?starttime=${startTime}&endtime=${endTime}` +
  `&maxlatitude=${bb.maxLat}&minlatitude=${bb.minLat}&maxlongitude=${bb.maxLng}&minlongitude=${bb.minLng}` +
  `&orderby=startdate&limit=${config.tileLimit}`
  return requestPath
}

function fakeData (tile, count) {
  const options = tile2LatLngBounds(tile)
  return new Promise(resolve => {
    setTimeout(function () {
      resolve(fakeEruptionDataset(count, options))
    }, Math.random() * 1000)
  })
}

export class EruptionRequestAborted {}

export class EruptionAPIError {
  constructor (statusText, response) {
    this.message = statusText
    this.response = response
  }
}

export default class EruptionDataAPI {
  constructor () {
    this.cache = new Cache()
    this.currentRequests = new Set()
  }

  isInCache (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180]. That's the convention we follow in
    // #getFromCache and #fetchTile.
    const wrappedTile = wrapTileX(tile)
    return this.cache.has(wrappedTile)
  }

  getFromCache (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180], ask cache for this modified tile,
    // copy it then shift longitude values back to the initial range.
    const wrappedTile = wrapTileX(tile)
    const lngOffset = lngDiff(tile, wrappedTile)
    const data = this.cache.get(wrappedTile)
    // Copy and shift so we don't modify cached data!
    return data && lngOffset !== 0 ? copyAndShiftEruptionLng(data, lngOffset) : data
  }

  getTilesFromCache (tiles) {
    const cachedTiles = tiles.filter(t => this.isInCache(t)).map(t => this.getFromCache(t))
    console.log('cached data tiles:', cachedTiles.length)
    return concatenateEruptionData(cachedTiles)
  }

  fetchTile (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180], ask API for this modified tile,
    // copy it then shift longitude values back to the initial range.
    const wrappedTile = wrapTileX(tile)
    const lngOffset = lngDiff(tile, wrappedTile)
    const dataPromise = config.api === 'fake'
      ? fakeData(wrappedTile, 10)
      : this._fetchData(getAPIPath(wrappedTile))
    return dataPromise
      .then(response => processEruptionAPIResponse(response, config.tileLimit))
      .then(data => this.cache.set(wrappedTile, data))
      // Copy and shift so we don't modify cached data!
      .then(data => lngOffset !== 0 ? copyAndShiftEruptionLng(data, lngOffset) : data)
  }

  abortAllRequests () {
    this.currentRequests.forEach(request => request.abort())
    this.currentRequests.clear()
  }

  _fetchData (url) {
    return new Promise((resolve, reject) => {
      const oReq = new window.XMLHttpRequest()
      oReq.addEventListener('load', function () {
        if (this.status >= 200 && this.status < 300) {
          try {
            resolve(JSON.parse(this.responseText))
          } catch (e) {
            // Sometimes USGS API returns malformed JSONs. Report that.
            reject(new EruptionAPIError('Malformed GeoJSON', e))
          }
        } else {
          reject(new EruptionAPIError(this.statusText, this))
        }
      })
      oReq.addEventListener('abort', function () {
        reject(new EruptionRequestAborted())
      })
      oReq.addEventListener('error', function () {
        reject(new EruptionAPIError(this.statusText, this))
      })
      oReq.open('GET', url)
      oReq.send()
      // Add it do the set so it can be aborted using #abortAllRequests.
      this.currentRequests.add(oReq)
    })
  }
}
<commit_msg>Change import order of eruptions to fix sprite ordering<commit_after>import { fakeEruptionDataset } from './data/fake-data'
import { processEruptionAPIResponse, copyAndShiftEruptionLng, concatenateEruptionData } from './data/helpers'
import { wrapTileX, lngDiff, tile2LatLngBounds } from './map-tile-helpers'
import Cache from './cache'
import config from './config'

const CONCORD_API = 'https://e401fd4io0.execute-api.us-east-1.amazonaws.com/production/seismic-explorer-eruptions'
const CLOUDFRONT_CONCORD_API = 'https://d876rjgss4hzs.cloudfront.net/production/seismic-explorer-eruptions'

function getAPIHost () {
  if (config.cache) {
    return CLOUDFRONT_CONCORD_API
  } else {
    return CONCORD_API
  }
}

function getAPIPath (tile) {
  const bb = tile2LatLngBounds(tile)
  const startTime = (new Date(config.startTime)).toISOString()
  const endTime = (new Date(config.endTime)).toISOString()
  const requestPath = `${getAPIHost()}?starttime=${startTime}&endtime=${endTime}` +
  `&maxlatitude=${bb.maxLat}&minlatitude=${bb.minLat}&maxlongitude=${bb.maxLng}&minlongitude=${bb.minLng}` +
  `&orderby=startdate-asc&limit=${config.tileLimit}`
  return requestPath
}

function fakeData (tile, count) {
  const options = tile2LatLngBounds(tile)
  return new Promise(resolve => {
    setTimeout(function () {
      resolve(fakeEruptionDataset(count, options))
    }, Math.random() * 1000)
  })
}

export class EruptionRequestAborted {}

export class EruptionAPIError {
  constructor (statusText, response) {
    this.message = statusText
    this.response = response
  }
}

export default class EruptionDataAPI {
  constructor () {
    this.cache = new Cache()
    this.currentRequests = new Set()
  }

  isInCache (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180]. That's the convention we follow in
    // #getFromCache and #fetchTile.
    const wrappedTile = wrapTileX(tile)
    return this.cache.has(wrappedTile)
  }

  getFromCache (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180], ask cache for this modified tile,
    // copy it then shift longitude values back to the initial range.
    const wrappedTile = wrapTileX(tile)
    const lngOffset = lngDiff(tile, wrappedTile)
    const data = this.cache.get(wrappedTile)
    // Copy and shift so we don't modify cached data!
    return data && lngOffset !== 0 ? copyAndShiftEruptionLng(data, lngOffset) : data
  }

  getTilesFromCache (tiles) {
    const cachedTiles = tiles.filter(t => this.isInCache(t)).map(t => this.getFromCache(t))
    console.log('cached data tiles:', cachedTiles.length)
    return concatenateEruptionData(cachedTiles)
  }

  fetchTile (tile) {
    // Tile can be outside [-180, 180] range. Limit it to [-180, 180], ask API for this modified tile,
    // copy it then shift longitude values back to the initial range.
    const wrappedTile = wrapTileX(tile)
    const lngOffset = lngDiff(tile, wrappedTile)
    const dataPromise = config.api === 'fake'
      ? fakeData(wrappedTile, 10)
      : this._fetchData(getAPIPath(wrappedTile))
    return dataPromise
      .then(response => processEruptionAPIResponse(response, config.tileLimit))
      .then(data => this.cache.set(wrappedTile, data))
      // Copy and shift so we don't modify cached data!
      .then(data => lngOffset !== 0 ? copyAndShiftEruptionLng(data, lngOffset) : data)
  }

  abortAllRequests () {
    this.currentRequests.forEach(request => request.abort())
    this.currentRequests.clear()
  }

  _fetchData (url) {
    return new Promise((resolve, reject) => {
      const oReq = new window.XMLHttpRequest()
      oReq.addEventListener('load', function () {
        if (this.status >= 200 && this.status < 300) {
          try {
            resolve(JSON.parse(this.responseText))
          } catch (e) {
            // Sometimes USGS API returns malformed JSONs. Report that.
            reject(new EruptionAPIError('Malformed GeoJSON', e))
          }
        } else {
          reject(new EruptionAPIError(this.statusText, this))
        }
      })
      oReq.addEventListener('abort', function () {
        reject(new EruptionRequestAborted())
      })
      oReq.addEventListener('error', function () {
        reject(new EruptionAPIError(this.statusText, this))
      })
      oReq.open('GET', url)
      oReq.send()
      // Add it do the set so it can be aborted using #abortAllRequests.
      this.currentRequests.add(oReq)
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    os = require('os'),
    app = express(),
    cors = require('cors'),
    fs = require('fs'),
    platform,
    server;

if (os.platform() === 'win32') {
    platform = 'win32';
} else {
    platform = 'linux';
}

app.use(cors({
    credentials: true,
    origin: true,
    exposedHeaders: ['Location']
}));

app.use(function (req, res, next) {
    var data = '';

    req.setEncoding('utf8');
    req.on('data', function (chunk) {
        data += chunk;
    });
    req.on('end', function () {
        req.rawBody = data;
        next();
    });
});

app.post('/screenshots/:filename', function (req, res) {
    fs.writeFile('test/results/' + req.params.filename, req.rawBody, 'base64', function () {
        res.writeHead(200);
        res.end();
    });
});

app.get('/screenshots/:filename', function (req, res) {
    var path = 'test/reference/' + req.params.filename;

    if (!fs.existsSync(path)) {
        path = 'test/reference/' + platform + '/' + req.params.filename;
        if (!fs.existsSync(path)) {
            res.status(404).send('Sorry cant find that!');
            return;
        }
    }

    fs.readFile(path, 'base64', function (err, data) {
        res.end(data);
    });
});

app.get('/samples/:filename', function (req, res) {
    fs.readFile('test/samples/' + req.params.filename, function (err, data) {
        res.end(data);
    });
});

server = app.listen(9001, function () {
    console.log('App listening at port %s', server.address().port);
});
<commit_msg>travis workaround<commit_after>'use strict';

var express = require('express'),
    os = require('os'),
    app = express(),
    cors = require('cors'),
    fs = require('fs'),
    platform,
    server;

if (os.platform() === 'win32') {
    platform = 'win32';
} else {
    platform = 'linux';
}

app.use(cors({
    credentials: true,
    origin: true,
    exposedHeaders: ['Location']
}));

app.use(function (req, res, next) {
    var data = '';

    req.setEncoding('utf8');
    req.on('data', function (chunk) {
        data += chunk;
    });
    req.on('end', function () {
        req.rawBody = data;
        next();
    });
});

app.post('/screenshots/:filename', function (req, res) {
    console.log(req.rawBody);

    fs.writeFile('test/results/' + req.params.filename, req.rawBody, 'base64', function () {
        res.writeHead(200);
        res.end();
    });
});

app.get('/screenshots/:filename', function (req, res) {
    var path = 'test/reference/' + req.params.filename;

    if (!fs.existsSync(path)) {
        path = 'test/reference/' + platform + '/' + req.params.filename;
        if (!fs.existsSync(path)) {
            res.status(404).send('Sorry cant find that!');
            return;
        }
    }

    fs.readFile(path, 'base64', function (err, data) {
        res.end(data);
    });
});

app.get('/samples/:filename', function (req, res) {
    fs.readFile('test/samples/' + req.params.filename, function (err, data) {
        res.end(data);
    });
});

server = app.listen(9001, function () {
    console.log('App listening at port %s', server.address().port);
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
CLASS({
  package: 'foam.u2.md',
  name: 'Select',
  extends: 'foam.u2.View',
  traits: ['foam.u2.ChoiceViewTrait'],

  requires: [
    'foam.u2.md.PopupMenu',
  ],
  imports: [
    'document',
  ],

  listeners: [
    {
      name: 'onClick',
      isFramed: true,
      code: function() {
        // Blur any active input element.
        var active = this.document.activeElement;
        if (active) active.blur();

        var self = this;
        var popup = this.PopupMenu.create({
          data$: this.data$,
          choices: this.choices,
          autoSetData: this.autoSetData
        });
        popup.open(this.index, this.id$el);
      }
    },
  ],

  templates: [
    function CSS() {/*
      .foam-u2-md-Select {
        align-items: flex-end;
        border-bottom: 1px solid #e0e0e0;
        cursor: pointer;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        margin: 24px 16px 8px;
        padding: 8px 0;
        position: relative;
      }

      .foam-u2-md-Select-label {
        color: #999;
        flex-grow: 1;
        font-size: 85%;
        font-weight: 500;
        position: absolute;
        top: -8px;
        z-index: 0;
      }

      .foam-u2-md-Select-value {
        flex-grow: 1;
      }

      .foam-u2-md-Select-down-arrow {
        fill: #999;
        height: 12px;
        margin: 8px 8px 2px 16px;
        width: 12px;
      }
    */},
    function initE() {/*#U2

        {{this.label$}}

{{this.text$}}

        <svg class="$-down-arrow" width="12px" height="12px" viewBox="0 0 48 48">
          <g><path d="M0 16 l24 24 24 -24 z"></path></g>
        </svg>

    */},
  ]
});
<commit_msg>U2 MD Select: Guard opening selector when mode is not read-write<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
CLASS({
  package: 'foam.u2.md',
  name: 'Select',
  extends: 'foam.u2.View',
  traits: ['foam.u2.ChoiceViewTrait'],

  requires: [
    'foam.u2.md.PopupMenu',
  ],
  imports: [
    'document',
  ],

  listeners: [
    {
      name: 'onClick',
      isFramed: true,
      code: function() {
        if ( this.mode !== 'rw' ) return;
        // Blur any active input element.
        var active = this.document.activeElement;
        if (active) active.blur();

        var self = this;
        var popup = this.PopupMenu.create({
          data$: this.data$,
          choices: this.choices,
          autoSetData: this.autoSetData
        });
        popup.open(this.index, this.id$el);
      }
    },
  ],

  templates: [
    function CSS() {/*
      .foam-u2-md-Select {
        align-items: flex-end;
        border-bottom: 1px solid #e0e0e0;
        cursor: pointer;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        margin: 24px 16px 8px;
        padding: 8px 0;
        position: relative;
      }

      .foam-u2-md-Select-label {
        color: #999;
        flex-grow: 1;
        font-size: 85%;
        font-weight: 500;
        position: absolute;
        top: -8px;
        z-index: 0;
      }

      .foam-u2-md-Select-value {
        flex-grow: 1;
      }

      .foam-u2-md-Select-down-arrow {
        fill: #999;
        height: 12px;
        margin: 8px 8px 2px 16px;
        width: 12px;
      }
    */},
    function initE() {/*#U2

        {{this.label$}}

{{this.text$}}

        <svg class="$-down-arrow" width="12px" height="12px" viewBox="0 0 48 48">
          <g><path d="M0 16 l24 24 24 -24 z"></path></g>
        </svg>

    */},
  ]
});
<|endoftext|>