<commit_before>(function() {
  function loadScript(src, callback)
  {
    var s,
        r,
        t;
    r = false;
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = src;
    s.onload = s.onreadystatechange = function() {
      //console.log( this.readyState ); //uncomment this line to see which ready states are called.
      if ( !r && (!this.readyState || this.readyState == 'complete') )
      {
        r = true;
        callback();
      }
    };
    t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
  }
  var dom;
  var successMsgs = ['Good job.', 'Nice work.', 'Good eye.', 'Well done.', 'Nicely done.'];
  var pauseMsgs = ['Looks fine there.', 'Seems ok.', 'All clear there.', 'Just splashing around.'];
  var player;
  var gameState;

  function init() {
    loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', function() {
      loadScript('observable.js', function() {
        wireDom();
        youtubeInit(onPlayerReady, onPlayerStateChange);
      });
    });

    loadScript('share.min.js', function() {
      new Share('.share', {
        title: 'Spot The Drowning Child',
        description: 'An interactive PSA about the instinctive drowning response.',
        url: 'http://spotthedrowningchild.com'
      });
    });
  }
  init();

  function onPlayerReady(event) {
    setupGame(gameState);
    if (gameState.frameRefresh)
      clearInterval(gameState.frameRefresh);
    gameState.frameRefresh = setInterval(function gameFrame() {
      if (!player || !player.getCurrentTime || player.getPlayerState() !== YT.PlayerState.PLAYING)
          return;
      var time = player.getCurrentTime();
      // State transitions: ok -> drowning -> spotted -> saved
      if (time > gameState.swimmerSavedSecs && gameState.status() === 'spotted') {
          gameState.status('saved');
      } else if (time > gameState.whistleSecs && gameState.status() === 'drowning') {
          gameState.status('spotted');
      } else if (time > gameState.drowningStartSecs && gameState.status() === 'ok') {
          gameState.status('drowning');
      }
    }, 100);
  }

  function youtubeInit(onPlayerReady, onPlayerStateChange) {
    window.Videos.getYoutubePlayer().then(
      function(player_gameState) {
        player = player_gameState[0];
        gameState = player_gameState[1];
        player.addEventListener('onStateChange', onPlayerStateChange);
        onPlayerReady();
      }
    );
  }

  function wireDom() {
    dom = {
      findBox: $('#box'),
      statusBox: $('.status'),
      statusText: document.getElementById('status'),
      infoBox: document.getElementById('info'),
      winInfoBox: document.getElementById('wininfo'),
      scoreBox: document.getElementById('scorebox'),
      creatorLink: document.getElementById('creator-link'),
      cursorLooks: $('.cursor-look'),
      cursorDot: $('#cursor-dot'),
      playAgain: $('.play-again'),
      showStatus: function showStatus(text) {
        this.statusText.textContent = text;
      },
      showInfo: function showInfo() {
        this.infoBox.setAttribute('style', 'display: block; -webkit-animation: info-fade 4s; animation: info-fade 4s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
      },
      showWinInfo: function showWinInfo() {
        this.statusBox.addClass('win');
        this.winInfoBox.setAttribute('style', 'display: block; -webkit-animation: wininfo-fade 4s; animation: wininfo-fade 4s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
        loadScript('buoy.js', function() {});
      },
      showTime: function showTime(time) {
        var timeStr = time.toPrecision(2);
        if (time > 0) {
          timeStr = '+'+timeStr;
          this.scoreBox.className += ' win-hue';
          this.creatorLink.setAttribute('style', 'display: inline-block');
        }
        timeStr += 's';
        this.scoreBox.textContent = timeStr;
      },
      showCursorDot: function showCursorDot(x, y, win) {
        var positionStyle = 'display: block; position: absolute; top:'+(y-5)+'px;left:'+(x-5)+'px;';
        this.cursorDot.attr('style', positionStyle+'-webkit-animation: cursor-throb 1s infinite ease; animation: cursor-throb 1s infinite ease;');
        if (win) {
          this.cursorDot.addClass('win-hue');
          this.cursorDot.attr('style', positionStyle+'-webkit-animation: fadeout 10s; animation: fadeout 10s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
        }
      },
      hideCursorDot: function hideCursorDot() {
        this.cursorDot.attr('style', 'display: none;');
      },
      isMobile: function isMobile() {
        return navigator.userAgent.match(/(iPod|iPhone|iPad)/);
      }
    };

    // Set up the play-again links:
    window.Videos.getYoutubePlayer().then(
      function(player_gameState) {
        var gameState = player_gameState[1];
        var nextGame = gameState.next();

        dom.playAgain.attr('href', window.location.pathname + '?' + $.param({'g':nextGame.index}));
        if (history.pushState) {
            // If we refresh, don't choose the same video
            var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
            window.history.pushState({path:newurl},'',newurl);
        }
      });

    dom.findBox.click(function(e) {
      if (gameState.status() === 'drowning' || gameState.status() === 'spotted') {
        dom.showCursorDot(e.pageX, e.pageY, true);
        success();
        dom.findBox.attr('style', 'display: none;');
      }
    });

    dom.cursorLooks.click(function(e) {
      if (player.getPlayerState() === YT.PlayerState.PAUSED) {
        player.playVideo();
      } else if (player.getPlayerState() === YT.PlayerState.PLAYING) {
        var status = gameState.status();
        if (status === 'drowning' || status === 'ok' || status === 'spotted') {
          if (!gameState.winTime) {
            dom.showCursorDot(e.pageX, e.pageY);
          }
        }
        player.pauseVideo();
      }
      ga('send', 'event', gameState.videoId, 'click', 'video clicked', {'dimension1': gameState.videoId});
    });

    dom.cursorDot.click(function() {
      player.playVideo();
    });
  }

  function setupGame(gameState) {
    gameState.status = observable();
    gameState.status('ok');
    gameState.pauseCount = 0;
    gameState.ongoingPlayStatus = 'Spot the drowning child.';
    player.cueVideoById(gameState.videoId, undefined, 'large');
    dom.findBox.attr('style', gameState.findBoxStyle);
    player.playVideo();

    ga('set', 'dimension1', gameState.videoId);
    ga('send', 'event', 'game', 'setup', gameState.videoId);

    gameState.status(function(newStatus) {
      if (newStatus === 'drowning') {
        dom.findBox.attr('style', 'display: block;' + gameState.findBoxStyle);
        setTimeout(function() {
          if (!gameState.winTime) {
            gameState.ongoingPlayStatus = 'Spot the drowning child. Click the video to help the lifeguard.';
            dom.showStatus(gameState.ongoingPlayStatus);
          }
        }, (gameState.whistleSecs - gameState.drowningStartSecs) * Math.random() * 1000);
      } else if (newStatus === 'saved') {
        if (gameState.frameRefresh) {
          clearInterval(gameState.frameRefresh);
        }
        loadScript('jquery-scrollto.js', function() {
          $('#bottomsquare').ScrollTo({
            duration: 1000
          });
        });
      } else if (newStatus === 'spotted') {
        if (!gameState.winTime) {
          gameState.ongoingPlayStatus = 'Spot the drowning child. Click the video to help the lifeguard.';
          dom.showStatus(gameState.ongoingPlayStatus);
        }
        end();
      }
    });
  }

  function success() {
    gameState.winTime = player.getCurrentTime();
    ga('send', 'event', 'game', 'success', gameState.videoId);
    ga('send', 'event', gameState.videoId, 'win', 'game time', gameState.winTime);

    var status = gameState.status();
    gameState.status('spotted');
    if (!dom.isMobile()) {
      if (status === 'drowning') {
        player.seekTo(gameState.whistleSecs);
      }
      player.setPlaybackRate(2);
      player.playVideo();
    } else {
      setTimeout(function() {
        if (status === 'drowning') {
          player.seekTo(gameState.whistleSecs);
        }
        player.playVideo();
      }, 1000);
    }

    var time = gameState.whistleSecs - gameState.winTime;
    var msg = pickRandom(successMsgs);
    dom.showStatus(msg);
    dom.showTime(time);

    dom.showWinInfo();
  }

  function end() {
    ga('send', 'event', 'game', 'end', gameState.videoId);
    dom.showInfo();
  }

  // 4. The API will call this function when the video player is ready.

  function onPlayerStateChange(event) {
    var status = gameState.status();
    if (event.data === YT.PlayerState.ENDED) {
      end();
    } else if (event.data === YT.PlayerState.PAUSED) {
      gameState.pauseCount += 1;
      ga('send', 'event', 'game', 'paused', gameState.videoId, gameState.pauseCount);
      dom.cursorLooks.hide();
      if (status === 'drowning' || status === 'ok') {
        if (!dom.isMobile() || gameState.pauseCount > 1) {
          var pauseMsg = pickRandom(pauseMsgs);
          dom.showStatus(pauseMsg + ' Keep looking.');
        }
      } else if (status === 'spotted' || status === 'saved') {
        end();
      }
    } else if (event.data === YT.PlayerState.PLAYING) {
      ga('send', 'event', 'game', 'played', gameState.videoId);
      if (!dom.isMobile())
        dom.cursorLooks.show();
      if (status === 'drowning' || status === 'ok') {
        dom.hideCursorDot();
        if (!gameState.winTime) {
          dom.showStatus(gameState.ongoingPlayStatus);
        }
      }
    }
  }

  function pickRandom(items) {
    return items[Math.floor(Math.random()*items.length)];
  }
})();
<commit_msg>Whistle time is t=0.<commit_after>(function() {
  function loadScript(src, callback)
  {
    var s,
        r,
        t;
    r = false;
    s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = src;
    s.onload = s.onreadystatechange = function() {
      //console.log( this.readyState ); //uncomment this line to see which ready states are called.
      if ( !r && (!this.readyState || this.readyState == 'complete') )
      {
        r = true;
        callback();
      }
    };
    t = document.getElementsByTagName('script')[0];
    t.parentNode.insertBefore(s, t);
  }
  var dom;
  var successMsgs = ['Good job.', 'Nice work.', 'Good eye.', 'Well done.', 'Nicely done.'];
  var pauseMsgs = ['Looks fine there.', 'Seems ok.', 'All clear there.', 'Just splashing around.'];
  var player;
  var gameState;

  function init() {
    loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', function() {
      loadScript('observable.js', function() {
        wireDom();
        youtubeInit(onPlayerReady, onPlayerStateChange);
      });
    });

    loadScript('share.min.js', function() {
      new Share('.share', {
        title: 'Spot The Drowning Child',
        description: 'An interactive PSA about the instinctive drowning response.',
        url: 'http://spotthedrowningchild.com'
      });
    });
  }
  init();

  function onPlayerReady(event) {
    setupGame(gameState);
    if (gameState.frameRefresh)
      clearInterval(gameState.frameRefresh);
    gameState.frameRefresh = setInterval(function gameFrame() {
      if (!player || !player.getCurrentTime || player.getPlayerState() !== YT.PlayerState.PLAYING)
          return;
      var time = player.getCurrentTime();
      // State transitions: ok -> drowning -> spotted -> saved
      if (time > gameState.swimmerSavedSecs && gameState.status() === 'spotted') {
          gameState.status('saved');
      } else if (time > gameState.whistleSecs && gameState.status() === 'drowning') {
          gameState.status('spotted');
      } else if (time > gameState.drowningStartSecs && gameState.status() === 'ok') {
          gameState.status('drowning');
      }
    }, 100);
  }

  function youtubeInit(onPlayerReady, onPlayerStateChange) {
    window.Videos.getYoutubePlayer().then(
      function(player_gameState) {
        player = player_gameState[0];
        gameState = player_gameState[1];
        player.addEventListener('onStateChange', onPlayerStateChange);
        onPlayerReady();
      }
    );
  }

  function wireDom() {
    dom = {
      findBox: $('#box'),
      statusBox: $('.status'),
      statusText: document.getElementById('status'),
      infoBox: document.getElementById('info'),
      winInfoBox: document.getElementById('wininfo'),
      scoreBox: document.getElementById('scorebox'),
      creatorLink: document.getElementById('creator-link'),
      cursorLooks: $('.cursor-look'),
      cursorDot: $('#cursor-dot'),
      playAgain: $('.play-again'),
      showStatus: function showStatus(text) {
        this.statusText.textContent = text;
      },
      showInfo: function showInfo() {
        this.infoBox.setAttribute('style', 'display: block; -webkit-animation: info-fade 4s; animation: info-fade 4s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
      },
      showWinInfo: function showWinInfo() {
        this.statusBox.addClass('win');
        this.winInfoBox.setAttribute('style', 'display: block; -webkit-animation: wininfo-fade 4s; animation: wininfo-fade 4s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
        loadScript('buoy.js', function() {});
      },
      showTime: function showTime(time) {
        var timeStr = time.toPrecision(2);
        if (time > 0) {
          timeStr = '+'+timeStr;
        } else {
          this.scoreBox.className += ' win-hue';
          this.creatorLink.setAttribute('style', 'display: inline-block');
        }
        timeStr += 's';
        this.scoreBox.textContent = timeStr;
      },
      showCursorDot: function showCursorDot(x, y, win) {
        var positionStyle = 'display: block; position: absolute; top:'+(y-5)+'px;left:'+(x-5)+'px;';
        this.cursorDot.attr('style', positionStyle+'-webkit-animation: cursor-throb 1s infinite ease; animation: cursor-throb 1s infinite ease;');
        if (win) {
          this.cursorDot.addClass('win-hue');
          this.cursorDot.attr('style', positionStyle+'-webkit-animation: fadeout 10s; animation: fadeout 10s; -webkit-animation-fill-mode: forwards; animation-fill-mode: forwards;');
        }
      },
      hideCursorDot: function hideCursorDot() {
        this.cursorDot.attr('style', 'display: none;');
      },
      isMobile: function isMobile() {
        return navigator.userAgent.match(/(iPod|iPhone|iPad)/);
      }
    };

    // Set up the play-again links:
    window.Videos.getYoutubePlayer().then(
      function(player_gameState) {
        var gameState = player_gameState[1];
        var nextGame = gameState.next();

        dom.playAgain.attr('href', window.location.pathname + '?' + $.param({'g':nextGame.index}));
        if (history.pushState) {
            // If we refresh, don't choose the same video
            var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
            window.history.pushState({path:newurl},'',newurl);
        }
      });

    dom.findBox.click(function(e) {
      if (gameState.status() === 'drowning' || gameState.status() === 'spotted') {
        dom.showCursorDot(e.pageX, e.pageY, true);
        success();
        dom.findBox.attr('style', 'display: none;');
      }
    });

    dom.cursorLooks.click(function(e) {
      if (player.getPlayerState() === YT.PlayerState.PAUSED) {
        player.playVideo();
      } else if (player.getPlayerState() === YT.PlayerState.PLAYING) {
        var status = gameState.status();
        if (status === 'drowning' || status === 'ok' || status === 'spotted') {
          if (!gameState.winTime) {
            dom.showCursorDot(e.pageX, e.pageY);
          }
        }
        player.pauseVideo();
      }
      ga('send', 'event', gameState.videoId, 'click', 'video clicked', {'dimension1': gameState.videoId});
    });

    dom.cursorDot.click(function() {
      player.playVideo();
    });
  }

  function setupGame(gameState) {
    gameState.status = observable();
    gameState.status('ok');
    gameState.pauseCount = 0;
    gameState.ongoingPlayStatus = 'Spot the drowning child.';
    player.cueVideoById(gameState.videoId, undefined, 'large');
    dom.findBox.attr('style', gameState.findBoxStyle);
    player.playVideo();

    ga('set', 'dimension1', gameState.videoId);
    ga('send', 'event', 'game', 'setup', gameState.videoId);

    gameState.status(function(newStatus) {
      if (newStatus === 'drowning') {
        dom.findBox.attr('style', 'display: block;' + gameState.findBoxStyle);
        setTimeout(function() {
          if (!gameState.winTime) {
            gameState.ongoingPlayStatus = 'Spot the drowning child. Click the video to help the lifeguard.';
            dom.showStatus(gameState.ongoingPlayStatus);
          }
        }, (gameState.whistleSecs - gameState.drowningStartSecs) * Math.random() * 1000);
      } else if (newStatus === 'saved') {
        if (gameState.frameRefresh) {
          clearInterval(gameState.frameRefresh);
        }
        loadScript('jquery-scrollto.js', function() {
          $('#bottomsquare').ScrollTo({
            duration: 1000
          });
        });
      } else if (newStatus === 'spotted') {
        if (!gameState.winTime) {
          gameState.ongoingPlayStatus = 'Spot the drowning child. Click the video to help the lifeguard.';
          dom.showStatus(gameState.ongoingPlayStatus);
        }
        end();
      }
    });
  }

  function success() {
    gameState.winTime = player.getCurrentTime();
    ga('send', 'event', 'game', 'success', gameState.videoId);
    ga('send', 'event', gameState.videoId, 'win', 'game time', gameState.winTime);

    var status = gameState.status();
    gameState.status('spotted');
    if (!dom.isMobile()) {
      if (status === 'drowning') {
        player.seekTo(gameState.whistleSecs);
      }
      player.setPlaybackRate(2);
      player.playVideo();
    } else {
      setTimeout(function() {
        if (status === 'drowning') {
          player.seekTo(gameState.whistleSecs);
        }
        player.playVideo();
      }, 1000);
    }

    var time = gameState.winTime - gameState.whistleSecs;
    var msg = pickRandom(successMsgs);
    dom.showStatus(msg);
    dom.showTime(time);

    dom.showWinInfo();
  }

  function end() {
    ga('send', 'event', 'game', 'end', gameState.videoId);
    dom.showInfo();
  }

  // 4. The API will call this function when the video player is ready.

  function onPlayerStateChange(event) {
    var status = gameState.status();
    if (event.data === YT.PlayerState.ENDED) {
      end();
    } else if (event.data === YT.PlayerState.PAUSED) {
      gameState.pauseCount += 1;
      ga('send', 'event', 'game', 'paused', gameState.videoId, gameState.pauseCount);
      dom.cursorLooks.hide();
      if (status === 'drowning' || status === 'ok') {
        if (!dom.isMobile() || gameState.pauseCount > 1) {
          var pauseMsg = pickRandom(pauseMsgs);
          dom.showStatus(pauseMsg + ' Keep looking.');
        }
      } else if (status === 'spotted' || status === 'saved') {
        end();
      }
    } else if (event.data === YT.PlayerState.PLAYING) {
      ga('send', 'event', 'game', 'played', gameState.videoId);
      if (!dom.isMobile())
        dom.cursorLooks.show();
      if (status === 'drowning' || status === 'ok') {
        dom.hideCursorDot();
        if (!gameState.winTime) {
          dom.showStatus(gameState.ongoingPlayStatus);
        }
      }
    }
  }

  function pickRandom(items) {
    return items[Math.floor(Math.random()*items.length)];
  }
})();
<|endoftext|>


<commit_before>module.exports = {
  'rules': {
    // enforce spacing inside array brackets
    'array-bracket-spacing': [2, 'always', {
      'objectsInArrays': false,
      'arraysInArrays': false
    }],
    // specify the maximum length of a line in your program
    // https://github.com/eslint/eslint/blob/master/docs/rules/max-len.md
    'max-len': [2, 80, 2, {
      'ignoreUrls': true,
      'ignoreComments': false
    }],
    // require or disallow use of semicolons instead of ASI
    // I use Babel, it takes care of this for me
    'semi': [2, 'never'],
    // space around the keywords.
    // http://github.com/eslint/eslint/blob/master/docs/rules/keyword-spacing.md
    'keyword-spacing': [2, {
      'before': true,
      'after': true,
      'overrides': {
        'case': { 'after': true },
        'return': { 'after': true },
        'throw': { 'after': true }
      }
    }],
    // require or disallow spaces inside parentheses
    // disabled, because this rule is strange
    // TODO: write and implement a better rule
    'space-in-parens': 0
  }
};
<commit_msg>Enable `newline-after-var` rule<commit_after>module.exports = {
  'rules': {
    // enforce spacing inside array brackets
    'array-bracket-spacing': [2, 'always', {
      'objectsInArrays': false,
      'arraysInArrays': false
    }],
    // specify the maximum length of a line in your program
    // https://github.com/eslint/eslint/blob/master/docs/rules/max-len.md
    'max-len': [2, 80, 2, {
      'ignoreUrls': true,
      'ignoreComments': false
    }],
    // allow/disallow an empty newline after var statement
    // https://github.com/eslint/eslint/blob/master/docs/rules/newline-after-var.md
    'newline-after-var': [2, 'always'],
    // require or disallow use of semicolons instead of ASI
    // I use Babel, it takes care of this for me
    'semi': [2, 'never'],
    // space around the keywords.
    // http://github.com/eslint/eslint/blob/master/docs/rules/keyword-spacing.md
    'keyword-spacing': [2, {
      'before': true,
      'after': true,
      'overrides': {
        'case': { 'after': true },
        'return': { 'after': true },
        'throw': { 'after': true }
      }
    }],
    // require or disallow spaces inside parentheses
    // disabled, because this rule is strange
    // TODO: write and implement a better rule
    'space-in-parens': 0
  }
};
<|endoftext|>


<commit_before>// Canvas Size
var WIDTH = 1280;
var HEIGHT = 720;

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: false, transparent: false, resolution: 1});
renderer.backgroundColor = 0xFF00FF;
document.getElementById("game").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Config goes here:
var fontConfig = {font: "30px 'rockfire'", fill: "#000000", align: "left"};
var relcenter = (0.5,0.5);

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();
/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui

Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

// Version Text (top left)
var versionconfig = fontConfig;
var actionconfig = {font: "80px 'rockfire'", fill: "#000000", align:"center"};
var statsconfig = {font: "45px 'rockfire'", fill: "#000000", align:"right"};

var versionText = new PIXI.Text("Version 0.02d", versionconfig);
var actionText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionconfig);
var statsText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsconfig);
var animstatText = new PIXI.Text("n\nm\nN", statsconfig);

versionText.position = {x:10,y:10};
actionText.position = {x:WIDTH/2,y:HEIGHT/2};
actionText.anchor = {x:0.5,y:2.25};
statsText.position = {x:WIDTH-10, y:HEIGHT-10};
statsText.anchor = {x:1,y:1}
animstatText.position = {x:WIDTH-180, y:HEIGHT-10};
animstatText.anchor = {x:1,y:1}

// Adding info text
cGui.addChild(versionText);
cGui.addChild(actionText);
cGui.addChild(statsText);
cGui.addChild(animstatText);

// Keyboard IO
// TODO on screen keys (interactive=true)
var loadKey = keyboard(65);
loadKey.press=function(){
    ingameLoad();
};
var unloadKey = keyboard(68);
unloadKey.press=function(){
    ingameUnload();
};
// Don't worry about this one
var fuckKey = keyboard(70);
fuckKey.press=function(){
    versionText.text="FUCK YOU!";
}

// init Gamestate
var gameState = new State();

// Image Locations
var loadbtn_file = "assets/image/buttons/load_btn.png";
var unloadbtn_file = "assets/image/buttons/unload_btn.png";
var seabg_file = "assets/image/bg/sea_layer.png";
var shitsprite_file = "assets/image/sprites/boat_layer.png";

// Load Images
// eg. assets/images/buttons/[load_btn.png, unload_btn.png]
PIXI.loader
    .add(loadbtn_file)
    .add(unloadbtn_file)
    .add(seabg_file)
    .add(shitsprite_file)
    .load(setup)

// Global sprites
var loadbtn = null;
var unloadbtn = null;
var background = null;

function showIngame(){
    loadbtn.position = {x: 10,y: HEIGHT-100};
    loadbtn.height = 93;
    loadbtn.width = 190;
    unloadbtn.position = {x: loadbtn.width + 15, y: HEIGHT-100};
    unloadbtn.height = 93;
    unloadbtn.width = 190;
    cGui.addChild(loadbtn);
    cGui.addChild(unloadbtn);
    loadbtn.interactive = true;
    unloadbtn.interactive = true;
    loadbtn.click = function(data){ingameLoad(); loadbtn.rotation=-0.03;window.setTimeout(function(){loadbtn.rotation=0.03;window.setTimeout(function(){loadbtn.rotation=0},200)},200)};
    unloadbtn.click = function(data){ingameUnload(); unloadbtn.rotation=-0.03;window.setTimeout(function(){unloadbtn.rotation=0.03;window.setTimeout(function(){unloadbtn.rotation=0},200)},200)};
}

// TODO: Do Howler Stuff here
// TODO: "rate" changes speed

// Called just before rendering the first frame
function setup(){
    loadbtn = new PIXI.Sprite.fromImage(loadbtn_file);
    unloadbtn = new PIXI.Sprite.fromImage(unloadbtn_file);
    background = new PIXI.Sprite.fromImage(seabg_file);
    background.height = HEIGHT;
    background.width = WIDTH;
    cBack.addChild(background);

    showIngame();
    testship = new Ship();
    renderStage();
}

// Class for Gamestate
function State(){
    this.level = 1;
    this.name = "Testie";
    this.mistakes = 0;
    this.points = 0;
    this.display = function(){
        // mistake, point, ship;
        animstatText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
    }
    window.setInterval(function(){gameState.display();},100);
}

// Class for Ships
function Ship(){
    ship = this;
    this.start = rinr(3,15);
    this.end = 9;
    this.tint = rinr(100,255)*1 + rinr(100,255)*16 + rinr(100,255)*256;
    this.sprite = new PIXI.Sprite.fromImage(shitsprite_file);
    this.sprite.scale={x:1.6,y:1.6};
    this.sprite.position={x:WIDTH+5,y:HEIGHT-350};
    this.sprite.tint = this.tint;
    cMiddle.addChild(this.sprite);
    this.die = function(){
        window.clearInterval(this.movement);
        cMiddle.removeChild(this.sprite);
        testship = new Ship();
    };
    this.leftlevel = 0;
    this.middlelevel = 0;
    this.rightlevel = 0;
    this.bobx = 0;
    this.boby = 0;
    this.move = function(){
        this.sprite.x -= gameState.points+3;
        // TODO: Bobbing...
        // this.bobx += rinr(-100,100)/100000.0;
        // this.boby += rinr(-100,100)/100000.0;
        // this.sprite.anchor = {x:this.bobx, y:this.boby};
        if (this.sprite.x+this.sprite.width<-4) {
            gameState.level += 1;
            this.die();
        }
    }
    this.movement = window.setInterval(function(){ship.move();},20);
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    renderLoop();
    renderer.render(stage);
}

// Called on "Load"-Press
function ingameLoad(){
    // Debug
    gameState.points += 1;
}

// Called on "Unload"-Press
function ingameUnload(){
    // Debug
    gameState.mistakes += 1;
}

// Called in-between rendering
// should be used for logic
function renderLoop(){

}
<commit_msg>Filter<commit_after>// Canvas Size
var WIDTH = 1280;
var HEIGHT = 720;

// Initialize Renderer
var renderer = PIXI.autoDetectRenderer(WIDTH, HEIGHT, {antialiasing: false, transparent: false, resolution: 1});
renderer.backgroundColor = 0xFF00FF;
document.getElementById("game").appendChild(renderer.view);

// Master Containter
var stage = new PIXI.Container();

// Config goes here:
var fontConfig = {font: "30px 'rockfire'", fill: "#000000", align: "left"};
var relcenter = (0.5,0.5);

// Layers
var cBack = new PIXI.Container();
var cMiddle = new PIXI.Container();
var cFront = new PIXI.Container();
var cGui = new PIXI.Container();
/*
    stage
      |
      +-- cBack
      +-- cMiddle
      +-- cFront
      +-- cGui

Drawn from top to bottom
*/
stage.addChild(cBack);
stage.addChild(cMiddle);
stage.addChild(cFront);
stage.addChild(cGui);

// Version Text (top left)
var versionconfig = fontConfig;
var actionconfig = {font: "80px 'rockfire'", fill: "#000000", align:"center"};
var statsconfig = {font: "45px 'rockfire'", fill: "#000000", align:"right"};

var versionText = new PIXI.Text("Version 0.02d", versionconfig);
var actionText = new PIXI.Text("Fill all container ships\nSo that they carry 9 containers", actionconfig);
var statsText = new PIXI.Text("Mistake[s]\nPoint[s]\n#   Ship", statsconfig);
var animstatText = new PIXI.Text("n\nm\nN", statsconfig);

versionText.position = {x:10,y:10};
actionText.position = {x:WIDTH/2,y:HEIGHT/2};
actionText.anchor = {x:0.5,y:2.25};
statsText.position = {x:WIDTH-10, y:HEIGHT-10};
statsText.anchor = {x:1,y:1}
animstatText.position = {x:WIDTH-180, y:HEIGHT-10};
animstatText.anchor = {x:1,y:1}

// Adding info text
cGui.addChild(versionText);
cGui.addChild(actionText);
cGui.addChild(statsText);
cGui.addChild(animstatText);

// Keyboard IO
// TODO on screen keys (interactive=true)
var loadKey = keyboard(65);
loadKey.press=function(){
    ingameLoad();
};
var unloadKey = keyboard(68);
unloadKey.press=function(){
    ingameUnload();
};
// Don't worry about this one
var fuckKey = keyboard(70);
fuckKey.press=function(){
    versionText.text="FUCK YOU!";
}

// init Gamestate
var gameState = new State();

// Image Locations
var loadbtn_file = "assets/image/buttons/load_btn.png";
var unloadbtn_file = "assets/image/buttons/unload_btn.png";
var seabg_file = "assets/image/bg/sea_layer.png";
var shitsprite_file = "assets/image/sprites/boat_layer.png";

// Load Images
// eg. assets/images/buttons/[load_btn.png, unload_btn.png]
PIXI.loader
    .add(loadbtn_file)
    .add(unloadbtn_file)
    .add(seabg_file)
    .add(shitsprite_file)
    .load(setup)

// Global sprites
var loadbtn = null;
var unloadbtn = null;
var background = null;

function showIngame(){
    loadbtn.position = {x: 10,y: HEIGHT-100};
    loadbtn.height = 93;
    loadbtn.width = 190;
    unloadbtn.position = {x: loadbtn.width + 15, y: HEIGHT-100};
    unloadbtn.height = 93;
    unloadbtn.width = 190;
    cGui.addChild(loadbtn);
    cGui.addChild(unloadbtn);
    loadbtn.interactive = true;
    unloadbtn.interactive = true;
    loadbtn.click = function(data){ingameLoad(); loadbtn.rotation=-0.03;window.setTimeout(function(){loadbtn.rotation=0.03;window.setTimeout(function(){loadbtn.rotation=0},200)},200)};
    unloadbtn.click = function(data){ingameUnload(); unloadbtn.rotation=-0.03;window.setTimeout(function(){unloadbtn.rotation=0.03;window.setTimeout(function(){unloadbtn.rotation=0},200)},200)};
}

// TODO: Do Howler Stuff here
// TODO: "rate" changes speed

// Called just before rendering the first frame
function setup(){
    loadbtn = new PIXI.Sprite.fromImage(loadbtn_file);
    unloadbtn = new PIXI.Sprite.fromImage(unloadbtn_file);
    background = new PIXI.Sprite.fromImage(seabg_file);
    background.height = HEIGHT;
    background.width = WIDTH;
    cBack.addChild(background);

    showIngame();
    testship = new Ship();

    // Filters
    // thisfil = new PIXI.filters.ColorMatrixFilter();
    // stage.filters = [thisfil];

    renderStage();
}

// Class for Gamestate
function State(){
    this.level = 1;
    this.name = "Testie";
    this.mistakes = 0;
    this.points = 0;
    this.display = function(){
        // mistake, point, ship;
        animstatText.text=this.mistakes+"\n"+this.points+"\n"+this.level;
    }
    window.setInterval(function(){gameState.display();},100);
}

// Class for Ships
function Ship(){
    ship = this;
    this.start = rinr(3,15);
    this.end = 9;
    this.filter = new PIXI.filters.ColorMatrixFilter();
    this.filter.hue(rinr(0,360));
    this.sprite = new PIXI.Sprite.fromImage(shitsprite_file);
    this.sprite.scale={x:1.6,y:1.6};
    this.sprite.position={x:WIDTH+5,y:HEIGHT-350};
    this.sprite.filters = [this.filter];
    cMiddle.addChild(this.sprite);
    this.die = function(){
        window.clearInterval(this.movement);
        cMiddle.removeChild(this.sprite);
        testship = new Ship();
    };
    this.leftlevel = 0;
    this.middlelevel = 0;
    this.rightlevel = 0;
    this.bobx = 0;
    this.boby = 0;
    this.move = function(){
        this.sprite.x -= gameState.points+3;
        // TODO: Bobbing...
        // this.bobx += rinr(-100,100)/100000.0;
        // this.boby += rinr(-100,100)/100000.0;
        // this.sprite.anchor = {x:this.bobx, y:this.boby};
        if (this.sprite.x+this.sprite.width<-4) {
            gameState.level += 1;
            this.die();
        }
    }
    this.movement = window.setInterval(function(){ship.move();},20);
}

// Request Animation Frame
function renderStage(){
    requestAnimationFrame(renderStage);
    renderLoop();
    renderer.render(stage);
}

// Called on "Load"-Press
function ingameLoad(){
    // Debug
    gameState.points += 1;
}

// Called on "Unload"-Press
function ingameUnload(){
    // Debug
    gameState.mistakes += 1;
}

// Called in-between rendering
// should be used for logic
function renderLoop(){

}
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var path = require('path');
var logger = require('morgan');
var auth = require('http-auth');

var config = require('./config/config.js');
var confluenceAuth = require('./backend/confluenceAuth.js');
var api = require('./backend/routes');
var adminApi = require('./backend/routes-admin');

var basicAuth = auth.basic({
    realm: 'Nappikauppa v2 - use your speksi-intra account',
  }, function(username, password, cb) {
    confluenceAuth.auth(username, password, config.confluence_auth.groups.base, cb);
  }
);

var app = express();

app.use(logger('dev'));

app.use('/public/', express.static(path.join(__dirname, '/frontend/build/public')));
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/frontend/build/index.html');
});

app.all('/admin*', auth.connect(basicAuth));
app.get('/admin/', function(req, res) {
  res.sendFile(__dirname + '/frontend/build/admin.html');
});

app.use('/api', api);
app.use('/admin-api', adminApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.send({
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.send({
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>direct morgan output to winston for logging HTTP queries<commit_after>'use strict';

var express = require('express');
var path = require('path');
var morgan = require('morgan');
var auth = require('http-auth');

var config = require('./config/config.js');
var confluenceAuth = require('./backend/confluenceAuth.js');
var api = require('./backend/routes');
var adminApi = require('./backend/routes-admin');

var log = require('./backend/log.js');

var basicAuth = auth.basic({
    realm: 'Nappikauppa v2 - use your speksi-intra account',
  }, function(username, password, cb) {
    confluenceAuth.auth(username, password, config.confluence_auth.groups.base, cb);
  }
);

var app = express();

app.use(morgan('combined', {stream: {
  write: function(message) { log.info(message); }
}}));

app.use('/public/', express.static(path.join(__dirname, '/frontend/build/public')));
app.get('/', function(req, res) {
  res.sendFile(__dirname + '/frontend/build/index.html');
});

app.all('/admin*', auth.connect(basicAuth));
app.get('/admin/', function(req, res) {
  res.sendFile(__dirname + '/frontend/build/admin.html');
});

app.use('/api', api);
app.use('/admin-api', adminApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.send({
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('crack', 'crack.png', 16, 6);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = game.add.sprite(0, 0, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = game.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some cracks (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 cracks per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 70, this.game.width, 45);

        for (var i = 1; i <= 7; i++)
        {
            for (var w = 0; w < 7; w++)
            {
                var crack = this.layer.create(area.randomX, area.randomY, 'crack', this.rnd.between(0, 2));
                'crack'.anchor.y = -1.5;
                this.physics.arcade.enable(crack);
                crack.body.velocity.x = -120 + (i * -30);
            }

            area.y += 45;
        }

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 550)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<commit_msg>Create game.js<commit_after>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('crack', 'crack.png', 16, 6);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {

        var town = game.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = game.add.sprite(-100, -100, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = game.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        //  Let's create some cracks (harmless eye candy)
        //
        //  Divide screen vertically into 520px / 8 layers = 65px per layer
        //  Place 8 cracks per layer (8*8 total)

        var area = new Phaser.Rectangle(0, 70, this.game.width, 45);

        for (var i = 1; i <= 7; i++)
        {
            for (var w = 0; w < 7; w++)
            {
                var crack = this.layer.create(area.randomX, area.randomY, 'crack', this.rnd.between(0, 2));
                'crack'.anchor.y = -1.5;
                this.physics.arcade.enable(crack);
                crack.body.velocity.x = -120 + (i * -30);
            }

            area.y += 45;
        }

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 0, 16);
        }
        else
        {
            item.body.setSize(16, 8, 0, 24);
        }

        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 550)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 550;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'abdelkader'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>résolution du conflit<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'abdelkader'));
app.set('view engine', 'kies mohamed');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('kies mohamed abdelkader');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>var game = new Phaser.Game(256, 224, Phaser.AUTO, '', { preload: preload, create: create, update: update }, false, true, null);

var score = 0;
var scoreText;

function preload() {

	game.load.image('sky', 'assets/maps/yoshis-island-1/background.png');
	game.load.image('ground', 'assets/tutorial/platform.png');
	game.load.image('star', 'assets/tutorial/star.png');
	game.load.atlasJSONArray('mario', 'assets/sprites/spritesheets/mario.png', 'assets/sprites/spritesheets/mario.json');
	game.load.atlasJSONArray('items', 'assets/items/items.png', 'assets/items/items.json');

  // scale the game 4x
  game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;
  game.scale.setUserScale(3, 3);

  // enable crisp rendering
  game.renderer.renderSession.roundPixels = true;
  Phaser.Canvas.setImageRenderingCrisp(this.game.canvas)

	// Music
	game.load.audio('Overworld Theme', 'assets/sound/music/2-53\ Overworld\ Theme\ (SMW).mp3')

	// Sound Effects
	game.load.audio('Jump Wav', 'assets/sound/effects/jump.wav');
	game.load.audio('Coin Wav', 'assets/sound/effects/coin.wav');
}

function create() {
	// Enable physics
	game.physics.startSystem(Phaser.Physics.ARCADE);

	// Sky background
	game.add.sprite(0,-200,'sky');

	// Platforms
	platforms = game.add.group();
	platforms.enableBody = true;

	// Ground
	var ground = platforms.create(0, game.world.height - 2, 'ground');
	ground.scale.setTo(2,2);
	ground.body.immovable = true;

	// Music
	music = game.add.audio('Overworld Theme');
  music.play();

	// Sound effects
	jumpWav = game.add.audio('Jump Wav');
	coinWav = game.add.audio('Coin Wav');

	/*
	********************************************
	PLAYER
	********************************************
	*/

	player = game.add.sprite(32, game.world.height - 150, 'mario');
	game.physics.arcade.enable(player);
	player.body.bounce.y = 0;
	player.body.gravity.y = 500;
	player.body.collideWorldBounds = true;

	// default direction
  player.direction = 'right';

	player.anchor.setTo(.5,1);
	player.animations.add('left', [1,0], 10, true);
  player.animations.add('right', [1,0], 10, true);
  // player.animations.play('down', [10], 10, true);
  // player.animations.add('up', [15], 1, true);

	/*
	********************************************
	Coins
	********************************************
	*/

	coins = game.add.group();

	coins.enableBody = true;

	for (var i = 0; i < 12; i++){
		var coin = coins.create(i*70,0,'items');
		coin.frame = 0;
		coin.body.gravity.y = 6;
		coin.body.bounce.y = 0.7 + Math.random() * 0.2;
	}

	/*
	*******************************************
	CONTROLS
	*******************************************
	*/
	// Load arrow key controls
	cursors = game.input.keyboard.createCursorKeys();
	buttons = {
		'A': game.input.keyboard.addKey(Phaser.Keyboard.D),
		'B': game.input.keyboard.addKey(Phaser.Keyboard.S)
	};

	/*
	*******************************************
	SCORE
	*******************************************
	*/
	// scoreText = game.add.text(16, 16, 'Score: 0', { fontSize: '32px', fill: '#000'});

}

function update() {
	var hitPlatform = game.physics.arcade.collide(player, platforms);

	if (player.direction === 'right'){
		player.scale.x = 1;
	} else if (player.direction === 'left'){
		player.scale.x = -1;
	}

	player.body.velocity.x = 0;
	if (cursors.left.isDown){
		player.body.velocity.x = -75;
		player.direction = 'left';
		player.animations.play('left');
	}
	else if (cursors.right.isDown)
	{
		player.body.velocity.x = 75;
		player.direction = 'right';
		player.animations.play('right');
	}
	else
	{
		player.animations.stop();
    if (player.direction === 'left'){
      player.frame = 0;
    } else if (player.direction === 'right'){
		  player.frame = 0;
    }
	}

	if (cursors.up.isDown && player.body.touching.down && hitPlatform)
	{
		player.frame = 2;
	}

	if (cursors.down.isDown && player.body.touching.down && hitPlatform)
	{
		player.frame = 3;
	}

	if (buttons.B.isDown && player.body.touching.down && hitPlatform)
	{
		player.body.velocity.y = -200;
		jumpWav.play();
    // if (player.direction === 'left'){
    //   player.frame = 12;
    // } else if (player.direction === 'right'){
		//   player.frame = 13;
    // }
	}

	game.physics.arcade.collide(coins, platforms);
	game.physics.arcade.overlap(player, coins, collectCoin, null, this);

}

function collectCoin(player, coin) {
	coin.kill();
	coinWav.play();

	score += 10;
	// scoreText.text = 'Score: ' + score;
}
<commit_msg>antialiasing back off<commit_after>var game = new Phaser.Game(256, 224, Phaser.AUTO, '', { preload: preload, create: create, update: update }, false, false, null);

var score = 0;
var scoreText;

function preload() {

	game.load.image('sky', 'assets/maps/yoshis-island-1/background.png');
	game.load.image('ground', 'assets/tutorial/platform.png');
	game.load.image('star', 'assets/tutorial/star.png');
	game.load.atlasJSONArray('mario', 'assets/sprites/spritesheets/mario.png', 'assets/sprites/spritesheets/mario.json');
	game.load.atlasJSONArray('items', 'assets/items/items.png', 'assets/items/items.json');

  // scale the game 4x
  game.scale.scaleMode = Phaser.ScaleManager.USER_SCALE;
  game.scale.setUserScale(3, 3);

  // enable crisp rendering
  game.renderer.renderSession.roundPixels = true;
  Phaser.Canvas.setImageRenderingCrisp(this.game.canvas)

	// Music
	game.load.audio('Overworld Theme', 'assets/sound/music/2-53\ Overworld\ Theme\ (SMW).mp3')

	// Sound Effects
	game.load.audio('Jump Wav', 'assets/sound/effects/jump.wav');
	game.load.audio('Coin Wav', 'assets/sound/effects/coin.wav');
}

function create() {
	// Enable physics
	game.physics.startSystem(Phaser.Physics.ARCADE);

	// Sky background
	game.add.sprite(0,-200,'sky');

	// Platforms
	platforms = game.add.group();
	platforms.enableBody = true;

	// Ground
	var ground = platforms.create(0, game.world.height - 2, 'ground');
	ground.scale.setTo(2,2);
	ground.body.immovable = true;

	// Music
	music = game.add.audio('Overworld Theme');
  music.play();

	// Sound effects
	jumpWav = game.add.audio('Jump Wav');
	coinWav = game.add.audio('Coin Wav');

	/*
	********************************************
	PLAYER
	********************************************
	*/

	player = game.add.sprite(32, game.world.height - 150, 'mario');
	game.physics.arcade.enable(player);
	player.body.bounce.y = 0;
	player.body.gravity.y = 500;
	player.body.collideWorldBounds = true;

	// default direction
  player.direction = 'right';

	player.anchor.setTo(.5,1);
	player.animations.add('left', [1,0], 10, true);
  player.animations.add('right', [1,0], 10, true);
  // player.animations.play('down', [10], 10, true);
  // player.animations.add('up', [15], 1, true);

	/*
	********************************************
	Coins
	********************************************
	*/

	coins = game.add.group();

	coins.enableBody = true;

	for (var i = 0; i < 12; i++){
		var coin = coins.create(i*70,0,'items');
		coin.frame = 0;
		coin.body.gravity.y = 6;
		coin.body.bounce.y = 0.7 + Math.random() * 0.2;
	}

	/*
	*******************************************
	CONTROLS
	*******************************************
	*/
	// Load arrow key controls
	cursors = game.input.keyboard.createCursorKeys();
	buttons = {
		'A': game.input.keyboard.addKey(Phaser.Keyboard.D),
		'B': game.input.keyboard.addKey(Phaser.Keyboard.S)
	};

	/*
	*******************************************
	SCORE
	*******************************************
	*/
	// scoreText = game.add.text(16, 16, 'Score: 0', { fontSize: '32px', fill: '#000'});

}

function update() {
	var hitPlatform = game.physics.arcade.collide(player, platforms);

	if (player.direction === 'right'){
		player.scale.x = 1;
	} else if (player.direction === 'left'){
		player.scale.x = -1;
	}

	player.body.velocity.x = 0;
	if (cursors.left.isDown){
		player.body.velocity.x = -75;
		player.direction = 'left';
		player.animations.play('left');
	}
	else if (cursors.right.isDown)
	{
		player.body.velocity.x = 75;
		player.direction = 'right';
		player.animations.play('right');
	}
	else
	{
		player.animations.stop();
    if (player.direction === 'left'){
      player.frame = 0;
    } else if (player.direction === 'right'){
		  player.frame = 0;
    }
	}

	if (cursors.up.isDown && player.body.touching.down && hitPlatform)
	{
		player.frame = 2;
	}

	if (cursors.down.isDown && player.body.touching.down && hitPlatform)
	{
		player.frame = 3;
	}

	if (buttons.B.isDown && player.body.touching.down && hitPlatform)
	{
		player.body.velocity.y = -200;
		jumpWav.play();
    // if (player.direction === 'left'){
    //   player.frame = 12;
    // } else if (player.direction === 'right'){
		//   player.frame = 13;
    // }
	}

	game.physics.arcade.collide(coins, platforms);
	game.physics.arcade.overlap(player, coins, collectCoin, null, this);

}

function collectCoin(player, coin) {
	coin.kill();
	coinWav.play();

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


<commit_before>var getApp = function (config) {
	var express = require('express');
	var app = express();
	var bodyParser=require('body-parser');
	var methodOverride=require('method-override');
	var cookieParser=require('cookie-parser');
	var errorHandler=require('errorhandler');
	//middleware
	function local_env (req, res, next){
		res.local.real_time_server=config.server.production.real_time_server;
		next();
	}

		app.set('views', __dirname + '/views');
		app.set('view engine', 'ejs');
		app.engine('.html', require('ejs').renderFile);
		app.engine('.ejs', require('ejs').renderFile);
		app.use(bodyParser());
		app.use(methodOverride());
		app.use(cookieParser());

		app.use(local_env);

		var oneYear = 31557600000;
		app.use(express.static(__dirname + '/public', { maxAge: oneYear }));

	  app.use(errorHandler({ dumpExceptions: true, showStack: true }));

	//routes
	require('./routes/index').configure(app);

	return app;
};

exports.getApp = getApp;
<commit_msg>update express from 2.5 to 4<commit_after>var getApp = function (config) {
	var express = require('express');
	var app = express();
	var bodyParser=require('body-parser');
	var methodOverride=require('method-override');
	var cookieParser=require('cookie-parser');
	var errorHandler=require('errorhandler');

		app.set('views', __dirname + '/views');
		app.set('view engine', 'ejs');
		app.engine('.html', require('ejs').renderFile);
		app.engine('.ejs', require('ejs').renderFile);
		app.use(bodyParser());
		app.use(methodOverride());
		app.use(cookieParser());

	//middleware
		app.use(function(req, res, next){
                	res.locals.real_time_server=config.server.production.real_time_server;
                	next();
        	});

		var oneYear = 31557600000;
		app.use(express.static(__dirname + '/public', { maxAge: oneYear }));

	  app.use(errorHandler({ dumpExceptions: true, showStack: true }));

	//routes
	require('./routes/index').configure(app);

	return app;
};

exports.getApp = getApp;
<|endoftext|>


<commit_before>var events = require('../events.js');

var User = function(options) {
  options = options || {};
  this.id = options.id;
  this.email = options.email;
  this.token = options.token;
};
User.prototype.isAuthenticated = function() {
  return this.token ? true : false;
};
User.prototype.getToken = function() {
  return this.token;
};
User.prototype.update = function(data) {
  var changed = false;
  if (!data) { return this; }

  ['id', 'email', 'token'].forEach(function(prop) {
    if(prop in data && data[prop] !== this[prop]) {
      this[prop] = data[prop];
      changed = true;
    }
  }, this);

  if(changed) {
    this.triggerChange();
  }
  return this;
};
User.prototype.reset = function() {
  return this.update({id:undefined,email:undefined,token:undefined});
};
User.prototype.saveLogin = function() {
  if (!this.isAuthenticated()) {
    localStorage.removeItem("wordmapper-user");
    return this;
  }
  if (!window.localStorage) {
    return this;
  }
  var data = {id: this.id, email: this.email, token: this.token};
  data.expires = new Date();
  data.expires.setHours(data.expires.getHours() + 3);

  localStorage.setItem("wordmapper-user", JSON.stringify(data));
  return this;
};
User.prototype.restoreLogin = function() {
  var result = null;
  if (!window.localStorage) {
    return this;
  }
  result = localStorage.getItem("wordmapper-user");
  if (result === null) {
    return this;
  }
  result = JSON.parse(result);

  var expires = new Date(result.expires);
  var now = new Date();
  if (now >= expires) {
    localStorage.removeItem("wordmapper-user");
    return this;
  }

  return this.update(result);
};
User.prototype.triggerChange = function() {
  this.trigger("change");
};
User.prototype.toString = function() {
  return this.email || 'guest';
};
User.prototype.toJSON = function() {
  return {
    "type": "user",
    "data": {
      "id": this.id,
      "email": this.email
    }
  };
};
User.prototype.serialize = function() {
  return JSON.stringify(this.toJSON(), null, '\t');
};
events.Events.mixin(User.prototype);

module.exports = User;
<commit_msg>Update user.js<commit_after>var events = require('../events.js');

var User = function(options) {
  options = options || {};
  this.id = options.id;
  this.email = options.email;
  this.token = options.token;
};
User.prototype.isAuthenticated = function() {
  return this.token ? true : false;
};
User.prototype.getToken = function() {
  return this.token;
};
User.prototype.update = function(data) {
  var changed = false;
  if (!data) { return this; }

  ['id', 'email', 'token'].forEach(function(prop) {
    if(prop in data && data[prop] !== this[prop]) {
      this[prop] = data[prop];
      changed = true;
    }
  }, this);

  if(changed) {
    this.triggerChange();
  }
  return this;
};
User.prototype.reset = function() {
  return this.update({id:undefined,email:undefined,token:undefined});
};
User.prototype.saveLogin = function() {
  if (!window.localStorage) {
    return this;
  }
  if (!this.isAuthenticated()) {
    localStorage.removeItem("wordmapper-user");
    return this;
  }

  var data = {id: this.id, email: this.email, token: this.token};
  data.expires = new Date();
  data.expires.setHours(data.expires.getHours() + 3);

  localStorage.setItem("wordmapper-user", JSON.stringify(data));
  return this;
};
User.prototype.restoreLogin = function() {
  var result = null;
  if (!window.localStorage) {
    return this;
  }
  result = localStorage.getItem("wordmapper-user");
  if (result === null) {
    return this;
  }
  result = JSON.parse(result);

  var expires = new Date(result.expires);
  var now = new Date();
  if (now >= expires) {
    localStorage.removeItem("wordmapper-user");
    return this;
  }

  return this.update(result);
};
User.prototype.triggerChange = function() {
  this.trigger("change");
};
User.prototype.toString = function() {
  return this.email || 'guest';
};
User.prototype.toJSON = function() {
  return {
    "type": "user",
    "data": {
      "id": this.id,
      "email": this.email
    }
  };
};
User.prototype.serialize = function() {
  return JSON.stringify(this.toJSON(), null, '\t');
};
events.Events.mixin(User.prototype);

module.exports = User;
<|endoftext|>


<commit_before>import "base";
import "../toolbar/button"
import "../utils/icons"

mpld3.BoxZoomPlugin = mpld3_BoxZoomPlugin;
mpld3.register_plugin("boxzoom", mpld3_BoxZoomPlugin);
mpld3_BoxZoomPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_BoxZoomPlugin.prototype.constructor = mpld3_BoxZoomPlugin;
mpld3_BoxZoomPlugin.prototype.requiredProps = [];
mpld3_BoxZoomPlugin.prototype.defaultProps = {
    button: true,
    enabled: null
};

function mpld3_BoxZoomPlugin(fig, props) {
    mpld3_Plugin.call(this, fig, props);
    if (this.props.enabled === null){
        this.props.enabled = !(this.props.button);
    }

    var enabled = this.props.enabled;
    if (this.props.button){
	// add a button to enable/disable box zoom
	var BoxZoomButton = mpld3.ButtonFactory({
	    buttonID: "boxzoom",
            sticky: true,
            actions: ["drag"],
	    onActivate: this.activate.bind(this),
	    onDeactivate: this.deactivate.bind(this),
            onDraw: function(){this.setState(enabled);},
	    icon: function(){return mpld3.icons["zoom"];},
	});
	this.fig.buttons.push(BoxZoomButton);
    }
    this.extentClass = "boxzoombrush";
}

mpld3_BoxZoomPlugin.prototype.activate = function(){
    if(this.enable) this.enable();
};

mpld3_BoxZoomPlugin.prototype.deactivate = function(){
    if(this.disable) this.disable();
};

mpld3_BoxZoomPlugin.prototype.draw = function(){
    mpld3.insert_css("#" + this.fig.figid + " rect.extent." + this.extentClass,
		     {"fill": "#fff",
                      "fill-opacity": 0,
                      "stroke": "#999"});

    // getBrush is a d3.svg.brush() object, set up for use on the figure.
    var brush = this.fig.getBrush();

    this.enable = function(){
        this.fig.showBrush(this.extentClass);
        brush.on("brushend", brushend.bind(this));
        this.enabled = true;
    }

    this.disable = function(){
        this.fig.hideBrush(this.extentClass);
        this.enabled = false;
    }

    this.toggle = function(){
	this.enabled ? this.disable() : this.enable();
    }

    function brushend(d){
	if(this.enabled){
	    var extent = brush.extent();
            if(!brush.empty()){
		d.set_axlim([extent[0][0], extent[1][0]],
		            [extent[0][1], extent[1][1]]);
            }
	}
	d.axes.call(brush.clear());
    }
    this.disable();
}

<commit_msg>Fix indents/style in boxzoom.js<commit_after>import "base";
import "../toolbar/button"
import "../utils/icons"

mpld3.BoxZoomPlugin = mpld3_BoxZoomPlugin;
mpld3.register_plugin("boxzoom", mpld3_BoxZoomPlugin);
mpld3_BoxZoomPlugin.prototype = Object.create(mpld3_Plugin.prototype);
mpld3_BoxZoomPlugin.prototype.constructor = mpld3_BoxZoomPlugin;
mpld3_BoxZoomPlugin.prototype.requiredProps = [];
mpld3_BoxZoomPlugin.prototype.defaultProps = {
    button: true,
    enabled: null
};

function mpld3_BoxZoomPlugin(fig, props) {
    mpld3_Plugin.call(this, fig, props);
    if (this.props.enabled === null) {
        this.props.enabled = !(this.props.button);
    }

    var enabled = this.props.enabled;
    if (this.props.button) {
        // add a button to enable/disable box zoom
        var BoxZoomButton = mpld3.ButtonFactory({
            buttonID: "boxzoom",
            sticky: true,
            actions: ["drag"],
            onActivate: this.activate.bind(this),
            onDeactivate: this.deactivate.bind(this),
            onDraw: function() { this.setState(enabled); },
            icon: function() { return mpld3.icons["zoom"]; },
        });
        this.fig.buttons.push(BoxZoomButton);
    }
    this.extentClass = "boxzoombrush";
}

mpld3_BoxZoomPlugin.prototype.activate = function(){
    if (this.enable) this.enable();
};

mpld3_BoxZoomPlugin.prototype.deactivate = function(){
    if (this.disable) this.disable();
};

mpld3_BoxZoomPlugin.prototype.draw = function(){
    mpld3.insert_css(
        "#" + this.fig.figid + " rect.extent." + this.extentClass,
        {
            "fill": "#fff",
            "fill-opacity": 0,
            "stroke": "#999",
        }
    );

    // getBrush is a d3.svg.brush() object, set up for use on the figure.
    var brush = this.fig.getBrush();

    this.enable = function() {
        this.fig.showBrush(this.extentClass);
        brush.on("brushend", brushend.bind(this));
        this.enabled = true;
    }

    this.disable = function() {
        this.fig.hideBrush(this.extentClass);
        this.enabled = false;
    }

    this.toggle = function() {
        this.enabled ? this.disable() : this.enable();
    }

    function brushend(d) {
        if (this.enabled) {
            var extent = brush.extent();
            if (!brush.empty()) {
                d.set_axlim([extent[0][0], extent[1][0]],
                [extent[0][1], extent[1][1]]);
            }
        }
        d.axes.call(brush.clear());
    }

    this.disable();
}

<|endoftext|>


<commit_before>// ==========================================================================
// UnorderedList
// ==========================================================================

// Init
// --------------------------------------------------------------------------

var express        = require('express'),
    app            = express(),
    server         = require('http').createServer(app),
    io             = require('socket.io').listen(server),
    mongoose       = require('mongoose');

// Connect
// --------------------------------------------------------------------------

server.listen(3000);

mongoose.connect('mongodb://localhost/ul', function (err) {
  if(err) {
    console.error(err);
  } else {
    console.log('...Connected to mongodb');
  }
});

// Schema
// --------------------------------------------------------------------------

var listSchema = mongoose.Schema({
                   name: String,
                   items: [{
                     body: String,
                     active: Boolean,
                     id: mongoose.Schema.Types.ObjectId,
                     added: { type: Date, default: Date.now }
                   }],
                   date: { type: Date, default: Date.now }
                 }),
          List = mongoose.model('List', listSchema);

// Config
// --------------------------------------------------------------------------

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});
app.use('/css', express.static(__dirname + '/css'));
app.use('/js', express.static(__dirname + '/js'));

// Events
// --------------------------------------------------------------------------

io.sockets.on('connection', function (socket) {

  // user connected
  console.log('User Connected - ' + new Date());

  // load list
  socket.on('load list', function (data) {
    List.find({ 'name' : data }, function (err, doc) {
      if(err) {
        console.error(err);

      // create new
      } else if (!doc.length) {
        var new_list = new List({ name: data });
        new_list.save( function (err) {
          if (err) {
            console.error(err);

          } else {
            socket.list_name = data;
            socket.emit('new list');
          }
        });

      // load history
      } else {
        socket.list_name = data;
        List.find({ name: socket.list_name }, function (err, docs) {
          if(err) {
            console.error(err);

          } else {
            socket.emit('load list', docs[0].items);
          }
        });
      }
    });
  });

  // add item
  socket.on('add item', function (data) {
    List.findOne({ name: socket.list_name }, function (err, doc) {
      if(err) {
        console.error(err);

      // save + update
      } else {

        // TODO Check if item exists first...

        data = {
          body: data,
          active: true,
          itemId: new mongoose.Types.ObjectId,
          added: new Date
        };
        doc.items.push(data);
        doc.save( function (err) {
          if(err) {
            console.error(err);
          } else {
            io.sockets.emit('add item', data);
          }
        });
      }
    });
  });

  // TODO disconnect

});
<commit_msg>add disconnect event logger<commit_after>// ==========================================================================
// UnorderedList
// ==========================================================================

// Init
// --------------------------------------------------------------------------

var express        = require('express'),
    app            = express(),
    server         = require('http').createServer(app),
    io             = require('socket.io').listen(server),
    mongoose       = require('mongoose');

// Connect
// --------------------------------------------------------------------------

server.listen(3000);

mongoose.connect('mongodb://localhost/ul', function (err) {
  if(err) {
    console.error(err);
  } else {
    console.log('...Connected to mongodb');
  }
});

// Schema
// --------------------------------------------------------------------------

var listSchema = mongoose.Schema({
                   name: String,
                   items: [{
                     body: String,
                     active: Boolean,
                     id: mongoose.Schema.Types.ObjectId,
                     added: { type: Date, default: Date.now }
                   }],
                   date: { type: Date, default: Date.now }
                 }),
          List = mongoose.model('List', listSchema);

// Config
// --------------------------------------------------------------------------

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});
app.use('/css', express.static(__dirname + '/css'));
app.use('/js', express.static(__dirname + '/js'));

// Events
// --------------------------------------------------------------------------

io.sockets.on('connection', function (socket) {

  // user connected
  console.log('User Connected - ' + new Date());

  // load list
  socket.on('load list', function (data) {
    List.find({ 'name' : data }, function (err, doc) {
      if(err) {
        console.error(err);

      // create new
      } else if (!doc.length) {
        var new_list = new List({ name: data });
        new_list.save( function (err) {
          if (err) {
            console.error(err);

          } else {
            socket.list_name = data;
            socket.emit('new list');
          }
        });

      // load history
      } else {
        socket.list_name = data;
        List.find({ name: socket.list_name }, function (err, docs) {
          if(err) {
            console.error(err);

          } else {
            socket.emit('load list', docs[0].items);
          }
        });
      }
    });
  });

  // add item
  socket.on('add item', function (data) {
    List.findOne({ name: socket.list_name }, function (err, doc) {
      if(err) {
        console.error(err);

      // save + update
      } else {

        // TODO Check if item exists first...

        data = {
          body: data,
          active: true,
          itemId: new mongoose.Types.ObjectId,
          added: new Date
        };
        doc.items.push(data);
        doc.save( function (err) {
          if(err) {
            console.error(err);
          } else {
            io.sockets.emit('add item', data);
          }
        });
      }
    });
  });

  // user disconnected
  socket.on('disconnect', function () {
    console.log('User Disconnected - ' + new Date());
  });

});
<|endoftext|>