<commit_before>'use strict';

var frowShowRunning = false;
var frowTicketsOut = 0;
var frowTicketsDone = 0;

var checkIfAttribute = function(element, attribute, attributeIsClass) {
    if (!attribute || attributeIsClass) {
        attribute = (attribute) ? attribute : 'frow-hide';
        return (' ' + element.className + ' ').indexOf(' ' + attribute + ' ') > -1;
    } else if (attribute.indexOf('=') > -1) {
        attribute = attribute.split('=');
        return (element.hasAttribute(attribute[0])) && (element.getAttribute(attribute[0]) === attribute[1]);
    } else {
        return (element.hasAttribute(attribute) && (element.getAttribute(attribute) === ''));
    }
}

var findAnimateTime = function(times) {
    if (times.indexOf(',') > -1) {
        times = times.split(',');
        for (var i = 0; i < times.length; i++) {
            times[i] = Number(times[i].slice(0, -1));
        }
        times = Math.max.apply(null, times);
    } else {
        times = Number(times.slice(0, -1));
    }
    return times;
};

var alterAttribute = function(element, styles, add, attribute, attributeIsClass, lastOne) {
    var command = (add) ? 'add' : 'remove';

    if (attributeIsClass) {
        var alterAttributeDone = function() {
            element.removeEventListener('animationend', alterAttributeDone, false);
            if (add) {
                element.classList.add(attribute);
            }
            element.classList.remove(attribute + '-' + command);
            element.classList.remove(attribute + '-' + command + '-active');
            element.classList.remove('frow-animate');
            if (lastOne) {
                frowTicketsDone++;
                frowShowRunning = false;
            }
        };

        element.classList.add('frow-animate');
        element.classList.add(attribute + '-' + command);
        if (!add) {
            element.classList.remove(attribute);
        }
        setTimeout(function() {
            if ((styles.transitionDuration !== '0s') || (styles.animationDuration !== '0s')) {
                element.classList.add(attribute + '-' + command + '-active');
                var maxTransitionTime = findAnimateTime(styles.transitionDuration);
                var maxAnimationTime = findAnimateTime(styles.animationDuration);
                var maxTime = Math.ceil(Math.max(maxTransitionTime, maxAnimationTime)*1000);
                setTimeout(alterAttributeDone, maxTime);
                if (styles.animationDuration !== '0s') {
                    element.addEventListener('animationend', alterAttributeDone, false);
                }
            } else {
                alterAttributeDone();
            }
        }, 0);
    } else {
        // var setTheAttribute = function() {
        //     element.setAttribute(attribute[0], attribute[1]);
        // }
        if (add) {
            if (attribute.indexOf('=') > -1) {
                 attribute = attribute.split('=');
                 element.setAttribute(attribute[0], attribute[1]);
            } else {
                element.setAttribute(attribute, '');
            }
        } else {
            if (attribute.indexOf('=') > -1) {
                 attribute = attribute.split('=');
                 element.removeAttribute(attribute[0]);
            } else {
                element.removeAttribute(attribute);
            }
        }
        if (lastOne) {
            frowTicketsDone++;
            frowShowRunning = false;
        }
    }
};

var router = function(target, command, attribute) {
    if (target) {
        if (command) {
            if (typeof target === 'string') {
                var targetType = null;
                var attributeIsClass = null;
                var lastOne = false;
                if (target.charAt(0) === '#') {
                    targetType = 'id';
                    target = target.substring(1);
                    var element = document.getElementById(target);
                    if (element !== null) {
                        var styles = window.getComputedStyle(element, null);
                        if (command === 'show' || command === 'hide') {
                            if (!attribute) {
                                if (command === 'show') {
                                    alterAttribute(element, styles, false, 'frow-hide', true, true);
                                } else if (command === 'hide') {
                                    alterAttribute(element, styles, true, 'frow-hide', true, true);
                                }
                            } else {
                                console.log('frowShow: using \'show\' or \'hide\' command can not have an \'attribute\' parameter.');
                            }
                        } else if ((command === 'add') || (command === 'remove')) {
                            if (attribute) {
                                if (attribute.charAt(0) === '.') {
                                    attributeIsClass = true;
                                    attribute = attribute.substring(1);
                                }
                                if (command === 'add') {
                                    alterAttribute(element, styles, true, attribute, attributeIsClass, true);
                                } else if (command === 'remove') {
                                    alterAttribute(element, styles, false, attribute, attributeIsClass, true);
                                }
                            } else {
                                console.log('frowShow: using \'add\' or \'remove\' command must also have an \'attribute\' parameter.');
                            }
                        } else if (command === 'toggle') {
                            if (attribute && attribute.charAt(0) === '.') {
                                attributeIsClass = true;
                                attribute = attribute.substring(1);
                            } else if (!attribute) {
                                attributeIsClass = true;
                                attribute = 'frow-hide';
                            }
                            if (checkIfAttribute(element, attribute, attributeIsClass)) {
                                alterAttribute(element, styles, false, attribute, attributeIsClass, true);
                            } else {
                                alterAttribute(element, styles, true, attribute, attributeIsClass, true);
                            }
                        } else {
                            console.log('frowShow: \'command\' parameter is not the string \'show\', \'hide\', \'add\', \'remove\', or \'toggle\'.');
                        }
                    } else {
                        console.log('frowShow: no element of ' + targetType + ' \'' + target + '\' found on page.');
                    }
                } else {
                    var element = [];
                    if (target.charAt(0) === '.') {
                        targetType = 'class';
                        target = target.substring(1);
                        element = document.getElementsByClassName(target);
                    } else {
                        targetType = 'tag';
                        element = document.getElementsByTagName(target);
                    }
                    if (element.length > 0) {
                        if ((command === 'show') || (command === 'hide')) {
                            if (!attribute) {
                                if (command === 'show') {
                                    for (var i = 0; i < element.length; i++) {
                                        var styles = window.getComputedStyle(element[i], null);
                                        if (i === (element.length - 1) ) {
                                            lastOne = true;
                                        }
                                        alterAttribute(element[i], styles, false, 'frow-hide', true, lastOne);
                                    }
                                } else if (command === 'hide') {
                                    for (var i = 0; i < element.length; i++) {
                                        var styles = window.getComputedStyle(element[i], null);
                                        if (i === (element.length - 1) ) {
                                            lastOne = true;
                                        }
                                        alterAttribute(element[i], styles, true, 'frow-hide', true, lastOne);
                                    }
                                }
                            } else {
                                console.log('frowShow: using \'show\' or \'hide\' command can not have an \'attribute\' parameter.');
                            }
                        } else if ((command === 'add') || (command === 'remove')) {
                            if (attribute) {
                                if (attribute.charAt(0) === '.') {
                                    attributeIsClass = true;
                                    attribute = attribute.substring(1);
                                }
                                if (command === 'add') {
                                    for (var i = 0; i < element.length; i++) {
                                        var styles = window.getComputedStyle(element[i], null);
                                        if (i === (element.length - 1) ) {
                                            lastOne = true;
                                        }
                                        alterAttribute(element[i], styles, true, attribute, attributeIsClass, lastOne);
                                    }
                                } else if (command === 'remove') {
                                    for (var i = 0; i < element.length; i++) {
                                        var styles = window.getComputedStyle(element[i], null);
                                        if (i === (element.length - 1) ) {
                                            lastOne = true;
                                        }
                                        alterAttribute(element[i], styles, false, attribute, attributeIsClass, lastOne);
                                    }
                                }
                            } else {
                                console.log('frowShow: using \'add\' or \'remove\' command must also have an \'attribute\' parameter.');
                            }
                        } else if (command === 'toggle') {
                            if (attribute && attribute.charAt(0) === '.') {
                                attributeIsClass = true;
                                attribute = attribute.substring(1);
                            }
                            for (var i = 0; i < element.length; i++) {
                                var styles = window.getComputedStyle(element[i], null);
                                if (i === (element.length - 1) ) {
                                    lastOne = true;
                                }
                                if (checkIfAttribute(element[i], attribute, attributeIsClass)) {
                                    alterAttribute(element[i], styles, false, attribute, attributeIsClass, lastOne);
                                } else {
                                    alterAttribute(element[i], styles, true, attribute, attributeIsClass, lastOne);
                                }
                            }
                        } else {
                            console.log('frowShow: \'command\' parameter is not the string \'show\', \'hide\', \'add\', \'remove\', or \'toggle\'.');
                        }
                    } else {
                        console.log('frowShow: no element of ' + targetType + ' \'' + target + '\' found on page.');
                    }
                }
            } else {
                console.log('frowShow: \'target\' parameter is not a string type.');
            }
        } else {
            console.log('frowShow: missing \'command\' parameter.');
        }
    } else {
        console.log('frowShow: missing \'target\' parameter.');
    }
};

var frowShow = function(target, command, attribute, claimedTicket) {
    if (!claimedTicket) {
        frowTicketsOut++;
        claimedTicket = frowTicketsOut;
    }
    if (frowShowRunning && frowTicketsDone !== claimedTicket) {
        setTimeout(function () {
            frowShow(target, command, attribute, claimedTicket);
        }, 0);
    } else {
        frowShowRunning = true;
        router(target, command, attribute);
    }
}
<commit_msg>feat(frow.js): make queueing optional<commit_after>'use strict';

var frowShowRunning = false;
var frowTicketsOut = 0;
var frowTicketsDone = 0;

var frowShow = function(target, command, attribute, queue) {
    var queueMatters = false;

    var checkIfAttribute = function(element, attribute, attributeIsClass) {
        if (!attribute || attributeIsClass) {
            attribute = (attribute) ? attribute : 'frow-hide';
            return (' ' + element.className + ' ').indexOf(' ' + attribute + ' ') > -1;
        } else if (attribute.indexOf('=') > -1) {
            attribute = attribute.split('=');
            return (element.hasAttribute(attribute[0])) && (element.getAttribute(attribute[0]) === attribute[1]);
        } else {
            return (element.hasAttribute(attribute) && (element.getAttribute(attribute) === ''));
        }
    }

    var findAnimateTime = function(times) {
        if (times.indexOf(',') > -1) {
            times = times.split(',');
            for (var i = 0; i < times.length; i++) {
                times[i] = Number(times[i].slice(0, -1));
            }
            times = Math.max.apply(null, times);
        } else {
            times = Number(times.slice(0, -1));
        }
        return times;
    };

    var alterAttribute = function(element, styles, add, attribute, attributeIsClass, lastOne) {
        var command = (add) ? 'add' : 'remove';

        if (attributeIsClass) {
            var alterAttributeDone = function() {
                element.removeEventListener('animationend', alterAttributeDone, false);
                if (add) {
                    element.classList.add(attribute);
                }
                element.classList.remove(attribute + '-' + command);
                element.classList.remove(attribute + '-' + command + '-active');
                element.classList.remove('frow-animate');
                if (queueMatters && lastOne) {
                    frowTicketsDone++;
                    frowShowRunning = false;
                }
            };

            element.classList.add('frow-animate');
            element.classList.add(attribute + '-' + command);
            if (!add) {
                element.classList.remove(attribute);
            }
            setTimeout(function() {
                if ((styles.transitionDuration !== '0s') || (styles.animationDuration !== '0s')) {
                    element.classList.add(attribute + '-' + command + '-active');
                    var maxTransitionTime = findAnimateTime(styles.transitionDuration);
                    var maxAnimationTime = findAnimateTime(styles.animationDuration);
                    var maxTime = Math.ceil(Math.max(maxTransitionTime, maxAnimationTime)*1000);
                    setTimeout(alterAttributeDone, maxTime);
                    if (styles.animationDuration !== '0s') {
                        element.addEventListener('animationend', alterAttributeDone, false);
                    }
                } else {
                    alterAttributeDone();
                }
            }, 0);
        } else {
            // var setTheAttribute = function() {
            //     element.setAttribute(attribute[0], attribute[1]);
            // }
            if (add) {
                if (attribute.indexOf('=') > -1) {
                     attribute = attribute.split('=');
                     element.setAttribute(attribute[0], attribute[1]);
                } else {
                    element.setAttribute(attribute, '');
                }
            } else {
                if (attribute.indexOf('=') > -1) {
                     attribute = attribute.split('=');
                     element.removeAttribute(attribute[0]);
                } else {
                    element.removeAttribute(attribute);
                }
            }
            if (queueMatters && lastOne) {
                frowTicketsDone++;
                frowShowRunning = false;
            }
        }
    };

    var router = function(target, command, attribute) {
        if (target) {
            if (command) {
                if (typeof target === 'string') {
                    var targetType = null;
                    var attributeIsClass = null;
                    var lastOne = false;
                    if (target.charAt(0) === '#') {
                        targetType = 'id';
                        target = target.substring(1);
                        var element = document.getElementById(target);
                        if (element !== null) {
                            var styles = window.getComputedStyle(element, null);
                            if (command === 'show' || command === 'hide') {
                                if (!attribute) {
                                    if (command === 'show') {
                                        alterAttribute(element, styles, false, 'frow-hide', true, true);
                                    } else if (command === 'hide') {
                                        alterAttribute(element, styles, true, 'frow-hide', true, true);
                                    }
                                } else {
                                    console.log('frowShow: using \'show\' or \'hide\' command can not have an \'attribute\' parameter.');
                                }
                            } else if ((command === 'add') || (command === 'remove')) {
                                if (attribute) {
                                    if (attribute.charAt(0) === '.') {
                                        attributeIsClass = true;
                                        attribute = attribute.substring(1);
                                    } else if (attribute.charAt(0) === '#') {
                                        attribute = 'id=' + attribute.substring(1);
                                    }
                                    if (command === 'add') {
                                        alterAttribute(element, styles, true, attribute, attributeIsClass, true);
                                    } else if (command === 'remove') {
                                        alterAttribute(element, styles, false, attribute, attributeIsClass, true);
                                    }
                                } else {
                                    console.log('frowShow: using \'add\' or \'remove\' command must also have an \'attribute\' parameter.');
                                }
                            } else if (command === 'toggle') {
                                if (attribute && attribute.charAt(0) === '.') {
                                    attributeIsClass = true;
                                    attribute = attribute.substring(1);
                                } else if (attribute && attribute.charAt(0) === '#') {
                                    attribute = 'id=' + attribute.substring(1);
                                } else if (!attribute) {
                                    attributeIsClass = true;
                                    attribute = 'frow-hide';
                                }
                                if (checkIfAttribute(element, attribute, attributeIsClass)) {
                                    alterAttribute(element, styles, false, attribute, attributeIsClass, true);
                                } else {
                                    alterAttribute(element, styles, true, attribute, attributeIsClass, true);
                                }
                            } else {
                                console.log('frowShow: \'command\' parameter is not the string \'show\', \'hide\', \'add\', \'remove\', or \'toggle\'.');
                            }
                        } else {
                            console.log('frowShow: no element of ' + targetType + ' \'' + target + '\' found on page.');
                        }
                    } else {
                        var element = [];
                        if (target.charAt(0) === '.') {
                            targetType = 'class';
                            target = target.substring(1);
                            element = document.getElementsByClassName(target);
                        } else {
                            targetType = 'tag';
                            element = document.getElementsByTagName(target);
                        }
                        if (element.length > 0) {
                            if ((command === 'show') || (command === 'hide')) {
                                if (!attribute) {
                                    if (command === 'show') {
                                        for (var i = 0; i < element.length; i++) {
                                            var styles = window.getComputedStyle(element[i], null);
                                            if (i === (element.length - 1) ) {
                                                lastOne = true;
                                            }
                                            alterAttribute(element[i], styles, false, 'frow-hide', true, lastOne);
                                        }
                                    } else if (command === 'hide') {
                                        for (var i = 0; i < element.length; i++) {
                                            var styles = window.getComputedStyle(element[i], null);
                                            if (i === (element.length - 1) ) {
                                                lastOne = true;
                                            }
                                            alterAttribute(element[i], styles, true, 'frow-hide', true, lastOne);
                                        }
                                    }
                                } else {
                                    console.log('frowShow: using \'show\' or \'hide\' command can not have an \'attribute\' parameter.');
                                }
                            } else if ((command === 'add') || (command === 'remove')) {
                                if (attribute) {
                                    if (attribute.charAt(0) === '.') {
                                        attributeIsClass = true;
                                        attribute = attribute.substring(1);
                                    } else if (attribute.charAt(0) === '#') {
                                        attribute = 'id=' + attribute.substring(1);
                                    }
                                    if (command === 'add') {
                                        for (var i = 0; i < element.length; i++) {
                                            var styles = window.getComputedStyle(element[i], null);
                                            if (i === (element.length - 1) ) {
                                                lastOne = true;
                                            }
                                            alterAttribute(element[i], styles, true, attribute, attributeIsClass, lastOne);
                                        }
                                    } else if (command === 'remove') {
                                        for (var i = 0; i < element.length; i++) {
                                            var styles = window.getComputedStyle(element[i], null);
                                            if (i === (element.length - 1) ) {
                                                lastOne = true;
                                            }
                                            alterAttribute(element[i], styles, false, attribute, attributeIsClass, lastOne);
                                        }
                                    }
                                } else {
                                    console.log('frowShow: using \'add\' or \'remove\' command must also have an \'attribute\' parameter.');
                                }
                            } else if (command === 'toggle') {
                                if (attribute && attribute.charAt(0) === '.') {
                                    attributeIsClass = true;
                                    attribute = attribute.substring(1);
                                } else if (attribute && attribute.charAt(0) === '#') {
                                    attribute = 'id=' + attribute.substring(1);
                                }
                                for (var i = 0; i < element.length; i++) {
                                    var styles = window.getComputedStyle(element[i], null);
                                    if (i === (element.length - 1) ) {
                                        lastOne = true;
                                    }
                                    if (checkIfAttribute(element[i], attribute, attributeIsClass)) {
                                        alterAttribute(element[i], styles, false, attribute, attributeIsClass, lastOne);
                                    } else {
                                        alterAttribute(element[i], styles, true, attribute, attributeIsClass, lastOne);
                                    }
                                }
                            } else {
                                console.log('frowShow: \'command\' parameter is not the string \'show\', \'hide\', \'add\', \'remove\', or \'toggle\'.');
                            }
                        } else {
                            console.log('frowShow: no element of ' + targetType + ' \'' + target + '\' found on page.');
                        }
                    }
                } else {
                    console.log('frowShow: \'target\' parameter is not a string type.');
                }
            } else {
                console.log('frowShow: missing \'command\' parameter.');
            }
        } else {
            console.log('frowShow: missing \'target\' parameter.');
        }
    };

    var queueControl = function(target, command, attribute, claimedTicket) {
        if (!claimedTicket) {
            claimedTicket = frowTicketsOut++;
        }
        if (frowShowRunning && frowTicketsDone !== claimedTicket) {
            setTimeout(function () {
                queueControl(target, command, attribute, claimedTicket);
            }, 0);
        } else {
            frowShowRunning = true;
            router(target, command, attribute);
        }
    };

    if (queue || attribute === true) {
        queueMatters = true;
        if (attribute === true) {
            queueControl(target, command);
        } else {
            if (typeof queue === 'boolean') {
                queueControl(target, command, attribute);
            } else {
                console.log('frowShow: \'queue\' parameter is not a boolean');
            }
        }
    } else {
        router(target, command, attribute);
    }
};
<|endoftext|>


<commit_before>var Game = {
	currency:  10,

	count: undefined,
	roster: undefined,
	market: undefined,
	cpsDisplay: undefined,

	handle: undefined,

	workers: [],
	companies: [],

	init: function(_workers, _companies) {
		var self = this;

		this.count = $('#currency-display');
		this.roster = $('#roster-container');
		this.market = $('#market-container');
		this.cpsDisplay = $('#cps-display');

		$.each(_workers, function(index, _worker) {
			var newWorker = Worker(_worker).init();
			self.workers.push(newWorker);
		});

		$.each(_companies, function(index, _company) {
			var newCompany = Company(_company).init();
			self.companies.push(newCompany);
		});

		this.handle = window.setInterval(function() {
			self._tick();
		}, 10);
	},

	_tick: function() {
		$.each(this.companies, function(index, company) {
			company.produce();
			company.check();
		});

		$.each(this.workers, function(index, worker) {
			worker.produce();
			worker.check();
		});

		this.count.text(this.currency.toFixed(2));
	},

	cps: function() {
		var cps = 0;

		$.each(this.companies, function(index, company) {
			cps += company.production * company.quantity;
			console.log(cps);
		});

		$.each(this.workers, function(index, worker) {
			cps += worker.production * worker.quantity;
			console.log(cps);
		});

		this.cpsDisplay.text(cps);
	}

};

var Company = function(options) {
	return $.extend({
		quantity: 0,
		increase: 1.15,

		button: undefined,

		produce: function() {
			Game.currency += this.quantity * this.production / 100;
		},

		check: function() {
			this.button.toggleClass('disabled', this.cost > Game.currency);
		},

		buy: function() {
			if(this.cost <= Game.currency){
				Game.currency -= this.cost;

				this.quantity++;
				this.cost = Math.ceil(this.cost * this.increase);
				this.button.text(this.name + ' - ' + this.cost);

				Game.cps();
			};
		},

		init: function() {
			var self = this;
			var row = undefined;

			this.row = $("<div/>")
			.addClass("row")

			Game.market.append(this.row);

			this.button = $("<div/>")
			.addClass("waves-effect waves-light btn-large")
			.text(this.name + " - " + this.cost)
			.click(function(){
				self.buy();
			});

			this.row.append(this.button);

			this.check();

			return this;
		}

	}, options);
};

var Worker = function(options) {
	return $.extend({
		quantity: 0,
		increase: 1.11,

		button: undefined,

		produce: function() {
			Game.currency += this.quantity * this.production / 100;
		},

		check: function() {
			this.button.toggleClass('disabled', this.cost > Game.currency);
		},

		buy: function() {
			if(this.cost <= Game.currency){
				Game.currency -= this.cost;

				this.quantity++;
				this.cost = Math.ceil(this.cost * this.increase);
				this.button.text(this.name + ' - ' + this.cost);
				console.log('hi');
				Game.cps();
			};
		},

		init: function() {
			var self = this;
			var row = undefined;

			this.row = $("<div/>")
			.addClass("row")

			Game.roster.append(this.row);

			this.button = $("<div/>")
			.addClass("waves-effect waves-light btn-large")
			.text(this.name + " - " + this.cost)
			.click(function(){
				self.buy();
			});

			this.row.append(this.button);

			this.check();

			return this;
		}

	}, options);
};

_companies = [
{
	name: "Small company",
	cost: 10,
	production: 1
},
{
	name: "Medium company",
	cost: 20,
	production: 3
},
{
	name: "Big company",
	cost: 50,
	production: 5
}
];

_workers = [
{
	name: "Junior employee",
	cost: 10,
	production: 1
},
{
	name: "Senior employee",
	cost: 20,
	production: 3
},
{
	name: "Master & Commander",
	cost: 50,
	production: 5
}
];

Game.init(_workers, _companies);

// (function refreshUI() {
// 	setTimeout(refreshUI, 10);
// })();<commit_msg>Use .attr() instead of .addClass()<commit_after>var Game = {
	currency:  10,

	count: undefined,
	roster: undefined,
	market: undefined,
	cpsDisplay: undefined,

	handle: undefined,

	workers: [],
	companies: [],

	init: function(_workers, _companies) {
		var self = this;

		this.count = $('#currency-display');
		this.roster = $('#roster-container');
		this.market = $('#market-container');
		this.cpsDisplay = $('#cps-display');

		$.each(_workers, function(index, _worker) {
			var newWorker = Worker(_worker).init();
			self.workers.push(newWorker);
		});

		$.each(_companies, function(index, _company) {
			var newCompany = Company(_company).init();
			self.companies.push(newCompany);
		});

		this.handle = window.setInterval(function() {
			self._tick();
		}, 10);
	},

	_tick: function() {
		$.each(this.companies, function(index, company) {
			company.produce();
			company.check();
		});

		$.each(this.workers, function(index, worker) {
			worker.produce();
			worker.check();
		});

		this.count.text(this.currency.toFixed(2));
	},

	cps: function() {
		var cps = 0;

		$.each(this.companies, function(index, company) {
			cps += company.production * company.quantity;
			console.log(cps);
		});

		$.each(this.workers, function(index, worker) {
			cps += worker.production * worker.quantity;
			console.log(cps);
		});

		this.cpsDisplay.text(cps);
	}

};

var Company = function(options) {
	return $.extend({
		quantity: 0,
		increase: 1.15,

		button: undefined,

		produce: function() {
			Game.currency += this.quantity * this.production / 100;
		},

		check: function() {
			this.button.toggleClass('disabled', this.cost > Game.currency);
		},

		buy: function() {
			if(this.cost <= Game.currency){
				Game.currency -= this.cost;

				this.quantity++;
				this.cost = Math.ceil(this.cost * this.increase);
				this.button.text(this.name + ' - ' + this.cost);

				Game.cps();
			};
		},

		init: function() {
			var self = this;
			var row = undefined;

			this.row = $("<div/>")
			.addClass("row")

			Game.market.append(this.row);

			this.button = $("<div/>")
			.attr('class', 'waves-effect waves-light btn-large')
			.text(this.name + " - " + this.cost)
			.click(function(){
				self.buy();
			});

			this.row.append(this.button);

			this.check();

			return this;
		}

	}, options);
};

var Worker = function(options) {
	return $.extend({
		quantity: 0,
		increase: 1.11,

		button: undefined,

		produce: function() {
			Game.currency += this.quantity * this.production / 100;
		},

		check: function() {
			this.button.toggleClass('disabled', this.cost > Game.currency);
		},

		buy: function() {
			if(this.cost <= Game.currency){
				Game.currency -= this.cost;

				this.quantity++;
				this.cost = Math.ceil(this.cost * this.increase);
				this.button.text(this.name + ' - ' + this.cost);
				console.log('hi');
				Game.cps();
			};
		},

		init: function() {
			var self = this;
			var row = undefined;

			this.row = $("<div/>")
			.addClass("row")

			Game.roster.append(this.row);

			this.button = $("<div/>")
			.attr('class', 'waves-effect waves-light btn-large')
			.text(this.name + " - " + this.cost)
			.click(function() {
				self.buy();
			});

			this.row.append(this.button);

			this.check();

			return this;
		}

	}, options);
};

_companies = [
{
	name: "Small company",
	cost: 10,
	production: 1
},
{
	name: "Medium company",
	cost: 20,
	production: 3
},
{
	name: "Big company",
	cost: 50,
	production: 5
}
];

_workers = [
{
	name: "Junior employee",
	cost: 10,
	production: 1
},
{
	name: "Senior employee",
	cost: 20,
	production: 3
},
{
	name: "Master & Commander",
	cost: 50,
	production: 5
}
];

Game.init(_workers, _companies);

// (function refreshUI() {
// 	setTimeout(refreshUI, 10);
// })();<|endoftext|>


<commit_before>window.answer = parseInt(Math.random()*100, 10)

$(document).on('ready', begin)

function begin() {
  var range = $('.range')
  loopForTimes( 100, function(i) {
    range.append($('

'))
  })
}

$(document).on('click', '.dot', function() {
  if($('.range.game-ended, .range.guessing').length > 0) return
  number = parseInt($(this).data('number'), 10)
  guess(number, 'you')
})

function hubotGuess () {
  $('.range').addClass('guessing')
  setTimeout(function() {
    number = parseInt( $('.dot').eq(parseInt((Math.random()*100, 10)%($('.dot').length - 1)) + 1).data('number'), 10)
    guess(number, 'bot')
    $('.range').removeClass('guessing')
  }, 1000)
}

function guess (number, role) {
  write(role + ' guessed ' + number)
  if(number == window.answer) {
    $('.dot[data-number='+ window.answer + ']').addClass('boom')
    write('boom!!! the answer is ' + window.answer + ', ' + role + ' lost!')
    $('.range').addClass('game-ended')
  } else if (number < window.answer) {
    $('.dot').filter(function(_, e) {
      return parseInt($(e).data('number') - 1, 10) < number
    }).remove()
    if($('.dot').length == 1) guess($('.dot').data('number'), (role == 'bot' ? 'you' : 'bot'))
    logRange()
  } else {
    $('.dot').filter(function(_,e) {
      return parseInt($(e).data('number') + 1, 10) > number
    }).remove()
    if($('.dot').length == 1) guess($('.dot').data('number'), (role == 'bot' ? 'you' : 'bot'))
    logRange()
  }
  if( role != 'bot' && number != window.answer ) {
    hubotGuess()
  }

}

function logRange() {
  write($('.dot:first').data('number') + ' to ' + $('.dot:last').data('number'))
}

function write(text) {
  $('.range').after('
' + text + '
')
}

// Because I don't like ot write for()
function loopForTimes( times, callback ) {
  for( var i=0; i < times; i++ ){
    callback(i)
  }
}
<commit_msg>Change the 'if' condition to close correctly.<commit_after>window.answer = parseInt(Math.random()*100, 10)

$(document).on('ready', begin)

function begin() {
  var range = $('.range')
  loopForTimes( 100, function(i) {
    range.append($('

'))
  })
}

$(document).on('click', '.dot', function() {
  if($('.range.game-ended, .range.guessing').length > 0) return
  number = parseInt($(this).data('number'), 10)
  guess(number, 'you')
})

function hubotGuess () {
  $('.range').addClass('guessing')
  setTimeout(function() {
    number = parseInt( $('.dot').eq(parseInt((Math.random()*100, 10)%($('.dot').length - 1)) + 1).data('number'), 10)
    guess(number, 'bot')
    $('.range').removeClass('guessing')
  }, 1000)
}

function guess (number, role) {
  write(role + ' guessed ' + number)
  if(number == window.answer) {
    $('.dot[data-number='+ window.answer + ']').addClass('boom')
    write('boom!!! the answer is ' + window.answer + ', ' + role + ' lost!')
    $('.range').addClass('game-ended')
  } else if (number < window.answer) {
    $('.dot').filter(function(_, e) {
      return parseInt($(e).data('number') - 1, 10) < number
    }).remove()
	logRange()
    if($('.dot').length == 1) guess($('.dot').data('number'), (role == 'bot' ? 'you' : 'bot'))
  } else {
    $('.dot').filter(function(_,e) {
      return parseInt($(e).data('number') + 1, 10) > number
    }).remove()
	logRange()
    if($('.dot').length == 1) guess($('.dot').data('number'), (role == 'bot' ? 'you' : 'bot'))
  }
  if( role != 'bot' && number != window.answer && $('.dot').length != 1) {
    hubotGuess()
  }

}

function logRange() {
  write($('.dot:first').data('number') + ' to ' + $('.dot:last').data('number'))
}

function write(text) {
  $('.range').after('
' + text + '
')
}

// Because I don't like ot write for()
function loopForTimes( times, callback ) {
  for( var i=0; i < times; i++ ){
    callback(i)
  }
}
<|endoftext|>


<commit_before>var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

// create a Matter.js engine
var engine = Engine.create({
  render: {
    element: document.body,
    canvas: document.getElementById("playingField")
  }
});

engine.render.options.wireframes = true;
engine.render.options.background = "#007500";
engine.render.canvas.width = 1920;
engine.render.canvas.height = 1080;
engine.world.gravity.y = 0;

// CATEGORIES:
var CAT_BALL = 1;
var CAT_PLAYER = 2;
var CAT_RESTRICT_BALL = 4;

// init game field
World.add(engine.world, [
  Bodies.rectangle(1920/2, 10, 1920, 20, { isStatic: true }),
  Bodies.rectangle(1920/2, 1070, 1920, 20, { isStatic: true }),
  Bodies.rectangle(10, 1080/2, 20, 1080, { isStatic: true }),
  Bodies.rectangle(1910, 1080/2, 20, 1080, { isStatic: true }),
  Bodies.rectangle(1920/2, 50, 1920, 100, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1920/2, 1030, 1920, 100, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(50, 1080/2, 100, 1080, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1870, 1080/2, 100, 1080, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  })
]);

var ball = Bodies.circle(700,500,15,{
  restitution: 0.4,
  intertia: Number.POSITIVE_INFINITY,
  collisionFilter: {
    category: CAT_BALL,
    mask: CAT_PLAYER | CAT_RESTRICT_BALL
  },
  render: {
    fillStyle: "white",
    strokeStyle: "black",
    lineWidth: 4
  }
});

var circle = Bodies.circle(450,300,20,{
  restitution: 0.4,
  mass: 10,
  frictionAir: 0.1,
  intertia: Number.POSITIVE_INFINITY,
  render: {
    fillStyle: "red",
    strokeStyle: "black",
    lineWidth: 4
  },
  collisionFilter: {
    category: CAT_PLAYER,
    mask: CAT_BALL | CAT_PLAYER
  }
});

var circle2 = Bodies.circle(500,250,20,{
  restitution: 0.4,
  mass: 10,
  frictionAir: 0.1,
  intertia: Number.POSITIVE_INFINITY,
  render: {
    fillStyle: "blue",
    strokeStyle: "black",
    lineWidth: 4
  },
  collisionFilter: {
    category: CAT_PLAYER,
    mask: CAT_BALL | CAT_PLAYER
  }
});

// add all of the bodies to the world
World.add(engine.world, [circle, circle2, ball]);

// run the engine
Engine.run(engine);

function update() {
  var gamepads = navigator.getGamepads();
  var pad = gamepads[0]
  if (pad !== undefined) {
    var x = pad.axes[0];
    var y = pad.axes[1];
    var vect = Matter.Vector.create(x,y);
    if (Matter.Vector.magnitude(vect) > 0.1) {
      Matter.Body.applyForce(circle, circle.position, Matter.Vector.mult(vect,0.01));
    }
    if (pad.buttons[0].pressed) {
      circle.render.strokeStyle = "white";
    }
    else {
      circle.render.strokeStyle = "black";
    }
  }
  requestAnimationFrame(update);
}

requestAnimationFrame(update);
<commit_msg>added poles<commit_after>var Engine = Matter.Engine,
    World = Matter.World,
    Bodies = Matter.Bodies;

// create a Matter.js engine
var engine = Engine.create({
  render: {
    element: document.body,
    canvas: document.getElementById("playingField")
  }
});

engine.render.options.wireframes = true;
engine.render.options.background = "#007500";
engine.render.canvas.width = 1920;
engine.render.canvas.height = 1080;
engine.world.gravity.y = 0;

// CATEGORIES:
var CAT_BALL = 1;
var CAT_PLAYER = 2;
var CAT_RESTRICT_BALL = 4;

// init game field
World.add(engine.world, [
  Bodies.rectangle(1920/2, 10, 1920, 20, { isStatic: true }),
  Bodies.rectangle(1920/2, 1070, 1920, 20, { isStatic: true }),
  Bodies.rectangle(10, 1080/2, 20, 1080, { isStatic: true }),
  Bodies.rectangle(1910, 1080/2, 20, 1080, { isStatic: true }),
  Bodies.rectangle(1920/2, 50, 1920, 100, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1920/2, 1030, 1920, 100, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(25, 1080/2, 50, 1080, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1895, 1080/2, 50, 1080, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(60, 1080/4, 120, 1080/3, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(60, 1080-1080/4, 120, 1080/3, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1860, 1080/4, 120, 1080/3, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.rectangle(1860, 1080-1080/4, 120, 1080/3, {
    isStatic: true,
    collisionFilter: {
      category: CAT_RESTRICT_BALL,
      mask: CAT_BALL
    },
    render: {
      visible: engine.render.options.wireframes
    }
  }),
  Bodies.circle(120,450,10, {
    isStatic: true,
    collisionFilter: {
      category: CAT_PLAYER,
      mask: CAT_BALL | CAT_PLAYER
    }
  }),
  Bodies.circle(120,630,10, {
    isStatic: true,
    collisionFilter: {
      category: CAT_PLAYER,
      mask: CAT_BALL | CAT_PLAYER
    }
  }),
  Bodies.circle(1800,450,10, {
    isStatic: true,
    collisionFilter: {
      category: CAT_PLAYER,
      mask: CAT_BALL | CAT_PLAYER
    }
  }),
  Bodies.circle(1800,630,10, {
    isStatic: true,
    collisionFilter: {
      category: CAT_PLAYER,
      mask: CAT_BALL | CAT_PLAYER
    }
  })
]);

var ball = Bodies.circle(700,500,15,{
  restitution: 0.4,
  intertia: Number.POSITIVE_INFINITY,
  collisionFilter: {
    category: CAT_BALL,
    mask: CAT_PLAYER | CAT_RESTRICT_BALL
  },
  render: {
    fillStyle: "white",
    strokeStyle: "black",
    lineWidth: 4
  }
});

var circle = Bodies.circle(450,300,20,{
  restitution: 0.4,
  mass: 10,
  frictionAir: 0.1,
  intertia: Number.POSITIVE_INFINITY,
  render: {
    fillStyle: "red",
    strokeStyle: "black",
    lineWidth: 4
  },
  collisionFilter: {
    category: CAT_PLAYER,
    mask: CAT_BALL | CAT_PLAYER
  }
});

var circle2 = Bodies.circle(500,250,20,{
  restitution: 0.4,
  mass: 10,
  frictionAir: 0.1,
  intertia: Number.POSITIVE_INFINITY,
  render: {
    fillStyle: "blue",
    strokeStyle: "black",
    lineWidth: 4
  },
  collisionFilter: {
    category: CAT_PLAYER,
    mask: CAT_BALL | CAT_PLAYER
  }
});

// add all of the bodies to the world
World.add(engine.world, [circle, circle2, ball]);

// run the engine
Engine.run(engine);

function update() {
  var gamepads = navigator.getGamepads();
  var pad = gamepads[0]
  if (pad !== undefined) {
    var x = pad.axes[0];
    var y = pad.axes[1];
    var vect = Matter.Vector.create(x,y);
    if (Matter.Vector.magnitude(vect) > 0.1) {
      Matter.Body.applyForce(circle, circle.position, Matter.Vector.mult(vect,0.01));
    }
    if (pad.buttons[0].pressed) {
      circle.render.strokeStyle = "white";
    }
    else {
      circle.render.strokeStyle = "black";
    }
  }
  requestAnimationFrame(update);
}

requestAnimationFrame(update);
<|endoftext|>


<commit_before>(function() {

'use strict';

var game,
    planetCollisionGroup,
    playerCollisionGroup,
    projectileCollisionGroup,
    controls,
    background,
    trails,
    trailTexture,
    trailImage,
    planets,
    currentPlanet,
    players,
    projectiles,
    gravityDirection;

var colours = {
    red:    0xcc6666,
    orange: 0xde935f,
    yellow: 0xf0c674,
    green:  0xb5bd68,
    aqua:   0x8abeb7,
    blue:   0x81a2be,
    purple: 0xb294bb,
    brown:  0xa3685a,
}

window.startGame = function() {
    game = new Phaser.Game(
        1820, 1024,
        Phaser.AUTO
    );

    game.state.add('main', mainState);
    game.state.start('main');
};

var mainState = {
    preload: function() {
        game.load.image('background', 'assets/background.png');
        game.load.image('trail',      'assets/trail.png');
        game.load.image('player',     'assets/player.png');
        game.load.image('planet',     'assets/planet.png');
        game.load.image('projectile', 'assets/projectile.png');
    },

    create: function() {
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.scale.setScreenSize(true);

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

        trailImage = game.make.image(0, 0, 'trail');
        trailImage.anchor.set(0.5);

        game.physics.startSystem(Phaser.Physics.P2JS);

        playerCollisionGroup     = game.physics.p2.createCollisionGroup();
        planetCollisionGroup     = game.physics.p2.createCollisionGroup();
        projectileCollisionGroup = game.physics.p2.createCollisionGroup();

        // Make things collide with the bounds.
        // game.physics.p2.updateBoundsCollisionGroup();

        background = game.add.tileSprite(0, 0, 1820, 1024, 'background');

        trails      = game.add.group();
        players     = game.add.group();
        planets     = game.add.group();
        projectiles = game.add.group();

        addPlayer(game.world.centerX, game.world.centerY);

        for (var i = 0; i < 11; i++) {
            var x = game.rnd.integerInRange(0, game.world.width);
            var y = game.rnd.integerInRange(0, game.world.height);
            while (Math.abs(game.world.centerX - x) < 300 && Math.abs(game.world.centerY - y) < 300) {
                x = game.rnd.integerInRange(0, game.world.width);
                y = game.rnd.integerInRange(0, game.world.height);
            }

            addPlanet(x, y, i === 0);
        }
    },

    update: function() {
        players.forEachAlive(movePlayer, this);
        planets.forEachAlive(movePlanet, this);

        players.forEachAlive(maybeFire, this);

        if (players.countLiving() === 1) {
            lerpWorldCenterTowardsPlayer(players.getFirstAlive());
        } else {
            lerpWorldCenterTowardsCurrentPlanet();
        }

        players.forEachAlive(maybeWrap, this);
        planets.forEachAlive(maybeWrap, this);
        projectiles.forEachAlive(maybeWrap, this);
    },

    shutdown: function() {
        // FIXME: Tidy up and reset everything!
    },
}

function lerpWorldCenterTowardsCurrentPlanet() {
    lerpWorldCenterTowardsXY(currentPlanet.body.x, currentPlanet.body.y, 50);
}

function lerpWorldCenterTowardsPlayer(player) {
    lerpWorldCenterTowardsXY(player.body.x, player.body.y, 50);
}

function lerpWorldCenterTowardsXY(targetX, targetY, lerpFactor) {
    var x = (game.world.centerX - targetX) / lerpFactor;
    var y = (game.world.centerY - targetY) / lerpFactor;

    background.tilePosition.x += x;
    background.tilePosition.y += y;

    function lerp(obj) {
        obj.body.x += x;
        obj.body.y += y;
    }

    players.forEachAlive(lerp, this);
    planets.forEachAlive(lerp, this);
    projectiles.forEachAlive(lerp, this);
}

function addPlanet(x, y, isCurrent) {
    var planet = planets.create(x, y, 'planet');
    game.physics.p2.enable(planet);

    planet.anchor.set(0.5);
    planet.tint = colours.aqua;

    planet.body.velocity.x = game.rnd.integerInRange(-100, 100);
    planet.body.velocity.y = game.rnd.integerInRange(-100, 100);

    planet.body.rotateRight(game.rnd.integerInRange(-20, 20));

    planet.body.mass    = 1000;
    planet.body.damping = 0;
    planet.body.angularDamping = 0;

    planet.body.setCollisionGroup(planetCollisionGroup);
    planet.body.collides(playerCollisionGroup);
    planet.body.collides(projectileCollisionGroup);

    if (isCurrent) {
        setCurrentPlanet(planet);
    }
}

function setCurrentPlanet(planet, gravityDirectionToSet) {
    if (gravityDirectionToSet === undefined) {
        gravityDirectionToSet = 1;
    }

    if (currentPlanet !== undefined) {
        currentPlanet.tint = colours.aqua;
        currentPlanet.body.mass = 100;
    }

    if (gravityDirectionToSet === 1) {
        planet.tint = colours.green;
    } else {
        planet.tint = colours.purple;
    }

    planet.body.mass = 1000000;

    gravityDirection = gravityDirectionToSet;

    currentPlanet = planet;
}

function addPlayer(x, y) {
    var player = players.create(x, y, 'player');
    game.physics.p2.enable(player);

    player.anchor.set(0.5);
    player.body.rotation = Math.PI * 3 / 4;

    player.body.damping = 0;
    player.body.angularDamping = 0.99;

    player.body.setCollisionGroup(playerCollisionGroup);
    player.body.collides(playerCollisionGroup);
    player.body.collides(planetCollisionGroup);

    player.body.onBeginContact.add(function(body) {
        playerHit(player, body);
    }, this);

    player.canFire = true;

    // FIXME: This should display the actual trajectory of the player, not their movement in camera space.
    player.trailTexture = game.add.renderTexture(game.world.width, game.world.height, 'trailTexture');

    player.trail = trails.create(game.world.centerX, game.world.centerY, player.trailTexture);
    player.trail.anchor.set(0.5);

    player.trailTimer = game.time.create(false);

    player.trailTimer.loop(Phaser.Timer.SECOND / 4, function() {
        addToTrail(player);
    }, this);

    player.trailTimer.start();
}

function playerHit(player, body) {
    // FIXME: This is if they hit a wall.
    if (body === null) {
        return;
    }

    player.trailTimer.destroy();
    player.kill();

    if (body.sprite.key === 'player') {
        body.sprite.trailTimer.destroy();
        body.kill();
    }
}

function movePlayer(player) {
    var sign = 0;
    if (controls.left.isDown) {
        sign = -1;
    } else if (controls.right.isDown) {
        sign = 1;
    }

    player.body.angularForce += sign * 30;

    move(player, 5, false);
}

function movePlanet(planet) {
    if (planet === currentPlanet) {
        return;
    }

    move(planet, 1, true);
}

function move(obj, forceCoefficient, shouldSpin) {
    accelerateToObject(obj, currentPlanet, forceCoefficient, shouldSpin);
}

function accelerateToObject(obj, target, forceCoefficient, shouldSpin) {
    // These are axis aligned squares!
    var objTopLeftX     = obj.x - obj.width / 2;
    var objTopLeftY     = obj.y + obj.height / 2;

    var objTopRightX    = obj.x + obj.width / 2;
    var objTopRightY    = obj.y + obj.height / 2;

    var objBottomLeftX  = obj.x - obj.width / 2;
    var objBottomLeftY  = obj.y - obj.height / 2;

    var objBottomRightX = obj.x + obj.width / 2;
    var objBottomRightY = obj.y - obj.height / 2;

    var averageObjX = (objTopLeftX + objTopRightX + objBottomLeftX + objBottomRightX) / 4;
    var averageObjY = (objTopLeftY + objTopRightY + objBottomLeftY + objBottomRightY) / 4;

    var targetTopLeftX     = target.x - target.width / 2;
    var targetTopLeftY     = target.y + target.height / 2;

    var targetTopRightX    = target.x + target.width / 2;
    var targetTopRightY    = target.y + target.height / 2;

    var targetBottomLeftX  = target.x - target.width / 2;
    var targetBottomLeftY  = target.y - target.height / 2;

    var targetBottomRightX = target.x + target.width / 2;
    var targetBottomRightY = target.y - target.height / 2;

    var averageTargetX = (targetTopLeftX + targetTopRightX + targetBottomLeftX + targetBottomRightX) / 4;
    var averageTargetY = (targetTopLeftY + targetTopRightY + targetBottomLeftY + targetBottomRightY) / 4;

    var directX = averageTargetX - averageObjX;
    var directY = averageTargetY - averageObjY;

    var indirectX = directX + game.width;
    var indirectY = directY + game.height;

    var x;
    if (Math.abs(directX) < Math.abs(indirectX)) {
        x = directX;
    } else {
        x = indirectX;
    }

    var y;
    if (Math.abs(directY) < Math.abs(indirectY)) {
        y = directY;
    } else {
        y = indirectY;
    }

    var squaredDistance = (x * x + y * y);
    var angle = Math.atan2(y, x);

    var force = Math.min(
        20000000,
        gravityDirection * forceCoefficient * obj.body.mass * target.body.mass / squaredDistance
    );

    obj.body.force.x = Math.cos(angle) * force;
    obj.body.force.y = Math.sin(angle) * force;

    if (shouldSpin) {
        var angularForce = 0;

        var objTopLeftToTargetX = objTopLeftX - averageTargetX;
        var objTopLeftToTargetY = objTopLeftY - averageTargetY;
        var objTopLeftToTargetSquaredDistance = objTopLeftToTargetX * objTopLeftToTargetX + objTopLeftToTargetY * objTopLeftToTargetY;

        // Axis aligned box means the vector from center to corner is (1, 1), so the dot product divided by the distance squared is:
        angularForce += (objTopLeftToTargetX + objTopLeftToTargetY) / objTopLeftToTargetSquaredDistance;

        var objTopRightToTargetX = objTopRightX - averageTargetX;
        var objTopRightToTargetY = objTopRightY - averageTargetY;
        var objTopRightToTargetSquaredDistance = objTopRightToTargetX * objTopRightToTargetX + objTopRightToTargetY * objTopRightToTargetY;

        angularForce += (objTopRightToTargetX + objTopRightToTargetY) / objTopRightToTargetSquaredDistance;

        var objBottomLeftToTargetX = objBottomLeftX - averageTargetX;
        var objBottomLeftToTargetY = objBottomLeftY - averageTargetY;
        var objBottomLeftToTargetSquaredDistance = objBottomLeftToTargetX * objBottomLeftToTargetX + objBottomLeftToTargetY * objBottomLeftToTargetY;

        angularForce += (objBottomLeftToTargetX + objBottomLeftToTargetY) / objBottomLeftToTargetSquaredDistance;

        var objBottomRightToTargetX = objBottomRightX - averageTargetX;
        var objBottomRightToTargetY = objBottomRightY - averageTargetY;
        var objBottomRightToTargetSquaredDistance = objBottomRightToTargetX * objBottomRightToTargetX + objBottomRightToTargetY * objBottomRightToTargetY;

        angularForce += (objBottomRightToTargetX + objBottomRightToTargetY) / objBottomRightToTargetSquaredDistance;

        obj.body.angularForce = Math.min(10000, 10000 * angularForce);
    }
}

function addToTrail(player) {
    player.trailTexture.render(trailImage, player.position, false);
}

function maybeFire(player) {
    var fireType;
    if (controls.up.isDown) {
        fireType = 1;
    } else if (controls.down.isDown) {
        fireType = -1;
    } else {
        return;
    }

    addProjectile(player, fireType);
}

function addProjectile(player, fireType) {
    if (!player.canFire) {
        return;
    }

    var projectile = projectiles.create(player.x, player.y, 'projectile');
    game.physics.p2.enable(projectile);

    projectile.anchor.set(0.5);

    projectile.body.rotation = player.body.rotation;

    var angle = projectile.body.rotation - Math.PI / 2;
    var speed = 1500;

    projectile.body.velocity.x = Math.cos(angle) * speed;
    projectile.body.velocity.y = Math.sin(angle) * speed;

    projectile.body.damping = 0;
    projectile.body.angularDamping = 0;

    projectile.body.setCollisionGroup(projectileCollisionGroup);
    projectile.body.collides(planetCollisionGroup);

    projectile.body.onBeginContact.add(function(body) {
        projectileHit(player, projectile, body);
    }, this);

    projectile.fireType = fireType;

    game.time.events.add(Phaser.Timer.SECOND / 5, function() {
        player.canFire = true;
    }, this);

    player.canFire = false;
}

function projectileHit(player, projectile, body) {
    projectile.kill();

    player.hasProjectile = false;

    // FIXME: This is if it hit a wall.
    if (body === null) {
        return;
    }

    setCurrentPlanet(body.sprite, projectile.fireType);
}

function maybeWrap(obj) {
    game.world.wrap(obj.body, Math.sqrt(obj.height / 2, obj.width / 2));
}

})();
<commit_msg>Disable the trail.<commit_after>(function() {

'use strict';

var game,
    planetCollisionGroup,
    playerCollisionGroup,
    projectileCollisionGroup,
    controls,
    background,
    trails,
    trailTexture,
    trailImage,
    planets,
    currentPlanet,
    players,
    projectiles,
    gravityDirection;

var colours = {
    red:    0xcc6666,
    orange: 0xde935f,
    yellow: 0xf0c674,
    green:  0xb5bd68,
    aqua:   0x8abeb7,
    blue:   0x81a2be,
    purple: 0xb294bb,
    brown:  0xa3685a,
}

window.startGame = function() {
    game = new Phaser.Game(
        1820, 1024,
        Phaser.AUTO
    );

    game.state.add('main', mainState);
    game.state.start('main');
};

var mainState = {
    preload: function() {
        game.load.image('background', 'assets/background.png');
        game.load.image('trail',      'assets/trail.png');
        game.load.image('player',     'assets/player.png');
        game.load.image('planet',     'assets/planet.png');
        game.load.image('projectile', 'assets/projectile.png');
    },

    create: function() {
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.scale.setScreenSize(true);

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

        trailImage = game.make.image(0, 0, 'trail');
        trailImage.anchor.set(0.5);

        game.physics.startSystem(Phaser.Physics.P2JS);

        playerCollisionGroup     = game.physics.p2.createCollisionGroup();
        planetCollisionGroup     = game.physics.p2.createCollisionGroup();
        projectileCollisionGroup = game.physics.p2.createCollisionGroup();

        // Make things collide with the bounds.
        // game.physics.p2.updateBoundsCollisionGroup();

        background = game.add.tileSprite(0, 0, 1820, 1024, 'background');

        trails      = game.add.group();
        players     = game.add.group();
        planets     = game.add.group();
        projectiles = game.add.group();

        addPlayer(game.world.centerX, game.world.centerY);

        for (var i = 0; i < 11; i++) {
            var x = game.rnd.integerInRange(0, game.world.width);
            var y = game.rnd.integerInRange(0, game.world.height);
            while (Math.abs(game.world.centerX - x) < 300 && Math.abs(game.world.centerY - y) < 300) {
                x = game.rnd.integerInRange(0, game.world.width);
                y = game.rnd.integerInRange(0, game.world.height);
            }

            addPlanet(x, y, i === 0);
        }
    },

    update: function() {
        players.forEachAlive(movePlayer, this);
        planets.forEachAlive(movePlanet, this);

        players.forEachAlive(maybeFire, this);

        if (players.countLiving() === 1) {
            lerpWorldCenterTowardsPlayer(players.getFirstAlive());
        } else {
            lerpWorldCenterTowardsCurrentPlanet();
        }

        players.forEachAlive(maybeWrap, this);
        planets.forEachAlive(maybeWrap, this);
        projectiles.forEachAlive(maybeWrap, this);
    },

    shutdown: function() {
        // FIXME: Tidy up and reset everything!
    },
}

function lerpWorldCenterTowardsCurrentPlanet() {
    lerpWorldCenterTowardsXY(currentPlanet.body.x, currentPlanet.body.y, 50);
}

function lerpWorldCenterTowardsPlayer(player) {
    lerpWorldCenterTowardsXY(player.body.x, player.body.y, 50);
}

function lerpWorldCenterTowardsXY(targetX, targetY, lerpFactor) {
    var x = (game.world.centerX - targetX) / lerpFactor;
    var y = (game.world.centerY - targetY) / lerpFactor;

    background.tilePosition.x += x;
    background.tilePosition.y += y;

    function lerp(obj) {
        obj.body.x += x;
        obj.body.y += y;
    }

    players.forEachAlive(lerp, this);
    planets.forEachAlive(lerp, this);
    projectiles.forEachAlive(lerp, this);
}

function addPlanet(x, y, isCurrent) {
    var planet = planets.create(x, y, 'planet');
    game.physics.p2.enable(planet);

    planet.anchor.set(0.5);
    planet.tint = colours.aqua;

    planet.body.velocity.x = game.rnd.integerInRange(-100, 100);
    planet.body.velocity.y = game.rnd.integerInRange(-100, 100);

    planet.body.rotateRight(game.rnd.integerInRange(-20, 20));

    planet.body.mass    = 1000;
    planet.body.damping = 0;
    planet.body.angularDamping = 0;

    planet.body.setCollisionGroup(planetCollisionGroup);
    planet.body.collides(playerCollisionGroup);
    planet.body.collides(projectileCollisionGroup);

    if (isCurrent) {
        setCurrentPlanet(planet);
    }
}

function setCurrentPlanet(planet, gravityDirectionToSet) {
    if (gravityDirectionToSet === undefined) {
        gravityDirectionToSet = 1;
    }

    if (currentPlanet !== undefined) {
        currentPlanet.tint = colours.aqua;
        currentPlanet.body.mass = 100;
    }

    if (gravityDirectionToSet === 1) {
        planet.tint = colours.green;
    } else {
        planet.tint = colours.purple;
    }

    planet.body.mass = 1000000;

    gravityDirection = gravityDirectionToSet;

    currentPlanet = planet;
}

function addPlayer(x, y) {
    var player = players.create(x, y, 'player');
    game.physics.p2.enable(player);

    player.anchor.set(0.5);
    player.body.rotation = Math.PI * 3 / 4;

    player.body.damping = 0;
    player.body.angularDamping = 0.99;

    player.body.setCollisionGroup(playerCollisionGroup);
    player.body.collides(playerCollisionGroup);
    player.body.collides(planetCollisionGroup);

    player.body.onBeginContact.add(function(body) {
        playerHit(player, body);
    }, this);

    player.canFire = true;

    // FIXME: This should display the actual trajectory of the player, not their movement in camera space.
    player.trailTexture = game.add.renderTexture(game.world.width, game.world.height, 'trailTexture');

    player.trail = trails.create(game.world.centerX, game.world.centerY, player.trailTexture);
    player.trail.anchor.set(0.5);

    player.trailTimer = game.time.create(false);

    player.trailTimer.loop(Phaser.Timer.SECOND / 4, function() {
        addToTrail(player);
    }, this);

    // player.trailTimer.start();
}

function playerHit(player, body) {
    // FIXME: This is if they hit a wall.
    if (body === null) {
        return;
    }

    player.trailTimer.destroy();
    player.kill();

    if (body.sprite.key === 'player') {
        body.sprite.trailTimer.destroy();
        body.kill();
    }
}

function movePlayer(player) {
    var sign = 0;
    if (controls.left.isDown) {
        sign = -1;
    } else if (controls.right.isDown) {
        sign = 1;
    }

    player.body.angularForce += sign * 30;

    move(player, 5, false);
}

function movePlanet(planet) {
    if (planet === currentPlanet) {
        return;
    }

    move(planet, 1, true);
}

function move(obj, forceCoefficient, shouldSpin) {
    accelerateToObject(obj, currentPlanet, forceCoefficient, shouldSpin);
}

function accelerateToObject(obj, target, forceCoefficient, shouldSpin) {
    // These are axis aligned squares!
    var objTopLeftX     = obj.x - obj.width / 2;
    var objTopLeftY     = obj.y + obj.height / 2;

    var objTopRightX    = obj.x + obj.width / 2;
    var objTopRightY    = obj.y + obj.height / 2;

    var objBottomLeftX  = obj.x - obj.width / 2;
    var objBottomLeftY  = obj.y - obj.height / 2;

    var objBottomRightX = obj.x + obj.width / 2;
    var objBottomRightY = obj.y - obj.height / 2;

    var averageObjX = (objTopLeftX + objTopRightX + objBottomLeftX + objBottomRightX) / 4;
    var averageObjY = (objTopLeftY + objTopRightY + objBottomLeftY + objBottomRightY) / 4;

    var targetTopLeftX     = target.x - target.width / 2;
    var targetTopLeftY     = target.y + target.height / 2;

    var targetTopRightX    = target.x + target.width / 2;
    var targetTopRightY    = target.y + target.height / 2;

    var targetBottomLeftX  = target.x - target.width / 2;
    var targetBottomLeftY  = target.y - target.height / 2;

    var targetBottomRightX = target.x + target.width / 2;
    var targetBottomRightY = target.y - target.height / 2;

    var averageTargetX = (targetTopLeftX + targetTopRightX + targetBottomLeftX + targetBottomRightX) / 4;
    var averageTargetY = (targetTopLeftY + targetTopRightY + targetBottomLeftY + targetBottomRightY) / 4;

    var directX = averageTargetX - averageObjX;
    var directY = averageTargetY - averageObjY;

    var indirectX = directX + game.width;
    var indirectY = directY + game.height;

    var x;
    if (Math.abs(directX) < Math.abs(indirectX)) {
        x = directX;
    } else {
        x = indirectX;
    }

    var y;
    if (Math.abs(directY) < Math.abs(indirectY)) {
        y = directY;
    } else {
        y = indirectY;
    }

    var squaredDistance = (x * x + y * y);
    var angle = Math.atan2(y, x);

    var force = Math.min(
        20000000,
        gravityDirection * forceCoefficient * obj.body.mass * target.body.mass / squaredDistance
    );

    obj.body.force.x = Math.cos(angle) * force;
    obj.body.force.y = Math.sin(angle) * force;

    if (shouldSpin) {
        var angularForce = 0;

        var objTopLeftToTargetX = objTopLeftX - averageTargetX;
        var objTopLeftToTargetY = objTopLeftY - averageTargetY;
        var objTopLeftToTargetSquaredDistance = objTopLeftToTargetX * objTopLeftToTargetX + objTopLeftToTargetY * objTopLeftToTargetY;

        // Axis aligned box means the vector from center to corner is (1, 1), so the dot product divided by the distance squared is:
        angularForce += (objTopLeftToTargetX + objTopLeftToTargetY) / objTopLeftToTargetSquaredDistance;

        var objTopRightToTargetX = objTopRightX - averageTargetX;
        var objTopRightToTargetY = objTopRightY - averageTargetY;
        var objTopRightToTargetSquaredDistance = objTopRightToTargetX * objTopRightToTargetX + objTopRightToTargetY * objTopRightToTargetY;

        angularForce += (objTopRightToTargetX + objTopRightToTargetY) / objTopRightToTargetSquaredDistance;

        var objBottomLeftToTargetX = objBottomLeftX - averageTargetX;
        var objBottomLeftToTargetY = objBottomLeftY - averageTargetY;
        var objBottomLeftToTargetSquaredDistance = objBottomLeftToTargetX * objBottomLeftToTargetX + objBottomLeftToTargetY * objBottomLeftToTargetY;

        angularForce += (objBottomLeftToTargetX + objBottomLeftToTargetY) / objBottomLeftToTargetSquaredDistance;

        var objBottomRightToTargetX = objBottomRightX - averageTargetX;
        var objBottomRightToTargetY = objBottomRightY - averageTargetY;
        var objBottomRightToTargetSquaredDistance = objBottomRightToTargetX * objBottomRightToTargetX + objBottomRightToTargetY * objBottomRightToTargetY;

        angularForce += (objBottomRightToTargetX + objBottomRightToTargetY) / objBottomRightToTargetSquaredDistance;

        obj.body.angularForce = Math.min(10000, 10000 * angularForce);
    }
}

function addToTrail(player) {
    player.trailTexture.render(trailImage, player.position, false);
}

function maybeFire(player) {
    var fireType;
    if (controls.up.isDown) {
        fireType = 1;
    } else if (controls.down.isDown) {
        fireType = -1;
    } else {
        return;
    }

    addProjectile(player, fireType);
}

function addProjectile(player, fireType) {
    if (!player.canFire) {
        return;
    }

    var projectile = projectiles.create(player.x, player.y, 'projectile');
    game.physics.p2.enable(projectile);

    projectile.anchor.set(0.5);

    projectile.body.rotation = player.body.rotation;

    var angle = projectile.body.rotation - Math.PI / 2;
    var speed = 1500;

    projectile.body.velocity.x = Math.cos(angle) * speed;
    projectile.body.velocity.y = Math.sin(angle) * speed;

    projectile.body.damping = 0;
    projectile.body.angularDamping = 0;

    projectile.body.setCollisionGroup(projectileCollisionGroup);
    projectile.body.collides(planetCollisionGroup);

    projectile.body.onBeginContact.add(function(body) {
        projectileHit(player, projectile, body);
    }, this);

    projectile.fireType = fireType;

    game.time.events.add(Phaser.Timer.SECOND / 5, function() {
        player.canFire = true;
    }, this);

    player.canFire = false;
}

function projectileHit(player, projectile, body) {
    projectile.kill();

    player.hasProjectile = false;

    // FIXME: This is if it hit a wall.
    if (body === null) {
        return;
    }

    setCurrentPlanet(body.sprite, projectile.fireType);
}

function maybeWrap(obj) {
    game.world.wrap(obj.body, Math.sqrt(obj.height / 2, obj.width / 2));
}

})();
<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.AUTO);

game.constants = {
  tileSize: 64,
  maxJumpHeight: 200
};
game.objects = {};
game.colorPalette = {
  accent: '#22CC77',
  light: '#ddd',
  middle: '#888',
  dark: '#333'
};

states = {};

states.running = function(game) {};
states.running.prototype = {
  preload: function () {},

  create: function () {
    var groundHeight = game.world.height - game.constants.tileSize;
    game.stage.backgroundColor = game.colorPalette.light;

    game.objects.runner = new Phaser.Rectangle(game.world.centerX - game.constants.tileSize / 2, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);
    game.objects.ground = new Phaser.Rectangle(0, groundHeight, game.world.width, game.constants.tileSize);
    game.objects.obstacle = new Phaser.Rectangle(game.world.width + 20, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);

    game.input.onDown.add(this.onDown, this);
    game.input.onUp.add(this.onUp, this);
  },

  update: function () {
    game.objects.obstacle.x -= 2;
    if (game.objects.obstacle.x < -20) {
      game.objects.obstacle.x = game.world.width + 20;
    }
  },

  render: function () {
    game.debug.geom(game.objects.runner, game.colorPalette.accent);
    game.debug.geom(game.objects.ground, game.colorPalette.dark);
    game.debug.geom(game.objects.obstacle, game.colorPalette.middle);
  },

  onDown: function (pointer, mouseEvent) {
    if(mouseEvent.identifier === 0) {
      game.objects.runner.y -= game.constants.maxJumpHeight;
    }
  },

  onUp: function (pointer, mouseEvent) {
    // Prevents 'mouse leaving the game world' from firing this, too
    if(mouseEvent.identifier === 0 && pointer.identifier === 0) {
      game.objects.runner.y += game.constants.maxJumpHeight;
    }
  }
};

states.waiting = function(game) {};
states.waiting.prototype = {
  preload: function () {},

  create: function () {
    var groundHeight = game.world.height - game.constants.tileSize;
    game.stage.backgroundColor = game.colorPalette.light;

    game.objects.runner = new Phaser.Rectangle(game.world.centerX - game.constants.tileSize / 2, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);
    game.objects.ground = new Phaser.Rectangle(0, groundHeight, game.world.width, game.constants.tileSize);

    game.input.onTap.add(this.startRunning, this);
  },

  render: function () {
    game.debug.geom(game.objects.runner, game.colorPalette.accent);
    game.debug.geom(game.objects.ground, game.colorPalette.dark);
  },

  startRunning: function() {
    game.state.start('running');
  }
};

game.state.add('running', states.running);
game.state.add('waiting', states.waiting);
game.state.start('waiting');
<commit_msg>added lose condition on collision<commit_after>var game = new Phaser.Game(800, 600, Phaser.AUTO);

game.constants = {
  tileSize: 64,
  maxJumpHeight: 200
};
game.objects = {};
game.colorPalette = {
  accent: '#22CC77',
  light: '#ddd',
  middle: '#888',
  dark: '#333'
};

states = {};

states.running = function(game) {};
states.running.prototype = {
  preload: function () {},

  create: function () {
    var groundHeight = game.world.height - game.constants.tileSize;
    game.stage.backgroundColor = game.colorPalette.light;

    game.objects.runner = new Phaser.Rectangle(game.world.centerX - game.constants.tileSize / 2, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);
    game.objects.ground = new Phaser.Rectangle(0, groundHeight, game.world.width, game.constants.tileSize);
    game.objects.obstacle = new Phaser.Rectangle(game.world.width + 20, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);

    game.input.onDown.add(this.onDown, this);
    game.input.onUp.add(this.onUp, this);
  },

  update: function () {
    game.objects.obstacle.x -= 2;
    if (game.objects.obstacle.x < -20) {
      game.objects.obstacle.x = game.world.width + 20;
    }
    if(game.objects.obstacle.intersects(game.objects.runner)) {
      game.state.start('waiting');
    }
  },

  render: function () {
    game.debug.geom(game.objects.runner, game.colorPalette.accent);
    game.debug.geom(game.objects.ground, game.colorPalette.dark);
    game.debug.geom(game.objects.obstacle, game.colorPalette.middle);
  },

  onDown: function (pointer, mouseEvent) {
    if(mouseEvent.identifier === 0) {
      game.objects.runner.y -= game.constants.maxJumpHeight;
    }
  },

  onUp: function (pointer, mouseEvent) {
    // Prevents 'mouse leaving the game world' from firing this, too
    if(mouseEvent.identifier === 0 && pointer.identifier === 0) {
      game.objects.runner.y += game.constants.maxJumpHeight;
    }
  }
};

states.waiting = function(game) {};
states.waiting.prototype = {
  preload: function () {},

  create: function () {
    var groundHeight = game.world.height - game.constants.tileSize;
    game.stage.backgroundColor = game.colorPalette.light;

    game.objects.runner = new Phaser.Rectangle(game.world.centerX - game.constants.tileSize / 2, groundHeight - game.constants.tileSize, game.constants.tileSize, game.constants.tileSize);
    game.objects.ground = new Phaser.Rectangle(0, groundHeight, game.world.width, game.constants.tileSize);

    game.input.onTap.add(this.startRunning, this);
  },

  render: function () {
    game.debug.geom(game.objects.runner, game.colorPalette.accent);
    game.debug.geom(game.objects.ground, game.colorPalette.dark);
  },

  startRunning: function() {
    game.state.start('running');
  }
};

game.state.add('running', states.running);
game.state.add('waiting', states.waiting);
game.state.start('waiting');
<|endoftext|>


<commit_before>import _ from 'lodash';
import request from 'request';

/**
 * Makes a request to Classy's API.
 *
 * @param  {string} path    Request URI
 * @param  {string} method  Request method
 * @param  {object} headers Request headers
 * @param  {object} form    Request form (optional)
 * @return {promise}         Promise based on API request
 */
export default function _makeRequest(path, method, headers, form, data) {
  const _this = this;
  let forceQs = null;

  if (data.noLog) {
    headers['x-no-log'] = true;
    delete data.noLog;
  }

  if (_.isObject(data.qs)) {
    forceQs = data.qs;
    delete data.qs;
  }

  const promise = new Promise((resolve, reject) => {
    const requestParams = {
      baseUrl: this.baseUrl,
      uri: path,
      method: method,
      headers: headers,
      rejectUnauthorized: false,
      form: form
    };

    if (method === 'GET') {
      requestParams.qs = data;
    } else {
      requestParams.body = JSON.stringify(data);
    }

    if (forceQs) {
      requestParams.qs = _.merge(requestParams.qs || {}, forceQs);
    }

    request(requestParams, (err, response, body) => {
      if (err || !/^2/.test('' + response.statusCode)) {
        let error;
        if (err && err instanceof Error) {
          error = err;
          error.statusCode = response.statusCode;
        } else if (err && !(err instanceof Error)) {
          const errorString = JSON.stringify(err);
          error = new Error(errorString);
          error.statusCode = response.statusCode;
        } else {
          const errorString = body ? JSON.stringify(body) : 'Non-200 response';
          error = new Error(errorString);
          error.statusCode = response.statusCode;
        }

        reject(error);
      } else {
        body = body ? JSON.parse(body) : {};
        resolve(body);
      }
    });

  });

  return promise;
}
<commit_msg>Fix tests<commit_after>import _ from 'lodash';
import request from 'request';

/**
 * Makes a request to Classy's API.
 *
 * @param  {string} path    Request URI
 * @param  {string} method  Request method
 * @param  {object} headers Request headers
 * @param  {object} form    Request form (optional)
 * @return {promise}         Promise based on API request
 */
export default function _makeRequest(path, method, headers, form, data) {
  const _this = this;
  let forceQs = null;

  if (data.noLog) {
    headers['x-no-log'] = true;
    delete data.noLog;
  }

  if (_.isObject(data.qs)) {
    forceQs = data.qs;
    delete data.qs;
  }

  const promise = new Promise((resolve, reject) => {
    const requestParams = {
      baseUrl: this.baseUrl,
      uri: path,
      method: method,
      headers: headers,
      rejectUnauthorized: false,
      form: form
    };

    if (method === 'GET') {
      requestParams.qs = data;
    } else {
      requestParams.body = JSON.stringify(data);
    }

    if (forceQs) {
      requestParams.qs = _.merge(requestParams.qs || {}, forceQs);
    }

    request(requestParams, (err, response, body) => {
      if (err || !/^2/.test('' + response.statusCode)) {
        let error;
        if (err && err instanceof Error) {
          error = err;
        } else if (err && !(err instanceof Error)) {
          const errorString = JSON.stringify(err);
          error = new Error(errorString);
        } else {
          const errorString = body ? JSON.stringify(body) : 'Non-200 response';
          error = new Error(errorString);
          error.statusCode = response.statusCode;
        }

        reject(error);
      } else {
        body = body ? JSON.parse(body) : {};
        resolve(body);
      }
    });

  });

  return promise;
}
<|endoftext|>


<commit_before>Drac.Game = function(game) {
    score = 0;
    lives = 0;
};

/**
 * No preload function required here as that is handled in the Drac.Loader state.
 *
 * @type {Object}
 */
Drac.Game.prototype = {
    create: function() {

    },
    update: function() {

    },
    touchDrac: function() {

    },
    hitDrac: function() {

    },
    quitGame: function(){
        this.state.start('Menu');
    }
};<commit_msg>Adding floor as simple rect - finding graphics assets is tough<commit_after>Drac.Game = function(game) {
    score = 0;
    lives = 0;
};

/**
 * No preload function required here as that is handled in the Drac.Loader state.
 *
 * @type {Object}
 */
Drac.Game.prototype = {
    create: function() {
        this.createFloor();
    },
    update: function() {

    },
    touchDrac: function() {

    },
    hitDrac: function() {

    },
    quitGame: function(){
        this.state.start('Menu');
    },
    createFloor: function(){
        // Init vector shape
        this.ground = this.game.add.graphics(0, 0);
        this.ground.lineStyle(2, 0x663300, 1);
        this.ground.beginFill(0x331900, 1);

        // Draw shape
        this.ground.drawRect(-2, this.game.world.height-20, this.game.world.width+20, 20);
        this.ground.immovable = true;
    }
};<|endoftext|>