<commit_before>/**
 * This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server.
 * Static file Requests are answered directly from this module, Socket.IO messages are passed
 * to MessageHandler and minfied requests are passed to minified.
 */

/*
 * 2011 Peter 'Pita' Martischka
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require('joose');

var socketio = require('socket.io');
var fs = require('fs');
var settings = require('./settings');
var socketIORouter = require("./SocketIORouter");
var db = require('./db');
var async = require('async');
var express = require('express');
var path = require('path');
var minify = require('./minify');
var exportHandler;
var importHandler;
var exporthtml;
var readOnlyManager;

//try to get the git version
var version = "";
try
{
  var ref = fs.readFileSync("../.git/HEAD", "utf-8");
  var refPath = "../.git/" + ref.substring(5, ref.indexOf("\n"));
  version = fs.readFileSync(refPath, "utf-8");
  version = version.substring(0, 8);
}
catch(e)
{
  console.error("Can't get git version for server header\n" + e.message)
}

var serverName = "Etherpad-Lite " + version + " (http://j.mp/ep-lite)";

//cache 6 hours
exports.maxAge = 1000*60*60*6;

async.waterfall([
  //initalize the database
  function (callback)
  {
    db.init(callback);
  },
  //initalize the http server
  function (callback)
  {
    //create server
    var app = express.createServer();

    //load modules that needs a initalized db
    readOnlyManager = require("./ReadOnlyManager");
    exporthtml = require("./exporters/exporthtml");
    exportHandler = require('./ExportHandler');
    importHandler = require('./ImportHandler');

    //set logging
    if(settings.logHTTP)
      app.use(express.logger({ format: ':date: :status, :method :url' }));

    //serve static files
    app.get('/static/*', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/.." + req.url.split("?")[0]);
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve minified files
    app.get('/minified/:id', function(req, res)
    {
      res.header("Server", serverName);

      var id = req.params.id;

      if(id == "pad.js")
      {
        minify.padJS(req,res);
      }
      else
      {
        res.send('404 - Not Found', 404);
      }
    });

    //serve read only pad
    app.get('/ro/:id', function(req, res)
    {
      res.header("Server", serverName);

      var html;
      var padId;
      var pad;

      async.series([
        //translate the read only pad to a padId
        function(callback)
        {
          readOnlyManager.getPadId(req.params.id, function(err, _padId)
          {
            padId = _padId;
            callback(err);
          });
        },
        //render the html document
        function(callback)
        {
          //return if the there is no padId
          if(padId == null)
          {
            callback("notfound");
            return;
          }

          //render the html document
          exporthtml.getPadHTMLDocument(padId, null, false, function(err, _html)
          {
            html = _html;
            callback(err);
          });
        }
      ], function(err)
      {
        //throw any unexpected error
        if(err && err != "notfound")
          throw err;

        if(err == "notfound")
          res.send('404 - Not Found', 404);
        else
          res.send(html);
      });
    });

    //serve pad.html under /p
    app.get('/p/:pad', function(req, res, next)
    {
      //ensure the padname is valid and the url doesn't end with a /
      if(!isValidPadname(req.params.pad) || /\/$/.test(req.url))
      {
        next();
        return;
      }

      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/pad.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve timeslider.html under /p/$padname/timeslider
    app.get('/p/:pad/timeslider', function(req, res, next)
    {
      //ensure the padname is valid and the url doesn't end with a /
      if(!isValidPadname(req.params.pad) || /\/$/.test(req.url))
      {
        next();
        return;
      }

      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/timeslider.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve timeslider.html under /p/$padname/timeslider
    app.get('/p/:pad/export/:type', function(req, res, next)
    {
      var types = ["pdf", "doc", "txt", "html", "odt"];
      //send a 404 if we don't support this filetype
      if(types.indexOf(req.params.type) == -1)
      {
        next();
        return;
      }

      //if abiword is disabled, and this is a format we only support with abiword, output a message
      if(settings.abiword == null && req.params.type != "html" && req.params.type != "txt" )
      {
        res.send("Abiword is not enabled at this Etherpad Lite instance. Set the path to Abiword in settings.json to enable this feature");
        return;
      }

      res.header("Server", serverName);
      exportHandler.doExport(req, res, req.params.pad, req.params.type);
    });

    //handle import requests
    app.post('/p/:pad/import', function(req, res, next)
    {
      //if abiword is disabled, skip handling this request
      if(settings.abiword == null)
      {
        next();
        return;
      }

      res.header("Server", serverName);
      importHandler.doImport(req, res, req.params.pad);
    });

    //serve index.html under /
    app.get('/', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/index.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve robots.txt
    app.get('/robots.txt', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/robots.txt");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve favicon.ico
    app.get('/favicon.ico', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/favicon.ico");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //let the server listen
    app.listen(settings.port);
    console.log("Server is listening at port " + settings.port);

    //init socket.io and redirect all requests to the MessageHandler
    var io = socketio.listen(app);

    //this is only a workaround to ensure it works with all browers behind a proxy
    //we should remove this when the new socket.io version is more stable
    io.set('transports', ['xhr-polling']);

    //reduce the log level
    io.set('log level', 2);

    var padMessageHandler = require("./PadMessageHandler");
    var timesliderMessageHandler = require("./TimesliderMessageHandler");

    //Initalize the Socket.IO Router
    socketIORouter.setSocketIO(io);
    socketIORouter.addComponent("pad", padMessageHandler);
    socketIORouter.addComponent("timeslider", timesliderMessageHandler);

    callback(null);
  }
]);

function isValidPadname(padname)
{
  //ensure there is no dollar sign in the pad name
  if(padname.indexOf("$")!=-1)
    return false;

  return true;
}
<commit_msg>Log the disconnect diagnostic info that etherpad still sends. Maybe thats usefull<commit_after>/**
 * This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server.
 * Static file Requests are answered directly from this module, Socket.IO messages are passed
 * to MessageHandler and minfied requests are passed to minified.
 */

/*
 * 2011 Peter 'Pita' Martischka
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require('joose');

var socketio = require('socket.io');
var fs = require('fs');
var settings = require('./settings');
var socketIORouter = require("./SocketIORouter");
var db = require('./db');
var async = require('async');
var express = require('express');
var path = require('path');
var minify = require('./minify');
var formidable = require('formidable');
var exportHandler;
var importHandler;
var exporthtml;
var readOnlyManager;

//try to get the git version
var version = "";
try
{
  var ref = fs.readFileSync("../.git/HEAD", "utf-8");
  var refPath = "../.git/" + ref.substring(5, ref.indexOf("\n"));
  version = fs.readFileSync(refPath, "utf-8");
  version = version.substring(0, 8);
}
catch(e)
{
  console.error("Can't get git version for server header\n" + e.message)
}

var serverName = "Etherpad-Lite " + version + " (http://j.mp/ep-lite)";

//cache 6 hours
exports.maxAge = 1000*60*60*6;

async.waterfall([
  //initalize the database
  function (callback)
  {
    db.init(callback);
  },
  //initalize the http server
  function (callback)
  {
    //create server
    var app = express.createServer();

    //load modules that needs a initalized db
    readOnlyManager = require("./ReadOnlyManager");
    exporthtml = require("./exporters/exporthtml");
    exportHandler = require('./ExportHandler');
    importHandler = require('./ImportHandler');

    //set logging
    if(settings.logHTTP)
      app.use(express.logger({ format: ':date: :status, :method :url' }));

    //serve static files
    app.get('/static/*', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/.." + req.url.split("?")[0]);
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve minified files
    app.get('/minified/:id', function(req, res)
    {
      res.header("Server", serverName);

      var id = req.params.id;

      if(id == "pad.js")
      {
        minify.padJS(req,res);
      }
      else
      {
        res.send('404 - Not Found', 404);
      }
    });

    //serve read only pad
    app.get('/ro/:id', function(req, res)
    {
      res.header("Server", serverName);

      var html;
      var padId;
      var pad;

      async.series([
        //translate the read only pad to a padId
        function(callback)
        {
          readOnlyManager.getPadId(req.params.id, function(err, _padId)
          {
            padId = _padId;
            callback(err);
          });
        },
        //render the html document
        function(callback)
        {
          //return if the there is no padId
          if(padId == null)
          {
            callback("notfound");
            return;
          }

          //render the html document
          exporthtml.getPadHTMLDocument(padId, null, false, function(err, _html)
          {
            html = _html;
            callback(err);
          });
        }
      ], function(err)
      {
        //throw any unexpected error
        if(err && err != "notfound")
          throw err;

        if(err == "notfound")
          res.send('404 - Not Found', 404);
        else
          res.send(html);
      });
    });

    //serve pad.html under /p
    app.get('/p/:pad', function(req, res, next)
    {
      //ensure the padname is valid and the url doesn't end with a /
      if(!isValidPadname(req.params.pad) || /\/$/.test(req.url))
      {
        next();
        return;
      }

      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/pad.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve timeslider.html under /p/$padname/timeslider
    app.get('/p/:pad/timeslider', function(req, res, next)
    {
      //ensure the padname is valid and the url doesn't end with a /
      if(!isValidPadname(req.params.pad) || /\/$/.test(req.url))
      {
        next();
        return;
      }

      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/timeslider.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve timeslider.html under /p/$padname/timeslider
    app.get('/p/:pad/export/:type', function(req, res, next)
    {
      var types = ["pdf", "doc", "txt", "html", "odt"];
      //send a 404 if we don't support this filetype
      if(types.indexOf(req.params.type) == -1)
      {
        next();
        return;
      }

      //if abiword is disabled, and this is a format we only support with abiword, output a message
      if(settings.abiword == null && req.params.type != "html" && req.params.type != "txt" )
      {
        res.send("Abiword is not enabled at this Etherpad Lite instance. Set the path to Abiword in settings.json to enable this feature");
        return;
      }

      res.header("Server", serverName);
      exportHandler.doExport(req, res, req.params.pad, req.params.type);
    });

    //handle import requests
    app.post('/p/:pad/import', function(req, res, next)
    {
      //if abiword is disabled, skip handling this request
      if(settings.abiword == null)
      {
        next();
        return;
      }

      res.header("Server", serverName);
      importHandler.doImport(req, res, req.params.pad);
    });

    //The Etherpad client side sends information about how a disconnect happen
    //I don't know how to use them, but maybe there usefull, so we should print them out to the log
    app.post('/ep/pad/connection-diagnostic-info', function(req, res)
    {
      new formidable.IncomingForm().parse(req, function(err, fields, files)
      {
        console.log(new Date().toUTCString() + ": DIAGNOSTIC-INFO: " + fields.diagnosticInfo);
        res.end("OK");
      });
    });

    //serve index.html under /
    app.get('/', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/index.html");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve robots.txt
    app.get('/robots.txt', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/robots.txt");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //serve favicon.ico
    app.get('/favicon.ico', function(req, res)
    {
      res.header("Server", serverName);
      var filePath = path.normalize(__dirname + "/../static/favicon.ico");
      res.sendfile(filePath, { maxAge: exports.maxAge });
    });

    //let the server listen
    app.listen(settings.port);
    console.log("Server is listening at port " + settings.port);

    //init socket.io and redirect all requests to the MessageHandler
    var io = socketio.listen(app);

    //this is only a workaround to ensure it works with all browers behind a proxy
    //we should remove this when the new socket.io version is more stable
    io.set('transports', ['xhr-polling']);

    //reduce the log level
    io.set('log level', 2);

    var padMessageHandler = require("./PadMessageHandler");
    var timesliderMessageHandler = require("./TimesliderMessageHandler");

    //Initalize the Socket.IO Router
    socketIORouter.setSocketIO(io);
    socketIORouter.addComponent("pad", padMessageHandler);
    socketIORouter.addComponent("timeslider", timesliderMessageHandler);

    callback(null);
  }
]);

function isValidPadname(padname)
{
  //ensure there is no dollar sign in the pad name
  if(padname.indexOf("$")!=-1)
    return false;

  return true;
}
<|endoftext|>


<commit_before>(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        var oldFuzz = window.Fuzz;
        var api window.Fuzz = factory();
        api.noConflict = function () {
            window.Fuzz = oldFuzz;
            return api;
        };
    }
}(function () {
    // Internal functions

    var prepareCollection = function (collection) {
        var _this = this;

        var newCollection = [];
        var length = collection.length;

        for (var i = length; i >= 0; i--) {
            newCollection.push(collection[i]);
        }
    };

    var indexIsSectionStart = function (string, index) {
        return  index === 0 ||
                (string[index].toUpperCase() === string[index] &&
                    (index === 1 ||
                     string[index - 1].toUpperCase() !== string[index - 1]));
    };

    var prepareItem = function(name) {

    }

    // Main obj
    var Fuzz = function (collection) {
        this.main = collection;
        this.collection = prepareCollection.call(this, this.main);

        return this;
    };

    Fuzz.prototype.match = function (string) {
        var input = string;
        var query = input.replace(/\s+/g, '').split('');
    };

    // Item obj
    var Item = function(name) {
        this.name = name;

        return this;
    };
}));<commit_msg>Adds matching algorithm<commit_after>(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        var oldFuzz = window.Fuzz;
        var api = window.Fuzz = factory();
        api.noConflict = function () {
            window.Fuzz = oldFuzz;
            return api;
        };
    }
}(function () {
    // Internal functions

    var prepareCollection = function (collection) {
        var _this = this;
        var newCollection = [];
        var l = collection.length;

        for (var i = 0; i < l; i++) {
            newCollection.push(new Item(collection[i], i));
        }

        return newCollection;
    };

    var indexIsSectionStart = function (string, index) {
        return  index === 0 ||
                (string[index].toUpperCase() === string[index] &&
                    (index === 1 ||
                     string[index - 1].toUpperCase() !== string[index - 1]));
    };

    var prepareItem = function (nameArray) {
        var detailedItem = [];
        var detailedChar;
        var l = nameArray.length;
        for (var i = 0; i < l; i++) {
            detailedChar = {
                index: i,
                c: nameArray[i],
                beginSection: indexIsSectionStart(nameArray, i),
                w: 0
            };

            detailedItem.push(detailedChar);
        }

        return detailedItem;
    };

    // Main obj
    var Fuzz = function (collection, options) {
        options || (options = {});

        this.main = collection;
        this.collection = prepareCollection.call(this, this.main);

        return this;
    };

    Fuzz.prototype.match = function (string) {
        var input = string;
        var query = input.replace(/\s+/g, '').toLowerCase();

        var l = this.collection.length;
        var results = [];

        for (var i = 0; i < l; i++) {
            var match = this.collection[i].match(query);

            if (match) results.push(this.collection[i]);
        }

        return results;
    };

    // Item obj
    var Item = function(name, index) {
        this.name = this.parse(name);
        this.nameArray = this.name.split('');
        this.detailed = prepareItem(this.nameArray);

        return this;
    };

    Item.prototype.parse = function(item) {
        return item;
    };

    Item.prototype.clearWeight = function () {
        var l = this.detailed.length;
        for (var i = 0; i < l; i++) {
            this.detailed[i].w = 0;
        }
    };

    Item.prototype.match = function (string) {
        var matchIndex = [];
        var searchIndex = -1;
        var lookUpper = true;
        var testName = this.name;

        for (var i = 0; i < string.length; i++) {
            var currentChar = string.charAt(i);

            if (lookUpper) {
                testName = this.name;
                currentChar = currentChar.toUpperCase();
            }

            if (!lookUpper) testName = testName.toLowerCase();

            if (searchIndex >= this.name.length) return false;

            searchIndex = testName.indexOf(currentChar, searchIndex + 1);

            if (searchIndex > -1) {
                matchIndex.push(searchIndex);
            } else {
                if (lookUpper === false) {
                    matchIndex = [];
                    break;
                }

                if (lookUpper === true) {
                    i -= 1;
                    searchIndex = matchIndex[matchIndex.length -1] || -1;
                }

                lookUpper = !lookUpper;
            }
        }

        this.matched = matchIndex.length ? matchIndex : false;

        return !!(this.matched.length);
    };

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


<commit_before>//Objects demo

//villain damage health

//inheritance skeleton zombie

//prototypal
<commit_msg>add objectsDemo<commit_after>//Objects demo

//villain damage health

//inheritance skeleton zombie

//prototypal

/**
 * This is how things inherit in javascript
 *
**/

//make a Villain constructor
function Villain(damage, health){
    this.damage = damage;
    this.health = health;
}

//make a Skeleton (a villain)
function Skeleton(numberOfBones){
    this.damage = 5;
    this.health = 7;

    this.numberOfBones = numberOfBones;
}

Skeleton.prototype = new Villain();

//make a Zombie (a villain)
function Zombie(hungerLevel){
    this.damage = 2;
    this.health = 20;

    this.hungerLevel = hungerLevel;
}

Zombie.prototype = new Villain();

<|endoftext|>


<commit_before>
//Settings:
var backgroundColor = "#000000";
var elementColor = "#FFFFFF";
var initialBallSpeed = 20; //How many px should we move per frame?
var initialBallK = 3;

var canvas = document.getElementById("arena");
var height = window.innerHeight;
var width = window.innerWidth;

//canvas.style.backgroundColor = "#000000";
document.getElementsByName("body").height = height;
canvas.height = height;
canvas.width = width;

var ctx = canvas.getContext("2d");

//Draw background
ctx.fillStyle = backgroundColor;
ctx.fillRect(0,0,canvas.width, canvas.height);

var Ball = function(height, width, startX, startY, boundX, boundY){
    this.color = elementColor;
    this.height = height;
    this.width = width;

    //Where is the ball?
    this.x = startX;
    this.y = startY;

    //where is the center of the ball?
    this.centerX = this.x + width/2;
    this.centerY = this.y + height/2;

    //How much should we move each frame?
    this.velocity = initialBallSpeed;
    this.k = initialBallK;
    this.right = 1; //Should the ball go left or right? Right = 1, left = -1
    this.dX = null;
    this.dY = null;
    this.angle = Math.atan(this.k); //angle from horizontal plane
    if (this.right == -1) this.angle = this.angle + Math.PI;

    this.oldX = null;
    this.oldY = null;

    this.boundX = boundX;
    this.boundY = boundY;
};

Ball.prototype.draw = function(canvasDrawer){
    //first clear the ball
    ctx.fillStyle = backgroundColor;
    ctx.clearRect(ball.oldX, ball.oldY, ball.width, ball.height);
    ctx.fillRect(ball.oldX - 2, ball.oldY -2, ball.width +4, ball.height + 4); //Someone needs to take a look into this. Why doen't the ball get cleared when we only use oldX and oldY?

    //Now, draw a new ball :D
    canvasDrawer.fillStyle = this.color;
    canvasDrawer.fillRect(this.x, this.y, this.width, this.height);
};
Ball.prototype.calculatedXdY = function(){
    var v = this.velocity;
    var k = this.k;

    //Pythaghoras sats, emaila John för en förklaring :)
    var calcdX = this.right * Math.sqrt((v * v)/(1 + k * k));
    var calcdY = k * calcdX;

    this.dX = calcdX;
    this.dY = calcdY;
};
Ball.prototype.move = function(){
    if (!this.dX || !this.dY) this.calculatedXdY();

    this.oldX = this.x;
    this.oldY = this.y;

    if(/*this.x >= this.boundX || this.x <= 0 || */this.y >= this.boundY || this.y <= 0){
        //We hit left or right wall!! D:
        if (this.x >= this.boundX || this.x <= 0) this.right = this.right * -1; //Change direction
        this.k = this.k * -1;
        this.calculatedXdY();
    }

    this.x = this.x + this.dX;
    this.y = this.y + this.dY;

    this.centerX = this.x + this.width/2;

};
var start = null;
var ball = new Ball(10, 10, width/2 - 5, height/2-5, canvas.width, canvas.height);

var running = true;
var step = function(timestamp){
    ball.draw(ctx);
    ball.move();

    if(running) window.requestAnimationFrame(step);
    if(ball.x <= 0){
        alert("Lefty vann!");
        running = false;
    }
    if(ball.x >= ball.boundX){
        alert("alliansen vann!")
        running = false;
    }
};
window.requestAnimationFrame(step);<commit_msg>ball.setVelocity, correct redraw of ball and remove uneccesary calculation<commit_after>
//Settings:
var backgroundColor = "#000000";
var elementColor = "#FFFFFF";
var initialBallSpeed = 20; //How many px should we move per frame?
var initialBallK = 3;

var canvas = document.getElementById("arena");
var height = window.innerHeight;
var width = window.innerWidth;

//canvas.style.backgroundColor = "#000000";
document.getElementsByName("body").height = height;
canvas.height = height;
canvas.width = width;

var ctx = canvas.getContext("2d");

//Draw backgroucanvasDrawerctx.fillStyle = backgroundColor;
ctx.fillRect(0,0,canvas.width, canvas.height);

var Ball = function(height, width, startX, startY, boundX, boundY){
    this.color = elementColor;
    this.height = parseInt(height);
    this.width = parseInt(width);

    //Where is the ball?
    this.x = startX;
    this.y = startY;

    //where is the center of the ball?
    this.centerX = this.x + width/2;
    this.centerY = this.y + height/2;

    //How much should we move each frame?
    this.velocity = initialBallSpeed;
    this.k = initialBallK;
    this.right = 1; //Should the ball go left or right? Right = 1, left = -1
    this.dX = null;
    this.dY = null;
    this.angle = Math.atan(this.k); //angle from horizontal plane
    if (this.right == -1) this.angle = this.angle + Math.PI;

    this.oldX = null;
    this.oldY = null;

    this.boundX = boundX;
    this.boundY = boundY;
};

Ball.prototype.draw = function(canvasDrawer){
    //first clear the ball
    canvasDrawer.fillStyle = backgroundColor;
    //canvasDrawer.clearRect(ball.oldX, ball.oldY, ball.width, ball.height);
    canvasDrawer.fillRect(parseInt(ball.oldX), parseInt(ball.oldY), ball.width, ball.height);

    //Now, draw a new ball :D
    canvasDrawer.fillStyle = this.color;
    canvasDrawer.fillRect(parseInt(this.x), parseInt(this.y), this.width, this.height);
};
Ball.prototype.calculatedXdY = function(){
    var v = this.velocity;
    var k = this.k;

    //Pythaghoras sats, emaila John för en förklaring :)
    var calcdX = this.right * Math.sqrt((v * v)/(1 + k * k));
    var calcdY = k * calcdX;

    this.dX = calcdX;
    this.dY = calcdY;
};
Ball.prototype.setXfromCenter = function(center){
    this.x = center - this.width/2;
    return this.x;
}
Ball.prototype.setYfromCenter = function(center){
    this.y = center - this.height/2;
    return this.y;
}
Ball.prototype.move = function(){

    var checkHits = function(ball){

        var setRight = function(inVal, bound){

            var outside = inVal - bound;
            var result = bound - outside;
            return result;
        }

        //Vertical walls
        if(ball.centerX >= ball.boundX || ball.centerX < 0){

            //set position right

            if(ball.centerX > ball.boundX) {
                 ball.setXfromCenter(setRight(ball.centerX, ball.boundX));
            }
            if(ball.centerX < 0) {
                ball.setXfromCenter(-ball.centerX);
            }

            //Bounce, go other direction
            ball.right = ball.right * -1;
            ball.dX = ball.dX * ball.right;
        };

        //Horizontal walls
        if(ball.centerY >= ball.boundY || ball.centerY <= 0){

            //set position right
            if(ball.centerY > ball.boundY){
                ball.setYfromCenter(setRight(ball.centerY, ball.boundY));
            }
            if(ball.centerY < 0){
                ball.setYfromCenter(-ball.centerY);
            }

            //Flip k, (but that is the same as a flip of dY
            ball.dY = -ball.dY;
        };

        //TODO: Check for a hit with platform
    }
    if (!this.dX || !this.dY) this.calculatedXdY();

    this.oldX = this.x;
    this.oldY = this.y;

    //Check for wall hits

    checkHits(this);

    this.x = this.x + this.dX;
    this.y = this.y + this.dY;

    this.centerX = this.x + this.width/2;
    this.centerY = this.y + this.height/2;

};
Ball.prototype.setVelocity = function(vel){
    //Recalculate dX and dY. They are proportional to velocity
    var change = vel/this.velocity;
    this.dX = this.dX * change;
    this.dY = this.dY * change;
    this.velocity = vel;
};
Ball.prototype.setK = function(inK){
    this.k = inK;
    this.calculatedXdY();
};
var start = null;
var ball = new Ball(10, 10, width/2 - 5, height/2-5, canvas.width, canvas.height);

var running = true;
var step = function(timestamp){
    ball.draw(ctx);
    ball.move();

    if(running) window.requestAnimationFrame(step);

    //Very advanced system for detection of winner. Please be careful when you
    //uncomment this. It could lead to a broken toe, or worse, a
    //pinple on your elbow. Please uncomment with cuation.

    /*if(ball.centerX <= 0){
        alert("alliansen vann!")
        running = false;
    }
    if(ball.centerX >= ball.boundX){
        alert("Lefty vann!");
        running = false;
    }*/
};
window.requestAnimationFrame(step);<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(500, 200, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 50, 50, 50);

        if ( apple.alive() == true){
            console.log("Apple is alive");
        }
        else{
            console.log("Apple is not alive");
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Apple<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 50, 50, 50);

        if ( apple.alive == true){
            console.log("Apple is alive");
        }
        else{
            console.log("Apple is not alive");
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>


<commit_before>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevel = [
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]
]

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    var game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update});

    function preload() {

        game.load.image('logo', 'phaser.png');

        game.load.image('mosque', 'assets/mosque.png');

        game.load.image('synagogue', 'assets/synagogue.png');

        game.load.image('church', 'assets/church.png');

        game.load.image('block', 'assets/blue_tile.png');
    }

    function update() {

        updateBuldings();
        drawBoard(gameLevel);

    }

    function create() {

        createBuildings(); //temp function
        drawBoard(gameLevel);

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j* gameOptions.tileSize;
                var y = i* gameOptions.tileSize;
                var assetName = 'block';
                if(tileType == 1){
                    assetName = 'mosque';

                }
                var sprite = game.add.sprite(x, y, assetName);

            }

        }
    }

    function createBuildings() {
        this.mosques = [];
        this.churches = [];
        this.synagogues = [];
        this.mosques.push(new Mosque(game, 100, 100, "mosque"));
    }

    function updateBuldings() {
        var buildings = this.mosques.concat(this.churches).concat(synagogues);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

};
<commit_msg>locToTile<commit_after>/**
 * Created by shaibenvalid on 1/20/17.
 */

var gameOptions = {
    gameWidth: 960,    // game width, in pixels
    gameHeight: 600,   // game height, in pixels
    tileSize: 60,     // tile size, in pixels
    colors: [0xff0000, 0x00ff00, 0x0000ff, 0xffff00] // tile colors
}

var gameLevel = [
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0]
]

window.onload = function () {

    //  Note that this html file is set to pull down Phaser 2.5.0 from the JS Delivr CDN.
    //  Although it will work fine with this tutorial, it's almost certainly not the most current version.
    //  Be sure to replace it with an updated version before you start experimenting with adding your own code.

    var game = new Phaser.Game(960, 600, Phaser.AUTO, '', {preload: preload, create: create, update: update});

    function preload() {

        game.load.image('logo', 'phaser.png');

        game.load.image('mosque', 'assets/mosque.png');

        game.load.image('synagogue', 'assets/synagogue.png');

        game.load.image('church', 'assets/church.png');

        game.load.image('block', 'assets/blue_tile.png');
    }

    function update() {

        updateBuldings();
        drawBoard(gameLevel);

    }

    function create() {

        createBuildings(); //temp function
        drawBoard(gameLevel);

    }

    function drawBoard(board) {
        for (var i = 0; i < board.length; i++) {
            var row = board[i];
            for (var j = 0; j < row.length; j++) {
                var tileType = row[j];
                var x = j* gameOptions.tileSize;
                var y = i* gameOptions.tileSize;
                var assetName = 'block';
                if(tileType == 1){
                    assetName = 'mosque';

                }
                var sprite = game.add.sprite(x, y, assetName);

            }

        }
    }

    function locToTile() {
        return [j* gameOptions.tileSize, i* gameOptions.tileSize ]
    }

    function createBuildings() {
        this.mosques = [];
        this.churches = [];
        this.synagogues = [];
        this.mosques.push(new Mosque(game, 100, 100, "mosque"));
    }

    function updateBuldings() {
        var buildings = this.mosques.concat(this.churches).concat(synagogues);
        for (var i = 0; i < buildings.length; i++) {
            var building = buildings[i];
            building.doTick(new Date());
        }
    }

};
<|endoftext|>


<commit_before>$(function() {

window.onload = function() {

    var game = new Phaser.Game(1536, 864, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    var jumping = "0";

    var score = 0;
    var lives = 3;

    var lookdir;

    function preload() {

        game.load.image('bob', 'assets/images/bob.png');
        game.load.image('background', 'assets/images/background.png');
        game.load.image('ocean', 'assets/images/ocean.png');
        cursors = game.input.keyboard.createCursorKeys();
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

    }

    function create() {

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

        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');

        //score

        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        //hiding this for now its in the way
        //var fatty1 = game.add.sprite(0, 0, 'fatty1');

        //Uncaught TypeError: Cannot read property 'velocity' of null
        //fatty1.body.velocity.x=20;

        ocean = game.add.sprite(0, game.world.height - 635, 'ocean');

        //fatty1 = game.add.sprite(450, game.world.height - 300, 'fatty1');
        //fatty2 = game.add.sprite(450, game.world.height - 300, 'fatty2');
        //fatty3 = game.add.sprite(450, game.world.height - 300, 'fatty3');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        ocean.body.immovable = true;

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        //Player physics properties.
        //player.body.bounce.y = 0.3;
        //player.body.gravity.y = 800;
        player.body.collideWorldBounds = true;

        //start the player looking right
        //lookdir = "right";

    }

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
        }

        }

};
});<commit_msg>Trying frames<commit_after>$(function() {

window.onload = function() {

    var game = new Phaser.Game(1536, 864, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    var jumping = "0";

    var score = 0;
    var lives = 3;

    var lookdir;

    function preload() {

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        game.load.image('background', 'assets/images/background.png');
        game.load.image('ocean', 'assets/images/ocean.png');
        cursors = game.input.keyboard.createCursorKeys();
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

    }

    function create() {

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

        //Game Objects
        var player = game.add.sprite(775, game.world.height - 150, 'bob');

        //score

        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        //hiding this for now its in the way
        //var fatty1 = game.add.sprite(0, 0, 'fatty1');

        //Uncaught TypeError: Cannot read property 'velocity' of null
        //fatty1.body.velocity.x=20;

        ocean = game.add.sprite(0, game.world.height - 635, 'ocean');

        //fatty1 = game.add.sprite(450, game.world.height - 300, 'fatty1');
        //fatty2 = game.add.sprite(450, game.world.height - 300, 'fatty2');
        //fatty3 = game.add.sprite(450, game.world.height - 300, 'fatty3');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        ocean.body.immovable = true;

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        //Player physics properties.
        //player.body.bounce.y = 0.3;
        //player.body.gravity.y = 800;
        player.body.collideWorldBounds = true;

        //start the player looking right
        //lookdir = "right";

    }

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.frame("3");
            player.body.velocity.y = 180;
        }

        }

};
});<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if ( Phaser.Keyboard.SPACEBAR = true ){
            horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 100, 50, 50);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Space?<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        if ( Phaser.Keyboard.SPACEBAR == true ){
            horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 100, 50, 50);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>


<commit_before>/* @flow weak */

var renderer = null;
var frameWidth = 30;
var frameHeight = 20;

var currentFrameX = 0;
var currentFrameY = 0;

var alphaX = 0.04;
var alphaY = 0.01;

var robots = [];
var terrain = null;
var population = null;
var gui = null;

function startLinkages() {
  renderer = new p2.WebGLRenderer(function() {
    var world = new p2.World({
      gravity: [0, -10],
      broadphase: new p2.SAPBroadphase()
    });

    this.setWorld(world);

    world.defaultContactMaterial.friction = 1000;

    terrain = new Terrain(world, -10, 0);
    population = new Population(world, 8, 1, 5, 7);

    var guiParent = document.getElementById('gui-parent');
    gui = new GUI(guiParent, world, terrain, population);

    // baseWidth, baseHeight, baseAngle, driverLength, topSpindlyLength,
    // bottomSpindlyLength, middleSpindlyLength, legLength
    var klannGenome = new KlannGenome(2.5, 2, Math.PI / 6 + 0.3,
                                      1.8, 1.8 + 0.4, 0.9, 3.25, 5.5, 1 / 3);
    var baseRobotGenome = new RobotGenome(3, 2, 40, klannGenome, klannGenome);
    robots = population.synthesize(baseRobotGenome);

    terrain.update(50);

    updateFrame(this);
    addHackyResizer();

    this.frame(0, 0, frameWidth, frameHeight);
  }, {
    hideGUI: true
  });
  // renderer.paused = true;
  updateRendererDimensions();
}

function smooth(oldVal, newVal, alphaBase) {
  var alpha = alphaBase * Math.max(Math.abs((oldVal - newVal) / 4), 1);
  return oldVal * (1 - alpha) + newVal * alpha;
}

function updateFrame(renderer) {
  var maxX = 0;
  var maxY = 0;

  var anyAlive = false;
  for (var i = 0; i < robots.length; i++) {
    robots[i].update();

    if (!robots[i].alive) {
      continue;
    }

    var robotX = robots[i].maxX;
    var robotY = robots[i].y;
    if (robotX > maxX) {
      maxX = robotX;
      maxY = robotY;
    }

    anyAlive = true;
  }

  currentFrameX = smooth(currentFrameX, maxX, alphaX);
  currentFrameY = smooth(currentFrameY, maxY, alphaY);

  terrain.update(maxX);

  renderer.frame(currentFrameX + frameWidth / 8, currentFrameY,
                 frameWidth, frameHeight);

  if (!anyAlive) {
    gui.addGenerationResults(robots);

    robots = population.spawn(robots);
  }
  window.requestAnimationFrame(function() {
    updateFrame(renderer, robots);
  });
}

function updateRendererDimensions() {
  if (!renderer) {
    return;
  }
  var width = window.innerWidth;
  var height = window.innerHeight * 3 / 5;
  var dpr = window.devicePixelRatio || 1;

  renderer.resize(width * dpr, height * dpr);
}

function addHackyResizer() {
  window.addEventListener('resize', updateRendererDimensions);
}

startLinkages();
<commit_msg>Fix sudden NaN<commit_after>/* @flow weak */

var renderer = null;
var frameWidth = 30;
var frameHeight = 20;

var currentFrameX = 0;
var currentFrameY = 0;

var alphaX = 0.04;
var alphaY = 0.01;

var robots = [];
var terrain = null;
var population = null;
var gui = null;

function startLinkages() {
  renderer = new p2.WebGLRenderer(function() {
    var world = new p2.World({
      gravity: [0, -10],
      broadphase: new p2.SAPBroadphase()
    });

    this.setWorld(world);

    world.defaultContactMaterial.friction = 1000;

    terrain = new Terrain(world, -10, 0);
    population = new Population(world, 8, 1, 5, 7);

    var guiParent = document.getElementById('gui-parent');
    gui = new GUI(guiParent, world, terrain, population);

    // baseWidth, baseHeight, baseAngle, driverLength, topSpindlyLength,
    // bottomSpindlyLength, middleSpindlyLength, legLength
    var klannGenome = new KlannGenome(2.5, 2, Math.PI / 6 + 0.3,
                                      1.8, 1.8 + 0.4, 0.9, 3.25, 5.5, 1 / 3);
    var baseRobotGenome = new RobotGenome(3, 2, 40, klannGenome, klannGenome);
    robots = population.synthesize(baseRobotGenome);

    terrain.update(50);

    updateFrame(this);
    addHackyResizer();

    this.frame(0, 0, frameWidth, frameHeight);
  }, {
    hideGUI: true
  });
  // renderer.paused = true;
  updateRendererDimensions();
}

function smooth(oldVal, newVal, alphaBase) {
  if (isNaN(oldVal)) {
    return newVal;
  }
  var alpha = alphaBase * Math.max(Math.abs((oldVal - newVal) / 4), 1);
  return oldVal * (1 - alpha) + newVal * alpha;
}

function updateFrame(renderer) {
  var maxX = 0;
  var maxY = 0;

  var anyAlive = false;
  for (var i = 0; i < robots.length; i++) {
    robots[i].update();

    if (!robots[i].alive) {
      continue;
    }

    var robotX = robots[i].maxX;
    var robotY = robots[i].y;
    if (robotX > maxX) {
      maxX = robotX;
      maxY = robotY;
    }

    anyAlive = true;
  }

  currentFrameX = smooth(currentFrameX, maxX, alphaX);
  currentFrameY = smooth(currentFrameY, maxY, alphaY);

  terrain.update(maxX);

  renderer.frame(currentFrameX + frameWidth / 8, currentFrameY,
                 frameWidth, frameHeight);

  if (!anyAlive) {
    gui.addGenerationResults(robots);

    robots = population.spawn(robots);
  }
  window.requestAnimationFrame(function() {
    updateFrame(renderer, robots);
  });
}

function updateRendererDimensions() {
  if (!renderer) {
    return;
  }
  var width = window.innerWidth;
  var height = window.innerHeight * 3 / 5;
  var dpr = window.devicePixelRatio || 1;

  renderer.resize(width * dpr, height * dpr);
}

function addHackyResizer() {
  window.addEventListener('resize', updateRendererDimensions);
}

startLinkages();
<|endoftext|>


<commit_before>// http-server ./

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render });

function preload() {
    game.load.image('bg', 'assets/bg.jpg');
    game.load.image('ground', 'assets/platform.png');
    game.load.spritesheet('spider', 'assets/spider_trimmed.png');
    game.load.spritesheet('projectile', 'assets/projectile.png');
    game.load.image('arrow', 'assets/arrow.png');
}

var spaceKey;
var platforms;
var player;
var arrow;
var web;
var webLine;
var line;
var gfx;

function create() {

    // register keys
    spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    // stop the following keys from propagating up to the browser
    game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);

    // enable the Arcade Physics system
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // background
    game.add.sprite(0, -300, 'bg');

    // the platforms group contains the ground and the ledges we can jump on
    platforms = game.add.group();
    platforms.enableBody = true; // enable physics for any object that is created in this group
    var ground = platforms.create(0, game.world.height - 64, 'ground');
    ground.scale.setTo(2, 2);
    ground.body.immovable = true; // stop it from falling away when you jump on it
    // create two ledges
    var ledge = platforms.create(400, 400, 'ground');
    ledge.body.immovable = true;
    ledge = platforms.create(-150, 250, 'ground');
    ledge.body.immovable = true;

    // player
    player = game.add.sprite(300, game.world.height - 64 - 12, 'spider');
    //  enable physics on the player
    game.physics.arcade.enable(player);
    // The bounce gives a nice effect but currently messes with the web climbing...
    //player.body.bounce.y = 0.2;
    player.body.gravity.y = 300;
    player.body.collideWorldBounds = true;
    player.anchor.set(0.5, 0.5);

    // arrow
    arrow = game.add.sprite(player.x, player.y, 'arrow');
    arrow.anchor.setTo(0.5, 1.2);

    // controls
    cursors = game.input.keyboard.createCursorKeys();

    // graphics used to render line between player and anchor
    gfx = game.add.graphics(0, 0);
    gfx.lineStyle(1, '#000', 1);
}

function update() {

    // collide the player and the platforms
    var playerHitPlatform = game.physics.arcade.collide(player, platforms);
    // collide the web projectile and the platforms
    var webHitPlatform = game.physics.arcade.collide(web, platforms);

    // instantiate 'chain' on appropriate collision
    if (webHitPlatform) {
        console.log(web.x, web.y);
        webLine = {
            anchor: {
                x: web.x,
                y: web.y
            },
            radius: Phaser.Point.distance(player, web, false)
        };
        // remove the projectile - the 'chain' remains
        web.kill();
    }

    // handle layer/anchor interaction as long as the webline is present
    if (webLine) {
        var dist = Phaser.Point.distance(player, webLine.anchor, false);
        var delta = dist - webLine.radius;
        var k = 10;
        var acc = Phaser.Point.normalize(Phaser.Point.subtract(webLine.anchor, player)).setMagnitude(delta * k);
        player.body.acceleration = acc;
    }

    // let arrow follow player
    arrow.x = player.x;
    arrow.y = player.y;

    // fire mechanism
    if (spaceKey.justReleased(50)) {
        if (webLine)
        {
            // Cut
            webLine = null;
        } else {
            fire();
        }
    }

    // reset the players velocity (movement)
    player.body.velocity.x = 0;

    // keyboard movement
    if (cursors.left.isDown) {
        if (cursors.left.shiftKey===true)
        {
            // aim
            arrow.rotation -= 0.05;
        } else {
            // move
            player.body.velocity.x = -50;
        }
    }
    if (cursors.right.isDown) {
        if (cursors.right.shiftKey===true)
        {
            // aim
            arrow.rotation += 0.05;
        } else {
            // move
            player.body.velocity.x = 50;
        }
    }
    if (cursors.up.isDown) {
        if (cursors.right.shiftKey===true && webLine)
        {
            // climb
            webLine.radius -= 10;
        } else if (player.body.touching.down && playerHitPlatform) {
            // jump if touching the ground
            player.body.velocity.y = -150;
        }
    }

    // draw line between player and anchor
    if (webLine) {

        // find a way to redraw the line at the correct location - destroy() below doesn't work
        // if (line) {
        //     line.destroy();
        // }

        // draw the line!
        gfx.moveTo(webLine.anchor.x, webLine.anchor.y);
        line = gfx.lineTo(player.x, player.y);
    } else if (line) {
        // remove the line if no webline - destroy() seems not to be the best way as it prevents rendering of subsequent lines...
        line.destroy();
    }
}

function render() {
    // debug info
    //game.debug.spriteInfo(arrow, 32, 32);
}

function fire() {
    if (web) web.kill();
    // instantiate web
    web = game.add.sprite(player.x, player.y, 'projectile');
    web.anchor.set(0.5, 0.5);
    game.physics.arcade.enable(web);
    web.body.gravity.y = 300;
    web.body.collideWorldBounds = true;

    var magnitude = 500;
    var firingAngle = (arrow.angle - 90) * Math.PI / 180;
    web.body.velocity.x = magnitude * Math.cos(firingAngle);
    web.body.velocity.y = magnitude * Math.sin(firingAngle);
}
<commit_msg>Mere sving<commit_after>// http-server ./

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render });

function preload() {
    game.load.image('bg', 'assets/bg.jpg');
    game.load.image('ground', 'assets/platform.png');
    game.load.spritesheet('spider', 'assets/spider_trimmed.png');
    game.load.spritesheet('projectile', 'assets/projectile.png');
    game.load.image('arrow', 'assets/arrow.png');
}

var spaceKey;
var platforms;
var player;
var arrow;
var web;
var webLine;
var line;
var gfx;

function create() {

    // register keys
    spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    // stop the following keys from propagating up to the browser
    game.input.keyboard.addKeyCapture([Phaser.Keyboard.SPACEBAR]);

    // enable the Arcade Physics system
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // background
    game.add.sprite(0, -300, 'bg');

    // the platforms group contains the ground and the ledges we can jump on
    platforms = game.add.group();
    platforms.enableBody = true; // enable physics for any object that is created in this group
    var ground = platforms.create(0, game.world.height - 64, 'ground');
    ground.scale.setTo(2, 2);
    ground.body.immovable = true; // stop it from falling away when you jump on it
    // create two ledges
    var ledge = platforms.create(400, 400, 'ground');
    ledge.body.immovable = true;
    ledge = platforms.create(-150, 250, 'ground');
    ledge.body.immovable = true;

    // player
    player = game.add.sprite(300, game.world.height - 64 - 12, 'spider');
    //  enable physics on the player
    game.physics.arcade.enable(player);
    // The bounce gives a nice effect but currently messes with the web climbing...
    //player.body.bounce.y = 0.2;
    player.body.gravity.y = 300;
    player.body.collideWorldBounds = true;
    player.anchor.set(0.5, 0.5);

    // arrow
    arrow = game.add.sprite(player.x, player.y, 'arrow');
    arrow.anchor.setTo(0.5, 1.2);

    // controls
    cursors = game.input.keyboard.createCursorKeys();

    // graphics used to render line between player and anchor
    gfx = game.add.graphics(0, 0);
    gfx.lineStyle(1, '#000', 1);
}

function update() {

    // collide the player and the platforms
    var playerHitPlatform = game.physics.arcade.collide(player, platforms);
    // collide the web projectile and the platforms
    var webHitPlatform = game.physics.arcade.collide(web, platforms);

    // instantiate 'chain' on appropriate collision
    if (webHitPlatform) {
        console.log(web.x, web.y);
        webLine = {
            anchor: {
                x: web.x,
                y: web.y
            },
            radius: Phaser.Point.distance(player, web, false)
        };
        // remove the projectile - the 'chain' remains
        web.kill();
    }

    // handle layer/anchor interaction as long as the webline is present
    if (webLine) {
        var dist = Phaser.Point.distance(player, webLine.anchor, false);
        var playerRadius = 30;
        var delta = dist - (webLine.radius - playerRadius);
        // console.log("delta: ", delta);
        // only pull not push
        if (delta > 0) {
            var dir = Phaser.Point.subtract(webLine.anchor, player);
            // console.log("dir: ", dir);
            // mass * spring constant
            var k = 1;
            var acc = Phaser.Point.normalize(dir).setMagnitude(delta * k);
            // console.log("acc: ", acc);
            player.body.velocity = Phaser.Point.add(player.body.velocity, acc);
        }
    }

    // let arrow follow player
    arrow.x = player.x;
    arrow.y = player.y;

    // fire mechanism
    if (spaceKey.justReleased(50)) {
        if (webLine)
        {
            // Cut
            webLine = null;
        } else {
            fire();
        }
    }

    // reset the players velocity (movement)
    if (player.body.touching.down && playerHitPlatform) {
        player.body.velocity.x = 0;
    }

    // keyboard movement
    if (cursors.left.isDown) {
        if (cursors.left.shiftKey===true)
        {
            // aim
            arrow.rotation -= 0.05;
        } else {
            // move
            player.body.velocity.x = -50;
        }
    }
    if (cursors.right.isDown) {
        if (cursors.right.shiftKey===true)
        {
            // aim
            arrow.rotation += 0.05;
        } else {
            // move
            player.body.velocity.x = 50;
        }
    }
    if (cursors.up.isDown) {
        if (cursors.right.shiftKey===true && webLine)
        {
            // climb
            webLine.radius -= 10;
        } else if (player.body.touching.down && playerHitPlatform) {
            // jump if touching the ground
            player.body.velocity.y += -150;
        }
    }

    // draw line between player and anchor
    if (webLine) {

        // find a way to redraw the line at the correct location - destroy() below doesn't work
        // if (line) {
        //     line.destroy();
        // }

        // draw the line!
        gfx.moveTo(webLine.anchor.x, webLine.anchor.y);
        line = gfx.lineTo(player.x, player.y);
    } else if (line) {
        // remove the line if no webline - destroy() seems not to be the best way as it prevents rendering of subsequent lines...
        line.destroy();
    }
}

function render() {
    // debug info
    //game.debug.spriteInfo(arrow, 32, 32);
}

function fire() {
    if (web) web.kill();
    // instantiate web
    web = game.add.sprite(player.x, player.y, 'projectile');
    web.anchor.set(0.5, 0.5);
    game.physics.arcade.enable(web);
    web.body.gravity.y = 300;
    web.body.collideWorldBounds = true;

    var magnitude = 500;
    var firingAngle = (arrow.angle - 90) * Math.PI / 180;
    web.body.velocity.x = magnitude * Math.cos(firingAngle);
    web.body.velocity.y = magnitude * Math.sin(firingAngle);
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2017 Marc Khouzam.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>Don't open the developer tools automatically<commit_after>/*******************************************************************************
 * Copyright (c) 2017 Marc Khouzam.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow

const path = require('path')
const url = require('url')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600})

  // and load the index.html of the app.
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
//  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>