<commit_before>Ext.ux.ToastWindowMgr = {
    positions: []
};

Ext.ux.ToastWindow = Ext.extend(Ext.Window, {
    initComponent: function(){
          Ext.apply(this, {
              iconCls: this.iconCls || 'information',
            width: 200,
            height: 100,
            autoScroll: true,
            autoDestroy: true,
            plain: false
          });
        this.task = new Ext.util.DelayedTask(this.hide, this);
        Ext.ux.ToastWindow.superclass.initComponent.call(this);
    },
    setMessage: function(msg){
        this.body.update(msg);
    },
    setTitle: function(title, iconCls){
        Ext.ux.ToastWindow.superclass.setTitle.call(this, title, iconCls||this.iconCls);
    },
    onRender:function(ct, position) {
        Ext.ux.ToastWindow.superclass.onRender.call(this, ct, position);
    },
    onDestroy: function(){
        Ext.ux.ToastWindowMgr.positions.remove(this.pos);
        Ext.ux.ToastWindow.superclass.onDestroy.call(this);
    },
    afterShow: function(){
        Ext.ux.ToastWindow.superclass.afterShow.call(this);
        this.on('move', function(){
               Ext.ux.ToastWindowMgr.positions.remove(this.pos);
            this.task.cancel();}
        , this);
        this.task.delay(2000);
    },
    animShow: function(){
        this.pos = 0;
        while(Ext.ux.ToastWindowMgr.positions.indexOf(this.pos)>-1)
            this.pos++;
        Ext.ux.ToastWindowMgr.positions.push(this.pos);
        this.setSize(200,100);
        this.el.alignTo(document, "br-br", [ -20, -20-((this.getSize().height+10)*this.pos) ]);
        this.el.slideIn('b', {
            duration: 1,
            callback: this.afterShow,
            scope: this
        });
    },
    animHide: function(){
           Ext.ux.ToastWindowMgr.positions.remove(this.pos);
        this.el.ghost("b", {
            duration: 1,
            remove: true,
        scope: this,
        callback: this.destroy
        });
    }
});<commit_msg> - enhancement: added configuration properties for creating instances of ToastWindow<commit_after>Ext.ux.ToastWindowMgr = {
    positions: []
};

Ext.ux.ToastWindow = Ext.extend(Ext.Window, {
    initComponent: function(){
          Ext.applyIf(this, {
              iconCls: this.iconCls || 'information',
            width: 200,
            height: 100,
            delay : 2000,
            autoScroll: true,
            autoDestroy: true,
            plain: false
          });
        this.task = new Ext.util.DelayedTask(this.hide, this);
        Ext.ux.ToastWindow.superclass.initComponent.call(this);
    },
    setMessage: function(msg){
        this.body.update(msg);
    },
    setTitle: function(title, iconCls){
        Ext.ux.ToastWindow.superclass.setTitle.call(this, title, iconCls||this.iconCls);
    },
    onRender:function(ct, position) {
        Ext.ux.ToastWindow.superclass.onRender.call(this, ct, position);
    },
    onDestroy: function(){
        Ext.ux.ToastWindowMgr.positions.remove(this.pos);
        Ext.ux.ToastWindow.superclass.onDestroy.call(this);
    },
    afterShow: function(){
        Ext.ux.ToastWindow.superclass.afterShow.call(this);
        this.on('move', function(){
               Ext.ux.ToastWindowMgr.positions.remove(this.pos);
            this.task.cancel();}
        , this);
        this.task.delay(this.delay);
    },
    animShow: function(){
        this.pos = 0;
        while(Ext.ux.ToastWindowMgr.positions.indexOf(this.pos)>-1)
            this.pos++;
        Ext.ux.ToastWindowMgr.positions.push(this.pos);
        this.setSize(this.width, this.height);
        this.el.alignTo(document, "br-br", [ -20, -20-((this.getSize().height+10)*this.pos) ]);
        this.el.slideIn('b', {
            duration: 1,
            callback: this.afterShow,
            scope: this
        });
    },
    animHide: function(){
           Ext.ux.ToastWindowMgr.positions.remove(this.pos);
        this.el.ghost("b", {
            duration: 1,
            remove: true,
        scope: this,
        callback: this.destroy
        });
    }
});<|endoftext|>


<commit_before>/**
* user.js
* Handles all of the user functions the client needs
* to perform in conjunction with the server.
* Author: Nick Rabb <nrabb@outlook.com>
* Yes And Games (C) 2016
* yesandgames@gmail.com
*/

/*global $*/
/*global yag_api_endpoint*/

/**
 * Get the details of a user's data.
 * @author Nick Rabb <nrabb@outlook.com>
 * @param {number} userId     The ID of the user to fetch data for.
 */
function userGetData(userId, callback) {
  'use strict';
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": yag_api_endpoint + "users/" + userId,
    "method": "GET",
    "headers": {
      "content-type": "application/json",
      "cache-control": "no-cache"
    },
    "processData": false
  };

  $.ajax(settings).done(function (response) {
    callback();
  });
}
<commit_msg>Added set email function to user client file<commit_after>/**
* user.js
* Handles all of the user functions the client needs
* to perform in conjunction with the server.
* Author: Nick Rabb <nrabb@outlook.com>
* Yes And Games (C) 2016
* yesandgames@gmail.com
*/

/*global $*/
/*global yag_api_endpoint*/

/**
 * Get the details of a user's data.
 * @author Nick Rabb <nrabb@outlook.com>
 * @param {number} userId     The ID of the user to fetch data for.
 */
function userGetData(userId, callback) {
  'use strict';
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": yag_api_endpoint + "users/" + userId,
    "method": "GET",
    "headers": {
      "content-type": "application/json",
      "cache-control": "no-cache"
    },
    "processData": false
  };

  $.ajax(settings).done(function (response) {
    callback();
  });
}

/**
 * Set a user's email address.
 * @author Nick Rabb <nrabb@outlook.com>
 * @param {number} userId     The ID of the user to fetch data for.
 * @param {string} email      The email address to use for the user.
 * @param {string} password   The user's password.
 * @param {function} callback Code to run after the request comes back.
 */
function userSetEmail(userId, email, password, callback) {
    'use strict';
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": yag_api_endpoint + "users/" + userId + "/setEmail",
      "method": "POST",
      "headers": {
        "content-type": "application/json",
        "cache-control": "no-cache"
      },
      "data": "{\n  \"email\": \"" + email + "\", \"password\":\" + password + \"\n}",
      "processData": false
    };

    $.ajax(settings).done(function (response) {
      callback();
    });
}
<|endoftext|>


<commit_before>game.SmallMap = me.Entity.extend({

});

<commit_msg>finished video I6<commit_after>game.SmallMap = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, "init", [x, y, {
                image: "smallmap",
                width: 507,
                height: 76,
                spritewidth: "507",
                spriteheight: "76",
                getShape: function(){
                    return(new meRect(0, 0, 507, 76)).toPolygon();
                }
        }]);
    this.floating = true;
    }
});

<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import Command from '../../utils/Command';
import Calculation from '../../utils/Calculation';

import './TextInput.scss';

export default class TextInput extends Component {

    constructor(props) {

        super(props);

        this.state = {
            value: this.calculateValue(props)
        };

        this.focus = this::this.focus;
        this.calculateValue = this::this.calculateValue;
        this.doChange = this::this.doChange;
        this.changeHandle = this::this.changeHandle;
        this.keyDownHandle = this::this.keyDownHandle;

    }

    focus(props = this.props) {

        if (!props.isEditorFocused) {
            return;
        }

        const textInput = this.refs.textInput;

        setTimeout(() => {
            textInput.focus();
            textInput.setSelectionRange(0, textInput.value.length);
        }, 0);

    }

    calculateValue(props = this.props) {
        return Calculation.getSelectionValue(props);
    }

    doChange(result) {

        if (!result) {
            return;
        }

        const {newDataArray, newPosition} = result;

        this.setState({
            value: this.calculateValue()
        }, () => {
            this.props.onChange(newDataArray, newPosition);
            this.focus();
        });

    }

    changeHandle(e) {
        // if (e.target.value === '') {
        //     this.doChange(Command.doCut(this.props)); // cut
        // } else {
        this.doChange(Command.doInput(e.target.value, this.props));
        // }
    }

    keyDownHandle(e) {
        switch (e.keyCode) {
            case 8: // back space
                e.preventDefault();
                this.doChange(Command.doDelete(this.props));
                break;
        }
    }

    componentDidMount() {
        this.focus();
    }

    componentWillReceiveProps(nextProps) {

        if (!_.isEqual(nextProps.selectStartPosition, this.props.selectStartPosition)
            || !_.isEqual(nextProps.selectStopPosition, this.props.selectStopPosition)) {
            this.setState({
                value: this.calculateValue(nextProps)
            }, () => {
                this.focus(nextProps);
            });
        }

        this.focus(nextProps);

    }

    componentDidUpdate(prevProps) {
        this.focus(prevProps);
    }

    render() {

        const {value} = this.state;

        return (
            <textarea ref="textInput"
                      className="react-editor-text-input"
                      value={value}
                      onChange={this.changeHandle}
                      onKeyDown={this.keyDownHandle}></textarea>
        );

    }
};

TextInput.propTypes = {

    editorEl: PropTypes.object,
    isEditorFocused: PropTypes.bool,
    editorDataArray: PropTypes.array,
    selectStartPosition: PropTypes.object,
    selectStopPosition: PropTypes.object,

    onChange: PropTypes.func

};

TextInput.defaultProps = {
    editorEl: null,
    editorDataArray: [],
    selectStartPosition: null,
    selectStopPosition: null
};<commit_msg>update<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';

import Command from '../../utils/Command';
import Calculation from '../../utils/Calculation';

import './TextInput.scss';

export default class TextInput extends Component {

    constructor(props) {

        super(props);

        // this.state = {
        //     value: this.calculateValue(props)
        // };

        this.focus = this::this.focus;
        this.calculateValue = this::this.calculateValue;
        this.doChange = this::this.doChange;
        this.changeHandle = this::this.changeHandle;
        this.keyDownHandle = this::this.keyDownHandle;

    }

    focus(props = this.props) {

        if (!props.isEditorFocused) {
            return;
        }

        const textInput = this.refs.textInput;

        setTimeout(() => {
            textInput.focus();
            textInput.setSelectionRange(0, textInput.value.length);
        }, 0);

    }

    calculateValue(props = this.props) {
        return Calculation.getSelectionValue(props);
    }

    doChange(result) {

        if (!result) {
            return;
        }

        const {newDataArray, newPosition} = result;

        // this.setState({
        //     value: this.calculateValue()
        // }, () => {

        // this.refs.textInput.value = this.calculateValue();
        this.props.onChange(newDataArray, newPosition);
        this.focus();
        // });

    }

    changeHandle(e) {
        // if (e.target.value === '') {
        //     this.doChange(Command.doCut(this.props)); // cut
        // } else {
        this.doChange(Command.doInput(e.target.value, this.props));
        // }
    }

    keyDownHandle(e) {
        switch (e.keyCode) {
            case 8: // back space
                e.preventDefault();
                this.doChange(Command.doDelete(this.props));
                break;
        }
    }

    componentDidMount() {

        // this.refs.textInput.value = this.calculateValue();

        this.focus();

    }

    componentWillReceiveProps(nextProps) {

        if (!_.isEqual(nextProps.selectStartPosition, this.props.selectStartPosition)
            || !_.isEqual(nextProps.selectStopPosition, this.props.selectStopPosition)) {
            // this.setState({
            //     value: this.calculateValue(nextProps)
            // }, () => {
            // this.refs.textInput.value = this.calculateValue(nextProps);
            this.focus(nextProps);
            // });
        }

        this.focus(nextProps);

    }

    componentDidUpdate(prevProps) {
        this.focus(prevProps);
    }

    render() {

        // const {value} = this.state;

        return (
            <textarea ref="textInput"
                      className="react-editor-text-input"
                // value={value}
                      onChange={this.changeHandle}
                      onKeyDown={this.keyDownHandle}></textarea>
        );

    }
};

TextInput.propTypes = {

    editorEl: PropTypes.object,
    isEditorFocused: PropTypes.bool,
    editorDataArray: PropTypes.array,
    selectStartPosition: PropTypes.object,
    selectStopPosition: PropTypes.object,

    onChange: PropTypes.func

};

TextInput.defaultProps = {
    editorEl: null,
    editorDataArray: [],
    selectStartPosition: null,
    selectStopPosition: null
};<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend ({
	init: function(x, y, settings){
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();
		this.setFlags();

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //makes it so the window always follows the character on BOTH axis

		this.addAnimation();

		this.type = "PlayerEntity";

		this.attack = game.data.playerAttack;
		this.renderable.addAnimation("idle", [78]); //animation for when the character is not moving
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80); //walking animation for character using the OrcSpear sprite sheet

		this.renderable.setCurrentAnimation("idle"); //sets the default animation to "idle"

	},

	setSuper:function(){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64, //size put aside for the character
			height: 64,
			spritewidth: "64", //size of the image
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 50)).toPolygon();	//pretty much the hitbox of the character
			}
		}]);
	},

	setPlayerTimers: function(){
		this.lastAttack = new Date().getTime();
		this.now = new Date().getTime();
		this.lastHit = this.now;
	},

	setAttributes: function(){
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 14); //moves five units right
	},

	setFlags: function(){
		this.dead = false;
		this.facing ="right";
		//keeps track of the direction of the character
	 },

	update: function(delta){
		this.now = new Date().getTime(); //keeps track of the timer

		this.dead.checkIfDead();

		this.checkKeyPressesAndMove();

		this.setAnimation();

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta); //delta is the change in time

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

	checkIfDead: function(){
		if(this.health <=0){ //if the character's health is less than zero
			return true; //the character is dead
		}
	},

	checkKeyPressesAndMove: function(){
		if(me.input.isKeyPressed("right")){ //checks if the right key is pressed
			this.moveRight();
		}
		else if(me.input.isKeyPressed("left")){
			this.moveLeft();
		}
		else{
			this.body.vel.x = 0;
		}
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){ //says that you can only jump if you're not already jumping or falling
			this.jump();
		}

		this.attacking = me.input.isKeyPressed("attack") && !this.body.jumping && !this.body.falling && !isCurrentAnimation("walk");
	},

	moveRight: function(){
		//adds to the position of the x by adding the velocity defined above in setVelocity() and multiplying
		//it by me.timer.tick
		//me.time.tick makes movement smooth
		this.facing = "right";
		this.body.vel.x += this.body.accel.x * me.timer.tick;
		this.flipX(true);
	},

	moveLeft: function(){
		this.facing = "left";
		this.body.vel.x -= this.body.accel.x * me.timer.tick;
		this.flipX(false); //flips the animation so that when the character goes left, the animation goes the same way
	},

	jump: function(){
		this.body.jumping = true;
		this.body.vel.y -= this.body.accel.y * me.timer.tick;
	},

	setAnimation: function(){
		if(this.attacking){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle"); //sets current animation to attack then reverts back to idle
				this.renderable.setAnimationFrame(); //the next time this sequence starts, it begins form the first animtion and not from where it left off
			}
		}
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")){
			this.renderable.setCurrentAnimation("idle"); //if the character isn't moving the character becomes idle
		}
	},

	collideHandler: function(response){
		if(response.b.type === 'EnemyBaseEntity'){ //if something runs into the Enemy base, it checks some things
			var ydif = this.pos.y - response.b.pos.y; //the difference between the base's y and the player's y
			var xdif = this.pos.x - response.b.pos.x; //the difference between the base's x and the player's x

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

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerTimer){ //checks to see if there's been 400 miliseconds since the base was last hit
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerHealth);
			}
		}else if(response.b.type==='EnemyCreep'){
			var ydif = this.pos.y - response.b.pos.y; //the difference between the base's y and the player's y
			var xdif = this.pos.x - response.b.pos.x; //the difference between the base's x and the player's x

			if(xdif > 0){ //makes it so you can't walk through the creep without doing damage
				this.pos.x = this.pos.x +1;
				if(this.facing==='left'){
					this.body.vel.x = 0;
				}
			}else{
				this.pos.x = this.pos.x -1;
				if(this.facing==='right'){
					this.body.vel.x = 0;
				}
			}

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerTimer
				&&	(Math.abs(ydif<=40)
				&& ((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")
				)){ //if I'm attacking, and I attacked one second ago, and my ydif is less than 40, and I'm facing right or left, it will attack
				this.lastHit = this.now;
				//if the creeps health is less than the attack, execute code
				if(response.b.health <= game.data.playerAttack){
					//adds one gold for killing a creep
					console.log("gold " + game.data.gold);
					game.data.gold += 1;
				}

				response.b.loseHealth(game.data.playerAttack);
			}
		}
	},
	loseHealth: function(damage){
		this.health = this.health - damage;
	}
xa<commit_msg>video 33, refactoring collision, CODED (no need for comments) *receiving expected error "x is not defined"<commit_after>game.PlayerEntity = me.Entity.extend ({
	init: function(x, y, settings){
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();
		this.setFlags();

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //makes it so the window always follows the character on BOTH axis

		this.addAnimation();

		this.type = "PlayerEntity";

		this.attack = game.data.playerAttack;
		this.renderable.addAnimation("idle", [78]); //animation for when the character is not moving
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80); //walking animation for character using the OrcSpear sprite sheet

		this.renderable.setCurrentAnimation("idle"); //sets the default animation to "idle"

	},

	setSuper:function(){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64, //size put aside for the character
			height: 64,
			spritewidth: "64", //size of the image
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 50)).toPolygon();	//pretty much the hitbox of the character
			}
		}]);
	},

	setPlayerTimers: function(){
		this.lastAttack = new Date().getTime();
		this.now = new Date().getTime();
		this.lastHit = this.now;
	},

	setAttributes: function(){
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 14); //moves five units right
	},

	setFlags: function(){
		this.dead = false;
		this.facing ="right";
		//keeps track of the direction of the character
	 },

	update: function(delta){
		this.now = new Date().getTime(); //keeps track of the timer

		this.dead.checkIfDead();

		this.checkKeyPressesAndMove();

		this.setAnimation();

		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta); //delta is the change in time

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

	checkIfDead: function(){
		if(this.health <=0){ //if the character's health is less than zero
			return true; //the character is dead
		}
	},

	checkKeyPressesAndMove: function(){
		if(me.input.isKeyPressed("right")){ //checks if the right key is pressed
			this.moveRight();
		}
		else if(me.input.isKeyPressed("left")){
			this.moveLeft();
		}
		else{
			this.body.vel.x = 0;
		}
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){ //says that you can only jump if you're not already jumping or falling
			this.jump();
		}

		this.attacking = me.input.isKeyPressed("attack") && !this.body.jumping && !this.body.falling && !isCurrentAnimation("walk");
	},

	moveRight: function(){
		//adds to the position of the x by adding the velocity defined above in setVelocity() and multiplying
		//it by me.timer.tick
		//me.time.tick makes movement smooth
		this.facing = "right";
		this.body.vel.x += this.body.accel.x * me.timer.tick;
		this.flipX(true);
	},

	moveLeft: function(){
		this.facing = "left";
		this.body.vel.x -= this.body.accel.x * me.timer.tick;
		this.flipX(false); //flips the animation so that when the character goes left, the animation goes the same way
	},

	jump: function(){
		this.body.jumping = true;
		this.body.vel.y -= this.body.accel.y * me.timer.tick;
	},

	setAnimation: function(){
		if(this.attacking){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle"); //sets current animation to attack then reverts back to idle
				this.renderable.setAnimationFrame(); //the next time this sequence starts, it begins form the first animtion and not from where it left off
			}
		}
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")){
			this.renderable.setCurrentAnimation("idle"); //if the character isn't moving the character becomes idle
		}
	},

	collideHandler: function(response){
		this.collideWithEnemyBase(response);

		this.collideWithEnemyCreep(response);

	},

	collideWithEnemyBase: function(){
		if(response.b.type === 'EnemyBaseEntity'){ //if something runs into the Enemy base, it checks some things
			var ydif = this.pos.y - response.b.pos.y; //the difference between the base's y and the player's y
			var xdif = this.pos.x - response.b.pos.x; //the difference between the base's x and the player's x

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

			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerTimer){ //checks to see if there's been 400 miliseconds since the base was last hit
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerHealth);
			}
		}
	},

	collideWithEnemyCreep: function(){
		var ydif = this.pos.y - response.b.pos.y; //the difference between the base's y and the player's y
		var xdif = this.pos.x - response.b.pos.x; //the difference between the base's x and the player's x

		this.stopMovement(xdif);

		if(this.checkAttack(xdif, ydif)){
			this.hitCreep(response);
		};

	},

	stopMovement: function(xdif){
		if(xdif > 0){ //makes it so you can't walk through the creep without doing damage
			this.pos.x = this.pos.x +1;
			if(this.facing==='left'){
				this.body.vel.x = 0;
			}
		}else{
			this.pos.x = this.pos.x -1;
			if(this.facing==='right'){
				this.body.vel.x = 0;
			}
		}
	},

	checkAttack: function(xdif, ydif){
		if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerTimer
			&&	(Math.abs(ydif<=40)
			&& ((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")
			)){ //if I'm attacking, and I attacked one second ago, and my ydif is less than 40, and I'm facing right or left, it will attack
			this.lastHit = this.now;
			return true;
		}
		return false;
	},

	hitCreep: function(response){
		//if the creeps health is less than the attack, execute code
		if(response.b.health <= game.data.playerAttack){
			//adds one gold for killing a creep
			console.log("gold " + game.data.gold);
			game.data.gold += 1;
		}
		response.b.loseHealth(game.data.playerAttack);
	},

	loseHealth: function(damage){
		this.health = this.health - damage;
	}
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';

const TextInput = ({
  labelText,
  className,
  id,
  placeholder,
  type,
  onChange,
  onClick,
  hideLabel,
  invalid,
  invalidText,
  ...other
}) => {
  const textInputProps = {
    id,
    onChange: evt => {
      if (!other.disabled) {
        onChange(evt);
      }
    },
    onClick: evt => {
      if (!other.disabled) {
        onClick(evt);
      }
    },
    placeholder,
    type,
  };

  const textInputClasses = classNames('bx--text-input', className);
  const labelClasses = classNames('bx--label', {
    'bx--visually-hidden': hideLabel,
  });

  const label = labelText ? (

      {labelText}

  ) : null;

  const error = invalid ? (

{invalidText}

  ) : null;

  const input = invalid ? (
    <input
      {...other}
      {...textInputProps}
      data-invalid
      className={textInputClasses}
    />
  ) : (
    <input {...other} {...textInputProps} className={textInputClasses} />
  );

  return (

      {label}
      {input}
      {error}

  );
};

TextInput.propTypes = {
  className: PropTypes.string,
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  disabled: PropTypes.bool,
  id: PropTypes.string.isRequired,
  labelText: PropTypes.string,
  onChange: PropTypes.func,
  onClick: PropTypes.func,
  placeholder: PropTypes.string,
  type: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  hideLabel: PropTypes.bool,
  invalid: PropTypes.bool,
  invalidText: PropTypes.string,
};

TextInput.defaultProps = {
  className: 'bx--text__input',
  disabled: false,
  type: 'text',
  onChange: () => {},
  onClick: () => {},
  invalid: false,
  labelText: '',
  invalidText: 'Provide invalidText',
};

export default TextInput;
<commit_msg>feat(textInput): Add aria-invalid and aria-describedBy to invalid textInput (#439)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';

const TextInput = ({
  labelText,
  className,
  id,
  placeholder,
  type,
  onChange,
  onClick,
  hideLabel,
  invalid,
  invalidText,
  ...other
}) => {
  const textInputProps = {
    id,
    onChange: evt => {
      if (!other.disabled) {
        onChange(evt);
      }
    },
    onClick: evt => {
      if (!other.disabled) {
        onClick(evt);
      }
    },
    placeholder,
    type,
  };

  const errorId = id + '-error-msg';
  const textInputClasses = classNames('bx--text-input', className);
  const labelClasses = classNames('bx--label', {
    'bx--visually-hidden': hideLabel,
  });

  const label = labelText ? (

      {labelText}

  ) : null;

  const error = invalid ? (

      {invalidText}

  ) : null;

  const input = invalid ? (
    <input
      {...other}
      {...textInputProps}
      data-invalid
      aria-invalid
      aria-describedBy={errorId}
      className={textInputClasses}
    />
  ) : (
    <input {...other} {...textInputProps} className={textInputClasses} />
  );

  return (

      {label}
      {input}
      {error}

  );
};

TextInput.propTypes = {
  className: PropTypes.string,
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  disabled: PropTypes.bool,
  id: PropTypes.string.isRequired,
  labelText: PropTypes.string,
  onChange: PropTypes.func,
  onClick: PropTypes.func,
  placeholder: PropTypes.string,
  type: PropTypes.string,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  hideLabel: PropTypes.bool,
  invalid: PropTypes.bool,
  invalidText: PropTypes.string,
};

TextInput.defaultProps = {
  className: 'bx--text__input',
  disabled: false,
  type: 'text',
  onChange: () => {},
  onClick: () => {},
  invalid: false,
  labelText: '',
  invalidText: 'Provide invalidText',
};

export default TextInput;
<|endoftext|>


<commit_before>// TODO
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();
                    //sets player size and shape
                }
            }]);
        this.body.setVelocity(5, 20);
// keeps track of direction
        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
        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");
    },
    update: function(delta) {
        this.now = new Date().getTime();
        if (me.input.isKeyPressed("right")) {
            //sets x position by adding value set in set velocity
            //multiplying by me.timer.tick
            //me.timer.tick smooths movement
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }
        else if (me.input.isKeyPressed("left")) {
            //tells character to move left
            this.facing = "left";
            this.flipX(false);
            // flips animations for moving right
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            // sets velocity and speed for moving left
        }
        else {
            this.body.vel.x = 0;
        }

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

        if (me.input.isKeyPressed("attack")) {
            if (!this.renderable.isCurrentAnimation("attack")) {

                //sets animation to attack and idle after
                this.renderable.setCurrentAnimation("attack", "idle");
                //resets animation process
                this.renderable.setAnimationFrame();
            }

        }

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

                this.renderable.setCurrentAnimation("walk");
            }

        } else if (!this.renderable.isCurrentAnimation("attack")) {
            this.renderable.setCurrentAnimation("idle");
        }
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        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 (ydif < -40 && xdif < 70 && xdif > -35) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            else 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;
            }
            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= 300) {
                console.log(response.b.health);
                this.lastHit = this.now;
                response.b.loseHealth();

            }

        }

    }

});
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, 70)).toPolygon();
                    this.broken = false;
                    this.health = 10;
                    this.alwaysUpdate = true;
                    this.body.onCollision = this.onCollision.bind(this);

                }
            }]);

        this.type = "PlayerBaseEntity";
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    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, 70)).toPolygon();

                    this.body.onCollision = this.onCollision.bind(this);
                }
            }]);
        this.type = "EnemyBaseEntity";
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            console.log("this.health");
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;

    },
    onCollision: function() {

    },
    loseHealth: function() {
        this.health--;
    }

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

            }]);
        this.health = 5;
        this.alwaysUpdate = true;
        this.now = new date().getTime();

        this.body.setVelocity(3, 20);
        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");

    },
    update: function(delta) {

        this.body.vel.x -= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true)

        this.body.update(delta);

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

        return true;
    },

    collideHandler: function(response){

    }

});

game.GameManager = Object.extend({
    init: function(x, y, settings) {
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;

    },
    update: function() {
        this.now = new Date().getTime();

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);

        }
        return true;
    }
});
<commit_msg>back on pace<commit_after>// TODO
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();
                    //sets player size and shape
                }
            }]);
        this.body.setVelocity(5, 20);
// keeps track of direction
        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
        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");
    },
    update: function(delta) {
        this.now = new Date().getTime();
        if (me.input.isKeyPressed("right")) {
            //sets x position by adding value set in set velocity
            //multiplying by me.timer.tick
            //me.timer.tick smooths movement
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }
        else if (me.input.isKeyPressed("left")) {
            //tells character to move left
            this.facing = "left";
            this.flipX(false);
            // flips animations for moving right
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            // sets velocity and speed for moving left
        }
        else {
            this.body.vel.x = 0;
        }

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

        if (me.input.isKeyPressed("attack")) {
            if (!this.renderable.isCurrentAnimation("attack")) {

                //sets animation to attack and idle after
                this.renderable.setCurrentAnimation("attack", "idle");
                //resets animation process
                this.renderable.setAnimationFrame();
            }

        }

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

                this.renderable.setCurrentAnimation("walk");
            }

        } else if (!this.renderable.isCurrentAnimation("attack")) {
            this.renderable.setCurrentAnimation("idle");
        }
        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);
        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 (ydif < -40 && xdif < 70 && xdif > -35) {
                this.body.falling = false;
                this.body.vel.y = -1;
            }
            else 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;
            }
            if (this.renderable.isCurrentAnimation("attack") && this.now - this.lastHit >= 300) {
                console.log(response.b.health);
                this.lastHit = this.now;
                response.b.loseHealth();

            }

        }

    }

});
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, 70)).toPolygon();

                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "PlayerBaseEntity";
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    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;

    },
    loseHealth: function(damage){
        this.health = this.health - damage;
    },

    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, 70)).toPolygon();

                    this.body.onCollision = this.onCollision.bind(this);
                }
            }]);
        this.type = "EnemyBaseEntity";
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            console.log("this.health");
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);
        this._super(me.Entity, "update", [delta]);
        return true;

    },
    onCollision: function() {

    },
    loseHealth: function() {
        this.health--;
    }

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

            }]);
        this.health = 5;
        this.attacking = false;
        //identifies enemy movement is attacking
        this.alwaysUpdate = true;
        this.now = new date().getTime();
        this.lastAttacking = new date().getTime();
        this.lastHit = new date().getTime();
        this.body.setVelocity(3, 20);
        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");

    },
    update: function(delta) {
        this.now = new Date().getTime();

        this.body.vel.x -= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true);

        this.body.update(delta);

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

        return true;
    },
    collideHandler: function(response) {
        if (response.b.type === 'PlayerBaseEntity') {
            this.attacking = true;
            this.lastAttacking = this.now;
            this.body.vel.x = 0;
            this.pos.x = this.pos.x + 1;
            if ((this.now - this.lastHit >= 1000)) {
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }

        }

    }

});

game.GameManager = Object.extend({
    init: function(x, y, settings) {
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;

    },
    update: function() {
        this.now = new Date().getTime();

        if (Math.round(this.now / 1000) % 10 === 0 && (this.now - this.lastCreep >= 1000)) {
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);

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


<commit_before>HAL.Http.Client = function(opts) {
  this.vent = opts.vent;
  this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01' };
  cookie = document.cookie.match('(^|;)\\s*' + 'MyHalBrowserToken' + '\\s*=\\s*([^;]+)');
  cookie ? this.defaultHeaders.Authorization = 'Bearer ' + cookie.pop() : '';
  this.headers = this.defaultHeaders;
};

HAL.Http.Client.prototype.get = function(url) {
  var self = this;
  this.vent.trigger('location-change', { url: url });
  var jqxhr = $.ajax({
    url: url,
    dataType: 'json',
    xhrFields: {
      withCredentials: false
    },
    headers: this.headers,
    success: function(resource, textStatus, jqXHR) {
      self.vent.trigger('response', {
        resource: resource,
        jqxhr: jqXHR,
        headers: jqXHR.getAllResponseHeaders()
      });
    }
  }).fail(function() {
    self.vent.trigger('fail-response', { jqxhr: jqxhr });
  });
};

HAL.Http.Client.prototype.request = function(opts) {
  var self = this;
  opts.dataType = 'json';
  opts.xhrFields = opts.xhrFields || {};
  opts.xhrFields.withCredentials = opts.xhrFields.withCredentials || false;
  self.vent.trigger('location-change', { url: opts.url });
  return jqxhr = $.ajax(opts);
};

HAL.Http.Client.prototype.updateHeaders = function(headers) {
  this.headers = headers;
};

HAL.Http.Client.prototype.getHeaders = function() {
  return this.headers;
};
<commit_msg>chore: add back in the X-Interface='HAL Browser' header<commit_after>HAL.Http.Client = function(opts) {
  this.vent = opts.vent;
  this.defaultHeaders = { 'Accept': 'application/hal+json, application/json, */*; q=0.01', 'X-Interface': 'HAL Browser' }; //pact_broker
  cookie = document.cookie.match('(^|;)\\s*' + 'MyHalBrowserToken' + '\\s*=\\s*([^;]+)');
  cookie ? this.defaultHeaders.Authorization = 'Bearer ' + cookie.pop() : '';
  this.headers = this.defaultHeaders;
};

HAL.Http.Client.prototype.get = function(url) {
  var self = this;
  this.vent.trigger('location-change', { url: url });
  var jqxhr = $.ajax({
    url: url,
    dataType: 'json',
    xhrFields: {
      withCredentials: false
    },
    headers: this.headers,
    success: function(resource, textStatus, jqXHR) {
      self.vent.trigger('response', {
        resource: resource,
        jqxhr: jqXHR,
        headers: jqXHR.getAllResponseHeaders()
      });
    }
  }).fail(function() {
    self.vent.trigger('fail-response', { jqxhr: jqxhr });
  });
};

HAL.Http.Client.prototype.request = function(opts) {
  var self = this;
  opts.dataType = 'json';
  opts.xhrFields = opts.xhrFields || {};
  opts.xhrFields.withCredentials = opts.xhrFields.withCredentials || false;
  self.vent.trigger('location-change', { url: opts.url });
  return jqxhr = $.ajax(opts);
};

HAL.Http.Client.prototype.updateHeaders = function(headers) {
  this.headers = headers;
};

HAL.Http.Client.prototype.getHeaders = function() {
  return this.headers;
};
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import { connect } from "react-redux";
import { push } from "redux-router";

import { CardOverlay } from "../CardOverlay";
import { Card, CardText } from 'material-ui/Card';

import { Actions } from "./redux/actions";
import {
    Actions as ServiceActions,
    ActionKeyStore as ServiceActionKeyStore
} from "../../services/servicemanager/redux/actions";
import {
    Actions as ConfigurationsActions,
    ActionKeyStore as ConfigurationsActionKeyStore
} from "../../services/configurations/redux/actions";

import { resizeVisualization } from "../../utils/resize"

import { GraphManager } from "../Graphs/index";
import { ServiceManager } from "../../services/servicemanager/index";

import style from "./styles"

import FontAwesome from "react-fontawesome";

class VisualizationView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            parameterizable: true,
            hasResults: false,
            showDescription: false,
        }
    }

    componentWillMount() {
        this.initialize(this.props.id);
    }

    componentDidMount() {
        this.updateSize();

        // If present, register the resize callback
        // to respond to interactive resizes from react-grid-layout.
        if (this.props.registerResize) {
            this.props.registerResize(this.updateSize.bind(this))
        }
    }

    componentWillReceiveProps(nextProps) {
        this.initialize(nextProps.id);
    }

    componentDidUpdate() {
        this.updateSize();
    }

    updateSize() {
        if (this._element) {
            const { width, height } = resizeVisualization(this._element);

            if (width !== this.state.width || height !== this.state.height) {
                this.setState({ width, height });
            }
        }
    }

    initialize(id) {

        this.props.fetchConfigurationIfNeeded(id).then((c) => {
            const { configuration } = this.props

            if (!configuration)
                return;

            this.props.fetchQueryIfNeeded(configuration.get("query")).then(() => {
                const { queryConfiguration, executeQueryIfNeeded, context } = this.props;

                if (!queryConfiguration)
                    return;

                executeQueryIfNeeded(queryConfiguration, context).then(
                    () => {
                        this.setState({
                            parameterizable: true,
                        });
                    },
                    (error) => {
                        this.setState({
                            parameterizable: false,
                        });
                    },
                );
            });

            if(configuration.get("listeners")){
                configuration.get("listeners").forEach((listener) => {

                    const {
                      event = "onMarkClick",
                      redirect = window.location.pathname,
                      params = {}
                    } = listener.toJS();

                    console.log("navigation is configured");
                    console.log(event, redirect, params);
                });
            }
        });
    }

    shouldShowVisualization() {
        const { configuration, response } = this.props;

        return configuration && response && !response.isFetching;
    }

    renderVisualization() {
        const { configuration, queryConfiguration, response } = this.props;

        const graphName      = configuration.get("graph"),
              GraphComponent = GraphManager.getGraphComponent(graphName);

        let description;

        if (this.state.showDescription) {
            description = <CardOverlay
                                overlayStyle={style.descriptionContainer}
                                textStyle={style.descriptionText}
                                text={configuration.get("description")}
                                onTouchTapOverlay={() => { this.setState({showDescription: false}); }}
                                />
        }

        return (

                <GraphComponent
                  response={response}
                  configuration={configuration.toJS()}
                  queryConfiguration={queryConfiguration}
                  width={this.state.width}
                  height={this.state.height}
                />
                {description}

        )
    }

    renderVisualizationIfNeeded() {
        if (this.shouldShowVisualization()) {
            return this.renderVisualization();
        }

        if (!this.state.parameterizable) {
            return (
                <CardOverlay
                    overlayStyle={style.overlayContainer}
                    textStyle={style.overlayText}
                    text={(

                            <FontAwesome
                                name="meh-o"
                                size="2x"
                                />

                            Oops, we are missing some parameters here!

                    )}
                    onTouchTapOverlay={() => { this.setState({showDescription: false}); }}
                    />
            )
        }

        return (

                    <FontAwesome
                        name="circle-o-notch"
                        spin
                        />

                    Please wait while loading...

        )
    }

    shouldShowTitle() {
        const { configuration } = this.props;

        return configuration && configuration.get("title") && this.state.parameterizable;
    }

    renderTitleIfNeeded() {
        const { configuration } = this.props;

        if (!this.shouldShowTitle())
            return;

        const descriptionIcon = !configuration.get("description") ? null : (

                <FontAwesome
                    name="info-circle"
                    onTouchTap={() => { this.setState({showDescription: !!configuration.get("description")}); }}
                    />

        )

        return (

                {configuration.get("title")}
                {descriptionIcon}

        )
    }

    cardTextReference = (c) => {
        if (this._element)
            return;

        this._element = ReactDOM.findDOMNode(c).parentElement;
    }

    render() {
        return (
            <Card
              style={style.card}
              containerStyle={style.cardContainer}
              ref={this.cardTextReference}
            >
                { this.renderTitleIfNeeded() };
                <CardText style={style.cardText}>
                    { this.renderVisualizationIfNeeded() }
                </CardText>
            </Card>
        );
    }
}

const mapStateToProps = (state, ownProps) => {

    const configurationID = ownProps.id || ownProps.params.id,
          context         = ownProps.context || ownProps.location.query;

    const props = {
        id: configurationID,
        context: context,

        configuration: state.configurations.getIn([
            ConfigurationsActionKeyStore.VISUALIZATIONS,
            configurationID,
            ConfigurationsActionKeyStore.DATA
        ]),

        error: state.configurations.getIn([
            ConfigurationsActionKeyStore.VISUALIZATIONS,
            configurationID,
            ConfigurationsActionKeyStore.ERROR
        ])

    };

    // Expose the query template as a JS object if it is available.
    if (props.configuration) {
        const queryConfiguration = state.configurations.getIn([
            ConfigurationsActionKeyStore.QUERIES,
            props.configuration.get("query")
        ]);

        if (queryConfiguration && !queryConfiguration.get(
            ConfigurationsActionKeyStore.IS_FETCHING
        )) {
            props.queryConfiguration = queryConfiguration.get(
                ConfigurationsActionKeyStore.DATA
            ).toJS();
        }

        // Expose received response if it is available
        if (props.queryConfiguration) {
            const requestID = ServiceManager.getRequestID(props.queryConfiguration, context);

            let response = state.services.getIn([
                ServiceActionKeyStore.REQUESTS,
                requestID
            ]);

            if (response && !response.get(ServiceActionKeyStore.IS_FETCHING))
                props.response = response.toJS();
        }
    }

    return props;
};

const actionCreators = (dispatch) => ({

    setPageTitle: function(aTitle) {
        dispatch(Actions.updateTitle(aTitle));
    },

    goTo: function(link, filters) {
        dispatch(push({pathname:link, query:filters}));
    },

    fetchConfigurationIfNeeded: function(id) {
        return dispatch(ConfigurationsActions.fetchIfNeeded(
            id,
            ConfigurationsActionKeyStore.VISUALIZATIONS
        ));
    },

    fetchQueryIfNeeded: function(id) {
        return dispatch(ConfigurationsActions.fetchIfNeeded(
            id,
            ConfigurationsActionKeyStore.QUERIES
        ));
    },

    executeQueryIfNeeded: function(queryConfiguration, context) {
        return dispatch(ServiceActions.fetchIfNeeded(queryConfiguration, context));
    }

 });

export default connect(mapStateToProps, actionCreators)(VisualizationView);
<commit_msg>Parse sourceColumn and destinationParam<commit_after>import React from "react";
import ReactDOM from "react-dom";
import { connect } from "react-redux";
import { push } from "redux-router";

import { CardOverlay } from "../CardOverlay";
import { Card, CardText } from 'material-ui/Card';

import { Actions } from "./redux/actions";
import {
    Actions as ServiceActions,
    ActionKeyStore as ServiceActionKeyStore
} from "../../services/servicemanager/redux/actions";
import {
    Actions as ConfigurationsActions,
    ActionKeyStore as ConfigurationsActionKeyStore
} from "../../services/configurations/redux/actions";

import { resizeVisualization } from "../../utils/resize"

import { GraphManager } from "../Graphs/index";
import { ServiceManager } from "../../services/servicemanager/index";

import style from "./styles"

import FontAwesome from "react-fontawesome";

class VisualizationView extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            parameterizable: true,
            hasResults: false,
            showDescription: false,
        }
    }

    componentWillMount() {
        this.initialize(this.props.id);
    }

    componentDidMount() {
        this.updateSize();

        // If present, register the resize callback
        // to respond to interactive resizes from react-grid-layout.
        if (this.props.registerResize) {
            this.props.registerResize(this.updateSize.bind(this))
        }
    }

    componentWillReceiveProps(nextProps) {
        this.initialize(nextProps.id);
    }

    componentDidUpdate() {
        this.updateSize();
    }

    updateSize() {
        if (this._element) {
            const { width, height } = resizeVisualization(this._element);

            if (width !== this.state.width || height !== this.state.height) {
                this.setState({ width, height });
            }
        }
    }

    initialize(id) {

        this.props.fetchConfigurationIfNeeded(id).then((c) => {
            const { configuration } = this.props

            if (!configuration)
                return;

            this.props.fetchQueryIfNeeded(configuration.get("query")).then(() => {
                const { queryConfiguration, executeQueryIfNeeded, context } = this.props;

                if (!queryConfiguration)
                    return;

                executeQueryIfNeeded(queryConfiguration, context).then(
                    () => {
                        this.setState({
                            parameterizable: true,
                        });
                    },
                    (error) => {
                        this.setState({
                            parameterizable: false,
                        });
                    },
                );
            });

            if(configuration.get("listeners")){
                configuration.get("listeners").forEach((listener) => {

                    const {
                        event = "onMarkClick",
                        redirect = window.location.pathname,
                        params = {}
                    } = listener.toJS();

                    console.log("navigation is configured");

                    console.log(event, redirect, params);

                    Object.keys(params).forEach((destinationParam) => {
                        const sourceColumn = params[destinationParam];
                        console.log("sourceColumn = " + sourceColumn);
                        console.log("destinationParam = " + destinationParam);
                    });
                });
            }
        });
    }

    shouldShowVisualization() {
        const { configuration, response } = this.props;

        return configuration && response && !response.isFetching;
    }

    renderVisualization() {
        const { configuration, queryConfiguration, response } = this.props;

        const graphName      = configuration.get("graph"),
              GraphComponent = GraphManager.getGraphComponent(graphName);

        let description;

        if (this.state.showDescription) {
            description = <CardOverlay
                                overlayStyle={style.descriptionContainer}
                                textStyle={style.descriptionText}
                                text={configuration.get("description")}
                                onTouchTapOverlay={() => { this.setState({showDescription: false}); }}
                                />
        }

        return (

                <GraphComponent
                  response={response}
                  configuration={configuration.toJS()}
                  queryConfiguration={queryConfiguration}
                  width={this.state.width}
                  height={this.state.height}
                />
                {description}

        )
    }

    renderVisualizationIfNeeded() {
        if (this.shouldShowVisualization()) {
            return this.renderVisualization();
        }

        if (!this.state.parameterizable) {
            return (
                <CardOverlay
                    overlayStyle={style.overlayContainer}
                    textStyle={style.overlayText}
                    text={(

                            <FontAwesome
                                name="meh-o"
                                size="2x"
                                />

                            Oops, we are missing some parameters here!

                    )}
                    onTouchTapOverlay={() => { this.setState({showDescription: false}); }}
                    />
            )
        }

        return (

                    <FontAwesome
                        name="circle-o-notch"
                        spin
                        />

                    Please wait while loading...

        )
    }

    shouldShowTitle() {
        const { configuration } = this.props;

        return configuration && configuration.get("title") && this.state.parameterizable;
    }

    renderTitleIfNeeded() {
        const { configuration } = this.props;

        if (!this.shouldShowTitle())
            return;

        const descriptionIcon = !configuration.get("description") ? null : (

                <FontAwesome
                    name="info-circle"
                    onTouchTap={() => { this.setState({showDescription: !!configuration.get("description")}); }}
                    />

        )

        return (

                {configuration.get("title")}
                {descriptionIcon}

        )
    }

    cardTextReference = (c) => {
        if (this._element)
            return;

        this._element = ReactDOM.findDOMNode(c).parentElement;
    }

    render() {
        return (
            <Card
              style={style.card}
              containerStyle={style.cardContainer}
              ref={this.cardTextReference}
            >
                { this.renderTitleIfNeeded() };
                <CardText style={style.cardText}>
                    { this.renderVisualizationIfNeeded() }
                </CardText>
            </Card>
        );
    }
}

const mapStateToProps = (state, ownProps) => {

    const configurationID = ownProps.id || ownProps.params.id,
          context         = ownProps.context || ownProps.location.query;

    const props = {
        id: configurationID,
        context: context,

        configuration: state.configurations.getIn([
            ConfigurationsActionKeyStore.VISUALIZATIONS,
            configurationID,
            ConfigurationsActionKeyStore.DATA
        ]),

        error: state.configurations.getIn([
            ConfigurationsActionKeyStore.VISUALIZATIONS,
            configurationID,
            ConfigurationsActionKeyStore.ERROR
        ])

    };

    // Expose the query template as a JS object if it is available.
    if (props.configuration) {
        const queryConfiguration = state.configurations.getIn([
            ConfigurationsActionKeyStore.QUERIES,
            props.configuration.get("query")
        ]);

        if (queryConfiguration && !queryConfiguration.get(
            ConfigurationsActionKeyStore.IS_FETCHING
        )) {
            props.queryConfiguration = queryConfiguration.get(
                ConfigurationsActionKeyStore.DATA
            ).toJS();
        }

        // Expose received response if it is available
        if (props.queryConfiguration) {
            const requestID = ServiceManager.getRequestID(props.queryConfiguration, context);

            let response = state.services.getIn([
                ServiceActionKeyStore.REQUESTS,
                requestID
            ]);

            if (response && !response.get(ServiceActionKeyStore.IS_FETCHING))
                props.response = response.toJS();
        }
    }

    return props;
};

const actionCreators = (dispatch) => ({

    setPageTitle: function(aTitle) {
        dispatch(Actions.updateTitle(aTitle));
    },

    goTo: function(link, filters) {
        dispatch(push({pathname:link, query:filters}));
    },

    fetchConfigurationIfNeeded: function(id) {
        return dispatch(ConfigurationsActions.fetchIfNeeded(
            id,
            ConfigurationsActionKeyStore.VISUALIZATIONS
        ));
    },

    fetchQueryIfNeeded: function(id) {
        return dispatch(ConfigurationsActions.fetchIfNeeded(
            id,
            ConfigurationsActionKeyStore.QUERIES
        ));
    },

    executeQueryIfNeeded: function(queryConfiguration, context) {
        return dispatch(ServiceActions.fetchIfNeeded(queryConfiguration, context));
    }

 });

export default connect(mapStateToProps, actionCreators)(VisualizationView);
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
angular.module('starter.controllers', [])
//-----------------------------------------------------------------------------
.controller('mainCtrl', function($scope) {
  var cubeGL, cubeContainer
  function init() {
    var useLockedControls = true, controls = useLockedControls ? ERNO.Locked : ERNO.Freeform
    cubeGL = new ERNO.Cube({
      controls: controls,
      keyboardControlsEnabled: true,
      mouseControlsEnabled: false
    })
    cubeContainer = document.getElementById('container')
    cubeContainer.appendChild(cubeGL.domElement)
  };
  init();
  $scope.shuffle = () => {
    console.log("shuffle");
  };
  $scope.solve = () => {
    console.log("solve");
  };
})
//-----------------------------------------------------------------------------
<commit_msg>use mouse<commit_after>//-----------------------------------------------------------------------------
angular.module('starter.controllers', [])
//-----------------------------------------------------------------------------
.controller('mainCtrl', function($scope) {
  var cubeGL, cubeContainer
  function init() {
    var useLockedControls = true, controls = useLockedControls ? ERNO.Locked : ERNO.Freeform
    cubeGL = new ERNO.Cube({
      controls: controls,
      keyboardControlsEnabled: true,
      mouseControlsEnabled: true
    })
    cubeContainer = document.getElementById('container')
    cubeContainer.appendChild(cubeGL.domElement)
  };
  init();
  $scope.shuffle = () => {
    console.log("shuffle");
  };
  $scope.solve = () => {
    console.log("solve");
  };
})
//-----------------------------------------------------------------------------
<|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.type = "PlayerEntity";
      this.health = 20;
    	this.body.setVelocity(5, 20);
    	this.facing = "right";
    	this.now = new Date().getTime();
    	this.lastHit = this.now;
    	this.lastAttack = new Date().getTime();

    	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){
 	    	this.now = new Date().getTime();
   		 	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.facing = "right";
 	        	this.flipX(true);
 	        } else if(me.input.isKeyPressed("left")){
 	        	this.facing.left = "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.body.jumping = true;
 	      		this.body.vel.y -= this.body.accel.y * me.timer.tick;

 	      }

 	        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 && !this.renderable.isCurrentAnimation("attack")){
             if(!this.renderable.isCurrentAnimation("walk")){
          	   this.renderable.setCurrentAnimation("walk");

            }

          }else if (!this.renderable.isCurrentAnimation("attack")){
             this.renderable.setCurrentAnimation("idle");

          }

 	       me.collision.check(this, true, this.collideHandler.bind(this), true);
 	       this.body.update(delta);

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

      loseHealth: function(damage){
        this.health = this.health - damage;
        console.log(this.health);
      },

 	    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;

 	    		if(ydif<-40 && xdif< 70 && xdif>-35){
 	    			this.body.falling = false;
 	    			this.body.vel.y = -1;
 	    	     }
 	    		else if(xdif>-35 && this.facing=== 'right' && (xdif<0) && ydif>-50){
 	    			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;
 	    	   }

 	    	    if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
 	    			console.log("tower Hit");
 	    			this.lastHit = this.now;
 	    			response.b.loseHealth();
 	    	}
 	    }

 	 }

   });

// 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 = "PlayerBase";

},

  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;

  },

  loseHealth: function(damage){
    this.health = this.health - damage;
  },

  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(){

  },

  loseHealth: function(){
  	this.health--;
  }

});

game.EnemyCreep = me.Entity.extend({
	init: function(x,y, settings){
		this._super(me.Entity, 'init', [x, y, {
          image: "creep1",
          width: 32,
          height: 64,
          spritewidth: "32",
          spriteheight: "64",
          getShape: function(){
          	return (new me.Rect(0, 0, 32, 64)).toPolygon();
          }
	  }]);
		this.health = 10;
		this.alwaysUpdate = true;
    this.now = new Date().getTime();
    this.attacking = false;
    this.lastAttacking = new Date().getTime();
    this.lastHit = new Date().getTime();
		this.body.setVelocity(3, 20);

		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);
		this.renderable.setCurrentAnimation("walk");
	},

	update: function(delta){
    this.now = new Date().getTime();
    this.body.vel.x -= this.body.accel.x * me.timer.tick;

    me.collision.check(this, true, this.collideHandler.bind(this), true);

    this.body.update(delta);

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

    return true;
	},

   loseHealth: function(damage){
    this.health = this.health - damage;
   },

  collideHandler: function(response) {
    if(response.b.type === 'PlayerBase') {
      this.attacking=true;
      this.lastAttacking=this.now;
      this.body.vel.x = 0;
      this.pos.x = this.pos.x + 1;
        if((this.now-this.lastHit >= 1000)){
          this.lastHit = this.now;
          response.b.loseHealth(1);
        }

    }else if (response.b.type=== 'PlayerEntity') {
        var xdif = this.pos.x = response.b.pos.x;

        this.attacking=true;
        this.lastAttacking=this.now;

        if(xdif>0){
          // keeps moving the creep to the right to maintain its position
          this.pos.x = this.pos.x + 1;
          this.body.vel.x = 0;
        }
        if((this.now-this.lastHit >= 1000) && xdif>0){
          this.lastHit = this.now;
          response.b.loseHealth(1);
        }

    }
  }

});

game.GameManager = Object.extend ({
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date(). getTime();

		this.alwaysUpdate = true;

	},

    update: function(){
     	this.now = new Date().getTime();

     	if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
     		this.lastCreep = this.now;
     		var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
     		me.game.world.addChild(creepe, 5);

     	}

     	return true;
    }
});

//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
// This.facing keeps track of hich direction, your character is going
//me.collision is basically just checking for collisions
//what is going on is we are passing our parameter to our function collide.handler
//response.a represents our player
// response.b represents whatever we are colliding with
//vary dif represents the difference between my players y position and the bases y position
// what we want to happen is our Y variable to be dealt with first
// we have not used attack var yet
//this.health-- makes the health go down one
//the attack animation will detect collisions over and over
//this.now keeps track of the time in the game
//this.lastAttack is for a hit delay
//everytime you call for an update you want to change this.now
// our GameManager is not something that will appear on the screen
//It is not an entity it is just something we are using
//we want to make sure the game manager is continuosuly updating
//math.round checks to see if we have a multiple of 10
// this is mod %, it will check and see if we have a multiple of 10
// We want the creeps to drop to the ground and begin walking
// delta represents time as a parameter
//We want the creeps to drop to the ground and begin walking
// delta represents time as a parameter
// this.attacking lets us know if the nemy is currently attacking
// this.pos.x keeps moving the creep
// we do not want our creep to hit multiple things
//we put an if else statement so it can only be hitting one of those things
//To the right the x value will be bigger
//The position change will only happen when the creep is attacking<commit_msg>Video 23<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.type = "PlayerEntity";
      this.health = 20;
    	this.body.setVelocity(5, 20);
    	this.facing = "right";
    	this.now = new Date().getTime();
    	this.lastHit = this.now;
    	this.lastAttack = new Date().getTime();

    	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){
 	    	this.now = new Date().getTime();
   		 	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.facing = "right";
 	        	this.flipX(true);
 	        } else if(me.input.isKeyPressed("left")){
 	        	this.facing.left = "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.body.jumping = true;
 	      		this.body.vel.y -= this.body.accel.y * me.timer.tick;

 	      }

 	        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 && !this.renderable.isCurrentAnimation("attack")){
             if(!this.renderable.isCurrentAnimation("walk")){
          	   this.renderable.setCurrentAnimation("walk");

            }

          }else if (!this.renderable.isCurrentAnimation("attack")){
             this.renderable.setCurrentAnimation("idle");

          }

 	       me.collision.check(this, true, this.collideHandler.bind(this), true);
 	       this.body.update(delta);

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

      loseHealth: function(damage){
        this.health = this.health - damage;
        console.log(this.health);
      },

 	    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;

 	    		if(ydif<-40 && xdif< 70 && xdif>-35){
 	    			this.body.falling = false;
 	    			this.body.vel.y = -1;
 	    	     }
 	    		else if(xdif>-35 && this.facing=== 'right' && (xdif<0) && ydif>-50){
 	    			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;
 	    	   }

 	    	    if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
 	    			console.log("tower Hit");
 	    			this.lastHit = this.now;
 	    			response.b.loseHealth();
 	    	}
 	    }else if(response.b.type==='EnemyCreep') {
          var xdif = this.pos.x - response.b.pos.x;
          var ydif = this.pos.y - response.b.pos.y;

          if (xdif>0) {
              this.pos.x = this.pos.x + 1;
              if(this.facing==="left"){
                this.body.vel.x = 0;
              }
          }else{
            this.pos.x = this.pos.x - 1;
             if(this.facing==="right"){
                this.body.vel.x = 0;
              }
          }
          if(this.renderable.isCurrentAnimation('attack') && this.now-this.lastHit >= 1000
              && (Math.abs(ydif) <=40) &&
              (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")))
          {
            this.lastHit = this.now;
            response.b.loseHealth(1);
          }
      }
 	 }

   });

// 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 = "PlayerBase";

},

  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;

  },

  loseHealth: function(damage){
    this.health = this.health - damage;
  },

  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);

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

        // }

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

  },

  onCollision: function(){

  },

  loseHealth: function(){
  	this.health--;
  }

});

game.EnemyCreep = me.Entity.extend({
	init: function(x,y, settings){
		this._super(me.Entity, 'init', [x, y, {
          image: "creep1",
          width: 32,
          height: 64,
          spritewidth: "32",
          spriteheight: "64",
          getShape: function(){
          	return (new me.Rect(0, 0, 32, 64)).toPolygon();
          }
	  }]);
		this.health = 10;
		this.alwaysUpdate = true;
    this.now = new Date().getTime();
    this.attacking = false;
    this.lastAttacking = new Date().getTime();
    this.lastHit = new Date().getTime();
		this.body.setVelocity(3, 20);

		this.type = "EnemyCreep";

		this.renderable.addAnimation("walk", [3, 4, 5], 80);
		this.renderable.setCurrentAnimation("walk");
	},

   // test
  // public class Enemy : MonoBehaviour {

 //public float speed = 4f;
 //public float jetPackSpeed = 0.3f;
 //public float jumpSpeed = 8f;
 //public float gravity = 10;

 //private Transform _Player;
 //private CharacterController character;
 //private Transform tr;
 //private float vSpeed = 0f;
 //private bool jump = false;

 //void Start ()
 //{
     //_Player = GameObject.FindGameObjectWithTag("Player").transform;
     //character = GetComponent<CharacterController>();
     //tr = transform;
// }

 //void Update ()
 // {    // find the vector enemy -> player
    // Vector3 chaseDir = _Player.position - tr.position;
     // chaseDir.y = 0; // let only the horizontal direction
     // float distance = chaseDir.magnitude;  // get the distance
    // if (distance <= 2)
        // Debug.Log("Attacking Player");
     // else
    // {    // find the player direction
        // Quaternion rot = Quaternion.LookRotation(chaseDir);
         // rotate to his direction
        // tr.rotation = Quaternion.Slerp(tr.rotation, rot, Time.deltaTime * 4);
        // if (character.isGrounded){ // if is grounded...
            // vSpeed = 0;  // vertical speed  is zero
             // if (jump){    // if should jump...
               //  vSpeed = jumpSpeed; // aplly jump speed
                //  jump = false; // only jump once!
           //  }
        // }
         // else // but if lost ground, check if it's an abyss
         // if (!Physics.Raycast(tr.position, -tr.up, 20f)){ // if no ground below
            // vSpeed = jetPackSpeed;  // use jetpack
        // }
         // vSpeed -= gravity * Time.deltaTime; // apply gravity
         // calculate horizontal velocity vector
        // chaseDir = chaseDir.normalized * speed;
         // chaseDir.y += vSpeed; // include vertical speed
         // and move the enemy
     //    //character.Move(chaseDir * Time.deltaTime);
    // }
// }

 // if collided with some wall or block, jump
// void OnControllerColliderHit(ControllerColliderHit hit){
     // only check lateral collisions
     //if (Mathf.Abs(hit.normal.y) < 0.5){
        // jump = true; // jump if collided laterally
    // }
 // },
 // end of test

  loseHealth: function(damage) {

    this.health = this.health - damage;

  },

	update: function(delta){
    if(this.health <= 0){
       console.log(this.health);
       if(this.health <= 0) {
          me.game.world.removeChild(this);
       }
    }
    this.now = new Date().getTime();
    this.body.vel.x -= this.body.accel.x * me.timer.tick;

    me.collision.check(this, true, this.collideHandler.bind(this), true);

    this.body.update(delta);

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

   // if (jump == true)
   //{
//
        //Playerypos -=  vel;
        //Playerxpos +=  vel;
    // }

   // public void jump() {
   // if(gameTime.getTimeMS() - jumpTime > jumpDelayInMilliseconds) {
      // jumpTime = gameTime.getTimeMS();
      // character.jump();
   // }
/// this is a test
  // if(Jump == true){

       //  if(JumpFall == false){
           // shiftY -= 1;
       //  }
        // if(shiftY == PUT_YOUR_JUMP_HEIGHT_HERE){
          //  JumpFall = true;
      //  }
       //  if(JumpFall == true){
            // shiftY += 1;
       //  }
      //  if(shiftY >=PUT_YOUR_STARTING_HEIGHT_HERE){
            // Jump = false;
            // JumpFall = false;
      //  }
   // }
    ///// test is above

    return true;
	},

   loseHealth: function(damage){
    this.health = this.health - damage;
   },

  collideHandler: function(response) {
    if(response.b.type === 'PlayerBase') {
      this.attacking=true;
      this.lastAttacking=this.now;
      this.body.vel.x = 0;
      this.pos.x = this.pos.x + 1;
        if((this.now-this.lastHit >= 1000)){
          this.lastHit = this.now;
          response.b.loseHealth(1);
        }

    }else if (response.b.type=== 'PlayerEntity') {
        var xdif = this.pos.x = response.b.pos.x;

        this.attacking=true;
        this.lastAttacking=this.now;

        if(xdif>0){
          // keeps moving the creep to the right to maintain its position
          this.pos.x = this.pos.x + 1;
          this.body.vel.x = 0;
        }
        if((this.now-this.lastHit >= 1000) && xdif>0){
          this.lastHit = this.now;
          response.b.loseHealth(1);
        }

    }
  }

});

game.GameManager = Object.extend ({
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date(). getTime();

		this.alwaysUpdate = true;

	},

    update: function(){
     	this.now = new Date().getTime();

     	if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
     		this.lastCreep = this.now;
     		var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
     		me.game.world.addChild(creepe, 5);

     	}

     	return true;
    }
});

//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
// This.facing keeps track of hich direction, your character is going
//me.collision is basically just checking for collisions
//what is going on is we are passing our parameter to our function collide.handler
//response.a represents our player
// response.b represents whatever we are colliding with
//vary dif represents the difference between my players y position and the bases y position
// what we want to happen is our Y variable to be dealt with first
// we have not used attack var yet
//this.health-- makes the health go down one
//the attack animation will detect collisions over and over
//this.now keeps track of the time in the game
//this.lastAttack is for a hit delay
//everytime you call for an update you want to change this.now
// our GameManager is not something that will appear on the screen
//It is not an entity it is just something we are using
//we want to make sure the game manager is continuosuly updating
//math.round checks to see if we have a multiple of 10
// this is mod %, it will check and see if we have a multiple of 10
// We want the creeps to drop to the ground and begin walking
// delta represents time as a parameter
//We want the creeps to drop to the ground and begin walking
// delta represents time as a parameter
// this.attacking lets us know if the nemy is currently attacking
// this.pos.x keeps moving the creep
// we do not want our creep to hit multiple things
//we put an if else statement so it can only be hitting one of those things
//To the right the x value will be bigger
//The position change will only happen when the creep is attacking<|endoftext|>