<commit_before>var util = require("./util.js");
var controller = require("%%PATH_TO_CONTROLLER%%");
var bidManager = require("./bidManager.js");
var CONSTANTS = require("./constants.js");
var CONFIG = require("./config.js");
var ucTag = require("prebid-universal-creative");
var conf = require("./conf.js");
var prebid = require("./adapters/prebid.js");
var metaInfo = util.getMetaInfo(window);
window.PWT = window.PWT || {};
window.PWT.bidMap = window.PWT.bidMap || {};
window.PWT.bidIdMap = window.PWT.bidIdMap || {};
window.PWT.adUnits = window.PWT.adUnits || {};
window.PWT.floorData = window.PWT.floorData || {};
window.PWT.isIframe = window.PWT.isIframe || metaInfo.isInIframe;
window.PWT.protocol = window.PWT.protocol || metaInfo.protocol;
window.PWT.secure = window.PWT.secure || metaInfo.secure;
window.PWT.pageURL = window.PWT.pageURL || metaInfo.pageURL;
window.PWT.refURL = window.PWT.refURL || metaInfo.refURL;
window.PWT.isSafeFrame = window.PWT.isSafeFrame || false;
window.PWT.safeFrameMessageListenerAdded = window.PWT.safeFrameMessageListenerAdded || false;
// usingDifferentProfileVersion
window.PWT.udpv = window.PWT.udpv || util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtv");

util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtc") && util.enableDebugLog();
util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtvc") && util.enableVisualDebugLog();

var isPrebidPubMaticAnalyticsEnabled = CONFIG.isPrebidPubMaticAnalyticsEnabled();

window.PWT.displayCreative = function(theDocument, bidID){
	util.log("In displayCreative for: " + bidID);
	if(isPrebidPubMaticAnalyticsEnabled){
		window[CONSTANTS.COMMON.PREBID_NAMESPACE].renderAd(theDocument, bidID);
	} else {
		// removeIf(removeLegacyAnalyticsRelatedCode)
		bidManager.displayCreative(theDocument, bidID);
		// endRemoveIf(removeLegacyAnalyticsRelatedCode)
	}
};

window.PWT.displayPMPCreative = function(theDocument, values, priorityArray){
	util.log("In displayPMPCreative for: " + values);
	var bidID = util.getBididForPMP(values, priorityArray);
	if(bidID){
		if(isPrebidPubMaticAnalyticsEnabled){
			window[CONSTANTS.COMMON.PREBID_NAMESPACE].renderAd(theDocument, bidID);
		} else {
			// removeIf(removeLegacyAnalyticsRelatedCode)
			bidManager.displayCreative(theDocument, bidID);
			// endRemoveIf(removeLegacyAnalyticsRelatedCode)
		}
	}
};

window.PWT.sfDisplayCreative = function(theDocument, bidID){
	util.log("In sfDisplayCreative for: " + bidID);
	ucTag = window.ucTag || {};
	this.isSafeFrame = true;
	ucTag = window.ucTag || {};
	if(isPrebidPubMaticAnalyticsEnabled){
		ucTag.renderAd(theDocument, {adId: bidID, pubUrl: document.referrer});
	}
	else {
		window.parent.postMessage(
			JSON.stringify({
				pwt_type: "1",
				pwt_bidID: bidID,
				pwt_origin: CONSTANTS.COMMON.PROTOCOL+window.location.hostname
			}),
			"*"
		);
	}
};

window.PWT.sfDisplayPMPCreative = function(theDocument, values, priorityArray){
	util.log("In sfDisplayPMPCreative for: " + values);
	this.isSafeFrame = true;
	var bidID = util.getBididForPMP(values, priorityArray);
	if(bidID){
		if(CONFIG.isPrebidPubMaticAnalyticsEnabled()){
			ucTag.renderAd(theDocument, {adId: bidID, pubUrl: document.referrer});
		} else{
			window.parent.postMessage(
				JSON.stringify({
					pwt_type: "1",
					pwt_bidID: bidID,
					pwt_origin: CONSTANTS.COMMON.PROTOCOL+window.location.hostname
				}),
				"*"
			);
		}
	}
};

// removeIf(removeNativeRelatedCode)
window.PWT.initNativeTrackers = function(theDocument,bidID){
	util.log("In startTrackers for: " + bidID);
	util.addEventListenerForClass(window,"click", CONSTANTS.COMMON.OW_CLICK_NATIVE,bidManager.loadTrackers);
	bidManager.executeTracker(bidID);
};
// endRemoveIf(removeNativeRelatedCode)

window.PWT.getUserIds = function(){
	return util.getUserIds();
};

window.OWT = {
	notifyCount: 0, // To maintain the id which should be return after externalBidder registered
	externalBidderStatuses: {}
};

window.OWT.registerExternalBidders = function(divIds) {
	window.OWT.notifyCount++;

	util.forEachOnArray(divIds, function (key, divId) {
		util.log("registerExternalBidders: " + divId);
		window.OWT.externalBidderStatuses[divId] = {
			id: window.OWT.notifyCount,
			status: false
		};
	});

	return window.OWT.notifyCount;
};

window.OWT.notifyExternalBiddingComplete = function(notifyId) {
	util.forEachOnObject(window.OWT.externalBidderStatuses, function (key, obj) {
		if(obj && (obj.id === notifyId)) {
			util.log("notify externalBidding complete: " + key);
			window.OWT.externalBidderStatuses[key] = {
				id: obj.id,
				status: true
			};
		}
	});
};

// removeIf(removeLegacyAnalyticsRelatedCode)
window.PWT.UpdateVastWithTracker = function(bid, vast){
	return util.UpdateVastWithTracker(bid, vast);
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)

// removeIf(removeInStreamRelatedCode)
window.PWT.generateDFPURL= function(adUnit,cust_params){
	var dfpurl = "";
	if(!adUnit || !util.isObject(adUnit)) {
		util.logError("An AdUnit should be an Object", adUnit);
	}
	if(adUnit.bidData && adUnit.bidData.wb && adUnit.bidData.kvp){
		adUnit.bid = adUnit.bidData.wb;
		adUnit.bid["adserverTargeting"] = adUnit.bidData.kvp;
	}
	else{
		util.logWarning("No bid found for given adUnit");
	}
	var params = {
		adUnit: adUnit,
		params: {
			iu: adUnit.adUnitId,
			cust_params: cust_params,
			output: "vast"
		}
	};
	if(adUnit.bid){
		params["bid"] = adUnit.bid;
	}
	dfpurl = window.owpbjs.adServers.dfp.buildVideoUrl(params);
	return dfpurl;
};
// endRemoveIf(removeInStreamRelatedCode)

// removeIf(removeInStreamRelatedCode)
window.PWT.getCustomParamsForDFPVideo = function(customParams, bid){
	return util.getCustomParamsForDFPVideo(customParams, bid);
};
// endRemoveIf(removeInStreamRelatedCode)

window.PWT.setAuctionTimeout = function(timeout){
	if(!isNaN(timeout)){
		util.log("updating aution timeout from: " + conf.pwt.t +" to: "+timeout);
		conf.pwt.t = timeout;
	}
}

window.PWT.versionDetails =  util.getOWConfig();

controller.init(window);
<commit_msg>Exposed a function for pubmatic2 alias<commit_after>var util = require("./util.js");
var controller = require("%%PATH_TO_CONTROLLER%%");
var bidManager = require("./bidManager.js");
var CONSTANTS = require("./constants.js");
var CONFIG = require("./config.js");
var ucTag = require("prebid-universal-creative");
var conf = require("./conf.js");
var prebid = require("./adapters/prebid.js");
var metaInfo = util.getMetaInfo(window);
window.PWT = window.PWT || {};
window.PWT.bidMap = window.PWT.bidMap || {};
window.PWT.bidIdMap = window.PWT.bidIdMap || {};
window.PWT.adUnits = window.PWT.adUnits || {};
window.PWT.floorData = window.PWT.floorData || {};
window.PWT.isIframe = window.PWT.isIframe || metaInfo.isInIframe;
window.PWT.protocol = window.PWT.protocol || metaInfo.protocol;
window.PWT.secure = window.PWT.secure || metaInfo.secure;
window.PWT.pageURL = window.PWT.pageURL || metaInfo.pageURL;
window.PWT.refURL = window.PWT.refURL || metaInfo.refURL;
window.PWT.isSafeFrame = window.PWT.isSafeFrame || false;
window.PWT.safeFrameMessageListenerAdded = window.PWT.safeFrameMessageListenerAdded || false;
// usingDifferentProfileVersion
window.PWT.udpv = window.PWT.udpv || util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtv");

util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtc") && util.enableDebugLog();
util.findQueryParamInURL(metaInfo.isIframe ? metaInfo.refURL : metaInfo.pageURL, "pwtvc") && util.enableVisualDebugLog();

var isPrebidPubMaticAnalyticsEnabled = CONFIG.isPrebidPubMaticAnalyticsEnabled();

window.PWT.displayCreative = function(theDocument, bidID){
	util.log("In displayCreative for: " + bidID);
	if(isPrebidPubMaticAnalyticsEnabled){
		window[CONSTANTS.COMMON.PREBID_NAMESPACE].renderAd(theDocument, bidID);
	} else {
		// removeIf(removeLegacyAnalyticsRelatedCode)
		bidManager.displayCreative(theDocument, bidID);
		// endRemoveIf(removeLegacyAnalyticsRelatedCode)
	}
};

window.PWT.displayPMPCreative = function(theDocument, values, priorityArray){
	util.log("In displayPMPCreative for: " + values);
	var bidID = util.getBididForPMP(values, priorityArray);
	if(bidID){
		if(isPrebidPubMaticAnalyticsEnabled){
			window[CONSTANTS.COMMON.PREBID_NAMESPACE].renderAd(theDocument, bidID);
		} else {
			// removeIf(removeLegacyAnalyticsRelatedCode)
			bidManager.displayCreative(theDocument, bidID);
			// endRemoveIf(removeLegacyAnalyticsRelatedCode)
		}
	}
};

window.PWT.sfDisplayCreative = function(theDocument, bidID){
	util.log("In sfDisplayCreative for: " + bidID);
	ucTag = window.ucTag || {};
	this.isSafeFrame = true;
	ucTag = window.ucTag || {};
	if(isPrebidPubMaticAnalyticsEnabled){
		ucTag.renderAd(theDocument, {adId: bidID, pubUrl: document.referrer});
	}
	else {
		window.parent.postMessage(
			JSON.stringify({
				pwt_type: "1",
				pwt_bidID: bidID,
				pwt_origin: CONSTANTS.COMMON.PROTOCOL+window.location.hostname
			}),
			"*"
		);
	}
};

window.PWT.sfDisplayPMPCreative = function(theDocument, values, priorityArray){
	util.log("In sfDisplayPMPCreative for: " + values);
	this.isSafeFrame = true;
	var bidID = util.getBididForPMP(values, priorityArray);
	if(bidID){
		if(CONFIG.isPrebidPubMaticAnalyticsEnabled()){
			ucTag.renderAd(theDocument, {adId: bidID, pubUrl: document.referrer});
		} else{
			window.parent.postMessage(
				JSON.stringify({
					pwt_type: "1",
					pwt_bidID: bidID,
					pwt_origin: CONSTANTS.COMMON.PROTOCOL+window.location.hostname
				}),
				"*"
			);
		}
	}
};

// removeIf(removeNativeRelatedCode)
window.PWT.initNativeTrackers = function(theDocument,bidID){
	util.log("In startTrackers for: " + bidID);
	util.addEventListenerForClass(window,"click", CONSTANTS.COMMON.OW_CLICK_NATIVE,bidManager.loadTrackers);
	bidManager.executeTracker(bidID);
};
// endRemoveIf(removeNativeRelatedCode)

window.PWT.getUserIds = function(){
	return util.getUserIds();
};

window.OWT = {
	notifyCount: 0, // To maintain the id which should be return after externalBidder registered
	externalBidderStatuses: {}
};

window.OWT.registerExternalBidders = function(divIds) {
	window.OWT.notifyCount++;

	util.forEachOnArray(divIds, function (key, divId) {
		util.log("registerExternalBidders: " + divId);
		window.OWT.externalBidderStatuses[divId] = {
			id: window.OWT.notifyCount,
			status: false
		};
	});

	return window.OWT.notifyCount;
};

window.OWT.notifyExternalBiddingComplete = function(notifyId) {
	util.forEachOnObject(window.OWT.externalBidderStatuses, function (key, obj) {
		if(obj && (obj.id === notifyId)) {
			util.log("notify externalBidding complete: " + key);
			window.OWT.externalBidderStatuses[key] = {
				id: obj.id,
				status: true
			};
		}
	});
};

// removeIf(removeLegacyAnalyticsRelatedCode)
window.PWT.UpdateVastWithTracker = function(bid, vast){
	return util.UpdateVastWithTracker(bid, vast);
};
// endRemoveIf(removeLegacyAnalyticsRelatedCode)

// removeIf(removeInStreamRelatedCode)
window.PWT.generateDFPURL= function(adUnit,cust_params){
	var dfpurl = "";
	if(!adUnit || !util.isObject(adUnit)) {
		util.logError("An AdUnit should be an Object", adUnit);
	}
	if(adUnit.bidData && adUnit.bidData.wb && adUnit.bidData.kvp){
		adUnit.bid = adUnit.bidData.wb;
		adUnit.bid["adserverTargeting"] = adUnit.bidData.kvp;
	}
	else{
		util.logWarning("No bid found for given adUnit");
	}
	var params = {
		adUnit: adUnit,
		params: {
			iu: adUnit.adUnitId,
			cust_params: cust_params,
			output: "vast"
		}
	};
	if(adUnit.bid){
		params["bid"] = adUnit.bid;
	}
	dfpurl = window.owpbjs.adServers.dfp.buildVideoUrl(params);
	return dfpurl;
};
// endRemoveIf(removeInStreamRelatedCode)

// removeIf(removeInStreamRelatedCode)
window.PWT.getCustomParamsForDFPVideo = function(customParams, bid){
	return util.getCustomParamsForDFPVideo(customParams, bid);
};
// endRemoveIf(removeInStreamRelatedCode)

window.PWT.setAuctionTimeout = function(timeout){
	if(!isNaN(timeout)){
		util.log("updating aution timeout from: " + conf.pwt.t +" to: "+timeout);
		conf.pwt.t = timeout;
	}
}

window.PWT.versionDetails =  util.getOWConfig();

window.PWT.getAdapterNameForAlias = CONFIG.getAdapterNameForAlias;

controller.init(window);
<|endoftext|>


<commit_before>import React from 'react';

import { blazyb } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SPECS from 'game/SPECS';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [blazyb],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.0.1',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: true,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      Welcome to the Resto Druid analyzer! We hope you find these suggestions and statistics useful.

      If you want to learn more about Resto Druids, join the Druid community at the Dreamgrove discord channel. Remember to check the pins (ctrl-P while in #resto channel) for guides, FAQs, and gearing guidelines.
    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/tVvxzMN74jDCbkZF/28-Heroic+G\'huun+-+Kill+(6:49)/1-Blazyb',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.RESTORATION_DRUID,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "RestorationDruid" */).then(exports => exports.default)),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<commit_msg>Resto druid - Updated patch compatibility.<commit_after>import React from 'react';

import { blazyb } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SPECS from 'game/SPECS';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [blazyb],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.1',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: true,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      Welcome to the Resto Druid analyzer! We hope you find these suggestions and statistics useful.

      If you want to learn more about Resto Druids, join the Druid community at the Dreamgrove discord channel. Remember to check the pins (ctrl-P while in #resto channel) for guides, FAQs, and gearing guidelines.
    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/tVvxzMN74jDCbkZF/28-Heroic+G\'huun+-+Kill+(6:49)/1-Blazyb',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.RESTORATION_DRUID,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "RestorationDruid" */).then(exports => exports.default)),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<|endoftext|>


<commit_before>// request animation frame polyfill
if(!window.requestAnimationFrame){
    window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setInterval(callback, 1000/60);
    };
}

// Actor with built in collision detection
var Actor = function(x, y , width, height){
    var me = this;
    me.pos = {x : x || 0, y: y || 0};
    me.vel = {x : 0, y: 0};
    me.width = width || 0;
    me.height = height || 0;
    me.color = 'white';
    return me;
};

Actor.prototype.collides = function(actor){
    return !((this.pos.x + this.width) < actor.pos.x || this.pos.x > (actor.pos.x + actor.width) || (this.pos.y + this.height) < actor.pos.y || this.pos.y > (actor.pos.y + actor.height));
};

Actor.prototype.update = function(delta, game){
	this.pos.x += this.vel.x * delta/1000;
	this.pos.y += this.vel.y * delta/1000;

};

Actor.prototype.draw = function(delta, game){
	game.ctx.fillStyle = this.color;
	game.ctx.fillRect(this.pos.x, this.pos.y, this.width, this.height);
};

// Sound
var AudioContext = new window.webkitAudioContext();
var Sound = function(soundUrl, volume, playOnLoad){
	var me = this;
	me.context = AudioContext;
	me.volume = me.context.createGain();
	me.volume.gain.value = volume || 1;

	me.soundUrl = soundUrl || "";
	me.loaded = false;
	me.buffer = null;
	me.sound = null;

	me.load = function(){
		var request = new XMLHttpRequest();
		request.open('GET', soundUrl);
		request.responseType = 'arraybuffer';
		request.onload = function(){
			me.context.decodeAudioData(request.response, function(decodedBuffer){
				me.buffer = decodedBuffer;
				me.loaded = true;
				if(playOnLoad){
					me.play();
				}
			});
		}
		request.send();
	};

	// load the sound
	me.load();
	return me;
};

Sound.prototype.play = function(){
	if(this.loaded){
		this.sound = this.context.createBufferSource(this.buffer);
		this.sound.buffer = this.buffer;
		this.sound.connect(this.volume);
		this.volume.connect(this.context.destination);
		this.sound.start(0);
	}
};

Sound.prototype.stop = function(){
	if(this.sound){
		this.sound.noteOff(0);
	}
}

// Animations
var Sprite = function(image, ctx, sx, sy, sw, sh){
    var me = this;
    if(typeof image == 'string'){
        me.image = new Image();
        me.image.src = image;
    }else{
        me.image = image;
	}

    me.ctx = ctx;
    me.draw = function(x, y, width, height){
        me.ctx.drawImage(me.image, sx, sy, sw, sh, x, y, width || sw, height || sh);
    };
};

var Animation = function(spritesheet, ctx, columns, rows, sw, sh){
    var me = this;
    var image = new Image();
    image.src = spritesheet;
    var sprites = new Array(columns * rows);
    var currIndex = 0;
    me.speed = 50;
    me.loop = false;
    var lastTick = Date.now();

    for(var i = 0; i < rows; i++){
        for(var j = 0; j < columns; j++){
            sprites[j+i*columns] = new Sprite(image, ctx, j*sw, i*sh, sw, sh);
        }
    }

    var tick = function(){
    	var currentTime = Date.now();
    	if(currentTime - lastTick > me.speed){
        	currIndex = me.loop ? (currIndex + 1) % sprites.length : currIndex + 1;
        	lastTick = currentTime;
    	}
    };

    me.draw = function(x, y){
        tick();
        if(currIndex < sprites.length){
        	sprites[currIndex].draw(x, y);
    	}
    };

    me.done = function(){
    	return !me.loop && currIndex >= sprites.length;
    };

    return me;
};
//var animation = new Animation('images/spriteexplosion.png', 5, 5, 45, 45);

// Game container
var Game = function(canvasId){
	var me = this;
    var running = false;

    me.canvas = document.getElementById(canvasId);
    me.ctx = me.canvas.getContext('2d');

    me.actors = [];
    me.animations = [];
    me.keys = [];

    me.score = 0;
    me.lost = false;
    me.removeActor = function(actor){
        var index = me.actors.indexOf(actor);
        if(index > -1){
            me.actors.splice(index, 1);
        }
    };

    me.playAnimation = function(animation, x, y){
    	me.animations.push({anim: animation, x: x, y: y});
    };

    var clear = function(){
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0, 0, me.canvas.width, me.canvas.height);
	};

    var drawFPS = function(fps){
        me.ctx.fillStyle = 'red';
        me.ctx.fillText('FPS: ' + fps.toFixed(1), 5, 20);
	};

	var drawScore = function(){
        me.ctx.save();
		me.ctx.translate(me.canvas.width - 200, 0);
		me.ctx.scale(2, 2);
		me.ctx.fillStyle = 'lime';
        me.ctx.fillText( me.score, 10, 10);
        me.ctx.restore();
	};

	me.update = function(delta){
		// update state of the game
		// including players, npcs, scenery, animations, etc.
		me.actors.forEach(function(actor){
			actor.update(delta, me);
		});

		me.animations = me.animations.filter(function(a){
			return !a.anim.done();
		});
	};

	me.draw = function(delta){
		clear();
		// draw the game
        // draw players, npcs, scenery, animations, etc.
        me.actors.forEach(function(actor){
            actor.draw(delta, me);
        });

        me.animations.forEach(function(a){
        	a.anim.draw(a.x, a.y);
        });
	};

	me.lose = function(){
		me.lost = true;
	};
	var drawLoseMessage = function(){
		me.ctx.save();
		me.ctx.translate(20, me.canvas.height/2);
		me.ctx.scale(3, 3);
		me.ctx.fillStyle = 'red';
		me.ctx.fillText("ALL YOUR BASE ARE BELONG TO US", 0, 0);
		me.ctx.restore();
	};

	me.start = function(){
		// Setup key listeners
		window.addEventListener('keydown', function(e){
			if(me.keys.indexOf(e.keyCode) === -1){
				me.keys.push(e.keyCode);
			}
		});
		window.addEventListener('keyup', function(e){
			var index;
			if((index = me.keys.indexOf(e.keyCode)) > -1){
				me.keys.splice(index,1);
			}
		});

		// Start mainloop
        running = true;
		var lastTime =  Date.now();
		(function mainloop(){
            if(!running) return;

            window.requestAnimationFrame(mainloop);

			// Get the time to calculate time-elapsed
			var now = Date.now();
			var elapsed = Math.floor(now - lastTime);

			me.update(elapsed);
			me.draw(elapsed);

			drawFPS(1/(elapsed/1000));
			drawScore();
			if(me.lost){
				drawLoseMessage();
			}

			lastTime = now;
		})();
	};

	me.onstop = function(){

	};

    me.stop = function(){
        running = false;
        me.onstop();
    };

	return me;
};

// Initialize the game
var game = new Game('game');

// Setup helpers

var bullets = [];
var enemyBullets = [];
var enemies = [];

// Load resources
var allYourBase = new Sound('sounds/soundeffect.mp3', 0.05);
var soundTrack = new Sound('sounds/soundtrack.mp3',0.2, true);
var laser = new Sound('sounds/laser.mp3', 0.3, false);

var shipSprite = new Sprite('images/fighter.png', game.ctx, 0, 0, 40, 40);
var enemySprite = new Sprite('images/enemy.png', game.ctx, 0, 0, 40, 40);

// Bullet helper
var throttle = 500;//ms
var flipGun = false;
var lastFire = Date.now();
fireBullet = function(x, y){
	var currentTime = Date.now();
	if(currentTime - lastFire > throttle){
		flipGun = !flipGun;
		var bullet = new Actor(x+40, flipGun?y:y+40, 10, 2);
		bullet.color = 'lime';
		var bulletSpeed = 900;
		bullet.update = function(delta, game){
			Actor.prototype.update.apply(this, [delta, game]);
			bullet.vel.x = bulletSpeed;

			// Check collisions with game boarders
			if((bullet.pos.x + bullet.width) > game.canvas.width){
				game.removeActor(bullet);
				var index = bullets.indexOf(bullet);
				bullets.splice(index, 1);
			}
			if((bullet.pos.y + bullet.height) > game.canvas.height){
				game.removeActor(bullet);
                var index = bullets.indexOf(bullet);
                bullets.splice(index, 1);
			}

		};
		laser.play();
		game.actors.push(bullet);
		bullets.push(bullet);
		lastFire = currentTime;
	}
};

// Setup enemies
var createEnemy = function(){
	var enemy = new Actor(game.canvas.width + 20, Math.random()*game.canvas.height, 40, 40);
	enemy.vel.x = -50;

	enemy.update = function(delta, game){
		Actor.prototype.update.apply(enemy, [delta, game]);
		if(enemy.pos.x < -90) game.removeActor(enemy);

		// Check if bullet killed this enemy
		for(var i = 0; i < bullets.length; i++){
			if(bullets[i].collides(enemy)){
				game.score += 100;
				game.removeActor(bullets[i]);
				bullets.splice(i, 1);
				var explosion = new Animation('images/spriteexplosion.png', game.ctx, 5, 5, 45, 45);
				game.playAnimation(explosion, enemy.pos.x, enemy.pos.y);
				game.removeActor(enemy);
				var index = enemies.indexOf(enemy);
				enemies.splice(index,1);
				break;
			}
		}
	};

	enemy.draw = function(){
		game.ctx.save();
		game.ctx.translate(enemy.pos.x, enemy.pos.y);
		game.ctx.scale(3, 3);
		enemySprite.draw(0, 0, 20, 20);
		game.ctx.restore();
	};
	enemies.push(enemy);
	game.actors.push(enemy);
};

// Setup starfield
var createStarField = function(starCount){
	var createStar = function(){
		var star = new Actor(Math.random()*game.canvas.width, Math.random()*game.canvas.height, 2, 2);
		star.vel.x = -Math.random()*100-100;
		star.vel.y = 0;
		star.color = 'white';
		star.update = function(delta, game){
			Actor.prototype.update.apply(star, [delta, game]);
			// Check collisions with game boarders
			if(star.pos.x < 0) star.pos.x = game.canvas.width;
		};

		game.actors.push(star);
	};
	for(var i = 0; i< starCount; i++){
		createStar();
	}
};

// Setup player
var createPlayer = function(){
	// Setup player
	var actor = new Actor(50, 50, 20, 20);
	var speed = 100;
	var alive = true;
	actor.update = function(delta, game){
		Actor.prototype.update.apply(this, [delta, game]);
		actor.vel.y = 0;
		actor.vel.x = 0;

		if(game.keys.indexOf(38) > -1){
			actor.vel.y = -speed;
		}

		if(game.keys.indexOf(40) > -1){
			actor.vel.y = speed;
		}

		if(game.keys.indexOf(39) > -1){
			actor.vel.x = speed;
		}

		if(game.keys.indexOf(37) > -1){
			actor.vel.x = -speed;
		}

		if(game.keys.indexOf(32) > -1){
			fireBullet(actor.pos.x, actor.pos.y);
		}

		// Check collisions with game boarders
		if(actor.pos.x < 0) actor.pos.x = 0;
		if(actor.pos.y < 0) actor.pos.y = 0;
		if((actor.pos.x + actor.width) > game.canvas.width) actor.pos.x = game.canvas.width - actor.width;
		if((actor.pos.y + actor.height) > game.canvas.height) actor.pos.y = game.canvas.height - actor.height;

		// Check for collision with baddies
		// Check if bullet killed this enemy
		for(var i = 0; i < enemies.length; i++){
			if(enemies[i].collides(actor)){
				game.removeActor(enemies[i]);
				game.removeActor(actor);
				var explosion = new Animation('images/spriteexplosion.png', game.ctx, 5, 5, 45, 45);
				game.playAnimation(explosion, actor.pos.x, actor.pos.y);
				game.lose();
				allYourBase.play();
				break;
			}
		}

	};

	actor.draw = function(delta, game){
		game.ctx.save();
		game.ctx.translate(actor.pos.x, actor.pos.y);

		shipSprite.draw(-10, -10, 60, 60);

		game.ctx.restore();
	};
	game.actors.push(actor);
};

// Create game objects and start

// Create star field with 100 stars
createStarField(100);

// Create enemies every 2 seconds
setInterval(function(){
	createEnemy();
},2000);

// Add the player and start
createPlayer();

soundTrack.play();

// delay game start for a few seconds and wait for resources to load
setTimeout(function(){
	game.start();
},4000);

game.onstop = function(){
	soundTrack.stop();
}
<commit_msg>Last tweak I swear<commit_after>// request animation frame polyfill
if(!window.requestAnimationFrame){
    window.requestAnimationFrame = window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){
        window.setInterval(callback, 1000/60);
    };
}

// Actor with built in collision detection
var Actor = function(x, y , width, height){
    var me = this;
    me.pos = {x : x || 0, y: y || 0};
    me.vel = {x : 0, y: 0};
    me.width = width || 0;
    me.height = height || 0;
    me.color = 'white';
    return me;
};

Actor.prototype.collides = function(actor){
    return !((this.pos.x + this.width) < actor.pos.x || this.pos.x > (actor.pos.x + actor.width) || (this.pos.y + this.height) < actor.pos.y || this.pos.y > (actor.pos.y + actor.height));
};

Actor.prototype.update = function(delta, game){
	this.pos.x += this.vel.x * delta/1000;
	this.pos.y += this.vel.y * delta/1000;

};

Actor.prototype.draw = function(delta, game){
	game.ctx.fillStyle = this.color;
	game.ctx.fillRect(this.pos.x, this.pos.y, this.width, this.height);
};

// Sound
var AudioContext = new window.webkitAudioContext();
var Sound = function(soundUrl, volume, playOnLoad){
	var me = this;
	me.context = AudioContext;
	me.volume = me.context.createGain();
	me.volume.gain.value = volume || 1;

	me.soundUrl = soundUrl || "";
	me.loaded = false;
	me.buffer = null;
	me.sound = null;

	me.load = function(){
		var request = new XMLHttpRequest();
		request.open('GET', soundUrl);
		request.responseType = 'arraybuffer';
		request.onload = function(){
			me.context.decodeAudioData(request.response, function(decodedBuffer){
				me.buffer = decodedBuffer;
				me.loaded = true;
				if(playOnLoad){
					me.play();
				}
			});
		}
		request.send();
	};

	// load the sound
	me.load();
	return me;
};

Sound.prototype.play = function(){
	if(this.loaded){
		this.sound = this.context.createBufferSource(this.buffer);
		this.sound.buffer = this.buffer;
		this.sound.connect(this.volume);
		this.volume.connect(this.context.destination);
		this.sound.start(0);
	}
};

Sound.prototype.stop = function(){
	if(this.sound){
		this.sound.noteOff(0);
	}
}

// Animations
var Sprite = function(image, ctx, sx, sy, sw, sh){
    var me = this;
    if(typeof image == 'string'){
        me.image = new Image();
        me.image.src = image;
    }else{
        me.image = image;
	}

    me.ctx = ctx;
    me.draw = function(x, y, width, height){
        me.ctx.drawImage(me.image, sx, sy, sw, sh, x, y, width || sw, height || sh);
    };
};

var Animation = function(spritesheet, ctx, columns, rows, sw, sh){
    var me = this;
    var image = new Image();
    image.src = spritesheet;
    var sprites = new Array(columns * rows);
    var currIndex = 0;
    me.speed = 50;
    me.loop = false;
    var lastTick = Date.now();

    for(var i = 0; i < rows; i++){
        for(var j = 0; j < columns; j++){
            sprites[j+i*columns] = new Sprite(image, ctx, j*sw, i*sh, sw, sh);
        }
    }

    var tick = function(){
    	var currentTime = Date.now();
    	if(currentTime - lastTick > me.speed){
        	currIndex = me.loop ? (currIndex + 1) % sprites.length : currIndex + 1;
        	lastTick = currentTime;
    	}
    };

    me.draw = function(x, y){
        tick();
        if(currIndex < sprites.length){
        	sprites[currIndex].draw(x, y);
    	}
    };

    me.done = function(){
    	return !me.loop && currIndex >= sprites.length;
    };

    return me;
};
//var animation = new Animation('images/spriteexplosion.png', 5, 5, 45, 45);

// Game container
var Game = function(canvasId){
	var me = this;
    var running = false;

    me.canvas = document.getElementById(canvasId);
    me.ctx = me.canvas.getContext('2d');

    me.actors = [];
    me.animations = [];
    me.keys = [];

    me.score = 0;
    me.lost = false;
    me.removeActor = function(actor){
        var index = me.actors.indexOf(actor);
        if(index > -1){
            me.actors.splice(index, 1);
        }
    };

    me.playAnimation = function(animation, x, y){
    	me.animations.push({anim: animation, x: x, y: y});
    };

    var clear = function(){
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0, 0, me.canvas.width, me.canvas.height);
	};

    var drawFPS = function(fps){
        me.ctx.fillStyle = 'red';
        me.ctx.fillText('FPS: ' + fps.toFixed(1), 5, 20);
	};

	var drawScore = function(){
        me.ctx.save();
		me.ctx.translate(me.canvas.width - 200, 0);
		me.ctx.scale(2, 2);
		me.ctx.fillStyle = 'lime';
        me.ctx.fillText( me.score, 10, 10);
        me.ctx.restore();
	};

	me.update = function(delta){
		// update state of the game
		// including players, npcs, scenery, animations, etc.
		me.actors.forEach(function(actor){
			actor.update(delta, me);
		});

		me.animations = me.animations.filter(function(a){
			return !a.anim.done();
		});
	};

	me.draw = function(delta){
		clear();
		// draw the game
        // draw players, npcs, scenery, animations, etc.
        me.actors.forEach(function(actor){
            actor.draw(delta, me);
        });

        me.animations.forEach(function(a){
        	a.anim.draw(a.x, a.y);
        });
	};

	me.lose = function(){
		me.lost = true;
	};
	var drawLoseMessage = function(){
		me.ctx.save();
		me.ctx.translate(20, me.canvas.height/2);
		me.ctx.scale(3, 3);
		me.ctx.fillStyle = 'red';
		me.ctx.fillText("ALL YOUR BASE ARE BELONG TO US", 0, 0);
		me.ctx.restore();
	};

	me.start = function(){
		// Setup key listeners
		window.addEventListener('keydown', function(e){
			if(me.keys.indexOf(e.keyCode) === -1){
				me.keys.push(e.keyCode);
			}
		});
		window.addEventListener('keyup', function(e){
			var index;
			if((index = me.keys.indexOf(e.keyCode)) > -1){
				me.keys.splice(index,1);
			}
		});

		// Start mainloop
        running = true;
		var lastTime =  Date.now();
		(function mainloop(){
            if(!running) return;

            window.requestAnimationFrame(mainloop);

			// Get the time to calculate time-elapsed
			var now = Date.now();
			var elapsed = Math.floor(now - lastTime);

			me.update(elapsed);
			me.draw(elapsed);

			drawFPS(1/(elapsed/1000));
			drawScore();
			if(me.lost){
				drawLoseMessage();
			}

			lastTime = now;
		})();
	};

	me.onstop = function(){

	};

    me.stop = function(){
        running = false;
        me.onstop();
    };

	return me;
};

// Initialize the game
var game = new Game('game');

// Setup helpers

var bullets = [];
var enemyBullets = [];
var enemies = [];

// Load resources
var allYourBase = new Sound('sounds/soundeffect.mp3', 0.05);
var soundTrack = new Sound('sounds/soundtrack.mp3',0.2, true);
var laser = new Sound('sounds/laser.mp3', 0.3, false);

var shipSprite = new Sprite('images/fighter.png', game.ctx, 0, 0, 40, 40);
var enemySprite = new Sprite('images/enemy.png', game.ctx, 0, 0, 40, 40);

// Bullet helper
var throttle = 500;//ms
var flipGun = false;
var lastFire = Date.now();
fireBullet = function(x, y){
	var currentTime = Date.now();
	if(currentTime - lastFire > throttle){
		flipGun = !flipGun;
		var bullet = new Actor(x+40, flipGun?y:y+40, 10, 2);
		bullet.color = 'lime';
		var bulletSpeed = 900;
		bullet.update = function(delta, game){
			Actor.prototype.update.apply(this, [delta, game]);
			bullet.vel.x = bulletSpeed;

			// Check collisions with game boarders
			if((bullet.pos.x + bullet.width) > game.canvas.width){
				game.removeActor(bullet);
				var index = bullets.indexOf(bullet);
				bullets.splice(index, 1);
			}
			if((bullet.pos.y + bullet.height) > game.canvas.height){
				game.removeActor(bullet);
                var index = bullets.indexOf(bullet);
                bullets.splice(index, 1);
			}

		};
		laser.play();
		game.actors.push(bullet);
		bullets.push(bullet);
		lastFire = currentTime;
	}
};

// Setup enemies
var createEnemy = function(){
	var enemy = new Actor(game.canvas.width + 20, Math.random()*game.canvas.height, 40, 40);
	enemy.vel.x = -50;
	var angle = 0;
	var y = enemy.pos.y;
	enemy.update = function(delta, game){
		Actor.prototype.update.apply(enemy, [delta, game]);
		if(enemy.pos.x < -90) game.removeActor(enemy);
		angle += Math.PI/4 * delta/1000;
		enemy.pos.y = 100*Math.sin(angle) - 200 + y;

		// Check if bullet killed this enemy
		for(var i = 0; i < bullets.length; i++){
			if(bullets[i].collides(enemy)){
				game.score += 100;
				game.removeActor(bullets[i]);
				bullets.splice(i, 1);
				var explosion = new Animation('images/spriteexplosion.png', game.ctx, 5, 5, 45, 45);
				game.playAnimation(explosion, enemy.pos.x, enemy.pos.y);
				game.removeActor(enemy);
				var index = enemies.indexOf(enemy);
				enemies.splice(index,1);
				break;
			}
		}
	};

	enemy.draw = function(){
		game.ctx.save();
		game.ctx.translate(enemy.pos.x, enemy.pos.y);
		game.ctx.scale(3, 3);
		enemySprite.draw(0, 0, 20, 20);
		game.ctx.restore();
	};
	enemies.push(enemy);
	game.actors.push(enemy);
};

// Setup starfield
var createStarField = function(starCount){
	var createStar = function(){
		var star = new Actor(Math.random()*game.canvas.width, Math.random()*game.canvas.height, 2, 2);
		star.vel.x = -Math.random()*100-100;
		star.vel.y = 0;
		star.color = 'white';
		star.update = function(delta, game){
			Actor.prototype.update.apply(star, [delta, game]);
			// Check collisions with game boarders
			if(star.pos.x < 0) star.pos.x = game.canvas.width;
		};

		game.actors.push(star);
	};
	for(var i = 0; i< starCount; i++){
		createStar();
	}
};

// Setup player
var createPlayer = function(){
	// Setup player
	var actor = new Actor(50, 50, 20, 20);
	var speed = 100;
	var alive = true;
	actor.update = function(delta, game){
		Actor.prototype.update.apply(this, [delta, game]);
		actor.vel.y = 0;
		actor.vel.x = 0;

		if(game.keys.indexOf(38) > -1){
			actor.vel.y = -speed;
		}

		if(game.keys.indexOf(40) > -1){
			actor.vel.y = speed;
		}

		if(game.keys.indexOf(39) > -1){
			actor.vel.x = speed;
		}

		if(game.keys.indexOf(37) > -1){
			actor.vel.x = -speed;
		}

		if(game.keys.indexOf(32) > -1){
			fireBullet(actor.pos.x, actor.pos.y);
		}

		// Check collisions with game boarders
		if(actor.pos.x < 0) actor.pos.x = 0;
		if(actor.pos.y < 0) actor.pos.y = 0;
		if((actor.pos.x + actor.width) > game.canvas.width) actor.pos.x = game.canvas.width - actor.width;
		if((actor.pos.y + actor.height) > game.canvas.height) actor.pos.y = game.canvas.height - actor.height;

		// Check for collision with baddies
		// Check if bullet killed this enemy
		for(var i = 0; i < enemies.length; i++){
			if(enemies[i].collides(actor)){
				game.removeActor(enemies[i]);
				game.removeActor(actor);
				var explosion = new Animation('images/spriteexplosion.png', game.ctx, 5, 5, 45, 45);
				game.playAnimation(explosion, actor.pos.x, actor.pos.y);
				game.lose();
				allYourBase.play();
				break;
			}
		}

	};

	actor.draw = function(delta, game){
		game.ctx.save();
		game.ctx.translate(actor.pos.x, actor.pos.y);

		shipSprite.draw(-10, -10, 60, 60);

		game.ctx.restore();
	};
	game.actors.push(actor);
};

// Create game objects and start

// Create star field with 100 stars
createStarField(100);

// Create enemies every 2 seconds
setInterval(function(){
	createEnemy();
},2000);

// Add the player and start
createPlayer();

soundTrack.play();

// delay game start for a few seconds and wait for resources to load
setTimeout(function(){
	game.start();
},4000);

game.onstop = function(){
	soundTrack.stop();
}
<|endoftext|>


<commit_before>var states = ["wind-up", "thrown", "scored"]
var config = {
    type: Phaser.AUTO,
    width: 870,
    height: 595,
    backgroundColor: 0xffc836,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { x: 0, y: 1000}
        }
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

var game = new Phaser.Game(config);
var launch_pos = {x: 50, y: 300};
var first_click = {x:0, y:0};
var balls = [];
var red_cells = [];
var walls = [];
var line = null;
var ball_group;
var wall_group;
var red_button;
var launch_spot;

var state = "wind-up";

var ball_settings = {mass: 1};
var red_cell_settings = {mass: 1000};

var red_cells = [];

var fireing = false;

function preload ()
{
    this.load.image('ball', 'assets/ball.png');
    this.load.image('red_cell', 'assets/blackHole.png');
    this.load.image('trash', 'assets/trash.png');

    this.load.image('button', 'assets/red.png');
    this.load.image('background', 'assets/doofinc.jpg');
    this.load.spritesheet('explosion', 'assets/explosion.png', {frameWidth: 100, frameHeight: 100});
    ball_group = this.physics.add.group();
    wall_group = this.physics.add.staticGroup();
    this.physics.add.collider(ball_group, ball_group);
    this.physics.add.collider(ball_group, wall_group);

}

function create()
{   balls = [];
    red_cells = [];
    walls = [];
    line = null;
    red_button = null;
    this.add.image(0, 0, 'background').setOrigin(0, 0);
    load_room(this);

    // create_new_ball(this);
}
function create_new_ball(scene)
{
    var ball = scene.physics.add.image(launch_pos.x, launch_pos.y, 'ball');
    ball_group.add(ball);
    ball.body.x = launch_pos.x;
    ball.body.y = launch_pos.y;
    // ball.setOrigin(0, 0);
    ball.setScale(0.125);
    ball.body.drag.x = 0.1;
    ball.body.drag.y = 5;
    ball.setVelocity(0, 0);
    ball.body.setAllowGravity(false);
    ball.setBounce(0.9, 0.7);
    ball.setCollideWorldBounds(true);
    ball.fired = false;
    balls.unshift(ball);

}

function draw_line(scene)
{
    if(line === null)
    {
        line = scene.add.line(0, 0, 100, 100,  0, 0, 0xff0000);
        line.setOrigin(0, 0);
        line.setStrokeStyle(10, 0, 0);
    }
    line.setStrokeStyle(10, 0, 1);
    line.setTo(game.input.mousePointer.x, game.input.mousePointer.y, first_click.x, first_click.y);
}
function update ()
{
    red_cells.forEach(element => {
        balls.forEach(ball => {
            if(ball.fired){
                apply_force(ball, element);
            }
        })
    });
    if (game.input.mousePointer.isDown)
    {
        if(fireing === false)
        {
            first_click.x = game.input.mousePointer.x;
            first_click.y = game.input.mousePointer.y;
        }
        draw_line(this);
        fireing = true;
    }
    if (!game.input.mousePointer.isDown && fireing === true)
    {
        create_new_ball(this);

        line.setStrokeStyle(10, 0, 0);
        fireing = false;
        var dist = Math.abs(Phaser.Math.Distance.BetweenPoints(first_click, game.input.mousePointer));
        var force = 3*dist;
        var angle = Phaser.Math.Angle.BetweenPoints(first_click, game.input.mousePointer);
        balls[0].body.velocity.x += force * Math.cos(angle);
        balls[0].body.velocity.y += force * Math.sin(angle);
        balls[0].body.setAllowGravity(true);

        balls[0].fired = true;

    }
}

function load_room(scene)
{

    scene.add.rectangle(launch_pos.x, launch_pos.y, 64, 64, 0xaaaaaa, 0.5);
    var num_red_cells = Math.floor(1 + Math.random() * 4);
    red_cells = [];
    for(var i = 0; i < num_red_cells; i++)
    {
        var x_pos = Math.floor(150 + Math.random()*650);
        var y_pos = Math.floor(150 + Math.random()*450);
        var cell = scene.physics.add.image(x_pos, y_pos, 'red_cell');
        cell.setScale(0.25);
        cell.body.setAllowGravity(false);
        red_cells.push(cell);
    }

    var num_walls = Math.floor(2 + Math.random()*8);
    for(var i = 0; i < num_walls; i++)
    {
        var x_pos = Math.floor(300 + Math.random()*(870-300));
        var y_pos = Math.floor(Math.random()*500);
        let wall = scene.add.rectangle(x_pos, y_pos, 20, 100, 0xff0000);
        wall_group.add(wall);
    }

    let button_height = Math.floor(150 + Math.random()*250);
    red_button = scene.physics.add.image(870 - 20, button_height, 'button');
    red_button.setScale(0.25);
    red_button.setRotation(-1.59);
    red_button.body.setAllowGravity(false);
    scene.physics.add.collider(ball_group, red_button, function() {explode_and_reset(scene)});
}

function explode_and_reset(scene)
{
    let pop = scene.add.sprite(435, 250);
    pop.setScale(10, 10);
    scene.anims.create({
        key: 'bomb',
        frames: scene.anims.generateFrameNumbers('explosion'),
        frameRate: 60,
        repeat: 0
    });
    pop.play('bomb');
    pop.on("animationcomplete", () => { scene.registry.destroy();
                                        scene.events.off();
                                        scene.scene.restart();})
}

function apply_force(object, source)
{
    var dist = 0.075 * Math.abs(Phaser.Math.Distance.BetweenPoints(object, source));
    if(dist < 10) dist = 10;
    var force = 5*ball_settings.mass*red_cell_settings.mass/(dist*dist);
    var angle = Phaser.Math.Angle.BetweenPoints(object, source);
    object.body.velocity.x += force * Math.cos(angle);
    object.body.velocity.y += force * Math.sin(angle);
}<commit_msg>feat: add scoreboard to game<commit_after>var states = ["wind-up", "thrown", "scored"]
var config = {
    type: Phaser.AUTO,
    width: 870,
    height: 595,
    backgroundColor: 0xffc836,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { x: 0, y: 1000}
        }
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    }
};

var game = new Phaser.Game(config);
var launch_pos = {x: 50, y: 300};
var first_click = {x:0, y:0};
var balls = [];
var red_cells = [];
var walls = [];
var line = null;
var ball_group;
var wall_group;
var red_button;
var launch_spot;

var totalShots = 0;
var totalButtons = 0;

var scoreboard;

var state = "wind-up";

var ball_settings = {mass: 1};
var red_cell_settings = {mass: 1000};

var red_cells = [];

var fireing = false;

function preload ()
{
    this.load.image('ball', 'assets/ball.png');
    this.load.image('red_cell', 'assets/blackHole.png');
    this.load.image('trash', 'assets/trash.png');

    this.load.image('button', 'assets/red.png');
    this.load.image('background', 'assets/doofinc.jpg');
    this.load.spritesheet('explosion', 'assets/explosion.png', {frameWidth: 100, frameHeight: 100});
    ball_group = this.physics.add.group();
    wall_group = this.physics.add.staticGroup();
    this.physics.add.collider(ball_group, ball_group);
    this.physics.add.collider(ball_group, wall_group);

}

function create()
{   balls = [];
    red_cells = [];
    walls = [];
    line = null;
    red_button = null;
    this.add.image(0, 0, 'background').setOrigin(0, 0);
    scoreboard = this.add.text(25, 25, '', { font: '16px Courier', fill: '#00ff00' });
    scoreboard.setDataEnabled();
    scoreboard.data.set('balls', totalShots);
    scoreboard.data.set('buttons', totalButtons);

    scoreboard.setText(['Total Balls Thrown: ' + scoreboard.data.get('balls'), 'Total Inators Destroyed: '+ scoreboard.data.get('buttons')]);
    scoreboard.on('changedata-balls', function(){
        scoreboard.setText(['Total Balls Thrown: ' + scoreboard.data.get('balls'), 'Total Inators Destroyed: '+ scoreboard.data.get('buttons')]);
    })
    load_room(this);

    // create_new_ball(this);
}
function create_new_ball(scene)
{
    var ball = scene.physics.add.image(launch_pos.x, launch_pos.y, 'ball');
    ball_group.add(ball);
    ball.body.x = launch_pos.x;
    ball.body.y = launch_pos.y;
    // ball.setOrigin(0, 0);
    ball.setScale(0.125);
    ball.body.drag.x = 0.1;
    ball.body.drag.y = 5;
    ball.setVelocity(0, 0);
    ball.body.setAllowGravity(false);
    ball.setBounce(0.9, 0.7);
    ball.setCollideWorldBounds(true);
    ball.fired = false;
    totalShots += 1;
    scoreboard.data.values.balls = totalShots;
    balls.unshift(ball);

}

function draw_line(scene)
{
    if(line === null)
    {
        line = scene.add.line(0, 0, 100, 100,  0, 0, 0xff0000);
        line.setOrigin(0, 0);
        line.setStrokeStyle(10, 0, 0);
    }
    line.setStrokeStyle(10, 0, 1);
    line.setTo(game.input.mousePointer.x, game.input.mousePointer.y, first_click.x, first_click.y);
}
function update ()
{
    red_cells.forEach(element => {
        balls.forEach(ball => {
            if(ball.fired){
                apply_force(ball, element);
            }
        })
    });
    if (game.input.mousePointer.isDown)
    {
        if(fireing === false)
        {
            first_click.x = game.input.mousePointer.x;
            first_click.y = game.input.mousePointer.y;
        }
        draw_line(this);
        fireing = true;
    }
    if (!game.input.mousePointer.isDown && fireing === true)
    {
        create_new_ball(this);

        line.setStrokeStyle(10, 0, 0);
        fireing = false;
        var dist = Math.abs(Phaser.Math.Distance.BetweenPoints(first_click, game.input.mousePointer));
        var force = 3*dist;
        var angle = Phaser.Math.Angle.BetweenPoints(first_click, game.input.mousePointer);
        balls[0].body.velocity.x += force * Math.cos(angle);
        balls[0].body.velocity.y += force * Math.sin(angle);
        balls[0].body.setAllowGravity(true);

        balls[0].fired = true;

    }
}

function load_room(scene)
{

    scene.add.rectangle(launch_pos.x, launch_pos.y, 64, 64, 0xaaaaaa, 0.5);
    var num_red_cells = Math.floor(1 + Math.random() * 4);
    red_cells = [];
    for(var i = 0; i < num_red_cells; i++)
    {
        var x_pos = Math.floor(150 + Math.random()*650);
        var y_pos = Math.floor(150 + Math.random()*450);
        var cell = scene.physics.add.image(x_pos, y_pos, 'red_cell');
        cell.setScale(0.25);
        cell.body.setAllowGravity(false);
        red_cells.push(cell);
    }

    var num_walls = Math.floor(2 + Math.random()*8);
    for(var i = 0; i < num_walls; i++)
    {
        var x_pos = Math.floor(300 + Math.random()*(870-300));
        var y_pos = Math.floor(Math.random()*500);
        let wall = scene.add.rectangle(x_pos, y_pos, 20, 100, 0xff0000);
        wall_group.add(wall);
    }

    let button_height = Math.floor(150 + Math.random()*250);
    red_button = scene.physics.add.image(870 - 20, button_height, 'button');
    red_button.setScale(0.25);
    red_button.setRotation(-1.59);
    red_button.body.setAllowGravity(false);
    scene.physics.add.collider(ball_group, red_button, function() {explode_and_reset(scene)});
}

function explode_and_reset(scene)
{
    let pop = scene.add.sprite(435, 250);
    pop.setScale(10, 10);
    scene.anims.create({
        key: 'bomb',
        frames: scene.anims.generateFrameNumbers('explosion'),
        frameRate: 60,
        repeat: 0
    });
    pop.play('bomb');
    pop.on("animationcomplete", () => { totalButtons+=1;
                                        scene.registry.destroy();
                                        scene.events.off();
                                        scene.scene.restart();})
}

function apply_force(object, source)
{
    var dist = 0.075 * Math.abs(Phaser.Math.Distance.BetweenPoints(object, source));
    if(dist < 10) dist = 10;
    var force = 5*ball_settings.mass*red_cell_settings.mass/(dist*dist);
    var angle = Phaser.Math.Angle.BetweenPoints(object, source);
    object.body.velocity.x += force * Math.cos(angle);
    object.body.velocity.y += force * Math.sin(angle);
}<|endoftext|>


<commit_before>if (document.body.className.indexOf("no-contains-view")>-1) {
    console.log("No view detected");
} else {
    var cvbtn = document.querySelector(".view-buttons .cards");
    var lvbtn = document.querySelector(".view-buttons .list");
    var vlst = document.querySelector(".view");

    var listView = function () {
        cvbtn.classList.remove("active");
        lvbtn.classList.add("active");
        vlst.classList.remove("cards");
        vlst.classList.add("list");
        localStorage.setItem("view", "list");
    }

    var cardsView = function () {
        lvbtn.classList.remove("active");
        cvbtn.classList.add("active");
        vlst.classList.remove("list");
        vlst.classList.add("cards");
        localStorage.setItem("view", "cards");
    }

    var restoreView = function () {
        if (localStorage in window) {
            var v = localStorage.getItem("view");
            if (v !== null) {
                if (v == "list") {
                    listView();
                } else {
                    cardsView();
                }
            } else {
                cardsView();
            }
        } else {
            cardsView();
        }
    }

    lvbtn.addEventListener("click", listView);
    cvbtn.addEventListener("click", cardsView);

    restoreView();
}<commit_msg>Fix bug in web UI<commit_after>if (document.body.className.indexOf("no-contains-view")>-1) {
    console.log("No view detected");
} else {
    var cvbtn = document.querySelector(".view-buttons .cards");
    var lvbtn = document.querySelector(".view-buttons .list");
    var vlst = document.querySelector(".view");

    var listView = function () {
        cvbtn.classList.remove("active");
        lvbtn.classList.add("active");
        vlst.classList.remove("cards");
        vlst.classList.add("list");
        localStorage.setItem("view", "list");
    }

    var cardsView = function () {
        lvbtn.classList.remove("active");
        cvbtn.classList.add("active");
        vlst.classList.remove("list");
        vlst.classList.add("cards");
        localStorage.setItem("view", "cards");
    }

    var restoreView = function () {
        if (window.localStorage) {
            var v = localStorage.getItem("view");
            if (v !== null) {
                if (v == "list") {
                    listView();
                } else {
                    cardsView();
                }
            } else {
                cardsView();
            }
        } else {
            cardsView();
        }
    }

    lvbtn.addEventListener("click", listView);
    cvbtn.addEventListener("click", cardsView);

    restoreView();
}<|endoftext|>


<commit_before>function mobilify(url, origin) {
  if (url) {
    return url.replace(/https?:\/\/(?:np\.)?(?:www\.)?reddit.com/g, origin || '');
  }

  return url;
}

export default mobilify;
<commit_msg>Fix a small bug in the mobilify helper function<commit_after>function mobilify(url, origin) {
  if (url) {
    return url.replace(/https?:\/\/(?:np\.)?(?:www\.)?reddit\.com\//g, `${origin || ''}/`);
  }

  return url;
}

export default mobilify;
<|endoftext|>


<commit_before>module.exports.server=function(serv)
{
  serv.broadcast = (message, color) =>
    serv.players.forEach(player => player.chat({
      "text": message,
      "color": color
    }));
};

module.exports.player=function(player)
{
  player._client.on('chat', ({message} = {}) => {
    if(message[0]=="/") {
      var command = message.slice(1);
      player.handleCommand(command);
    }
    else {
      serv.broadcast('<' + player.username + '>' + ' ' + message);
      player.emit("chat",message);
    }
  });

  player.chat = message => {
    player._client.write('chat', { message: JSON.stringify(message), position: 0 });
  };

  player.system = message => {
    player._client.write('chat', { message: JSON.stringify(message), position: 2 });
  };
};<commit_msg>fix missing serv in chat.js<commit_after>module.exports.server=function(serv)
{
  serv.broadcast = (message, color) =>
    serv.players.forEach(player => player.chat({
      "text": message,
      "color": color
    }));
};

module.exports.player=function(player,serv)
{
  player._client.on('chat', ({message} = {}) => {
    if(message[0]=="/") {
      var command = message.slice(1);
      player.handleCommand(command);
    }
    else {
      serv.broadcast('<' + player.username + '>' + ' ' + message);
      player.emit("chat",message);
    }
  });

  player.chat = message => {
    player._client.write('chat', { message: JSON.stringify(message), position: 0 });
  };

  player.system = message => {
    player._client.write('chat', { message: JSON.stringify(message), position: 2 });
  };
};<|endoftext|>


<commit_before>import hashSymbol from './hash-symbol';
import compute31BitDateHash from './hash-date';
import compute31BitNumberHash from './hash-number';
import compute31BitStringHash from './hash-string';
import compute31BitObjecHash from './hash-object';

/**
* Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures such as a hash table.
* @param {Object} obj An object to retrieve the hash code for.
* @param {...Objects} rest Optional number of objects to combine their hash codes.
* @returns {Number}
*/
export default function hash(obj, ...rest) {
    var _hash;

    // null/undefined hash is 0
    if (obj == null) {
        _hash = 0;
    }

    // use 'instanceof' and 'typeof' operators to maximize performance

    // Compute 'Number' primitive type hash (does not incluede 'new Number(value)')
    if (typeof obj === 'number') {
        _hash = compute31BitNumberHash(obj);
    }

    // Compute 'String' primitive type hash (does not incluede 'new String(value)')
    else if (typeof obj === 'string') {
        _hash = compute31BitStringHash(obj);
    }

    // Compute 'Boolean' primitive type hash (does not incluede 'new Boolean(value)')
    else if (typeof obj === 'boolean') {
        _hash = obj ? 1 : 0;
    }

    // Compute 'Objects' hash
    else {
        // Compute 'Date' object type hash
        if (obj instanceof Date) {
            _hash = compute31BitDateHash(obj);
        }

        // Compute overriden 'hash' method
        else if (typeof obj[hashSymbol] === 'function') {
            _hash = obj[hashSymbol]();
        }

        // Compute 'Object' type hash for all other types
        else {
            _hash = compute31BitObjecHash(obj);
        }
    }

    // Combine hash codes for given inputs
    if (rest.length) {
        var _len = rest.length,
            _i = 0;

        while (++_i < _len) {
            // Josh Bloch hash method to combine 2 hash
            _hash = (17 * 31 + _hash) * 31 + hash(rest[_i]);
        }
    }

    return _hash;
}
<commit_msg>fix hash with multi-arguments<commit_after>import hashSymbol from './hash-symbol';
import compute31BitDateHash from './hash-date';
import compute31BitNumberHash from './hash-number';
import compute31BitStringHash from './hash-string';
import compute31BitObjecHash from './hash-object';

/**
* Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures such as a hash table.
* @param {Object} obj An object to retrieve the hash code for.
* @param {...Objects} rest Optional number of objects to combine their hash codes.
* @returns {Number}
*/
export default function hash(obj) {
    var _hash;

    // null/undefined hash is 0
    if (obj == null) {
        _hash = 0;
    }

    // use 'instanceof' and 'typeof' operators to maximize performance

    // Compute 'Number' primitive type hash (does not incluede 'new Number(value)')
    if (typeof obj === 'number') {
        _hash = compute31BitNumberHash(obj);
    }

    // Compute 'String' primitive type hash (does not incluede 'new String(value)')
    else if (typeof obj === 'string') {
        _hash = compute31BitStringHash(obj);
    }

    // Compute 'Boolean' primitive type hash (does not incluede 'new Boolean(value)')
    else if (typeof obj === 'boolean') {
        _hash = obj ? 1 : 0;
    }

    // Compute 'Objects' hash
    else {
        // Compute 'Date' object type hash
        if (obj instanceof Date) {
            _hash = compute31BitDateHash(obj);
        }

        // Compute overriden 'hash' method
        else if (typeof obj[hashSymbol] === 'function') {
            _hash = obj[hashSymbol]();
        }

        // Compute 'Object' type hash for all other types
        else {
            _hash = compute31BitObjecHash(obj);
        }
    }

    // Combine hash codes for given inputs
    if (arguments.length > 1) {
        var _len = arguments.length,
            _i = 1;

        while (_i < _len) {
            // Josh Bloch hash method to combine 2 hash
            _hash = (17 * 31 + _hash) * 31 + hash(arguments[_i++]);
        }
    }

    return _hash;
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name Udacity Extended Keybindings
// @description Vim and Emacs keybindings for the Udacity IDE.
// @version 0.9.2
//
// @namespace http://e.cmendenhall.com/
//
// @downloadURL http://ecmendenhall.github.com/udacity-keybindings/udacity-extended-keybindings.user.js
//
// @include https://www.udacity.com/course/viewer*
// @match https://www.udacity.com/course/viewer*
//
//
// ==/UserScript==

function inject(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script);
    document.body.removeChild(script);
}

function change_keymap () {

    var codemirror = document.getElementsByClassName('CodeMirror')[0];
    var code_editor = codemirror.CodeMirror;
    var keymap_mode;

    if (document.all) {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.innerText;
    } else {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.textContent;
    }

    if (keymap_mode === 'VIM') {

        code_editor.setOption('keyMap', 'vim');
        code_editor.setOption('extraKeys', {"':'": function (cm) {
            var state = cm.getOption('keyMap')
            if (state === 'vim-insert') {
               cm.replaceSelection(':', "end");
            }
        }});
        code_editor.setOption('onKeyEvent', function (instance, key_event) {

                function changeCursor(state) {
                     var cm_div = document.getElementsByClassName('CodeMirror')[0];
                     var current_class = cm_div.className;
                     var focus = current_class.search('CodeMirror-focused');
                     var new_class;
                     if (state === 'normal') {
                         new_class = 'CodeMirror cm-s-codacity cm-keymap-fat-cursor';
                     }
                     else if (state === 'insert') {
                         new_class = 'CodeMirror cm-s-codacity';
                     }
                     if (focus) {
                         new_class = new_class + ' CodeMirror-focused';
                     }
                     cm_div.className = new_class;
                 }

                 // ESC
                 if (key_event.keyCode === 27) {
                     changeCursor('normal');
                 }
                 // C-[
                 else if (key_event.keyCode === 219 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // C-c
                 else if (key_event.keyCode === 67 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // a
                 else if (key_event.keyCode === 65) {
                     changeCursor('insert');
                 }

                 // i
                 else if (key_event.keyCode === 73) {
                     changeCursor('insert');
                 }

                 // s
                 else if (key_event.keyCode === 83) {
                     changeCursor('insert');
                 }

                 // o
                 else if (key_event.keyCode === 79) {
                     changeCursor('insert');
                 }
        });
    }

    else if (keymap_mode === 'DEFAULT') {
        code_editor.setOption('keyMap', 'default');
        code_editor.setOption('extraKeys', null);

    }

    else if (keymap_mode === 'EMACS') {
        code_editor.setOption('keyMap', 'emacs');
        code_editor.setOption('extraKeys', null);
        code_editor.setOption('onKeyEvent', function () {});
    }
}

function load_bindings () {

        function insert_script(name, url) {
            var newscript = document.createElement('script');
            newscript.type = 'text/javascript';
            newscript.src = url;
            newscript.id = name;
            document.head.appendChild(newscript);
        }

        var scripts = [{name: 'vimbindings',
                        src:'http://ecmendenhall.github.com/udacity-keybindings/vim.js'},
                       {name: 'emacsbindings',
                        src: 'http://ecmendenhall.github.com/udacity-keybindings/emacs.js'}];

        for (var i=0, len=scripts.length; i<len; i++) {
            insert_script(scripts[i].name, scripts[i].src);
        }

        var cursor_style = ['.CodeMirror.cm-keymap-fat-cursor pre.CodeMirror-cursor {',
                           '    z-index: 10;',
                           '    width: auto;',
                           '    border: 0;',
                           '    background: transparent;',
                           '    background: rgba(0, 200, 0, .4);',
                           '}'].join('\n');

        var new_css = document.createElement('style');
        new_css.type = 'text/css';
        new_css.innerHTML = cursor_style;
        document.head.appendChild(new_css);
}

function load_keymap_btn () {

    function toggle_mode (btn) {
        var binding_titles = ["DEFAULT", "VIM", "EMACS"];
        var btn_state = btn.getAttribute('state');
        var i = parseInt(btn_state, 10);
        i = (i + 1) % binding_titles.length;
        btn.setAttribute("state", i);
        var keymap_mode = binding_titles[i];
        if (document.all) {
            btn.firstElementChild.innerText = keymap_mode;
        } else {
            btn.firstElementChild.textContent = keymap_mode;
        }
        return keymap_mode;
    }

    function reset_mode (btn) {
        btn.setAttribute("state", 0);
        if (document.all) {
            btn.firstElementChild.innerText = "DEFAULT";
        } else {
            btn.firstElementChild.textContent = "DEFAULT";
        }
    }

    function try_append () {
        var test_run = document.getElementsByClassName('test-run')[0];
        if (test_run) {
          quiz_controls.appendChild(keymap_btn);
        } else {
            setTimeout(try_append, 500);
        }
    }

    var quiz_controls = document.getElementsByClassName('programming-quiz-controls')[0];

    var keymap_btn = document.createElement('div');
    keymap_btn.setAttribute("class", "btn");
    keymap_btn.setAttribute("id", "keymap_btn");
    if (document.all) {
        keymap_btn.innerText = " Key bindings: ";
    } else {
        keymap_btn.textContent = " Key bindings: ";
    }
    var strong_state = document.createElement('strong');
    if (document.all) {
        strong_state.innerText = "DEFAULT";
    } else {
        strong_state.textContent = "DEFAULT";
    }
    keymap_btn.appendChild(strong_state);

    var keymap_btn_style = ['#keymap_btn {',
                             '  margin-right: 10px;',
                             '  line-height: 18px;',
                             '}'].join('\n');

    var keymap_btn_css = document.createElement('style');
        keymap_btn_css.type = 'text/css';
        keymap_btn_css.innerHTML = keymap_btn_style;
        document.head.appendChild(keymap_btn_css);

    keymap_btn.setAttribute("state", 0);

    keymap_btn.addEventListener('click', function () {
        var keymap_mode = toggle_mode(this);
        inject(change_keymap);
    });

    window.addEventListener('hashchange', function () {
        reset_mode(keymap_btn);
    });

    inject(load_bindings);
    try_append();

}

load_keymap_btn();
<commit_msg>Incremented version number.<commit_after>// ==UserScript==
// @name Udacity Extended Keybindings
// @description Vim and Emacs keybindings for the Udacity IDE.
// @version 0.9.3
//
// @namespace http://e.cmendenhall.com/
//
// @downloadURL http://ecmendenhall.github.com/udacity-keybindings/udacity-extended-keybindings.user.js
//
// @include https://www.udacity.com/course/viewer*
// @match https://www.udacity.com/course/viewer*
//
//
// ==/UserScript==

function inject(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script);
    document.body.removeChild(script);
}

function change_keymap () {

    var codemirror = document.getElementsByClassName('CodeMirror')[0];
    var code_editor = codemirror.CodeMirror;
    var keymap_mode;

    if (document.all) {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.innerText;
    } else {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.textContent;
    }

    if (keymap_mode === 'VIM') {

        code_editor.setOption('keyMap', 'vim');
        code_editor.setOption('extraKeys', {"':'": function (cm) {
            var state = cm.getOption('keyMap')
            if (state === 'vim-insert') {
               cm.replaceSelection(':', "end");
            }
        }});
        code_editor.setOption('onKeyEvent', function (instance, key_event) {

                function changeCursor(state) {
                     var cm_div = document.getElementsByClassName('CodeMirror')[0];
                     var current_class = cm_div.className;
                     var focus = current_class.search('CodeMirror-focused');
                     var new_class;
                     if (state === 'normal') {
                         new_class = 'CodeMirror cm-s-codacity cm-keymap-fat-cursor';
                     }
                     else if (state === 'insert') {
                         new_class = 'CodeMirror cm-s-codacity';
                     }
                     if (focus) {
                         new_class = new_class + ' CodeMirror-focused';
                     }
                     cm_div.className = new_class;
                 }

                 // ESC
                 if (key_event.keyCode === 27) {
                     changeCursor('normal');
                 }
                 // C-[
                 else if (key_event.keyCode === 219 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // C-c
                 else if (key_event.keyCode === 67 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // a
                 else if (key_event.keyCode === 65) {
                     changeCursor('insert');
                 }

                 // i
                 else if (key_event.keyCode === 73) {
                     changeCursor('insert');
                 }

                 // s
                 else if (key_event.keyCode === 83) {
                     changeCursor('insert');
                 }

                 // o
                 else if (key_event.keyCode === 79) {
                     changeCursor('insert');
                 }
        });
    }

    else if (keymap_mode === 'DEFAULT') {
        code_editor.setOption('keyMap', 'default');
        code_editor.setOption('extraKeys', null);

    }

    else if (keymap_mode === 'EMACS') {
        code_editor.setOption('keyMap', 'emacs');
        code_editor.setOption('extraKeys', null);
        code_editor.setOption('onKeyEvent', function () {});
    }
}

function load_bindings () {

        function insert_script(name, url) {
            var newscript = document.createElement('script');
            newscript.type = 'text/javascript';
            newscript.src = url;
            newscript.id = name;
            document.head.appendChild(newscript);
        }

        var scripts = [{name: 'vimbindings',
                        src:'http://ecmendenhall.github.com/udacity-keybindings/vim.js'},
                       {name: 'emacsbindings',
                        src: 'http://ecmendenhall.github.com/udacity-keybindings/emacs.js'}];

        for (var i=0, len=scripts.length; i<len; i++) {
            insert_script(scripts[i].name, scripts[i].src);
        }

        var cursor_style = ['.CodeMirror.cm-keymap-fat-cursor pre.CodeMirror-cursor {',
                           '    z-index: 10;',
                           '    width: auto;',
                           '    border: 0;',
                           '    background: transparent;',
                           '    background: rgba(0, 200, 0, .4);',
                           '}'].join('\n');

        var new_css = document.createElement('style');
        new_css.type = 'text/css';
        new_css.innerHTML = cursor_style;
        document.head.appendChild(new_css);
}

function load_keymap_btn () {

    function toggle_mode (btn) {
        var binding_titles = ["DEFAULT", "VIM", "EMACS"];
        var btn_state = btn.getAttribute('state');
        var i = parseInt(btn_state, 10);
        i = (i + 1) % binding_titles.length;
        btn.setAttribute("state", i);
        var keymap_mode = binding_titles[i];
        if (document.all) {
            btn.firstElementChild.innerText = keymap_mode;
        } else {
            btn.firstElementChild.textContent = keymap_mode;
        }
        return keymap_mode;
    }

    function reset_mode (btn) {
        btn.setAttribute("state", 0);
        if (document.all) {
            btn.firstElementChild.innerText = "DEFAULT";
        } else {
            btn.firstElementChild.textContent = "DEFAULT";
        }
    }

    function try_append () {
        var test_run = document.getElementsByClassName('test-run')[0];
        if (test_run) {
          quiz_controls.appendChild(keymap_btn);
        } else {
            setTimeout(try_append, 500);
        }
    }

    var quiz_controls = document.getElementsByClassName('programming-quiz-controls')[0];

    var keymap_btn = document.createElement('div');
    keymap_btn.setAttribute("class", "btn");
    keymap_btn.setAttribute("id", "keymap_btn");
    if (document.all) {
        keymap_btn.innerText = " Key bindings: ";
    } else {
        keymap_btn.textContent = " Key bindings: ";
    }
    var strong_state = document.createElement('strong');
    if (document.all) {
        strong_state.innerText = "DEFAULT";
    } else {
        strong_state.textContent = "DEFAULT";
    }
    keymap_btn.appendChild(strong_state);

    var keymap_btn_style = ['#keymap_btn {',
                             '  margin-right: 10px;',
                             '  line-height: 18px;',
                             '}'].join('\n');

    var keymap_btn_css = document.createElement('style');
        keymap_btn_css.type = 'text/css';
        keymap_btn_css.innerHTML = keymap_btn_style;
        document.head.appendChild(keymap_btn_css);

    keymap_btn.setAttribute("state", 0);

    keymap_btn.addEventListener('click', function () {
        var keymap_mode = toggle_mode(this);
        inject(change_keymap);
    });

    window.addEventListener('hashchange', function () {
        reset_mode(keymap_btn);
    });

    inject(load_bindings);
    try_append();

}

load_keymap_btn();
<|endoftext|>


<commit_before>goog.provide("prism.theme.builder.ui.ThemesUI");

goog.require("goog.cssom");
goog.require("goog.dom");
goog.require("goog.events");
goog.require("goog.dom.classlist");
goog.require("goog.events.EventType");
goog.require("prism.theme.builder.LanguageTheme");
goog.require("prism.theme.builder.LanguageThemeFactory");
goog.require("prism.theme.builder.ui.AbstractUI");
goog.require("prism.theme.builder.ui.Event");
goog.require("prism.theme.builder.ui.EventType");
goog.require("prism.theme.builder.ui.PrismPalette");

/**
 * @constructor
 * @author Sandra https://github.com/SandraShklyaeva
 *
 * @param {goog.ui.ControlRenderer}
 *            opt_renderer
 * @param {goog.dom.DomHelper}
 *            opt_domHelper
 * @extends {prism.theme.builder.ui.AbstractUI}
 */
prism.theme.builder.ui.ThemesUI = function(builder, opt_renderer, opt_domHelper) {

	prism.theme.builder.ui.AbstractUI.call(this, null, opt_renderer,
			opt_domHelper);

	this.builder = builder;
	this.palette = new prism.theme.builder.ui.PrismPalette();
}
goog.inherits(prism.theme.builder.ui.ThemesUI,
		prism.theme.builder.ui.AbstractUI);

/**
 *
 */
prism.theme.builder.ui.ThemesUI.prototype.createContent = function() {

};

/**
 *
 */
prism.theme.builder.ui.ThemesUI.prototype.render = function(element) {

	this.sceneStyles = [];

	this.scene = goog.dom.createElement("div");
	goog.dom.classlist.add(this.scene, "Builder-ThemesOverviewWrapper");

	var themesDiv = goog.dom.createElement("div");
	goog.dom.classlist.add(themesDiv, "Builder-ThemesOverview");
	goog.dom.classlist.add(themesDiv, "pure-g");

	var themes = prism.theme.builder.LanguageThemeFactory.themes;

	for ( var themeName in themes) {
		var theme = new prism.theme.builder.LanguageTheme();
		prism.theme.builder.LanguageThemeFactory.applyTheme(themeName,
				this.builder.getTokens(), theme);

		var themeWrapperWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist
				.set(themeWrapperWrapperDiv, "pure-u-1 pure-u-lg-1-3");

		var themeWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist.add(themeWrapperDiv, "theme-" + themeName);
		goog.dom.classlist.add(themeWrapperDiv, "Builder-ThemesOverview-Item");

		var author = prism.theme.builder.LanguageThemeFactory
				.getAuthor(themeName);
		var themeHeader = goog.dom.createElement("h2");

		if (author != null) {
			goog.dom.setTextContent(themeHeader, theme.getLabel() + " / ");
			var authorLabel = this.getDomHelper().createElement("a");
			goog.dom.setProperties(authorLabel, {
				"title" : "View author's profile on GitHub",
				"href" : "https://github.com/" + author,
				"target" : "_blank"
			});
			goog.dom.setTextContent(authorLabel, author);
			goog.dom.appendChild(themeHeader, authorLabel);
		} else {
			goog.dom.setTextContent(themeHeader, theme.getLabel());
		}

		goog.dom.appendChild(themeWrapperDiv, themeHeader);

		var themeInnerWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist.add(themeInnerWrapperDiv,
				"Builder-ThemesOverview-Inner");

		var themePre = goog.dom.createElement("pre");
		var themeCode = goog.dom.createElement("code");
		goog.dom.classlist.set(themeCode, "language-javascript");
		goog.dom.setTextContent(themeCode, this.getDummyCode());

		goog.dom.appendChild(themePre, themeCode);
		goog.dom.appendChild(themeInnerWrapperDiv, themePre);
		goog.dom.appendChild(themeWrapperDiv, themeInnerWrapperDiv);
		this.createButtons(themeWrapperDiv, themeName);

		goog.dom.appendChild(themeWrapperWrapperDiv, themeWrapperDiv);
		goog.dom.appendChild(themesDiv, themeWrapperWrapperDiv);

		this.sceneStyles.push(goog.cssom.addCssText(theme.toCSS(null,
				(".theme-" + themeName)), null));
	}

	var content = this.getDomHelper().createElement("div");
	goog.dom.classlist.add(content, "Builder-UIContent");

	this.getDomHelper().appendChild(this.scene, themesDiv);
	this.getDomHelper().appendChild(content, this.scene);
	this.setContent(content);

	prism.theme.builder.ui.ThemesUI.base(this, 'render', element);
	var parentElement = this.getElement();

	this.palette.render(parentElement);

};

prism.theme.builder.ui.ThemesUI.prototype.createButtons = function(parentNode,
		themeName) {

	var wrapper = goog.dom.createElement("div");
	goog.dom.classlist.add(wrapper, "pure-g");

	var unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	var button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "View");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this
				.dispatchEvent(new prism.theme.builder.ui.Event(themeName,
						null, prism.theme.builder.ui.EventType.VIEW,
						this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "Edit");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this
				.dispatchEvent(new prism.theme.builder.ui.Event(themeName,
						null, prism.theme.builder.ui.EventType.EDIT,
						this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "Download");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this.dispatchEvent(new prism.theme.builder.ui.Event(themeName, null,
				prism.theme.builder.ui.EventType.DOWNLOAD,
				this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	goog.dom.appendChild(parentNode, wrapper);
}

prism.theme.builder.ui.ThemesUI.prototype.getDummyCode = function() {
	return "function rise(name){\n"
			+ "    return \"Rise and shine, \" + name + \". Rise and... shine.\"\n"
			+ "};\n"
			+ "\n"
			+ "rise(\"Mister Freeman\");\n"
			+ "\n"
			+ "var answer = prompt(\"Do you really want to live in a world without coca-cola?\");\n"
			+ "" + "";
}<commit_msg>fixed layout for themes<commit_after>goog.provide("prism.theme.builder.ui.ThemesUI");

goog.require("goog.cssom");
goog.require("goog.dom");
goog.require("goog.events");
goog.require("goog.dom.classlist");
goog.require("goog.events.EventType");
goog.require("prism.theme.builder.LanguageTheme");
goog.require("prism.theme.builder.LanguageThemeFactory");
goog.require("prism.theme.builder.ui.AbstractUI");
goog.require("prism.theme.builder.ui.Event");
goog.require("prism.theme.builder.ui.EventType");
goog.require("prism.theme.builder.ui.PrismPalette");

/**
 * @constructor
 * @author Sandra https://github.com/SandraShklyaeva
 *
 * @param {goog.ui.ControlRenderer}
 *            opt_renderer
 * @param {goog.dom.DomHelper}
 *            opt_domHelper
 * @extends {prism.theme.builder.ui.AbstractUI}
 */
prism.theme.builder.ui.ThemesUI = function(builder, opt_renderer, opt_domHelper) {

	prism.theme.builder.ui.AbstractUI.call(this, null, opt_renderer,
			opt_domHelper);

	this.builder = builder;
	this.palette = new prism.theme.builder.ui.PrismPalette();
}
goog.inherits(prism.theme.builder.ui.ThemesUI,
		prism.theme.builder.ui.AbstractUI);

/**
 *
 */
prism.theme.builder.ui.ThemesUI.prototype.createContent = function() {

};

/**
 *
 */
prism.theme.builder.ui.ThemesUI.prototype.render = function(element) {

	this.sceneStyles = [];

	this.scene = goog.dom.createElement("div");
	goog.dom.classlist.add(this.scene, "Builder-ThemesOverviewWrapper");

	var themesDiv = goog.dom.createElement("div");
	goog.dom.classlist.add(themesDiv, "Builder-ThemesOverview");
	goog.dom.classlist.add(themesDiv, "pure-g");

	var themes = prism.theme.builder.LanguageThemeFactory.themes;

	for ( var themeName in themes) {
		var theme = new prism.theme.builder.LanguageTheme();
		prism.theme.builder.LanguageThemeFactory.applyTheme(themeName,
				this.builder.getTokens(), theme);

		var themeWrapperWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist
				.set(themeWrapperWrapperDiv, "pure-u-1 pure-u-lg-1-2");

		var themeWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist.add(themeWrapperDiv, "theme-" + themeName);
		goog.dom.classlist.add(themeWrapperDiv, "Builder-ThemesOverview-Item");

		var author = prism.theme.builder.LanguageThemeFactory
				.getAuthor(themeName);
		var themeHeader = goog.dom.createElement("h2");

		if (author != null) {
			goog.dom.setTextContent(themeHeader, theme.getLabel() + " / ");
			var authorLabel = this.getDomHelper().createElement("a");
			goog.dom.setProperties(authorLabel, {
				"title" : "View author's profile on GitHub",
				"href" : "https://github.com/" + author,
				"target" : "_blank"
			});
			goog.dom.setTextContent(authorLabel, author);
			goog.dom.appendChild(themeHeader, authorLabel);
		} else {
			goog.dom.setTextContent(themeHeader, theme.getLabel());
		}

		goog.dom.appendChild(themeWrapperDiv, themeHeader);

		var themeInnerWrapperDiv = goog.dom.createElement("div");
		goog.dom.classlist.add(themeInnerWrapperDiv,
				"Builder-ThemesOverview-Inner");

		var themePre = goog.dom.createElement("pre");
		var themeCode = goog.dom.createElement("code");
		goog.dom.classlist.set(themeCode, "language-javascript");
		goog.dom.setTextContent(themeCode, this.getDummyCode());

		goog.dom.appendChild(themePre, themeCode);
		goog.dom.appendChild(themeInnerWrapperDiv, themePre);
		goog.dom.appendChild(themeWrapperDiv, themeInnerWrapperDiv);
		this.createButtons(themeWrapperDiv, themeName);

		goog.dom.appendChild(themeWrapperWrapperDiv, themeWrapperDiv);
		goog.dom.appendChild(themesDiv, themeWrapperWrapperDiv);

		this.sceneStyles.push(goog.cssom.addCssText(theme.toCSS(null,
				(".theme-" + themeName)), null));
	}

	var content = this.getDomHelper().createElement("div");
	goog.dom.classlist.add(content, "Builder-UIContent");

	this.getDomHelper().appendChild(this.scene, themesDiv);
	this.getDomHelper().appendChild(content, this.scene);
	this.setContent(content);

	prism.theme.builder.ui.ThemesUI.base(this, 'render', element);
	var parentElement = this.getElement();

	this.palette.render(parentElement);

};

prism.theme.builder.ui.ThemesUI.prototype.createButtons = function(parentNode,
		themeName) {

	var wrapper = goog.dom.createElement("div");
	goog.dom.classlist.add(wrapper, "pure-g");

	var unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	var button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "View");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this
				.dispatchEvent(new prism.theme.builder.ui.Event(themeName,
						null, prism.theme.builder.ui.EventType.VIEW,
						this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "Edit");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this
				.dispatchEvent(new prism.theme.builder.ui.Event(themeName,
						null, prism.theme.builder.ui.EventType.EDIT,
						this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	unit = goog.dom.createElement("div");
	goog.dom.classlist.set(unit, "pure-u-1-3");
	goog.dom.appendChild(wrapper, unit);

	button = goog.dom.createElement("div");
	goog.dom.classlist.set(button, "Builder-Button");
	goog.dom.setTextContent(button, "Download");
	goog.events.listen(button, goog.events.EventType.CLICK, function(e) {
		this.dispatchEvent(new prism.theme.builder.ui.Event(themeName, null,
				prism.theme.builder.ui.EventType.DOWNLOAD,
				this.actualEventTarget_));
	}, false, this);

	goog.dom.appendChild(unit, button);

	goog.dom.appendChild(parentNode, wrapper);
}

prism.theme.builder.ui.ThemesUI.prototype.getDummyCode = function() {
	return "function rise(name){\n"
			+ "    return \"Rise and shine, \" + name + \". Rise and... shine.\"\n"
			+ "};\n"
			+ "\n"
			+ "rise(\"Mister Freeman\");\n"
			+ "\n"
			+ "var answer = prompt(\"Do you really want to live in a world without coca-cola?\");\n"
			+ "" + "";
}<|endoftext|>