<commit_before>/*
 * MelonJS Game Engine
 * (C) 2011 - 2015 Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 * Tile QT 0.7.x format
 * http://www.mapeditor.org/
 *
 */
(function (TMXConstants) {

    /**
     * a TMX Tile Set Object
     * @class
     * @memberOf me
     * @constructor
     */
    me.TMXTileset = Object.extend({
        // constructor
        init: function (tileset) {
            var i = 0;
            // first gid

            // tile properties (collidable, etc..)
            this.TileProperties = [];

            this.firstgid = this.lastgid = +tileset[TMXConstants.TMX_TAG_FIRSTGID];
            var src = tileset[TMXConstants.TMX_TAG_SOURCE];
            if (src && me.utils.getFileExtension(src).toLowerCase() === "tsx") {
                // load TSX
                src = me.utils.getBasename(src);
                // replace tileset with a local variable
                tileset = me.loader.getTMX(src).tileset;

                if (!tileset) {
                    throw new me.Error(src + " TSX tileset not found");
                }
                // normally tileset shoudld directly contains the required
                //information : UNTESTED as I did not find how to generate a JSON TSX file
            }

            this.name = tileset[TMXConstants.TMX_TAG_NAME];
            this.tilewidth = +tileset[TMXConstants.TMX_TAG_TILEWIDTH];
            this.tileheight = +tileset[TMXConstants.TMX_TAG_TILEHEIGHT];
            this.spacing = +tileset[TMXConstants.TMX_TAG_SPACING] || 0;
            this.margin = +tileset[TMXConstants.TMX_TAG_MARGIN] || 0;

            // set tile offset properties (if any)
            this.tileoffset = new me.Vector2d(0, 0);

            /**
             * Tileset contains animated tiles
             * @public
             * @type Boolean
             * @name me.TMXTileset#isAnimated
             */
            this.isAnimated = false;

            /**
             * Tileset animations
             * @private
             * @type Map
             * @name me.TMXTileset#animations
             */
            this.animations = new Map();

            var tiles = tileset.tiles;
            if (typeof(tiles) !== "undefined") {
                // native JSON format
                for (i in tiles) {
                    if (tiles.hasOwnProperty(i) && ("animation" in tiles[i])) {
                        this.isAnimated = true;
                        this.animations.set(+i + this.firstgid, {
                            dt      : 0,
                            idx     : 0,
                            frames  : tiles[i].animation,
                            cur     : tiles[i].animation[0]
                        });
                    }
                }
            }

            var offset = tileset[TMXConstants.TMX_TAG_TILEOFFSET];
            if (offset) {
                this.tileoffset.x = +offset[TMXConstants.TMX_TAG_X];
                this.tileoffset.y = +offset[TMXConstants.TMX_TAG_Y];
            }

            // set tile properties, if any
            var tileInfo = tileset.tileproperties;

            if (tileInfo) {
                // native JSON format
                for (i in tileInfo) {
                    if (tileInfo.hasOwnProperty(i)) {
                        this.setTileProperty(i + this.firstgid, tileInfo[i]);
                    }
                }
            }
            else if (tileset[TMXConstants.TMX_TAG_TILE]) {
                // converted XML format
                tileInfo = tileset[TMXConstants.TMX_TAG_TILE];
                if (!Array.isArray(tileInfo)) {
                    tileInfo = [ tileInfo ];
                }

                // iterate it
                for (i = 0; i < tileInfo.length; i++) {
                    var tileID = +tileInfo[i][TMXConstants.TMX_TAG_ID] + this.firstgid;
                    var prop = {};
                    me.TMXUtils.applyTMXProperties(prop, tileInfo[i]);
                    //apply tiled defined properties
                    this.setTileProperty(tileID, prop);

                    // Get animations
                    if ("animation" in tileInfo[i]) {
                        this.isAnimated = true;
                        this.animations.set(tileID, {
                            dt      : 0,
                            idx     : 0,
                            frames  : tileInfo[i].animation.frame,
                            cur     : tileInfo[i].animation.frame[0]
                        });
                    }
                }
            }

            // check for the texture corresponding image
            // manage inconstency between XML and JSON format
            var imagesrc = (
                typeof(tileset[TMXConstants.TMX_TAG_IMAGE]) === "string" ?
                tileset[TMXConstants.TMX_TAG_IMAGE] : tileset[TMXConstants.TMX_TAG_IMAGE].source
            );
            // extract base name
            imagesrc = me.utils.getBasename(imagesrc);
            this.image = imagesrc ? me.loader.getImage(imagesrc) : null;

            if (!this.image) {
                console.log("melonJS: '" + imagesrc + "' file for tileset '" + this.name + "' not found!");
            }

            // create a texture atlas for the given tileset
            this.texture = me.video.renderer.cache.get(this.image, {
                framewidth : this.tilewidth,
                frameheight : this.tileheight,
                margin : this.margin,
                spacing : this.spacing,
                // ignore error where the tileset is not divisible by the tile size
                ignoreError : true
            });
            this.atlas = this.texture.getAtlas();

            // calculate the number of tiles per horizontal line
            var hTileCount = ~~((this.image.width - this.margin) / (this.tilewidth + this.spacing));
            var vTileCount = ~~((this.image.height - this.margin) / (this.tileheight + this.spacing));
            // compute the last gid value in the tileset
            this.lastgid = this.firstgid + (((hTileCount * vTileCount) - 1) || 0);

            // check if transparency is defined for a specific color
            var transparency = tileset[TMXConstants.TMX_TAG_TRANS] || tileset[TMXConstants.TMX_TAG_IMAGE][TMXConstants.TMX_TAG_TRANS];
            // set Color Key for transparency if needed
            if (typeof(transparency) !== "undefined") {
                // applyRGB Filter (return a context object)
                this.image = me.video.renderer.applyRGBFilter(this.image, "transparent", transparency.toUpperCase()).canvas;
            }
        },

        /**
         * set the tile properties
         * @ignore
         * @function
         */
        setTileProperty : function (gid, prop) {
            // set the given tile id
            this.TileProperties[gid] = prop;
        },

        /**
         * return true if the gid belongs to the tileset
         * @name me.TMXTileset#contains
         * @public
         * @function
         * @param {Number} gid
         * @return {Boolean}
         */
        contains : function (gid) {
            return gid >= this.firstgid && gid <= this.lastgid;
        },

        /**
         * Get the view (local) tile ID from a GID, with animations applied
         * @name me.TMXTileset#getViewTileId
         * @public
         * @function
         * @param {Number} gid Global tile ID
         * @return {Number} View tile ID
         */
        getViewTileId : function (gid) {
            if (this.animations.has(gid)) {
                // apply animations
                gid = this.animations.get(gid).cur.tileid;
            }
            else {
                // get the local tileset id
                gid -= this.firstgid;
            }

            return gid;
        },

        /**
         * return a renderable object based on the given gid, with animations applied
         * @name me.TMXTileset#getTileObject
         * @public
         * @function
         * @param {me.Tile} a Tile object
         * @return {me.Renderable} either a me.Sprite object or a me.AnimationSheet
         */
        getTileObject : function (tile) {
            var renderable;

            if (this.animations.has(tile.tileId)) {
                var frames = [];
                (this.animations.get(tile.tileId).frames).forEach(function (frame) {
                    frames.push(frame.tileid);
                });
                renderable = this.texture.createAnimationFromName(frames);
            } else {
                renderable = this.texture.createSpriteFromName(tile.tileId);
            }

            if (tile.fippedAD) {
                renderable._sourceAngle += Math.PI / 2;
            }

            renderable.flipX(tile.fippedX);
            renderable.flipY(tile.fippedY);

            return renderable;
        },

        /**
         * return the properties of the specified tile
         * @name me.TMXTileset#getTileProperties
         * @public
         * @function
         * @param {Number} tileId
         * @return {Object}
         */
        getTileProperties: function (tileId) {
            return this.TileProperties[tileId];
        },

        // update tile animations
        update : function (dt) {
            var duration = 0,
                result = false;

            this.animations.forEach(function (anim) {
                anim.dt += dt;
                duration = anim.cur.duration;
                if (anim.dt >= duration) {
                    anim.dt -= duration;
                    anim.idx = (anim.idx + 1) % anim.frames.length;
                    anim.cur = anim.frames[anim.idx];
                    result = true;
                }
            });

            return result;
        },

        // draw the x,y tile
        drawTile : function (renderer, dx, dy, tmxTile) {
            // check if any transformation is required
            if (tmxTile.flipped) {
                renderer.save();
                // apply the tile current transform
                renderer.translate(dx, dy);
                renderer.transform(tmxTile.transform);
                // reset both values as managed through transform();
                dx = dy = 0;
            }

            var offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset;

            // draw the tile
            renderer.drawImage(
                this.image,
                offset.x, offset.y,
                this.tilewidth, this.tileheight,
                dx, dy,
                this.tilewidth, this.tileheight
            );

            if (tmxTile.flipped)  {
                // restore the context to the previous state
                renderer.restore();
            }
        }
    });

    /**
     * an object containing all tileset
     * @class
     * @memberOf me
     * @constructor
     */
    me.TMXTilesetGroup = Object.extend({
        // constructor
        init: function () {
            this.tilesets = [];
        },

        //add a tileset to the tileset group
        add : function (tileset) {
            this.tilesets.push(tileset);
        },

        //return the tileset at the specified index
        getTilesetByIndex : function (i) {
            return this.tilesets[i];
        },

        /**
         * return the tileset corresponding to the specified id <br>
         * will throw an exception if no matching tileset is found
         * @name me.TMXTilesetGroup#getTilesetByGid
         * @public
         * @function
         * @param {Number} gid
         * @return {me.TMXTileset} corresponding tileset
         */
        getTilesetByGid : function (gid) {
            var invalidRange = -1;
            // cycle through all tilesets
            for (var i = 0, len = this.tilesets.length; i < len; i++) {
                // return the corresponding tileset if matching
                if (this.tilesets[i].contains(gid)) {
                    return this.tilesets[i];
                }
                // typically indicates a layer with no asset loaded (collision?)
                if (this.tilesets[i].firstgid === this.tilesets[i].lastgid &&
                    gid >= this.tilesets[i].firstgid) {
                    // store the id if the [firstgid .. lastgid] is invalid
                    invalidRange = i;
                }
            }
            // return the tileset with the invalid range
            if (invalidRange !== -1) {
                return this.tilesets[invalidRange];
            }
            else {
                throw new me.Error("no matching tileset found for gid " + gid);
            }
        }
    });
})(me.TMXConstants);
<commit_msg>[#592] fixed typo (and bugs) in the flip flags<commit_after>/*
 * MelonJS Game Engine
 * (C) 2011 - 2015 Olivier Biot, Jason Oster, Aaron McLeod
 * http://www.melonjs.org
 *
 * Tile QT 0.7.x format
 * http://www.mapeditor.org/
 *
 */
(function (TMXConstants) {

    /**
     * a TMX Tile Set Object
     * @class
     * @memberOf me
     * @constructor
     */
    me.TMXTileset = Object.extend({
        // constructor
        init: function (tileset) {
            var i = 0;
            // first gid

            // tile properties (collidable, etc..)
            this.TileProperties = [];

            this.firstgid = this.lastgid = +tileset[TMXConstants.TMX_TAG_FIRSTGID];
            var src = tileset[TMXConstants.TMX_TAG_SOURCE];
            if (src && me.utils.getFileExtension(src).toLowerCase() === "tsx") {
                // load TSX
                src = me.utils.getBasename(src);
                // replace tileset with a local variable
                tileset = me.loader.getTMX(src).tileset;

                if (!tileset) {
                    throw new me.Error(src + " TSX tileset not found");
                }
                // normally tileset shoudld directly contains the required
                //information : UNTESTED as I did not find how to generate a JSON TSX file
            }

            this.name = tileset[TMXConstants.TMX_TAG_NAME];
            this.tilewidth = +tileset[TMXConstants.TMX_TAG_TILEWIDTH];
            this.tileheight = +tileset[TMXConstants.TMX_TAG_TILEHEIGHT];
            this.spacing = +tileset[TMXConstants.TMX_TAG_SPACING] || 0;
            this.margin = +tileset[TMXConstants.TMX_TAG_MARGIN] || 0;

            // set tile offset properties (if any)
            this.tileoffset = new me.Vector2d(0, 0);

            /**
             * Tileset contains animated tiles
             * @public
             * @type Boolean
             * @name me.TMXTileset#isAnimated
             */
            this.isAnimated = false;

            /**
             * Tileset animations
             * @private
             * @type Map
             * @name me.TMXTileset#animations
             */
            this.animations = new Map();

            var tiles = tileset.tiles;
            if (typeof(tiles) !== "undefined") {
                // native JSON format
                for (i in tiles) {
                    if (tiles.hasOwnProperty(i) && ("animation" in tiles[i])) {
                        this.isAnimated = true;
                        this.animations.set(+i + this.firstgid, {
                            dt      : 0,
                            idx     : 0,
                            frames  : tiles[i].animation,
                            cur     : tiles[i].animation[0]
                        });
                    }
                }
            }

            var offset = tileset[TMXConstants.TMX_TAG_TILEOFFSET];
            if (offset) {
                this.tileoffset.x = +offset[TMXConstants.TMX_TAG_X];
                this.tileoffset.y = +offset[TMXConstants.TMX_TAG_Y];
            }

            // set tile properties, if any
            var tileInfo = tileset.tileproperties;

            if (tileInfo) {
                // native JSON format
                for (i in tileInfo) {
                    if (tileInfo.hasOwnProperty(i)) {
                        this.setTileProperty(i + this.firstgid, tileInfo[i]);
                    }
                }
            }
            else if (tileset[TMXConstants.TMX_TAG_TILE]) {
                // converted XML format
                tileInfo = tileset[TMXConstants.TMX_TAG_TILE];
                if (!Array.isArray(tileInfo)) {
                    tileInfo = [ tileInfo ];
                }

                // iterate it
                for (i = 0; i < tileInfo.length; i++) {
                    var tileID = +tileInfo[i][TMXConstants.TMX_TAG_ID] + this.firstgid;
                    var prop = {};
                    me.TMXUtils.applyTMXProperties(prop, tileInfo[i]);
                    //apply tiled defined properties
                    this.setTileProperty(tileID, prop);

                    // Get animations
                    if ("animation" in tileInfo[i]) {
                        this.isAnimated = true;
                        this.animations.set(tileID, {
                            dt      : 0,
                            idx     : 0,
                            frames  : tileInfo[i].animation.frame,
                            cur     : tileInfo[i].animation.frame[0]
                        });
                    }
                }
            }

            // check for the texture corresponding image
            // manage inconstency between XML and JSON format
            var imagesrc = (
                typeof(tileset[TMXConstants.TMX_TAG_IMAGE]) === "string" ?
                tileset[TMXConstants.TMX_TAG_IMAGE] : tileset[TMXConstants.TMX_TAG_IMAGE].source
            );
            // extract base name
            imagesrc = me.utils.getBasename(imagesrc);
            this.image = imagesrc ? me.loader.getImage(imagesrc) : null;

            if (!this.image) {
                console.log("melonJS: '" + imagesrc + "' file for tileset '" + this.name + "' not found!");
            }

            // create a texture atlas for the given tileset
            this.texture = me.video.renderer.cache.get(this.image, {
                framewidth : this.tilewidth,
                frameheight : this.tileheight,
                margin : this.margin,
                spacing : this.spacing,
                // ignore error where the tileset is not divisible by the tile size
                ignoreError : true
            });
            this.atlas = this.texture.getAtlas();

            // calculate the number of tiles per horizontal line
            var hTileCount = ~~((this.image.width - this.margin) / (this.tilewidth + this.spacing));
            var vTileCount = ~~((this.image.height - this.margin) / (this.tileheight + this.spacing));
            // compute the last gid value in the tileset
            this.lastgid = this.firstgid + (((hTileCount * vTileCount) - 1) || 0);

            // check if transparency is defined for a specific color
            var transparency = tileset[TMXConstants.TMX_TAG_TRANS] || tileset[TMXConstants.TMX_TAG_IMAGE][TMXConstants.TMX_TAG_TRANS];
            // set Color Key for transparency if needed
            if (typeof(transparency) !== "undefined") {
                // applyRGB Filter (return a context object)
                this.image = me.video.renderer.applyRGBFilter(this.image, "transparent", transparency.toUpperCase()).canvas;
            }
        },

        /**
         * set the tile properties
         * @ignore
         * @function
         */
        setTileProperty : function (gid, prop) {
            // set the given tile id
            this.TileProperties[gid] = prop;
        },

        /**
         * return true if the gid belongs to the tileset
         * @name me.TMXTileset#contains
         * @public
         * @function
         * @param {Number} gid
         * @return {Boolean}
         */
        contains : function (gid) {
            return gid >= this.firstgid && gid <= this.lastgid;
        },

        /**
         * Get the view (local) tile ID from a GID, with animations applied
         * @name me.TMXTileset#getViewTileId
         * @public
         * @function
         * @param {Number} gid Global tile ID
         * @return {Number} View tile ID
         */
        getViewTileId : function (gid) {
            if (this.animations.has(gid)) {
                // apply animations
                gid = this.animations.get(gid).cur.tileid;
            }
            else {
                // get the local tileset id
                gid -= this.firstgid;
            }

            return gid;
        },

        /**
         * return a renderable object based on the given gid, with animations applied
         * @name me.TMXTileset#getTileObject
         * @public
         * @function
         * @param {me.Tile} a Tile object
         * @return {me.Renderable} either a me.Sprite object or a me.AnimationSheet
         */
        getTileObject : function (tile) {
            var renderable;

            if (this.animations.has(tile.tileId)) {
                var frames = [];
                (this.animations.get(tile.tileId).frames).forEach(function (frame) {
                    frames.push(frame.tileid);
                });
                renderable = this.texture.createAnimationFromName(frames);
            } else {
                renderable = this.texture.createSpriteFromName(tile.tileId);
            }

            if (tile.fippedAD) {
                renderable._sourceAngle += Math.PI / 2;
            }

            renderable.flipX(tile.flippedX);
            renderable.flipY(tile.flippedY);

            return renderable;
        },

        /**
         * return the properties of the specified tile
         * @name me.TMXTileset#getTileProperties
         * @public
         * @function
         * @param {Number} tileId
         * @return {Object}
         */
        getTileProperties: function (tileId) {
            return this.TileProperties[tileId];
        },

        // update tile animations
        update : function (dt) {
            var duration = 0,
                result = false;

            this.animations.forEach(function (anim) {
                anim.dt += dt;
                duration = anim.cur.duration;
                if (anim.dt >= duration) {
                    anim.dt -= duration;
                    anim.idx = (anim.idx + 1) % anim.frames.length;
                    anim.cur = anim.frames[anim.idx];
                    result = true;
                }
            });

            return result;
        },

        // draw the x,y tile
        drawTile : function (renderer, dx, dy, tmxTile) {
            // check if any transformation is required
            if (tmxTile.flipped) {
                renderer.save();
                // apply the tile current transform
                renderer.translate(dx, dy);
                renderer.transform(tmxTile.transform);
                // reset both values as managed through transform();
                dx = dy = 0;
            }

            var offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset;

            // draw the tile
            renderer.drawImage(
                this.image,
                offset.x, offset.y,
                this.tilewidth, this.tileheight,
                dx, dy,
                this.tilewidth, this.tileheight
            );

            if (tmxTile.flipped)  {
                // restore the context to the previous state
                renderer.restore();
            }
        }
    });

    /**
     * an object containing all tileset
     * @class
     * @memberOf me
     * @constructor
     */
    me.TMXTilesetGroup = Object.extend({
        // constructor
        init: function () {
            this.tilesets = [];
        },

        //add a tileset to the tileset group
        add : function (tileset) {
            this.tilesets.push(tileset);
        },

        //return the tileset at the specified index
        getTilesetByIndex : function (i) {
            return this.tilesets[i];
        },

        /**
         * return the tileset corresponding to the specified id <br>
         * will throw an exception if no matching tileset is found
         * @name me.TMXTilesetGroup#getTilesetByGid
         * @public
         * @function
         * @param {Number} gid
         * @return {me.TMXTileset} corresponding tileset
         */
        getTilesetByGid : function (gid) {
            var invalidRange = -1;
            // cycle through all tilesets
            for (var i = 0, len = this.tilesets.length; i < len; i++) {
                // return the corresponding tileset if matching
                if (this.tilesets[i].contains(gid)) {
                    return this.tilesets[i];
                }
                // typically indicates a layer with no asset loaded (collision?)
                if (this.tilesets[i].firstgid === this.tilesets[i].lastgid &&
                    gid >= this.tilesets[i].firstgid) {
                    // store the id if the [firstgid .. lastgid] is invalid
                    invalidRange = i;
                }
            }
            // return the tileset with the invalid range
            if (invalidRange !== -1) {
                return this.tilesets[invalidRange];
            }
            else {
                throw new me.Error("no matching tileset found for gid " + gid);
            }
        }
    });
})(me.TMXConstants);
<|endoftext|>


<commit_before>

/**
 * Reusable components for each level
 * @param pgame current phaser game instance
 */
ajtxz_hcgame.levelbase = function (pgame) {
    //Constants
    var SLIDER_X_POS = 300;
    var SLIDER_Y_POS = 575;
    var CANNON_DEFAULT = -Math.PI/4.0; //45 degrees
    var MAX_VELOCITY = 1000; //NEED TO FIND BEST VALUE

    //Game
    var game = ajtxz_hcgame.game;
    var options = game.options;

    // Obstacle variable
    var crank, crank_knob;
    var cannon_body;
    var captain;
    var pool;

    //Global Game Components
    var bird, slider_button, slider_box, slider_bar;

    function collide_obstacles(){
        // Handle collision with obstacles

    }

    function drawCannon_captain() {

        var cb_x = 10,
            cb_y = (options.height * 0.6),
            cs_x = 20,
            cs_y = (options.height * 0.7) + 10;

        game.captain = game.addAsset(cb_x + 86, cb_y + 88, 'captain');
        captain = game.captain;
        captain.anchor.setTo(0.28, 0.78);

        cannon_body = game.addAsset(cb_x + 85, cb_y + 105, 'cannon_body');
        cannon_body.scale.setTo(0.5, 0.5);
        cannon_body.anchor.setTo(0.3,0.8);
        cannon_body.rotation = CANNON_DEFAULT;

        var cannon_stand = game.addAsset(cs_x + 40, cs_y + 20, 'cannon_stand')
            .scale.setTo(0.5, 0.5);

    }

    function drawObstacles(){
        game.obstacles = pgame.add.group();
        game.obstacles.enableBody = true;

        // Add pool
        pool = game.addAsset(590, 330, 'pool');
        pool.scale.setTo(0.7,0.7);

        // Add bird
        bird = game.obstacles.create(pgame.world.centerX, 300, 'bird');

        // Two animations, flying left and right.
        bird.animations.add('left', [0,1,2,3,4], 10, true);
        bird.animations.add('right', [5,6,7,8,9], 10, true);

        // Add water jet
        var waterjet = game.obstacles.create(400, 290, 'waterjet');
        waterjet.scale.setTo(1,1);
        waterjet.immovable = true;
        waterjet.animations.add('shooting', [0,1], 2, true);
        waterjet.animations.play('shooting');

        // Add fire rings
    }

    this.birdFly = function(motionDst, motionTime){
        var bird_orientation = 1;

        bird.animations.play('right');

        var tweenbird = pgame.add.tween(bird).to({ x: motionDst }, motionTime, Phaser.Easing.Linear.None, true, 0, Number.POSITIVE_INFINITY, true);

        tweenbird.onLoop.add(function(){
            if (bird_orientation == 1){
                bird.animations.play('left');
                bird_orientation = 0;
            }else{
                bird.animations.play('right');
                bird_orientation = 1;
            }
        });
    };

    //Returns velocity with respect to current gunpowder level
    function getVelocity()
    {
        var x_position = slider_button.x - slider_box.x; //Determine x position of slider button within box
        var percentage = x_position / (slider_box.width - slider_button.width); //Determine percentage of gunpowder bar filled
        return percentage * MAX_VELOCITY; //Determine velocity
    }

    function drawBackgrounds () {

        game.addAsset(0, 0, 'level_background');
        //game.controlBoard = game.addAsset(0, 480, 'control_board');
        var g = pgame.add.group();
        g.enableBody = true;

        game.controlBoard = g.create(0, pgame.world.height - 110, 'control_board');
        game.controlBoard.body.immovable = true;
    }

    function initControls()
    {
        ////Initialize Angle Crank////
        crank = game.addAsset(90, 609, 'crank');
        crank_knob = game.addAsset(crank.x, crank.y, 'crank_knob');

        crank.scale.setTo(0.8, 0.8);
        crank.anchor.setTo(0.5, 0.5);
        crank.blocked = false;

        crank_knob.scale.setTo(0.8, 0.8);
        crank_knob.anchor.setTo(0.5, 0.5);
        crank_knob.pivot = new PIXI.Point(-49, -1);
        crank_knob.inputEnabled = true;
        crank_knob.input.useHandCursor = true;

        ////Initialize Gunpowder Slider////
        slider_box = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS, 'slider_box'); //Load slider button
        slider_bar = game.addAsset(SLIDER_X_POS+13, SLIDER_Y_POS+20, 'slider_bar'); //Load slider button
        slider_button = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS+5, 'slider_button'); //Load slider box
        //Set up input handler
        slider_button.inputEnabled = true;
        slider_button.input.enableDrag(false);
        slider_button.input.allowVerticalDrag = false;
        slider_button.input.useHandCursor = true;
        slider_button.input.boundsSprite = slider_box;

        ////Initialize Fire Button////
        pgame.add.button(660, 565, 'fire_button', function() {
            game.captain.body.gravity.y = 800;

            //Velocity determined by current slider and wheel positions
            var velocity = getVelocity();
            new Phaser.Text(game, 300,300,velocity);
            //Need rotation angle to get velocity_x and velocity_y values from velocity
            game.captain.body.velocity.setTo(velocity, -velocity);
        }).scale.setTo(0.70, 0.70);
    }

    this.init = function() {
        drawBackgrounds();
        initControls();
        drawCannon_captain();
        drawObstacles();

        pgame.physics.arcade.enable(game.captain);
        game.captain.body.collideWorldBounds = true;
        game.captain.body.bounce.y = 0.3;

    };

    this.defaultUpdate = function()
    {
        pgame.physics.arcade.collide(game.captain, game.controlBoard);
        pgame.physics.arcade.collide(game.captain, game.obstacles, collide_obstacles);

        //Stretch slider bar with slider button
        if (slider_button.input.pointerDragged())
            slider_bar.width = slider_button.x - slider_box.x;

        //Crank Functionality
        if (crank_knob.input.pointerDown())
        {
            var click = pgame.input.activePointer;
            var angle = Phaser.Math.angleBetween(crank.x, crank.y, click.x, click.y);

            if (crank.blocked == false)
            {
                crank_knob.rotation = crank.rotation = angle;
                //game.captain.rotation = angle;
                cannon_body.rotation = CANNON_DEFAULT + angle / 4;
            }
        }

        var current_angle = Phaser.Math.ceilTo(cannon_body.angle);
        if (current_angle == -89 || current_angle == 0)
            crank.blocked = true;

        if (crank.blocked && crank_knob.input.justReleased()) {
            crank.blocked = false;
            //Nudge crank backwards
            crank_knob.rotation = crank.rotation = crank.rotation + Math.PI/180.0;
            cannon_body.rotation += Math.PI/180.0;

        }

        console.log("crank blocked: " + crank.blocked);

    }

};
<commit_msg>crank blocking implemented<commit_after>

/**
 * Reusable components for each level
 * @param pgame current phaser game instance
 */
ajtxz_hcgame.levelbase = function (pgame) {
    //Constants
    var SLIDER_X_POS = 300;
    var SLIDER_Y_POS = 575;
    var CANNON_DEFAULT = -Math.PI/4.0; //45 degrees
    var MAX_VELOCITY = 1000; //NEED TO FIND BEST VALUE

    //Game
    var game = ajtxz_hcgame.game;
    var options = game.options;

    // Obstacle variable
    var crank, crank_knob;
    var cannon_body;
    var captain;
    var pool;

    //Global Game Components
    var bird, slider_button, slider_box, slider_bar;

    function collide_obstacles(){
        // Handle collision with obstacles

    }

    function drawCannon_captain() {

        var cb_x = 10,
            cb_y = (options.height * 0.6),
            cs_x = 20,
            cs_y = (options.height * 0.7) + 10;

        game.captain = game.addAsset(cb_x + 86, cb_y + 88, 'captain');
        captain = game.captain;
        captain.anchor.setTo(0.28, 0.78);

        cannon_body = game.addAsset(cb_x + 85, cb_y + 105, 'cannon_body');
        cannon_body.scale.setTo(0.5, 0.5);
        cannon_body.anchor.setTo(0.3,0.8);
        cannon_body.rotation = CANNON_DEFAULT;

        var cannon_stand = game.addAsset(cs_x + 40, cs_y + 20, 'cannon_stand')
            .scale.setTo(0.5, 0.5);

    }

    function drawObstacles(){
        game.obstacles = pgame.add.group();
        game.obstacles.enableBody = true;

        // Add pool
        pool = game.addAsset(590, 330, 'pool');
        pool.scale.setTo(0.7,0.7);

        // Add bird
        bird = game.obstacles.create(pgame.world.centerX, 300, 'bird');

        // Two animations, flying left and right.
        bird.animations.add('left', [0,1,2,3,4], 10, true);
        bird.animations.add('right', [5,6,7,8,9], 10, true);

        // Add water jet
        var waterjet = game.obstacles.create(400, 290, 'waterjet');
        waterjet.scale.setTo(1,1);
        waterjet.immovable = true;
        waterjet.animations.add('shooting', [0,1], 2, true);
        waterjet.animations.play('shooting');

        // Add fire rings
    }

    this.birdFly = function(motionDst, motionTime){
        var bird_orientation = 1;

        bird.animations.play('right');

        var tweenbird = pgame.add.tween(bird).to({ x: motionDst }, motionTime, Phaser.Easing.Linear.None, true, 0, Number.POSITIVE_INFINITY, true);

        tweenbird.onLoop.add(function(){
            if (bird_orientation == 1){
                bird.animations.play('left');
                bird_orientation = 0;
            }else{
                bird.animations.play('right');
                bird_orientation = 1;
            }
        });
    };

    //Returns velocity with respect to current gunpowder level
    function getVelocity()
    {
        var x_position = slider_button.x - slider_box.x; //Determine x position of slider button within box
        var percentage = x_position / (slider_box.width - slider_button.width); //Determine percentage of gunpowder bar filled
        return percentage * MAX_VELOCITY; //Determine velocity
    }

    function drawBackgrounds () {

        game.addAsset(0, 0, 'level_background');
        //game.controlBoard = game.addAsset(0, 480, 'control_board');
        var g = pgame.add.group();
        g.enableBody = true;

        game.controlBoard = g.create(0, pgame.world.height - 110, 'control_board');
        game.controlBoard.body.immovable = true;
    }

    function initControls()
    {
        ////Initialize Angle Crank////
        crank = game.addAsset(90, 609, 'crank');
        crank_knob = game.addAsset(crank.x, crank.y, 'crank_knob');

        crank.scale.setTo(0.8, 0.8);
        crank.anchor.setTo(0.5, 0.5);
        crank.blocked = false;

        crank_knob.scale.setTo(0.8, 0.8);
        crank_knob.anchor.setTo(0.5, 0.5);
        crank_knob.pivot = new PIXI.Point(-49, -1);
        crank_knob.inputEnabled = true;
        crank_knob.input.useHandCursor = true;

        ////Initialize Gunpowder Slider////
        slider_box = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS, 'slider_box'); //Load slider button
        slider_bar = game.addAsset(SLIDER_X_POS+13, SLIDER_Y_POS+20, 'slider_bar'); //Load slider button
        slider_button = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS+5, 'slider_button'); //Load slider box
        //Set up input handler
        slider_button.inputEnabled = true;
        slider_button.input.enableDrag(false);
        slider_button.input.allowVerticalDrag = false;
        slider_button.input.useHandCursor = true;
        slider_button.input.boundsSprite = slider_box;

        ////Initialize Fire Button////
        pgame.add.button(660, 565, 'fire_button', function() {
            game.captain.body.gravity.y = 800;

            //Velocity determined by current slider and wheel positions
            var velocity = getVelocity();
            new Phaser.Text(game, 300,300,velocity);
            //Need rotation angle to get velocity_x and velocity_y values from velocity
            game.captain.body.velocity.setTo(velocity, -velocity);
        }).scale.setTo(0.70, 0.70);
    }

    this.init = function() {
        drawBackgrounds();
        initControls();
        drawCannon_captain();
        drawObstacles();

        pgame.physics.arcade.enable(game.captain);
        game.captain.body.collideWorldBounds = true;
        game.captain.body.bounce.y = 0.3;

    };

    this.defaultUpdate = function()
    {
        pgame.physics.arcade.collide(game.captain, game.controlBoard);
        pgame.physics.arcade.collide(game.captain, game.obstacles, collide_obstacles);

        //Stretch slider bar with slider button
        if (slider_button.input.pointerDragged())
            slider_bar.width = slider_button.x - slider_box.x;

        //Crank Functionality
        var current_angle = Phaser.Math.ceilTo(cannon_body.angle);
        if (crank_knob.input.pointerDown())
        {
            var click = pgame.input.activePointer;
            var angle = Phaser.Math.angleBetween(crank.x, crank.y, click.x, click.y);

            if ((current_angle != -89 || angle < 0 && angle > -178) && (current_angle != 0 || angle > 0 && angle < 179))
            {
                crank_knob.rotation = crank.rotation = angle;
                //game.captain.rotation = angle;
                cannon_body.rotation = CANNON_DEFAULT + angle / 4;
            }
        }

        /*console.log("crank blocked: " + crank.blocked);*/

    }

};
<|endoftext|>


<commit_before>/*
 * owo-whats this - Core file
 *
 * Contributed by Ovyerus
 */

const fs = require('fs');
const bot = require(`${__baseDir}/bot.js`).bot;

/**
 * Parse a message's content to check if it starts with a registered prefix.
 * @arg {String} content Message content to check.
 * @returns {?String} Content without the prefix if the content starts with a prefix.
 */
function parse(content) {
    return new Promise((resolve, reject) => {
        if (typeof content !== 'string') reject(new Error('content is not a string'));

        var oldContent = content;
        var prefixes = JSON.parse(fs.readFileSync(`${__baseDir}/data/prefixes.json`));
        prefixes.push(`<@${bot.user.id}> `);

        if (!content.startsWith(bot.config.mainPrefix)) {
            for (let i in prefixes) {
                if (content.startsWith(prefixes[i])) {
                    content = content.substring(prefixes[i].length);
                    break;
                }
            }
        } else {
            content = content.substring(bot.config.mainPrefix.length);
        }

        if (content !== oldContent) {
            resolve(content);
        } else {
            resolve();
        }
    });
}

module.exports = parse;<commit_msg>Edit comment<commit_after>/*
 * owo-whats this - prefix parser
 *
 * Contributed by Ovyerus
 */

const fs = require('fs');
const bot = require(`${__baseDir}/bot.js`).bot;

/**
 * Parse a message's content to check if it starts with a registered prefix.
 * @arg {String} content Message content to check.
 * @returns {?String} Content without the prefix if the content starts with a prefix.
 */
function parse(content) {
    return new Promise((resolve, reject) => {
        if (typeof content !== 'string') reject(new Error('content is not a string'));

        var oldContent = content;
        var prefixes = JSON.parse(fs.readFileSync(`${__baseDir}/data/prefixes.json`));
        prefixes.push(`<@${bot.user.id}> `);

        if (!content.startsWith(bot.config.mainPrefix)) {
            for (let i in prefixes) {
                if (content.startsWith(prefixes[i])) {
                    content = content.substring(prefixes[i].length);
                    break;
                }
            }
        } else {
            content = content.substring(bot.config.mainPrefix.length);
        }

        if (content !== oldContent) {
            resolve(content);
        } else {
            resolve();
        }
    });
}

module.exports = parse;<|endoftext|>


<commit_before>var windows = [{
    title: "File Explorer",
    url: "http://0.0.0.0:3000/fileExplorer/index.html",
    running: false,
    minimized: true,
    icon: "fileExplorer/logo.png",
    zIndex: 0
  },
  {
    title: "Text Editor",
    url: "http://0.0.0.0:3000/textEditor/index.html",
    running: false,
    minimized: true,
    icon: "textEditor/logo.png",
    zIndex: 0
               },
              ];

// order of open windows.  Used to calculate z-index.
var windowOrder = [];

var wm = new Vue({
  el: '#desktop',
  data: {
    windows: windows
  }
});

// update z-index of windows
var updateOrder = function () {
  for (var i = 0; i < windows.length; ++i) {
    console.log(windows[i].title)
    if (windows[i].running === true & windows[i].minimized !== true) {
      console.log(windows[i].title + "will be updated");
       var position = windowOrder.indexOf(windows[i].title);
      if(position > -1){
        windows[i].zIndex = 200 - position;
      }
    }
  }
}
var taskbar = new Vue({
  el: '#taskbar',
  data: {
    programs: windows
  },
  methods: {
    open: function (app) {
      app.running = true;

    app.minimized = !app.minimized;
      if (app.minimized === false) {
        windowOrder.unshift(app.title);
      }
     if(app.minimized === true){
       windowOrder.pop(app.title);
     }
      updateOrder();
  },
  minimize: function (app) {
    // put window on top
    app.minimized = !app.minimized;

  }
}
})<commit_msg>removed extra comma.<commit_after>var windows = [{
    title: "File Explorer",
    url: "http://0.0.0.0:3000/fileExplorer/index.html",
    running: false,
    minimized: true,
    icon: "fileExplorer/logo.png",
    zIndex: 0
  },
  {
    title: "Text Editor",
    url: "http://0.0.0.0:3000/textEditor/index.html",
    running: false,
    minimized: true,
    icon: "textEditor/logo.png",
    zIndex: 0
               }

              ];

// order of open windows.  Used to calculate z-index.
var windowOrder = [];

var wm = new Vue({
  el: '#desktop',
  data: {
    windows: windows
  }
});

// update z-index of windows
var updateOrder = function () {
  for (var i = 0; i < windows.length; ++i) {
    console.log(windows[i].title)
    if (windows[i].running === true & windows[i].minimized !== true) {
      console.log(windows[i].title + "will be updated");
       var position = windowOrder.indexOf(windows[i].title);
      if(position > -1){
        windows[i].zIndex = 200 - position;
      }
    }
  }
}
var taskbar = new Vue({
  el: '#taskbar',
  data: {
    programs: windows
  },
  methods: {
    open: function (app) {
      app.running = true;

    app.minimized = !app.minimized;
      if (app.minimized === false) {
        windowOrder.unshift(app.title);
      }
     if(app.minimized === true){
       windowOrder.pop(app.title);
     }
      updateOrder();
  },
  minimize: function (app) {
    // put window on top
    app.minimized = !app.minimized;

  }
}
})<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc object
 * @name conferenceApp
 * @requires $routeProvider
 * @requires conferenceControllers
 * @requires ui.bootstrap
 *
 * @description
 * Root app, which routes and specifies the partial html
 * and controller depending on the url requested.
 *
 */
var app = angular.module('conferenceApp',
    ['conferenceControllers', 'ngRoute', 'ui.bootstrap']).
    config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
                when('/conference', {
                    templateUrl: '/partials/show_conferences.html',
                    controller: 'ShowConferenceCtrl'
                }).
                when('/conference/create', {
                    templateUrl: '/partials/create_conferences.html',
                    controller: 'CreateConferenceCtrl'
                }).
                when('/conference/detail/:websafeConferenceKey', {
                    templateUrl: '/partials/conference_detail.html',
                    controller: 'ConferenceDetailCtrl'
                }).
                when('/profile', {
                    templateUrl: '/partials/profile.html',
                    controller: 'MyProfileCtrl'
                }).
                when('/', {
                    templateUrl: '/partials/home.html'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

/**
 * @ngdoc filter
 * @name startFrom
 *
 * @description
 * A filter that extracts an array from the specific index.
 *
 */
app.filter('startFrom', function () {
    /**
     * Extracts an array from the specific index.
     *
     * @param {Array} data
     * @param {Integer} start
     * @returns {Array|*}
     */
    var filter = function (data, start) {
        return data.slice(start);
    }
    return filter;
});

/**
 * @ngdoc constant
 * @name HTTP_ERRORS
 *
 * @description
 * Holds the constants that represent HTTP error codes.
 *
 */
app.constant('HTTP_ERRORS', {
    'UNAUTHORIZED': 401
});

/**
 * @ngdoc service
 * @name oauth2Provider
 *
 * @description
 * Service that holds the OAuth2 information shared across all the pages.
 *
 */
app.factory('oauth2Provider', function ($modal) {
    var oauth2Provider = {
        CLIENT_ID: '346836589331-cfqac60nqcrn1boavmsbuej52u0djdj6.apps.googleusercontent.com',
        SCOPES: 'https://www.googleapis.com/auth/userinfo.email profile',
        signedIn: false
    };

    /**
     * Calls the OAuth2 authentication method.
     */
    oauth2Provider.signIn = function (callback) {
        gapi.auth.signIn({
            'clientid': oauth2Provider.CLIENT_ID,
            'cookiepolicy': 'single_host_origin',
            'accesstype': 'online',
            'approveprompt': 'auto',
            'scope': oauth2Provider.SCOPES,
            'callback': callback
        });
    };

    /**
     * Logs out the user.gapi.auth.setToken(null);
     */
    oauth2Provider.signOut = function () {
        gapi.auth.signOut();
        // Explicitly set the invalid access token in order to make the API calls fail.
        gapi.auth.setToken({access_token: ''})
        oauth2Provider.signedIn = false;
    };

    /**
     * Shows the modal with Google+ sign in button.
     *
     * @returns {*|Window}
     */
    oauth2Provider.showLoginModal = function() {
        var modalInstance = $modal.open({
            templateUrl: '/partials/login.modal.html',
            controller: 'OAuth2LoginModalCtrl'
        });
        return modalInstance;
    };

    return oauth2Provider;
});
<commit_msg>Update app.js<commit_after>'use strict';

/**
 * @ngdoc object
 * @name conferenceApp
 * @requires $routeProvider
 * @requires conferenceControllers
 * @requires ui.bootstrap
 *
 * @description
 * Root app, which routes and specifies the partial html
 * and controller depending on the url requested.
 *
 */
var app = angular.module('conferenceApp',
    ['conferenceControllers', 'ngRoute', 'ui.bootstrap']).
    config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
                when('/conference', {
                    templateUrl: '/partials/show_conferences.html',
                    controller: 'ShowConferenceCtrl'
                }).
                when('/conference/create', {
                    templateUrl: '/partials/create_conferences.html',
                    controller: 'CreateConferenceCtrl'
                }).
                when('/conference/detail/:websafeConferenceKey', {
                    templateUrl: '/partials/conference_detail.html',
                    controller: 'ConferenceDetailCtrl'
                }).
                when('/profile', {
                    templateUrl: '/partials/profile.html',
                    controller: 'MyProfileCtrl'
                }).
                when('/', {
                    templateUrl: '/partials/home.html'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

/**
 * @ngdoc filter
 * @name startFrom
 *
 * @description
 * A filter that extracts an array from the specific index.
 *
 */
app.filter('startFrom', function () {
    /**
     * Extracts an array from the specific index.
     *
     * @param {Array} data
     * @param {Integer} start
     * @returns {Array|*}
     */
    var filter = function (data, start) {
        return data.slice(start);
    }
    return filter;
});

/**
 * @ngdoc constant
 * @name HTTP_ERRORS
 *
 * @description
 * Holds the constants that represent HTTP error codes.
 *
 */
app.constant('HTTP_ERRORS', {
    'UNAUTHORIZED': 401
});

/**
 * @ngdoc service
 * @name oauth2Provider
 *
 * @description
 * Service that holds the OAuth2 information shared across all the pages.
 *
 */
app.factory('oauth2Provider', function ($modal) {
    var oauth2Provider = {
        CLIENT_ID: '346836589331-cfqac60nqcrn1boavmsbuej52u0djdj6.apps.googleusercontent.com',
        SCOPES: 'https://www.googleapis.com/auth/userinfo.email profile',
        signedIn: false
    };

    /**
     * Calls the OAuth2 authentication method.
     */
    oauth2Provider.signIn = function (callback) {
        gapi.auth.signIn({
            'clientid': oauth2Provider.CLIENT_ID,
            'cookiepolicy': 'single_host_origin',
            'accesstype': 'online',
            'approveprompt': 'auto',
            'scope': oauth2Provider.SCOPES,
            'callback': callback
        });
    };

    /**
     * Logs out the user.gapi.auth.setToken(null); or auth2.disconnect();
     */
    oauth2Provider.signOut = function () {
        gapi.auth.signOut();
        // Explicitly set the invalid access token in order to make the API calls fail.
        gapi.auth.setToken({access_token: ''})
        oauth2Provider.signedIn = false;
    };

    /**
     * Shows the modal with Google+ sign in button.
     *
     * @returns {*|Window}
     */
    oauth2Provider.showLoginModal = function() {
        var modalInstance = $modal.open({
            templateUrl: '/partials/login.modal.html',
            controller: 'OAuth2LoginModalCtrl'
        });
        return modalInstance;
    };

    return oauth2Provider;
});
<|endoftext|>


<commit_before>/* @flow */
'use strict';

import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, StyleSheet } = React;

import SerifText from '../../text/serif'
import LargeShowsList from './large_list'
import SmallShowsList from './small_list'

class Shows extends React.Component {
  render() {
    return (
      <View style={styles.container}>

        <SerifText style={styles.title}>Current & Upcoming Shows</SerifText>
        <LargeShowsList shows={this.props.artist.current_shows} />

        <View style={{height: 1, backgroundColor: 'grey', flex: 3, marginTop: 40, marginBottom: 20}}></View>

        <View style={{marginBottom: 50}}>
          <SerifText style={styles.title}>Past Shows</SerifText>
          <SmallShowsList shows={this.props.artist.past_shows} style={{marginBottom: 50}} />
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'flex-start',
  },
  title: {
    fontSize: 20,
    textAlign: 'left',
    marginLeft: -3,
  },
  listView: {
     paddingBottom: 40,
  },
});

export default Relay.createContainer(Shows, {
  fragments: {
    artist: () => Relay.QL`
      fragment on Artist {
        current_shows: partner_shows(status: "running") {
          ${LargeShowsList.getFragment('shows')}
        }
        past_shows: partner_shows(status: "closed") {
          ${SmallShowsList.getFragment('shows')}
        }
      }
    `,
  }
});<commit_msg>[Shows] Add upcoming shows.<commit_after>/* @flow */
'use strict';

import Relay from 'react-relay';
import React from 'react-native';
const { View, Text, StyleSheet } = React;

import SerifText from '../../text/serif'
import LargeShowsList from './large_list'
import SmallShowsList from './small_list'

class Shows extends React.Component {
  render() {
    return (
      <View style={styles.container}>

        <SerifText style={styles.title}>Current & Upcoming Shows</SerifText>
        <LargeShowsList shows={this.props.artist.current_shows} />
        <LargeShowsList shows={this.props.artist.upcoming_shows} />

        <View style={{height: 1, backgroundColor: 'grey', flex: 3, marginTop: 40, marginBottom: 20}}></View>

        <View style={{marginBottom: 50}}>
          <SerifText style={styles.title}>Past Shows</SerifText>
          <SmallShowsList shows={this.props.artist.past_shows} style={{marginBottom: 50}} />
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'flex-start',
  },
  title: {
    fontSize: 20,
    textAlign: 'left',
    marginLeft: -3,
  },
  listView: {
     paddingBottom: 40,
  },
});

export default Relay.createContainer(Shows, {
  fragments: {
    artist: () => Relay.QL`
      fragment on Artist {
        current_shows: partner_shows(status: "running") {
          ${LargeShowsList.getFragment('shows')}
        }
        upcoming_shows: partner_shows(status: "upcoming") {
          ${LargeShowsList.getFragment('shows')}
        }
        past_shows: partner_shows(status: "closed") {
          ${SmallShowsList.getFragment('shows')}
        }
      }
    `,
  }
});<|endoftext|>


<commit_before>import { GET_PRODUCT_ANALYSIS, GET_CATEGORY_COMPARISON, SHOW_PRODUCT_DETAILS } from './FoodProductActions';

const foodProductInitialState = {
  upc: '',
  productAnalysis: {},
  categoryComparison: '',
  productDetails: {}
};

const foodProductReducer = (state = foodProductInitialState, action) => {
  switch (action.type) {
    case GET_PRODUCT_ANALYSIS:
      return Object.assign({}, state, {
        productAnalysis: action.productAnalysis
      });
    case GET_CATEGORY_COMPARISON: {
      let category;
      if (state.categoryComparison === action.categoryComparison) {
        category = '';
      } else {
        category = action.categoryComparison;
      }
      return Object.assign({}, state, {
        categoryComparison: category
      });
    }
    case SHOW_PRODUCT_DETAILS: {
      let productDetails;
      if (state.productDetails.UPC === action.productDetails.UPC) {
        productDetails = {};
      } else {
        productDetails = action.productDetails;
      }
      return Object.assign({}, state, {
        productDetails
      });
    }
    default:
      return state;
  }
};

export default foodProductReducer;
<commit_msg>use dropdown for category selection<commit_after>import { GET_PRODUCT_ANALYSIS, GET_CATEGORY_COMPARISON, SHOW_PRODUCT_DETAILS } from './FoodProductActions';

const foodProductInitialState = {
  upc: '',
  productAnalysis: {},
  categoryComparison: '',
  productDetails: {}
};

const foodProductReducer = (state = foodProductInitialState, action) => {
  switch (action.type) {
    case GET_PRODUCT_ANALYSIS:
      return Object.assign({}, state, {
        productAnalysis: action.productAnalysis
      });
    case GET_CATEGORY_COMPARISON:
      return Object.assign({}, state, {
        categoryComparison: action.categoryComparison,
        productDetails: {}
      });
    case SHOW_PRODUCT_DETAILS: {
      let productDetails;
      if (state.productDetails.UPC === action.productDetails.UPC) {
        productDetails = {};
      } else {
        productDetails = action.productDetails;
      }
      return Object.assign({}, state, {
        productDetails
      });
    }
    default:
      return state;
  }
};

export default foodProductReducer;
<|endoftext|>


<commit_before>process.on('uncaughtException', function(e){
  process.send({error: e.stack});
});

const constants = require('../../constants');
const Events = require('./eventsWrapper');

class ProcessWrapper {

  /**
   * Class from which process extend. Should not be instantiated alone.
   * Manages the log interception so that all console.* get sent back to the parent process
   * Also creates an Events instance. To use it, just do `this.events.[on|request]`
   *
   * @param {Options}     options    pingParent: true by default
   */
  constructor(options = {}) {
    this.options = Object.assign({pingParent: true}, options);
    this.interceptLogs();
    this.env = _options ? _options.env : 'development';
    this.events = new Events();
    if(this.options.pingParent) {
      this.pingParent();
    }
  }

  // Ping parent to see if it is still alive. Otherwise, let's die
  pingParent() {
    const self = this;
    self.retries = 0;
    function error() {
      if (self.retries > 2) {
          self.kill();
          process.exit();
      }
      self.retries++;
    }
    setInterval(() => {
      try {
        let result = self.send({action: 'ping'});
        if (!result) {
          return error();
        }
        self.retries = 0;
      } catch (e) {
        error();
      }
    }, 500);
  }

  interceptLogs() {
    const context = {};
    context.console = console;

    context.console.log = this._log.bind(this, 'log');
    context.console.warn = this._log.bind(this, 'warn');
    context.console.error = this._log.bind(this, 'error');
    context.console.info = this._log.bind(this, 'info');
    context.console.debug = this._log.bind(this, 'debug');
    context.console.trace = this._log.bind(this, 'trace');
    context.console.dir = this._log.bind(this, 'dir');
  }

  _log(type, ...messages) {
    const isHardSource = messages.some(message => {
      return (typeof message === 'string' && message.indexOf('hardsource') > -1);
    });
    if (isHardSource) {
      return;
    }
    this.send({result: constants.process.log, message: messages, type});
  }

  send() {
    if (!process.connected) {
      return false;
    }
    return process.send(...arguments);
  }

  kill() {
    // Should be implemented by derived class
    console.log('Process killed');
  }
}

process.on('exit', () => {
  process.exit(0);
});

module.exports = ProcessWrapper;
<commit_msg>more conservative: only modify webpack's subclass of ProcessWrapper<commit_after>process.on('uncaughtException', function(e){
  process.send({error: e.stack});
});

const constants = require('../../constants');
const Events = require('./eventsWrapper');

class ProcessWrapper {

  /**
   * Class from which process extend. Should not be instantiated alone.
   * Manages the log interception so that all console.* get sent back to the parent process
   * Also creates an Events instance. To use it, just do `this.events.[on|request]`
   *
   * @param {Options}     options    pingParent: true by default
   */
  constructor(options = {}) {
    this.options = Object.assign({pingParent: true}, options);
    this.interceptLogs();
    this.events = new Events();
    if(this.options.pingParent) {
      this.pingParent();
    }
  }

  // Ping parent to see if it is still alive. Otherwise, let's die
  pingParent() {
    const self = this;
    self.retries = 0;
    function error() {
      if (self.retries > 2) {
          self.kill();
          process.exit();
      }
      self.retries++;
    }
    setInterval(() => {
      try {
        let result = self.send({action: 'ping'});
        if (!result) {
          return error();
        }
        self.retries = 0;
      } catch (e) {
        error();
      }
    }, 500);
  }

  interceptLogs() {
    const context = {};
    context.console = console;

    context.console.log = this._log.bind(this, 'log');
    context.console.warn = this._log.bind(this, 'warn');
    context.console.error = this._log.bind(this, 'error');
    context.console.info = this._log.bind(this, 'info');
    context.console.debug = this._log.bind(this, 'debug');
    context.console.trace = this._log.bind(this, 'trace');
    context.console.dir = this._log.bind(this, 'dir');
  }

  _log(type, ...messages) {
    const isHardSource = messages.some(message => {
      return (typeof message === 'string' && message.indexOf('hardsource') > -1);
    });
    if (isHardSource) {
      return;
    }
    this.send({result: constants.process.log, message: messages, type});
  }

  send() {
    if (!process.connected) {
      return false;
    }
    return process.send(...arguments);
  }

  kill() {
    // Should be implemented by derived class
    console.log('Process killed');
  }
}

process.on('exit', () => {
  process.exit(0);
});

module.exports = ProcessWrapper;
<|endoftext|>


<commit_before>const Promise = require('promise');

// Constants
const possibleResponses = require('../../config/options');

// Models
const Game = require('../models/game');
const GameResponse = require('../models/game-response');

module.exports = function(slackClient, slackWebClient) {
  const dataHelpers = require('../data/helpers')(slackWebClient);
  const messanger = require('./messanger')(slackClient, slackWebClient);
  const startGameValidator = require('../validators/start-game');
  const restartGameValidator = require('../validators/restart-game');
  const responseValidator = require('../validators/response');
  const gameRules = require('./game-rules');

  return {
    channelMessageToSlackbot(message) {
      const firstWord = message.text.split(' ')[0];
      const slackBotId = slackClient.activeUserId;
      console.log(slackBotId);
      return (firstWord === process.env.SLACK_BOT_NAME) ||
        (firstWord === `<@${slackBotId}>:`) ||
        (firstWord === `<@${slackBotId}>`);
    },

    privateMessageToSlackbot(message) {
      dataHelpers.fetchUserDirectMessageId(message).then((directMessageId) => {
        if (message.channel === directMessageId) this._acceptResponse(message);
      });
    },

    startGame(message) {
      if (restartGameValidator(message, messanger)) {
        return this._restartGame(message);
      }

      const users = startGameValidator(message, messanger);
      if (!users.length) return;

      const game = new Game({ playerIds: users, channelId: message.channel });
      game.save(() => {
        messanger.notifyAboutStartGame(message, game);
      });
    },

    _acceptResponse(message) {
      this._extractPossibleGameObject(message).then((game) => {
        if (responseValidator(message, game, messanger)) return this._createResponse(message, game);
      }).then((game) => {
        this._checkGameStatus(game);
      }).catch((err) => {
        if (err !== 'Flow escape') console.log(err);
      });
    },

    _extractPossibleGameObject(message) {
      var gameId = message.text.split(' ')[0];
      if (gameId.match(/\*[a-zA-Z0-9]*\*/)) {
        gameId = gameId.slice(1, gameId.length - 1);
      }

      return new Promise((resolve, reject) => {
        Game.findOne({ '_id': gameId }, (error, game) => {
          if (game) {
            resolve(game);
          } else {
            Game.find({ playerIds: message.user })
              .sort({ createdAt: -1 })
              .limit(1).lean().exec((err, results) => {
                const response = [];
                response.push({ content: 'No such game in database :crying_cat_face:', color: 'danger' });
                if (results.length) {
                  response.push({ content: `Maybe a typo? Your last game was *${results[0]._id}*`, color: 'warning' });
                }
                messanger.respondWith(response, message.channel);
              });
            reject('Flow escape');
          }
        });
      });
    },

    _createResponse(message, game) {
      return new Promise((resolve, reject) => {
        GameResponse.findOne({ 'gameId': game._id, 'userId': message.user }, (error, gameResponse) => {
          if (gameResponse) {
            messanger.respondWith([{ content: 'You already responded to this game! :troll:', color: 'danger' }], message.channel);
            reject('Flow escape');
          } else {
            resolve();
          }
        });
      }).then(() => {
        return new Promise((resolve, reject) => {
          const gameResponseObject = new GameResponse({
            gameId: game._id,
            userId: message.user,
            response: message.text.split(' ')[1],
          });
          gameResponseObject.save(() => {
            messanger.respondWith([{ content: '*Acknowledgement!* Wish you luck! :ok_hand:', color: 'good' }], message.channel);
            messanger.notifyAboutResponse(game, gameResponseObject);
            resolve(game);
          });
        });
      });
    },

    _checkGameStatus(game) {
      GameResponse.find({ 'gameId': game._id }).lean().exec((err, results) => {
        if (game.playerIds.length !== results.length) return;

        const gameCounter = gameRules.processToGameCounter(results);
        if (gameRules.drawByAllPossibilites(gameCounter)) {
          messanger.notifyAboutDraw(game);
        } else if (gameRules.drawByOnlyOnePossibility(gameCounter)) {
          messanger.notifyAboutDraw(game);
        } else {
          messanger.notifyAboutWinners(game, gameRules.giveWinners(gameCounter, results));
        }
        setTimeout(() => {
          messanger.notifyAboutResponses(game, results);
        }, 500);
      });
    },

    _restartGame(message) {
      Game.find({ playerIds: message.user })
        .sort({ createdAt: -1 })
        .limit(1).lean().exec((err, results) => {
          if (results.length) {
            const game = new Game({
              playerIds: results[0].playerIds,
              channelId: results[0].channelId
            });

            game.save(() => {
              messanger.notifyAboutStartGame(message, game);
            });
          } else {
            messanger.respondWith([{ content: `Holy moly, you have not played yet! :rocket:`, color: 'warning' }], message.channel);
          }
        });
    },
  };
};
<commit_msg>fix bug with responding to not yours game<commit_after>const Promise = require('promise');

// Constants
const possibleResponses = require('../../config/options');

// Models
const Game = require('../models/game');
const GameResponse = require('../models/game-response');

module.exports = function(slackClient, slackWebClient) {
  const dataHelpers = require('../data/helpers')(slackWebClient);
  const messanger = require('./messanger')(slackClient, slackWebClient);
  const startGameValidator = require('../validators/start-game');
  const restartGameValidator = require('../validators/restart-game');
  const responseValidator = require('../validators/response');
  const gameRules = require('./game-rules');

  return {
    channelMessageToSlackbot(message) {
      const firstWord = message.text.split(' ')[0];
      const slackBotId = slackClient.activeUserId;
      return (firstWord === process.env.SLACK_BOT_NAME) ||
        (firstWord === `<@${slackBotId}>:`) ||
        (firstWord === `<@${slackBotId}>`);
    },

    privateMessageToSlackbot(message) {
      dataHelpers.fetchUserDirectMessageId(message).then((directMessageId) => {
        if (message.channel === directMessageId) this._acceptResponse(message);
      });
    },

    startGame(message) {
      if (restartGameValidator(message, messanger)) {
        return this._restartGame(message);
      }

      const users = startGameValidator(message, messanger, slackClient.activeUserId);
      if (!users.length) return;

      const game = new Game({ playerIds: users, channelId: message.channel });
      game.save(() => {
        messanger.notifyAboutStartGame(message, game);
      });
    },

    _acceptResponse(message) {
      this._extractPossibleGameObject(message).then((game) => {
        if (responseValidator(message, game, messanger)) return this._createResponse(message, game);
      }).then((game) => {
        this._checkGameStatus(game);
      }).catch((err) => {
        if (err !== 'Flow escape') console.log(err);
      });
    },

    _extractPossibleGameObject(message) {
      var gameId = message.text.split(' ')[0];
      if (gameId.match(/\*[a-zA-Z0-9]*\*/)) {
        gameId = gameId.slice(1, gameId.length - 1);
      }

      return new Promise((resolve, reject) => {
        Game.findOne({ '_id': gameId }, (error, game) => {
          if (game) {
            if (game.playerIds.indexOf(message.user) > -1) {
              resolve(game);
            } else {
              const response = [{ content: 'It\'s not your game, you :troll:', color: 'danger' }];
              messanger.respondWith(response, message.channel);
              reject('Flow escape');
            }
          } else {
            Game.find({ playerIds: message.user })
              .sort({ createdAt: -1 })
              .limit(1).lean().exec((err, results) => {
                const response = [];
                response.push({ content: 'No such game in database :crying_cat_face:', color: 'danger' });
                if (results.length) {
                  response.push({ content: `Maybe a typo? Your last game was *${results[0]._id}*`, color: 'warning' });
                }
                messanger.respondWith(response, message.channel);
              });
            reject('Flow escape');
          }
        });
      });
    },

    _createResponse(message, game) {
      return new Promise((resolve, reject) => {
        GameResponse.findOne({ 'gameId': game._id, 'userId': message.user }, (error, gameResponse) => {
          if (gameResponse) {
            messanger.respondWith([{ content: 'You already responded to this game! :troll:', color: 'danger' }], message.channel);
            reject('Flow escape');
          } else {
            resolve();
          }
        });
      }).then(() => {
        return new Promise((resolve, reject) => {
          const gameResponseObject = new GameResponse({
            gameId: game._id,
            userId: message.user,
            response: message.text.split(' ')[1],
          });
          gameResponseObject.save(() => {
            messanger.respondWith([{ content: '*Acknowledgement!* Wish you luck! :ok_hand:', color: 'good' }], message.channel);
            messanger.notifyAboutResponse(game, gameResponseObject);
            resolve(game);
          });
        });
      });
    },

    _checkGameStatus(game) {
      GameResponse.find({ 'gameId': game._id }).lean().exec((err, results) => {
        if (game.playerIds.length !== results.length) return;

        const gameCounter = gameRules.processToGameCounter(results);
        if (gameRules.drawByAllPossibilites(gameCounter)) {
          messanger.notifyAboutDraw(game);
        } else if (gameRules.drawByOnlyOnePossibility(gameCounter)) {
          messanger.notifyAboutDraw(game);
        } else {
          messanger.notifyAboutWinners(game, gameRules.giveWinners(gameCounter, results));
        }
        setTimeout(() => {
          messanger.notifyAboutResponses(game, results);
        }, 500);
      });
    },

    _restartGame(message) {
      Game.find({ playerIds: message.user })
        .sort({ createdAt: -1 })
        .limit(1).lean().exec((err, results) => {
          if (results.length) {
            const game = new Game({
              playerIds: results[0].playerIds,
              channelId: results[0].channelId
            });

            game.save(() => {
              messanger.notifyAboutStartGame(message, game);
            });
          } else {
            messanger.respondWith([{ content: `Holy moly, you have not played yet! :rocket:`, color: 'warning' }], message.channel);
          }
        });
    },
  };
};
<|endoftext|>


<commit_before>//
// All parameters are required.
// The delegate must implement the process method.
//
function PPFileManager(delegate, textInputId, saveLinkId) {
    if (delegate == null || textInputId == null || saveLinkId == null) {
      throw new Error("PPFileManager missing required parameter.");
    }

  if ( ! PPUtils.objectImplementsMethod( delegate, "process") ) {
     throw new Error("Process function is not implemented by delegate.");
  }

  this.delegate = delegate;
  this.textInputId = textInputId;
  this.saveLinkId = saveLinkId;

   var self = this;
   // Bind to html elements when document is loaded.
   PPUtils.bind("load", window, function () {self.bind();} );
}

PPFileManager.prototype.bind = function () {
   //  onclick="PPFileManager.createFile(this);"
  var self = this;
  PPUtils.bind("click", $(this.saveLinkId), function () {self.createFile();} );
}

PPFileManager.prototype.createFile = function () {
  var a = $(this.saveLinkId);
  var filename = $(this.textInputId).value;

  // Escape encodes % but does not encode * @ etc
  // TODO test with those characters...
  // TODO -- relies on global variable.
  var data = escape(JSON.stringify(theApp.tournament));

  a.href = "data:application/json;charset=utf-8," + data;
  a.download = filename;
}

PPFileManager.errorHandler = function (evt) {
    switch(evt.target.error.code) {
      case evt.target.error.NOT_FOUND_ERR:
        PPUtils.log('File Not Found!');
        break;
      case evt.target.error.NOT_READABLE_ERR:
        PPUtils.log('File is not readable');
        break;
      case evt.target.error.SECURITY_ERR:
        // This will occur when loading a file and using a file:// URL.
        // Run a local http server when testing load functionality.
        //
        // python -m SimpleHTTPServer
        //
        // or run chrome with --allow-file-access-from-files
        //
        // Reference: http://stackoverflow.com/questions/2704929/uncaught-error-security-err-dom-exception-18
        PPUtils.log('A Security Error occurred');

        break;
      case evt.target.error.ABORT_ERR:
        break; // no op
      default:
        PPUtils.log('An error occurred reading this file. Error code = ' + evt.target.error.code);
    };
  }

PPFileManager.load = function(e) { console.log("HERE"); }

PPFileManager.prototype.handleFileSelect = function (evt) {
  var files = evt.target.files; // FileList object
  var delegate = this.delegate;
  var f = files[0];
  var reader = new FileReader();

  reader.onerror = PPFileManager.errorHandler;
  reader.onprogress = function(e) { PPUtils.log('Progress!!'); };
  reader.onabort = function(e) { PPUtils.log('File read cancelled'); };
  reader.onload = function(e) {   delegate.process(e.target.result); };

  reader.readAsText(f);
}

<commit_msg>remove progress println<commit_after>//
// All parameters are required.
// The delegate must implement the process method.
//
function PPFileManager(delegate, textInputId, saveLinkId) {
    if (delegate == null || textInputId == null || saveLinkId == null) {
      throw new Error("PPFileManager missing required parameter.");
    }

  if ( ! PPUtils.objectImplementsMethod( delegate, "process") ) {
     throw new Error("Process function is not implemented by delegate.");
  }

  this.delegate = delegate;
  this.textInputId = textInputId;
  this.saveLinkId = saveLinkId;

   var self = this;
   // Bind to html elements when document is loaded.
   PPUtils.bind("load", window, function () {self.bind();} );
}

PPFileManager.prototype.bind = function () {
  var self = this;
  PPUtils.bind("click", $(this.saveLinkId), function () {self.createFile();} );
}

PPFileManager.prototype.createFile = function () {
  var a = $(this.saveLinkId);
  var filename = $(this.textInputId).value;

  // Escape encodes % but does not encode * @ etc
  // TODO test with those characters...
  // TODO -- relies on global variable. get from delegate.
  var data = escape(JSON.stringify(theApp.tournament));

  a.href = "data:application/json;charset=utf-8," + data;
  a.download = filename;
}

PPFileManager.errorHandler = function (evt) {
    switch(evt.target.error.code) {
      case evt.target.error.NOT_FOUND_ERR:
        PPUtils.log('File Not Found!');
        break;
      case evt.target.error.NOT_READABLE_ERR:
        PPUtils.log('File is not readable');
        break;
      case evt.target.error.SECURITY_ERR:
        // This will occur when loading a file and using a file:// URL.
        // Run a local http server when testing load functionality.
        //
        // python -m SimpleHTTPServer
        //
        // or run chrome with --allow-file-access-from-files
        //
        // Reference: http://stackoverflow.com/questions/2704929/uncaught-error-security-err-dom-exception-18
        PPUtils.log('A Security Error occurred');

        break;
      case evt.target.error.ABORT_ERR:
        break; // no op
      default:
        PPUtils.log('An error occurred reading this file. Error code = ' + evt.target.error.code);
    };
  }

PPFileManager.load = function(e) { console.log("HERE"); }

PPFileManager.prototype.handleFileSelect = function (evt) {
  var files = evt.target.files; // FileList object
  var delegate = this.delegate;
  var f = files[0];
  var reader = new FileReader();

  reader.onerror = PPFileManager.errorHandler;
  reader.onprogress = function(e) { };
  reader.onabort = function(e) { PPUtils.log('File read cancelled'); };
  reader.onload = function(e) {   delegate.process(e.target.result); };

  reader.readAsText(f);
}

<|endoftext|>