<commit_before>(function () {
    "use strict";
    angular.module("bestPlayerApp", [
        "ngMaterial",
        "eloRating",
        "players"
    ]);

    angular.module("bestPlayerApp").config(['$mdThemingProvider', function($mdThemingProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('blue-grey')
            .accentPalette('blue-grey')
            .warnPalette('deep-orange');
    }]);

    angular.module("bestPlayerApp").controller("AppCtrl", ["$scope", "$mdSidenav", function ($scope, $mdSidenav) {
        $scope.toggleSidenav = function (menuId) {
            $mdSidenav(menuId).toggle();
        };
    }]);

    angular.module("bestPlayerApp").directive("appContent", function () {

        var appContentDirectiveController = function ($scope, $http, $log, $mdSidenav, $mdToast, ratingService, playerService) {
            var self = this;

            self.games = [];
            self.players = [];
            self.loading = true;
            self.newGame = {};

            self.toggleTab = function () {
                $mdSidenav("left").toggle();
            };

            function getGames() {
                var stored = JSON.parse(localStorage.getItem("games"));
                return stored ? stored : [];
            }

            function saveGames(games) {
                localStorage.setItem("games", JSON.stringify(games));
                self.games = games;
            }

            function gameIsValid() {
                var valid = true;
                if (self.newGame.playerAName.length === 0) {
                    $log.error("player A name empty");
                    valid = false;
                }
                if (self.newGame.playerBName.length === 0) {
                    $log.error("player B name empty");
                    valid = false;
                }
                if (typeof(parseInt(self.newGame.scoreA)) !== "number") {
                    $log.error("player A score not a number");
                    valid = false;
                }
                if (typeof(parseInt(self.newGame.scoreB)) !== "number") {
                    $log.error("player B score not a number");
                    valid = false;
                }
                if (parseInt(self.newGame.scoreA) === parseInt(self.newGame.scoreB)) {
                    $log.error("player A score === player B score");
                    valid = false;
                }
                return valid;
            }

            self.save = function () {

                if (!gameIsValid()) {
                    return false;
                }

                var players = playerService.list();

                var playerA = null;
                var playerB = null;

                var playerAName = self.newGame.playerAName;
                var playerBName = self.newGame.playerBName;

                // search players in players
                playerA = playerService.findByName(playerAName);
                playerB = playerService.findByName(playerBName);

                // create players if required
                if (!playerA) {
                    playerA = playerService.add(playerAName);
                }
                if (!playerB) {
                    playerB = playerService.add(playerBName);
                }

                var ratingA = parseInt(playerA.rating);
                var ratingB = parseInt(playerB.rating);

                var scoreA = parseInt(self.newGame.scoreA);
                var scoreB = parseInt(self.newGame.scoreB);

                var scoreAForRating = parseInt(scoreA);
                var scoreBForRating = parseInt(scoreB);

                if (ratingService.scoreIsBool) {
                    var comp = parseInt(scoreA - scoreB);
                    scoreAForRating = (comp > 0) ? 1 : 0;
                    scoreBForRating = (comp < 0) ? 1 : 0;
                }

                var gamesCountA = playerA.gamesCount;
                var gamesCountB = playerB.gamesCount;

                var newRatings = ratingService.getNewRatings(
                    ratingA,
                    ratingB,
                    scoreAForRating,
                    scoreBForRating,
                    gamesCountA,
                    gamesCountB
                );

                playerA.rating = newRatings.newRatings.A;
                playerB.rating = newRatings.newRatings.B;

                var playerAExpectedVictory = (newRatings.expectedResult.A > newRatings.expectedResult.B);

                var d = new Date();
                var game = {
                    id: d.getTime(),
                    date: d,
                    playerAExpectedVictory: playerAExpectedVictory,
                    playerAVictory: (scoreA > scoreB),

                    playerAId: playerA.id,
                    playerAName: playerA.name,
                    scoreA: scoreA,
                    playerARatingBeforeGame: ratingA,
                    playerARatingAfterGame: playerA.rating,
                    playerAQuotation: Math.round((1/newRatings.expectedResult.A)*100)/100,

                    playerBId: playerB.id,
                    playerBName: playerB.name,
                    scoreB: scoreB,
                    playerBRatingBeforeGame: ratingB,
                    playerBRatingAfterGame: playerB.rating,
                    playerBQuotation: Math.round((1/newRatings.expectedResult.B)*100)/100
                };

                var gameLog = "Game [" + game.id + "], " + playerA.name + " [" + ratingA + "=>" + playerA.rating + "], "
                    + playerB.name + " [" + ratingB + "=>" + playerB.rating + "]";

                $log.debug(gameLog);

                $mdToast.show(
                    $mdToast.simple()
                        .content(gameLog)
                        .position("bottom right")
                        .hideDelay(5000)
                );

                // store game :
                var games = getGames();
                games.push(game);
                // save games
                saveGames(games);

                playerA.gamesCount += 1;
                playerB.gamesCount += 1;

                playerService.update(playerA);
                playerService.update(playerB);
                // udpate players list
                self.players = playerService.list();

                // reset :
                self.newGame = {};
                //self.setFakeValues();
            };

            self.setFakeValues = function () {
                var sA = Math.round((Math.random() * 10) / 2);
                var sB = Math.round((Math.random() * 10) / 2);
                if (sA === sB) sA += 1;

                var nA = Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 1).toUpperCase();
                var nB = Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 1).toUpperCase();

                // Nom des joueurs qui jouent beaucoup
                var mnA = "Stade Rennais";
                var mnB = "PSG";

                nA = nA.replace(/[J-Z]+/g, mnA);
                nB = nB.replace(/[J-Z]+/g, mnB);
                if (nA === nB) {
                    nA = mnA;
                    nB = mnB;
                }
                self.newGame = {
                    "playerAName": nA,
                    "scoreA": sA,
                    "scoreB": sB,
                    "playerBName": nB
                };
            };

            self.resetAll = function () {
                localStorage.setItem("games", "[]");
                localStorage.setItem("players", "[]");
                self.games = [];
                self.players = [];
            };

            self.loadAll = function () {
                self.games = getGames();
                self.players = playerService.list();
            };

            self.mockGames = function (count) {
                $scope.generating = true;
                var timer = "Mock " + count + " games";
                var start;
                var end;
                if(window.performance){
                    start = window.performance.now();
                }else{
                    var d1 = new Date();
                    start = d1.getTime();
                }
                console.time(timer);
                var initialCount = parseInt(self.games.length);
                while (self.games.length < (initialCount + count)) {
                    if (!self.playerAName) {
                        self.setFakeValues();
                    }
                    self.save();
                }
                console.timeEnd(timer);
                if(window.performance){
                    end = window.performance.now();
                }else{
                    var d2 = new Date();
                    end = d2.getTime();
                }

                $mdToast.show(
                    $mdToast.simple()
                        .content(count + " games in " + Math.round(end - start) + " ms.")
                        .position("bottom right")
                        .hideDelay(3000)
                );
                $scope.generating = false;

                //$log.info("games : " + self.games.length);
            }
        };

        var appContentLink = function (scope, element, attrs, controller) {
            controller.loadAll();
            //controller.setFakeValues();

            controller.show = "list";
            //console.log("appContent link executed");
            scope.mockAmount = 100;
        };
        return {
            templateUrl: "views/app-content.html",
            replace: true,
            controllerAs: "appContent",
            controller: ["$scope", "$http", "$log", "$mdSidenav", "$mdToast", "AdaptedEloRating", "simplePlayersService", appContentDirectiveController],
            link: appContentLink
        };
    });

})();<commit_msg>fix #16<commit_after>(function () {
    "use strict";
    angular.module("bestPlayerApp", [
        "ngMaterial",
        "eloRating",
        "players"
    ]);

    angular.module("bestPlayerApp").config(['$mdThemingProvider', function($mdThemingProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('blue-grey')
            .accentPalette('brown')
            .warnPalette('deep-orange');
    }]);

    angular.module("bestPlayerApp").controller("AppCtrl", ["$scope", "$mdSidenav", function ($scope, $mdSidenav) {
        $scope.toggleSidenav = function (menuId) {
            $mdSidenav(menuId).toggle();
        };
    }]);

    angular.module("bestPlayerApp").directive("appContent", function () {

        var appContentDirectiveController = function ($scope, $http, $log, $mdSidenav, $mdToast, ratingService, playerService) {
            var self = this;

            self.games = [];
            self.players = [];
            self.loading = true;
            self.newGame = {};

            self.toggleTab = function () {
                $mdSidenav("left").toggle();
            };

            function getGames() {
                var stored = JSON.parse(localStorage.getItem("games"));
                return stored ? stored : [];
            }

            function saveGames(games) {
                localStorage.setItem("games", JSON.stringify(games));
                self.games = games;
            }

            function gameIsValid() {
                var valid = true;
                if (self.newGame.playerAName.length === 0) {
                    $log.error("player A name empty");
                    valid = false;
                }
                if (self.newGame.playerBName.length === 0) {
                    $log.error("player B name empty");
                    valid = false;
                }
                if (typeof(parseInt(self.newGame.scoreA)) !== "number") {
                    $log.error("player A score not a number");
                    valid = false;
                }
                if (typeof(parseInt(self.newGame.scoreB)) !== "number") {
                    $log.error("player B score not a number");
                    valid = false;
                }
                if (parseInt(self.newGame.scoreA) === parseInt(self.newGame.scoreB)) {
                    $log.error("player A score === player B score");
                    valid = false;
                }
                return valid;
            }

            self.save = function () {

                if (!gameIsValid()) {
                    return false;
                }

                var players = playerService.list();

                var playerA = null;
                var playerB = null;

                var playerAName = self.newGame.playerAName;
                var playerBName = self.newGame.playerBName;

                // search players in players
                playerA = playerService.findByName(playerAName);
                playerB = playerService.findByName(playerBName);

                // create players if required
                if (!playerA) {
                    playerA = playerService.add(playerAName);
                }
                if (!playerB) {
                    playerB = playerService.add(playerBName);
                }

                var ratingA = parseInt(playerA.rating);
                var ratingB = parseInt(playerB.rating);

                var scoreA = parseInt(self.newGame.scoreA);
                var scoreB = parseInt(self.newGame.scoreB);

                var scoreAForRating = parseInt(scoreA);
                var scoreBForRating = parseInt(scoreB);

                if (ratingService.scoreIsBool) {
                    var comp = parseInt(scoreA - scoreB);
                    scoreAForRating = (comp > 0) ? 1 : 0;
                    scoreBForRating = (comp < 0) ? 1 : 0;
                }

                var gamesCountA = playerA.gamesCount;
                var gamesCountB = playerB.gamesCount;

                var newRatings = ratingService.getNewRatings(
                    ratingA,
                    ratingB,
                    scoreAForRating,
                    scoreBForRating,
                    gamesCountA,
                    gamesCountB
                );

                playerA.rating = newRatings.newRatings.A;
                playerB.rating = newRatings.newRatings.B;

                var playerAExpectedVictory = (newRatings.expectedResult.A > newRatings.expectedResult.B);

                var d = new Date();
                var game = {
                    id: d.getTime(),
                    date: d,
                    playerAExpectedVictory: playerAExpectedVictory,
                    playerAVictory: (scoreA > scoreB),

                    playerAId: playerA.id,
                    playerAName: playerA.name,
                    scoreA: scoreA,
                    playerARatingBeforeGame: ratingA,
                    playerARatingAfterGame: playerA.rating,
                    playerAQuotation: Math.round((1/newRatings.expectedResult.A)*100)/100,

                    playerBId: playerB.id,
                    playerBName: playerB.name,
                    scoreB: scoreB,
                    playerBRatingBeforeGame: ratingB,
                    playerBRatingAfterGame: playerB.rating,
                    playerBQuotation: Math.round((1/newRatings.expectedResult.B)*100)/100
                };

                var gameLog = "Game [" + game.id + "], " + playerA.name + " [" + ratingA + "=>" + playerA.rating + "], "
                    + playerB.name + " [" + ratingB + "=>" + playerB.rating + "]";

                $log.debug(gameLog);

                $mdToast.show(
                    $mdToast.simple()
                        .content(gameLog)
                        .position("bottom right")
                        .hideDelay(5000)
                );

                // store game :
                var games = getGames();
                games.push(game);
                // save games
                saveGames(games);

                playerA.gamesCount += 1;
                playerB.gamesCount += 1;

                playerService.update(playerA);
                playerService.update(playerB);
                // udpate players list
                self.players = playerService.list();

                // reset :
                self.newGame = {};
                //self.setFakeValues();
            };

            self.setFakeValues = function () {
                var sA = Math.round((Math.random() * 10) / 2);
                var sB = Math.round((Math.random() * 10) / 2);
                if (sA === sB) sA += 1;

                var nA = Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 1).toUpperCase();
                var nB = Math.random().toString(36).replace(/[^a-z]+/g, "").substr(0, 1).toUpperCase();

                // Nom des joueurs qui jouent beaucoup
                var mnA = "Stade Rennais";
                var mnB = "PSG";

                nA = nA.replace(/[J-Z]+/g, mnA);
                nB = nB.replace(/[J-Z]+/g, mnB);
                if (nA === nB) {
                    nA = mnA;
                    nB = mnB;
                }
                self.newGame = {
                    "playerAName": nA,
                    "scoreA": sA,
                    "scoreB": sB,
                    "playerBName": nB
                };
            };

            self.resetAll = function () {
                localStorage.setItem("games", "[]");
                localStorage.setItem("players", "[]");
                self.games = [];
                self.players = [];
            };

            self.loadAll = function () {
                self.games = getGames();
                self.players = playerService.list();
            };

            self.mockGames = function (count) {
                $scope.generating = true;
                var timer = "Mock " + count + " games";
                var start;
                var end;
                if(window.performance){
                    start = window.performance.now();
                }else{
                    var d1 = new Date();
                    start = d1.getTime();
                }
                console.time(timer);
                var initialCount = parseInt(self.games.length);
                while (self.games.length < (initialCount + count)) {
                    if (!self.playerAName) {
                        self.setFakeValues();
                    }
                    self.save();
                }
                console.timeEnd(timer);
                if(window.performance){
                    end = window.performance.now();
                }else{
                    var d2 = new Date();
                    end = d2.getTime();
                }

                $mdToast.show(
                    $mdToast.simple()
                        .content(count + " games in " + Math.round(end - start) + " ms.")
                        .position("bottom right")
                        .hideDelay(3000)
                );
                $scope.generating = false;

                //$log.info("games : " + self.games.length);
            }
        };

        var appContentLink = function (scope, element, attrs, controller) {
            controller.loadAll();
            //controller.setFakeValues();

            controller.show = "list";
            //console.log("appContent link executed");
            scope.mockAmount = 100;
        };
        return {
            templateUrl: "views/app-content.html",
            replace: true,
            controllerAs: "appContent",
            controller: ["$scope", "$http", "$log", "$mdSidenav", "$mdToast", "AdaptedEloRating", "simplePlayersService", appContentDirectiveController],
            link: appContentLink
        };
    });

})();<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var Websocket = require('ws');
var util = require('util');
var _  = {assign: require('lodash.assign')};
var signRequest = require('../../lib/request_signer').signRequest;

/**
 * Create a new connection to a websocket feed
 * @param productID {string} Options. The GDAX product to connect to. Default: 'BTC-USD'
 * @param websocketURI {string} Optional. The websocker URL. Default: The official GDAX feed.
 * @param auth {object} Optional. An object containing your API ket details (key, secret & passphrase)
 */
var WebsocketClient = function(productID, websocketURI, auth) {
  var self = this;
  self.productID = productID || 'BTC-USD';
  self.websocketURI = websocketURI || 'wss://ws-feed.gdax.com';
  if (auth && !(auth.secret && auth.key && auth.passphrase)) {
    throw new Error('Invalid or incomplete authentication credentials. You should either provide all of the secret, key and passphrase fields, or leave auth null');
  }
  self.auth = auth || {};
  EventEmitter.call(self);
  self.connect();
};

util.inherits(WebsocketClient, EventEmitter);

_.assign(WebsocketClient.prototype, new function() {
  var prototype = this;

  prototype.connect = function() {
    var self = this;

    if (self.socket) {
      self.socket.close();
    }

    self.socket = new Websocket(self.websocketURI);

    self.socket.on('message', self.onMessage.bind(self));
    self.socket.on('open', self.onOpen.bind(self));
    self.socket.on('close', self.onClose.bind(self));
  };

  prototype.disconnect = function() {
    var self = this;

    if (!self.socket) {
      throw "Could not disconnect (not connected)"
    }

    self.socket.close();
  };

  prototype.onOpen = function() {
    var self = this;
    self.emit('open');
    var sig = signRequest(self.auth, 'GET', '/users/self');

    var subscribeMessage = {
      type: 'subscribe',
      product_id: self.productID,
      signature: sig.signature,
      key: sig.key,
      passphrase: sig.passphrase,
      timestamp: sig.timestamp
    };
    self.socket.send(JSON.stringify(subscribeMessage));

    // Set a 30 second ping to keep connection alive
    self.pinger = setInterval(function() {
      self.socket.ping("keepalive");
    }, 30000);

  };

  prototype.onClose = function() {
    var self = this;
    clearInterval(self.pinger);
    self.socket = null;
    self.emit('close');
  };

  prototype.onMessage = function(data) {
    var self = this;
    self.emit('message', JSON.parse(data));
  };

});
module.exports = exports = WebsocketClient;
<commit_msg>fix: Sign websocket 'subscribe' only if auth is given<commit_after>var EventEmitter = require('events').EventEmitter;
var Websocket = require('ws');
var util = require('util');
var _  = {assign: require('lodash.assign')};
var signRequest = require('../../lib/request_signer').signRequest;

/**
 * Create a new connection to a websocket feed
 * @param productID {string} Options. The GDAX product to connect to. Default: 'BTC-USD'
 * @param websocketURI {string} Optional. The websocker URL. Default: The official GDAX feed.
 * @param auth {object} Optional. An object containing your API ket details (key, secret & passphrase)
 */
var WebsocketClient = function(productID, websocketURI, auth) {
  var self = this;
  self.productID = productID || 'BTC-USD';
  self.websocketURI = websocketURI || 'wss://ws-feed.gdax.com';
  if (auth && !(auth.secret && auth.key && auth.passphrase)) {
    throw new Error('Invalid or incomplete authentication credentials. You should either provide all of the secret, key and passphrase fields, or leave auth null');
  }
  self.auth = auth || {};
  EventEmitter.call(self);
  self.connect();
};

util.inherits(WebsocketClient, EventEmitter);

_.assign(WebsocketClient.prototype, new function() {
  var prototype = this;

  prototype.connect = function() {
    var self = this;

    if (self.socket) {
      self.socket.close();
    }

    self.socket = new Websocket(self.websocketURI);

    self.socket.on('message', self.onMessage.bind(self));
    self.socket.on('open', self.onOpen.bind(self));
    self.socket.on('close', self.onClose.bind(self));
  };

  prototype.disconnect = function() {
    var self = this;

    if (!self.socket) {
      throw "Could not disconnect (not connected)"
    }

    self.socket.close();
  };

  prototype.onOpen = function() {
    var self = this;
    self.emit('open');

    var subscribeMessage = {
      type: 'subscribe',
      product_id: self.productID
    };

    // Add Signature
    if (self.auth.secret) {
      var sig = signRequest(self.auth, 'GET', '/users/self');
      subscribeMessage.signature = sig.signature
      subscribeMessage.key = sig.key
      subscribeMessage.passphrase = sig.passphrase
      subscribeMessage.timestamp = sig.timestamp
    }

    self.socket.send(JSON.stringify(subscribeMessage));

    // Set a 30 second ping to keep connection alive
    self.pinger = setInterval(function() {
      self.socket.ping("keepalive");
    }, 30000);

  };

  prototype.onClose = function() {
    var self = this;
    clearInterval(self.pinger);
    self.socket = null;
    self.emit('close');
  };

  prototype.onMessage = function(data) {
    var self = this;
    self.emit('message', JSON.parse(data));
  };

});
module.exports = exports = WebsocketClient;
<|endoftext|>


<commit_before>// Initialize the Phaser Game object and set default game window size
const game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
  preload: preload,
  create: create,
  update: update })

// Declare shared variables at the top so all methods can access them
let score = 0
let scoreText
let platforms
let diamonds
let cursors
let player

function preload () {
  // Load & Define our game assets
  game.load.image('sky', 'sky.png')
  game.load.image('ground', 'platform.png')
  game.load.image('diamond', 'diamond.png')
  game.load.spritesheet('woof', 'woof.png', 32, 32)
}

function create () {
    //  We're going to be using physics, so enable the Arcade Physics system
  game.physics.startSystem(Phaser.Physics.ARCADE)

    //  A simple background for our game
  game.add.sprite(0, 0, 'sky')

    //  The platforms group contains the ground and the 2 ledges we can jump on
  platforms = game.add.group()

    //  We will enable physics for any object that is created in this group
  platforms.enableBody = true

    // Here we create the ground.
  let ground = platforms.create(0, game.world.height - 64, 'ground')

    //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
  ground.scale.setTo(2, 2)

    //  This stops it from falling away when you jump on it
  ground.body.immovable = true

    //  Now let's create two ledges
  let ledge = platforms.create(400, 450, 'ground')
  ledge.body.immovable = true

  ledge = platforms.create(-75, 350, 'ground')
  ledge.body.immovable = true

    // The player and its settings
  player = game.add.sprite(32, game.world.height - 150, 'woof')

    //  We need to enable physics on the player
  game.physics.arcade.enable(player)

    //  Player physics properties. Give the little guy a slight bounce.
  player.body.bounce.y = 0.2
  player.body.gravity.y = 800
  player.body.collideWorldBounds = true

    //  Our two animations, walking left and right.
  player.animations.add('left', [0, 1], 10, true)
  player.animations.add('right', [2, 3], 10, true)

    //  Finally some diamonds to collect
  diamonds = game.add.group()

    //  Enable physics for any object that is created in this group
  diamonds.enableBody = true

    //  Create 12 diamonds evenly spaced apart
  for (var i = 0; i < 12; i++) {
    let diamond = diamonds.create(i * 70, 0, 'diamond')

      //  Drop em from the sky and bounce a bit
    diamond.body.gravity.y = 1000
    diamond.body.bounce.y = 0.3 + Math.random() * 0.2
  }

    //  Create the score text
  scoreText = game.add.text(16, 16, '', { fontSize: '32px', fill: '#000' })

    //  And bootstrap our controls
  cursors = game.input.keyboard.createCursorKeys()
}

function update () {
    //  We want the player to stop when not moving
  player.body.velocity.x = 0

    //  Setup collisions for the player, diamonds, and our platforms
  game.physics.arcade.collide(player, platforms)
  game.physics.arcade.collide(diamonds, platforms)

    //  Call callectionDiamond() if player overlaps with a diamond
  game.physics.arcade.overlap(player, diamonds, collectDiamond, null, this)

    // Configure the controls!
  if (cursors.left.isDown) {
    player.body.velocity.x = -150

    player.animations.play('left')
  } else if (cursors.right.isDown) {
    player.body.velocity.x = 150

    player.animations.play('right')
  } else {
    // If no movement keys are pressed, stop the player
    player.animations.stop()
  }

    //  This allows the player to jump!
  if (cursors.up.isDown && player.body.touching.down) {
    player.body.velocity.y = -400
  }
    // Show an alert modal when score reaches 120
  if (score === 120) {
    alert('You win!')
    score = 0
  }
}

function collectDiamond (player, diamond) {
    // Removes the diamond from the screen
  diamond.kill()

    //  And update the score
  score += 10
  scoreText.text = 'Score: ' + score
}
<commit_msg>linted indentation<commit_after>// Initialize the Phaser Game object and set default game window size
const game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
  preload: preload,
  create: create,
  update: update })

// Declare shared variables at the top so all methods can access them
let score = 0
let scoreText
let platforms
let diamonds
let cursors
let player

function preload () {
  // Load & Define our game assets
  game.load.image('sky', 'sky.png')
  game.load.image('ground', 'platform.png')
  game.load.image('diamond', 'diamond.png')
  game.load.spritesheet('woof', 'woof.png', 32, 32)
}

function create () {
  //  We're going to be using physics, so enable the Arcade Physics system
  game.physics.startSystem(Phaser.Physics.ARCADE)

  //  A simple background for our game
  game.add.sprite(0, 0, 'sky')

  //  The platforms group contains the ground and the 2 ledges we can jump on
  platforms = game.add.group()

  //  We will enable physics for any object that is created in this group
  platforms.enableBody = true

  // Here we create the ground.
  let ground = platforms.create(0, game.world.height - 64, 'ground')

  //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
  ground.scale.setTo(2, 2)

  //  This stops it from falling away when you jump on it
  ground.body.immovable = true

  //  Now let's create two ledges
  let ledge = platforms.create(400, 450, 'ground')
  ledge.body.immovable = true

  ledge = platforms.create(-75, 350, 'ground')
  ledge.body.immovable = true

  // The player and its settings
  player = game.add.sprite(32, game.world.height - 150, 'woof')

  //  We need to enable physics on the player
  game.physics.arcade.enable(player)

  //  Player physics properties. Give the little guy a slight bounce.
  player.body.bounce.y = 0.2
  player.body.gravity.y = 800
  player.body.collideWorldBounds = true

  //  Our two animations, walking left and right.
  player.animations.add('left', [0, 1], 10, true)
  player.animations.add('right', [2, 3], 10, true)

  //  Finally some diamonds to collect
  diamonds = game.add.group()

  //  Enable physics for any object that is created in this group
  diamonds.enableBody = true

  //  Create 12 diamonds evenly spaced apart
  for (var i = 0; i < 12; i++) {
    let diamond = diamonds.create(i * 70, 0, 'diamond')

    //  Drop em from the sky and bounce a bit
    diamond.body.gravity.y = 1000
    diamond.body.bounce.y = 0.3 + Math.random() * 0.2
  }

  //  Create the score text
  scoreText = game.add.text(16, 16, '', { fontSize: '32px', fill: '#000' })

  //  And bootstrap our controls
  cursors = game.input.keyboard.createCursorKeys()
}

function update () {
  //  We want the player to stop when not moving
  player.body.velocity.x = 0

  //  Setup collisions for the player, diamonds, and our platforms
  game.physics.arcade.collide(player, platforms)
  game.physics.arcade.collide(diamonds, platforms)

  //  Call callectionDiamond() if player overlaps with a diamond
  game.physics.arcade.overlap(player, diamonds, collectDiamond, null, this)

  // Configure the controls!
  if (cursors.left.isDown) {
    player.body.velocity.x = -150

    player.animations.play('left')
  } else if (cursors.right.isDown) {
    player.body.velocity.x = 150

    player.animations.play('right')
  } else {
    // If no movement keys are pressed, stop the player
    player.animations.stop()
  }

  //  This allows the player to jump!
  if (cursors.up.isDown && player.body.touching.down) {
    player.body.velocity.y = -400
  }
  // Show an alert modal when score reaches 120
  if (score === 120) {
    alert('You win!')
    score = 0
  }
}

function collectDiamond (player, diamond) {
  // Removes the diamond from the screen
  diamond.kill()

  //  And update the score
  score += 10
  scoreText.text = 'Score: ' + score
}
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const handlebars = require('handlebars')
const { pathToRegexp } = require('path-to-regexp')
const swaggerUi = require('swagger-ui-express')

const view = handlebars.compile(
    fs.readFileSync(__dirname + '/sitemap.hbs').toString())

handlebars.registerHelper('includes', (arr, word) => arr.includes(word))

/**
 * Exports a function that builds a middleware to render an HTML sitemap
 * for an express application.
 * This function also has a property parseRoutes, which is a function
 * that returns an array of Endpoint objects for a given express app.
 */
module.exports = sitemap
sitemap.parseRoutes = parseRoutes
sitemap.swaggerJson = swaggerJson
sitemap.swagger = swagger

const swaggerDocument = {
    'openapi': '3.0.0',
    'paths': {}
}

/**
 * @param {String} name Name to group endpoints on same tag.
 * @param {Express} app An express instance
 */
function swagger(name, app) {
    app.use('/api-docs', swaggerUi.serve)
    app.get('/api-docs', swaggerUi.setup(swaggerJson(name, app)))
}

/**
 * @param {String} name Name to group endpoints on same tag.
 * @param {Express} app An express instance
 */
function swaggerJson(name, app) {
    const routes = swaggerRoutes(app)
    routes
        .forEach(r => {
            swaggerDocument.paths[r.path] = {}
            r.methods.split(' ').forEach(verb => {
                swaggerDocument.paths[r.path][verb] = {
                    'tags': [name],
                    'parameters': [],
                    'responses': {}
                }
                r.keys.forEach(arg => swaggerDocument.paths[r.path][verb].parameters.push({
                    'in': 'path',
                    'name': arg.name,
                    'required': 'true'
                }))
            })
        })
    return swaggerDocument
}

/**
 * @param {Express} app An express instance
 */
function swaggerRoutes(app) {
    const endpoints = parseRoutes(app)
    endpoints
        .forEach(route => {
            const keys = []
            pathToRegexp(route.path, keys)
            route.keys = keys
            if(keys.length == 0) return
            keys.forEach(arg => route.path = route.path.replace(`:${arg.name}`, `{${arg.name}}`))
        })
    return endpoints
}

/**
 * Builds an express middleware that renders an HTML sitemap based
 * on the routes of app parameter.
 * @param {Express} app An express instance
 */
function sitemap(app) {
    let html
    return (req, res) => {
        if(!html) html = view(parseRoutes(app))
        res.set({
            'Content-Type': 'text/html',
            'Content-Length': html.length
        })
        res.send(html)
    }
}

/**
 * Returns an array of Endpoint objects containing: the methods; and
 * the path for each route of app parameter.
 * @param {Express} app An express instance.
 * @returns {Array<Endpoint>} An array of Enpoint objects
 */
function parseRoutes(app) {
    const routes = parseStack('', app._router.stack)
    routes.forEach(r => {
        if(!r.path.startsWith('/')) r.path = '/' + r.path
    })
    return routes
}

/**
 * @param {String} prev The path of the parent route containing the stack parameter.
 * @return {Array<Endpoint>} stack An  array of express routes.
 */
function parseStack(prev, stack) {
    const routes = stack
        .map(item => {
            if(item.route) return buildEndpoint(prev, item.route)
            const next = buildPrev(prev, item.regexp, item.path)
            if(item.handle && item.handle.stack)
                return parseStack(next, item.handle.stack)
            return next == ''? undefined : new Endpoint('get', next)
        })
        .filter(item => item != undefined)
        .reduce(concat, [])
        .groupBy('path')

    return Object
        .keys(routes)
        .map(k => {
            const methods = routes[k].map(ep => ep.methods).join(' ')
            return new Endpoint(methods, k)
        })
}

function buildEndpoint(prev, route) {
    const methods = route.methods
    return new Endpoint(
        Object.keys(methods).join(' '),
        prev + route.path)
}

/**
 * @typedef Endpoint
 * @property {String} methods The HTTP methods available for the path of this endpoint.
 * @property {String} path The path for this endpoint.
 */
class Endpoint {
    constructor(methods, path) {
        this.methods = methods
        this.path = path
    }
}

function buildPrev(prev, regexp, path) {
    if(path) return prev + path
    regexp = regexp.toString().replace('/^\\/', '')
    regexp = regexp.replace('?(?=\\/|$)/i', '')
    regexp = regexp.replace('\\/', '')
    regexp = regexp.replace('/^', '')
    return prev + regexp
}

function concat(arr, curr){
    if(curr instanceof Array) return arr.concat(curr)
    arr.push(curr)
    return arr
}

Array.prototype.groupBy = function(key) {
    return this.reduce((rv, x) => {
        (rv[x[key]] = rv[x[key]] || []).push(x)
        return rv
    }, {})
}<commit_msg>Little refactoring typedefs for Swagger elements.<commit_after>'use strict'

const fs = require('fs')
const handlebars = require('handlebars')
const { pathToRegexp } = require('path-to-regexp')
const swaggerUi = require('swagger-ui-express')

const view = handlebars.compile(
    fs.readFileSync(__dirname + '/sitemap.hbs').toString())

handlebars.registerHelper('includes', (arr, word) => arr.includes(word))

/**
 * Exports a function that builds a middleware to render an HTML sitemap
 * for an express application.
 * This function also has properties:
 *   * parseRoutes() - a function that returns an array of Endpoint objects for a
 *     given express app.
 *   * swaggerJson() - a function that return an Open API specification for an
 *     express instance.
 *   * swagger() - a function that installs two middleware handlers on app express
 *     instance to provide a swagger UI for all routes of that app.
 */
module.exports = sitemap
sitemap.parseRoutes = parseRoutes
sitemap.swaggerJson = swaggerJson
sitemap.swagger = swagger

/**
 * @param {String} name Name to group endpoints on same tag.
 * @param {Express} app An express instance
 */
function swagger(name, app) {
    app.use('/api-docs', swaggerUi.serve)
    app.get('/api-docs', swaggerUi.setup(swaggerJson(name, app)))
}

/**
 * @param {String} name Name to group endpoints on same tag.
 * @param {Express} app An express instance
 */
function swaggerJson(name, app) {
    const routes = swaggerRoutes(app)
    const swaggerDocument = {
        'openapi': '3.0.0',
        'paths': {}
    }
    routes
        .forEach(r => {
            swaggerDocument.paths[r.path] = {}
            r.methods.split(' ').forEach(verb => {
                const pathMethod = swaggerPathMethod(name)
                swaggerDocument.paths[r.path][verb] = pathMethod
                r.keys.forEach(arg => pathMethod.parameters.push(swaggerPathParam(arg.name)))
            })
        })
    return swaggerDocument
}

/**
 * @param {Express} app An express instance
 */
function swaggerRoutes(app) {
    const endpoints = parseRoutes(app)
    endpoints
        .forEach(route => {
            const keys = []
            pathToRegexp(route.path, keys)
            route.keys = keys
            if(keys.length == 0) return
            keys.forEach(arg => route.path = route.path.replace(`:${arg.name}`, `{${arg.name}}`))
        })
    return endpoints
}

/**
 * Builds an express middleware that renders an HTML sitemap based
 * on the routes of app parameter.
 * @param {Express} app An express instance
 */
function sitemap(app) {
    let html
    return (req, res) => {
        if(!html) html = view(parseRoutes(app))
        res.set({
            'Content-Type': 'text/html',
            'Content-Length': html.length
        })
        res.send(html)
    }
}

/**
 * Returns an array of Endpoint objects containing: the methods; and
 * the path for each route of app parameter.
 * @param {Express} app An express instance.
 * @returns {Array<Endpoint>} An array of Enpoint objects
 */
function parseRoutes(app) {
    const routes = parseStack('', app._router.stack)
    routes.forEach(r => {
        if(!r.path.startsWith('/')) r.path = '/' + r.path
    })
    return routes
}

/**
 * @param {String} prev The path of the parent route containing the stack parameter.
 * @return {Array<Endpoint>} stack An  array of express routes.
 */
function parseStack(prev, stack) {
    const routes = stack
        .map(item => {
            if(item.route) return buildEndpoint(prev, item.route)
            const next = buildPrev(prev, item.regexp, item.path)
            if(item.handle && item.handle.stack)
                return parseStack(next, item.handle.stack)
            return next == ''? undefined : new Endpoint('get', next)
        })
        .filter(item => item != undefined)
        .reduce(concat, [])
        .groupBy('path')

    return Object
        .keys(routes)
        .map(k => {
            const methods = routes[k].map(ep => ep.methods).join(' ')
            return new Endpoint(methods, k)
        })
}

function buildEndpoint(prev, route) {
    const methods = route.methods
    return new Endpoint(
        Object.keys(methods).join(' '),
        prev + route.path)
}

/**
 * @typedef Endpoint
 * @property {String} methods The HTTP methods available for the path of this endpoint.
 * @property {String} path The path for this endpoint.
 */
class Endpoint {
    constructor(methods, path) {
        this.methods = methods
        this.path = path
    }
}

/**
 * @typedef SwaggerPathMethod
 * @property {Array<String>} tags
 * @property {Array} parameters
 * @property {Array} responses
 */
function swaggerPathMethod(tag) {
    return {
        'tags': [tag],
        'parameters': [],
        'responses': {}
    }
}

/**
 * @typedef SwaggerPathParam
 * @property {String} in
 * @property {String} name
 * @property {Boolean} required
 */
function swaggerPathParam(name) {
    return {
        'in': 'path',
        'name': name,
        'required': 'true'
    }
}

function buildPrev(prev, regexp, path) {
    if(path) return prev + path
    regexp = regexp.toString().replace('/^\\/', '')
    regexp = regexp.replace('?(?=\\/|$)/i', '')
    regexp = regexp.replace('\\/', '')
    regexp = regexp.replace('/^', '')
    return prev + regexp
}

function concat(arr, curr){
    if(curr instanceof Array) return arr.concat(curr)
    arr.push(curr)
    return arr
}

Array.prototype.groupBy = function(key) {
    return this.reduce((rv, x) => {
        (rv[x[key]] = rv[x[key]] || []).push(x)
        return rv
    }, {})
}<|endoftext|>


<commit_before>var pkg = require('../package.json');
var fs = require('fs');
var versionFile = __dirname + '/../dist/commit';

module.exports = {
  ngVersion: '1.4.1',
  version: pkg.version,
  repository: pkg.repository.url
    .replace(/^git/,'https')
    .replace(/(\.git)?\/?$/,'')
};
<commit_msg>update(docs): rolls back to Angular v1.3.15 until v1.4.2 is released<commit_after>var pkg = require('../package.json');
var fs = require('fs');
var versionFile = __dirname + '/../dist/commit';

module.exports = {
  ngVersion: '1.3.15',
  version: pkg.version,
  repository: pkg.repository.url
    .replace(/^git/,'https')
    .replace(/(\.git)?\/?$/,'')
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import EmberUploader from 'ember-uploader';
var inject = Ember.inject;

export default Ember.Controller.extend({
    store: Ember.inject.service(),
    apiCall: Ember.inject.service('api-call'),
    taleInstanceName: "",
    init() {
        this.set("tale_instantiated", false);
        scroll(0, 0);
    },
    didInsertElement() {
        console.log("Controller didUpdate hook is called from nested tale 'view'");
    },
    modelObserver: Ember.observer("model", function(sender, key, value) {
        console.log("Controller model hook is called from nested tale 'view'");
        var model = this.get('model');
        // convert config json to a string for editing.
        // model.set('config', JSON.stringify(model.get('config')));
        console.log(model.get('config'));
    }),
    actions: {
        updateTale: function() {

            var component = this;

            component.set("tale_creating", true);

            var onSuccess = function(item) {
                component.set("tale_creating", false);
                component.set("tale_created", true);

                Ember.run.later((function() {
                    component.set("tale_created", false);
                    // component.transitionToRoute('upload.view', item);
                }), 10000);
            };

            var onFail = function(e) {
                // deal with the failure here
                component.set("tale_creating", false);
                component.set("tale_not_created", true);
                item = JSON.parse(item);
                component.set("error_msg", e.message);
                console.log(e);

                Ember.run.later((function() {
                    component.set("tale_not_created", false);
                }), 10000);

            };

            var tale = this.get("model");
            tale.save().then(onSuccess).catch(onFail);
        },
        launchTale: function() {
            var component = this;

            component.set("tale_instantiating", true);

            var onSuccess = function(item) {
                console.log(item);
                component.set("tale_instantiating", false);
                component.set("tale_instantiated", true);

                var instance = Ember.Object.create(JSON.parse(item));

                component.set("instance", instance);

                Ember.run.later((function() {
                    component.set("tale_instantiated", false);
                }), 30000);
            };

            var onFail = function(item) {
                // deal with the failure here
                component.set("tale_instantiating", false);
                component.set("tale_not_instantiated", true);
                item = JSON.parse(item);

                console.log(item);
                component.set("error_msg", item.message);

                Ember.run.later((function() {
                    component.set("tale_not_instantiated", false);
                }), 10000);

            };

            // submit: API
            // httpCommand, taleid, imageId, folderId, instanceId, name, description, isPublic, config

            var tale = this.get("model");

            this.get("apiCall").postInstance(
                tale.get("_id"),
                null,
                this.get('taleInstanceName'),
                onSuccess,
                onFail);
        },
        textUpdated: function(text) {
            // do something with

            console.log(this.get('model').get('description'));
        },
        back: function() {
            history.back();
        },
        openDeleteModal: function(id) {
            var selector = '.ui.' + id + '.modal';
            console.log("Selector: " + selector);
            $(selector).modal('show');
        },

        approveDelete: function(model) {
            console.log("Deleting model " + model.name);
            var component = this;

            model.destroyRecord({ reload: true }).then(function() {
                component.transitionToRoute('index');
            });

            return false;
        },

        denyDelete: function() {
            return true;
        },

        enableEditIcon() {
            let icon_uri_txt = Ember.$('#tale-icon');
            icon_uri_txt.prop("disabled", false);
            icon_uri_txt.focus();
        },

        generateIcon(model) {
            this.get('store').query('sils', { text: encodeURI(model.title) })
                .then(sils => {
                    sils.forEach(result => {
                        model.set('illustration', result.get('icon'));
                    })
                });
        }
    },

});<commit_msg>Fixed the other launch button<commit_after>import Ember from 'ember';
import EmberUploader from 'ember-uploader';
var inject = Ember.inject;

export default Ember.Controller.extend({
    store: Ember.inject.service(),
    apiCall: Ember.inject.service('api-call'),
    taleInstanceName: "",
    init() {
        this.set("tale_instantiated", false);
        scroll(0, 0);
    },
    didInsertElement() {
        console.log("Controller didUpdate hook is called from nested tale 'view'");
    },
    modelObserver: Ember.observer("model", function(sender, key, value) {
        console.log("Controller model hook is called from nested tale 'view'");
        var model = this.get('model');
        // convert config json to a string for editing.
        // model.set('config', JSON.stringify(model.get('config')));
        console.log(model.get('config'));
    }),
    actions: {
        updateTale: function() {

            var component = this;

            component.set("tale_creating", true);

            var onSuccess = function(item) {
                component.set("tale_creating", false);
                component.set("tale_created", true);

                Ember.run.later((function() {
                    component.set("tale_created", false);
                    // component.transitionToRoute('upload.view', item);
                }), 10000);
            };

            var onFail = function(e) {
                // deal with the failure here
                component.set("tale_creating", false);
                component.set("tale_not_created", true);
                item = JSON.parse(item);
                component.set("error_msg", e.message);
                console.log(e);

                Ember.run.later((function() {
                    component.set("tale_not_created", false);
                }), 10000);

            };

            var tale = this.get("model");
            tale.save().then(onSuccess).catch(onFail);
        },
        launchTale: function() {
            var component = this;

            component.set("tale_instantiating", true);

            var onSuccess = function(item) {
                console.log(item);
                component.set("tale_instantiating", false);
                component.set("tale_instantiated", true);

                var instance = Ember.Object.create(JSON.parse(item));

                component.set("instance", instance);

                Ember.run.later((function() {
                    component.set("tale_instantiated", false);
                }), 30000);
            };

            var onFail = function(item) {
                // deal with the failure here
                component.set("tale_instantiating", false);
                component.set("tale_not_instantiated", true);
                item = JSON.parse(item);

                console.log(item);
                component.set("error_msg", item.message);

                Ember.run.later((function() {
                    component.set("tale_not_instantiated", false);
                }), 10000);

            };

            // submit: API
            // httpCommand, taleid, imageId, folderId, instanceId, name, description, isPublic, config

            var tale = this.get("model");

            this.get("apiCall").postInstance(
                tale.get("_id"),
                tale.get('imageId'),
                this.get('taleInstanceName'),
                onSuccess,
                onFail);
        },
        textUpdated: function(text) {
            // do something with

            console.log(this.get('model').get('description'));
        },
        back: function() {
            history.back();
        },
        openDeleteModal: function(id) {
            var selector = '.ui.' + id + '.modal';
            console.log("Selector: " + selector);
            $(selector).modal('show');
        },

        approveDelete: function(model) {
            console.log("Deleting model " + model.name);
            var component = this;

            model.destroyRecord({ reload: true }).then(function() {
                component.transitionToRoute('index');
            });

            return false;
        },

        denyDelete: function() {
            return true;
        },

        enableEditIcon() {
            let icon_uri_txt = Ember.$('#tale-icon');
            icon_uri_txt.prop("disabled", false);
            icon_uri_txt.focus();
        },

        generateIcon(model) {
            this.get('store').query('sils', { text: encodeURI(model.title) })
                .then(sils => {
                    sils.forEach(result => {
                        model.set('illustration', result.get('icon'));
                    })
                });
        }
    },

});<|endoftext|>


<commit_before>$(document).ready(function () {

  // game states
  var LOADING = 0;
  var READY = 1;
  var STARTED = 2;
  var SAFE = 3;
  var LOST = 4;
  var state = LOADING;

  // Enable pusher logging - don't include this in production
  Pusher.log = function (message) {
    if (window.console && window.console.log) {
      window.console.log(message);
    }
  };

  var pusher = new Pusher('054a6c871c383a05df7d', {
    encrypted: true,
  });

  var channel = pusher.subscribe('jsjoust-channel');

  channel.bind('join', function (data) {
    var joinGameLink = 'Join Game';
    $('h1').html(joinGameLink);
    $('.join-game').on('click', function (e) {
      e.preventDefault();
      console.log($(this).attr('data-game-db'));
      joinGame(data.gameDb);
    });
  });

  var joinGame = function (gameDB) {
    var api = '/keygen?user=' + gameDB;
    $.get(api, function (data) {
      localStorage.setItem('url', data.url);
      var url = data.url;
      var localDB = $('', { href: url })[0].pathname.substr(1);
      var gameDB = PouchDB(localDB);
      gameDB.sync(url, { live: true, retry: true }).on('change', function (info) {
        // handle change
        console.log(info);
      }).on('paused', function () {
        // replication paused (e.g. user went offline)
      }).on('active', function () {
        // replicate resumed (e.g. user went back online)
      }).on('denied', function (info) {
        // a document failed to replicate (e.g. due to permissions)
      }).on('complete', function (info) {
        // handle complete
      }).on('error', function (err) {
        // handle error
        console.log(err);
      });

      gameDB.put({
        _id: twitterUser + '_join',
        status: 'join',
        twitter: twitterUser,
        timestamp: Date.now(),
      }).then(function (response) {
        // handle response
        console.log('Everyone Informed of join');
        $('h1').html('Ready');
        state = READY;
      }).catch(function (err) {
        console.log(err);
      });

      console.log('Waiting for join/loss responses');
      var changes = gameDB.changes({
        live: true,
        retry: true,
        include_docs: true,
      }).on('change', function (change) {
        // handle change
        var username = change.doc.twitter;
        if (username) {
          var status   = change.doc.status;
          var $userItem = $('li[data-twitter="' + username + '"]');
          if ($userItem.length) {
            if (status !== 'join') {
              if (!$userItem.hasClass(status)) {
                $userItem.addClass(status);
                $userItem.removeClass('join');
              }
            }
          } else {
            var li = '
';
            li += '';
            li += '' + username + '';
            li += '
';
            $('ul#players').append(li);
          }
        }
      }).on('complete', function (info) {
        // changes() was canceled
        console.log('Change Cancelled');
      }).on('error', function (err) {
        console.log(err);
      });

      var playGame = function () {
        trackMotion();
        setInterval(function () { state = STARTED; }, 1000);
      };

      var trackMotion = function () {
        window.addEventListener('deviceorientation', function (e) {
          if (e.gamma !== null && state === STARTED) {
            // Get the distance
            var distance = Math.sqrt(
              Math.pow(Math.sin(2 * Math.PI * (e.gamma / 180)), 2) +
              Math.pow(Math.sin(2 * Math.PI * (e.alpha / 360)), 2) +
              Math.pow(Math.sin(2 * Math.PI * (e.beta / 360)), 2)
            );

            // Scale the distance
            distance = scale(distance);

            // Display the changes
            console.log(distance);
            $('body').css('background', colour(distance));

            // Knock you out
            if (tooFast(distance)) {
              endGame();
            }
          }
        });
      };

      // End Game
      var endGame = function () {
        // alert('lose');
        state = LOST;
        navigator.vibrate([3000, 2000, 1000]);
        gameDB.put({
          _id: twitterUser + '_lost',
          status: 'lost',
          twitter: twitterUser,
          timestamp: Date.now(),
        }).then(function (response) {
          // handle response
          console.log('Everyone Informed of loss');
          window.location.href = '/gameover/' + localDB;
        }).catch(function (err) {
          console.log(err);
        });
      };

      channel.bind('start-' + localDB, function (data) {
        console.log('Game On');
        playGame();
      });

      channel.bind('end-' + localDB, function (data) {
        console.log('Game Over');
        window.location.href = '/gameover/' + localDB;
      });

      channel.bind('safe-' + localDB, function (data) {
        console.log('You can move more');
        state = SAFE;
      });

      channel.bind('notsafe-' + localDB, function (data) {
        console.log('Ow Shit, stop moving!');
        state = STARTED;
      });
    });
  };

  // Scale result
  var scale = function scale(d) {
    return Math.min(1, d * 0.7);
  };

  // Return the Hue
  var hue = function (d) {
    return Math.floor((1 - d) * 120);
  };

  // Return a HSL colour
  var colour = function (d) {
    return 'hsl(' + hue(d) + ', 100%, 45%)';
  };

  // If you go to fast
  var tooFast = function tooFast(s) {
    return (s >= 1 && state !== SAFE) ? true : false;
  };
});
<commit_msg>Disable game if started<commit_after>$(document).ready(function () {

  // game states
  var LOADING = 0;
  var READY = 1;
  var STARTED = 2;
  var SAFE = 3;
  var LOST = 4;
  var state = LOADING;

  // Enable pusher logging - don't include this in production
  Pusher.log = function (message) {
    if (window.console && window.console.log) {
      window.console.log(message);
    }
  };

  var pusher = new Pusher('054a6c871c383a05df7d', {
    encrypted: true,
  });

  var channel = pusher.subscribe('jsjoust-channel');

  channel.bind('join', function (data) {
    var joinGameLink = 'Join Game';
    $('h1').html(joinGameLink);
    $('.join-game').on('click', function (e) {
      e.preventDefault();
      console.log($(this).attr('data-game-db'));
      joinGame(data.gameDb);
    });
  });

  var joinGame = function (gameDB) {
    var api = '/keygen?user=' + gameDB;
    $.get(api, function (data) {
      localStorage.setItem('url', data.url);
      var url = data.url;
      var localDB = $('', { href: url })[0].pathname.substr(1);
      var gameDB = PouchDB(localDB);
      gameDB.sync(url, { live: true, retry: true }).on('change', function (info) {
        // handle change
        console.log(info);
      }).on('paused', function () {
        // replication paused (e.g. user went offline)
      }).on('active', function () {
        // replicate resumed (e.g. user went back online)
      }).on('denied', function (info) {
        // a document failed to replicate (e.g. due to permissions)
      }).on('complete', function (info) {
        // handle complete
      }).on('error', function (err) {
        // handle error
        console.log(err);
      });

      gameDB.put({
        _id: twitterUser + '_join',
        status: 'join',
        twitter: twitterUser,
        timestamp: Date.now(),
      }).then(function (response) {
        // handle response
        console.log('Everyone Informed of join');
        $('h1').html('Ready');
        state = READY;
      }).catch(function (err) {
        console.log(err);
      });

      console.log('Waiting for join/loss responses');
      var changes = gameDB.changes({
        live: true,
        retry: true,
        include_docs: true,
      }).on('change', function (change) {
        // handle change
        var username = change.doc.twitter;
        if (username) {
          var status   = change.doc.status;
          var $userItem = $('li[data-twitter="' + username + '"]');
          if ($userItem.length) {
            if (status !== 'join') {
              if (!$userItem.hasClass(status)) {
                $userItem.addClass(status);
                $userItem.removeClass('join');
              }
            }
          } else {
            var li = '
';
            li += '';
            li += '' + username + '';
            li += '
';
            $('ul#players').append(li);
          }
        }
      }).on('complete', function (info) {
        // changes() was canceled
        console.log('Change Cancelled');
      }).on('error', function (err) {
        console.log(err);
      });

      var playGame = function () {
        trackMotion();
        setInterval(function () { state = STARTED; }, 1000);
      };

      var trackMotion = function () {
        window.addEventListener('deviceorientation', function (e) {
          if (e.gamma !== null && state === STARTED) {
            // Get the distance
            var distance = Math.sqrt(
              Math.pow(Math.sin(2 * Math.PI * (e.gamma / 180)), 2) +
              Math.pow(Math.sin(2 * Math.PI * (e.alpha / 360)), 2) +
              Math.pow(Math.sin(2 * Math.PI * (e.beta / 360)), 2)
            );

            // Scale the distance
            distance = scale(distance);

            // Display the changes
            console.log(distance);
            $('body').css('background', colour(distance));

            // Knock you out
            if (tooFast(distance)) {
              endGame();
            }
          }
        });
      };

      // End Game
      var endGame = function () {
        // alert('lose');
        state = LOST;
        navigator.vibrate([3000, 2000, 1000]);
        gameDB.put({
          _id: twitterUser + '_lost',
          status: 'lost',
          twitter: twitterUser,
          timestamp: Date.now(),
        }).then(function (response) {
          // handle response
          console.log('Everyone Informed of loss');
          window.location.href = '/gameover/' + localDB;
        }).catch(function (err) {
          console.log(err);
        });
      };

      channel.bind('start-' + localDB, function (data) {
        console.log('Game On');
        playGame();
        $('.join-game').addClass('disabled');
      });

      channel.bind('end-' + localDB, function (data) {
        console.log('Game Over');
        window.location.href = '/gameover/' + localDB;
      });

      channel.bind('safe-' + localDB, function (data) {
        console.log('You can move more');
        state = SAFE;
      });

      channel.bind('notsafe-' + localDB, function (data) {
        console.log('Ow Shit, stop moving!');
        state = STARTED;
      });
    });
  };

  // Scale result
  var scale = function scale(d) {
    return Math.min(1, d * 0.7);
  };

  // Return the Hue
  var hue = function (d) {
    return Math.floor((1 - d) * 120);
  };

  // Return a HSL colour
  var colour = function (d) {
    return 'hsl(' + hue(d) + ', 100%, 45%)';
  };

  // If you go to fast
  var tooFast = function tooFast(s) {
    return (s >= 1 && state !== SAFE) ? true : false;
  };
});
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

// tinymce doesn't like its plugins being async,
// all dependencies must export to window

define([
  'compiled/editor/stocktiny',
  'i18n!editor',
  'jquery',
  'str/htmlEscape',
  'quizzes_new',
  'i18n!account_homepage',
  // 'compiled/bundles/account_homepage',
  'jqueryui/dialog',
  'jquery.form',
  'jquery.instructure_misc_helpers'

], function(tinymce, I18n, $, htmlEscape) {
  var $box, $editor, $userURL, $altText, $actions, $flickrLink;

  var initted = false;

  var TRANSLATIONS = {
    click_to_embed: I18n.t('click_to_embed', 'Click to embed the image'),
    instructions: INST.htmlEscape(I18n.t('instructions', "Paste or type the URL of the image you'd like to embed:")),
    url: INST.htmlEscape(I18n.t('url', 'URL:')),
    alt_text: INST.htmlEscape(I18n.t('alt_text', 'Alternate Text:')),
    search_flickr: I18n.t('search_flickr', 'Search flickr creative commons'),
    loading: I18n.t('loading', 'Loading...'),
    embed_external: I18n.t('embed_external', 'Embed External Image'),
    embed_image: INST.htmlEscape(I18n.t('embed_image', 'Embed Image')),
    image_not_found: I18n.t('image_not_found', 'Image not found, please try a new URL')
  };

  function initShared () {
    $box = $('
', {html: TRANSLATIONS.instructions + "<form id='instructure_embed_prompt_form'>

"+ TRANSLATIONS.url +"	<input type='text' class='prompt' value='http://'/>

"+TRANSLATIONS.alt_text+"	<input type='text' class='alt_text' value=''/>

	<input class='btn' type='submit' value=" + TRANSLATIONS.click_to_embed +  " />

</form>

"}).hide();

    $altText = $box.find('.alt_text');
    $actions = $box.find('.actions');
    $userURL = $box.find('.prompt');
    $flickrLink = $('', {
      'class': 'flickr_search_link',
      text: TRANSLATIONS.search_flickr,
      href: '#'
    });

    $userURL.bind('keyup', validateURL);
    $actions.delegate('.embed_image_link', 'click', embedURLImage);
    $flickrLink.click(flickrLinkClickHandler);
    $box.append($flickrLink).find('#instructure_embed_prompt_form').submit(embedURLImage);
    var accountId = ENV.current_user_id;
    var upload = "<form id='background_image_uploader' action='/accounts/" + accountId + "/files' method='POST' enctype='multipart/form-data' >" +
        "
" +
        "
" +
        "" +
        I18n.t('choose_a_picture', 'choose a picture:') +
        "	" +
        "" +
        "<input id='background_bg_image' name='attachment[uploaded_data]' type='file'>" +
        "	" +
        "
" +
        "
" +
        "" +
        "	" +
        "" +
        "<input type='button' value=" + I18n.t('#accounts.homepage.upload', 'Upload') + " class='btn comfirm'>" +
        "	" +
        "
" +
        "
" +
        "</form>";

    $upload = $(upload);
    $box.append($upload);

    $('body').append($box);

    var $textUploading = $("上传中...");
    var $inputFile = $upload.find("#background_bg_image");
    var $confirm = $upload.find(".confirm");

    $upload.on('submit', function(e) {
      e.preventDefault();
      $(this).ajaxSubmit({
        clearForm: true,
        dataType: 'json',
        beforeSubmit: function() {
          var imageValidated = validateUploadedImage( $inputFile.val() );
          if(imageValidated) $confirm.hide().after($textUploading);
          return imageValidated;
        },
        success: function(data) {
          var img = "";
          $editor.editorBox('insert_code', img);
          $confirm.show();
          $textUploading.remove();
        },
        complete: function(){
          afterUploadedImageSuccess();
        }
      });

    });

    $box.dialog({
      autoOpen: false,
      width: 425,
      title: TRANSLATIONS.embed_external,
      dialogClass: "instructure_embed",
      open: function () {
        $userURL.select();
      }
    });
    initted = true;
  }

  function flickrLinkClickHandler (event) {
    event.preventDefault();
    $box.dialog('close');
    $.findImageForService('flickr_creative_commons', function (data) {
      var title = INST.htmlEscape(data.title),
          html = '';
      $box.dialog('close');
      $editor.editorBox('insert_code', html);
    });
  }

  function embedURLImage (event) {
    var alt = INST.htmlEscape($altText.val() || ''),
        text = INST.htmlEscape($userURL.val());

    event.preventDefault();
    $editor.editorBox('insert_code', "");
    $box.dialog('close');
  }

  function validateURL (event) {
    var val = $userURL.val();
    return (val.match(/\.(gif|png|jpg|jpeg)$/)) ? getImage(val) : invalidURL();
  }

  function invalidURL () {
    $actions.empty();
  }

  function getImage (val) {
    var $div = $('
'),
        $img = $('');

    $div.css('textAlign', 'center').text(TRANSLATIONS.loading);
    $actions.empty();
    $actions.append($div);
    $img.attr({
      src: val,
      title: TRANSLATIONS.click_to_embed
    })
    .addClass('embed_image_link')
    .css('cursor', 'pointer')
    .bind({
      load: function () {
        var img = $img[0];
        $img.height(img.height < 200 ? img.height : 100);
        $div.empty().append($img);
      },
      error: function () {
        $div.text(TRANSLATIONS.image_not_found);
      }
    });
  }

  function loadFields () {
    var selection = $(tinyMCE.get($editor.attr('id')).selection.getContent());
    if (selection.length) {
      $altText.val(selection.attr('alt'));
      $userURL.val(selection.attr('src'));
    } else {
      $altText.val('');
      $userURL.val('');
    }
  }

  tinymce.create('tinymce.plugins.InstructureEmbed', {
    init: function (editor, url) {
      var thisEditor = $('#' + editor.id);

      editor.addCommand('instructureEmbed', function (search) {
        if (!initted) initShared();
        $editor = thisEditor; // set shared $editor so images are pasted into the correct editor

        loadFields();
        $box.dialog('open');

        if (search === 'flickr') $flickrLink.click();
      });

      editor.addButton('instructure_embed', {
        title: TRANSLATIONS.embed_image,
        cmd: 'instructureEmbed',
        image: url + '/img/button.gif'
      });
    },

    getInfo: function () {
      return {
        longname: 'InstructureEmbed',
        author: 'Brian Whitmer',
        authorurl: 'http://www.jiaoxuebang.com',
        infourl: 'http://www.jiaoxuebang.com',
        version: tinymce.majorVersion + '.' + tinymce.minorVersion
      };
    }
  });

  tinymce.PluginManager.add('instructure_embed', tinymce.plugins.InstructureEmbed);
});

<commit_msg>upload image bug<commit_after>/**
 * Copyright (C) 2011 Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

// tinymce doesn't like its plugins being async,
// all dependencies must export to window

define([
  'compiled/editor/stocktiny',
  'i18n!editor',
  'jquery',
  'str/htmlEscape',
  'quizzes_new',
  'i18n!account_homepage',
  // 'compiled/bundles/account_homepage',
  'jqueryui/dialog',
  'jquery.form',
  'jquery.instructure_misc_helpers'

], function(tinymce, I18n, $, htmlEscape) {
  var $box, $editor, $userURL, $altText, $actions, $flickrLink;

  var initted = false;

  var TRANSLATIONS = {
    click_to_embed: I18n.t('click_to_embed', 'Click to embed the image'),
    instructions: INST.htmlEscape(I18n.t('instructions', "Paste or type the URL of the image you'd like to embed:")),
    url: INST.htmlEscape(I18n.t('url', 'URL:')),
    alt_text: INST.htmlEscape(I18n.t('alt_text', 'Alternate Text:')),
    search_flickr: I18n.t('search_flickr', 'Search flickr creative commons'),
    loading: I18n.t('loading', 'Loading...'),
    embed_external: I18n.t('embed_external', 'Embed External Image'),
    embed_image: INST.htmlEscape(I18n.t('embed_image', 'Embed Image')),
    image_not_found: I18n.t('image_not_found', 'Image not found, please try a new URL')
  };

  function initShared () {
    $box = $('
', {html: TRANSLATIONS.instructions + "<form id='instructure_embed_prompt_form'>

"+ TRANSLATIONS.url +"	<input type='text' class='prompt' value='http://'/>

"+TRANSLATIONS.alt_text+"	<input type='text' class='alt_text' value=''/>

	<input class='btn' type='submit' value=" + TRANSLATIONS.click_to_embed +  " />

</form>

"}).hide();

    $altText = $box.find('.alt_text');
    $actions = $box.find('.actions');
    $userURL = $box.find('.prompt');
    $flickrLink = $('', {
      'class': 'flickr_search_link',
      text: TRANSLATIONS.search_flickr,
      href: '#'
    });

    $userURL.bind('keyup', validateURL);
    $actions.delegate('.embed_image_link', 'click', embedURLImage);
    $flickrLink.click(flickrLinkClickHandler);
    $box.append($flickrLink).find('#instructure_embed_prompt_form').submit(embedURLImage);
    var accountId = ENV.current_user_id;
    var upload = "<form id='background_image_uploader' action='/accounts/" + accountId + "/files' method='POST' enctype='multipart/form-data' >" +
        "
" +
        "
" +
        "" +
        I18n.t('choose_a_picture', 'choose a picture:') +
        "	" +
        "" +
        "<input id='background_bg_image' name='attachment[uploaded_data]' type='file'>" +
        "	" +
        "
" +
        "
" +
        "" +
        "	" +
        "" +
        "<input type='submit' value=" + I18n.t('#accounts.homepage.upload', 'Upload') + " class='btn confirm'>" +
        "	" +
        "
" +
        "
" +
        "</form>";

    $upload = $(upload);
    $box.append($upload);

    $('body').append($box);

    var $textUploading = $("上传中...");
    var $inputFile = $upload.find("#background_bg_image");
    var $confirm = $upload.find(".confirm");

    $upload.on('submit', function(e) {
      e.preventDefault();
      $(this).ajaxSubmit({
        clearForm: true,
        dataType: 'json',
        beforeSubmit: function() {
          var imageValidated = validateUploadedImage( $inputFile.val() );
          if(imageValidated) $confirm.hide().after($textUploading);
          return imageValidated;
        },
        success: function(data) {
          var img = "";
          $editor.editorBox('insert_code', img);
          $confirm.show();
          $textUploading.remove();
        },
        complete: function(){
          afterUploadedImageSuccess();
        }
      });

    });

    $box.dialog({
      autoOpen: false,
      width: 425,
      title: TRANSLATIONS.embed_external,
      dialogClass: "instructure_embed",
      open: function () {
        $userURL.select();
      }
    });
    initted = true;
  }

  function flickrLinkClickHandler (event) {
    event.preventDefault();
    $box.dialog('close');
    $.findImageForService('flickr_creative_commons', function (data) {
      var title = INST.htmlEscape(data.title),
          html = '';
      $box.dialog('close');
      $editor.editorBox('insert_code', html);
    });
  }

  function embedURLImage (event) {
    var alt = INST.htmlEscape($altText.val() || ''),
        text = INST.htmlEscape($userURL.val());

    event.preventDefault();
    $editor.editorBox('insert_code', "");
    $box.dialog('close');
  }

  function validateURL (event) {
    var val = $userURL.val();
    return (val.match(/\.(gif|png|jpg|jpeg)$/)) ? getImage(val) : invalidURL();
  }

  function invalidURL () {
    $actions.empty();
  }

  function getImage (val) {
    var $div = $('
'),
        $img = $('');

    $div.css('textAlign', 'center').text(TRANSLATIONS.loading);
    $actions.empty();
    $actions.append($div);
    $img.attr({
      src: val,
      title: TRANSLATIONS.click_to_embed
    })
    .addClass('embed_image_link')
    .css('cursor', 'pointer')
    .bind({
      load: function () {
        var img = $img[0];
        $img.height(img.height < 200 ? img.height : 100);
        $div.empty().append($img);
      },
      error: function () {
        $div.text(TRANSLATIONS.image_not_found);
      }
    });
  }

  function loadFields () {
    var selection = $(tinyMCE.get($editor.attr('id')).selection.getContent());
    if (selection.length) {
      $altText.val(selection.attr('alt'));
      $userURL.val(selection.attr('src'));
    } else {
      $altText.val('');
      $userURL.val('');
    }
  }

  tinymce.create('tinymce.plugins.InstructureEmbed', {
    init: function (editor, url) {
      var thisEditor = $('#' + editor.id);

      editor.addCommand('instructureEmbed', function (search) {
        if (!initted) initShared();
        $editor = thisEditor; // set shared $editor so images are pasted into the correct editor

        loadFields();
        $box.dialog('open');

        if (search === 'flickr') $flickrLink.click();
      });

      editor.addButton('instructure_embed', {
        title: TRANSLATIONS.embed_image,
        cmd: 'instructureEmbed',
        image: url + '/img/button.gif'
      });
    },

    getInfo: function () {
      return {
        longname: 'InstructureEmbed',
        author: 'Brian Whitmer',
        authorurl: 'http://www.jiaoxuebang.com',
        infourl: 'http://www.jiaoxuebang.com',
        version: tinymce.majorVersion + '.' + tinymce.minorVersion
      };
    }
  });

  tinymce.PluginManager.add('instructure_embed', tinymce.plugins.InstructureEmbed);
});

<|endoftext|>


<commit_before>// The function gets called when the window is fully loaded
window.onload = function() {
    // Get the canvas and context
    var canvas = document.getElementById("viewport");
    var context = canvas.getContext("2d");

    // Define the image dimensions
    var width = canvas.width;
    var height = canvas.height;

    // Create an ImageData object
    var imagedata = context.createImageData(width, height);

    //----Data-----------------------------------
    var MaxRadius = 30;
    var MinRadius = 10;

    var seeds = [];
    //-------------------------------------------
    function setPixel(pixelindex, r,g,b,a){
        imagedata.data[pixelindex] = r; // Red
        imagedata.data[pixelindex+1] = g;  // Green
        imagedata.data[pixelindex+2] = b;  // Blue
        imagedata.data[pixelindex+3] = 255;   // Alpha
    }
    // Create the image
    function createImage() {
         var r = 0;
         var g = 0;
         var b = 0;

        // Loop over all of the pixels
        for (var x=0; x<width; x++) {
            for (var y=0; y<height; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;

                for (var w = 0; w <seeds.length; w++){
                    var seed = seeds[w];
                    var dist = Math.sqrt((x-seed.posx)*(x-seed.posx) + (y-seed.posy)*(y-seed.posy));

                    if (dist <= seed.r){
                        var factor = dist/seed.r;
                        r = 255*factor;
                        g = 255*factor;
                        b = 255*factor;

                        // Set the pixel data
                        setPixel(pixelindex, r,g,b,255);
                    }
                }
            }
        }
    }
    // Difuse the values in the grid canvas
    function Diffuse(){
        var DomainTemp = [];
        for(var i=0; i<4*width*length; i++){ //initialize the array
            DomainTemp.push(0);
        }

        // Loop over all of the pixels
        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;

                var offsetl = (y * width + x-1) * 4;
                var offsetr = (y * width + x+1) * 4;
                var offsett = ((y-1) * width + x) * 4;
                var offsetb = ((y+1) * width + x) * 4;

                var sum = 0.25*(imagedata.data[offsetl] + imagedata.data[offsetr] + imagedata.data[offsett] + imagedata.data[offsetb]);

                DomainTemp[pixelindex] = sum;
                DomainTemp[pixelindex+1] = sum;
                DomainTemp[pixelindex+2] = sum;
                DomainTemp[pixelindex+3] = sum;
            }
        }

        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;                   setPixel(pixelindex,DomainTemp[pixelindex],DomainTemp[pixelindex],DomainTemp[pixelindex],255);
            }
        }
    }

    function clearImage() {
        // Loop over all of the pixels
        for (var x=0; x<width; x++) {
            for (var y=0; y<height; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;
                // Set the pixel data
                 setPixel(pixelindex, 0,0,0,255);
            }
        }
    }
    function generateSamples(amount, type){
        seeds.length = 0;
        //Random
        if (type == 'RANDOM'){
            for( var i=0; i<amount; i++){
               var x =  Math.floor(Math.random()*width);
               var y =  Math.floor(Math.random()*height);

               // Get the pixel index
                var pixelindex = (y * width + x) * 4;
                var radius = MinRadius + Math.floor(Math.random()*(MaxRadius - MinRadius));

                var seed = {
                    posx:x,
                    posy:y,
                    r:radius
                }
                seeds.push(seed);
            }
        }

        //Grid
        if (type == 'GRID'){
            var sqrAmount = Math.floor(Math.sqrt(amount));
             for( var i=0; i<sqrAmount; i++){
                 for(var j = 0; j < sqrAmount; j++){
                    var x =  i*width/sqrAmount; //Math.floor(Math.random()*width);
                    var y =  j*height/sqrAmount; //Math.floor(Math.random()*height);

                    // Get the pixel index
                    var pixelindex = (y * width + x) * 4;
                    var radius = MinRadius + Math.floor(Math.random()*(MaxRadius - MinRadius));

                    var seed = {
                        posx:x,
                        posy:y,
                        r:radius
                    }
                    seeds.push(seed);
                 }
            }
        }
    }

    // Main loop
    function main(tframe) {
        // Request animation frames
        window.requestAnimationFrame(main);
        context.clearRect(0, 0, canvas.width, canvas.height);

        if (tframe == 0){
            clearImage();
            generateSamples(100, 'RANDOM');

            // Create the image
            createImage();
        }
        Diffuse();

        // Draw the image data to the canvas
        context.putImageData(imagedata, 0, 0);
    }

    // Call the main loop
    main(0);
};<commit_msg>Interesting stable cellular automata<commit_after>// The function gets called when the window is fully loaded
window.onload = function() {
    // Get the canvas and context
    var canvas = document.getElementById("viewport");
    var context = canvas.getContext("2d");

    // Define the image dimensions
    var width = canvas.width;
    var height = canvas.height;

    // Create an ImageData object
    var imagedata = context.createImageData(width, height);

    //----Data-----------------------------------
    var MaxRadius = 50;
    var MinRadius = 10;

    var seeds = [];
    //-------------------------------------------
    function setPixel(pixelindex, r,g,b,a){
        imagedata.data[pixelindex] = r; // Red
        imagedata.data[pixelindex+1] = g;  // Green
        imagedata.data[pixelindex+2] = b;  // Blue
        imagedata.data[pixelindex+3] = 255;   // Alpha
    }
    // Create the image
    function createImage() {
         var r = 0;
         var g = 0;
         var b = 0;

        // Loop over all of the pixels
        for (var x=0; x<width; x++) {
            for (var y=0; y<height; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;

                for (var w = 0; w <seeds.length; w++){
                    var seed = seeds[w];
                    var dist = Math.sqrt((x-seed.posx)*(x-seed.posx) + (y-seed.posy)*(y-seed.posy));

                    if (dist <= seed.r){
                        var factor = 1; //dist/seed.r;
                        r = 255*factor;
                        g = 255*factor;
                        b = 255*factor;

                        // Set the pixel data
                        setPixel(pixelindex, r,g,b,255);
                    }
                }
            }
        }
    }
    // Difuse the values in the grid canvas
    function Diffuse(){
        var DomainTemp = [];
        for(var i=0; i<4*width*length; i++){ //initialize the array
            DomainTemp.push(0);
        }

        // Loop over all of the pixels
        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;

                var offsetl = (y * width + x-1) * 4;
                var offsetr = (y * width + x+1) * 4;
                var offsett = ((y-1) * width + x) * 4;
                var offsetb = ((y+1) * width + x) * 4;

                var sum = 0.25*(imagedata.data[offsetl] + imagedata.data[offsetr] + imagedata.data[offsett] + imagedata.data[offsetb]);

                DomainTemp[pixelindex] = sum;
                DomainTemp[pixelindex+1] = sum;
                DomainTemp[pixelindex+2] = sum;
                DomainTemp[pixelindex+3] = sum;
            }
        }

        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;                   setPixel(pixelindex,DomainTemp[pixelindex],DomainTemp[pixelindex],DomainTemp[pixelindex],255);
            }
        }
    }
    function CellExpand(){
        var DomainTemp = [];
        for(var i=0; i<4*width*length; i++){ //initialize the array
            DomainTemp.push(0);
        }

        // Loop over all of the pixels
        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;

                var offsetl = (y * width + x-1) * 4;
                var offsetr = (y * width + x+1) * 4;
                var offsett = ((y-1) * width + x) * 4;
                var offsetb = ((y+1) * width + x) * 4;

                var val = rules(imagedata.data[offsetl],imagedata.data[offsett],imagedata.data[offsetr], imagedata.data[offsetb]);

                if (val>255) val = 255;

                DomainTemp[pixelindex] = val;
                DomainTemp[pixelindex+1] = val;
                DomainTemp[pixelindex+2] = val;
                DomainTemp[pixelindex+3] = val;
            }
        }

        for (var x=1; x<width-1; x++) {
            for (var y=1; y<height-1; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;
                setPixel(pixelindex,DomainTemp[pixelindex],DomainTemp[pixelindex],DomainTemp[pixelindex],255);
            }
        }
    }
    function clearImage() {
        // Loop over all of the pixels
        for (var x=0; x<width; x++) {
            for (var y=0; y<height; y++) {
                // Get the pixel index
                var pixelindex = (y * width + x) * 4;
                // Set the pixel data
                 setPixel(pixelindex, 0,0,0,255);
            }
        }
    }
    function generateSamples(amount, type){
        seeds.length = 0;
        //Random
        if (type == 'RANDOM'){
            for( var i=0; i<amount; i++){
               var x =  Math.floor(Math.random()*width);
               var y =  Math.floor(Math.random()*height);

               // Get the pixel index
                var pixelindex = (y * width + x) * 4;
                var radius = MinRadius + Math.floor(Math.random()*(MaxRadius - MinRadius));

                var seed = {
                    posx:x,
                    posy:y,
                    r:radius
                }
                seeds.push(seed);
            }
        }

        //Grid
        if (type == 'GRID'){
            var sqrAmount = Math.floor(Math.sqrt(amount));
             for( var i=0; i<sqrAmount; i++){
                 for(var j = 0; j < sqrAmount; j++){
                    var x =  i*width/sqrAmount; //Math.floor(Math.random()*width);
                    var y =  j*height/sqrAmount; //Math.floor(Math.random()*height);

                    // Get the pixel index
                    var pixelindex = (y * width + x) * 4;
                    var radius = MinRadius + Math.floor(Math.random()*(MaxRadius - MinRadius));

                    var seed = {
                        posx:x,
                        posy:y,
                        r:radius
                    }
                    seeds.push(seed);
                 }
            }
        }
    }
    function rules(r,t,l,b){
//        if (r>0 && t==0 && l == 0 && b==0) return 255;
//        if (r==0 && t>0 && l == 0 && b==0) return 255;
//        if (r==0 && t==0 && l > 0 && b==0) return 255;
//        if (r==0 && t==0 && l == 0 && b>0) return 255;
//
        if (r>0 && t>0 && l == 0 && b==0) return 255;
        if (r>0 && t==0 && l == 0 && b>0) return 255;
        if (r==0 && t>0 && l > 0 && b==0) return 255;
        if (r==0 && t==0 && l > 0 && b>0) return 255;

        if (r>0 && t>0 && l >0 && b==0) return 255;
        if (r>0 && t==0 && l> 0 && b>0) return 255;
        if (r>0 && t>0 && l == 0 && b>0) return 255;
        if (r==0 && t>0 && l > 0 && b>0) return 255;

        else return 0;
    }

    // Main loop
    function main(tframe) {
        // Request animation frames
        window.requestAnimationFrame(main);
        context.clearRect(0, 0, canvas.width, canvas.height);

        if (tframe == 0){
            clearImage();
            generateSamples(10, 'RANDOM');

            // Create the image
            createImage();
        }
        CellExpand();

        // Draw the image data to the canvas
        context.putImageData(imagedata, 0, 0);
    }

    // Call the main loop
    main(0);
};<|endoftext|>