<commit_before>(function(win) {

    var Game = new Vue({
        el: '#mainVue',
        data: {
            tileDimension: 124,
            tilePosition: 121,
            startTiles: 2,
            tiles: [],
            grid: [],
            conf: {
                score: 0,
                size: 5,
                bestScore: gameStorage.fetch('vue2048-config').bestScore || 0
            }
        },

        created: function() {
            this.getWindowSize();
        },

        ready: function() {
            var data = gameStorage.fetch('vue2048');

            if (data.length === 0) {
                this.init();
            } else {
                this.continueGame(data);
            }

            this.$watch('tiles', function(tiles) {
                gameStorage.save('vue2048', tiles);
            });

            this.$watch('conf', function(conf) {
                gameStorage.save('vue2048-config', conf);
            });

        },
        //Can go to templates
        computed: {
            findDimension: function() {
                return this.grid.length * this.tileDimension;
            },

            // selected: function(el){
            //     debugger;

            //    return 'selected';
            // },

            allDone: {
                $get: function() {
                    return this.remaining === 0;
                },
                $set: function(value) {
                    this.todos.forEach(function(todo) {
                        todo.completed = value;
                    });
                }
            }
        },

        components: {
            grid: {
                template: '
\

\

',
                replace: false
            },

            tile: {
                //Better to use template, todo delete tile position
                template: '
\

{{value}}
\

',

                replace: true,

                computed: {
                    calculateStyle: function() {
                        var tilePosition = this.$parent.tilePosition;
                        var x = this.x * tilePosition;
                        var y = this.y * tilePosition;

                        return '-webkit-transform: translate(' + x + 'px, ' + y + 'px);' +
                            '-moz-transform: translate(' + x + 'px, ' + y + 'px);' +
                            'transform: translate(' + x + 'px, ' + y + 'px);';
                    }
                }
            }
        },

        methods: {

            init: function() {

                var startTiles = this.startTiles;

                this.initArrayGrid(this.conf.size);
                this.clearMessage();

                this.tiles = [];
                this.updateScore(0);

                for (var i = 0; i < startTiles; i++) {
                    this.addRandomTile();
                }
            },

            continueGame: function(data) {
                var arr,
                    conf;

                this.conf = conf = gameStorage.fetch('vue2048-config');
                this.initArrayGrid(conf.size);
                arr = this.grid;
                this.tiles = data;

                data.forEach(function(item) {
                    arr[item.x][item.y] = 1;
                });
            },

            gameOver: function() {
                this.message();
            },

            initArrayGrid: function(size) {
                var arr = [];

                for (var x = 0; x < size; x++) {
                    arr[x] = [];
                    for (var y = 0; y < size; y++) {
                        arr[x][y] = 0;
                    }
                }

                this.grid = arr;
            },

            changesTilesSize: function(e) {
                this.conf.size = parseInt(e.target.value);

                this.init();
            },

            addRandomTile: function() {

                if (this.availableCells().length > 0) {
                    var value = Math.random() < 0.9 ? 2 : 4,
                        randomCell = this.randomAvailableCell();

                    this.tiles.$set(this.tiles.length, {
                        x: randomCell.x,
                        y: randomCell.y,
                        value: value
                    });

                    this.grid[randomCell.x][randomCell.y] = 1;

                }

            },

            // Find the first available random position
            randomAvailableCell: function() {
                var cells = this.availableCells();

                if (cells.length) {
                    return cells[Math.floor(Math.random() * cells.length)];
                }
            },

            availableCells: function() {
                var cells = [],
                    size = this.conf.size,
                    grid = this.grid;

                for (var x = 0; x < size; x++) {
                    for (var y = 0; y < size; y++) {
                        if (!grid[x][y]) {
                            cells.push({
                                x: x,
                                y: y
                            });
                        }
                    }
                }

                return cells;
            },

            getVector: function(direction) {
                var map = {
                    0: {
                        x: 0,
                        y: -1
                    }, // Up
                    1: {
                        x: 1,
                        y: 0
                    }, // Right
                    2: {
                        x: 0,
                        y: 1
                    }, // Down
                    3: {
                        x: -1,
                        y: 0
                    } // Left
                };

                return map[direction];
            },

            findFarthestPosition: function(cell, vector) {
                var previous;

                do {
                    previous = cell;
                    cell = {
                        x: previous.x + vector.x,
                        y: previous.y + vector.y
                    };

                } while (this.withinBounds(cell) && !this.grid[cell.x][cell.y]);

                return {
                    farthest: previous,
                    next: cell // Used to check if a merge is required
                };
            },

            findTile: function(position) {

                if (position.x === -1 || position.y === -1)
                    return null;
                else {
                    var tiles = this.tiles;

                    return tiles.filter(function(item, index) {
                        return item.x === position.x && item.y === position.y;
                    })[0];
                }

            },

            moveTile: function(tile, position) {

                if (tile.x === position.x && tile.y === position.y) {
                    return false;
                } else {
                    this.grid[tile.x][tile.y] = 0;
                    this.grid[position.x][position.y] = 1;

                    tile.x = position.x;
                    tile.y = position.y;

                    return true;
                }

            },

            mergeTiles: function(curr, next, position) {

                next.value = next.value * 2;
                var tiles = this.tiles;

                //Better Way to find index of data
                for (var key in tiles) {
                    if (tiles[key].x === curr.x && tiles[key].y === curr.y) {
                        break;
                    }
                }

                this.grid[curr.x][curr.y] = 0;
                this.tiles.$remove(parseInt(key));

                // Update the score
                this.updateScore(next.value);
            },

            move: function(direction) {

                var vector = this.getVector(direction);
                var traversals = this.buildTraversals(vector);
                var moved = false;
                var self = this;
                var grid = self.grid;
                var positions;
                var next;
                var tile;

                traversals.x.forEach(function(x) {
                    traversals.y.forEach(function(y) {
                        // console.log(x, y);
                        if (grid[x][y]) {
                            var tile = self.findTile({
                                x: x,
                                y: y
                            });
                            var positions = self.findFarthestPosition({
                                x: x,
                                y: y
                            }, vector);
                            //console.log(positions);
                            var next = self.findTile(positions.next);

                            //console.log(next);
                            // Only one merger per row traversal?
                            if (next && next.value === tile.value) {

                                self.mergeTiles(tile, next, positions.next);

                            } else {
                                moved = self.moveTile(tile, positions.farthest);
                            }

                        }

                    });
                });

                if (moved) {
                    this.addRandomTile();

                    if (grid.toString().indexOf('0') === -1) {
                        if (!this.tileMatchesAvailable()) {
                            this.gameOver();
                        }

                    }

                }

            },

            tileMatchesAvailable: function() {

                var size = this.conf.size;
                var grid = this.grid;
                var tiles = this.tiles;
                var tile;

                for (var x = 0; x < size; x++) {
                    for (var y = 0; y < size; y++) {
                        tile = grid[x][y];

                        if (tile) {
                            for (var direction = 0; direction < 4; direction++) {
                                var vector = this.getVector(direction);
                                var cell = {
                                    x: x + vector.x,
                                    y: y + vector.y
                                },
                                    other;

                                if (cell.x >= 0 && cell.x < size && cell.y >= 0 && cell.y < size) {
                                    other = grid[cell.x][cell.y];
                                } else {
                                    continue;
                                }

                                if (other && this.findTile(cell).value === this.findTile({
                                    x: x,
                                    y: y
                                }).value) {
                                    return true; // These two tiles can be merged
                                }
                            }
                        }
                    }
                }

                return false;
            },

            withinBounds: function(position) {
                var size = this.conf.size;

                return position.x >= 0 && position.x < size && position.y >= 0 && position.y < size;
            },

            buildTraversals: function(vector) {
                var traversals = {
                    x: [],
                    y: []
                },
                    size = this.conf.size;

                for (var pos = 0; pos < size; pos++) {
                    traversals.x.push(pos);
                    traversals.y.push(pos);
                }

                // Always traverse from the farthest cell in the chosen direction
                if (vector.x === 1) traversals.x = traversals.x.reverse();
                if (vector.y === 1) traversals.y = traversals.y.reverse();

                return traversals;
            },

            updateScore: function(score) {
                var scoreContainer = document.getElementsByClassName('score-container')[0];

                //On init
                if (score === 0) {
                    this.conf.score = 0;
                    //gameStorage.save('score', 0);

                    return false;
                }

                this.conf.score += score;
                //gameStorage.save('score', this.score);

                if (this.conf.score > this.conf.bestScore) {
                    this.conf.bestScore = this.conf.score;
                    //gameStorage.save('bestScore', this.bestScore);
                }

                // The mighty 2048 tile
                if (score === 2048)
                    this.message(true);

                var addition = document.createElement("div");
                addition.classList.add("score-addition");
                addition.textContent = "+" + score;
                scoreContainer.appendChild(addition);

            },

            message: function(won) {
                var type = won ? "game-won" : "game-over";
                var message = won ? "You win!" : "Game over!";
                var messageContainer = document.querySelector(".game-message");

                messageContainer.classList.add(type);
                messageContainer.getElementsByTagName("p")[0].textContent = message;
            },

            clearMessage: function() {
                messageContainer = document.querySelector(".game-message");

                messageContainer.classList.remove("game-won");
                messageContainer.classList.remove("game-over");
            },

            clearContainer: function(container) {
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
            },

            getWindowSize: function() {
                var w = window,
                    d = document,
                    e = d.documentElement,
                    g = d.getElementsByTagName('body')[0],
                    x = w.innerWidth || e.clientWidth || g.clientWidth,
                    y = w.innerHeight || e.clientHeight || g.clientHeight;

                if (x < 520) {
                    this.tileDimension = 69.5;
                    this.tilePosition = 67;
                } else {
                    this.tileDimension = 124;
                    this.tilePosition = 121;

                }
            }

        }
    });

    var Keys = new KeyboardInputManager();

    Keys.on('move', function(direction) {
        Game.move(direction);
    });

    win.onresize = function(event) {
        Game.getWindowSize();
    };

})(window);<commit_msg>change default tiles number to 4<commit_after>(function(win) {

    var Game = new Vue({
        el: '#mainVue',
        data: {
            tileDimension: 124,
            tilePosition: 121,
            startTiles: 2,
            tiles: [],
            grid: [],
            conf: {
                score: 0,
                size: 4,
                bestScore: gameStorage.fetch('vue2048-config').bestScore || 0
            }
        },

        created: function() {
            this.getWindowSize();
        },

        ready: function() {
            var data = gameStorage.fetch('vue2048');

            if (data.length === 0) {
                this.init();
            } else {
                this.continueGame(data);
            }

            this.$watch('tiles', function(tiles) {
                gameStorage.save('vue2048', tiles);
            });

            this.$watch('conf', function(conf) {
                gameStorage.save('vue2048-config', conf);
            });

        },
        //Can go to templates
        computed: {
            findDimension: function() {
                return this.grid.length * this.tileDimension;
            },

            // selected: function(el){
            //     debugger;

            //    return 'selected';
            // },

            allDone: {
                $get: function() {
                    return this.remaining === 0;
                },
                $set: function(value) {
                    this.todos.forEach(function(todo) {
                        todo.completed = value;
                    });
                }
            }
        },

        components: {
            grid: {
                template: '
\

\

',
                replace: false
            },

            tile: {
                //Better to use template, todo delete tile position
                template: '
\

{{value}}
\

',

                replace: true,

                computed: {
                    calculateStyle: function() {
                        var tilePosition = this.$parent.tilePosition;
                        var x = this.x * tilePosition;
                        var y = this.y * tilePosition;

                        return '-webkit-transform: translate(' + x + 'px, ' + y + 'px);' +
                            '-moz-transform: translate(' + x + 'px, ' + y + 'px);' +
                            'transform: translate(' + x + 'px, ' + y + 'px);';
                    }
                }
            }
        },

        methods: {

            init: function() {

                var startTiles = this.startTiles;

                this.initArrayGrid(this.conf.size);
                this.clearMessage();

                this.tiles = [];
                this.updateScore(0);

                for (var i = 0; i < startTiles; i++) {
                    this.addRandomTile();
                }
            },

            continueGame: function(data) {
                var arr,
                    conf;

                this.conf = conf = gameStorage.fetch('vue2048-config');
                this.initArrayGrid(conf.size);
                arr = this.grid;
                this.tiles = data;

                data.forEach(function(item) {
                    arr[item.x][item.y] = 1;
                });
            },

            gameOver: function() {
                this.message();
            },

            initArrayGrid: function(size) {
                var arr = [];

                for (var x = 0; x < size; x++) {
                    arr[x] = [];
                    for (var y = 0; y < size; y++) {
                        arr[x][y] = 0;
                    }
                }

                this.grid = arr;
            },

            changesTilesSize: function(e) {
                this.conf.size = parseInt(e.target.value);

                this.init();
            },

            addRandomTile: function() {

                if (this.availableCells().length > 0) {
                    var value = Math.random() < 0.9 ? 2 : 4,
                        randomCell = this.randomAvailableCell();

                    this.tiles.$set(this.tiles.length, {
                        x: randomCell.x,
                        y: randomCell.y,
                        value: value
                    });

                    this.grid[randomCell.x][randomCell.y] = 1;

                }

            },

            // Find the first available random position
            randomAvailableCell: function() {
                var cells = this.availableCells();

                if (cells.length) {
                    return cells[Math.floor(Math.random() * cells.length)];
                }
            },

            availableCells: function() {
                var cells = [],
                    size = this.conf.size,
                    grid = this.grid;

                for (var x = 0; x < size; x++) {
                    for (var y = 0; y < size; y++) {
                        if (!grid[x][y]) {
                            cells.push({
                                x: x,
                                y: y
                            });
                        }
                    }
                }

                return cells;
            },

            getVector: function(direction) {
                var map = {
                    0: {
                        x: 0,
                        y: -1
                    }, // Up
                    1: {
                        x: 1,
                        y: 0
                    }, // Right
                    2: {
                        x: 0,
                        y: 1
                    }, // Down
                    3: {
                        x: -1,
                        y: 0
                    } // Left
                };

                return map[direction];
            },

            findFarthestPosition: function(cell, vector) {
                var previous;

                do {
                    previous = cell;
                    cell = {
                        x: previous.x + vector.x,
                        y: previous.y + vector.y
                    };

                } while (this.withinBounds(cell) && !this.grid[cell.x][cell.y]);

                return {
                    farthest: previous,
                    next: cell // Used to check if a merge is required
                };
            },

            findTile: function(position) {

                if (position.x === -1 || position.y === -1)
                    return null;
                else {
                    var tiles = this.tiles;

                    return tiles.filter(function(item, index) {
                        return item.x === position.x && item.y === position.y;
                    })[0];
                }

            },

            moveTile: function(tile, position) {

                if (tile.x === position.x && tile.y === position.y) {
                    return false;
                } else {
                    this.grid[tile.x][tile.y] = 0;
                    this.grid[position.x][position.y] = 1;

                    tile.x = position.x;
                    tile.y = position.y;

                    return true;
                }

            },

            mergeTiles: function(curr, next, position) {

                next.value = next.value * 2;
                var tiles = this.tiles;

                //Better Way to find index of data
                for (var key in tiles) {
                    if (tiles[key].x === curr.x && tiles[key].y === curr.y) {
                        break;
                    }
                }

                this.grid[curr.x][curr.y] = 0;
                this.tiles.$remove(parseInt(key));

                // Update the score
                this.updateScore(next.value);
            },

            move: function(direction) {

                var vector = this.getVector(direction);
                var traversals = this.buildTraversals(vector);
                var moved = false;
                var self = this;
                var grid = self.grid;
                var positions;
                var next;
                var tile;

                traversals.x.forEach(function(x) {
                    traversals.y.forEach(function(y) {
                        // console.log(x, y);
                        if (grid[x][y]) {
                            var tile = self.findTile({
                                x: x,
                                y: y
                            });
                            var positions = self.findFarthestPosition({
                                x: x,
                                y: y
                            }, vector);
                            //console.log(positions);
                            var next = self.findTile(positions.next);

                            //console.log(next);
                            // Only one merger per row traversal?
                            if (next && next.value === tile.value) {

                                self.mergeTiles(tile, next, positions.next);

                            } else {
                                moved = self.moveTile(tile, positions.farthest);
                            }

                        }

                    });
                });

                if (moved) {
                    this.addRandomTile();

                    if (grid.toString().indexOf('0') === -1) {
                        if (!this.tileMatchesAvailable()) {
                            this.gameOver();
                        }

                    }

                }

            },

            tileMatchesAvailable: function() {

                var size = this.conf.size;
                var grid = this.grid;
                var tiles = this.tiles;
                var tile;

                for (var x = 0; x < size; x++) {
                    for (var y = 0; y < size; y++) {
                        tile = grid[x][y];

                        if (tile) {
                            for (var direction = 0; direction < 4; direction++) {
                                var vector = this.getVector(direction);
                                var cell = {
                                    x: x + vector.x,
                                    y: y + vector.y
                                },
                                    other;

                                if (cell.x >= 0 && cell.x < size && cell.y >= 0 && cell.y < size) {
                                    other = grid[cell.x][cell.y];
                                } else {
                                    continue;
                                }

                                if (other && this.findTile(cell).value === this.findTile({
                                    x: x,
                                    y: y
                                }).value) {
                                    return true; // These two tiles can be merged
                                }
                            }
                        }
                    }
                }

                return false;
            },

            withinBounds: function(position) {
                var size = this.conf.size;

                return position.x >= 0 && position.x < size && position.y >= 0 && position.y < size;
            },

            buildTraversals: function(vector) {
                var traversals = {
                    x: [],
                    y: []
                },
                    size = this.conf.size;

                for (var pos = 0; pos < size; pos++) {
                    traversals.x.push(pos);
                    traversals.y.push(pos);
                }

                // Always traverse from the farthest cell in the chosen direction
                if (vector.x === 1) traversals.x = traversals.x.reverse();
                if (vector.y === 1) traversals.y = traversals.y.reverse();

                return traversals;
            },

            updateScore: function(score) {
                var scoreContainer = document.getElementsByClassName('score-container')[0];

                //On init
                if (score === 0) {
                    this.conf.score = 0;
                    //gameStorage.save('score', 0);

                    return false;
                }

                this.conf.score += score;
                //gameStorage.save('score', this.score);

                if (this.conf.score > this.conf.bestScore) {
                    this.conf.bestScore = this.conf.score;
                    //gameStorage.save('bestScore', this.bestScore);
                }

                // The mighty 2048 tile
                if (score === 2048)
                    this.message(true);

                var addition = document.createElement("div");
                addition.classList.add("score-addition");
                addition.textContent = "+" + score;
                scoreContainer.appendChild(addition);

            },

            message: function(won) {
                var type = won ? "game-won" : "game-over";
                var message = won ? "You win!" : "Game over!";
                var messageContainer = document.querySelector(".game-message");

                messageContainer.classList.add(type);
                messageContainer.getElementsByTagName("p")[0].textContent = message;
            },

            clearMessage: function() {
                messageContainer = document.querySelector(".game-message");

                messageContainer.classList.remove("game-won");
                messageContainer.classList.remove("game-over");
            },

            clearContainer: function(container) {
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
            },

            getWindowSize: function() {
                var w = window,
                    d = document,
                    e = d.documentElement,
                    g = d.getElementsByTagName('body')[0],
                    x = w.innerWidth || e.clientWidth || g.clientWidth,
                    y = w.innerHeight || e.clientHeight || g.clientHeight;

                if (x < 520) {
                    this.tileDimension = 69.5;
                    this.tilePosition = 67;
                } else {
                    this.tileDimension = 124;
                    this.tilePosition = 121;

                }
            }

        }
    });

    var Keys = new KeyboardInputManager();

    Keys.on('move', function(direction) {
        Game.move(direction);
    });

    win.onresize = function(event) {
        Game.getWindowSize();
    };

})(window);<|endoftext|>


<commit_before>let DontPanic = {};
let player;
let obstacle;
let enemy;
let background;
let gameStarted = false;
let coinTotal = localStorage['coinTotal'] || '0';
let currentDistance;
let bestDistance = localStorage['bestDistance'] || '0';
let filter;
let improbabilityDrive;
let improbabilityDriveTriggered = false;
let extraLife;

function init() {
  const gameWidth = 360;
  const gameHeight = 600;
  DontPanic.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, 'gameWindow', {
    preload: preload,
    create: create,
    update: update
  });
}

function preload() {
  DontPanic.game.load.script('filter', 'https://cdn.rawgit.com/photonstorm/phaser/master/v2/filters/LightBeam.js');
  DontPanic.game.load.image('background1', 'assets/space_background.png');
  DontPanic.game.load.image('home_background', 'assets/game_screen.jpg');
  DontPanic.game.load.image('startButton', 'assets/button_start.png'); // placeholders for now
  DontPanic.game.load.image('settingsButton', 'assets/button_settings.png'); // placeholders for now
  DontPanic.game.load.image('playAgainButton', 'assets/button_play-again.png'); // placeholders for now
  DontPanic.game.load.spritesheet('rocket_red', 'assets/rocket_spritesheet1.png', 115, 175);
  DontPanic.game.load.spritesheet('rocket_blue', 'assets/rocket_spritesheet_blue1.png', 115, 175);
  DontPanic.game.load.spritesheet('enemyShip', 'assets/enemy_ship_spritesheet1.png', 440, 1140);
  DontPanic.game.load.spritesheet('red_button', 'assets/iid-button.png', 472, 472);
  DontPanic.game.load.image('heart', 'assets/life.png');
  DontPanic.game.load.image('enemyBullet', 'assets/enemy-bullet.png'); //placeholder
  DontPanic.game.load.image('coin', 'assets/coin_2.png');
  DontPanic.game.load.image('extraLife', 'assets/extra_life.png');

  DontPanic.game.load.image('IID_background1', 'assets/iid/iid_bg.png');
  DontPanic.game.load.spritesheet('IID_enemy1', 'assets/iid/iid_enemy1.png', 440, 1140);
  DontPanic.game.load.spritesheet('IID_player1', 'assets/iid/iid_player1.png', 115, 175);
  DontPanic.game.load.image('IID_teacup', 'assets/iid/tea.png');
  DontPanic.game.load.image('whale', 'assets/iid/whale.png');
  DontPanic.game.load.image('petunias', 'assets/iid/flowers.png');
}

function create() {
  DontPanic.game.world.setBounds(0, 0, 360, 600);
  cursors = DontPanic.game.input.keyboard.createCursorKeys();
  mainMenu();
}

function update() {
  if (gameStarted) {
    player.handleInput();
    handleCollision();
    enemy.moveEnemy();
  }
}

function startGame() {
  gameStarted = true;
  background = new Background();
  player = new Player();
  enemy = new Enemy();
  coins = new Coins();
  lives = new LivesScore();
  coinScore = new CoinScore();
  distanceScore = new DistanceScore();
  improbabilityDrive = new ImprobabilityDrive();
  obstacle = new Obstacle();
  extraLife = new ExtraLife();
}

function handleCollision() {
  DontPanic.game.physics.arcade.overlap(player.playerSprite, coins.coins, collectCoin, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, enemy.enemies, abductPlayer, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, obstacle.obstacles, obstacleCollision, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, extraLife.extraLives, gainLife, null, this);
}

function gainLife(player, life) {
  life.kill();
  lives.gainLife();
}

function obstacleCollision() {
  player.playerSprite.kill();
  gameOver();
}

function collectCoin(player, coin) {
  coin.kill();
  coinScore.addToCoinScore()
}

function abductPlayer(playerSprite, vogon) {
  if (!vogon.abductSuccessful && vogon.frame == 3) {
    lives.loseLife();
    playerSprite.play('lifeLost');
    vogon.abductSuccessful = true;
    // pause game assets for a sec?
  }
}

function stopGameAssetGeneration() {
  coins.coinTimer.timer.stop();
  enemy.enemyTimer.timer.stop();
}

function gameOver() {
  player.playerSprite.kill();
  DontPanic.game.gameOver = DontPanic.game.add.text(DontPanic.game.world.centerX, DontPanic.game.world.centerY * 0.75, 'GAME OVER', { font: '40px whoopass', fill: '#fff' });
  DontPanic.game.gameOver.anchor.setTo(0.5);
  DontPanic.game.camera.fade(0x0000000, 4000);
  DontPanic.game.camera.onFadeComplete.add(playAgainMenu, this);
  gameStarted = false;
  stopGameAssetGeneration();
  if (currentDistance > parseInt(bestDistance)) {
    localStorage['bestDistance'] = currentDistance.toString();
  }
}
<commit_msg>shake camera on life lost<commit_after>let DontPanic = {};
let player;
let obstacle;
let enemy;
let background;
let gameStarted = false;
let coinTotal = localStorage['coinTotal'] || '0';
let currentDistance;
let bestDistance = localStorage['bestDistance'] || '0';
let filter;
let improbabilityDrive;
let improbabilityDriveTriggered = false;
let extraLife;

function init() {
  const gameWidth = 360;
  const gameHeight = 600;
  DontPanic.game = new Phaser.Game(gameWidth, gameHeight, Phaser.AUTO, 'gameWindow', {
    preload: preload,
    create: create,
    update: update
  });
}

function preload() {
  DontPanic.game.load.script('filter', 'https://cdn.rawgit.com/photonstorm/phaser/master/v2/filters/LightBeam.js');
  DontPanic.game.load.image('background1', 'assets/space_background.png');
  DontPanic.game.load.image('home_background', 'assets/game_screen.jpg');
  DontPanic.game.load.image('startButton', 'assets/button_start.png'); // placeholders for now
  DontPanic.game.load.image('settingsButton', 'assets/button_settings.png'); // placeholders for now
  DontPanic.game.load.image('playAgainButton', 'assets/button_play-again.png'); // placeholders for now
  DontPanic.game.load.spritesheet('rocket_red', 'assets/rocket_spritesheet1.png', 115, 175);
  DontPanic.game.load.spritesheet('rocket_blue', 'assets/rocket_spritesheet_blue1.png', 115, 175);
  DontPanic.game.load.spritesheet('enemyShip', 'assets/enemy_ship_spritesheet1.png', 440, 1140);
  DontPanic.game.load.spritesheet('red_button', 'assets/iid-button.png', 472, 472);
  DontPanic.game.load.image('heart', 'assets/life.png');
  DontPanic.game.load.image('enemyBullet', 'assets/enemy-bullet.png'); //placeholder
  DontPanic.game.load.image('coin', 'assets/coin_2.png');
  DontPanic.game.load.image('extraLife', 'assets/extra_life.png');

  DontPanic.game.load.image('IID_background1', 'assets/iid/iid_bg.png');
  DontPanic.game.load.spritesheet('IID_enemy1', 'assets/iid/iid_enemy1.png', 440, 1140);
  DontPanic.game.load.spritesheet('IID_player1', 'assets/iid/iid_player1.png', 115, 175);
  DontPanic.game.load.image('IID_teacup', 'assets/iid/tea.png');
  DontPanic.game.load.image('whale', 'assets/iid/whale.png');
  DontPanic.game.load.image('petunias', 'assets/iid/flowers.png');
}

function create() {
  DontPanic.game.world.setBounds(0, 0, 360, 600);
  cursors = DontPanic.game.input.keyboard.createCursorKeys();
  mainMenu();
}

function update() {
  if (gameStarted) {
    player.handleInput();
    handleCollision();
    enemy.moveEnemy();
  }
}

function startGame() {
  gameStarted = true;
  background = new Background();
  player = new Player();
  enemy = new Enemy();
  coins = new Coins();
  lives = new LivesScore();
  coinScore = new CoinScore();
  distanceScore = new DistanceScore();
  improbabilityDrive = new ImprobabilityDrive();
  obstacle = new Obstacle();
  extraLife = new ExtraLife();
}

function handleCollision() {
  DontPanic.game.physics.arcade.overlap(player.playerSprite, coins.coins, collectCoin, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, enemy.enemies, abductPlayer, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, obstacle.obstacles, obstacleCollision, null, this);
  DontPanic.game.physics.arcade.overlap(player.playerSprite, extraLife.extraLives, gainLife, null, this);
}

function gainLife(player, life) {
  life.kill();
  lives.gainLife();
}

function obstacleCollision() {
  player.playerSprite.kill();
  gameOver();
}

function collectCoin(player, coin) {
  coin.kill();
  coinScore.addToCoinScore()
}

function abductPlayer(playerSprite, vogon) {
  if (!vogon.abductSuccessful && vogon.frame == 3) {
    lives.loseLife();
    // player.playerSprite.lifeLostAnimate.play();
    DontPanic.game.camera.shake(0.005, 500);
    // player.loseLifeFlash(playerSprite);
    // playerSprite.play('lifeLost');
    vogon.abductSuccessful = true;
    // pause game assets for a sec?
  }
}

function stopGameAssetGeneration() {
  coins.coinTimer.timer.stop();
  enemy.enemyTimer.timer.stop();
}

function gameOver() {
  player.playerSprite.kill();
  DontPanic.game.gameOver = DontPanic.game.add.text(DontPanic.game.world.centerX, DontPanic.game.world.centerY * 0.75, 'GAME OVER', { font: '40px whoopass', fill: '#fff' });
  DontPanic.game.gameOver.anchor.setTo(0.5);
  DontPanic.game.camera.fade(0x0000000, 4000);
  DontPanic.game.camera.onFadeComplete.add(playAgainMenu, this);
  gameStarted = false;
  stopGameAssetGeneration();
  if (currentDistance > parseInt(bestDistance)) {
    localStorage['bestDistance'] = currentDistance.toString();
  }
}
<|endoftext|>


<commit_before>var app = angular.module('refApp', []);

app.controller('MainCtrl', [function() {
  var self = this
  self.references = [];
  // self.columns = 12
  self.addRef = function(urlToPass, size) {
    var added = {url: urlChecker(urlToPass), size: size};
    console.log(added);
    self.references.push(added);
    // self.columns -= size;
    // console.log(self.columns)
  };

  var urlChecker = function(urlToTest) {
    //checks if pattern is present
    // if not, adds on http to url
      // what if https needed? error handling?
      var pattern = /^(f|ht)tps?:\/\//i;
      if(!pattern.test(urlToTest)) {
        urlToTest = "http://" + urlToTest;
      };
      return urlToTest;
    };

  var removeImage = function(object) {

  };

  }]);
<commit_msg>adds in an image sizer<commit_after>var app = angular.module('refApp', []);

app.controller('MainCtrl', [function() {
  var self = this
  self.references = [];
  // self.columns = 12
  self.addRef = function(urlToPass, size) {
    var added = {url: urlChecker(urlToPass), size: size};
    console.log(added);
    self.references.push(added);
    // self.columns -= size;
    // console.log(self.columns)
  };

  var urlChecker = function(urlToTest) {
    //checks if pattern is present
    // if not, adds on http to url
      // what if https needed? error handling?
      var pattern = /^(f|ht)tps?:\/\//i;
      if(!pattern.test(urlToTest)) {
        urlToTest = "http://" + urlToTest;
      };
      return urlToTest;
    };

  var removeImage = function(object) {

  };

  var imgSizer = function(size) {
    if (size === 'small') {
      return 2;
    } else if (size === 'medium') {
      return 3
    } else if (size === 'large') {
      return 6
    } else if (size === 'x-large') {
      return 12
    }
  };

  }]);
<|endoftext|>


<commit_before>/*
 * This script requires JQuery, so be sure to load it beforehand.
 */

/** @type {String} Value of nav list that indicate the list is open. */
var nav_list_open = 'open';

/**
 * Initialize event listeners.
 * @return {undefined}
 */

var initialize = function(){
  var main = document.getElementsByTagName('main')[0];
  var nav_menu_icon = document.getElementById('nav_menu_icon');

  nav_menu_icon.addEventListener('click', toggle_nav_list_open);
  main.addEventListener('click', remove_open);

  // Add animations for the item images.
  $(".item_image").hover(
    function() {$(this).addClass("animated bounce"); },
    function() {$(this).removeClass("animated bounce"); }
  );
};

/**
 * Toggle the nav list's value of nav_list_open.
 * @return {undefined}
 */
var toggle_nav_list_open = function() {
  console.log('toggle_nav_list_open called.');

  var nav_list = document.getElementById('nav_list');
  nav_list.classList.toggle(nav_list_open);
};

/**
 * Removes nav_list_open value from the nav list.
 * @return {undefined}
 */
var remove_open = function() {
  console.log('remove_open called.');

  var nav_list = document.getElementById('nav_list');

  nav_list.classList.remove(nav_list_open);
};

// Bind initialize function.
$(window).bind('load', initialize);
<commit_msg>feat: change the animation for the item images<commit_after>/*
 * This script requires JQuery, so be sure to load it beforehand.
 */

/** @type {String} Value of nav list that indicate the list is open. */
var nav_list_open = 'open';

/**
 * Initialize event listeners.
 * @return {undefined}
 */

var initialize = function(){
  var main = document.getElementsByTagName('main')[0];
  var nav_menu_icon = document.getElementById('nav_menu_icon');

  nav_menu_icon.addEventListener('click', toggle_nav_list_open);
  main.addEventListener('click', remove_open);

  // Add animations for the item images.
  $(".item_image").hover(
    function() {$(this).addClass("animated pulse"); },
    function() {$(this).removeClass("animated pulse"); }
  );
};

/**
 * Toggle the nav list's value of nav_list_open.
 * @return {undefined}
 */
var toggle_nav_list_open = function() {
  console.log('toggle_nav_list_open called.');

  var nav_list = document.getElementById('nav_list');
  nav_list.classList.toggle(nav_list_open);
};

/**
 * Removes nav_list_open value from the nav list.
 * @return {undefined}
 */
var remove_open = function() {
  console.log('remove_open called.');

  var nav_list = document.getElementById('nav_list');

  nav_list.classList.remove(nav_list_open);
};

// Bind initialize function.
$(window).bind('load', initialize);
<|endoftext|>


<commit_before>var $ = document.querySelectorAll.bind(document);

var GAME = {
	board: new Board()
}

var $grid = $('.grid')[0]
Events.on('move', function(move) {
	if (move.fromRow === move.toRow && move.fromCol === move.toCol) return;
	var $tiles = $('.tile-'+move.fromRow+'-'+move.fromCol)
	var $old = $('.tile-'+move.toRow+'-'+move.toCol)[0]
	_.map($tiles, function($tile) {
		$tile.className = $tile.className.replace(/tile-\d-\d/, 'tile-'+move.toRow+'-'+move.toCol)
	})

	if ($old) {
		setTimeout(function() {
			_.map($tiles, function($tile) {
				try {
					$tile.parentElement.removeChild($tile)
				} catch(e) {
				}
			})
		}, 1000)
	}
})

Events.on('spawn', function(spawn) {
	var $div = document.createElement('div')
	var $tile = document.createElement('div')
	$tile.setAttribute('class', 'tile '+'tile-'+spawn.row+'-'+spawn.col+' tile-phase-'+(spawn.color-1))
	$tile.appendChild($div)
	$grid.appendChild($tile)
})

var maxColor = 1
Events.on('setColor', function(elem) {
	var $tiles = $('.tile-'+elem.row+'-'+elem.col)
	try {
		_.map($tiles, function($tile) {
			$tile.className = $tile.className.replace(/tile-phase-\d/, 'tile-phase-'+(elem.color-1))
		})

		if (elem.color > maxColor) {
			maxColor = elem.color
			$progress = $('#progress-cover')[0]
			$progress.className = $progress.className.replace(/progress-\d/, 'progress-'+(maxColor-1))
		}
	} catch (e) {}
})

// super hack to prevent multiple buttons spawning end of game
var gameOverOnce = false
Events.on('gameOver', function() {
	maxColor = 0
	var infoScreen = document.getElementById('info-screen')
	infoScreen.className = 'show'
	var gameOverBox = document.getElementById('game-over-box')
	gameOverBox.style.display = 'block'

	// move the score element inside this div, we move back to it's original spot when a new game is started
	if(scoreWrapperEle = $('.score-wrapper')[0])
		gameOverBox.appendChild(scoreWrapperEle)

	var challengeButton = document.createElement('button')
	challengeButton.innerText = 'Challenge a Friend'
	// Should add some sort of fastclick here... (touch first)
	challengeButton.addEventListener('click', function() {
		Events.emit('challengeFriend')
	})

	if (!gameOverOnce) {
		var gameOverButton = document.createElement('button')
		gameOverButton.innerText = 'Play Again'
		gameOverButton.className = 'play-again'
		// Should add some sort of fastclick here... (touch first)
		gameOverButton.addEventListener('click', function() {
			Events.emit('restartGame')
		})

		gameOverBox.appendChild(challengeButton)
		gameOverBox.appendChild(gameOverButton)
		gameOverOnce = true
	}
})

Events.on('challengeFriend', function() {
	var score = GAME.board.score;
	Clay.Social.smartShare({
		message: 'Think you can beat my score?',
		title: 'I just scored ' + score + ' in Prism!',
		//image: screenshotURL,
		data: {},
		//respond: // the username of our opponent // cards.kik.returnToConversation
	})
})

Events.on('restartGame', function() {
	$('.grid')[0].innerHTML = ''
	document.getElementById('progress-cover').className = 'progress-0'
	document.getElementById('info-screen').className = 'hide'
	// move the score element back to where it was before
	if(scoreWrapperEle = $('.score-wrapper')[0])
		document.body.appendChild(scoreWrapperEle)
	GAME.board.newGame()
})

scoreEle = $('#score')[0]
Events.on('score', function(score) {
	scoreEle.innerHTML = score;
})

// keybindings
var move = 'left';
Hammer(window, {
	drag_min_distance:5,
	drag_block_horizontal:true,
	drag_block_vertical:true
}).on("dragleft", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='left'
}).on("dragright", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='right'
}).on("dragup", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='up'
}).on("dragdown", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='down'
}).on('dragend', function(e) {
	GAME.board.move(move)
})

Mousetrap.bind(['up', 'down', 'left', 'right'], function(e) {
	GAME.board.move(e.keyIdentifier.toLowerCase())
});

// init
// Run the tutorial for first-time visitors
if(!localStorage['tutorial-shown']) {

	// row, col, color
	GAME.board.newGame([[2,1,1],[2,2,1]])
	GAME.tutorial = new Tutorial([2, 1])
	localStorage['tutorial-shown'] = 1
} else {
	GAME.board.newGame()
}

window.addEventListener('load', function() {
	// Load in sharing buttons
	// TODO
	html = ''
	html += ''
	document.getElementById('share').innerHTML = html
})

function sizing() {
	var gridWidth = window.innerWidth
	var gridHeight = window.innerHeight - $('.grid-inner')[0].offsetTop * 2 // .grid-outer padding
	var boxSize = Math.min(gridWidth, gridHeight)
	$('.grid-background')[0].style.width = boxSize + 'px'
	$('.grid-background')[0].style.height = (boxSize - 14) + 'px' // 7px  padding
}
sizing()
$grid.style.visibility = 'visible'
$('.grid-background')[0].style.visibility = 'visible'
window.onresize = sizing
<commit_msg>fixed end-game score position<commit_after>var $ = document.querySelectorAll.bind(document);

var GAME = {
	board: new Board()
}

var $grid = $('.grid')[0]
Events.on('move', function(move) {
	if (move.fromRow === move.toRow && move.fromCol === move.toCol) return;
	var $tiles = $('.tile-'+move.fromRow+'-'+move.fromCol)
	var $old = $('.tile-'+move.toRow+'-'+move.toCol)[0]
	_.map($tiles, function($tile) {
		$tile.className = $tile.className.replace(/tile-\d-\d/, 'tile-'+move.toRow+'-'+move.toCol)
	})

	if ($old) {
		setTimeout(function() {
			_.map($tiles, function($tile) {
				try {
					$tile.parentElement.removeChild($tile)
				} catch(e) {
				}
			})
		}, 1000)
	}
})

Events.on('spawn', function(spawn) {
	var $div = document.createElement('div')
	var $tile = document.createElement('div')
	$tile.setAttribute('class', 'tile '+'tile-'+spawn.row+'-'+spawn.col+' tile-phase-'+(spawn.color-1))
	$tile.appendChild($div)
	$grid.appendChild($tile)
})

var maxColor = 1
Events.on('setColor', function(elem) {
	var $tiles = $('.tile-'+elem.row+'-'+elem.col)
	try {
		_.map($tiles, function($tile) {
			$tile.className = $tile.className.replace(/tile-phase-\d/, 'tile-phase-'+(elem.color-1))
		})

		if (elem.color > maxColor) {
			maxColor = elem.color
			$progress = $('#progress-cover')[0]
			$progress.className = $progress.className.replace(/progress-\d/, 'progress-'+(maxColor-1))
		}
	} catch (e) {}
})

// super hack to prevent multiple buttons spawning end of game
var gameOverOnce = false
Events.on('gameOver', function() {
	maxColor = 0
	var infoScreen = document.getElementById('info-screen')
	infoScreen.className = 'show'
	var gameOverBox = document.getElementById('game-over-box')
	gameOverBox.style.display = 'block'

	var challengeButton = document.createElement('button')
	challengeButton.innerText = 'Challenge a Friend'
	// Should add some sort of fastclick here... (touch first)
	challengeButton.addEventListener('click', function() {
		Events.emit('challengeFriend')
	})

	if (!gameOverOnce) {
		var gameOverButton = document.createElement('button')
		gameOverButton.innerText = 'Play Again'
		gameOverButton.className = 'play-again'
		// Should add some sort of fastclick here... (touch first)
		gameOverButton.addEventListener('click', function() {
			Events.emit('restartGame')
		})

		gameOverBox.appendChild(challengeButton)
		gameOverBox.appendChild(gameOverButton)
		gameOverOnce = true
	}

	// move the score element inside this div, we move back to it's original spot when a new game is started
	var scoreWrapperEle = $('.score-wrapper')[0]
	if(scoreWrapperEle)
		gameOverBox.appendChild(scoreWrapperEle)
})

Events.on('challengeFriend', function() {
	var score = GAME.board.score;
	Clay.Social.smartShare({
		message: 'Think you can beat my score?',
		title: 'I just scored ' + score + ' in Prism!',
		//image: screenshotURL,
		data: {},
		//respond: // the username of our opponent // cards.kik.returnToConversation
	})
})

Events.on('restartGame', function() {
	$('.grid')[0].innerHTML = ''
	document.getElementById('progress-cover').className = 'progress-0'
	document.getElementById('info-screen').className = 'hide'
	// move the score element back to where it was before
	if(scoreWrapperEle = $('.score-wrapper')[0])
		document.body.appendChild(scoreWrapperEle)
	GAME.board.newGame()
})

scoreEle = $('#score')[0]
Events.on('score', function(score) {
	scoreEle.innerHTML = score;
})

// keybindings
var move = 'left';
Hammer(window, {
	drag_min_distance:5,
	drag_block_horizontal:true,
	drag_block_vertical:true
}).on("dragleft", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='left'
}).on("dragright", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='right'
}).on("dragup", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='up'
}).on("dragdown", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='down'
}).on('dragend', function(e) {
	GAME.board.move(move)
})

Mousetrap.bind(['up', 'down', 'left', 'right'], function(e) {
	GAME.board.move(e.keyIdentifier.toLowerCase())
});

// init
// Run the tutorial for first-time visitors
if(!localStorage['tutorial-shown']) {

	// row, col, color
	GAME.board.newGame([[2,1,1],[2,2,1]])
	GAME.tutorial = new Tutorial([2, 1])
	localStorage['tutorial-shown'] = 1
} else {
	GAME.board.newGame()
}

window.addEventListener('load', function() {
	// Load in sharing buttons
	// TODO
	html = ''
	html += ''
	document.getElementById('share').innerHTML = html
})

function sizing() {
	var gridWidth = window.innerWidth
	var gridHeight = window.innerHeight - $('.grid-inner')[0].offsetTop * 2 // .grid-outer padding
	var boxSize = Math.min(gridWidth, gridHeight)
	$('.grid-background')[0].style.width = boxSize + 'px'
	$('.grid-background')[0].style.height = (boxSize - 14) + 'px' // 7px  padding
}
sizing()
$grid.style.visibility = 'visible'
$('.grid-background')[0].style.visibility = 'visible'
window.onresize = sizing
<|endoftext|>


<commit_before>var emulabeller = (function() {
    'use strict';

    // autoload wav file and TextGrid for testing
    // will only work if running on server...
    var autoLoad = true;

    var tierInfos = {
        "tiers": [],
        "canvases": []
    };

    var osciCanvas = document.querySelector('#wave');
    var specCanvas = document.querySelector('#spectrogram');
    var scrollCanvas = document.querySelector('#scrollbar');
    var draggableBar = document.querySelector('#resizer');
    var timeline = document.querySelector('#timeline');
    var tiers = document.querySelector('#tiers');
    var cans = document.getElementById('cans');
    var fileSelect = document.querySelector('#fileSelect');
    var showLeftPush = document.getElementById('serverSelect');
    var spectroworker = document.querySelector('#spectroworker');
    var labeller = Object.create(EmuLabeller);

    labeller.init({
        osciCanvas: osciCanvas,
        specCanvas: specCanvas,
        scrollCanvas: scrollCanvas,
        tierInfos: tierInfos,
        draggableBar: draggableBar,
        timeline: timeline,
        tiers: tiers,
        cans: cans,
        fileSelect: fileSelect,
        showLeftPush: showLeftPush,
        spectroworker: spectroworker,
        internalCanvasWidth: '2048', // in pixel
        internalCanvasHeightSmall: '128', // in pixel -> Cans
        internalCanvasHeightBig: '64', // in pixel -> Wave & Spectro
        mode: 'standalone' // server or standalone
    });

    // see if on iPad... if so preload data... just for testing
    var isiPad = navigator.userAgent.match(/iPad/i) !== null;
    if (isiPad || autoLoad) {
        labeller.iohandler.xhrLoad('data/msajc003.TextGrid', 'text', 3);
        labeller.iohandler.xhrLoad('data/msajc003.wav', 'arraybuffer', 0);
    }

    // initial  launch

    $('#fileGetterBtn')[0].addEventListener('change', labeller.fileAPIread, false);

    // hack for hiding inputs of dialogs.. SIC!!!
    $("#dialog-messageSh").hide();
    $("#dialog-messageSetLabel").hide();
    $('#specSettings').click(function() {
        var isOpen = $('#specDialog').dialog('isOpen');
        if (!isOpen) {
            $('#specDialog').dialog('open');
            $("#specDialog").dialog('moveToTop');
            isOpen = true;
        } else {
            $('#specDialog').dialog('close');
            isOpen = false;
        }
    });

    // event redirect for Open File Button
    document.querySelector('#fileSelect').addEventListener('click', function(e) {
            // Use the native click() of the file input.
            document.querySelector('#fileGetterBtn').click();
        },
        false);

    $(document).bind("keydown", function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 8 && emulabeller.keyBindingAllowed()) { // 8 == backspace
            e.preventDefault();
            if (emulabeller.tierHandler.getSelectedTierType() == "seg" ||  emulabeller.tierHandler.getSelectedTierType() == "point")
                emulabeller.tierHandler.deleteSelected();
            else
                alert("Please mark one of more segments first!");
        }
        if (code == 9 ) { // 9 == tab
            e.preventDefault();
            if (!e.shiftKey) {
                emulabeller.tierHandler.selectPrevNextEvent(false);
            }else{
                emulabeller.tierHandler.selectPrevNextEvent(true);
            }
        }
       // if (code == 13 && emulabeller.keyBindingAllowed()) { // 13 == enter
       //     emulabeller.tierHandler.addSegmentAtSelection();
       //     e.preventDefault();
       // }
        if (code == 13 ) { // 13 == enter
            if(emulabeller.tierHandler.isEditing==true) {
    			emulabeller.tierHandler.saveLabelName(this);
	    		emulabeller.tierHandler.removeLabelDoubleClick();
	    	}
	    	else {
	    	    emulabeller.tierHandler.addSegmentAtSelection();
	    	}
		    e.preventDefault();
        }
        if (code == 16 && emulabeller.keyBindingAllowed()) { // 16 == ???
            emulabeller.tierHandler.history();
            e.preventDefault();
        }
        if (code == 18 && emulabeller.keyBindingAllowed()) { // 18 == ???
            emulabeller.tierHandler.history();
            e.preventDefault();
        }
        if (code == 27 && emulabeller.internalMode == labeller.EDITMODE.LABEL_RENAME) { // 27 == escape
            emulabeller.tierHandler.removeLabelDoubleClick();
            e.preventDefault();
        }
        if (code == 32 && emulabeller.keyBindingAllowed()) { // 32 == SPACE
            emulabeller.playPauseInView();
            e.preventDefault();
        }
        if (code == 46 && emulabeller.keyBindingAllowed()) { // 46 == entfernen
            emulabeller.tierHandler.deleteBorder();
            e.preventDefault();
        }
        if (code == 65 && emulabeller.keyBindingAllowed()) { // 65 == a
            emulabeller.shiftViewP(0);
            e.preventDefault();
        }
        if (code == 66 && emulabeller.keyBindingAllowed()) { // 66 == b
            emulabeller.tierHandler.snapSelectedBoundaryToNearestTopOrBottom(false);
            e.preventDefault();
        }
        if (code == 68 && emulabeller.keyBindingAllowed()) { // 68 == d
            emulabeller.shiftViewP(1);
            e.preventDefault();
        }
        if (code == 69 && emulabeller.keyBindingAllowed()) { // 69 == e
            emulabeller.zoomSel();
            e.preventDefault();
        }
        if (code == 70 && emulabeller.keyBindingAllowed()) { // 70 == f
            emulabeller.playInMode("all");
            e.preventDefault();
        }
        if (code == 78 && emulabeller.keyBindingAllowed()) { // 78 == n
            emulabeller.tierHandler.renameTier();
            e.preventDefault();
        }
        if (code == 79 && emulabeller.keyBindingAllowed()) { // 79 == o
            if (emulabeller.externalMode == labeller.USAGEMODE.STANDALONE)
                $('#fileGetterBtn').click();
            if (emulabeller.externalMode == labeller.USAGEMODE.SERVER)
                emulabeller.openSubmenu();
            e.preventDefault();
        }
        if (code == 81 && emulabeller.keyBindingAllowed()) { // 81 == q
            emulabeller.setView(-Infinity, Infinity);
            e.preventDefault();
        }
        if (code == 82 && emulabeller.keyBindingAllowed()) { // 82 == r
            if (!e.metaKey) {
                emulabeller.playInMode("sel");
                e.preventDefault();
            }
        }
        if (code == 83 && emulabeller.keyBindingAllowed()) { // 83 == s
            emulabeller.zoomViewPort(0);
            e.preventDefault();
        }
        if (code == 84 && emulabeller.keyBindingAllowed()) { // 84 == t
            emulabeller.tierHandler.snapSelectedBoundaryToNearestTopOrBottom(true);
            e.preventDefault();
        }
        if (code == 87 && emulabeller.keyBindingAllowed()) { // 87 == w
            emulabeller.zoomViewPort(1);
            e.preventDefault();
        }
        if (code == 88 && emulabeller.keyBindingAllowed()) { // 88 == x
            emulabeller.tierHandler.snapToNearestZeroCrossing();
            e.preventDefault();
        }
        if (code == 90 && emulabeller.keyBindingAllowed()) { // 90 == z
            emulabeller.tierHandler.goBackHistory();
            e.preventDefault();
        }
        // console.log(code);
    });

    // touch events
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
        // alert("On mobile device!!!! Lots of things not working yet...");
        var element = document.getElementById('timeline');
        var hammertime = Hammer(element).on("touch", function(event) {
            // console.log('stop touching me says the timeline');
        });
        hammertime = Hammer(element).on("doubletap", function(event) {
            // alert('stop touching me says the timeline');
            emulabeller.zoomSel();
        });
        hammertime = Hammer(element).on("dragleft", function(event) {
            emulabeller.shiftViewP(1);
        });
        hammertime = Hammer(element).on("dragright", function(event) {
            emulabeller.shiftViewP(0);
        });
        hammertime = Hammer(element).on("dragdown", function(event) {
            emulabeller.zoomViewPort(1);
            event.preventDefault();
        });
        hammertime = Hammer(element).on("dragup", function(event) {
            emulabeller.zoomViewPort(0);
        });
    }

    labeller.start();
    return labeller;
}());
<commit_msg>alt+tab version1 (like this?) or undo on tab<commit_after>var emulabeller = (function() {
    'use strict';

    // autoload wav file and TextGrid for testing
    // will only work if running on server...
    var autoLoad = true;

    var tierInfos = {
        "tiers": [],
        "canvases": []
    };

    var osciCanvas = document.querySelector('#wave');
    var specCanvas = document.querySelector('#spectrogram');
    var scrollCanvas = document.querySelector('#scrollbar');
    var draggableBar = document.querySelector('#resizer');
    var timeline = document.querySelector('#timeline');
    var tiers = document.querySelector('#tiers');
    var cans = document.getElementById('cans');
    var fileSelect = document.querySelector('#fileSelect');
    var showLeftPush = document.getElementById('serverSelect');
    var spectroworker = document.querySelector('#spectroworker');
    var labeller = Object.create(EmuLabeller);

    labeller.init({
        osciCanvas: osciCanvas,
        specCanvas: specCanvas,
        scrollCanvas: scrollCanvas,
        tierInfos: tierInfos,
        draggableBar: draggableBar,
        timeline: timeline,
        tiers: tiers,
        cans: cans,
        fileSelect: fileSelect,
        showLeftPush: showLeftPush,
        spectroworker: spectroworker,
        internalCanvasWidth: '2048', // in pixel
        internalCanvasHeightSmall: '128', // in pixel -> Cans
        internalCanvasHeightBig: '64', // in pixel -> Wave & Spectro
        mode: 'standalone' // server or standalone
    });

    // see if on iPad... if so preload data... just for testing
    var isiPad = navigator.userAgent.match(/iPad/i) !== null;
    if (isiPad || autoLoad) {
        labeller.iohandler.xhrLoad('data/msajc003.TextGrid', 'text', 3);
        labeller.iohandler.xhrLoad('data/msajc003.wav', 'arraybuffer', 0);
    }

    // initial  launch

    $('#fileGetterBtn')[0].addEventListener('change', labeller.fileAPIread, false);

    // hack for hiding inputs of dialogs.. SIC!!!
    $("#dialog-messageSh").hide();
    $("#dialog-messageSetLabel").hide();
    $('#specSettings').click(function() {
        var isOpen = $('#specDialog').dialog('isOpen');
        if (!isOpen) {
            $('#specDialog').dialog('open');
            $("#specDialog").dialog('moveToTop');
            isOpen = true;
        } else {
            $('#specDialog').dialog('close');
            isOpen = false;
        }
    });

    // event redirect for Open File Button
    document.querySelector('#fileSelect').addEventListener('click', function(e) {
            // Use the native click() of the file input.
            document.querySelector('#fileGetterBtn').click();
        },
        false);

    $(document).bind("keydown", function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 8 && emulabeller.keyBindingAllowed()) { // 8 == backspace
            e.preventDefault();
            if (emulabeller.tierHandler.getSelectedTierType() == "seg" ||  emulabeller.tierHandler.getSelectedTierType() == "point")
                emulabeller.tierHandler.deleteSelected();
            else
                alert("Please mark one of more segments first!");
        }
        if (code == 9 ) { // 9 == tab
            e.preventDefault();
            if(emulabeller.tierHandler.isEditing==true) {
    			emulabeller.tierHandler.saveLabelName(this);
	    		emulabeller.tierHandler.removeLabelDoubleClick();
	    	}
            if (!e.shiftKey) {
                emulabeller.tierHandler.selectPrevNextEvent(false);
            }else{
                emulabeller.tierHandler.selectPrevNextEvent(true);
            }
        }
       // if (code == 13 && emulabeller.keyBindingAllowed()) { // 13 == enter
       //     emulabeller.tierHandler.addSegmentAtSelection();
       //     e.preventDefault();
       // }
        if (code == 13 ) { // 13 == enter
            if(emulabeller.tierHandler.isEditing==true) {
    			emulabeller.tierHandler.saveLabelName(this);
	    		emulabeller.tierHandler.removeLabelDoubleClick();
	    	}
	    	else {
	    	    emulabeller.tierHandler.addSegmentAtSelection();
	    	}
		    e.preventDefault();
        }
        if (code == 16 && emulabeller.keyBindingAllowed()) { // 16 == ???
            emulabeller.tierHandler.history();
            e.preventDefault();
        }
        if (code == 18 && emulabeller.keyBindingAllowed()) { // 18 == ???
            emulabeller.tierHandler.history();
            e.preventDefault();
        }
        if (code == 27 && emulabeller.internalMode == labeller.EDITMODE.LABEL_RENAME) { // 27 == escape
            emulabeller.tierHandler.removeLabelDoubleClick();
            e.preventDefault();
        }
        if (code == 32 && emulabeller.keyBindingAllowed()) { // 32 == SPACE
            emulabeller.playPauseInView();
            e.preventDefault();
        }
        if (code == 46 && emulabeller.keyBindingAllowed()) { // 46 == entfernen
            emulabeller.tierHandler.deleteBorder();
            e.preventDefault();
        }
        if (code == 65 && emulabeller.keyBindingAllowed()) { // 65 == a
            emulabeller.shiftViewP(0);
            e.preventDefault();
        }
        if (code == 66 && emulabeller.keyBindingAllowed()) { // 66 == b
            emulabeller.tierHandler.snapSelectedBoundaryToNearestTopOrBottom(false);
            e.preventDefault();
        }
        if (code == 68 && emulabeller.keyBindingAllowed()) { // 68 == d
            emulabeller.shiftViewP(1);
            e.preventDefault();
        }
        if (code == 69 && emulabeller.keyBindingAllowed()) { // 69 == e
            emulabeller.zoomSel();
            e.preventDefault();
        }
        if (code == 70 && emulabeller.keyBindingAllowed()) { // 70 == f
            emulabeller.playInMode("all");
            e.preventDefault();
        }
        if (code == 78 && emulabeller.keyBindingAllowed()) { // 78 == n
            emulabeller.tierHandler.renameTier();
            e.preventDefault();
        }
        if (code == 79 && emulabeller.keyBindingAllowed()) { // 79 == o
            if (emulabeller.externalMode == labeller.USAGEMODE.STANDALONE)
                $('#fileGetterBtn').click();
            if (emulabeller.externalMode == labeller.USAGEMODE.SERVER)
                emulabeller.openSubmenu();
            e.preventDefault();
        }
        if (code == 81 && emulabeller.keyBindingAllowed()) { // 81 == q
            emulabeller.setView(-Infinity, Infinity);
            e.preventDefault();
        }
        if (code == 82 && emulabeller.keyBindingAllowed()) { // 82 == r
            if (!e.metaKey) {
                emulabeller.playInMode("sel");
                e.preventDefault();
            }
        }
        if (code == 83 && emulabeller.keyBindingAllowed()) { // 83 == s
            emulabeller.zoomViewPort(0);
            e.preventDefault();
        }
        if (code == 84 && emulabeller.keyBindingAllowed()) { // 84 == t
            emulabeller.tierHandler.snapSelectedBoundaryToNearestTopOrBottom(true);
            e.preventDefault();
        }
        if (code == 87 && emulabeller.keyBindingAllowed()) { // 87 == w
            emulabeller.zoomViewPort(1);
            e.preventDefault();
        }
        if (code == 88 && emulabeller.keyBindingAllowed()) { // 88 == x
            emulabeller.tierHandler.snapToNearestZeroCrossing();
            e.preventDefault();
        }
        if (code == 90 && emulabeller.keyBindingAllowed()) { // 90 == z
            emulabeller.tierHandler.goBackHistory();
            e.preventDefault();
        }
        // console.log(code);
    });

    // touch events
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
        // alert("On mobile device!!!! Lots of things not working yet...");
        var element = document.getElementById('timeline');
        var hammertime = Hammer(element).on("touch", function(event) {
            // console.log('stop touching me says the timeline');
        });
        hammertime = Hammer(element).on("doubletap", function(event) {
            // alert('stop touching me says the timeline');
            emulabeller.zoomSel();
        });
        hammertime = Hammer(element).on("dragleft", function(event) {
            emulabeller.shiftViewP(1);
        });
        hammertime = Hammer(element).on("dragright", function(event) {
            emulabeller.shiftViewP(0);
        });
        hammertime = Hammer(element).on("dragdown", function(event) {
            emulabeller.zoomViewPort(1);
            event.preventDefault();
        });
        hammertime = Hammer(element).on("dragup", function(event) {
            emulabeller.zoomViewPort(0);
        });
    }

    labeller.start();
    return labeller;
}());
<|endoftext|>


<commit_before>---
layout: null
sitemap:
  exclude: 'yes'
---

$(document).ready(function () {
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '35%'}, 400, swing = 'swing', function () {})
    }
  })

  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
	$('.content-wrapper').css("display", "block")
  }

  if (window.location.pathname.indexOf('page') !== -1) {
    $('.panel-cover').addClass('panel-cover--collapsed')
	$('.content-wrapper').css("display", "block")
  }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
	$('.content-wrapper').css("display", "block")
  })

})

<commit_msg>Update main.js<commit_after>---
layout: null
---

$(document).ready(function () {
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '35%'}, 400, swing = 'swing', function () {})
    }
  })

  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
	$('.content-wrapper').css("display", "block")
  }

  if (window.location.pathname.indexOf('page') !== -1) {
    $('.panel-cover').addClass('panel-cover--collapsed')
	$('.content-wrapper').css("display", "block")
  }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
	$('.content-wrapper').css("display", "block")
  })

})

<|endoftext|>


<commit_before>var CURR_TIME = (Math.floor(Date.now() / 1000)+31536000) * 1000000000;
var NON_ACTIVE_NUMBERS = [0, 3, 4, 5, 72, 109, 110, 111, 112] //2 = on foot... not sure how to count that
var SLEEP_NUMBERS = [79, 109, 110, 111]
var DAY = 86400000 //number of milliseconds in a day

var weight_data;
var all_activity_data;
var id_token;

function onSignIn(googleUser) {
  d3.select("#sign-in-button").classed("visuallyhidden", true);
  var profile = googleUser.getBasicProfile();

  id_token = googleUser.getAuthResponse().id_token;

  d3.select("#settings-drawer-header")
    .append("img")
      .attr("id", "profile-pic")
      .attr("src", profile.getImageUrl())
      .classed("demo-avatar", true);

  d3.select("#settings-drawer-header")
    .append("a")
      .attr("href", "#")
      .attr("id", "signout-link")
      .attr("onclick", "signOut();")
      .text("Sign out");

  loadGapi();
}

function onFailure(error) {
  console.log(error);
}

function signOut() {
  id_token = null;
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    d3.select("#signout-link").remove();
    d3.select("#profile-pic").remove();
    d3.select("#sign-in-button").classed("visuallyhidden", false);
    console.log('User signed out.');
  });
}

function addCard(variable) {
  var card = d3.select("#card-area")
    .append("div")
    .classed("mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop", true)

  card.append("div")
        .classed("mdl-card__title mdl-color--teal-300", true)
      .append("h2")
        .classed("mdl-card__title-text", true)
        .text(variable);

  card.append("div")
      .classed("mdl-card__supporting-text mdl-color-text--grey-600", true)
      .append("div")
      .attr("id", variable+"-graph");

  card.append("div")
        .classed("mdl-card__actions mdl-card--border", true)
      .append("a")
        .attr("href", "#")
        .classed("mdl-button mdl-js-button mdl-js-ripple-effect", true)
        .text("Read More");

  if (variable == "Sleep") {
    graphSleepData();
  } else if (variable == "Weight") {
    makeGraph(weight_data, "#Weight-graph", .8);
  }
}

function getWeight() {
  // 2. Initialize the JavaScript client library.
  gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources?dataTypeName=com.google.weight")
    .then(function(response) {
      weight_sources = response.result;
      idlist = [];
      for (el in weight_sources.dataSource){
        streamId = weight_sources.dataSource[el].dataStreamId;
        if (streamId == "derived:com.google.weight:com.google.android.gms:merge_weight") {
          idlist = [streamId];
          break;
        } else {
          idlist.push(streamId);
        }
      }
      Promise.all(idlist.map(getDataFromStream)).then(function(values){
        var data = extractDataFromStreams(values);
        for (el in data) {
          // Extract data from JSON object and convert kg to pounds
          data[el] = [new Date(+data[el].endTimeNanos/1000000), data[el].value[0].fpVal*2.20462];
        }
        weight_data = data;
      });
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};

function loadData() {
  // d3.selectAll(".getdata").classed("disabled", false);
  getWeight();
  getActivity()
}

function loadGapi() {
  gapi.load('client', loadData);
};

function getDataFromStream(streamId) {
  console.log("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
  return gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
}

function getActivity(){

  var activity_data = gapi.client.request({
    "path" : "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate",
    "method" : "POST",
    "body":{
      "aggregateBy": [
        {
          "dataTypeName": "com.google.activity.segment"
        }
      ],
      "endTimeMillis": Date.now(),
      "startTimeMillis": Date.now() - (30*DAY),
      "bucketByTime": {
        "period": {
          "type": "day",
          "value": 1,
          "timeZoneId": moment.tz.guess()
        }}
    }
  });
  activity_data.then(function(response){
    all_activity_data = response.result.bucket;
    graphSleepData();

  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
}

function graphSleepData(){
  sleep_data = [];
  for (i in all_activity_data) {
    if (all_activity_data[i].dataset[0].point.length > 0) {
      console.log(true);
      sleep_data.push([new Date(+all_activity_data[i].dataset[0].point[0].startTimeNanos/1000000), 0]);
    }
    for (j in all_activity_data[i].dataset[0].point){
      if (SLEEP_NUMBERS.includes(all_activity_data[i].dataset[0].point[j].value[0].intVal)) {
        sleep_data[sleep_data.length-1][1] += +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000;
      }
    }
  }
  makeGraph(sleep_data, "#Sleep-graph", .5);
}

function graphTotalActivityData(){
  data = [];
  for (i in all_activity_data) {
    for (j in all_activity_data[i].dataset[0].point){
      if (SLEEP_NUMBERS.includes(all_activity_data[i].dataset[0].point[j].value[0].intVal)) {
        data.push([new Date(+all_activity_data[i].dataset[0].point[j].startTimeNanos/1000000), +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000]);
      }
    }
  }
  makeGraph(data, "#Activity-graph", .5);
}

function extractDataFromStreams(streams) {
  var data = [];
  for (stream in streams) {
    var curr = streams[stream].result.point;
    if (curr.length > data.length) {
      data = curr;
    }
  }

  return data;
}

function toggleLabelYAxis() {
  $.ajax("http://www.stability-app.com/update_settings", {
      type:"POST",
      contentType:"application/json",
      data:JSON.stringify({"user":id_token, "value":true}),
      success:function() {alert("success");},
      error: function() {alert("failure");}
  });

  // var xmlHttp = new XMLHttpRequest();
  // xmlHttp.open( "POST", "http://stability-app.com/update_settings", true );
  // xmlHttp.send({"user":id_token, "value":true});
}

function makeGraph(data, svg_id, smoothing){
  // Based on https://github.com/jasondavies/science.js/blob/master/examples/loess/loess.js

  var id_without_hash = svg_id.slice(1, svg_id.length);

  var w = document.getElementById(id_without_hash).offsetWidth,
      h = 500,
      p = 35.5,
      n = 100;

  w -= 2*p; //margins need to come out of width

  var min_band = 2/data.length;

  var loess = science.stats.loess().bandwidth(d3.max([min_band, smoothing]));

  var zipped_data = d3.transpose(data);
  var loess_result = loess(zipped_data[0], zipped_data[1]);
  console.log("loess", loess_result);
  zipped_data[1] = loess_result.loess;
  zipped_data.push(loess_result.confint);
  data = d3.zip(zipped_data[0], zipped_data[1], zipped_data[2]);

  max_y = d3.max(data, function(d){return d[1]+d[2];});
  min_y = d3.min(data, function(d){return d[1]-d[2];});

  //Add margins
  max_y += max_y*.1
  min_y -= min_y*.1

  var x = d3.scaleTime().domain([new Date(data[0][0]-86400000), new Date(data[data.length-1][0]+86400000)]).range([0, w]);
  var y = d3.scaleLinear().domain([min_y, max_y]).range([h, 0]);

  var xAxis = d3.axisBottom(x),
      yAxis = d3.axisLeft(y);

  var vis = d3.select(svg_id)
    .append("svg")
      .attr("width", w + p + p)
      .attr("height", h + p + p)
    .append("g")
      .attr("transform", "translate(" + p + "," + p + ")");

  var area = d3.area()
        .x(function(d) { return x(d[0]); })
        .y0(function(d) { return d[2] ? y(d[1]-d[2]) : y(d[1]);})
        .y1(function(d) { return d[2] ? y(d[1]+d[2]) : y(d[1]);});

  vis.selectAll("path")
      .data([data])
    .enter().append("path")
      .attr("d", function(d){return area(d);})
      .attr("stroke", "black")
      .attr("fill", "purple")
      .attr("stroke-width", 1);

  vis.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + h + ")")
      .call(xAxis);

  vis.append("g")
      .attr("class", "left axis")
      .call(yAxis);
}
<commit_msg>handle all sleep numbers<commit_after>var CURR_TIME = (Math.floor(Date.now() / 1000)+31536000) * 1000000000;
var NON_ACTIVE_NUMBERS = [0, 3, 4, 5, 72, 109, 110, 111, 112] //2 = on foot... not sure how to count that
var SLEEP_NUMBERS = [79, 109, 110, 111]
var DAY = 86400000 //number of milliseconds in a day

var weight_data;
var all_activity_data;
var id_token;

function onSignIn(googleUser) {
  d3.select("#sign-in-button").classed("visuallyhidden", true);
  var profile = googleUser.getBasicProfile();

  id_token = googleUser.getAuthResponse().id_token;

  d3.select("#settings-drawer-header")
    .append("img")
      .attr("id", "profile-pic")
      .attr("src", profile.getImageUrl())
      .classed("demo-avatar", true);

  d3.select("#settings-drawer-header")
    .append("a")
      .attr("href", "#")
      .attr("id", "signout-link")
      .attr("onclick", "signOut();")
      .text("Sign out");

  loadGapi();
}

function onFailure(error) {
  console.log(error);
}

function signOut() {
  id_token = null;
  var auth2 = gapi.auth2.getAuthInstance();
  auth2.signOut().then(function () {
    d3.select("#signout-link").remove();
    d3.select("#profile-pic").remove();
    d3.select("#sign-in-button").classed("visuallyhidden", false);
    console.log('User signed out.');
  });
}

function addCard(variable) {
  var card = d3.select("#card-area")
    .append("div")
    .classed("mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop", true)

  card.append("div")
        .classed("mdl-card__title mdl-color--teal-300", true)
      .append("h2")
        .classed("mdl-card__title-text", true)
        .text(variable);

  card.append("div")
      .classed("mdl-card__supporting-text mdl-color-text--grey-600", true)
      .append("div")
      .attr("id", variable+"-graph");

  card.append("div")
        .classed("mdl-card__actions mdl-card--border", true)
      .append("a")
        .attr("href", "#")
        .classed("mdl-button mdl-js-button mdl-js-ripple-effect", true)
        .text("Read More");

  if (variable == "Sleep") {
    graphSleepData();
  } else if (variable == "Weight") {
    makeGraph(weight_data, "#Weight-graph", .8);
  }
}

function getWeight() {
  // 2. Initialize the JavaScript client library.
  gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources?dataTypeName=com.google.weight")
    .then(function(response) {
      weight_sources = response.result;
      idlist = [];
      for (el in weight_sources.dataSource){
        streamId = weight_sources.dataSource[el].dataStreamId;
        if (streamId == "derived:com.google.weight:com.google.android.gms:merge_weight") {
          idlist = [streamId];
          break;
        } else {
          idlist.push(streamId);
        }
      }
      Promise.all(idlist.map(getDataFromStream)).then(function(values){
        var data = extractDataFromStreams(values);
        for (el in data) {
          // Extract data from JSON object and convert kg to pounds
          data[el] = [new Date(+data[el].endTimeNanos/1000000), data[el].value[0].fpVal*2.20462];
        }
        weight_data = data;
      });
  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
};

function loadData() {
  // d3.selectAll(".getdata").classed("disabled", false);
  getWeight();
  getActivity()
}

function loadGapi() {
  gapi.load('client', loadData);
};

function getDataFromStream(streamId) {
  console.log("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
  return gapi.client.request("https://www.googleapis.com/fitness/v1/users/me/dataSources/"+streamId+"/datasets/0-"+CURR_TIME);
}

function getActivity(){

  var activity_data = gapi.client.request({
    "path" : "https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate",
    "method" : "POST",
    "body":{
      "aggregateBy": [
        {
          "dataTypeName": "com.google.activity.segment"
        }
      ],
      "endTimeMillis": Date.now(),
      "startTimeMillis": Date.now() - (30*DAY),
      "bucketByTime": {
        "period": {
          "type": "day",
          "value": 1,
          "timeZoneId": moment.tz.guess()
        }}
    }
  });
  activity_data.then(function(response){
    all_activity_data = response.result.bucket;
    graphSleepData();

  }, function(reason) {
    console.log('Error: ' + reason.result.error.message);
  });
}

function graphSleepData(){
  sleep_data = [];
  for (i in all_activity_data) {
    if (all_activity_data[i].dataset[0].point.length > 0) {
      console.log(true);
      sleep_data.push([new Date(+all_activity_data[i].dataset[0].point[0].startTimeNanos/1000000), 0]);
    }
    for (j in all_activity_data[i].dataset[0].point){
      if (SLEEP_NUMBERS.includes(+all_activity_data[i].dataset[0].point[j].value[0].intVal)) {
        sleep_data[sleep_data.length-1][1] += +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000;
      }
    }
  }
  makeGraph(sleep_data, "#Sleep-graph", .5);
}

function graphTotalActivityData(){
  data = [];
  for (i in all_activity_data) {
    for (j in all_activity_data[i].dataset[0].point){
      if (SLEEP_NUMBERS.includes(all_activity_data[i].dataset[0].point[j].value[0].intVal)) {
        data.push([new Date(+all_activity_data[i].dataset[0].point[j].startTimeNanos/1000000), +all_activity_data[i].dataset[0].point[j].value[1].intVal/3600000]);
      }
    }
  }
  makeGraph(data, "#Activity-graph", .5);
}

function extractDataFromStreams(streams) {
  var data = [];
  for (stream in streams) {
    var curr = streams[stream].result.point;
    if (curr.length > data.length) {
      data = curr;
    }
  }

  return data;
}

function toggleLabelYAxis() {
  $.ajax("http://www.stability-app.com/update_settings", {
      type:"POST",
      contentType:"application/json",
      data:JSON.stringify({"user":id_token, "value":true}),
      success:function() {alert("success");},
      error: function() {alert("failure");}
  });

  // var xmlHttp = new XMLHttpRequest();
  // xmlHttp.open( "POST", "http://stability-app.com/update_settings", true );
  // xmlHttp.send({"user":id_token, "value":true});
}

function makeGraph(data, svg_id, smoothing){
  // Based on https://github.com/jasondavies/science.js/blob/master/examples/loess/loess.js

  var id_without_hash = svg_id.slice(1, svg_id.length);

  var w = document.getElementById(id_without_hash).offsetWidth,
      h = 500,
      p = 35.5,
      n = 100;

  w -= 2*p; //margins need to come out of width

  var min_band = 2/data.length;

  var loess = science.stats.loess().bandwidth(d3.max([min_band, smoothing]));

  var zipped_data = d3.transpose(data);
  var loess_result = loess(zipped_data[0], zipped_data[1]);
  console.log("loess", loess_result);
  zipped_data[1] = loess_result.loess;
  zipped_data.push(loess_result.confint);
  data = d3.zip(zipped_data[0], zipped_data[1], zipped_data[2]);

  max_y = d3.max(data, function(d){return d[1]+d[2];});
  min_y = d3.min(data, function(d){return d[1]-d[2];});

  //Add margins
  max_y += max_y*.1
  min_y -= min_y*.1

  var x = d3.scaleTime().domain([new Date(data[0][0]-86400000), new Date(data[data.length-1][0]+86400000)]).range([0, w]);
  var y = d3.scaleLinear().domain([min_y, max_y]).range([h, 0]);

  var xAxis = d3.axisBottom(x),
      yAxis = d3.axisLeft(y);

  var vis = d3.select(svg_id)
    .append("svg")
      .attr("width", w + p + p)
      .attr("height", h + p + p)
    .append("g")
      .attr("transform", "translate(" + p + "," + p + ")");

  var area = d3.area()
        .x(function(d) { return x(d[0]); })
        .y0(function(d) { return d[2] ? y(d[1]-d[2]) : y(d[1]);})
        .y1(function(d) { return d[2] ? y(d[1]+d[2]) : y(d[1]);});

  vis.selectAll("path")
      .data([data])
    .enter().append("path")
      .attr("d", function(d){return area(d);})
      .attr("stroke", "black")
      .attr("fill", "purple")
      .attr("stroke-width", 1);

  vis.append("g")
      .attr("class", "bottom axis")
      .attr("transform", "translate(0," + h + ")")
      .call(xAxis);

  vis.append("g")
      .attr("class", "left axis")
      .call(yAxis);
}
<|endoftext|>


<commit_before>function start(){
	$("#gameover").hide();
	$("#gameWin").hide();
	hasWon = 0;
	devMode = 0;
	isRunning = 1;
	wood = 0;
	stone = 0;
	woodAdd = 1;
	stoneAdd = 1;
	food = 10;
	foodAdd = 10;
	population = 1;
	foodLossOn = 0;
	aiWoodOne = 100;
	aiStoneOne = 50;
	aiFoodOne = 200;
	aiPopOne = 10;
	aiOneRel = 100;
	$("#gamescreen").show();
}

function continueGame(){
	$("#gameWin").hide();
	$("#gamescreen").show();
	isRunning = 1;
	hasWon = 1;
}

var foodLossInterval = 0;

function update(){
	if(isRunning = 1){
		$("#gameover").hide();
		$("#gameWin").hide();

		$("#popText").text("Population: " + population);
		$("#foodText").text("Food: " + food);
		$("#stoneText").text("Stone: " + stone);
		$("#woodText").text("Wood: " + wood);
		if(foodLossInterval == 50){
			foodLossInterval = 0;
			if(population > food){
				population = population - 1;
			} else{
				food = food - population;
			}
			if(aiPopOne > aiFoodOne){
				aiPopOne = aiPopOne - 1;
			}else{
				aiFoodOne = aiFoodOne - aiPopOne;
			}
		}
		$("#aiWoodOneText").text("Wood: " + aiWoodOne);
		$("#aiStoneOneText").text("Stone: " + aiStoneOne);
		$("#aiFoodOneText").text("Food: " + aiFoodOne);
		if(devMode == 1){
			$("#aiPopOneText").show();
			$("#aiPopOneText").text("Population: " + aiPopOne);
		} else{
		$("#aiPopOneText").hide();
		}
		$("#aiOneRelText").text(aiOneRel + "% Relationship");
		checkLoss();
		checkWin();
	}
}
function foodLoss(){
	foodLossInterval++;
}<commit_msg>Update main.js<commit_after>function start(){
	$("#gameover").hide();
	$("#gameWin").hide();
	hasWon = 0;
	devMode = 0;
	isRunning = 1;
	wood = 0;
	stone = 0;
	woodAdd = 1;
	stoneAdd = 1;
	food = 10;
	foodAdd = 10;
	population = 1;
	foodLossOn = 0;
	aiWoodOne = 100;
	aiStoneOne = 50;
	aiFoodOne = 200;
	aiPopOne = 10;
	aiOneRel = 100;
	$("#gamescreen").show();
}

function continueGame(){
	$("#gameWin").hide();
	$("#gamescreen").show();
	isRunning = 1;
	hasWon = 1;
}

var foodLossInterval = 0;

function update(){
	if(isRunning = 1){
		$("#gameover").hide();
		$("#gameWin").hide();
		checkLoss();
		checkWin();
		$("#popText").text("Population: " + population);
		$("#foodText").text("Food: " + food);
		$("#stoneText").text("Stone: " + stone);
		$("#woodText").text("Wood: " + wood);
		if(foodLossInterval == 50){
			foodLossInterval = 0;
			if(population > food){
				population = population - 1;
			} else{
				food = food - population;
			}
			if(aiPopOne > aiFoodOne){
				aiPopOne = aiPopOne - 1;
			}else{
				aiFoodOne = aiFoodOne - aiPopOne;
			}
		}
		$("#aiWoodOneText").text("Wood: " + aiWoodOne);
		$("#aiStoneOneText").text("Stone: " + aiStoneOne);
		$("#aiFoodOneText").text("Food: " + aiFoodOne);
		if(devMode == 1){
			$("#aiPopOneText").show();
			$("#aiPopOneText").text("Population: " + aiPopOne);
		} else{
		$("#aiPopOneText").hide();
		}
		$("#aiOneRelText").text(aiOneRel + "% Relationship");
	}
}
function foodLoss(){
	foodLossInterval++;
}
<|endoftext|>