<commit_before>(function(){
	var Quay = function() {
		var _self = this;

		/*Utility Functions*/
		var contains = function(a, obj) {var i = a.length;while (i--) {if (a[i] === obj) {return true;}}return false;},
			remove = function(a, x) {
				if (contains(a,x)) {
					a.splice(a.indexOf(x),1 );
				}
			};

		var pressing = [],
			special_keys = {
				8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
				20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
				37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
				96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
				104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
				112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
				120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 186: ";", 191: "/",
				220: "\\", 222: "'", 224: "meta"
			};

		this.convert = function(key) {

			if (contains(Object.keys(special_keys),String(key)))
			//if(Object.keys(special_keys).contains(String(key)))
			{
				return special_keys[key];
			} else {
				return String.fromCharCode(key).toLowerCase();
			}
		};
		this.run = function(key) {
			var string = this.convert(key.which);
			pressing.push(string);
		};

		this.press = function(key_bindings) { this.bindings = key_bindings; };

		window.onkeydown = function(e) {
			_self.run(e);

			var currently_pressing = pressing.join('_');
			if (contains(Object.keys(_self.bindings),currently_pressing))
			{
				_self.bindings[currently_pressing]();
			}
		};

		window.onkeyup = function(e) {
			remove(pressing,_self.convert(e.which));
		};
	};

	window.Quay = new Quay();
})();
<commit_msg>Removed an unneeded comment<commit_after>(function(){
	var Quay = function() {
		var _self = this;

		/*Utility Functions*/
		var contains = function(a, obj) {var i = a.length;while (i--) {if (a[i] === obj) {return true;}}return false;},
			remove = function(a, x) {
				if (contains(a,x)) {
					a.splice(a.indexOf(x),1 );
				}
			};

		var pressing = [],
			special_keys = {
				8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
				20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
				37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
				96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
				104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
				112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
				120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 186: ";", 191: "/",
				220: "\\", 222: "'", 224: "meta"
			};

		this.convert = function(key) {

			if (contains(Object.keys(special_keys),String(key)))
			{
				return special_keys[key];
			} else {
				return String.fromCharCode(key).toLowerCase();
			}
		};
		this.run = function(key) {
			var string = this.convert(key.which);
			pressing.push(string);
		};

		this.press = function(key_bindings) { this.bindings = key_bindings; };

		window.onkeydown = function(e) {
			_self.run(e);

			var currently_pressing = pressing.join('_');
			if (contains(Object.keys(_self.bindings),currently_pressing))
			{
				_self.bindings[currently_pressing]();
			}
		};

		window.onkeyup = function(e) {
			remove(pressing,_self.convert(e.which));
		};
	};

	window.Quay = new Quay();
})();
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs-extra');
var path = require('path');
var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var assert = require('chai').assert;

var rewire = require('rewire');
var Cli = rewire('../../dist/Cli');

describe('Configuration content:', function() {
  let testResults = "test/integration/results/content_test";

  describe('with a styleguide configuration with given pages', function () {
    afterEach(function() {
      return fs.remove(path.resolve(testResults));
    });

    it('should create html files for each tag page', function () {
      let testCWD = "test/integration/fixtures/content_test";
      let a = Cli.__get__('build')({ cwd: testCWD })

      // file  assertions!
      .then(res => {
        return Promise.resolve(fs.statSync(path.resolve(testResults, 'atoms.html')));
      })

      .then(res => {
        return Promise.resolve(fs.statSync(path.resolve(testResults, 'atoms', 'forms.html')));
      });

      return assert.isFulfilled(a, "files available");
    });

  });
});
<commit_msg>USXP-680 added test for content creation inclusively to navigation nesting<commit_after>"use strict";

var fs = require('fs-extra');
var path = require('path');
var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var assert = require('chai').assert;

var jsdom = require("jsdom");
var jquery = fs.readFileSync(path.resolve(__dirname, "../../node_modules/jquery/dist/jquery.js"), "utf-8");

var rewire = require('rewire');
var Cli = rewire('../../dist/Cli');

describe('Configuration content:', function() {
  var testCWD = "test/integration/fixtures/content_test";
  var testResults = "test/integration/results/content_test";

  describe('with given pages', function () {

    afterEach(function(done) {
      fs.remove(path.resolve(testResults), function() {
        return done();
      });
    });

    it('should create html files for each tag page', function () {
      let a = Cli.__get__('build')({ cwd: testCWD })

      // file  assertions!
      .then(res => {
        return Promise.resolve(fs.statSync(path.resolve(testResults, 'atoms.html')));
      })

      .then(res => {
        return Promise.resolve(fs.statSync(path.resolve(testResults, 'atoms', 'forms.html')));
      });

      return assert.isFulfilled(a, "files available");
    });

    it('should create a nested navigation for the content structure', function () {
      let a = Cli.__get__('build')({ cwd: testCWD })

      // file  assertions!
      .then(res => {
        return new Promise(function(resolve, reject) {
          jsdom.env({
            file: path.resolve(testResults, 'atoms.html'),
            src: [jquery],
            done: function (err, window) {
              if (!!err) {
                console.log("ERR", err);
                reject(err);
              }
              var nav = window.$('.test-stylegen-main-nav');
              var navEntries = window.$('.test-stylegen-main-nav > a');
              var childLinks = nav.find('.children');

              if (navEntries.length !== 1) {
                return reject("Expected to have exactly one link in first nav layer");
              }

              var baseLinkText = 'Atoms';
              if (navEntries.text().trim() !== baseLinkText) {
                return reject(`Expected the link to have the link text "${baseLinkText}" instead it has "${navEntries.text()}"`);
              }

              if (childLinks.length !== 1) {
                return reject("Expected to have exactly one child link in first nav layer");
              }

              var childLinkText = 'Forms';
              if (childLinks.text().trim() !== childLinkText) {
                return reject(`Expected the link to have the link text "${childLinkText}" instead it has "${childLinks.text().trim()}"`);
              }

              return resolve(true);
            }
          });
        });
      });

      return assert.isFulfilled(a, "navigation entries available");
    });
  });
});
<|endoftext|>


<commit_before>module.exports = function (config) {
	'use strict';

	config.set({
		basePath: '../../',
		frameworks: ['jasmine'],
		files: [
			'node_modules/angular/angular.js',
			'node_modules/angular-route/angular-route.js',
			'node_modules/angular-mocks/angular-mocks.js',
			'js/**/*.js',
			'test/unit/**/*.js'
		],
		autoWatch: true,
		singleRun: false,
		browsers: ['Chrome', 'Firefox']
	});
};
// test
<commit_msg>Update karma.conf.js<commit_after>module.exports = function (config) {
	'use strict';

	config.set({
		basePath: '../../',
		frameworks: ['jasmine'],
		files: [
			'node_modules/angular/angular.js',
			'node_modules/angular-route/angular-route.js',
			'node_modules/angular-mocks/angular-mocks.js',
			'js/**/*.js',
			'test/unit/**/*.js'
		],
		autoWatch: true,
		singleRun: false,
		browsers: ['Chrome', 'Firefox'],

		reporters: ['coverage'],
		coverageReporter: {
            dir: 'test/coverage/',
            reporters: [
                {
                    type: 'lcovonly'
                },
                {
                    type: 'cobertura',subdir: '.', file: 'cobertura.xml'
                }
            ]
        },

	});
};
// test
<|endoftext|>


<commit_before>/** MIT License (c) copyright B Cavalier & J Hann */

(function (define) {
define(function (require) {
"use strict";

	var guess, domEvents, watchNode;

	guess = require('../guess');
	domEvents = require('../events');
	watchNode = domEvents.watchNode;

	/**
	 * Creates a cola adapter for interacting with dom nodes.  Be sure to
	 * unwatch any watches to prevent memory leaks in Internet Explorer 6-8.
	 * @constructor
	 * @param rootNode {Node}
	 * @param options {Object}
	 */
	function NodeAdapter (rootNode, options) {

		this._rootNode = rootNode;

		// set options
		this._options = options || {};

		// flag to avoid circles when updating from an event
		this._updating = false;

		// event unwatchers to be called to prevent memory leaks in IE
		this._unwatches = [];

		this._watchAllEvents();

	}

	NodeAdapter.prototype = {

		getOptions: function () {
			return this._options;
		},

		update: function (item) {
			this._item = item;
			for (var p in item) {
				this._setProperty(p, item[p]);
			}
		},

		destroy: function () {
			var unwatches = this._unwatches;
			while (unwatches.length) unwatches.pop()();
		},

		/**
		 * Changes the value of a node attribute mapped from an item property.
		 * @param name {String} the name of the property
		 * @param value the new value of the property
		 */
		_setProperty: function (name, value) {
			var b, node, prop, current;

			b = this._getBindingsFor(name);

			// If there are no bindings for this name, there's
			// no way to divine what property to set.  Give up.
			if(!b) {
				return;
			} else if(b.to) {
				// HACK: Until we change the way bindings are done,
				// this allows binding data props to multiple things.

				// If there's a "to" override, then this binding
				// actually applies to the data property specified
				// by it.

				name = b.to;
			}

			node = this._getNode(b.node, name);

			if (node) {
				prop = 'prop' in b ? b.prop : guess.propFor(node);
				current = guess.getNodePropOrAttr(node, prop);
				if (current !== value) {
					guess.setNodePropOrAttr(node, prop, value);
				}
			}
		},

		/**
		 * Returns the binding info for a node, if it exists.
		 * @param name {String} the name of the node
		 * @returns {Object} {
		 *     node: aNode,
		 *     prop: 'aProp',
		 *     events: 'event1,event2' // optional
		 * }
		 */
		_getBindingsFor: function (name) {
			var bindings, binding;

			bindings = this._options.bindings;
			if (bindings && name in bindings) {
				binding = bindings[name];
			}

			return binding;
		},

		_getNode: function (selector, name) {
			// TODO: cache querySelector lookups?
			var node;
			if (guess.isNode(selector)) {
				node = selector;
			}
			else if (selector) {
				node = this._options.querySelector(selector, this._rootNode);
			}
			if (!node) {
				node = guess.nodeByName(this._rootNode, name) || this._rootNode;
			}
			return node;
		},

		_watchAllEvents: function () {
			var name, binding, events, node, prop;

			for (name in this._options.bindings) {
				binding = this._options.bindings[name];

				if(binding.to) name = binding.to;

				node = this._getNode(binding.node, name);
				prop = binding.prop || guess.propForNode(node);
				events = binding.event || binding.events;
				if(events == null) {
					events = guess.eventsForNode(node);
				}

				if (events && node && prop) {
					this._watchEvents(node, events, name, prop);
				}
			}
		},

		_watchEvents: function (node, events, name, prop) {
			var self = this;

			this._unwatches.push(listenToNode(node, events, function () {
				var prev, curr;

				prev = self._item[name];
				curr = guess.getNodePropOrAttr(node, prop);

				if (prev !== curr) {
					self._item[name] = curr;
				}
			}));
		}

	};

	/**
	 * Tests whether the given object is a candidate to be handled by
	 * this adapter. Returns true if this is a DOMNode (or looks like one).
	 * @param obj
	 * @returns {Boolean}
	 */
	NodeAdapter.canHandle = function (obj) {
		// crude test if an object is a node.
		return obj && obj.tagName && obj.getAttribute && obj.setAttribute;
	};

	function listenToNode (node, events, callback) {

		var unwatchers, i;

		if (typeof events == 'string') {
			events = events.split(/\s*,\s*/);
		}
		else if (!events) {
			events = [];
		}

		// create unwatchers
		unwatchers = [];
		for (i = 0; i < events.length; i++) {
			unwatchers.push(watchNode(node, events[i], callback));
		}

		// create and return single unwatcher to unwatch all events
		return function () {
			var unwatch;
			while ((unwatch == unwatchers.pop())) squelchedUnwatch(unwatch);
		};

	}

	function squelchedUnwatch (unwatch) {
		try { unwatch(); } catch (ex) {}
	}

	return NodeAdapter;

});
}(
	typeof define == 'function'
		? define
		: function (factory) { module.exports = factory(require); }
));<commit_msg>Fix propForNode method name<commit_after>/** MIT License (c) copyright B Cavalier & J Hann */

(function (define) {
define(function (require) {
"use strict";

	var guess, domEvents, watchNode;

	guess = require('../guess');
	domEvents = require('../events');
	watchNode = domEvents.watchNode;

	/**
	 * Creates a cola adapter for interacting with dom nodes.  Be sure to
	 * unwatch any watches to prevent memory leaks in Internet Explorer 6-8.
	 * @constructor
	 * @param rootNode {Node}
	 * @param options {Object}
	 */
	function NodeAdapter (rootNode, options) {

		this._rootNode = rootNode;

		// set options
		this._options = options || {};

		// flag to avoid circles when updating from an event
		this._updating = false;

		// event unwatchers to be called to prevent memory leaks in IE
		this._unwatches = [];

		this._watchAllEvents();

	}

	NodeAdapter.prototype = {

		getOptions: function () {
			return this._options;
		},

		update: function (item) {
			this._item = item;
			for (var p in item) {
				this._setProperty(p, item[p]);
			}
		},

		destroy: function () {
			var unwatches = this._unwatches;
			while (unwatches.length) unwatches.pop()();
		},

		/**
		 * Changes the value of a node attribute mapped from an item property.
		 * @param name {String} the name of the property
		 * @param value the new value of the property
		 */
		_setProperty: function (name, value) {
			var b, node, prop, current;

			b = this._getBindingsFor(name);

			// If there are no bindings for this name, there's
			// no way to divine what property to set.  Give up.
			if(!b) {
				return;
			} else if(b.to) {
				// HACK: Until we change the way bindings are done,
				// this allows binding data props to multiple things.

				// If there's a "to" override, then this binding
				// actually applies to the data property specified
				// by it.

				name = b.to;
			}

			node = this._getNode(b.node, name);

			if (node) {
				prop = 'prop' in b ? b.prop : guess.propForNode(node);
				current = guess.getNodePropOrAttr(node, prop);
				if (current !== value) {
					guess.setNodePropOrAttr(node, prop, value);
				}
			}
		},

		/**
		 * Returns the binding info for a node, if it exists.
		 * @param name {String} the name of the node
		 * @returns {Object} {
		 *     node: aNode,
		 *     prop: 'aProp',
		 *     events: 'event1,event2' // optional
		 * }
		 */
		_getBindingsFor: function (name) {
			var bindings, binding;

			bindings = this._options.bindings;
			if (bindings && name in bindings) {
				binding = bindings[name];
			}

			return binding;
		},

		_getNode: function (selector, name) {
			// TODO: cache querySelector lookups?
			var node;
			if (guess.isNode(selector)) {
				node = selector;
			}
			else if (selector) {
				node = this._options.querySelector(selector, this._rootNode);
			}
			if (!node) {
				node = guess.nodeByName(this._rootNode, name) || this._rootNode;
			}
			return node;
		},

		_watchAllEvents: function () {
			var name, binding, events, node, prop;

			for (name in this._options.bindings) {
				binding = this._options.bindings[name];

				if(binding.to) name = binding.to;

				node = this._getNode(binding.node, name);
				prop = binding.prop || guess.propForNode(node);
				events = binding.event || binding.events;
				if(events == null) {
					events = guess.eventsForNode(node);
				}

				if (events && node && prop) {
					this._watchEvents(node, events, name, prop);
				}
			}
		},

		_watchEvents: function (node, events, name, prop) {
			var self = this;

			this._unwatches.push(listenToNode(node, events, function () {
				var prev, curr;

				prev = self._item[name];
				curr = guess.getNodePropOrAttr(node, prop);

				if (prev !== curr) {
					self._item[name] = curr;
				}
			}));
		}

	};

	/**
	 * Tests whether the given object is a candidate to be handled by
	 * this adapter. Returns true if this is a DOMNode (or looks like one).
	 * @param obj
	 * @returns {Boolean}
	 */
	NodeAdapter.canHandle = function (obj) {
		// crude test if an object is a node.
		return obj && obj.tagName && obj.getAttribute && obj.setAttribute;
	};

	function listenToNode (node, events, callback) {

		var unwatchers, i;

		if (typeof events == 'string') {
			events = events.split(/\s*,\s*/);
		}
		else if (!events) {
			events = [];
		}

		// create unwatchers
		unwatchers = [];
		for (i = 0; i < events.length; i++) {
			unwatchers.push(watchNode(node, events[i], callback));
		}

		// create and return single unwatcher to unwatch all events
		return function () {
			var unwatch;
			while ((unwatch == unwatchers.pop())) squelchedUnwatch(unwatch);
		};

	}

	function squelchedUnwatch (unwatch) {
		try { unwatch(); } catch (ex) {}
	}

	return NodeAdapter;

});
}(
	typeof define == 'function'
		? define
		: function (factory) { module.exports = factory(require); }
));<|endoftext|>


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

/**
 * @fileoverview Definitions for W3C's Permissions Policy API and Feature Policy API.
 * @see https://w3c.github.io/webappsec-permissions-policy/
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy
 *
 * @externs
 * @author zhengwe@google.com (Zheng Wei)
 */

/**
 * @interface
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
function PermissionsPolicy() {}

/**
 * @param {string} feature
 * @param {string=} origin
 * @return {boolean}
 */
PermissionsPolicy.prototype.allowFeatures = function(feature, origin) {};

/**
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.features = function() {};

/**
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.allowedFeatures = function() {};

/**
 * @param {string} feature
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.getAllowlistForFeature = function(feature) {};

/**
 * @return {!PermissionsPolicy|undefined}
 */
Document.prototype.featurePolicy;

/**
 * @return {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
Document.prototype.permissionsPolicy;

/**
 * @type {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
HTMLIFrameElement.prototype.featurePolicy;

/**
 * @type {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
HTMLIFrameElement.prototype.permissionsPolicy;

<commit_msg>Correct some names and types in the externs for the `PermissionPolicy` object.<commit_after>/*
 * Copyright 2021 The Closure Compiler Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Definitions for W3C's Permissions Policy API and Feature Policy API.
 * @see https://w3c.github.io/webappsec-permissions-policy/
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Feature_Policy
 *
 * @externs
 * @author zhengwe@google.com (Zheng Wei)
 */

/**
 * @interface
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
function PermissionsPolicy() {}

/**
 * @param {string} feature
 * @param {string=} origin
 * @return {boolean}
 */
PermissionsPolicy.prototype.allowsFeature = function(feature, origin) {};

/**
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.features = function() {};

/**
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.allowedFeatures = function() {};

/**
 * @param {string} feature
 * @return {!Array<string>}
 */
PermissionsPolicy.prototype.getAllowlistForFeature = function(feature) {};

/**
 * @type {!PermissionsPolicy|undefined}
 */
Document.prototype.featurePolicy;

/**
 * @type {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
Document.prototype.permissionsPolicy;

/**
 * @type {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
HTMLIFrameElement.prototype.featurePolicy;

/**
 * @type {!PermissionsPolicy|undefined}
 * @see https://w3c.github.io/webappsec-permissions-policy/#the-policy-object
 */
HTMLIFrameElement.prototype.permissionsPolicy;

<|endoftext|>


<commit_before>//= require "../chrome/storage"

// shortcut method
var push = Array.prototype.push;

var Libraries = function () {
  this.init();

  this.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");

  // read from storage
  for (var i = 0; i < this.userSpecified.length; i++) {
    push.call(this, this.userSpecified[i]);
  }
};

Libraries.prototype.init = function () {
  var libs = {
    yui: {
      text: 'YUI',
      scripts: [
        { text: 'YUI 3.3.0', url: 'http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js'},
        { text: 'YUI 2.8.2', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.8.2/build/yuiloader/yuiloader-min.js'}
      ]
    },
    mootools: {
      text: 'MooTools',
      scripts: [
        { text: 'Mootools 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js'},
        { text: 'Mootools 1.2.4', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js' }
      ]
    },
    prototype: {
      text: 'Prototype',
      scripts: [
        { text: 'Prototype latest', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js' },
        { text: 'Prototype 1.7.0.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js'},
        { text: 'Prototype 1.6.1.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js' }
      ]
    },
    jquery: {
      text: 'jQuery',
      scripts: [
        { text: 'jQuery latest', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' },
        { text: 'jQuery WIP (via git)', url: 'http://code.jquery.com/jquery-git.js' },
        { text: 'jQuery 1.6.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' },
        { text: 'jQuery 1.5.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js' }
      ]
    },
    jqueryui : {
      text: 'jQuery UI',
      requires: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',
      style: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css',
      scripts: [
        { text: 'jQuery UI 1.8.13', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js' }
      ]
    },
    jquerymobile : {
      text: 'jQuery Mobile',
      requires: 'http://code.jquery.com/jquery-1.6.2.min.js',
      style: 'http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css',
      scripts: [
        { text: 'jQuery Mobile 1.0b2', url: 'http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js' },
        { text: 'jQuery Mobile 1.0a4.1', url: 'http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js' }
      ]
    },
    others: {
      text: 'Others',
      scripts: [
        { text: 'Modernizr 2.0.4', url: 'http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.4/modernizr.min.js' },
        { text: 'Processing 1.2.1', url: 'http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.2.1/processing-api.min.js' },
        { text: 'Raphaël 1.5.2', url: 'http://cdnjs.cloudflare.com/ajax/libs/raphael/1.5.2/raphael-min.js' },
        { text: 'underscore 1.1.6', url: 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.6/underscore-min.js' }
      ]
    },
    scriptaculous: {
      text: 'script.aculo.us',
      requires: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js',
      scripts: [
        { text: 'script.aculo.us 1.8.3', url: 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js' }
      ]
    },
    dojo : {
      text: 'Dojo',
      scripts: [
        { text: 'Dojo 1.6.0', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js' },
        { text: 'Dojo 1.4.1', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js' }
      ]
    }
    // ext : {
    //   text: 'Ext Core',
    //   style: 'http://extjs.cachefly.net/ext-2.2/resources/css/ext-all.css',
    //   scripts: [
    //     { text: 'Ext Core 3.1', url: 'http://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js' }
    //   ]
    // }
  },
  // NOTE if a new library category is added, you need to add it here
  order = 'jquery jqueryui jquerymobile prototype scriptaculous yui mootools dojo others'.split(' '),
  i = 0;

  this.length = 0; // triggers support for length prop
  for (i = 0; i < order.length; i++) {
    push.call(this, libs[order[i]]);
  }
};

Libraries.prototype.add = function (lib) {
  // save to localStorage
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  push.call(this, lib);
  $('#library').trigger('init');
};

Libraries.prototype.clear = function () {
  this.userSpecified = [];
  localStorage.removeItem('libraries');
  this.init();
  $('#library').trigger('init');
};

// OO based to all me to fiddle the object to resemble an array
var libraries = new Libraries();
window.libraries = libraries; // expose a command line API
<commit_msg>Added jQM b3<commit_after>//= require "../chrome/storage"

// shortcut method
var push = Array.prototype.push;

var Libraries = function () {
  this.init();

  this.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");

  // read from storage
  for (var i = 0; i < this.userSpecified.length; i++) {
    push.call(this, this.userSpecified[i]);
  }
};

Libraries.prototype.init = function () {
  var libs = {
    yui: {
      text: 'YUI',
      scripts: [
        { text: 'YUI 3.3.0', url: 'http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js'},
        { text: 'YUI 2.8.2', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.8.2/build/yuiloader/yuiloader-min.js'}
      ]
    },
    mootools: {
      text: 'MooTools',
      scripts: [
        { text: 'Mootools 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.3.2/mootools-yui-compressed.js'},
        { text: 'Mootools 1.2.4', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js' }
      ]
    },
    prototype: {
      text: 'Prototype',
      scripts: [
        { text: 'Prototype latest', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js' },
        { text: 'Prototype 1.7.0.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js'},
        { text: 'Prototype 1.6.1.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js' }
      ]
    },
    jquery: {
      text: 'jQuery',
      scripts: [
        { text: 'jQuery latest', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' },
        { text: 'jQuery WIP (via git)', url: 'http://code.jquery.com/jquery-git.js' },
        { text: 'jQuery 1.6.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' },
        { text: 'jQuery 1.5.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js' }
      ]
    },
    jqueryui : {
      text: 'jQuery UI',
      requires: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',
      style: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css',
      scripts: [
        { text: 'jQuery UI 1.8.13', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js' }
      ]
    },
    jquerymobile : {
      text: 'jQuery Mobile',
      requires: 'http://code.jquery.com/jquery-1.6.2.min.js',
      style: 'http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css',
      scripts: [
        { text: 'jQuery Mobile 1.0b3', url: 'http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js' },
        { text: 'jQuery Mobile 1.0b2', url: 'http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js' },
        { text: 'jQuery Mobile 1.0a4.1', url: 'http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js' }
      ]
    },
    others: {
      text: 'Others',
      scripts: [
        { text: 'Modernizr 2.0.4', url: 'http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.0.4/modernizr.min.js' },
        { text: 'Processing 1.2.1', url: 'http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.2.1/processing-api.min.js' },
        { text: 'Raphaël 1.5.2', url: 'http://cdnjs.cloudflare.com/ajax/libs/raphael/1.5.2/raphael-min.js' },
        { text: 'underscore 1.1.6', url: 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.1.6/underscore-min.js' }
      ]
    },
    scriptaculous: {
      text: 'script.aculo.us',
      requires: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js',
      scripts: [
        { text: 'script.aculo.us 1.8.3', url: 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js' }
      ]
    },
    dojo : {
      text: 'Dojo',
      scripts: [
        { text: 'Dojo 1.6.0', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js' },
        { text: 'Dojo 1.4.1', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js' }
      ]
    }
    // ext : {
    //   text: 'Ext Core',
    //   style: 'http://extjs.cachefly.net/ext-2.2/resources/css/ext-all.css',
    //   scripts: [
    //     { text: 'Ext Core 3.1', url: 'http://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js' }
    //   ]
    // }
  },
  // NOTE if a new library category is added, you need to add it here
  order = 'jquery jqueryui jquerymobile prototype scriptaculous yui mootools dojo others'.split(' '),
  i = 0;

  this.length = 0; // triggers support for length prop
  for (i = 0; i < order.length; i++) {
    push.call(this, libs[order[i]]);
  }
};

Libraries.prototype.add = function (lib) {
  // save to localStorage
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  push.call(this, lib);
  $('#library').trigger('init');
};

Libraries.prototype.clear = function () {
  this.userSpecified = [];
  localStorage.removeItem('libraries');
  this.init();
  $('#library').trigger('init');
};

// OO based to all me to fiddle the object to resemble an array
var libraries = new Libraries();
window.libraries = libraries; // expose a command line API
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
	//setting function
	init: function(x, y, settings) {
		//extending the function
		this._super(me.Entity, 'init', [x, y, {
			//setting the player image and its width and height
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",

			getShape: function(){
				//new shift
				//rectangle to make the character walk into it
				//setting it to the right size
				return (new me.Rect (0, 0, 64, 64)).toPolygon();
			}
		}]);
		//setting the velocity
		this.body.setVelocity(5, 20);
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//makes the player stand in idle position
		this.renderable.addAnimation("idle" , [78]);
		//makes the playeer walk in a cool animated way
		this.renderable.addAnimation("walk", [117, 118 , 119 , 120 , 121 , 122 , 123 , 124 , 125], 80);
		//
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		//when the player is not moving he is idle
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		//checking if the right key is pressed
		if (me.input.isKeyPressed("right")) {
			//adds to  the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);

			//if other key is pressed it wont work
		}
		 else if (me.input.isKeyPressed("left")){
		 	this.facing = "left";
        	this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		 else {
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
          this.jumping = true;
          this.body.vel.y -= this.body.accel.y * me.timer.tick;
    }

		if(this.body.vel.x !== 0) {

			if(me.input.isKeyPressed("attack")){
				if(!this.renderable.isCurrentAnimation("attack")){
					console.log(!this.renderable.isCurrentAnimation("attack"));
					this.renderable.setCurrentAnimation("attack" , "idle");
					this.renderable.setAnimationFrame();
					}
		        }
		        else if(this.body.vel.x !== 0){

		// states tat if the right key is pressed he is walkig
		if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
	}
}
// if he isnt walking then he is idle
       else {

	this.renderable.setCurrentAnimation("idle");
}
if(me.input.isKeyPressed("attack")){

	if(!this.renderable.isCurrentAnimation("attack")){
		console.log(!this.renderable.isCurrentAnimation("attack"));
		//sets the current animation to attack and once that is over
	//goes back to the idle animation
	this.renderable.setCurrentAnimation("attack" , "idle");
	//makes it so that the next time we start this sequence we begin
	//from the first animation, not wherever we left off when we
	//switched to another animation
	this.renderable.setAnimationFrame();
	}
}
        me.collision.check(this, true, this.collideHandler.bind(this), true);
		//updating the game
		this.body.update(delta);
// udated the player
//reaches to the constructor of Entity
		this._super(me.Entity, "update" , [delta]);
		return true;
		collideHandler: function(response) {
		if(response.b.type==='EnemyBaseEntity') {
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif " + xdif + " ydif " + ydif);

			if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}else if(xdif<70 && this.facing==='left' && xdif>0) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

			}
		}
	}
});

// settings for the players base
game.PlayerBaseEntity = me.Entity.extend ({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			//adding the tower image , and setting its size
             image: "tower",
             width: 100,
             height: 100,
             spritewidth: "100",
             spriteheight: "100",
             getShape: function() {
             	//setting the rectangle thats for the tower
             	return (new me.Rect(0, 0, 100, 80)).toPolygon();
             }
		}]);
        //the health of the power .. if you hit it more than 10 times , then it will blow up
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		// ,akes the tower colidable
		this.body.onCollision = this.onCollision.bind(this);
// declares what type of entity
		this.type = "PlayerBaseEntity";
// classes that animate my bases
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//the tower when it has no hits yet , (health is at 0 )
           if(this.health<=0) {
           	this.broken = true;
            this.renderable.setCurrentAnimation("broken");
           }
           this.body.update(delta);
           // updates when or if the base is hit
           this._super(me.Entity, "update", [delta]);
           return true;
	},

	onCollision: function() {

	}

});

//setting for the enemy base
game.EnemyBaseEntity = me.Entity.extend ({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
             //adding the tower image , and setting its size
             image: "tower",
             width: 100,
             height: 100,
             spritewidth: "100",
             spriteheight: "100",
             getShape: function() {
             	//setting the rectangle thats for the tower
             	return (new me.Rect(0, 0, 100, 80)).toPolygon();
             }
		}]);
        //the health of the power .. if you hit it more than 10 times , then it will blow up
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
/// classses that animate my base
		this.renderable.addAnimation("idle" , [0]);
		this.renderable.addAnimation("broken" , [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		// if the halth is less or = to 0 it will show the animated base being destroyed
           if(this.health<=0) {
           	this.broken = true;
           	this.renderable.setCurrentAnimation("broken");

           }
           this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function() {

	}

});<commit_msg>finished 16<commit_after>game.PlayerEntity = me.Entity.extend({
	//setting function
	init: function(x, y, settings) {
		//extending the function
		this._super(me.Entity, 'init', [x, y, {
			//setting the player image and its width and height
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",

			getShape: function(){
				//new shift
				//rectangle to make the character walk into it
				//setting it to the right size
				return (new me.Rect (0, 0, 64, 64)).toPolygon();
			}
		}]);
		//setting the velocity
		this.body.setVelocity(5, 20);
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//makes the player stand in idle position
		this.renderable.addAnimation("idle" , [78]);
		//makes the playeer walk in a cool animated way
		this.renderable.addAnimation("walk", [117, 118 , 119 , 120 , 121 , 122 , 123 , 124 , 125], 80);
		//
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		//when the player is not moving he is idle
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		//checking if the right key is pressed
		if (me.input.isKeyPressed("right")) {
			//adds to  the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);

			//if other key is pressed it wont work
		}
		 else if (me.input.isKeyPressed("left")){
		 	this.facing = "left";
        	this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		 else {
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
          this.jumping = true;
          this.body.vel.y -= this.body.accel.y * me.timer.tick;
    }

		if(this.body.vel.x !== 0) {

			if(me.input.isKeyPressed("attack")){
				if(!this.renderable.isCurrentAnimation("attack")){
					console.log(!this.renderable.isCurrentAnimation("attack"));
					this.renderable.setCurrentAnimation("attack" , "idle");
					this.renderable.setAnimationFrame();
					}
		        }
		        else if(this.body.vel.x !== 0){

		// states tat if the right key is pressed he is walkig
		if(!this.renderable.isCurrentAnimation("walk")){
			this.renderable.setCurrentAnimation("walk");
	}
}
// if he isnt walking then he is idle
       else {

	this.renderable.setCurrentAnimation("idle");
}
if(me.input.isKeyPressed("attack")){

	if(!this.renderable.isCurrentAnimation("attack")){
		console.log(!this.renderable.isCurrentAnimation("attack"));
		//sets the current animation to attack and once that is over
	//goes back to the idle animation
	this.renderable.setCurrentAnimation("attack" , "idle");
	//makes it so that the next time we start this sequence we begin
	//from the first animation, not wherever we left off when we
	//switched to another animation
	this.renderable.setAnimationFrame();
	}
}
        me.collision.check(this, true, this.collideHandler.bind(this), true);
		//updating the game
		this.body.update(delta);
// udated the player
//reaches to the constructor of Entity
		this._super(me.Entity, "update" , [delta]);
		return true;
		collideHandler: function(response) {
		if(response.b.type==='EnemyBaseEntity') {
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif " + xdif + " ydif " + ydif);

			if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}else if(xdif<70 && this.facing==='left' && xdif>0) {
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;

 //			}
		}
	}
});

// settings for the players base
game.PlayerBaseEntity = me.Entity.extend ({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			//adding the tower image , and setting its size
             image: "tower",
             width: 100,
             height: 100,
             spritewidth: "100",
             spriteheight: "100",
             getShape: function() {
             	//setting the rectangle thats for the tower
             	return (new me.Rect(0, 0, 100, 80)).toPolygon();
             }
		}]);
        //the health of the power .. if you hit it more than 10 times , then it will blow up
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		// ,akes the tower colidable
		this.body.onCollision = this.onCollision.bind(this);
// declares what type of entity
		this.type = "PlayerBaseEntity";
// classes that animate my bases
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//the tower when it has no hits yet , (health is at 0 )
           if(this.health<=0) {
           	this.broken = true;
            this.renderable.setCurrentAnimation("broken");
           }
           this.body.update(delta);
           // updates when or if the base is hit
           this._super(me.Entity, "update", [delta]);
           return true;
	},

	onCollision: function() {

	}

});

//setting for the enemy base
game.EnemyBaseEntity = me.Entity.extend ({
	init : function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
             //adding the tower image , and setting its size
             image: "tower",
             width: 100,
             height: 100,
             spritewidth: "100",
             spriteheight: "100",
             getShape: function() {
             	//setting the rectangle thats for the tower
             	return (new me.Rect(0, 0, 100, 80)).toPolygon();
             }
		}]);
        //the health of the power .. if you hit it more than 10 times , then it will blow up
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
/// classses that animate my base
		this.renderable.addAnimation("idle" , [0]);
		this.renderable.addAnimation("broken" , [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		// if the halth is less or = to 0 it will show the animated base being destroyed
           if(this.health<=0) {
           	this.broken = true;
           	this.renderable.setCurrentAnimation("broken");

           }
           this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function() {

	}

});<|endoftext|>


<commit_before>var BirdEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('clumsy');
        settings.width = 85;
        settings.height = 60;

        settings.spritewidth = 72;///need to fix
        settings.spriteheight= 48;///need to fix

        settings.framewidth = 85;
        settings.frameheight = 60;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0.2;
        this.gravityForce = 0.01;
        this.maxAngleRotation = Number.prototype.degToRad(30);
        this.maxAngleRotationDown = Number.prototype.degToRad(90);
        this.renderable.addAnimation("flying", [0, 1, 2]);
        this.renderable.addAnimation("idle", [0]);
        this.renderable.setCurrentAnimation("flying");
        this.renderable.anchorPoint = new me.Vector2d(0.1, 0.5);
        // manually add a rectangular collision shape
        this.body.removeShapeAt(0);
        this.body.addShape(new me.Ellipse(5, 5, 71, 51));

        // a tween object for the flying physic effect
        this.flyTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);

        // end animation tween
        this.endTween = null;

        // collision shape
        this.collided = false;
    },

    update: function(dt) {
        // mechanics

        if (!game.data.start) {
            return this._super(me.Entity, 'update', [dt]);
        }
        if (me.input.isKeyPressed('fly')) {
            me.audio.play('wing');
            this.gravityForce = 0.02;
            var currentPos = this.pos.y;
            // stop the previous tweens
            this.flyTween.stop();
            this.flyTween.to({y: currentPos - 72}, 50);
            this.flyTween.start();
            this.renderable.angle = -this.maxAngleRotation;
        } else {
            this.gravityForce += 0.2;
            this.pos.y += me.timer.tick * this.gravityForce;
            this.renderable.angle += Number.prototype.degToRad(0.5) * this.gravityForce;
            if (this.renderable.angle > this.maxAngleRotationDown)
                this.renderable.angle = this.maxAngleRotationDown;
        }
        me.Rect.prototype.updateBounds.apply(this);

        var hitSky = -80; // bird height + 20px
        if (this.pos.y <= hitSky || this.collided) {
            game.data.start = false;
            me.audio.play("lose");
            this.endAnimation();
            return false;
        }
        me.collision.check(this);
        this._super(me.Entity, 'update', [dt]);
        return true;
    },

    onCollision: function(response) {
        var obj = response.b;
        if (obj.type === 'pipe' || obj.type === 'ground') {
            me.device.vibrate(500);
            this.collided = true;
        }
        // remove the hit box
        if (obj.type === 'hit') {
            me.game.world.removeChildNow(obj);
            game.data.steps++;
            me.audio.play('hit');
            this.pos.x = 60;
        }
    },

    endAnimation: function() {
        me.game.viewport.fadeOut("#fff", 100);
        var currentPos = this.renderable.pos.y;
        this.endTween = new me.Tween(this.renderable.pos);
        this.endTween.easing(me.Tween.Easing.Exponential.InOut);

        this.flyTween.stop();
        this.renderable.angle = this.maxAngleRotationDown;
        var finalPos = me.video.renderer.getHeight() - this.renderable.width/2 - 96;
        this.endTween
            .to({y: currentPos}, 1000)
            .to({y: finalPos}, 1000)
            .onComplete(function() {
                me.state.change(me.state.GAME_OVER);
            });
        this.endTween.start();
    }

});

/*var RainbowEntity = me.Entity.extend({
   init: function(x,y,angle) {
        var settings = {};
        settings.image = me.loader.getImage('rainbow');
        settings.width = 20;
        settings.height = 36;
        this._super(me.Entity,'init',[x,y,settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-6,0);
        this.body.addShape(new me.Rect(0,0,settings.width,settings.height));
        this.renderable.angle = angle;
        this.body.collisionType = me.collision.types.NO_OBJECT;
        this.type = 'rainbow';

    },

*/

var PipeEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = this.image = me.loader.getImage('pipe');
        settings.width = 148;
        settings.height= 1664;
        settings.framewidth = 148;
        settings.frameheight = 1664;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-5, 0);
        this.type = 'pipe';
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this._super(me.Entity, 'update', [dt]);
        }
        this.pos.add(this.body.vel);
        if (this.pos.x < -this.image.width) {
            me.game.world.removeChild(this);
        }
        me.Rect.prototype.updateBounds.apply(this);
        this._super(me.Entity, 'update', [dt]);
        return true;
    },

});

var PipeGenerator = me.Renderable.extend({
    init: function() {
        this._super(me.Renderable, 'init', [0, me.game.viewport.width, me.game.viewport.height]);
        this.alwaysUpdate = true;
        this.generate = 0;
        this.pipeFrequency = 92;
        this.pipeHoleSize = 1240;
        this.posX = me.game.viewport.width;
    },

    update: function(dt) {
        if (this.generate++ % this.pipeFrequency == 0) {
            var posY = Number.prototype.random(
                    me.video.renderer.getHeight() - 100,
                    200
            );
            var posY2 = posY - me.video.renderer.getHeight() - this.pipeHoleSize;
            var pipe1 = new me.pool.pull('pipe', this.posX, posY);
            var pipe2 = new me.pool.pull('pipe', this.posX, posY2);
            var hitPos = posY - 100;
            var hit = new me.pool.pull("hit", this.posX, hitPos);
            pipe1.renderable.flipY(true);
            me.game.world.addChild(pipe1, 10);
            me.game.world.addChild(pipe2, 10);
            me.game.world.addChild(hit, 11);
        }
        this._super(me.Entity, "update", [dt]);
        return true;
    },

});

var HitEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = this.image = me.loader.getImage('hit');
        settings.width = 148;
        settings.height= 60;
        settings.framewidth = 148;
        settings.frameheight = 60;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.updateTime = false;
        this.renderable.alpha = 0;
        this.body.accel.set(-5, 0);
        this.body.removeShapeAt(0);
        this.body.addShape(new me.Rect(0, 0, settings.width - 30, settings.height - 30));
        this.type = 'hit';
    },

    update: function(dt) {
        // mechanics
        this.pos.add(this.body.accel);
        if (this.pos.x < -this.image.width) {
            me.game.world.removeChild(this);
        }
        me.Rect.prototype.updateBounds.apply(this);
        this._super(me.Entity, "update", [dt]);
        return true;
    },

});

var Ground = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('ground');
        settings.width = 900;
        settings.height= 96;
        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-4, 0);
        this.type = 'ground';
    },

    update: function(dt) {
        // mechanics
        this.pos.add(this.body.vel);
        if (this.pos.x < -this.renderable.width) {
            this.pos.x = me.video.renderer.getWidth() - 10;
        }
        me.Rect.prototype.updateBounds.apply(this);
        return this._super(me.Entity, 'update', [dt]);
    },

});
<commit_msg>steps to score<commit_after>var BirdEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('clumsy');
        settings.width = 85;
        settings.height = 60;

        settings.spritewidth = 72;///need to fix
        settings.spriteheight= 48;///need to fix

        settings.framewidth = 85;
        settings.frameheight = 60;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0.2;
        this.gravityForce = 0.01;
        this.maxAngleRotation = Number.prototype.degToRad(30);
        this.maxAngleRotationDown = Number.prototype.degToRad(90);
        this.renderable.addAnimation("flying", [0, 1, 2]);
        this.renderable.addAnimation("idle", [0]);
        this.renderable.setCurrentAnimation("flying");
        this.renderable.anchorPoint = new me.Vector2d(0.1, 0.5);
        // manually add a rectangular collision shape
        this.body.removeShapeAt(0);
        this.body.addShape(new me.Ellipse(5, 5, 71, 51));

        // a tween object for the flying physic effect
        this.flyTween = new me.Tween(this.pos);
        this.flyTween.easing(me.Tween.Easing.Exponential.InOut);

        // end animation tween
        this.endTween = null;

        // collision shape
        this.collided = false;
    },

    update: function(dt) {
        // mechanics

        if (!game.data.start) {
            return this._super(me.Entity, 'update', [dt]);
        }
        if (me.input.isKeyPressed('fly')) {
            me.audio.play('wing');
            this.gravityForce = 0.02;
            var currentPos = this.pos.y;
            // stop the previous tweens
            this.flyTween.stop();
            this.flyTween.to({y: currentPos - 72}, 50);
            this.flyTween.start();
            this.renderable.angle = -this.maxAngleRotation;
        } else {
            this.gravityForce += 0.2;
            this.pos.y += me.timer.tick * this.gravityForce;
            this.renderable.angle += Number.prototype.degToRad(0.5) * this.gravityForce;
            if (this.renderable.angle > this.maxAngleRotationDown)
                this.renderable.angle = this.maxAngleRotationDown;
        }
        me.Rect.prototype.updateBounds.apply(this);

        var hitSky = -80; // bird height + 20px
        if (this.pos.y <= hitSky || this.collided) {
            game.data.start = false;
            me.audio.play("lose");
            this.endAnimation();
            return false;
        }
        me.collision.check(this);
        this._super(me.Entity, 'update', [dt]);
        return true;
    },

    onCollision: function(response) {
        var obj = response.b;
        if (obj.type === 'pipe' || obj.type === 'ground') {
            me.device.vibrate(500);
            this.collided = true;
        }
        // remove the hit box
        if (obj.type === 'hit') {
            me.game.world.removeChildNow(obj);
            game.data.steps++;
            me.audio.play('hit');
            this.pos.x = 60;
        }
    },

    endAnimation: function() {
        me.game.viewport.fadeOut("#fff", 100);
        var currentPos = this.renderable.pos.y;
        this.endTween = new me.Tween(this.renderable.pos);
        this.endTween.easing(me.Tween.Easing.Exponential.InOut);

        this.flyTween.stop();
        this.renderable.angle = this.maxAngleRotationDown;
        var finalPos = me.video.renderer.getHeight() - this.renderable.width/2 - 96;
        this.endTween
            .to({y: currentPos}, 1000)
            .to({y: finalPos}, 1000)
            .onComplete(function() {
                me.state.change(me.state.GAME_OVER);
            });
        this.endTween.start();
    }

});

/*

var RainbowEntity = me.Entity.extend({
   init: function(x,y,angle) {
        var settings = {};
        settings.image = me.loader.getImage('rainbow');
        settings.width = 20;
        settings.height = 36;
        this._super(me.Entity,'init',[x,y,settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-6,0);
        this.body.addShape(new me.Rect(0,0,settings.width,settings.height));
        this.renderable.angle = angle;
        this.body.collisionType = me.collision.types.NO_OBJECT;
        this.type = 'rainbow';

    },
    update: function(dt) {
        this.pos.add(this.body.vel);
        if (this.pos.x < -this.renderable.width) {
            this.pos.x = me.video.renderer.getWidth() - 10;
        if(this.pos.x < -this.renderable.width) {
            me.game.world.removeChild(this);
        }
        this.updateBounds();
        return this._super(me.Entity, 'update', [dt]);
    },
    },
});
*/

var PipeEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = this.image = me.loader.getImage('pipe');
        settings.width = 148;
        settings.height= 1664;
        settings.framewidth = 148;
        settings.frameheight = 1664;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-5, 0);
        this.type = 'pipe';
    },

    update: function(dt) {
        // mechanics
        if (!game.data.start) {
            return this._super(me.Entity, 'update', [dt]);
        }
        this.pos.add(this.body.vel);
        if (this.pos.x < -this.image.width) {
            me.game.world.removeChild(this);
        }
        me.Rect.prototype.updateBounds.apply(this);
        this._super(me.Entity, 'update', [dt]);
        return true;
    },

});

var PipeGenerator = me.Renderable.extend({
    init: function() {
        this._super(me.Renderable, 'init', [0, me.game.viewport.width, me.game.viewport.height]);
        this.alwaysUpdate = true;
        this.generate = 0;
        this.pipeFrequency = 92;
        this.pipeHoleSize = 1240;
        this.posX = me.game.viewport.width;
    },

    update: function(dt) {
        if (this.generate++ % this.pipeFrequency == 0) {
            var posY = Number.prototype.random(
                    me.video.renderer.getHeight() - 100,
                    200
            );
            var posY2 = posY - me.video.renderer.getHeight() - this.pipeHoleSize;
            var pipe1 = new me.pool.pull('pipe', this.posX, posY);
            var pipe2 = new me.pool.pull('pipe', this.posX, posY2);
            var hitPos = posY - 100;
            var hit = new me.pool.pull("hit", this.posX, hitPos);
            pipe1.renderable.flipY(true);
            me.game.world.addChild(pipe1, 10);
            me.game.world.addChild(pipe2, 10);
            me.game.world.addChild(hit, 11);
        }
        this._super(me.Entity, "update", [dt]);
        return true;
    },

});

var HitEntity = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = this.image = me.loader.getImage('hit');
        settings.width = 148;
        settings.height= 60;
        settings.framewidth = 148;
        settings.frameheight = 60;

        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.updateTime = false;
        this.renderable.alpha = 0;
        this.body.accel.set(-5, 0);
        this.body.removeShapeAt(0);
        this.body.addShape(new me.Rect(0, 0, settings.width - 30, settings.height - 30));
        this.type = 'hit';
    },

    update: function(dt) {
        // mechanics
        this.pos.add(this.body.accel);
        if (this.pos.x < -this.image.width) {
            me.game.world.removeChild(this);
        }
        me.Rect.prototype.updateBounds.apply(this);
        this._super(me.Entity, "update", [dt]);
        return true;
    },

});

var Ground = me.Entity.extend({
    init: function(x, y) {
        var settings = {};
        settings.image = me.loader.getImage('ground');
        settings.width = 900;
        settings.height= 96;
        this._super(me.Entity, 'init', [x, y, settings]);
        this.alwaysUpdate = true;
        this.body.gravity = 0;
        this.body.vel.set(-4, 0);
        this.type = 'ground';
    },

    update: function(dt) {
        // mechanics
        this.pos.add(this.body.vel);
        if (this.pos.x < -this.renderable.width) {
            this.pos.x = me.video.renderer.getWidth() - 10;
        }
        me.Rect.prototype.updateBounds.apply(this);
        return this._super(me.Entity, 'update', [dt]);
    },

});
<|endoftext|>


<commit_before> game.PlayerEntity = me.Entity.extend({
 	init: function(x, y, settings) {
    	this._super(me.Entity, 'init', [x, y, {
    		image: "player",
    	  	width: 64,
    	  	height: 64,
    	  	spritewidth: "64",
    	  	spriteheight: "64",

    	  	getShape: function() {
    	  		return(new me.Rect(0, 0, 64, 64)).toPolygon();
    	  	}
		}]);

    	this.body.setVelocity(5, 20);

    	this.renderable.addAnimation("idle", [78]);
    	this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    	this.renderable.setCurrentAnimation("idle");

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
 	},

 	    update: function(delta){

   		 	if(me.input.isKeyPressed ("right")){
 	         	// sets position of my x by adding the velocity defined above in setvelocity() and multiplying it by me.timer.tick
 	        	this.body.vel.x += this.body.accel.x * me.timer.tick;
 	        	this.flipX(true);
 	        }else{
              this.body.vel.x = 0;
 	      }

 	        if(me.input.isKeyPressed("attack")){
 	      	  if(!this.renderable.isCurrentAnimation("attack")){
 	      	    console.log(!this.renderable.isCurrentAnimation("attack")){
 	      		// sets the current animation to attack and once it is over, goes back to idle animation
 	      		this.renderable.setCurrentAnimation("attack", "idle");
 	      		// the line of code below makes it so that, this sequence, we begin from the first animation, not wherever we left off when we switched
 	      		this.renderable.setAnimationFrame();
 	      }

 	    }

          else if(this.body.vel.x !== 0){
             if(!this.renderable.isCurrentAnimation("walk")){
          	 this.renderable.setCurrentAnimation("walk");

            }

          }else{
             this.renderable.setCurrentAnimation("idle");

          }

 	      if(me.input.isKeyPressed("attack")){
 	      	if(!this.renderable.isCurrentAnimation("attack")){
 	      	    console.log(!this.renderable.isCurrentAnimation("attack")){
 	      		// sets the current animation to attack and once it is over, goes back to idle animation
 	      		this.renderable.setCurrentAnimation("attack", "idle");
 	      		// the line of code below makes it so that, this sequence, we begin from the first animation, not wherever we left off when we switched
 	      		this.renderable.setAnimationFrame();
 	      }

 	    }

 	       this.body.update(delta);

 	       this._super(me.Entity, "update", [delta]);
 	       return true;
 	    }
   });

// END OF UPDATE FUNCTION ABOVE!!!!!!

 //the reason why this is a class, it gets to have both letters be capital
 // the init: is our constructor function
 // for entities it wants 3 parameters
 // the difference between the spriteheight and width vs the regular height and width is that sprite width and sprite height are passing the main info.
 // the regular width and the height is telling the screen what ammount of space to preserve
// this is for the player to move right
//velocity represnts our current position
// me.timer.tick makes the movement look smooth
//adds to the position of my x by the velocity defined above
//delta is the change in time that has happened
//the speed is 80 miliseconds
// what the If (!this statment is saying is, that we dont want to start the walk animation, if we are already walking
//// if we dont add this line the animations wont be able to animate on the fly
// this.flipX fixes the characters turning
game.PlayerBaseEntity = me.Entity.extend ({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function (){
				return (new me.Rect(0, 0, 100, 80)).toPolygon();
			}

	}]);
    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);
    this.renderable.addAnimation("idle", [0]);
    this.renderable.addAnimation("broken", [1]);
    this.renderable.setCurrentAnimation("idle");
    this.type = "PlayerBaseEntity";

},

  update:function(delta){
  	if(this.health<=0) {
  		this.broken = true;
  		this.renderable.setCurrentAnimation("broken");
  	}
  	this.body.update(delta);

  	this._super(me.Entity, "update", [delta]);
  	return true;

  },

  onCollision: function(){

  }

});

game.EnemyBaseEntity = me.Entity.extend ({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function (){
				return (new me.Rect(0, 0, 100, 80)).toPolygon();
			}

	}]);

    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);
    this.renderable.addAnimation("idle", [0]);
    this.renderable.addAnimation("broken", [1]);
    this.renderable.setCurrentAnimation("idle");
    this.type = "EnemyBaseEntity";

},

  update:function(delta){
  	if(this.health<=0) {
  		this.broken = true;
  		this.renderable.setCurrentAnimation("Broken");
  	}
  	this.body.update(delta);

  	this._super(me.Entity, "update", [delta]);
  	return true;

  },

  onCollision: function(){

  }

});

//This.broken is the variable we make to say that the tower is not destroyed
//this.health represents how much health you begin with
//this.type is for later collisions
//what the if statement does, is it looks at your health and determines if you are dead
// always call the super in update functions
//we then set the animations on the player and enemy base
// when we break the tower we want to set the animation to broken
//renderable is a class that they built in melon js, we use it to do most animations
//me.game.viewport allows us to follow the player<commit_msg>GOT THE ATTACK FUNCTION TO WORK ! FINALLY<commit_after> game.PlayerEntity = me.Entity.extend({
 	init: function(x, y, settings) {
    	this._super(me.Entity, 'init', [x, y, {
    		image: "player",
    	  	width: 64,
    	  	height: 64,
    	  	spritewidth: "64",
    	  	spriteheight: "64",

    	  	getShape: function() {
    	  		return(new me.Rect(0, 0, 64, 64)).toPolygon();
    	  	}
		}]);

    	this.body.setVelocity(5, 20);

    	this.renderable.addAnimation("idle", [78]);
    	this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
    	this.renderable.setCurrentAnimation("idle");

        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
 	},

 	    update: function(delta){

   		 	if(me.input.isKeyPressed ("right")){
 	         	// sets position of my x by adding the velocity defined above in setvelocity() and multiplying it by me.timer.tick
 	        	this.body.vel.x += this.body.accel.x * me.timer.tick;
 	        	this.flipX(true);
 	        }else{
              this.body.vel.x = 0;
 	      }

 	        if(me.input.isKeyPressed("attack")){
 	      	  if(!this.renderable.isCurrentAnimation("attack")){
 	      	    console.log(!this.renderable.isCurrentAnimation("attack"));
 	      		// sets the current animation to attack and once it is over, goes back to idle animation
 	      		this.renderable.setCurrentAnimation("attack", "idle");
 	      		// the line of code below makes it so that, this sequence, we begin from the first animation, not wherever we left off when we switched
 	      		this.renderable.setAnimationFrame();
 	      }

 	    }

          else if(this.body.vel.x !== 0){
             if(!this.renderable.isCurrentAnimation("walk")){
          	   this.renderable.setCurrentAnimation("walk");

            }

          }else{
             this.renderable.setCurrentAnimation("idle");

          }

 	      if(me.input.isKeyPressed("attack")){
 	      	if(!this.renderable.isCurrentAnimation("attack")){
 	      	    console.log(!this.renderable.isCurrentAnimation("attack"));
 	      		// sets the current animation to attack and once it is over, goes back to idle animation
 	      		this.renderable.setCurrentAnimation("attack", "idle");
 	      		// the line of code below makes it so that, this sequence, we begin from the first animation, not wherever we left off when we switched
 	      		this.renderable.setAnimationFrame();
 	      }

 	    }

 	       this.body.update(delta);

 	       this._super(me.Entity, "update", [delta]);
 	       return true;
 	    }
   });

// END OF UPDATE FUNCTION ABOVE!!!!!!

 //the reason why this is a class, it gets to have both letters be capital
 // the init: is our constructor function
 // for entities it wants 3 parameters
 // the difference between the spriteheight and width vs the regular height and width is that sprite width and sprite height are passing the main info.
 // the regular width and the height is telling the screen what ammount of space to preserve
// this is for the player to move right
//velocity represnts our current position
// me.timer.tick makes the movement look smooth
//adds to the position of my x by the velocity defined above
//delta is the change in time that has happened
//the speed is 80 miliseconds
// what the If (!this statment is saying is, that we dont want to start the walk animation, if we are already walking
//// if we dont add this line the animations wont be able to animate on the fly
// this.flipX fixes the characters turning
game.PlayerBaseEntity = me.Entity.extend ({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function (){
				return (new me.Rect(0, 0, 100, 80)).toPolygon();
			}

	}]);
    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);
    this.renderable.addAnimation("idle", [0]);
    this.renderable.addAnimation("broken", [1]);
    this.renderable.setCurrentAnimation("idle");
    this.type = "PlayerBaseEntity";

},

  update:function(delta){
  	if(this.health<=0) {
  		this.broken = true;
  		this.renderable.setCurrentAnimation("broken");
  	}
  	this.body.update(delta);

  	this._super(me.Entity, "update", [delta]);
  	return true;

  },

  onCollision: function(){

  }

});

game.EnemyBaseEntity = me.Entity.extend ({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function (){
				return (new me.Rect(0, 0, 100, 80)).toPolygon();
			}

	}]);

    this.broken = false;
    this.health = 10;
    this.alwaysUpdate = true;
    this.body.onCollision = this.onCollision.bind(this);
    this.renderable.addAnimation("idle", [0]);
    this.renderable.addAnimation("broken", [1]);
    this.renderable.setCurrentAnimation("idle");
    this.type = "EnemyBaseEntity";

},

  update:function(delta){
  	if(this.health<=0) {
  		this.broken = true;
  		this.renderable.setCurrentAnimation("Broken");
  	}
  	this.body.update(delta);

  	this._super(me.Entity, "update", [delta]);
  	return true;

  },

  onCollision: function(){

  }

});

//This.broken is the variable we make to say that the tower is not destroyed
//this.health represents how much health you begin with
//this.type is for later collisions
//what the if statement does, is it looks at your health and determines if you are dead
// always call the super in update functions
//we then set the animations on the player and enemy base
// when we break the tower we want to set the animation to broken
//renderable is a class that they built in melon js, we use it to do most animations
//me.game.viewport allows us to follow the player<|endoftext|>


<commit_before>define(['angular', 'angularMocks'], function (ng) {
	'use strict';

	describe('products controller', function () {

		var ctrlr,
			prodService,
			prodFactory,
			rootScope,
			scope,
			location;

		beforeEach(ng.mock.module('app'));

		beforeEach(ng.mock.inject(function ($rootScope, $controller, $location, productServices, productFactory) {

			rootScope = $rootScope;
			scope = $rootScope.$new();
			location = $location;
			prodService = productServices;
			prodFactory = productFactory;

			location.path('/');

			ctrlr = $controller('productsController', {
				'$scope': scope
			});

			spyOn(scope, 'addToCart').and.callThrough();
			spyOn(scope, '$emit');
			spyOn(prodService, 'isDuplicateOrder').and.callThrough();
			spyOn(prodService, 'addToCart').and.callThrough();
			spyOn(prodFactory, 'getProductsByKeyword').and.callThrough();
			spyOn(prodFactory, 'getAllProducts').and.callThrough();

		}));

		it('should show it is initialized with default path \'/\'', function () {

			expect(location.path()).toBe('/');
			expect(scope.showSearchResult).toBeFalsy();
		});

		it('should show products are defined', function () {

			expect(scope.products).toBeDefined();

		});

		it('should show there is at least 1 product', function () {

			expect(scope.products.length).toBeGreaterThan(1);

		});

		// test data
		var testProduct = {
				id: 123,
				name: 'test123',
				price: 23.99,
				category: 'animal',
				description: 'description description description.'
			};

		it('should call isDuplicateOrder and addToCart when new order does not match hitory', function () {

			rootScope.orders = [];
			scope.addToCart(testProduct);
			scope.$digest();

			expect(scope.addToCart).toHaveBeenCalled();
			expect(prodService.isDuplicateOrder).toHaveBeenCalled();
			expect(prodService.addToCart).toHaveBeenCalled();
			expect(scope.$emit).toHaveBeenCalled();

		});

		it('should call isDuplicateOrder but not addToCart when new order matches hitory', function () {

			rootScope.orders = [testProduct];
			scope.addToCart(testProduct);
			scope.$digest();

			expect(scope.addToCart).toHaveBeenCalled();
			expect(prodService.isDuplicateOrder).toHaveBeenCalled();
			expect(prodService.addToCart).not.toHaveBeenCalled();
			expect(scope.$emit).not.toHaveBeenCalled();

		});

		it('should search for all 3 products in \'sport\' category and 2 products with number \'5\'', ng.mock.inject(function ($controller) {

			location.path('/search');

			var searchKeyword = 'spor 5',
				anotherScope = rootScope.$new(),
				ctrl = $controller('productsController', {
					$scope: anotherScope,
					$routeParams: {
						query: searchKeyword
					}
				});

			expect(prodFactory.getProductsByKeyword).toHaveBeenCalled();
			expect(anotherScope.products).toBeDefined();
			expect(anotherScope.products.length).toEqual(5);

		}));
	});
});
<commit_msg>products controller update<commit_after>define(['angular', 'angularMocks'], function (ng) {
	'use strict';

	describe('products controller', function () {

		var ctrlr,
			prodService,
			prodFactory,
			rootScope,
			scope,
			location;

		beforeEach(ng.mock.module('app'));

		beforeEach(ng.mock.inject(function ($rootScope, $controller, $location, productServices, productFactory) {

			rootScope = $rootScope;
			scope = $rootScope.$new();
			location = $location;
			prodService = productServices;
			prodFactory = productFactory;

			location.path('/');

			ctrlr = $controller('productsController', {
				'$scope': scope
			});

			spyOn(scope, 'addToCart').and.callThrough();
			spyOn(scope, '$emit');
			spyOn(prodService, 'isDuplicateOrder').and.callThrough();
			spyOn(prodService, 'addToCart').and.callThrough();
			spyOn(prodFactory, 'getProductsByKeyword').and.callThrough();

		}));

		it('should show it is initialized with default path \'/\'', function () {

			expect(location.path()).toBe('/');
			expect(scope.showSearchResult).toBeFalsy();
		});

		it('should show products are defined', function () {

			expect(scope.products).toBeDefined();

		});

		it('should show there is at least 1 product', function () {

			expect(scope.products.length).toBeGreaterThan(1);

		});

		// test data
		var testProduct = {
				id: 123,
				name: 'test123',
				price: 23.99,
				category: 'animal',
				description: 'description description description.'
			};

		it('should call isDuplicateOrder and addToCart when new order does not match hitory', function () {

			rootScope.orders = [];
			scope.addToCart(testProduct);
			scope.$digest();

			expect(scope.addToCart).toHaveBeenCalled();
			expect(prodService.isDuplicateOrder).toHaveBeenCalled();
			expect(prodService.addToCart).toHaveBeenCalled();
			expect(scope.$emit).toHaveBeenCalled();

		});

		it('should call isDuplicateOrder but not addToCart when new order matches hitory', function () {

			rootScope.orders = [testProduct];
			scope.addToCart(testProduct);
			scope.$digest();

			expect(scope.addToCart).toHaveBeenCalled();
			expect(prodService.isDuplicateOrder).toHaveBeenCalled();
			expect(prodService.addToCart).not.toHaveBeenCalled();
			expect(scope.$emit).not.toHaveBeenCalled();

		});

		it('should search for all 3 products in \'sport\' category and 2 products with number \'5\'', ng.mock.inject(function ($controller) {

			location.path('/search');

			var searchKeyword = 'spor 5',
				anotherScope = rootScope.$new(),
				ctrl = $controller('productsController', {
					$scope: anotherScope,
					$routeParams: {
						query: searchKeyword
					}
				});

			expect(prodFactory.getProductsByKeyword).toHaveBeenCalled();
			expect(anotherScope.products).toBeDefined();
			expect(anotherScope.products.length).toEqual(5);

		}));
	});
});
<|endoftext|>


<commit_before>var app = angular.module('catsvsdogs', []);
var socket = io.connect("http://192.168.99.100:5002");

var bg1 = document.getElementById('background-stats-1');
var bg2 = document.getElementById('background-stats-2');

app.controller('statsCtrl', function($scope){
  var randomColor = function(){
    var r = (Math.round(Math.random()* 127) + 127).toString(16);
    var g = (Math.round(Math.random()* 127) + 127).toString(16);
    var b = (Math.round(Math.random()* 127) + 127).toString(16);
    return '#' + r + g + b;
  };
  var animateStats = function(a,b){
    var percentA = a/(a+b)*100;
    var percentB = 100-percentA;
    bg1.style.width= percentA+"%";
    bg2.style.width = percentB+"%";
  };

  $scope.catPercent = "";
  $scope.dogPercent = "";

  var updateScores = function(){
    socket.on('scores', function (data) {
       data = JSON.parse(data);
       animateStats(data.cats, data.dogs);
       $scope.$apply(function() {
         $scope.catPercent = data.cats;
         $scope.dogPercent = data.dogs;
      });
    });
  };

  var init = function(){
    document.body.style.opacity=1;
    updateScores();
    $scope.$apply(function(){
      $scope.color = [];
      $scope.color[0] = randomColor();
      $scope.color[1] = randomColor();
    });
  };
  socket.on('message',function(data){
    init();
  });
});
<commit_msg>counter in %<commit_after>var app = angular.module('catsvsdogs', []);
var socket = io.connect("http://192.168.99.100:5002");

var bg1 = document.getElementById('background-stats-1');
var bg2 = document.getElementById('background-stats-2');

app.controller('statsCtrl', function($scope){
  var randomColor = function(){
    var r = (Math.round(Math.random()* 127) + 127).toString(16);
    var g = (Math.round(Math.random()* 127) + 127).toString(16);
    var b = (Math.round(Math.random()* 127) + 127).toString(16);
    return '#' + r + g + b;
  };
  var animateStats = function(a,b){
    var percentA = a/(a+b)*100;
    var percentB = 100-percentA;
    bg1.style.width= percentA+"%";
    bg2.style.width = percentB+"%";
  };

  $scope.catPercent = "50%";
  $scope.dogPercent = "50%";

  var updateScores = function(){
    socket.on('scores', function (data) {
       data = JSON.parse(data);
       animateStats(data.cats, data.dogs);
       $scope.$apply(function() {
         $scope.catPercent = data.cats/(data.cats+data.dogs) * 100 + "%";
         $scope.dogPercent = data.dogs/(data.cats+data.dogs) * 100 + "%";
      });
    });
  };

  var init = function(){
    document.body.style.opacity=1;
    updateScores();
    $scope.$apply(function(){
      $scope.color = [];
      $scope.color[0] = randomColor();
      $scope.color[1] = randomColor();
    });
  };
  socket.on('message',function(data){
    init();
  });
});
<|endoftext|>