<commit_before>const Ball = require('./ball');
const Block = require('./block');
const Paddle = require('./paddle');
const Player = require('./player');

let game = class Game {
  constructor(ctx, canvas) {
    this.ctx = ctx;
    this.canvas = canvas;
    this.balls = [];
    this.paddles = [];
    this.players = [];
    this.cornerSize = 5;
    this.playerSize = 2;
    this.blockSize = 42;
  }

  beginRound(){
    let game = this;
    game.ctx.shadowColor = 'white';
    game.ctx.shadowBlur = 15;
    game.createGrid();
    game.balls.push(new Ball(275, 390, 10, 6, -3));
    setInterval(function() {
      game.balls.push(new Ball(375, 530, 10, -3, -4));
    }, 2000)

    requestAnimationFrame(function gameTime(){
      game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
      game.players.forEach(function(player){player.draw(game.ctx);});
      game.balls.forEach(function(ball){ ball.draw(game.ctx).move(game.paddles, game.players, game.canvas); });

      if (game.players.filter(function(player){return player.status == 1}).length == 1) {
        game.players.forEach(function(player){player.draw(game.ctx);});
        cancelAnimationFrame();
      } else {requestAnimationFrame(gameTime)}
    })
  }

  createGrid(){
    let canvasSize = this.canvas.width;
    let blockSize = this.blockSize;
    let playerSpace = blockSize * this.playerSize;
    let numBlocks = this.cornerSize;
    let deadSpace = canvasSize - (blockSize*numBlocks);

    this.players.push(new Player(1, 0, 0, playerSpace, canvasSize, '#00DD6B'));
    this.players.push(new Player(2, canvasSize - playerSpace, 0, playerSpace, canvasSize, '#DCED31'));
    this.players.push(new Player(3, 0, canvasSize - playerSpace, playerSpace, canvasSize, '#FF3864'));
    this.players.push(new Player(4, canvasSize - playerSpace, canvasSize - playerSpace, playerSpace, canvasSize, '#00A5FF'));

    this.players.forEach(function (player) {player.paddleListeners()})

    for (let y = 0; y < numBlocks; y++) {
      for (let x = 0; x < numBlocks; x++) {
        // Top Left
        if (x*blockSize >= playerSpace || y*blockSize >= playerSpace){
          this.players[0].blocks.push(new Block(x*blockSize, y*blockSize, blockSize, this.players[0].color))
        }
        // Top Right
        if (((x+1)*blockSize + deadSpace) <= canvasSize - playerSpace || y*blockSize >= playerSpace){
          this.players[1].blocks.push(new Block(deadSpace+(x*blockSize), y*blockSize, blockSize, this.players[1].color))
        }
        // Bottom Left
        if (x*blockSize >= playerSpace || ((y+1)*blockSize + deadSpace) <= canvasSize - playerSpace){
          this.players[2].blocks.push(new Block(x*blockSize, deadSpace+(y*blockSize), blockSize, this.players[2].color))
        }
        // Bottom Right
        if (((x+1)*blockSize + deadSpace) <= canvasSize - playerSpace || ((y+1)*blockSize + deadSpace) <= canvasSize - playerSpace){
          this.players[3].blocks.push(new Block(deadSpace+(x*blockSize), deadSpace+(y*blockSize), blockSize, this.players[3].color))
        }
      }
    }
  }
}

function random() {
  return Math.random() < 0.5 ? -1 : 1;
  return Math.random() * (6 - min) + min;
}

module.exports = game;
<commit_msg>Revert ball spawn speed from test value<commit_after>const Ball = require('./ball');
const Block = require('./block');
const Paddle = require('./paddle');
const Player = require('./player');

let game = class Game {
  constructor(ctx, canvas) {
    this.ctx = ctx;
    this.canvas = canvas;
    this.balls = [];
    this.paddles = [];
    this.players = [];
    this.cornerSize = 5;
    this.playerSize = 2;
    this.blockSize = 42;
  }

  beginRound(){
    let game = this;
    game.ctx.shadowColor = 'white';
    game.ctx.shadowBlur = 15;
    game.createGrid();
    game.balls.push(new Ball(275, 390, 10, 6, -3));
    setInterval(function() {
      game.balls.push(new Ball(375, 530, 10, -3, -4));
    }, 20000)

    requestAnimationFrame(function gameTime(){
      game.ctx.clearRect(0, 0, game.canvas.width, game.canvas.height);
      game.players.forEach(function(player){player.draw(game.ctx);});
      game.balls.forEach(function(ball){ ball.draw(game.ctx).move(game.paddles, game.players, game.canvas); });

      if (game.players.filter(function(player){return player.status == 1}).length == 1) {
        game.players.forEach(function(player){player.draw(game.ctx);});
        cancelAnimationFrame();
      } else {requestAnimationFrame(gameTime)}
    })
  }

  createGrid(){
    let canvasSize = this.canvas.width;
    let blockSize = this.blockSize;
    let playerSpace = blockSize * this.playerSize;
    let numBlocks = this.cornerSize;
    let deadSpace = canvasSize - (blockSize*numBlocks);

    this.players.push(new Player(1, 0, 0, playerSpace, canvasSize, '#00DD6B'));
    this.players.push(new Player(2, canvasSize - playerSpace, 0, playerSpace, canvasSize, '#DCED31'));
    this.players.push(new Player(3, 0, canvasSize - playerSpace, playerSpace, canvasSize, '#FF3864'));
    this.players.push(new Player(4, canvasSize - playerSpace, canvasSize - playerSpace, playerSpace, canvasSize, '#00A5FF'));

    this.players.forEach(function (player) {player.paddleListeners()})

    for (let y = 0; y < numBlocks; y++) {
      for (let x = 0; x < numBlocks; x++) {
        // Top Left
        if (x*blockSize >= playerSpace || y*blockSize >= playerSpace){
          this.players[0].blocks.push(new Block(x*blockSize, y*blockSize, blockSize, this.players[0].color))
        }
        // Top Right
        if (((x+1)*blockSize + deadSpace) <= canvasSize - playerSpace || y*blockSize >= playerSpace){
          this.players[1].blocks.push(new Block(deadSpace+(x*blockSize), y*blockSize, blockSize, this.players[1].color))
        }
        // Bottom Left
        if (x*blockSize >= playerSpace || ((y+1)*blockSize + deadSpace) <= canvasSize - playerSpace){
          this.players[2].blocks.push(new Block(x*blockSize, deadSpace+(y*blockSize), blockSize, this.players[2].color))
        }
        // Bottom Right
        if (((x+1)*blockSize + deadSpace) <= canvasSize - playerSpace || ((y+1)*blockSize + deadSpace) <= canvasSize - playerSpace){
          this.players[3].blocks.push(new Block(deadSpace+(x*blockSize), deadSpace+(y*blockSize), blockSize, this.players[3].color))
        }
      }
    }
  }
}

function random() {
  return Math.random() < 0.5 ? -1 : 1;
  return Math.random() * (6 - min) + min;
}

module.exports = game;
<|endoftext|>


<commit_before>if (typeof define !== 'function') {
    //noinspection JSUnresolvedVariable
    var define = require('amdefine')(module);
}

define(function (require) {
    var transport = require('./transport'),
        auth = require('./auth'),
        urlencode = require('./urlencode'),
        Exception = require('./exception');

    var placeholder = /^{(.+)}$/,
        safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true },
        synonyms;

    synonyms = {
        'PUT': ['save', 'replace'],
        'POST': ['add'],
        'DELETE': ['remove']
    };

    function result(value) {

        if (value.indexOf('=') === -1) {
            return value;
        }

        var parts = value.split('=');

        // TODO: remove primitive type object wrapper
        value = new String(parts[0]);
        value.variable = parts[1];

        return value;
    }

    function last(arr, except) {
        except || (except = 0);
        return typeof arr[arr.length - except - 1];
    }

    return function apic(desc, options) {
        options = options || {};

        var root = {},
            base = desc.base,
            variables = {},
            augments = {},
            language,
            lastDate;

        var scheme = 'http:';

        options.synonyms = options.synonyms || synonyms;
        options.tokenHeader = options.tokenHeader || 'X-Security-Token';
        options.authorizationHeader = options.authorizationHeader || 'Authorization';

        if (typeof window !== 'undefined') {
            scheme = location.protocol; // current URI scheme
        }

        auth.apply(root);

        root.augment = function (name, value) {

            if (value === undefined) {
                return augments[name];
            }

            augments[name] = value;
        };

        root.localize = function (value) {

            if (value !== undefined) {
                language = value;
            }

            return language;
        };

        root.variable = function (name, value) {

            if (value !== undefined) {
            	variables[name] = value;
            }

            return variables[name];
        };

        root.getLastDate = function () {
            return lastDate;
        };

        function method(verb, uri, res, params, secure) {
            var safe = safeMethods[verb] || false,
                protocol = (secure = secure || !safe) ? 'https:' : scheme;

            // do not ever use this
            if (options.__forceProtocol) {
                protocol = options.__forceProtocol;
            }

            return function () {
                var args = Array.prototype.slice.call(arguments),
                    headers = last(args) === 'object' && last(args, 1) === 'function' ? args.pop() : {},
                    callback = (last(args) === 'function' || last(args) === 'undefined') ? args.pop() : undefined,
                    representation = last(args) === 'object' ? args.pop() : undefined,
                    query = last(args) === 'object' ? args.pop() : {},
                    path = uri,
                    _;

                if (safeMethods[verb]) {
                    query = representation || {};
                    representation = undefined;
                }

                /*
                 Check if all necessary arguments passed in arguments or have default variable value
                 */
                if (params.reduce(function (a, b) {
                    return a - +(query[b] !== undefined || variables[b.variable] !== undefined);
                }, params.length) > args.length) {

                    throw new Error([
                        params.length, ' argument', (params.length === 1 ? '' : 's'),
                        params.length ? ' (' + params.join(', ') + ')' : '',
                        ' expected ', args.length, ' given',
                        args.length ? ' (' + args.join(', ') + ')' : ''
                    ].join(''));

                }

                params.forEach(function (name, i) {

                    if (!query[name]) {
                        query[name] = args[i] === undefined
                            ? (name.variable && variables[name.variable])
                            : args[i];
                    }

                    if (name.template) {
                        var _ = '{' + name + '}',
                            value = args[i] || query[name];

                        path.indexOf(_) === -1
                            ? (path += '/' + value)
                            : (path = path.replace(_, value));

                        delete query[name];
                    }

                });

                // cleanup
                for (_ in query) {

                    if (query[_] === undefined) {
                        delete query[_];
                    }

                }

                if (secure && root.authorize()) {
                    headers[options.authorizationHeader] = root.authorize();
                }

                if (language) {

                    if (safe) {
                        headers['Accept-Language'] = language;
                    } else if (representation) {
                        headers['Content-Language'] = language;
                    }

                }

                for (_ in augments) {

                    if (augments[_] !== null) {
                        headers[_] = augments[_];
                    }

                }

                transport.request({
                    uri: protocol + base + path + urlencode.encode(query),
                    method: verb,
                    headers: headers,
                    body: representation,
                    cookie: options.cookie
                }, function (err, body, xhr) {
                    var token;

                    lastDate = Date.parse(xhr.getResponseHeader('Date'));

                    function cb(err) {

                        if (!callback) {
                            return;
                        }

                        var args = [err, body];

                        /**
                         * Pass xhr object only if explicitly expected
                         * otherwise some libraries using 'arguments' object
                         * can work incorrectly
                         */
                        callback.length === 3 && args.push(xhr);
                        callback.apply(this, args);
                    }

                    if (err) {

                        if (err.status === 401) {
                            root.unauthorize();
                        }

                        cb(new Exception(err, body));

                        return;
                    }

                    res.variable && (variables[res.variable] = body && body[res]);

                    if (secure) {
                        token = xhr.getResponseHeader(options.tokenHeader);
                        token && root.authorize.token(token, root.authorize.realm());
                    }

                    cb(null);
                });
            };
        }

        return function generate(map, uri, res) {
            var key,
                value,
                parts,
                secure,
                transparent,
                tree,
                _;

            res = res || {};

            for (key in map) {
                if (map.hasOwnProperty(key) && key !== '@') {
                    value = map[key];

                    transparent = key.match(placeholder);

                    key = (parts = key.split('#')).shift();

                    parts = parts.map(function (name) {
                        var template, variable, match;

                        if (name.charAt(0) === '/') {
                            template = true;
                            name = name.substr(1);
                        }

                        if (match = name.match(placeholder)) {
                            _ = match[1].split('=');

                            name = _[0];
                            variable = _[1];
                        }

                        // monkey code
                        // TODO: remove primitive type object wrapper
                        name = new String(name);
                        name.template = template;
                        name.variable = variable;

                        return name;
                    });

                    if (key.charAt(key.length - 1) === '*')
                        secure = !!(key = key.substring(0, key.length - 1));

                    if (key.charAt(0) !== ':') {
                        _ = key.toLowerCase();

                        tree = typeof value === 'string'
                            ? method(key, uri || '/', result(value), parts, secure)
                            : generate(value, (uri || '') + '/' + (value['@'] || key), transparent && res);

                        transparent || (res[_] = tree);

                        options.synonyms[key] && options.synonyms[key].forEach(function (alias) {
                            res[alias] || (res[alias] = res[_]);
                        });
                    } else
                        res[key.substr(1)] = res[value.toLowerCase()];
                }
            }

            return res;
        }(desc.resources, undefined, root);
    };

});
<commit_msg>Added check for existence of the Date header in the Access-Control-Expose-Headers<commit_after>if (typeof define !== 'function') {
    //noinspection JSUnresolvedVariable
    var define = require('amdefine')(module);
}

define(function (require) {
    var transport = require('./transport'),
        auth = require('./auth'),
        urlencode = require('./urlencode'),
        Exception = require('./exception');

    var placeholder = /^{(.+)}$/,
        safeMethods = { 'GET': true, 'HEAD': true, 'OPTIONS': true },
        synonyms;

    synonyms = {
        'PUT': ['save', 'replace'],
        'POST': ['add'],
        'DELETE': ['remove']
    };

    function result(value) {

        if (value.indexOf('=') === -1) {
            return value;
        }

        var parts = value.split('=');

        // TODO: remove primitive type object wrapper
        value = new String(parts[0]);
        value.variable = parts[1];

        return value;
    }

    function last(arr, except) {
        except || (except = 0);
        return typeof arr[arr.length - except - 1];
    }

    return function apic(desc, options) {
        options = options || {};

        var root = {},
            base = desc.base,
            variables = {},
            augments = {},
            language,
            lastDate;

        var scheme = 'http:';

        options.synonyms = options.synonyms || synonyms;
        options.tokenHeader = options.tokenHeader || 'X-Security-Token';
        options.authorizationHeader = options.authorizationHeader || 'Authorization';

        if (typeof window !== 'undefined') {
            scheme = location.protocol; // current URI scheme
        }

        auth.apply(root);

        root.augment = function (name, value) {

            if (value === undefined) {
                return augments[name];
            }

            augments[name] = value;
        };

        root.localize = function (value) {

            if (value !== undefined) {
                language = value;
            }

            return language;
        };

        root.variable = function (name, value) {

            if (value !== undefined) {
                variables[name] = value;
            }

            return variables[name];
        };

        root.getLastDate = function () {
            return lastDate;
        };

        function method(verb, uri, res, params, secure) {
            var safe = safeMethods[verb] || false,
                protocol = (secure = secure || !safe) ? 'https:' : scheme;

            // do not ever use this
            if (options.__forceProtocol) {
                protocol = options.__forceProtocol;
            }

            return function () {
                var args = Array.prototype.slice.call(arguments),
                    headers = last(args) === 'object' && last(args, 1) === 'function' ? args.pop() : {},
                    callback = (last(args) === 'function' || last(args) === 'undefined') ? args.pop() : undefined,
                    representation = last(args) === 'object' ? args.pop() : undefined,
                    query = last(args) === 'object' ? args.pop() : {},
                    path = uri,
                    _;

                if (safeMethods[verb]) {
                    query = representation || {};
                    representation = undefined;
                }

                /*
                 Check if all necessary arguments passed in arguments or have default variable value
                 */
                if (params.reduce(function (a, b) {
                    return a - +(query[b] !== undefined || variables[b.variable] !== undefined);
                }, params.length) > args.length) {

                    throw new Error([
                        params.length, ' argument', (params.length === 1 ? '' : 's'),
                        params.length ? ' (' + params.join(', ') + ')' : '',
                        ' expected ', args.length, ' given',
                        args.length ? ' (' + args.join(', ') + ')' : ''
                    ].join(''));

                }

                params.forEach(function (name, i) {

                    if (!query[name]) {
                        query[name] = args[i] === undefined
                            ? (name.variable && variables[name.variable])
                            : args[i];
                    }

                    if (name.template) {
                        var _ = '{' + name + '}',
                            value = args[i] || query[name];

                        path.indexOf(_) === -1
                            ? (path += '/' + value)
                            : (path = path.replace(_, value));

                        delete query[name];
                    }

                });

                // cleanup
                for (_ in query) {

                    if (query[_] === undefined) {
                        delete query[_];
                    }

                }

                if (secure && root.authorize()) {
                    headers[options.authorizationHeader] = root.authorize();
                }

                if (language) {

                    if (safe) {
                        headers['Accept-Language'] = language;
                    } else if (representation) {
                        headers['Content-Language'] = language;
                    }

                }

                for (_ in augments) {

                    if (augments[_] !== null) {
                        headers[_] = augments[_];
                    }

                }

                transport.request({
                    uri: protocol + base + path + urlencode.encode(query),
                    method: verb,
                    headers: headers,
                    body: representation,
                    cookie: options.cookie
                }, function (err, body, xhr) {
                    var token;

                    function cb(err) {

                        if (!callback) {
                            return;
                        }

                        var args = [err, body];

                        /**
                         * Pass xhr object only if explicitly expected
                         * otherwise some libraries using 'arguments' object
                         * can work incorrectly
                         */
                        callback.length === 3 && args.push(xhr);
                        callback.apply(this, args);
                    }

                    if (/(^| )Date:/gm.test(xhr.getAllResponseHeaders())) {
                        lastDate = Date.parse(xhr.getResponseHeader('Date'));
                    }

                    if (err) {

                        if (err.status === 401) {
                            root.unauthorize();
                        }

                        cb(new Exception(err, body));

                        return;
                    }

                    res.variable && (variables[res.variable] = body && body[res]);

                    if (secure) {
                        token = xhr.getResponseHeader(options.tokenHeader);
                        token && root.authorize.token(token, root.authorize.realm());
                    }

                    cb(null);
                });
            };
        }

        return function generate(map, uri, res) {
            var key,
                value,
                parts,
                secure,
                transparent,
                tree,
                _;

            res = res || {};

            for (key in map) {
                if (map.hasOwnProperty(key) && key !== '@') {
                    value = map[key];

                    transparent = key.match(placeholder);

                    key = (parts = key.split('#')).shift();

                    parts = parts.map(function (name) {
                        var template, variable, match;

                        if (name.charAt(0) === '/') {
                            template = true;
                            name = name.substr(1);
                        }

                        if (match = name.match(placeholder)) {
                            _ = match[1].split('=');

                            name = _[0];
                            variable = _[1];
                        }

                        // monkey code
                        // TODO: remove primitive type object wrapper
                        name = new String(name);
                        name.template = template;
                        name.variable = variable;

                        return name;
                    });

                    if (key.charAt(key.length - 1) === '*')
                        secure = !!(key = key.substring(0, key.length - 1));

                    if (key.charAt(0) !== ':') {
                        _ = key.toLowerCase();

                        tree = typeof value === 'string'
                            ? method(key, uri || '/', result(value), parts, secure)
                            : generate(value, (uri || '') + '/' + (value['@'] || key), transparent && res);

                        transparent || (res[_] = tree);

                        options.synonyms[key] && options.synonyms[key].forEach(function (alias) {
                            res[alias] || (res[alias] = res[_]);
                        });
                    } else
                        res[key.substr(1)] = res[value.toLowerCase()];
                }
            }

            return res;
        }(desc.resources, undefined, root);
    };

});
<|endoftext|>


<commit_before>function getResult(callback, json) {
    var token = '';
    console.log('call_id : api_5_call_1');
    var input = json.input;
    var all_required = false;
    if (input.artistLike) {
        all_required = true;
    }
    if (all_required) {
        var call = 'https://api.spotify.com/v1/search?q=' + input.artistLike + '&type=artist';
        require('request')(call, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var info = JSON.parse(body);
                if (!json.input.artist) {
                    json.input.artist = {};
                }
                json.input.artist.genre = info.json.artists.items[0].genres[0];
                if (!json.input.spotify) {
                    json.input.spotify = {};
                }
                if (!json.input.spotify.artist) {
                    json.input.spotify.artist = {};
                }
                json.input.spotify.artist.id = info.json.artists.items[0].id;
                if (!json.input.artist) {
                    json.input.artist = {};
                }
                json.input.artist.pictureUrl = info.json.artists.items[0].images[0].url;
                if (!json.input.artist) {
                    json.input.artist = {};
                }
                json.input.artist.name = info.json.artists.items[0].name;
                json.index = json.index + 1;
                if (json.step[json.index].nb == 'end') {
                    callback(json.input[json.query]);
                } else {
                    var action_module = require('./' + json.step[json.index].call_id + '.js');
                    action_module.getResult(function(result) {
                        callback(result);
                    }, json);
                }
            } else {
                callback('the request failed');
            }
        });
    }
}
exports.getResult = getResult;
<commit_msg>Update api_5_call_1.js<commit_after>function getResult(callback, json) { var token = ''; console.log('call_id : api_5_call_1'); var input = json.input; var all_required = false; if(input.artistLike){ all_required = true; } if(all_required){ var call = 'https://api.spotify.com/v1/search?q='+input.artistLike+'&type=artist'; require('request')(call, function (error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.parse(body); if(!json.input.spotify){ json.input.spotify = {}; } if(!json.input.spotify.artist){ json.input.spotify.artist = {}; } if(!json.input.spotify.artist.external_urls){ json.input.spotify.artist.external_urls = {}; }json.input.spotify.artist.external_urls.spotify = info.artists.items[0].external.urls.spotify; if(!json.input.artist){ json.input.artist = {}; }json.input.artist.genre = info.artists.items[0].genres[0]; if(!json.input.spotify){ json.input.spotify = {}; } if(!json.input.spotify.artist){ json.input.spotify.artist = {}; }json.input.spotify.artist.id = info.artists.items[0].id; if(!json.input.artist){ json.input.artist = {}; }json.input.artist.pictureUrl = info.artists.items[0].images[0].url; if(!json.input.artist){ json.input.artist = {}; }json.input.artist.name = info.artists.items[0].name; json.index = json.index+1; if(json.step[json.index].nb=='end'){ callback(json.input[json.query]); }else{ var action_module = require('./'+ json.step[json.index].call_id + '.js'); action_module.getResult(function(result) { callback(result); },json); } }else{ callback('the request failed'); } }); } } exports.getResult = getResult;
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * n.b.: hella copy-pasted from sails/bin/sails-console.js
 */

require('babel-register')
const _ = require('lodash')
const fs = require('fs')
const sails = require('sails')

;(function () {
  // Try to get `rc` dependency
  var rc
  try {
    rc = require('rc')
  } catch (e0) {
    try {
      rc = require('sails/node_modules/rc')
    } catch (e1) {
      console.error('Could not find dependency: `rc`.')
      console.error('Your `.sailsrc` file(s) will be ignored.')
      console.error('To resolve this, run:')
      console.error('npm install rc --save')
      rc = () => ({})
    }
  }

  // Start server
  sails.lift(_.merge(rc('sails'), {
    log: {
      noShip: true
    },
    // comment out all of this hook-disabling to test sockets from the console
    hooks: {
      http: false,
      sockets: false,
      views: false
    }
  }), function (err) {
    var repl = require('repl').start('sails> ')
    try {
      history(repl, require('path').join(sails.config.paths.tmp, '.node_history'))
    } catch (e) {}
    repl.on('exit', function () {
      process.exit()
    })

    require('async-repl/stubber')(repl)
    // require('promirepl').promirepl(repl)
  })
})()

/**
* REPL History
* Pulled directly from https://github.com/tmpvar/repl.history
* with the slight tweak of setting historyIndex to -1 so that
* it works as expected.
*/

function history (repl, file) {
  try {
    repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse()
    repl.rli.history.shift()
    repl.rli.historyIndex = -1
  } catch (e) {}

  var fd = fs.openSync(file, 'a')

  repl.rli.addListener('line', function (code) {
    if (code && code !== '.history') {
      fs.write(fd, code + '\n')
    } else {
      repl.rli.historyIndex++
      repl.rli.history.pop()
    }
  })

  process.on('exit', function () {
    fs.closeSync(fd)
  })

  repl.commands['.history'] = {
    help: 'Show the history',
    action: function () {
      var out = []
      repl.rli.history.forEach(function (v, k) {
        out.push(v)
      })
      repl.outputStream.write(out.reverse().join('\n') + '\n')
      repl.displayPrompt()
    }
  }
}
<commit_msg>stop deprecation warning in console<commit_after>#!/usr/bin/env node

/**
 * n.b.: hella copy-pasted from sails/bin/sails-console.js
 */

require('babel-register')
const _ = require('lodash')
const fs = require('fs')
const sails = require('sails')

;(function () {
  // Try to get `rc` dependency
  var rc
  try {
    rc = require('rc')
  } catch (e0) {
    try {
      rc = require('sails/node_modules/rc')
    } catch (e1) {
      console.error('Could not find dependency: `rc`.')
      console.error('Your `.sailsrc` file(s) will be ignored.')
      console.error('To resolve this, run:')
      console.error('npm install rc --save')
      rc = () => ({})
    }
  }

  // Start server
  sails.lift(_.merge(rc('sails'), {
    log: {
      noShip: true
    },
    // comment out all of this hook-disabling to test sockets from the console
    hooks: {
      http: false,
      sockets: false,
      views: false
    }
  }), function (err) { // eslint-disable-line
    var repl = require('repl').start('sails> ')
    try {
      history(repl, require('path').join(sails.config.paths.tmp, '.node_history'))
    } catch (e) {}
    repl.on('exit', function () {
      process.exit()
    })

    require('async-repl/stubber')(repl)
    // require('promirepl').promirepl(repl)
  })
})()

/**
* REPL History
* Pulled directly from https://github.com/tmpvar/repl.history
* with the slight tweak of setting historyIndex to -1 so that
* it works as expected.
*/

function history (repl, file) {
  try {
    repl.rli.history = fs.readFileSync(file, 'utf-8').split('\n').reverse()
    repl.rli.history.shift()
    repl.rli.historyIndex = -1
  } catch (e) {}

  var fd = fs.openSync(file, 'a')

  repl.rli.addListener('line', function (code) {
    if (code && code !== '.history') {
      fs.write(fd, code + '\n', () => {})
    } else {
      repl.rli.historyIndex++
      repl.rli.history.pop()
    }
  })

  process.on('exit', function () {
    fs.closeSync(fd)
  })

  repl.commands['.history'] = {
    help: 'Show the history',
    action: function () {
      var out = []
      repl.rli.history.forEach(function (v, k) {
        out.push(v)
      })
      repl.outputStream.write(out.reverse().join('\n') + '\n')
      repl.displayPrompt()
    }
  }
}
<|endoftext|>


<commit_before>(function() {
/* globals define, Ember, DS, jQuery */

  function processEmberShims() {
    var shims = {
      'ember': {
        'default': Ember
      },
      'ember-application': {
        'default': Ember.Application
      },
      'ember-array': {
        'default': Ember.Array
      },
      'ember-array/mutable': {
        'default': Ember.MutableArray
      },
      'ember-array/utils': {
        'A':            Ember.A,
        'isEmberArray': Ember.isArray,
        'wrap':         Ember.makeArray
      },
      'ember-component': {
        'default': Ember.Component
      },
      'ember-components/checkbox': {
        'default': Ember.Checkbox
      },
      'ember-components/text-area': {
        'default': Ember.TextArea
      },
      'ember-components/text-field': {
        'default': Ember.TextField
      },
      'ember-controller': {
        'default': Ember.Controller
      },
      'ember-controller/inject': {
        'default': Ember.inject.controller
      },
      'ember-controller/proxy': {
        'default': Ember.ArrayProxy
      },
      'ember-controllers/sortable': {
        'default': Ember.SortableMixin
      },
      'ember-debug': {
        'log':      Ember.debug,
        'inspect':  Ember.inspect,
        'run':      Ember.runInDebug,
        'warn':     Ember.warn
      },
      'ember-debug/container-debug-adapter': {
        'default': Ember.ContainerDebugAdapter
      },
      'ember-debug/data-adapter': {
        'default': Ember.DataAdapter
      },
      'ember-deprecations': {
        'deprecate':      Ember.deprecate,
        'deprecateFunc':  Ember.deprecateFunc
      },
      'ember-enumerable': {
        'default': Ember.Enumerable
      },
      'ember-evented': {
        'default': Ember.Evented
      },
      'ember-evented/on': {
        'default': Ember.on
      },
      'ember-globals-resolver': {
        'default': Ember.DefaultResolver
      },
      'ember-helper': {
        'default':  Ember.Helper,
        'helper':   Ember.Helper.helper
      },
      'ember-instrumentation': {
        'instrument':   Ember.Instrumentation.instrument,
        'reset':        Ember.Instrumentation.reset,
        'subscribe':    Ember.Instrumentation.subscribe,
        'unsubscribe':  Ember.Instrumentation.unsubscribe
      },
      'ember-locations/hash': {
        'default': Ember.HashLocation
      },
      'ember-locations/history': {
        'default': Ember.HistoryLocation
      },
      'ember-locations/none': {
        'default': Ember.NoneLocation
      },
      'ember-map': {
        'default':      Ember.Map,
        'withDefault':  Ember.MapWithDefault
      },
      'ember-metal/destroy': {
        'default': Ember.destroy
      },
      'ember-metal/events': {
        'addListener':    Ember.addListener,
        'removeListener': Ember.removeListener,
        'send':           Ember.sendEvent
      },
      'ember-metal/get': {
        'default': Ember.get
      },
      'ember-metal/mixin': {
        'default': Ember.Mixin
      },
      'ember-metal/observer': {
        'default':        Ember.observer,
        'addObserver':    Ember.addObserver,
        'removeObserver': Ember.removeObserver
      },
      'ember-metal/on-load': {
        'default':  Ember.onLoad,
        'run':      Ember.runLoadHooks
      },
      'ember-metal/set': {
        'default':        Ember.set,
        'setProperties':  Ember.setProperties,
        'trySet':         Ember.trySet
      },
      'ember-metal/utils': {
        'aliasMethod':  Ember.aliasMethod,
        'assert':       Ember.assert,
        'cacheFor':     Ember.cacheFor,
        'copy':         Ember.copy,
      },
      'ember-object': {
        'default': Ember.Object
      },
      'ember-platform': {
        'assign':         Ember.merge,
        'create':         Ember.create,
        'defineProperty': Ember.platform.defineProperty,
        'hasAccessors':   Ember.platform.hasPropertyAccessors,
        'keys':           Ember.keys
      },
      'ember-route': {
        'default': Ember.Route
      },
      'ember-router': {
        'default': Ember.Router
      },
      'ember-runloop': {
        'default':      Ember.run,
        'begin':        Ember.run.begin,
        'bind':         Ember.run.bind,
        'cancel':       Ember.run.cancel,
        'debounce':     Ember.run.debounce,
        'end':          Ember.run.end,
        'join':         Ember.run.join,
        'later':        Ember.run.later,
        'next':         Ember.run.next,
        'once':         Ember.run.once,
        'schedule':     Ember.run.schedule,
        'scheduleOnce': Ember.run.scheduleOnce,
        'throttle':     Ember.run.throttle
      },
      'ember-service': {
        'default': Ember.Service
      },
      'ember-service/inject': {
        'default': Ember.inject.service
      },
      'ember-set/ordered': {
        'default': Ember.OrderedSet
      },
      'ember-string': {
        'camelize':     Ember.String.camelize,
        'capitalize':   Ember.String.capitalize,
        'classify':     Ember.String.classify,
        'dasherize':    Ember.String.dasherize,
        'decamelize':   Ember.String.decamelize,
        'fmt':          Ember.String.fmt,
        'htmlSafe':     Ember.String.htmlSafe,
        'loc':          Ember.String.loc,
        'underscore':   Ember.String.underscore,
        'w':            Ember.String.w
      },
      'ember-utils': {
        'isBlank':    Ember.isBlank,
        'isEmpty':    Ember.isEmpty,
        'isNone':     Ember.isNone,
        'isPresent':  Ember.isPresent,
        'tryInvoke':  Ember.tryInvoke,
        'typeOf':     Ember.typeOf
      }
    };

    // populate `ember/computed` named exports
    shims['ember-computed'] = {
      'default': Ember.computed
    };
    var computedMacros = [
      "empty","notEmpty", "none", "not", "bool", "match",
      "equal", "gt", "gte", "lt", "lte", "alias", "oneWay",
      "reads", "readOnly", "deprecatingAlias",
      "and", "or", "collect", "sum", "min", "max",
      "map", "sort", "setDiff", "mapBy", "mapProperty",
      "filter", "filterBy", "filterProperty", "uniq",
      "union", "intersect"
    ];
    for (var i = 0, l = computedMacros.length; i < l; i++) {
      var key = computedMacros[i];
      shims['ember-computed'][key] = Ember.computed[key];
    }

    for (var moduleName in shims) {
      generateModule(moduleName, shims[moduleName]);
    }
  }

  function processEmberDataShims() {
    var shims = {
      'ember-data':                          '',
      'ember-data/model':                    'Model',
      'ember-data/serializers/rest':         'RESTSerializer',
      'ember-data/serializers/active-model': 'ActiveModelSerializer',
      'ember-data/serializers/json':         'JSONSerializer',
      'ember-data/adapters/rest':            'RESTAdapter',
      'ember-data/adapter':                  'Adapter',
      'ember-data/adapters/active-model':    'ActiveModelAdapter',
      'ember-data/serializers/json':         'JSONSerializer',
      'ember-data/store':                    'Store',
      'ember-data/transform':                'Transform',
      'ember-data/attr':                     'attr',
      'ember-data/relationships':            ['hasMany', 'belongsTo']
    };

    for (var moduleName in shims) {
      generateLazyModule('DS', moduleName, shims[moduleName]);
    }

    if (Ember.Test) {
      var testShims = {
        'ember-test': {
          'default': Ember.Test
        },
        'ember-test/adapter': {
          'default': Ember.Test.Adapter
        },
        'ember-test/qunit-adapter': {
          'default': Ember.Test.QUnitAdapter
        }
      };

      for (var moduleName in testShims) {
        generateModule(moduleName, testShims[moduleName]);
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      return values;
    });
  }

  function generateLazyModule(namespace, name, globalName) {
    define(name, [], function() {
      'use strict';

      var exportObject = {};

      if (typeof globalName === 'object') {
        for (var i = 0, l = globalName.length; i < l; i++) {
          exportObject[globalName[i]] = window[namespace][globalName[i]];
        }
      } else {
        exportObject['default'] = (globalName !== '') ? window[namespace][globalName] : window[namespace];
      }

      return exportObject;
    });
  }

  processEmberShims();
  processEmberDataShims();
  generateModule('jquery', { 'default': jQuery });
})();
<commit_msg>Handle Ember.Helper being undefined (Ember < 1.13).<commit_after>(function() {
/* globals define, Ember, DS, jQuery */

  function processEmberShims() {
    var shims = {
      'ember': {
        'default': Ember
      },
      'ember-application': {
        'default': Ember.Application
      },
      'ember-array': {
        'default': Ember.Array
      },
      'ember-array/mutable': {
        'default': Ember.MutableArray
      },
      'ember-array/utils': {
        'A':            Ember.A,
        'isEmberArray': Ember.isArray,
        'wrap':         Ember.makeArray
      },
      'ember-component': {
        'default': Ember.Component
      },
      'ember-components/checkbox': {
        'default': Ember.Checkbox
      },
      'ember-components/text-area': {
        'default': Ember.TextArea
      },
      'ember-components/text-field': {
        'default': Ember.TextField
      },
      'ember-controller': {
        'default': Ember.Controller
      },
      'ember-controller/inject': {
        'default': Ember.inject.controller
      },
      'ember-controller/proxy': {
        'default': Ember.ArrayProxy
      },
      'ember-controllers/sortable': {
        'default': Ember.SortableMixin
      },
      'ember-debug': {
        'log':      Ember.debug,
        'inspect':  Ember.inspect,
        'run':      Ember.runInDebug,
        'warn':     Ember.warn
      },
      'ember-debug/container-debug-adapter': {
        'default': Ember.ContainerDebugAdapter
      },
      'ember-debug/data-adapter': {
        'default': Ember.DataAdapter
      },
      'ember-deprecations': {
        'deprecate':      Ember.deprecate,
        'deprecateFunc':  Ember.deprecateFunc
      },
      'ember-enumerable': {
        'default': Ember.Enumerable
      },
      'ember-evented': {
        'default': Ember.Evented
      },
      'ember-evented/on': {
        'default': Ember.on
      },
      'ember-globals-resolver': {
        'default': Ember.DefaultResolver
      },
      'ember-helper': {
        'default':  Ember.Helper,
        'helper':   Ember.Helper && Ember.Helper.helper
      },
      'ember-instrumentation': {
        'instrument':   Ember.Instrumentation.instrument,
        'reset':        Ember.Instrumentation.reset,
        'subscribe':    Ember.Instrumentation.subscribe,
        'unsubscribe':  Ember.Instrumentation.unsubscribe
      },
      'ember-locations/hash': {
        'default': Ember.HashLocation
      },
      'ember-locations/history': {
        'default': Ember.HistoryLocation
      },
      'ember-locations/none': {
        'default': Ember.NoneLocation
      },
      'ember-map': {
        'default':      Ember.Map,
        'withDefault':  Ember.MapWithDefault
      },
      'ember-metal/destroy': {
        'default': Ember.destroy
      },
      'ember-metal/events': {
        'addListener':    Ember.addListener,
        'removeListener': Ember.removeListener,
        'send':           Ember.sendEvent
      },
      'ember-metal/get': {
        'default': Ember.get
      },
      'ember-metal/mixin': {
        'default': Ember.Mixin
      },
      'ember-metal/observer': {
        'default':        Ember.observer,
        'addObserver':    Ember.addObserver,
        'removeObserver': Ember.removeObserver
      },
      'ember-metal/on-load': {
        'default':  Ember.onLoad,
        'run':      Ember.runLoadHooks
      },
      'ember-metal/set': {
        'default':        Ember.set,
        'setProperties':  Ember.setProperties,
        'trySet':         Ember.trySet
      },
      'ember-metal/utils': {
        'aliasMethod':  Ember.aliasMethod,
        'assert':       Ember.assert,
        'cacheFor':     Ember.cacheFor,
        'copy':         Ember.copy,
      },
      'ember-object': {
        'default': Ember.Object
      },
      'ember-platform': {
        'assign':         Ember.merge,
        'create':         Ember.create,
        'defineProperty': Ember.platform.defineProperty,
        'hasAccessors':   Ember.platform.hasPropertyAccessors,
        'keys':           Ember.keys
      },
      'ember-route': {
        'default': Ember.Route
      },
      'ember-router': {
        'default': Ember.Router
      },
      'ember-runloop': {
        'default':      Ember.run,
        'begin':        Ember.run.begin,
        'bind':         Ember.run.bind,
        'cancel':       Ember.run.cancel,
        'debounce':     Ember.run.debounce,
        'end':          Ember.run.end,
        'join':         Ember.run.join,
        'later':        Ember.run.later,
        'next':         Ember.run.next,
        'once':         Ember.run.once,
        'schedule':     Ember.run.schedule,
        'scheduleOnce': Ember.run.scheduleOnce,
        'throttle':     Ember.run.throttle
      },
      'ember-service': {
        'default': Ember.Service
      },
      'ember-service/inject': {
        'default': Ember.inject.service
      },
      'ember-set/ordered': {
        'default': Ember.OrderedSet
      },
      'ember-string': {
        'camelize':     Ember.String.camelize,
        'capitalize':   Ember.String.capitalize,
        'classify':     Ember.String.classify,
        'dasherize':    Ember.String.dasherize,
        'decamelize':   Ember.String.decamelize,
        'fmt':          Ember.String.fmt,
        'htmlSafe':     Ember.String.htmlSafe,
        'loc':          Ember.String.loc,
        'underscore':   Ember.String.underscore,
        'w':            Ember.String.w
      },
      'ember-utils': {
        'isBlank':    Ember.isBlank,
        'isEmpty':    Ember.isEmpty,
        'isNone':     Ember.isNone,
        'isPresent':  Ember.isPresent,
        'tryInvoke':  Ember.tryInvoke,
        'typeOf':     Ember.typeOf
      }
    };

    // populate `ember/computed` named exports
    shims['ember-computed'] = {
      'default': Ember.computed
    };
    var computedMacros = [
      "empty","notEmpty", "none", "not", "bool", "match",
      "equal", "gt", "gte", "lt", "lte", "alias", "oneWay",
      "reads", "readOnly", "deprecatingAlias",
      "and", "or", "collect", "sum", "min", "max",
      "map", "sort", "setDiff", "mapBy", "mapProperty",
      "filter", "filterBy", "filterProperty", "uniq",
      "union", "intersect"
    ];
    for (var i = 0, l = computedMacros.length; i < l; i++) {
      var key = computedMacros[i];
      shims['ember-computed'][key] = Ember.computed[key];
    }

    for (var moduleName in shims) {
      generateModule(moduleName, shims[moduleName]);
    }
  }

  function processEmberDataShims() {
    var shims = {
      'ember-data':                          '',
      'ember-data/model':                    'Model',
      'ember-data/serializers/rest':         'RESTSerializer',
      'ember-data/serializers/active-model': 'ActiveModelSerializer',
      'ember-data/serializers/json':         'JSONSerializer',
      'ember-data/adapters/rest':            'RESTAdapter',
      'ember-data/adapter':                  'Adapter',
      'ember-data/adapters/active-model':    'ActiveModelAdapter',
      'ember-data/serializers/json':         'JSONSerializer',
      'ember-data/store':                    'Store',
      'ember-data/transform':                'Transform',
      'ember-data/attr':                     'attr',
      'ember-data/relationships':            ['hasMany', 'belongsTo']
    };

    for (var moduleName in shims) {
      generateLazyModule('DS', moduleName, shims[moduleName]);
    }

    if (Ember.Test) {
      var testShims = {
        'ember-test': {
          'default': Ember.Test
        },
        'ember-test/adapter': {
          'default': Ember.Test.Adapter
        },
        'ember-test/qunit-adapter': {
          'default': Ember.Test.QUnitAdapter
        }
      };

      for (var moduleName in testShims) {
        generateModule(moduleName, testShims[moduleName]);
      }
    }
  }

  function generateModule(name, values) {
    define(name, [], function() {
      'use strict';

      return values;
    });
  }

  function generateLazyModule(namespace, name, globalName) {
    define(name, [], function() {
      'use strict';

      var exportObject = {};

      if (typeof globalName === 'object') {
        for (var i = 0, l = globalName.length; i < l; i++) {
          exportObject[globalName[i]] = window[namespace][globalName[i]];
        }
      } else {
        exportObject['default'] = (globalName !== '') ? window[namespace][globalName] : window[namespace];
      }

      return exportObject;
    });
  }

  processEmberShims();
  processEmberDataShims();
  generateModule('jquery', { 'default': jQuery });
})();
<|endoftext|>


<commit_before>var voxel = require('voxel')
var interact = require('interact')
var Chunker = require('./chunker')
var Detector = require('./detector')
var THREE = require('three')
var Stats = require('./stats')
var PlayerControls = require('./player-controls.js')
var requestAnimationFrame = require('raf')
var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter

module.exports = Game

function Game(opts) {
  if (!(this instanceof Game)) return new Game(opts)
  var self = this
  if (!opts) opts = {}
  this.generateVoxel = opts.generateVoxel || voxel.generator['Hilly Terrain']
  this.texturePath = opts.texturePath || '/textures/'
  this.cubeSize = opts.cubeSize || 25
  this.chunkSize = opts.chunkSize || 32
  this.chunkDistance = opts.chunkDistance || 2
  this.startingPosition = opts.startingPosition || new THREE.Vector3(35,1024,35)
  this.worldOrigin = opts.worldOrigin || new THREE.Vector3(0,0,0)
  if (opts.renderCallback) this.renderCallback = opts.renderCallback

  this.material = this.loadTextures([ 'grass', 'grass_dirt', 'brick' ])
  this.height = window.innerHeight
  this.width = window.innerWidth
  this.scene = scene = new THREE.Scene()
  this.camera = this.createCamera(scene)
  this.renderer = this.createRenderer()
  this.controls = this.createControls()
  this.addLights(this.scene)
  this.moveToPosition(this.startingPosition)
  this.chunker = new Chunker(this)
  var chunks = this.chunker.generateMissingChunks(this.worldOrigin)
  this.addStats()
  window.addEventListener('resize', this.onWindowResize.bind(this), false)
  window.addEventListener('mousedown', this.onMouseDown.bind(this), false)
  window.addEventListener('mouseup', this.onMouseUp.bind(this), false)
  requestAnimationFrame(window).on('data', this.tick.bind(this))
}

inherits(Game, EventEmitter)

Game.prototype.setupPointerLock = function(element) {
  var self = this
  element = element || document.body
  if (typeof element !== 'object') element = document.querySelector(element)
  if (!pointerLock.pointerAvailable()) return alert("Your browser doesn't support pointer lock!")
  var pointer = this.pointer = interact(document.body)
  pointer.on('attain', function(movements) {
    game.controls.enabled = true
    movements.pipe(self.controls)
  })
  pointer.on('release', function() {
    game.controls.enabled = false
  })
  pointer.on('error', function() {
    // user denied pointer lock OR it's not available
    console.error('pointerlock error')
  })
}

Game.prototype.requestPointerLock = function(element) {
  if (!this.pointer) this.setupPointerLock(element)
  this.pointer.request()
}

Game.prototype.moveToPosition = function(position) {
  var pos = this.controls.yawObject.position
  pos.x = position.x
  pos.y = position.y
  pos.z = position.z
}

Game.prototype.onWindowResize = function() {
  this.camera.aspect = window.innerWidth / window.innerHeight
  this.camera.updateProjectionMatrix()
  this.renderer.setSize( window.innerWidth, window.innerHeight )
}

Game.prototype.addMarker = function(position) {
  var geometry = new THREE.SphereGeometry( 1, 4, 4 );
  var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );
  var mesh = new THREE.Mesh( geometry, material );
  mesh.position.copy(position)
  this.scene.add(mesh)
}

Game.prototype.onMouseDown = function(e) {
  var intersection = this.raycast()
  if (intersection) this.emit('mousedown', intersection, e)
}

Game.prototype.onMouseUp = function(e) {
  var intersection = this.raycast()
  if (intersection) this.emit('mouseup', intersection, e)
}

Game.prototype.intersectAllMeshes = function(start, direction) {
  var self = this
  var meshes = []
  Object.keys(self.chunker.meshes).map(function(key) {
    meshes.push(self.chunker.meshes[key].surfaceMesh)
  })
  var d = direction.subSelf(start).normalize()
  var ray = new THREE.Raycaster(start, d)
  var intersections = ray.intersectObjects( meshes )
  if (intersections.length === 0) return false
  var intersection = intersections[0]
  var p = new THREE.Vector3()
  p.copy(intersection.point)
  p.x += d.x
  p.y += d.y
  p.z += d.z
  return p
}

Game.prototype.raycast = function() {
  var start = this.controls.yawObject.position.clone()
  var direction = this.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
  var intersects = this.intersectAllMeshes(start, direction)
  return intersects
}

Game.prototype.loadTextures = function(names) {
  var self = this;
  return new THREE.MeshFaceMaterial(names.map(function (name) {
    var tex = THREE.ImageUtils.loadTexture(self.texturePath + name + ".png")
    tex.magFilter = THREE.NearestFilter
    tex.minFilter = THREE.LinearMipMapLinearFilter

    return new THREE.MeshLambertMaterial({
      map: tex,
      ambient: 0xbbbbbb
    })
  }))
}

Game.prototype.createCamera = function() {
  var camera;
  camera = new THREE.PerspectiveCamera(60, this.width / this.height, 1, 10000)
  camera.lookAt(new THREE.Vector3(0, 0, 0))
  this.scene.add(camera)
  return camera
}

Game.prototype.createControls = function() {
  var controls = new PlayerControls(this.camera)
  this.scene.add( controls.yawObject )
  return controls
}

Game.prototype.createRenderer = function() {
  if( Detector.webgl ){
    this.renderer = new THREE.WebGLRenderer({
      antialias: true
    })
  } else {
    this.renderer = new THREE.CanvasRenderer()
  }
  this.renderer.setSize(this.width, this.height)
  this.renderer.setClearColorHex(0xBFD1E5, 1.0)
  this.renderer.clear()
  this.element = this.renderer.domElement
  return this.renderer
}

Game.prototype.appendTo = function (element) {
  if (typeof element === 'object') {
    element.appendChild(this.element)
  }
  else {
    document.querySelector(element).appendChild(this.element)
  }
}

Game.prototype.addStats = function() {
  stats = new Stats()
  stats.domElement.style.position  = 'absolute'
  stats.domElement.style.bottom  = '0px'
  document.body.appendChild( stats.domElement )
}

Game.prototype.cameraRotation = function() {
  var xAngle = this.controls.pitchObject.rotation.x
  var yAngle = this.controls.yawObject.rotation.y
  return {x: xAngle, y: yAngle}
}

Game.prototype.getCollisions = function(position, checker) {
  var self = this
  var p = position.clone()
  var w = self.cubeSize / 4 // width of player cube
  var h = self.cubeSize * 1.5 // height of player cube

  var vertices = {
    bottom: [
      new THREE.Vector3(p.x - w, p.y - h, p.z - w),
      new THREE.Vector3(p.x - w, p.y - h, p.z + w),
      new THREE.Vector3(p.x + w, p.y - h, p.z - w),
      new THREE.Vector3(p.x + w, p.y - h, p.z + w)
    ],
    middle: [
      new THREE.Vector3(p.x - w, p.y - h / 2, p.z - w),
      new THREE.Vector3(p.x - w, p.y - h / 2, p.z + w),
      new THREE.Vector3(p.x + w, p.y - h / 2, p.z - w),
      new THREE.Vector3(p.x + w, p.y - h / 2, p.z + w)
    ],
    top: [
      new THREE.Vector3(p.x - w, p.y, p.z - w),
      new THREE.Vector3(p.x - w, p.y, p.z + w),
      new THREE.Vector3(p.x + w, p.y, p.z - w),
      new THREE.Vector3(p.x + w, p.y, p.z + w)
    ],
  }

  return {
    bottom: vertices.bottom.map(check).filter(Boolean),
    middle: vertices.middle.map(check).filter(Boolean),
    top: vertices.top.map(check).filter(Boolean)
  }

  function check(vertex) {
    if (checker) return checker(vertex) && vertex
    return self.voxelAtPosition(vertex) && vertex
  }
}

Game.prototype.addLights = function(scene) {
  var ambientLight, directionalLight
  ambientLight = new THREE.AmbientLight(0xaaaaaa)
  scene.add(ambientLight)
  var light	= new THREE.DirectionalLight( 0xffffff )
  light.position.set( Math.random(), Math.random(), Math.random() ).normalize()
  scene.add( light )
};

Game.prototype.currentMesh = function() {
  var cid = game.chunker.chunkAtPosition(game.controls.yawObject.position).join('|')
  return game.chunker.meshes[cid]
}

Game.prototype.voxelIndex = function(pos) {
  var size = this.chunkSize
  var x = (size + Math.floor(pos.x / this.cubeSize)) % size
  var y = (size + Math.floor(pos.y / this.cubeSize)) % size
  var z = (size + Math.floor(pos.z / this.cubeSize)) % size
  var vidx = x + y*size + z*size*size
  return vidx
}

Game.prototype.createBlock = function(pos, val) {
  var self = this
  var direction = self.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
  var start = self.controls.yawObject.position.clone()
  var d = direction.subSelf(start).normalize()

  var p = new THREE.Vector3()
  p.copy(pos)
  p.x -= 1.1 * d.x
  p.y -= 1.1 * d.y
  p.z -= 1.1 * d.z
  var block = self.getBlock(p)
  if (block) return false

  var vidx = self.voxelIndex(p)
  var c = self.chunker.chunkAtPosition(p)
  var ckey = c.join('|')
  var chunk = self.chunker.chunks[ckey]
  if (!chunk) return false

  var collisions = self.getCollisions(self.controls.yawObject.position, check)
  if (collisions.top.length) return false
  if (collisions.middle.length) return false
  if (collisions.bottom.length) return false

  chunk.voxels[vidx] = val
  this.chunker.generateChunk(c[0], c[1], c[2])
  return true

  function check(v) { return vidx === self.voxelIndex(v) }
}

Game.prototype.setBlock = function(pos, val) {
  var hitVoxel = this.voxelAtPosition(pos, val)
  var c = this.chunker.chunkAtPosition(pos)
  this.chunker.generateChunk(c[0], c[1], c[2])
}

Game.prototype.getBlock = function(pos) {
  return this.voxelAtPosition(pos)
}

Game.prototype.voxelAtPosition = function(pos, val) {
  var ckey = this.chunker.chunkAtPosition(pos).join('|')
  var chunk = this.chunker.chunks[ckey]
  if (!chunk) return false
  var vidx = this.voxelIndex(pos)
  if (!vidx) return false
  if (typeof val !== 'undefined') {
    chunk.voxels[vidx] = val
  }
  var v = chunk.voxels[vidx]
  return v
}

Game.prototype.tick = function(dt) {
  var self = this
  this.controls.tick(dt, function () {
    var collisions = self.getCollisions(this.yawObject.position)

    if (collisions.middle.length || collisions.top.length) {
      this.yawObject.translateX(-this.velocity.x)
      this.yawObject.translateY(-this.velocity.y)
      this.yawObject.translateZ(-this.velocity.z)
      this.velocity.x *= -1
      this.velocity.z *= -1
      this.velocity.y = Math.min(0, this.velocity.y)
    }

    if (collisions.bottom.length) {
      this.gravityEnabled = false
      this.velocity.y = Math.max(0, this.velocity.y)
    }
    else {
      this.gravityEnabled = true
    }
  })
  if (this.renderCallback) this.renderCallback.call(this)
  this.renderer.render(this.scene, this.camera)
  stats.update()
}
<commit_msg>set pointerLockDisabled<commit_after>var voxel = require('voxel')
var interact = require('interact')
var Chunker = require('./chunker')
var Detector = require('./detector')
var THREE = require('three')
var Stats = require('./stats')
var PlayerControls = require('./player-controls.js')
var requestAnimationFrame = require('raf')
var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter

module.exports = Game

function Game(opts) {
  if (!(this instanceof Game)) return new Game(opts)
  var self = this
  if (!opts) opts = {}
  this.generateVoxel = opts.generateVoxel || voxel.generator['Hilly Terrain']
  this.texturePath = opts.texturePath || '/textures/'
  this.cubeSize = opts.cubeSize || 25
  this.chunkSize = opts.chunkSize || 32
  this.chunkDistance = opts.chunkDistance || 2
  this.startingPosition = opts.startingPosition || new THREE.Vector3(35,1024,35)
  this.worldOrigin = opts.worldOrigin || new THREE.Vector3(0,0,0)
  if (opts.renderCallback) this.renderCallback = opts.renderCallback

  this.material = this.loadTextures([ 'grass', 'grass_dirt', 'brick' ])
  this.height = window.innerHeight
  this.width = window.innerWidth
  this.scene = scene = new THREE.Scene()
  this.camera = this.createCamera(scene)
  this.renderer = this.createRenderer()
  this.controls = this.createControls()
  this.addLights(this.scene)
  this.moveToPosition(this.startingPosition)
  this.chunker = new Chunker(this)
  var chunks = this.chunker.generateMissingChunks(this.worldOrigin)
  this.addStats()
  window.addEventListener('resize', this.onWindowResize.bind(this), false)
  window.addEventListener('mousedown', this.onMouseDown.bind(this), false)
  window.addEventListener('mouseup', this.onMouseUp.bind(this), false)
  requestAnimationFrame(window).on('data', this.tick.bind(this))
}

inherits(Game, EventEmitter)

Game.prototype.setupPointerLock = function(element) {
  var self = this
  element = element || document.body
  if (typeof element !== 'object') element = document.querySelector(element)
  if (!pointerLock.pointerAvailable()) this.pointerLockDisabled = true
  var pointer = this.pointer = interact(document.body)
  pointer.on('attain', function(movements) {
    game.controls.enabled = true
    movements.pipe(self.controls)
  })
  pointer.on('release', function() {
    game.controls.enabled = false
  })
  pointer.on('error', function() {
    // user denied pointer lock OR it's not available
    self.pointerLockDisabled = true
    console.error('pointerlock error')
  })
}

Game.prototype.requestPointerLock = function(element) {
  if (!this.pointer) this.setupPointerLock(element)
  this.pointer.request()
}

Game.prototype.moveToPosition = function(position) {
  var pos = this.controls.yawObject.position
  pos.x = position.x
  pos.y = position.y
  pos.z = position.z
}

Game.prototype.onWindowResize = function() {
  this.camera.aspect = window.innerWidth / window.innerHeight
  this.camera.updateProjectionMatrix()
  this.renderer.setSize( window.innerWidth, window.innerHeight )
}

Game.prototype.addMarker = function(position) {
  var geometry = new THREE.SphereGeometry( 1, 4, 4 );
  var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );
  var mesh = new THREE.Mesh( geometry, material );
  mesh.position.copy(position)
  this.scene.add(mesh)
}

Game.prototype.onMouseDown = function(e) {
  var intersection = this.raycast()
  if (intersection) this.emit('mousedown', intersection, e)
}

Game.prototype.onMouseUp = function(e) {
  var intersection = this.raycast()
  if (intersection) this.emit('mouseup', intersection, e)
}

Game.prototype.intersectAllMeshes = function(start, direction) {
  var self = this
  var meshes = []
  Object.keys(self.chunker.meshes).map(function(key) {
    meshes.push(self.chunker.meshes[key].surfaceMesh)
  })
  var d = direction.subSelf(start).normalize()
  var ray = new THREE.Raycaster(start, d)
  var intersections = ray.intersectObjects( meshes )
  if (intersections.length === 0) return false
  var intersection = intersections[0]
  var p = new THREE.Vector3()
  p.copy(intersection.point)
  p.x += d.x
  p.y += d.y
  p.z += d.z
  return p
}

Game.prototype.raycast = function() {
  var start = this.controls.yawObject.position.clone()
  var direction = this.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
  var intersects = this.intersectAllMeshes(start, direction)
  return intersects
}

Game.prototype.loadTextures = function(names) {
  var self = this;
  return new THREE.MeshFaceMaterial(names.map(function (name) {
    var tex = THREE.ImageUtils.loadTexture(self.texturePath + name + ".png")
    tex.magFilter = THREE.NearestFilter
    tex.minFilter = THREE.LinearMipMapLinearFilter

    return new THREE.MeshLambertMaterial({
      map: tex,
      ambient: 0xbbbbbb
    })
  }))
}

Game.prototype.createCamera = function() {
  var camera;
  camera = new THREE.PerspectiveCamera(60, this.width / this.height, 1, 10000)
  camera.lookAt(new THREE.Vector3(0, 0, 0))
  this.scene.add(camera)
  return camera
}

Game.prototype.createControls = function() {
  var controls = new PlayerControls(this.camera)
  this.scene.add( controls.yawObject )
  return controls
}

Game.prototype.createRenderer = function() {
  if( Detector.webgl ){
    this.renderer = new THREE.WebGLRenderer({
      antialias: true
    })
  } else {
    this.renderer = new THREE.CanvasRenderer()
  }
  this.renderer.setSize(this.width, this.height)
  this.renderer.setClearColorHex(0xBFD1E5, 1.0)
  this.renderer.clear()
  this.element = this.renderer.domElement
  return this.renderer
}

Game.prototype.appendTo = function (element) {
  if (typeof element === 'object') {
    element.appendChild(this.element)
  }
  else {
    document.querySelector(element).appendChild(this.element)
  }
}

Game.prototype.addStats = function() {
  stats = new Stats()
  stats.domElement.style.position  = 'absolute'
  stats.domElement.style.bottom  = '0px'
  document.body.appendChild( stats.domElement )
}

Game.prototype.cameraRotation = function() {
  var xAngle = this.controls.pitchObject.rotation.x
  var yAngle = this.controls.yawObject.rotation.y
  return {x: xAngle, y: yAngle}
}

Game.prototype.getCollisions = function(position, checker) {
  var self = this
  var p = position.clone()
  var w = self.cubeSize / 4 // width of player cube
  var h = self.cubeSize * 1.5 // height of player cube

  var vertices = {
    bottom: [
      new THREE.Vector3(p.x - w, p.y - h, p.z - w),
      new THREE.Vector3(p.x - w, p.y - h, p.z + w),
      new THREE.Vector3(p.x + w, p.y - h, p.z - w),
      new THREE.Vector3(p.x + w, p.y - h, p.z + w)
    ],
    middle: [
      new THREE.Vector3(p.x - w, p.y - h / 2, p.z - w),
      new THREE.Vector3(p.x - w, p.y - h / 2, p.z + w),
      new THREE.Vector3(p.x + w, p.y - h / 2, p.z - w),
      new THREE.Vector3(p.x + w, p.y - h / 2, p.z + w)
    ],
    top: [
      new THREE.Vector3(p.x - w, p.y, p.z - w),
      new THREE.Vector3(p.x - w, p.y, p.z + w),
      new THREE.Vector3(p.x + w, p.y, p.z - w),
      new THREE.Vector3(p.x + w, p.y, p.z + w)
    ],
  }

  return {
    bottom: vertices.bottom.map(check).filter(Boolean),
    middle: vertices.middle.map(check).filter(Boolean),
    top: vertices.top.map(check).filter(Boolean)
  }

  function check(vertex) {
    if (checker) return checker(vertex) && vertex
    return self.voxelAtPosition(vertex) && vertex
  }
}

Game.prototype.addLights = function(scene) {
  var ambientLight, directionalLight
  ambientLight = new THREE.AmbientLight(0xaaaaaa)
  scene.add(ambientLight)
  var light	= new THREE.DirectionalLight( 0xffffff )
  light.position.set( Math.random(), Math.random(), Math.random() ).normalize()
  scene.add( light )
};

Game.prototype.currentMesh = function() {
  var cid = game.chunker.chunkAtPosition(game.controls.yawObject.position).join('|')
  return game.chunker.meshes[cid]
}

Game.prototype.voxelIndex = function(pos) {
  var size = this.chunkSize
  var x = (size + Math.floor(pos.x / this.cubeSize)) % size
  var y = (size + Math.floor(pos.y / this.cubeSize)) % size
  var z = (size + Math.floor(pos.z / this.cubeSize)) % size
  var vidx = x + y*size + z*size*size
  return vidx
}

Game.prototype.createBlock = function(pos, val) {
  var self = this
  var direction = self.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
  var start = self.controls.yawObject.position.clone()
  var d = direction.subSelf(start).normalize()

  var p = new THREE.Vector3()
  p.copy(pos)
  p.x -= 1.1 * d.x
  p.y -= 1.1 * d.y
  p.z -= 1.1 * d.z
  var block = self.getBlock(p)
  if (block) return false

  var vidx = self.voxelIndex(p)
  var c = self.chunker.chunkAtPosition(p)
  var ckey = c.join('|')
  var chunk = self.chunker.chunks[ckey]
  if (!chunk) return false

  var collisions = self.getCollisions(self.controls.yawObject.position, check)
  if (collisions.top.length) return false
  if (collisions.middle.length) return false
  if (collisions.bottom.length) return false

  chunk.voxels[vidx] = val
  this.chunker.generateChunk(c[0], c[1], c[2])
  return true

  function check(v) { return vidx === self.voxelIndex(v) }
}

Game.prototype.setBlock = function(pos, val) {
  var hitVoxel = this.voxelAtPosition(pos, val)
  var c = this.chunker.chunkAtPosition(pos)
  this.chunker.generateChunk(c[0], c[1], c[2])
}

Game.prototype.getBlock = function(pos) {
  return this.voxelAtPosition(pos)
}

Game.prototype.voxelAtPosition = function(pos, val) {
  var ckey = this.chunker.chunkAtPosition(pos).join('|')
  var chunk = this.chunker.chunks[ckey]
  if (!chunk) return false
  var vidx = this.voxelIndex(pos)
  if (!vidx) return false
  if (typeof val !== 'undefined') {
    chunk.voxels[vidx] = val
  }
  var v = chunk.voxels[vidx]
  return v
}

Game.prototype.tick = function(dt) {
  var self = this
  this.controls.tick(dt, function () {
    var collisions = self.getCollisions(this.yawObject.position)

    if (collisions.middle.length || collisions.top.length) {
      this.yawObject.translateX(-this.velocity.x)
      this.yawObject.translateY(-this.velocity.y)
      this.yawObject.translateZ(-this.velocity.z)
      this.velocity.x *= -1
      this.velocity.z *= -1
      this.velocity.y = Math.min(0, this.velocity.y)
    }

    if (collisions.bottom.length) {
      this.gravityEnabled = false
      this.velocity.y = Math.max(0, this.velocity.y)
    }
    else {
      this.gravityEnabled = true
    }
  })
  if (this.renderCallback) this.renderCallback.call(this)
  this.renderer.render(this.scene, this.camera)
  stats.update()
}
<|endoftext|>


<commit_before>
var canvas = $('#canvas')[0];
var ctx = canvas.getContext('2d');
var ballRadius = 10;
var ballX = canvas.width/2;
var ballY = canvas.height - (ballRadius * 8);
var directionX = 6;
var directionY = 6;
var paddleWidth = 150;
var paddleHeight = 20;
var paddle = new Block((canvas.width - paddleWidth)/2, 450, 150, 20);
var blocks = [];
var ball = {x: ballX, y: ballY};

function draw(){
  drawBall();
  paddle.draw();
}

function ballCollision() {
  canvasEdgeCollision();
  paddleAndBallCollision();
}

function ballMovement() {
ballX += directionX;
ballY -= directionY;
ball.x = ballX;
ball.y = ballY;
}

function canvasEdgeCollision() {
if(ballX > canvas.width - ballRadius || ballX < ballRadius){
  directionX = -directionX;
}
if(ballY < ballRadius){
  directionY = -directionY;
  }
}

function paddleAndBallCollision() {
if(ball.x <= paddle.x + paddle.width &&
  ball.x + ballRadius >= paddle.x &&
  ball.y <= paddle.y + paddle.height &&
  ballRadius + ball.y >= paddle.y) {
    directionY = -directionY;
  }
if(ball.x >= paddle.x &&
  ball.x <= paddle.x + paddle.width &&
  ball.y >= paddle.y &&
  ball.y <= paddle.y + paddle.height) {

  if(ball.x < paddle.x + paddle.width) {
    ball.x = paddle.x - ballRadius;
    directionX = -directionX;
  } else if(ball.x > paddle.x){
    ball.x = paddle.x + paddle.width + ballRadius;
    directionX = -directionX;
  }

// need to add if statement to shoot ball up if it gets stuck in body of paddle, may just shoot back up regardless.

}
}

if(ball.x + ballRadius > paddle.y && paddleAndBallCollision === false) {
  directionX = -directionX;
}

function drawBall(){
  ctx.beginPath();
  ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = '#617';
  ctx.fill();
  ctx.closePath();
}

requestAnimationFrame(function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
  draw();
  ballMovement();
  ballCollision();
  requestAnimationFrame(gameLoop);
});

$(document).on('keydown', function(e){
  //37 left, 39 right//
  if (e.keyCode === 37 && paddle.x > 0) {
    paddle.x -= 20;
  } else if (e.keyCode === 39 && paddle.x < canvas.width - paddle.width) {
    paddle.x += 20;
  } else if (e.keyCode === 38 || e.keyCode === 40){
    e.preventDefault();
  }
});

Block.prototype.draw = function() {
  ctx.fillRect(this.x, this.y, this.width, this.height);
};

// } || ballX < ballRadius){
//     directionX = -directionX;
//   }
//   if(ball > canvas.height - ballRadius || ballY < ballRadius){
//     directionY = -directionY;
// }

// function drawBlocks() {
//   for(i = 0; i < 8; i++){
//     for(j = 0; j < 4; j++) {
//     }  if (blocks.length < 32) {
//     this.blocks.push(new Block(2 + i * 100, 50 + j * 25, 96, 20));
//   } else {
//     return blocks;
//   }
// }}
<commit_msg>Add blocks to canvas and collision detection to blocks<commit_after>
var canvas = $('#canvas')[0];
var ctx = canvas.getContext('2d');
var ballRadius = 10;
var ballX = canvas.width/2;
var ballY = canvas.height - (ballRadius * 8);
var directionX = 6;
var directionY = 6;
var paddleWidth = 150;
var paddleHeight = 20;
var paddle = new Block((canvas.width - paddleWidth)/2, 450, 150, 20);
var blocks = [];
var ball = {x: ballX, y: ballY};

drawBlocks();

function draw(){
  drawBall();
  paddle.draw();
  blocks.forEach(function(block) {
    block.draw();
  });
}

function blockCollisionDetection() {
  blocks.forEach(function(block) {
    if(ball.x <= block.x + block.width &&
      ball.x + ballRadius >= block.x &&
      ball.y <= block.y + block.height &&
      ballRadius + ball.y >= block.y) {
        directionY = -directionY;
    }
  });
}

function ballCollision() {
  canvasEdgeCollision();
  paddleAndBallCollision();
  blockCollisionDetection();
}

function ballMovement() {
ballX += directionX;
ballY -= directionY;
ball.x = ballX;
ball.y = ballY;
}

function canvasEdgeCollision() {
if(ballX > canvas.width - ballRadius || ballX < ballRadius){
  directionX = -directionX;
}
if(ballY < ballRadius){
  directionY = -directionY;
  }
}

function paddleAndBallCollision() {
if(ball.x <= paddle.x + paddle.width &&
  ball.x + ballRadius >= paddle.x &&
  ball.y <= paddle.y + paddle.height &&
  ballRadius + ball.y >= paddle.y) {
    directionY = -directionY;
  }
if(ball.x >= paddle.x &&
  ball.x <= paddle.x + paddle.width &&
  ball.y >= paddle.y &&
  ball.y <= paddle.y + paddle.height) {

  if(ball.x < paddle.x + paddle.width) {
    ball.x = paddle.x - ballRadius;
    directionX = -directionX;
  } else if(ball.x > paddle.x){
    ball.x = paddle.x + paddle.width + ballRadius;
    directionX = -directionX;
  }

// need to add if statement to shoot ball up if it gets stuck in body of paddle, may just shoot back up regardless.

}
}

if(ball.x + ballRadius > paddle.y && paddleAndBallCollision === false) {
  directionX = -directionX;
}

function drawBall(){
  ctx.beginPath();
  ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2);
  ctx.fillStyle = '#617';
  ctx.fill();
  ctx.closePath();
}

requestAnimationFrame(function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  draw();
  ballMovement();
  ballCollision();
  requestAnimationFrame(gameLoop);
});

$(document).on('keydown', function(e){
  //37 left, 39 right//
  if (e.keyCode === 37 && paddle.x > 0) {
    paddle.x -= 20;
  } else if (e.keyCode === 39 && paddle.x < canvas.width - paddle.width) {
    paddle.x += 20;
  } else if (e.keyCode === 38 || e.keyCode === 40){
    e.preventDefault();
  }
});

Block.prototype.draw = function() {
  ctx.fillRect(this.x, this.y, this.width, this.height);
};

// } || ballX < ballRadius){
//     directionX = -directionX;
//   }
//   if(ball > canvas.height - ballRadius || ballY < ballRadius){
//     directionY = -directionY;
// }

function drawBlocks() {
  for(i = 0; i < 8; i++){
    for(j = 0; j < 4; j++) {
    this.blocks.push(new Block(2 + i * 100, 50 + j * 25, 96, 20));
    }
  }
}
<|endoftext|>


<commit_before>var _ = require('underscore');
var config = require('../config/game');
var scoring = require('../config/scoring');
var MobRepo = require('../config/mobs');
var WaveFactory = require('./wave_factory');

var Game = (function() {

	var onLastWaveEnemy;
	var _mobTypes = _.keys(MobRepo);

	var _waveInterval = config.waveInterval; // Wave trigger round mod

	function Game(player) {
		this.round = 1;
		this.waves = [];
		this.player = player;
		this.waveFactory = new WaveFactory();
	}

	Game.prototype.getRound = function() {
		return this.round;
	};

	Game.prototype.setupRound = function() {
		if (this.waves.length === 0 || this.round % _waveInterval === 0) {
			if (this.waves.length === 0) {
				this.player.waveCleared();
			}
			this.spawnEnemies();
		}
		this.round++;
	};

	Game.prototype.getEnemies = function() {
		var list = [];
		_.each(this.waves, function(enemyCollection){
			list.push(enemyCollection.list());
		});
		return _.flatten(list);
	};

	Game.prototype.spawnEnemies = function() {
		var wave = this.waveFactory.get(this.round);
		wave.onLastWaveEnemy(_.bind(onLastWaveEnemy, this));
		wave.onEnemyDeath(_.bind(this.player.handleKill, this.player));
		this.waves.push(wave);
	};

	// @deprecated
	Game.prototype.getEnemyAttackDamage = function() {
		var damage = 0;
		_.each(this.waves, function(collection){
			damage += collection.massAttack();
		});
		return damage;
	};

	/**
	 * Loops over the waves and collects information on enemy actions.
	 *
	 * Yields the player object to the enemies so that it can be inspected and/or attacked
	 * by the enemy objects.
	 *
	 * Stops processing if the player dies
	 *
	 * @param Player player
	 * @return Array
	 */
	Game.prototype.processEnemyActions = function(player){
		var waves, length, i, result;

		waves = this.waves;
		length = waves.length;
		result = [];
		for (i = 0; i <= length; i++){
			if (waves[i]){
				result.push.apply(result, waves[i].massAction(player));
			}
			if (player.isDead()){
				break;
			}
		}

		return result;
	};

	Game.prototype.getEnemyById = function(id) {
		var i, enemy, result;
		for (i = 0; i < this.waves.length; i++) {
			enemy = this.waves[i].byId(id);
			if (enemy) {
				result = {
					enemy : enemy,
					collection : this.waves[i]
				};
				break;
			}
		}
		return result;
	};

	Game.prototype.summary = function() {
		var summary = [];
		_.each(this.waves, function(collection){
			summary.push({
				wave : collection._id,
				enemies : collection.summary()
			});
		});
		return summary;
	};

	Game.prototype.recordGame = function(db, callback) {
		var resultsCollection, data;
		if (!db) {
			callback('No Mongo connection available.', this);
			return;
		}
		resultsCollection = db.collection('results');
		data = _.extend(
			{round: this.round},
			this.player.info(),
			{score: this.calculateScore()});
		resultsCollection.insert(data, _.bind(function(err) {
			callback(err, this);
		}, this));
	};

	Game.prototype.calculateScore = function() {
		return this.player.kills() * scoring.kill
			+ this.player.effectiveDamage() * scoring.damage
			+ this.round * scoring.round
			+ this.player.wavesCleared() * scoring.waveCleared;
	};

	/**
	 * Retrieve the (up to) top 10 scores.
	 *
	 * @param MongoClient db
	 * @param function callback
	 * @return void
	 */
	Game.topScoreList = function(db, callback) {
		if (!db) {
			callback('DB not available.');
			return;
		}
		db.collection('results').aggregate([
			{ $sort: {round: -1} },
			{ $group: { _id: "$name", round: { $first: "$round" } } },
			{ $sort: {round: -1}}, {$limit: 10}
		], function(err, result) {
			var results = [];
			if (err) {
				callback(err, []);
			}
			_.each(result, function(entry) {
				results.push({
					username: entry._id,
					round: entry.round
				});
			});
			callback(null, results);
		});
	};

	/**
	 * Listener for when the last enemy is removed from a wave's enemy collection.
	 *
	 * @access private
	 * @param EnemyCollection collection
	 * @return void
	 */
	onLastWaveEnemy = function(collection) {
		this.waves = _.reject(this.waves, function (wave) {
			return wave._id === collection._id;
		});
	};

	return Game;

}());

module.exports = Game;
<commit_msg>Lint.<commit_after>var _ = require('underscore');
var config = require('../config/game');
var scoring = require('../config/scoring');
var MobRepo = require('../config/mobs');
var WaveFactory = require('./wave_factory');

var Game = (function() {

	var onLastWaveEnemy;
	var _mobTypes = _.keys(MobRepo);

	var _waveInterval = config.waveInterval; // Wave trigger round mod

	function Game(player) {
		this.round = 1;
		this.waves = [];
		this.player = player;
		this.waveFactory = new WaveFactory();
	}

	Game.prototype.getRound = function() {
		return this.round;
	};

	Game.prototype.setupRound = function() {
		if (this.waves.length === 0 || this.round % _waveInterval === 0) {
			if (this.waves.length === 0) {
				this.player.waveCleared();
			}
			this.spawnEnemies();
		}
		this.round++;
	};

	Game.prototype.getEnemies = function() {
		var list = [];
		_.each(this.waves, function(enemyCollection){
			list.push(enemyCollection.list());
		});
		return _.flatten(list);
	};

	Game.prototype.spawnEnemies = function() {
		var wave = this.waveFactory.get(this.round);
		wave.onLastWaveEnemy(_.bind(onLastWaveEnemy, this));
		wave.onEnemyDeath(_.bind(this.player.handleKill, this.player));
		this.waves.push(wave);
	};

	// @deprecated
	Game.prototype.getEnemyAttackDamage = function() {
		var damage = 0;
		_.each(this.waves, function(collection){
			damage += collection.massAttack();
		});
		return damage;
	};

	/**
	 * Loops over the waves and collects information on enemy actions.
	 *
	 * Yields the player object to the enemies so that it can be inspected and/or attacked
	 * by the enemy objects.
	 *
	 * Stops processing if the player dies
	 *
	 * @param Player player
	 * @return Array
	 */
	Game.prototype.processEnemyActions = function(player){
		var waves, length, i, result;

		waves = this.waves;
		length = waves.length;
		result = [];
		for (i = 0; i <= length; i++){
			if (waves[i]){
				result.push.apply(result, waves[i].massAction(player));
			}
			if (player.isDead()){
				break;
			}
		}

		return result;
	};

	Game.prototype.getEnemyById = function(id) {
		var i, enemy, result;
		for (i = 0; i < this.waves.length; i++) {
			enemy = this.waves[i].byId(id);
			if (enemy) {
				result = {
					enemy : enemy,
					collection : this.waves[i]
				};
				break;
			}
		}
		return result;
	};

	Game.prototype.summary = function() {
		var summary = [];
		_.each(this.waves, function(collection){
			summary.push({
				wave : collection._id,
				enemies : collection.summary()
			});
		});
		return summary;
	};

	Game.prototype.recordGame = function(db, callback) {
		var resultsCollection, data;
		if (!db) {
			callback('No Mongo connection available.', this);
			return;
		}
		resultsCollection = db.collection('results');
		data = _.extend(
			{round: this.round},
			this.player.info(),
			{score: this.calculateScore()});
		resultsCollection.insert(data, _.bind(function(err) {
			callback(err, this);
		}, this));
	};

	Game.prototype.calculateScore = function() {
		return this.player.kills() * scoring.kill +
			this.player.effectiveDamage() * scoring.damage +
			this.round * scoring.round +
			this.player.wavesCleared() * scoring.waveCleared;
	};

	/**
	 * Retrieve the (up to) top 10 scores.
	 *
	 * @param MongoClient db
	 * @param function callback
	 * @return void
	 */
	Game.topScoreList = function(db, callback) {
		if (!db) {
			callback('DB not available.');
			return;
		}
		db.collection('results').aggregate([
			{ $sort: {round: -1} },
			{ $group: { _id: "$name", round: { $first: "$round" } } },
			{ $sort: {round: -1}}, {$limit: 10}
		], function(err, result) {
			var results = [];
			if (err) {
				callback(err, []);
			}
			_.each(result, function(entry) {
				results.push({
					username: entry._id,
					round: entry.round
				});
			});
			callback(null, results);
		});
	};

	/**
	 * Listener for when the last enemy is removed from a wave's enemy collection.
	 *
	 * @access private
	 * @param EnemyCollection collection
	 * @return void
	 */
	onLastWaveEnemy = function(collection) {
		this.waves = _.reject(this.waves, function (wave) {
			return wave._id === collection._id;
		});
	};

	return Game;

}());

module.exports = Game;
<|endoftext|>


<commit_before>describe( 'AppCtrl', function() {
  describe( 'isCurrentUrl', function() {
    var AppCtrl, $location, $scope;

    beforeEach( module('app'));

    beforeEach( inject( function( $controller, _$location_, $rootScope ) {
      $location = _$location_;
      $scope = $rootScope.$new();
      AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope });
    }));

    it( 'should pass a dummy test', inject( function() {
      expect( AppCtrl ).toBeTruthy();
    }));
  });
});<commit_msg>Fixed indentation<commit_after>describe( 'AppCtrl', function() {

    describe( 'isCurrentUrl', function() {
        var AppCtrl, $location, $scope;

        beforeEach( module('app'));

        beforeEach( inject( function( $controller, _$location_, $rootScope ) {
            $location = _$location_;
            $scope = $rootScope.$new();
            AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope });
        }));

        it( 'should pass a dummy test', inject( function() {
            expect( AppCtrl ).toBeTruthy();
        }));
    });

});<|endoftext|>