<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const urlParse = require('url').parse

const ImmutableComponent = require('./immutableComponent')
const windowActions = require('../actions/windowActions')
const KeyCodes = require('../constants/keyCodes')
const cx = require('../lib/classSet.js')
const ipc = global.require('electron').ipcRenderer

const UrlBarSuggestions = require('./urlBarSuggestions.js')
const messages = require('../constants/messages')
const dragTypes = require('../constants/dragTypes')
const contextMenus = require('../contextMenus')
const dndData = require('../dndData')

const {isUrl} = require('../lib/appUrlUtil')

class UrlBar extends ImmutableComponent {

  isActive () {
    return this.props.urlbar.get('active')
  }

  isSelected () {
    return this.props.urlbar.get('selected')
  }

  isFocused () {
    return this.props.urlbar.get('focused')
  }

  // update the DOM with state that is not stored in the component
  updateDOM () {
    this.updateDOMInputFocus(this.isFocused())
    this.updateDOMInputSelected(this.isSelected())
  }

  updateDOMInputFocus (focused) {
    const urlInput = this.urlInput
    if (focused) {
      urlInput.focus()
    }
  }

  updateDOMInputSelected (selected) {
    if (selected) {
      this.urlInput.select()
    }
  }

  get searchDetail () {
    return this.props.searchDetail
  }

  // restores the url bar to the current location
  restore () {
    const location = this.props.activeFrameProps.get('location')
    windowActions.setNavBarUserInput(location)
  }

  onKeyDown (e) {
    switch (e.keyCode) {
      case KeyCodes.ENTER:
        windowActions.setUrlBarActive(false)
        this.restore()
        e.preventDefault()
        let location = this.props.urlbar.get('location')
        if (location === null || location.length === 0) {
          windowActions.setUrlBarSelected(true)
        } else {
          const isLocationUrl = isUrl(location)
          const searchUrl = this.searchDetail.get('searchURL').replace('{searchTerms}', encodeURIComponent(location))
          // If control key is pressed and input has no space in it add www. as a prefix and .com as a suffix.
          // For whitepsace we want a search no matter what.
          if (!isLocationUrl && !/\s/g.test(location) && e.ctrlKey) {
            windowActions.loadUrl(this.props.activeFrameProps, `www.${location}.com`)
          } else if (this.shouldRenderUrlBarSuggestions && this.urlBarSuggestions.activeIndex > 0) {
            // Hack to make alt enter open a new tab for url bar suggestions when hitting enter on them.
            const isDarwin = process.platform === 'darwin'
            if (e.altKey) {
              if (isDarwin) {
                e.metaKey = true
              } else {
                e.ctrlKey = true
              }
            }
            // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
            // load the selected suggestion
            this.urlBarSuggestions.clickSelected(e)
          } else {
            location = isLocationUrl ? location : searchUrl
            // do search.
            if (e.altKey) {
              windowActions.newFrame({ location }, true)
            } else if (e.metaKey) {
              windowActions.newFrame({ location }, false)
            } else {
              windowActions.loadUrl(this.props.activeFrameProps, location)
            }
          }
          // this can't go through appActions for some reason
          // or the whole window will reload on the first page request
          this.updateDOMInputFocus(false)
        }
        break
      case KeyCodes.UP:
        if (this.shouldRenderUrlBarSuggestions) {
          // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
          this.urlBarSuggestions.previousSuggestion()
          e.preventDefault()
        }
        break
      case KeyCodes.DOWN:
        if (this.shouldRenderUrlBarSuggestions) {
          // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
          this.urlBarSuggestions.nextSuggestion()
          e.preventDefault()
        }
        break
      case KeyCodes.ESC:
        e.preventDefault()
        ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_STOP)
        break
      default:
    }
  }

  onClick (e) {
    // if the url bar is already selected then clicking in it should make it active
    if (this.isSelected()) {
      windowActions.setUrlBarSelected(false)
      windowActions.setUrlBarActive(true)
    }
  }

  onBlur (e) {
    windowActions.setNavBarFocused(false)
    windowActions.setUrlBarSelected(false)
  }

  onChange (e) {
    windowActions.setUrlBarSelected(false)
    windowActions.setUrlBarActive(true)
    windowActions.setNavBarUserInput(e.target.value)
  }

  onFocus (e) {
    windowActions.setUrlBarSelected(true)
  }

  onActiveFrameStop () {
    this.restore()
    windowActions.setUrlBarSelected(true)
    windowActions.setUrlBarActive(false)
  }

  componentWillMount () {
    ipc.on(messages.SHORTCUT_FOCUS_URL, (e, forSearchMode) => {
      windowActions.setUrlBarSelected(true, forSearchMode)
    })
    // escape key handling
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_STOP, this.onActiveFrameStop.bind(this))
  }

  componentDidMount () {
    this.updateDOM()
  }

  componentDidUpdate () {
    this.updateDOM()
  }

  get hostValue () {
    const parsed = urlParse(this.props.activeFrameProps.get('location'))
    return parsed.host && parsed.protocol !== 'about:' ? parsed.host : ''
  }

  get titleValue () {
    // For about:newtab we don't want the top of the browser saying New Tab
    // Instead just show "Brave"
    return ['about:blank', 'about:newtab'].includes(this.props.urlbar.get('location'))
      ? '' : this.props.activeFrameProps.get('title')
  }

  get locationValue () {
    return ['about:blank', 'about:newtab'].includes(this.props.urlbar.get('location'))
      ? '' : this.props.urlbar.get('location')
  }

  get loadTime () {
    let loadTime = ''
    if (this.props.activeFrameProps.get('startLoadTime') &&
        this.props.activeFrameProps.get('endLoadTime')) {
      const loadMilliseconds = this.props.activeFrameProps.get('endLoadTime') -
        this.props.activeFrameProps.get('startLoadTime')
      if (loadMilliseconds > 1000) {
        loadTime = (loadMilliseconds / 1000 | 0) + 's '
      }
      loadTime += (loadMilliseconds % 1000 | 0) + 'ms'
    }
    return loadTime
  }

  get secure () {
    return this.props.activeFrameProps.getIn(['security', 'isSecure'])
  }

  get aboutPage () {
    const protocol = urlParse(this.props.activeFrameProps.get('location')).protocol
    return ['about:', 'file:', 'chrome:', 'view-source:'].includes(protocol)
  }

  get isHTTPPage () {
    // Whether this page is HTTP or HTTPS. We don't show security indicators
    // for other protocols like mailto: and about:.
    const protocol = urlParse(this.props.activeFrameProps.get('location')).protocol
    return protocol === 'http:' || protocol === 'https:'
  }

  onSiteInfo () {
    windowActions.setSiteInfoVisible(true)
  }

  get shouldRenderUrlBarSuggestions () {
    return (this.props.urlbar.get('location') || this.props.urlbar.get('urlPreview')) &&
      this.props.urlbar.get('active')
  }

  onDragStart (e) {
    dndData.setupDataTransferURL(e.dataTransfer, this.props.activeFrameProps.get('location'), this.props.activeFrameProps.get('title'))
    dndData.setupDataTransferBraveData(e.dataTransfer, dragTypes.TAB, this.props.activeFrameProps)
  }

  render () {
    return <form
      className='urlbarForm'
      action='#'
      id='urlbar'
      ref='urlbar'>
      <span
        onDragStart={this.onDragStart.bind(this)}
        draggable
        onClick={this.onSiteInfo}
        className={cx({
          urlbarIcon: true,
          'fa': true,
          'fa-lock': this.isHTTPPage && this.secure && !this.props.urlbar.get('active'),
          'fa-unlock-alt': this.isHTTPPage && !this.secure && !this.props.urlbar.get('active') && !this.props.titleMode,
          'fa fa-search': this.props.searchSuggestions && this.props.urlbar.get('active') && this.props.loading === false,
          'fa fa-file': !this.props.searchSuggestions && this.props.urlbar.get('active') && this.props.loading === false,
          extendedValidation: this.extendedValidationSSL
        })} />
        {
          this.props.titleMode
          ?

            {this.hostValue}
            {this.hostValue && this.titleValue ? ' | ' : ''}
            {this.titleValue}

          : <input type='text'
            disabled={this.props.activeFrameProps.get('location') === undefined && this.loadTime === ''}
            onFocus={this.onFocus.bind(this)}
            onBlur={this.onBlur.bind(this)}
            onKeyDown={this.onKeyDown.bind(this)}
            onChange={this.onChange.bind(this)}
            onClick={this.onClick.bind(this)}
            onContextMenu={contextMenus.onUrlBarContextMenu.bind(this)}
            value={this.locationValue}
            data-l10n-id='urlbar'
            className={cx({
              insecure: !this.secure && this.props.loading === false && !this.isHTTPPage,
              private: this.private,
              testHookLoadDone: !this.props.loading
            })}
            id='urlInput'
            readOnly={this.props.titleMode}
            ref={(node) => { this.urlInput = node }}/>
        }
      <legend/>
        {
          this.props.titleMode
          ? null
          : {this.loadTime}
        }

        {
          this.shouldRenderUrlBarSuggestions
          ? <UrlBarSuggestions
            ref={(node) => { this.urlBarSuggestions = node }}
            suggestions={this.props.urlbar.get('suggestions')}
            sites={this.props.sites}
            frames={this.props.frames}
            searchDetail={this.searchDetail}
            searchSuggestions={this.props.searchSuggestions}
            activeFrameProps={this.props.activeFrameProps}
            urlLocation={this.props.urlbar.get('location')}
            urlPreview={this.props.urlbar.get('urlPreview')}
            previewActiveIndex={this.props.previewActiveIndex || 0} />
          : null
        }
    </form>
  }
}

module.exports = UrlBar
<commit_msg>Pretty load time when it's >1000ms<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const urlParse = require('url').parse

const ImmutableComponent = require('./immutableComponent')
const windowActions = require('../actions/windowActions')
const KeyCodes = require('../constants/keyCodes')
const cx = require('../lib/classSet.js')
const ipc = global.require('electron').ipcRenderer

const UrlBarSuggestions = require('./urlBarSuggestions.js')
const messages = require('../constants/messages')
const dragTypes = require('../constants/dragTypes')
const contextMenus = require('../contextMenus')
const dndData = require('../dndData')

const {isUrl} = require('../lib/appUrlUtil')

class UrlBar extends ImmutableComponent {

  isActive () {
    return this.props.urlbar.get('active')
  }

  isSelected () {
    return this.props.urlbar.get('selected')
  }

  isFocused () {
    return this.props.urlbar.get('focused')
  }

  // update the DOM with state that is not stored in the component
  updateDOM () {
    this.updateDOMInputFocus(this.isFocused())
    this.updateDOMInputSelected(this.isSelected())
  }

  updateDOMInputFocus (focused) {
    const urlInput = this.urlInput
    if (focused) {
      urlInput.focus()
    }
  }

  updateDOMInputSelected (selected) {
    if (selected) {
      this.urlInput.select()
    }
  }

  get searchDetail () {
    return this.props.searchDetail
  }

  // restores the url bar to the current location
  restore () {
    const location = this.props.activeFrameProps.get('location')
    windowActions.setNavBarUserInput(location)
  }

  onKeyDown (e) {
    switch (e.keyCode) {
      case KeyCodes.ENTER:
        windowActions.setUrlBarActive(false)
        this.restore()
        e.preventDefault()
        let location = this.props.urlbar.get('location')
        if (location === null || location.length === 0) {
          windowActions.setUrlBarSelected(true)
        } else {
          const isLocationUrl = isUrl(location)
          const searchUrl = this.searchDetail.get('searchURL').replace('{searchTerms}', encodeURIComponent(location))
          // If control key is pressed and input has no space in it add www. as a prefix and .com as a suffix.
          // For whitepsace we want a search no matter what.
          if (!isLocationUrl && !/\s/g.test(location) && e.ctrlKey) {
            windowActions.loadUrl(this.props.activeFrameProps, `www.${location}.com`)
          } else if (this.shouldRenderUrlBarSuggestions && this.urlBarSuggestions.activeIndex > 0) {
            // Hack to make alt enter open a new tab for url bar suggestions when hitting enter on them.
            const isDarwin = process.platform === 'darwin'
            if (e.altKey) {
              if (isDarwin) {
                e.metaKey = true
              } else {
                e.ctrlKey = true
              }
            }
            // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
            // load the selected suggestion
            this.urlBarSuggestions.clickSelected(e)
          } else {
            location = isLocationUrl ? location : searchUrl
            // do search.
            if (e.altKey) {
              windowActions.newFrame({ location }, true)
            } else if (e.metaKey) {
              windowActions.newFrame({ location }, false)
            } else {
              windowActions.loadUrl(this.props.activeFrameProps, location)
            }
          }
          // this can't go through appActions for some reason
          // or the whole window will reload on the first page request
          this.updateDOMInputFocus(false)
        }
        break
      case KeyCodes.UP:
        if (this.shouldRenderUrlBarSuggestions) {
          // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
          this.urlBarSuggestions.previousSuggestion()
          e.preventDefault()
        }
        break
      case KeyCodes.DOWN:
        if (this.shouldRenderUrlBarSuggestions) {
          // TODO: We shouldn't be calling into urlBarSuggestions from the parent component at all
          this.urlBarSuggestions.nextSuggestion()
          e.preventDefault()
        }
        break
      case KeyCodes.ESC:
        e.preventDefault()
        ipc.emit(messages.SHORTCUT_ACTIVE_FRAME_STOP)
        break
      default:
    }
  }

  onClick (e) {
    // if the url bar is already selected then clicking in it should make it active
    if (this.isSelected()) {
      windowActions.setUrlBarSelected(false)
      windowActions.setUrlBarActive(true)
    }
  }

  onBlur (e) {
    windowActions.setNavBarFocused(false)
    windowActions.setUrlBarSelected(false)
  }

  onChange (e) {
    windowActions.setUrlBarSelected(false)
    windowActions.setUrlBarActive(true)
    windowActions.setNavBarUserInput(e.target.value)
  }

  onFocus (e) {
    windowActions.setUrlBarSelected(true)
  }

  onActiveFrameStop () {
    this.restore()
    windowActions.setUrlBarSelected(true)
    windowActions.setUrlBarActive(false)
  }

  componentWillMount () {
    ipc.on(messages.SHORTCUT_FOCUS_URL, (e, forSearchMode) => {
      windowActions.setUrlBarSelected(true, forSearchMode)
    })
    // escape key handling
    ipc.on(messages.SHORTCUT_ACTIVE_FRAME_STOP, this.onActiveFrameStop.bind(this))
  }

  componentDidMount () {
    this.updateDOM()
  }

  componentDidUpdate () {
    this.updateDOM()
  }

  get hostValue () {
    const parsed = urlParse(this.props.activeFrameProps.get('location'))
    return parsed.host && parsed.protocol !== 'about:' ? parsed.host : ''
  }

  get titleValue () {
    // For about:newtab we don't want the top of the browser saying New Tab
    // Instead just show "Brave"
    return ['about:blank', 'about:newtab'].includes(this.props.urlbar.get('location'))
      ? '' : this.props.activeFrameProps.get('title')
  }

  get locationValue () {
    return ['about:blank', 'about:newtab'].includes(this.props.urlbar.get('location'))
      ? '' : this.props.urlbar.get('location')
  }

  get loadTime () {
    const { activeFrameProps } = this.props
    const startLoadTime = activeFrameProps.get('startLoadTime')
    const endLoadTime = activeFrameProps.get('endLoadTime')
    let loadTime = ''

    if (startLoadTime && endLoadTime) {
      const loadMilliseconds = endLoadTime - startLoadTime
      if (loadMilliseconds > 1000) {
        loadTime = (loadMilliseconds / 1000).toFixed(2) + 's'
      } else {
        loadTime = loadMilliseconds + 'ms'
      }
    }
    return loadTime
  }

  get secure () {
    return this.props.activeFrameProps.getIn(['security', 'isSecure'])
  }

  get aboutPage () {
    const protocol = urlParse(this.props.activeFrameProps.get('location')).protocol
    return ['about:', 'file:', 'chrome:', 'view-source:'].includes(protocol)
  }

  get isHTTPPage () {
    // Whether this page is HTTP or HTTPS. We don't show security indicators
    // for other protocols like mailto: and about:.
    const protocol = urlParse(this.props.activeFrameProps.get('location')).protocol
    return protocol === 'http:' || protocol === 'https:'
  }

  onSiteInfo () {
    windowActions.setSiteInfoVisible(true)
  }

  get shouldRenderUrlBarSuggestions () {
    return (this.props.urlbar.get('location') || this.props.urlbar.get('urlPreview')) &&
      this.props.urlbar.get('active')
  }

  onDragStart (e) {
    dndData.setupDataTransferURL(e.dataTransfer, this.props.activeFrameProps.get('location'), this.props.activeFrameProps.get('title'))
    dndData.setupDataTransferBraveData(e.dataTransfer, dragTypes.TAB, this.props.activeFrameProps)
  }

  render () {
    return <form
      className='urlbarForm'
      action='#'
      id='urlbar'
      ref='urlbar'>
      <span
        onDragStart={this.onDragStart.bind(this)}
        draggable
        onClick={this.onSiteInfo}
        className={cx({
          urlbarIcon: true,
          'fa': true,
          'fa-lock': this.isHTTPPage && this.secure && !this.props.urlbar.get('active'),
          'fa-unlock-alt': this.isHTTPPage && !this.secure && !this.props.urlbar.get('active') && !this.props.titleMode,
          'fa fa-search': this.props.searchSuggestions && this.props.urlbar.get('active') && this.props.loading === false,
          'fa fa-file': !this.props.searchSuggestions && this.props.urlbar.get('active') && this.props.loading === false,
          extendedValidation: this.extendedValidationSSL
        })} />
        {
          this.props.titleMode
          ?

            {this.hostValue}
            {this.hostValue && this.titleValue ? ' | ' : ''}
            {this.titleValue}

          : <input type='text'
            disabled={this.props.activeFrameProps.get('location') === undefined && this.loadTime === ''}
            onFocus={this.onFocus.bind(this)}
            onBlur={this.onBlur.bind(this)}
            onKeyDown={this.onKeyDown.bind(this)}
            onChange={this.onChange.bind(this)}
            onClick={this.onClick.bind(this)}
            onContextMenu={contextMenus.onUrlBarContextMenu.bind(this)}
            value={this.locationValue}
            data-l10n-id='urlbar'
            className={cx({
              insecure: !this.secure && this.props.loading === false && !this.isHTTPPage,
              private: this.private,
              testHookLoadDone: !this.props.loading
            })}
            id='urlInput'
            readOnly={this.props.titleMode}
            ref={(node) => { this.urlInput = node }}/>
        }
      <legend/>
        {
          this.props.titleMode
          ? null
          : {this.loadTime}
        }

        {
          this.shouldRenderUrlBarSuggestions
          ? <UrlBarSuggestions
            ref={(node) => { this.urlBarSuggestions = node }}
            suggestions={this.props.urlbar.get('suggestions')}
            sites={this.props.sites}
            frames={this.props.frames}
            searchDetail={this.searchDetail}
            searchSuggestions={this.props.searchSuggestions}
            activeFrameProps={this.props.activeFrameProps}
            urlLocation={this.props.urlbar.get('location')}
            urlPreview={this.props.urlbar.get('urlPreview')}
            previewActiveIndex={this.props.previewActiveIndex || 0} />
          : null
        }
    </form>
  }
}

module.exports = UrlBar
<|endoftext|>


<commit_before>var games = [
    "RationsPlease",
    "SuperSeaSerpentSimulator"
];

var portfolioItemTemplatePath = "templates/portfolioItemTemplate.html";
var modalTemplatePath = "templates/modalTemplate.html";

var portfolioItemTemplate;
var modalTemplate;

var versionNum = "v.29";

var GenerateContent = function(game){
	var portfolioItem = portfolioItemTemplate.clone();
	portfolioItem.id = game + "-portfolio-item";
	$("#portfolio-items").append(portfolioItem);

	var modal = modalTemplate.clone();
	modal = game + "-portfolio-modal";
	$("#modals").append(modal);
};

var LoadPortfolioItemData = function(game, data) {
	var portfolioItem = $(game+"-portfolio-item");

	if(data.hasOwnProperty("id")) {
		//console.log("setting id");
		var modalIdHolder = portfolioItem.find(".portfolio-link")[0];
		modalIdHolder.href = "#" + data["id"] + "-modal";
		//console.log(modalIdHolder);
	}
	else {
		console.log("missing id");
	}

	if(data.hasOwnProperty("portfolio-item-title")) {
		//console.log("setting title");
		var title = portfolioItem.find(".portfolio-item-title")[0];
		title.innerHTML = data["portfolio-item-title"];
		//console.log(title);
	}
	else {
		console.log("missing portfolio item title");
	}

	if(data.hasOwnProperty("portfolio-item-image")) {
		//console.log("setting image");
		var image = portfolioItem.find(".portfolio-item-image")[0];
		image.src = data["portfolio-item-image"];
		//console.log(image);
	}
	else {
		console.log("missing portfolio item image");
	}

	//console.log(portfolioItem);
};

var LoadModalData = function(game, data) {
	var modal = $(game+"-portfolio-modal");

	if(data.hasOwnProperty("id")) {
		//console.log("setting id");
		var modalIdHolder = modal.find(".portfolio-modal")[0];
		modalIdHolder.id = data["id"] + "-modal";
		//console.log(modalIdHolder);
	}
	else {
		console.log("missing id");
	}

	if(data.hasOwnProperty("modal-projectHeading")) {
		//console.log("setting projectHeading");
		var projectHeading = modal.find(".modal-projectHeading")[0];
		projectHeading.innerHTML = data["modal-projectHeading"];
		//console.log(projectHeading);
	}
	else {
		console.log("missing modal project heading");
	}

	if(data.hasOwnProperty("modal-intro")) {
		//console.log("setting intro");
		var intro = modal.find(".modal-intro")[0];
		intro.innerHTML = data["modal-intro"];
		//console.log(intro);
	}
	else {
		console.log("missing modal intro");
	}

	if(data.hasOwnProperty("modal-img")) {
		//console.log("setting image");
		var image = modal.find(".modal-img")[0];
		image.src = data["modal-img"];
		//console.log(image);
	}
	else {
		console.log("missing modal image");
	}

	if(data.hasOwnProperty("modal-html")) {
		//console.log("setting html");
		var html = modal.find(".modal-html")[0];
		html.innerHTML = data["modal-html"];
		//console.log(html);
	}
	else {
		console.log("missing modal html");
	}

	//console.log(modal);
};

var LoadFromJson = function(game, data) {
	//console.log(data);
	LoadPortfolioItemData(game, data);
	LoadModalData(game, data);
};

var LoadContent = function(game) {
	//console.log("Generating content for " + game);
	$.getJSON("data/" + game + ".json", null, function(data) {
		LoadFromJson(game, data);
	});
};

$(document).ready(function() {
	console.log(versionNum);

	portfolioItemTemplate = $('<div>').load(portfolioItemTemplatePath, function() { // load the portfolio item template
		modalTemplate = $('<div>').load(modalTemplatePath, function() { // load the modal template
			// fill in the data
			for (var i = games.length - 1; i >= 0; i--) {
				var game = games[i];
				GenerateContent(game); // generate first to ensure ordering
				LoadContent(game);
			}
		});
	});
});<commit_msg>json test 30<commit_after>var games = [
    "RationsPlease",
    "SuperSeaSerpentSimulator"
];

var portfolioItemTemplatePath = "templates/portfolioItemTemplate.html";
var modalTemplatePath = "templates/modalTemplate.html";

var portfolioItemTemplate;
var modalTemplate;

var versionNum = "v.30";

var GenerateContent = function(game){
	var portfolioItem = portfolioItemTemplate.clone()[0];
	portfolioItem.id = game + "-portfolio-item";
	$("#portfolio-items").append(portfolioItem);

	var modal = modalTemplate.clone()[0];
	modal.id = game + "-portfolio-modal";
	$("#modals").append(modal);
};

var LoadPortfolioItemData = function(game, data) {
	var portfolioItem = $(game+"-portfolio-item");

	if(data.hasOwnProperty("id")) {
		//console.log("setting id");
		var modalIdHolder = portfolioItem.find(".portfolio-link")[0];
		modalIdHolder.href = "#" + data["id"] + "-modal";
		//console.log(modalIdHolder);
	}
	else {
		console.log("missing id");
	}

	if(data.hasOwnProperty("portfolio-item-title")) {
		//console.log("setting title");
		var title = portfolioItem.find(".portfolio-item-title")[0];
		title.innerHTML = data["portfolio-item-title"];
		//console.log(title);
	}
	else {
		console.log("missing portfolio item title");
	}

	if(data.hasOwnProperty("portfolio-item-image")) {
		//console.log("setting image");
		var image = portfolioItem.find(".portfolio-item-image")[0];
		image.src = data["portfolio-item-image"];
		//console.log(image);
	}
	else {
		console.log("missing portfolio item image");
	}

	//console.log(portfolioItem);
};

var LoadModalData = function(game, data) {
	var modal = $(game+"-portfolio-modal");

	if(data.hasOwnProperty("id")) {
		//console.log("setting id");
		var modalIdHolder = modal.find(".portfolio-modal")[0];
		modalIdHolder.id = data["id"] + "-modal";
		//console.log(modalIdHolder);
	}
	else {
		console.log("missing id");
	}

	if(data.hasOwnProperty("modal-projectHeading")) {
		//console.log("setting projectHeading");
		var projectHeading = modal.find(".modal-projectHeading")[0];
		projectHeading.innerHTML = data["modal-projectHeading"];
		//console.log(projectHeading);
	}
	else {
		console.log("missing modal project heading");
	}

	if(data.hasOwnProperty("modal-intro")) {
		//console.log("setting intro");
		var intro = modal.find(".modal-intro")[0];
		intro.innerHTML = data["modal-intro"];
		//console.log(intro);
	}
	else {
		console.log("missing modal intro");
	}

	if(data.hasOwnProperty("modal-img")) {
		//console.log("setting image");
		var image = modal.find(".modal-img")[0];
		image.src = data["modal-img"];
		//console.log(image);
	}
	else {
		console.log("missing modal image");
	}

	if(data.hasOwnProperty("modal-html")) {
		//console.log("setting html");
		var html = modal.find(".modal-html")[0];
		html.innerHTML = data["modal-html"];
		//console.log(html);
	}
	else {
		console.log("missing modal html");
	}

	//console.log(modal);
};

var LoadFromJson = function(game, data) {
	//console.log(data);
	LoadPortfolioItemData(game, data);
	LoadModalData(game, data);
};

var LoadContent = function(game) {
	//console.log("Generating content for " + game);
	$.getJSON("data/" + game + ".json", null, function(data) {
		LoadFromJson(game, data);
	});
};

$(document).ready(function() {
	console.log(versionNum);

	portfolioItemTemplate = $('<div>').load(portfolioItemTemplatePath, function() { // load the portfolio item template
		modalTemplate = $('<div>').load(modalTemplatePath, function() { // load the modal template
			// fill in the data
			for (var i = games.length - 1; i >= 0; i--) {
				var game = games[i];
				GenerateContent(game); // generate first to ensure ordering
				LoadContent(game);
			}
		});
	});
});<|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();
                }
            }]);
        //sets velocity
        this.body.setVelocity(5, 20);
        this.facing = "right";
        //makes screen follow player
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        //adds animations for name, frames and speed
        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);
        //sets current animation for game start
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        //control for moving right
        if (me.input.isKeyPressed("right")) {
            this.flipX(true);
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";

        }
        //control for moving left
        else if (me.input.isKeyPressed("left")) {
            this.flipX(false);
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.facing = "left";
        }
        //for when mario stands still
        else {
            this.body.vel.x = 0;
        }
        //control for jumping
        if (me.input.isKeyPressed('jump')) {
            // make sure we are not already jumping or falling
            if (!this.body.jumping && !this.body.falling) {
                // set current vel to the maximum defined value
                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 than to idle
                this.renderable.setCurrentAnimation("attack", "idle");
                //begin from first animation
                this.renderable.setAnimationFrame();
            }

        } else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
                this.renderable.setAnimationFrame();
            }
        } else {
            this.renderable.setCurrentAnimation("idle");
        }
        // me.collision.check(this, true, this.collideHandler.bind(this));
        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;

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

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

        this.type = "EnemyBaseEntity";
        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 () {

    }

});<commit_msg>fixed collisions for left and right<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();
                }
            }]);
        //sets velocity
        this.body.setVelocity(5, 20);
        this.facing = "right";
        //makes screen follow player
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        //adds animations for name, frames and speed
        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);
        //sets current animation for game start
        this.renderable.setCurrentAnimation("idle");
    },
    update: function (delta) {
        //control for moving right
        if (me.input.isKeyPressed("right")) {
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.facing = "right";
            this.flipX(true);
        }
        //control for moving left
        else if (me.input.isKeyPressed("left")) {
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.facing = "left";
            this.flipX(false);
        }
        //for when mario stands still
        else {
            this.body.vel.x = 0;
        }
        //control for jumping
        if (me.input.isKeyPressed('jump')) {
            // make sure we are not already jumping or falling
            if (!this.body.jumping && !this.body.falling) {
                // set current vel to the maximum defined value
                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 than to idle
                this.renderable.setCurrentAnimation("attack", "idle");
                //begin from first animation
                this.renderable.setAnimationFrame();
            }

        } else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
                this.renderable.setAnimationFrame();
            }
        } else {
            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;

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

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

        this.type = "EnemyBaseEntity";
        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 () {

    }

});<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend ({
	// this is a class
	init: function(x, y, settings) {
		// melon js uses this constructor on most things to help us set up
		this._super(me.Entity, "init", [x, y, {
			// this means reaching to the constructor of entites
			image: "player",
			width: 64,
			// tells the screen what amount of space to reserve
			height: 64,
			spritewidth: "64",
			// spritewidth/height are passing the main information tells what to do with the image
			spriteheight: "64",
			// these are setting the properties of the picture o the right demensions so the picture appears properly
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
				// rect is what the guy can walk in to
			}
		}]);

		this.body.setVelocity(5, 20);
		// this also changes the y velocity of the character
		// this is the movement speed of the character
		this.facing = "right";
		// keeps track of which direction the character is going
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this says wherever the player goes the screen will follow him

		this.renderable.addAnimation("idle", [78]);
		// when the character is still this is what he will look like
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		// this is going to be what the cahracter is going to change into

		this.renderable.setCurrentAnimation("idle");
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72] , 80);
	},

	update: function(delta) {
		// this function is what happens on the fly
		if(me.input.isKeyPressed("right")) {
			// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "right";
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
			// this is flipping the animation around

		}
		else if(me.input.isKeyPressed("left")) {
			// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "left";
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.flipX(false);
			// this is flipping the animation around

		}
		else {
			this.body.vel.x = 0;
		}
		if (me.input.isKeyPressed('jump')) {
     	 // make sure we are not already jumping or falling
      		if (!this.body.jumping && !this.body.falling) {
        // set current vel to the maximum defined value
        // gravity will then do the rest
        	this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
        // set the jumping flag
        	this.body.jumping = true;
        }
    }
		if(me.input.isKeyPressed("attack")) {
			if (!this.renderable.isCurrentAnimation("attack")) {
				// set current animation to attack and once that is over
				// goes back to the idle animations
				this.renderable.setCurrentAnimation("attack", "idle");
				// makes it so that the next time we start this sequence we begin from the first animation not where we left off when we switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		if(this.body.vel.x !== 0)
		//allowing the guy to not immediately walk
		{
			if(!this.renderable.isCurrentAnimation("walk")) {
				this.renderable.setCurrentAnimation("walk");
				// this says it doesnt want to start the walk animation if it is already walking
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")) {
			this.renderable.setCurrentAnimation("idle");
		}
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		// passing a parameter into collide function
		// delta is the change in time that has happens
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		// this is updating the animations on the fly
		return true;
	},
	collideHandler: function(response) {
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

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

			if (xdif>-20 && this.facing=== 'right' xdif<0) {
				this.body.vel.x = 0;
				// stops the player from moving
				this.pos.x = this.pos.x - 1;
				// slighty turns the character
			}
			else if (xdif<60 && this.facing=== 'left' && xdif>0) {
				this.body.vel.x = 0;
				// stops the player from moving
				this.pos.x = this.pos.x + 1;
				// cant walk into castle from left or right
			}

		}
		// this is going to determine what happens when we hit the enemy entity
	}
});

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 shows the height of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been touched/attacked
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "PlayerBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the superclass to update
		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 shows the hight of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "EnemyBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the super class to update
		return true;
	},
		onCollision: function() {

		}

});<commit_msg>Video 16<commit_after>game.PlayerEntity = me.Entity.extend ({
	// this is a class
	init: function(x, y, settings) {
		// melon js uses this constructor on most things to help us set up
		this._super(me.Entity, "init", [x, y, {
			// this means reaching to the constructor of entites
			image: "player",
			width: 64,
			// tells the screen what amount of space to reserve
			height: 64,
			spritewidth: "64",
			// spritewidth/height are passing the main information tells what to do with the image
			spriteheight: "64",
			// these are setting the properties of the picture o the right demensions so the picture appears properly
			getShape: function() {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
				// rect is what the guy can walk in to
			}
		}]);

		this.body.setVelocity(8, 20);
		// this also changes the y velocity of the character
		// this is the movement speed of the character
		this.facing = "right";
		// keeps track of which direction the character is going
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this says wherever the player goes the screen will follow him

		this.renderable.addAnimation("idle", [78]);
		// when the character is still this is what he will look like
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		// this is going to be what the cahracter is going to change into

		this.renderable.setCurrentAnimation("idle");
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72] , 80);
	},

	update: function(delta) {
		// this function is what happens on the fly
		if(me.input.isKeyPressed("right")) {
			// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "right";
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
			// this is flipping the animation around

		}
		else if(me.input.isKeyPressed("left")) {
			// set the position of my x by adding the velocity to find above in set veloctiy
			// setVeloctiy() and multiplying it by timer.tick
			// me.timer.tick makes the movement look smooth
			this.facing = "left";
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			this.flipX(false);
			// this is flipping the animation around

		}
		else {
			this.body.vel.x = 0;
		}
		if (me.input.isKeyPressed('jump') && !this.body.jumping && !this.body.falling) {
     	 // make sure we are not already jumping or falling
      		this.body.jumping = true;
        // set current vel to the maximum defined value
        // gravity will then do the rest
        	this.body.vel.y -= this.body.accel.y * me.timer.tick;
    }
		if(me.input.isKeyPressed("attack")) {
			if (!this.renderable.isCurrentAnimation("attack")) {
				// set current animation to attack and once that is over
				// goes back to the idle animations
				this.renderable.setCurrentAnimation("attack", "idle");
				// makes it so that the next time we start this sequence we begin from the first animation not where we left off when we switched to another animation
				this.renderable.setAnimationFrame();
			}
		}
		if(this.body.vel.x !== 0)
		//allowing the guy to not immediately walk
		{
			if(!this.renderable.isCurrentAnimation("walk")) {
				this.renderable.setCurrentAnimation("walk");
				// this says it doesnt want to start the walk animation if it is already walking
			}
		}
		else if(!this.renderable.isCurrentAnimation("attack")) {
			this.renderable.setCurrentAnimation("idle");
		}
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		// passing a parameter into collide function
		// delta is the change in time that has happens
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		// this is updating the animations on the fly
		return true;
	},

	collideHandler: function(response) {
		console.log("collision");
		if(response.b.type === 'EnemyBase'){
			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 > -30 && this.facing === 'right' && (xdif < 0)) {
				this.body.vel.x = 0;
				// stops the player from moving
				this.pos.x = this.pos.x - 1;
				// slighty turns the character
			}
			else if (xdif< 70 && this.facing === 'left' && xdif > 0) {
				this.body.vel.x = 0;
				// stops the player from moving
				this.pos.x = this.pos.x + 1;
				// cant walk into castle from left or right
			}
		}
		// this is going to determine what happens when we hit the enemy entity
	}
});

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 shows the height of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been touched/attacked
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "PlayerBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the superclass to update
		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 shows the hight of the bases
			}
}]);
		this.broken = false;
		// this is saying that the tower has not yet been
		this.health = 10;
		// starting energy for tower
		this.alwaysUpdate = true;
		// updates the screen whether or not we are not looking at it
		this.body.onCollision = this.onCollision.bind(this);
		// if somebody runs into the tower it will be able to collide with it

		this.type = "EnemyBase";
		// this is a type you can use to check to see what you are running into
		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
		// renderable is a class built in melon js that we can play with the animation with

	},

	update: function(delta) {
		if( this.health <= 0) {
			this.broken =  true;
			// this means that the character is dead
			this.renderable.setCurrentAnimation("broken");
	}
		this.body.update(delta);
		// updates the code

		this._super(me.Entity, "update", [delta]);
		// telling the super class to update
		return true;
	},
		onCollision: function() {

		}

});<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
	// init function is creating my character and holding
	//all of his properties
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y,{
			image: "player",
			width: 64,
			height: 64,
			spritewidth:"64",
			spriteheight:"64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
             // this.body.setVelocity allows us to set were
			//our player standes
	  		this.body.setVelocity(5, 20);

	  		this.renderable.addAnimation('idle', [78]);
	  		this.renderable.addAnimation('walk',[117, 118, 119, 120, 121, 122,
	  			123, 124, 125], 80);
	  		this.renderable.setCurrentAnimation('idle');

	},
		// update function works with my PlayerEntity above
		// update function constently updates my PlayerEntity
	update: function(delta){
		if(me.input.isKeyPressed("right")){
			//sets the position of my X by adding the volocity above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);

		}
		else{
			this.body.vel.x = 0;
		}

		 //these if statements are checking the animation of the character
		if(this.body.vel.x !== 0){
		if(!this.renderable.isCurrentAnimation('walk')){
			this.renderable.setCurrentAnimation("walk");
		}
	}else{
		this.renderable.setCurrentAnimation("idle");
	}

		this.body.update(delta);
		//this._super updates my characters animation
		this._super(me.Entity, "update", [delta]);
		return true;
	}

// 	update: function(deltatime){
//         if(me.input.isKeyPressed("right")){
//          this.renderable.flipX(false);
//          this.vel.x += this.accel.x * me.timer.tick;
//  }
//         else if(me.input.isKeyPressed("left")){
//             this.renderable.flipX(true);
//             this.vel.x -= this.accel.x * me.timer.tick;
//  }

//          if(me.input.isKeyPressed("jump")){
//              this.jumping = true;
//            this.mutipleJump = (this.vel.y === 0)?1:this.mutipleJump;
// 	 if (this.mutipleJump<=2) {
// 				// easy 'math' for double jump
// 	   this.vel.y -= (this.maxVel.y * this.mutipleJump++) * me.timer.tick;

//   }
//   }
// }

});
//this is a Base Tower entity
game.PlyerBaseEntity = me.Entity.extend	({
	//init: function is creating my
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			imagae: 'tower',
			width: 100,
			height: 100,
			spritewidth '100',
			spriteheight '100',
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}

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

	update:function(){
		if(this.health<=0){
			this.broken = true;
		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function(){

	}
});<commit_msg>"Error on line 88 file entities.js"<commit_after>game.PlayerEntity = me.Entity.extend({
	// init function is creating my character and holding
	//all of his properties
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y,{
			image: "player",
			width: 64,
			height: 64,
			spritewidth:"64",
			spriteheight:"64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
             // this.body.setVelocity allows us to set were
			//our player standes
	  		this.body.setVelocity(5, 20);

	  		this.renderable.addAnimation('idle', [78]);
	  		this.renderable.addAnimation('walk',[117, 118, 119, 120, 121, 122,
	  			123, 124, 125], 80);
	  		this.renderable.setCurrentAnimation('idle');

	},
		// update function works with my PlayerEntity above
		// update function constently updates my PlayerEntity
	update: function(delta){
		if(me.input.isKeyPressed("right")){
			//sets the position of my X by adding the volocity above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);

		}
		else{
			this.body.vel.x = 0;
		}

		 //these if statements are checking the animation of the character
		if(this.body.vel.x !== 0){
		if(!this.renderable.isCurrentAnimation('walk')){
			this.renderable.setCurrentAnimation("walk");
		}
	}else{
		this.renderable.setCurrentAnimation("idle");
	}

		this.body.update(delta);
		//this._super updates my characters animation
		this._super(me.Entity, "update", [delta]);
		return true;
	}

// 	update: function(deltatime){
//         if(me.input.isKeyPressed("right")){
//          this.renderable.flipX(false);
//          this.vel.x += this.accel.x * me.timer.tick;
//  }
//         else if(me.input.isKeyPressed("left")){
//             this.renderable.flipX(true);
//             this.vel.x -= this.accel.x * me.timer.tick;
//  }

//          if(me.input.isKeyPressed("jump")){
//              this.jumping = true;
//            this.mutipleJump = (this.vel.y === 0)?1:this.mutipleJump;
// 	 if (this.mutipleJump<=2) {
// 				// easy 'math' for double jump
// 	   this.vel.y -= (this.maxVel.y * this.mutipleJump++) * me.timer.tick;

//   }
//   }
// }

});
//this is a Base Tower entity
game.PlyerBaseEntity = me.Entity.extend	({
	//init: function is creating my
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			imagae: 'tower',
			width: 100,
			height: 100,
			spritewidth "100",
			spriteheight "100",
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}

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

	update:function(){
		if(this.health<=0){
			this.broken = true;
		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function(){

	}
});

//this is the enemy Base
game.EnemyBaseEntity = me.Entity.extend	({
	//init: function is creating my
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			imagae: 'tower',
			width: 100,
			height: 100,
			spritewidth '100',
			spriteheight '100',
			getShape: function(){
				return (new me.Rect(0, 0, 100, 100)).toPolygon();
			}

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

	update:function(){
		if(this.health<=0){
			this.broken = true;
		}
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function(){

	}
});<|endoftext|>


<commit_before>// player's class
game.PlayerEntity = me.Entity.extend ({
	//constructor function
	init: function(x, y, settings){
		//reachers the constructor function for enitity
		this._super(me.Entity, 'init', [x, y, {
			//settings. shoes the player
			image: "player",
			//sets aside a width of 64 pixels for the sprite
			width: 64,
			//sets aside a height of 64 pixels for the sprite
			height: 64,
			//gives the sprite a width of 64.
			spritewidth : "64",
			//gives the sprite a width of 64
			spriteheight: "64",
			getShape: function(){
				//returns a rectangle of what the player walks into
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		//allows player to be interacted with
		this.type = "PlayerEntity";
		//sets the player's health to 100
		this.health = game.data.playerHealth;
		//sets movemet speed. allows player to move horizantally and vertically
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		//keeps track of which way the character is going
		this.facing = "right";
		//variable for keeping track of time and date
		this.now = new Date().getTime();
		//same ^^
		this.lastHit = this.now;
		//declares that player isn't dead
		this.dead = false;
		this.attack = game.data.playerAttack;
		//keeps the player from attacking multiple times
		this.lastAttack = new Date().getTime();
		//makesit so the player is always on the screen
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		//gives player animation while standing
		this.renderable.addAnimation("idle", [78]);
		//gives player animation while walking
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		//gives player animation while attacking
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		//the player's start animation
		this.renderable.setCurrentAnimation("idle");
	},

	//delta is the change in time that's happening
	update: function(delta){
		//keeps timer updated
		this.now = new Date().getTime();

		//allows characters health to go down
		if(this.health <= 0){
			this.dead = true;
		}

		//runs if the right key is pressed
		if(me.input.isKeyPressed("right")){
			//when right key is pressed, adds to the position of my x by the velocity defined above in setVelocity and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//so the program knows the character is facing right
			this.facing = "right";
			//flips the animation
			this.flipX(true);
		}

		else if(me.input.isKeyPressed("left")){
			//when right key is pressed, adds to the position of my x by the velocity defined above in setVelocity and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			//so the program knows the character is facing left
			this.facing = "left";
			//doesn't flip the animation
			this.flipX(false);
		}

		//if the right key isn't being pressed, the player doesn't move
		else{
			this.body.vel.x = 0;
		}
		//runs only if the up key is pressed, the player isn't already jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			//makes the player jump
			this.body.jumping = true;
			//sets velocity of the jump and the time
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

		//runs if the attack key is pressed
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				//sets current animation to attack. goes back to idle oncethe attack is over it goes back to idle
				this.renderable.setCurrentAnimation("attack", "idle")
				//makes it so that next time the button is pressed the player starts from the first animation, not where it left off
				this.renderable.setAnimationFrame();
			}
		}

		//runs if the player is moving horizantally and not attacking
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
			//runs if the player isn't already running the walk animation
			if(!this.renderable.isCurrentAnimation("walk")){
				//gives the player the walking animation
				this.renderable.setCurrentAnimation("walk");
			}
		}
		//runs if player is standing still and not attacking
		else if(!this.renderable.isCurrentAnimation("attack")){
			//gives the player the idle animation
			this.renderable.setCurrentAnimation("idle");
		}
		//checks to see if player is colliding with base
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		//tells above code to work
		this.body.update(delta);
		//updates the code
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	//runs when called
	loseHealth: function(damage){
		//subtracts set amount of health
		this.health = this.health - damage;
	},
	//function for when player collides with tower
	collideHandler: function(response){
		//runs if the player collides with the enemy base
		if (response.b.type === 'EnemyBaseEntity') {
			//represents the difference between player's y distance and enemy's y distance
			var ydif = this.pos.y - response.b.pos.y;
			//represents the difference between player's and enemy base's x distance
			var xdif = this.pos.x - response.b.pos.x;
			//runs if the player is on top of the enemy base
			if (ydif < -40 && xdif < 60 && xdif > -35) {
				//stops the player from moving down
				this.body.falling = false;
				//keeps the player from falling through the tower
				this.body.vel.y = -1;
			}
			//runs if the player's x position is 37 units away from the tower while facing right
			else if (xdif > -36 && this.facing === "right" && xdif < 0) {
				//stops player from moving
				this.body.vel.x = 0;
				//moves player slightly away from tower
				//this.pos.x = this.pos.x -1;
			}
			//runs if the player's x position is 74 units away from the tower while facing left
			else if (xdif < 75 && this.facing === "left" && xdif > 0) {
				//stops player from moving
				this.body.vel.x = 0;
				//moves player slightly away from tower
				//this.pos.x = this.pos.x +1;
			}
			//runs if the player is attacking and its been 400 milliseconds since the last hit
			if (this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				//so the computer knows th eplayer just hit the tower
				this.lastHit = this.now;
				//calls the loseHealth function
				response.b.loseHealth(game.data.playerAttack);
			}
		}
		//allows the player to attack the enemy creeps
		else if(response.b.type==='EnemyCreep'){
			var xdif = this.pos.x - response.b.pos.x;
			var ydif = this.pos.y - response.b.pos.y;

			//player can attack the creep when it is on the left
			if(xdif>0){
				//this.pos.x = this.pos.x + 1;
				if(this.facing==="left"){
					this.body.vel.x = 0;
				}
			}
			//player can attack the creep when it is on the right
			else{
				//this.pos.x = this.pos.x - 1;
				if(this.facing==="right"){
					this.body.vel.x = 0;
				}
			}

			//determines how much health the creep has
			//health is based on how long you can hit the creep before it dies
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
				&& (Math.abs(ydif) <=40) &&
				(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				){
				this.lastHit = this.now;
				//if the creeps health is below players attack then run the if statement
				if(response.b.health <= game.data.playerAttack){
					//adds 1 gold for a creep kill
					game.data.gold += 1;
					console.log("Current gold: " + game.data.gold);
				}

				response.b.loseHealth(game.data.playerAttack);
			}
		}
	}
});

// FRIENDLY CREEP ATTEMPT
// game.FriendCreep = me.Entity.extend({
// 	init: function(x, y, settings){
// 			//reaches the constructor function for enitity
// 			this._super(me.Entity, 'init', [x, y, {
// 				//settings. shows the creep
// 				image: "creep2",
// 				//sets aside a width of 64 pixels for the sprite
// 				width: 32,
// 				//sets aside a height of 64 pixels for the sprite
// 				height: 64,
// 				//gives the sprite a width of 64.
// 				spritewidth : "32",
// 				//gives the sprite a width of 64
// 				spriteheight: "64",
// 				//gives creep a form
// 				getShape: function(){
// 					return(new me.Rect(0, 0, 32, 64)).toPolygon();
// 				}
// 			}]);
// 			//sets health to ten
// 			this.health = 10;
// 			//makes the creep's satus update
// 			this.alwaysUpdate = true;
// 			//says the creep is not attacking
// 			this.attacking = false;
// 			//records last time creep attacked anything
// 			this.lastAttacking = new Date().getTime();
// 			//records last time creep hit anything
// 			this.lastHit = new Date().getTime();
// 			//timer for attacking
// 			this.now = new Date().getTime();
// 			//sets the creep's horizantal and vertical speed
// 			this.body.setVelocity(3, 20);
// 			//sets the sprite's type
// 			this.type = "FriendCreep";
// 			//creates the walking animation
// 			this.renderable.addAnimation("walk", [4, 5, 6, 7], 80);
// 			//applies the walking animation
// 			this.renderable.setCurrentAnimation("walk");
// 		},

// 		//delta is the change in time that's happening
// 		update: function(delta){
// 			//updates attack
// 			this.now = new Date().getTime();
// 			//makes the creep move
// 			this.body.vel.x += this.body.accel.x *  me.timer.tick;
// 			//checks for collisions with player
// 			me.collision.check(this, true, this.collideHandler.bind(this), true);
// 			//basic update functions
// 			this.body.update(delta);
// 			this._super(me.Entity, "update", [delta]);
// 			return true;
// 		},
// 		//function for creeps' collisions
// 		collideHandler: function(response){
// 			//runs if creep collides with player base
// 			if (response.b.type === 'EnemyBase') {
// 				//makes the creep attack
// 				this.attacking = true;
// 				//timer that says when last attacked
// 				//this.lastAttacking = this.now;
// 				//prevents the creep from walking through the tower
// 				this.body.vel.x = 0;
// 				//pushes the creep back a little to maintain its position
// 				this.pos.x = this.pos.x + 1;
// 				//makes the creep hit the tower every second
// 				if ((this.now - this.lastHit >= 1000)) {
// 					//updates the lastHit timer
// 					this.lastHit = this.now;
// 					//runs the losehealth function, with 1 point damage
// 					response.b.loseHealth(1);
// 				}
// 			}
// 		}

// });

<commit_msg>Video 30<commit_after>// player's class
game.PlayerEntity = me.Entity.extend ({
	//constructor function
	init: function(x, y, settings){
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();

		//allows player to be interacted with
		this.type = "PlayerEntity";
		this.setFlags();

		//makesit so the player is always on the screen
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.addAnimation();

		//the player's start animation
		this.renderable.setCurrentAnimation("idle");
	},

	setSuper: function(){
		//reachers the constructor function for enitity
		this._super(me.Entity, 'init', [x, y, {
			//settings. shoes the player
			image: "player",
			//sets aside a width of 64 pixels for the sprite
			width: 64,
			//sets aside a height of 64 pixels for the sprite
			height: 64,
			//gives the sprite a width of 64.
			spritewidth : "64",
			//gives the sprite a width of 64
			spriteheight: "64",
			getShape: function(){
				//returns a rectangle of what the player walks into
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
	},

	setPlayerTimers: function(){
		//variable for keeping track of time and date
		this.now = new Date().getTime();
		//same ^^
		this.lastHit = this.now;
		//keeps the player from attacking multiple times
		this.lastAttack = new Date().getTime();
	},

	setAttributes: function(){
		//sets the player's health to 100
		this.health = game.data.playerHealth;
		//sets movemet speed. allows player to move horizantally and vertically
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
	},

	setFlags: function(){
		//keeps track of which way the character is going
		this.facing = "right";
		//declares that player isn't dead
		this.dead = false;
	},

	addAnimation: function(){
		//gives player animation while standing
		this.renderable.addAnimation("idle", [78]);
		//gives player animation while walking
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		//gives player animation while attacking
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
	},

	//delta is the change in time that's happening
	update: function(delta){
		//keeps timer updated
		this.now = new Date().getTime();

		//allows characters health to go down
		if(this.health <= 0){
			this.dead = true;
		}

		//runs if the right key is pressed
		if(me.input.isKeyPressed("right")){
			//when right key is pressed, adds to the position of my x by the velocity defined above in setVelocity and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//so the program knows the character is facing right
			this.facing = "right";
			//flips the animation
			this.flipX(true);
		}

		else if(me.input.isKeyPressed("left")){
			//when right key is pressed, adds to the position of my x by the velocity defined above in setVelocity and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			//so the program knows the character is facing left
			this.facing = "left";
			//doesn't flip the animation
			this.flipX(false);
		}

		//if the right key isn't being pressed, the player doesn't move
		else{
			this.body.vel.x = 0;
		}
		//runs only if the up key is pressed, the player isn't already jumping or falling
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){
			//makes the player jump
			this.body.jumping = true;
			//sets velocity of the jump and the time
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

		//runs if the attack key is pressed
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				//sets current animation to attack. goes back to idle oncethe attack is over it goes back to idle
				this.renderable.setCurrentAnimation("attack", "idle")
				//makes it so that next time the button is pressed the player starts from the first animation, not where it left off
				this.renderable.setAnimationFrame();
			}
		}

		//runs if the player is moving horizantally and not attacking
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){
			//runs if the player isn't already running the walk animation
			if(!this.renderable.isCurrentAnimation("walk")){
				//gives the player the walking animation
				this.renderable.setCurrentAnimation("walk");
			}
		}
		//runs if player is standing still and not attacking
		else if(!this.renderable.isCurrentAnimation("attack")){
			//gives the player the idle animation
			this.renderable.setCurrentAnimation("idle");
		}
		//checks to see if player is colliding with base
		me.collision.check(this, true, this.collideHandler.bind(this), true);
		//tells above code to work
		this.body.update(delta);
		//updates the code
		this._super(me.Entity, "update", [delta]);
		return true;
	},
	//runs when called
	loseHealth: function(damage){
		//subtracts set amount of health
		this.health = this.health - damage;
	},
	//function for when player collides with tower
	collideHandler: function(response){
		//runs if the player collides with the enemy base
		if (response.b.type === 'EnemyBaseEntity') {
			//represents the difference between player's y distance and enemy's y distance
			var ydif = this.pos.y - response.b.pos.y;
			//represents the difference between player's and enemy base's x distance
			var xdif = this.pos.x - response.b.pos.x;
			//runs if the player is on top of the enemy base
			if (ydif < -40 && xdif < 60 && xdif > -35) {
				//stops the player from moving down
				this.body.falling = false;
				//keeps the player from falling through the tower
				this.body.vel.y = -1;
			}
			//runs if the player's x position is 37 units away from the tower while facing right
			else if (xdif > -36 && this.facing === "right" && xdif < 0) {
				//stops player from moving
				this.body.vel.x = 0;
				//moves player slightly away from tower
				//this.pos.x = this.pos.x -1;
			}
			//runs if the player's x position is 74 units away from the tower while facing left
			else if (xdif < 75 && this.facing === "left" && xdif > 0) {
				//stops player from moving
				this.body.vel.x = 0;
				//moves player slightly away from tower
				//this.pos.x = this.pos.x +1;
			}
			//runs if the player is attacking and its been 400 milliseconds since the last hit
			if (this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				//so the computer knows th eplayer just hit the tower
				this.lastHit = this.now;
				//calls the loseHealth function
				response.b.loseHealth(game.data.playerAttack);
			}
		}
		//allows the player to attack the enemy creeps
		else if(response.b.type==='EnemyCreep'){
			var xdif = this.pos.x - response.b.pos.x;
			var ydif = this.pos.y - response.b.pos.y;

			//player can attack the creep when it is on the left
			if(xdif>0){
				//this.pos.x = this.pos.x + 1;
				if(this.facing==="left"){
					this.body.vel.x = 0;
				}
			}
			//player can attack the creep when it is on the right
			else{
				//this.pos.x = this.pos.x - 1;
				if(this.facing==="right"){
					this.body.vel.x = 0;
				}
			}

			//determines how much health the creep has
			//health is based on how long you can hit the creep before it dies
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
				&& (Math.abs(ydif) <=40) &&
				(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				){
				this.lastHit = this.now;
				//if the creeps health is below players attack then run the if statement
				if(response.b.health <= game.data.playerAttack){
					//adds 1 gold for a creep kill
					game.data.gold += 1;
					console.log("Current gold: " + game.data.gold);
				}

				response.b.loseHealth(game.data.playerAttack);
			}
		}
	}
});

// FRIENDLY CREEP ATTEMPT
// game.FriendCreep = me.Entity.extend({
// 	init: function(x, y, settings){
// 			//reaches the constructor function for enitity
// 			this._super(me.Entity, 'init', [x, y, {
// 				//settings. shows the creep
// 				image: "creep2",
// 				//sets aside a width of 64 pixels for the sprite
// 				width: 32,
// 				//sets aside a height of 64 pixels for the sprite
// 				height: 64,
// 				//gives the sprite a width of 64.
// 				spritewidth : "32",
// 				//gives the sprite a width of 64
// 				spriteheight: "64",
// 				//gives creep a form
// 				getShape: function(){
// 					return(new me.Rect(0, 0, 32, 64)).toPolygon();
// 				}
// 			}]);
// 			//sets health to ten
// 			this.health = 10;
// 			//makes the creep's satus update
// 			this.alwaysUpdate = true;
// 			//says the creep is not attacking
// 			this.attacking = false;
// 			//records last time creep attacked anything
// 			this.lastAttacking = new Date().getTime();
// 			//records last time creep hit anything
// 			this.lastHit = new Date().getTime();
// 			//timer for attacking
// 			this.now = new Date().getTime();
// 			//sets the creep's horizantal and vertical speed
// 			this.body.setVelocity(3, 20);
// 			//sets the sprite's type
// 			this.type = "FriendCreep";
// 			//creates the walking animation
// 			this.renderable.addAnimation("walk", [4, 5, 6, 7], 80);
// 			//applies the walking animation
// 			this.renderable.setCurrentAnimation("walk");
// 		},

// 		//delta is the change in time that's happening
// 		update: function(delta){
// 			//updates attack
// 			this.now = new Date().getTime();
// 			//makes the creep move
// 			this.body.vel.x += this.body.accel.x *  me.timer.tick;
// 			//checks for collisions with player
// 			me.collision.check(this, true, this.collideHandler.bind(this), true);
// 			//basic update functions
// 			this.body.update(delta);
// 			this._super(me.Entity, "update", [delta]);
// 			return true;
// 		},
// 		//function for creeps' collisions
// 		collideHandler: function(response){
// 			//runs if creep collides with player base
// 			if (response.b.type === 'EnemyBase') {
// 				//makes the creep attack
// 				this.attacking = true;
// 				//timer that says when last attacked
// 				//this.lastAttacking = this.now;
// 				//prevents the creep from walking through the tower
// 				this.body.vel.x = 0;
// 				//pushes the creep back a little to maintain its position
// 				this.pos.x = this.pos.x + 1;
// 				//makes the creep hit the tower every second
// 				if ((this.now - this.lastHit >= 1000)) {
// 					//updates the lastHit timer
// 					this.lastHit = this.now;
// 					//runs the losehealth function, with 1 point damage
// 					response.b.loseHealth(1);
// 				}
// 			}
// 		}

// });

<|endoftext|>


<commit_before>//adds a specific player
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 the spawn
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your character is going
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
			//grabs animation from image
		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){
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		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;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		else if(this.body.vel.x !== 0){
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
			//Makes perameter
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

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

	},
			//Hold all information for collision
	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);
			//sets barrier on the top of the enemy base
			//y axis must come first because it;s more important
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				this.body.vel.y = -1;
			}
			//sets barrier on right side of the enemy base
			else if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			//sets barrier on left side of the enemy base
			// && x(y)dif>(<)0 makes it so the barrier doesn't work while facibg the other way
			}else if(xdif<70 && this.facing=='left' && xdif>0){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
			}
		}
	}
});
	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		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, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

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

	onCollision: function(){

	}

});<commit_msg>Video 17 No Comments<commit_after>//adds a specific player
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 the spawn
		this.body.setVelocity(5, 20);
		//Keeps track of which direction your character is going
		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);
			//grabs animation from image
		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();
			//binds a key
		if(me.input.isKeyPressed("right")){
			//adds to the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick.
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.facing = "right";
			this.flipX(true);
			//set player to move left
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			//flips animation
			this.flipX(false);
		}else{
			this.body.vel.x = 0;
		}
			//sets animation
			// && !this.jumping && !this.falling makes it so you can't
			// double jump while jumping or falling
		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;
		}

			//takes binded key from play.js and uses it
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
			//sets the current animation to attack and once that is over
			//goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
			//makes it so that the next time we start this sequence, we begin
			//from the first animation, not wherever we left off when we
			//switched to another animation
				this.renderable.setAnimationFrame();
			}
		}

			//sets current animation
		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");
		}
			//Makes perameter
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		this.body.update(delta);

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

	},
			//Hold all information for collision
	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);
			//sets barrier on the top of the enemy base
			//y axis must come first because it;s more important
			if(ydif<-40 && xdif< 70 && xdif>-35){
				this.body.falling = false;
				this.body.vel.y = -1;
			}
			//sets barrier on right side of the enemy base
			else if(xdif>-35 && this.facing=='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			//sets barrier on left side of the enemy base
			// && x(y)dif>(<)0 makes it so the barrier doesn't work while facibg the other way
			}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){
				this.lastHit = this.now;
				response.b.loseHealth();
			}

		}
	}
});

	//adds base class
game.PlayerBaseEntity = me.Entity.extend({
	init : function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "PlayerBaseEntity";

		//adds animation for PlayerBase
		this.renderable.addAnimation("idle", [0]);
		//burning animation
		this.renderable.addAnimation("broken", [1]);
		//normal animation
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		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, {
			//adds image
			image: "tower",
			width: 100,
			height: 100,
			spritewidth: "100",
			spriteheight: "100",
			getShape: function() {
				return (new me.Rect(0, 0, 100, 70)).toPolygon();
			}
		}]);
			//variable that say that tower is not destroyed
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		//if someone runs with the tower, they will collide
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";
			//sets animation for EnemyBase
		this.renderable.addAnimation("idle", [0]);
			//burned base
		this.renderable.addAnimation("broken", [1]);
			//fixed base
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//if health is below 0, then you should die
		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--;
	}

});<|endoftext|>


<commit_before>// TODO
// player's class
game.PlayerEntity = me.Entity.extend ({
	//constructor function
	init: function(x, y, settings){
		//reachers the constructor function for enitity
		this._super(me.Entity, 'init', [x, y, {
			//settings. shoes the player
			image: "player",
			//sets aside a width of 64 pixels for the sprite
			width: 64,
			//sets aside a height of 64 pixels for the sprite
			height: 64,
			//gives the sprite a width of 64.
			spritewidth : "64",
			//gives the sprite a width of 64
			spriteheight: "64",
			getShape: function(){
				//returns a rectangle of what the player walks into
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//tells movement of player when moved
		this.body.setVelocity(5, 20);
	},
		//current postion changes by setVelocity()
		//me.timer.tick keeps movement smooth
	update: function(delta) {
		if(me.input.isKeyPressed("right")) {
			this.body.vel.x += this.body.accel.x * me.timer.tick;
		}
		//current postion changes by setVelocity()
		//me.timer.tick keeps movement smooth
		else if(me.input.isKeyPressed("left")) {
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
		}
		else {
			//if not pressing, no change in velocity
			this.body.vel.x = 0;
		}

		//lets game know to update screen
		this.body.update(delta);
		return true;

});<commit_msg>Added Player<commit_after>// TODO
// player's class
game.PlayerEntity = me.Entity.extend ({
	//constructor function
	init: function(x, y, settings){
		//reachers the constructor function for enitity
		this._super(me.Entity, 'init', [x, y, {
			//settings. shoes the player
			image: "player",
			//sets aside a width of 64 pixels for the sprite
			width: 64,
			//sets aside a height of 64 pixels for the sprite
			height: 64,
			//gives the sprite a width of 64.
			spritewidth : "64",
			//gives the sprite a width of 64
			spriteheight: "64",
			getShape: function(){
				//returns a rectangle of what the player walks into
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//tells movement of player when moved
		this.body.setVelocity(5, 20);

		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);

		this.renderable.setCurrentAnimation("idle");
	},
		//current postion changes by setVelocity()
		//me.timer.tick keeps movement smooth
	update: function(delta) {
		if(me.input.isKeyPressed("right")) {
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			this.flipX(true);
		}
		//current postion changes by setVelocity()
		//me.timer.tick keeps movement smooth
		else if(me.input.isKeyPressed("left")) {
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
		}
		else {
			//if not pressing, no change in velocity
			this.body.vel.x = 0;
		}

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

		//lets game know to update screen
		this.body.update(delta);
		this._super(me.Entity, "update", [delta]);
		return true;

});<|endoftext|>