<commit_before>var CriteriaBox =  React.createClass({

  getInitialState: function() {
    //return {specialities: []};
    return {AE:false, GB:false, GPE:false, GMM:false, GM:false, GP:false, IR:false, AS:false, A1:false, A2:false, A3:false, A4:false, A5:false, All:false, frCV:false, enCV:false}
  },
/*
  componentDidMount : function() {
    $.ajax({
      url:'/Student/Specialities',
      dataType: 'json',
      cache: false,
      success : function(specialities) {
        this.setState({specialities: specialities});
      }.bind(this),
      error : function(xhr, status, err) {
        console.error('/Student/Specialities', status, err.toString());
      }.bind(this)
    });
  }, */

  handleCheckAE : function(e) {this.setState({AE:e.target.checked});},
  handleCheckGB : function(e) {this.setState({GB:e.target.checked});},
  handleCheckGPE : function(e) {this.setState({GPE:e.target.checked});},
  handleCheckGMM : function(e) {this.setState({GMM:e.target.checked});},
  handleCheckGM : function(e) {this.setState({GM:e.target.checked});},
  handleCheckGP : function(e) {this.setState({GP:e.target.checked});},
  handleCheckIR : function(e) {this.setState({IR:e.target.checked});},
  handleCheckAS : function(e) {this.setState({AS:e.target.checked});},
  handleCheckA1 : function(e) {this.setState({A1:e.target.checked});},
  handleCheckA2 : function(e) {this.setState({A2:e.target.checked});},
  handleCheckA3 : function(e) {this.setState({A3:e.target.checked});},
  handleCheckA4 : function(e) {this.setState({A4:e.target.checked});},
  handleCheckA5 : function(e) {this.setState({A5:e.target.checked});},
  handleCheckAll : function(e) {this.setState({All:e.target.checked});},
  handleCheckFrCV : function(e) {this.setState({frCV:e.target.checked});},
  handleCheckEnCV : function(e) {this.setState({enCV:e.target.checked});},

  onSearchSubmit : function(e) {
    e.preventDefault();
    var specialitiesSearch = [];
    var yearsSearch = [];

    if (this.state.AE)
      specialitiesSearch.push('Automatique, Électronique');
    if (this.state.GB)
      specialitiesSearch.push('Génie Biochimique');
    if (this.state.GPE)
      specialitiesSearch.push('Génie des Procédés');
    if (this.state.GMM)
      specialitiesSearch.push('Génie Mathématique et Modélisation');
    if (this.state.GM)
      specialitiesSearch.push('Génie Mécanique');
    if (this.state.GP)
      specialitiesSearch.push('Génie Physique');
    if (this.state.IR)
      specialitiesSearch.push('Informatique et Réseaux');
    if (this.state.AS)
      specialitiesSearch.push('Aucune spécialité');

    var All = this.state.All;

    if (this.state.A1)
      yearsSearch.push('1');
    if (this.state.A2)
      yearsSearch.push('2');
    if (this.state.A3)
      yearsSearch.push('3');
    if (this.state.A4)
      yearsSearch.push('4');
    if (this.state.A5)
      yearsSearch.push('5');

    var frCV=this.state.frCV;
    var enCV=this.state.enCV;

    console.log("specialitiesSearch : " + specialitiesSearch);
    console.log("yearSearch : " + yearsSearch);
    this.props.onSearch(specialitiesSearch,yearsSearch,All,frCV,enCV);
  },

  render : function() {
    /* var criteriaList = this.state.specialities.map(function(speciality){
      return (

            <input type="checkbox" name={speciality}/> {speciality}

      );
    }); */

    return( //Todo : A automatiser

Critères

        <form onSubmit={this.onSearchSubmit}>

Spécialités :

                <input id="AE" type="checkbox" name='Automatique, Électronique' onClick={this.handleCheckAE}/> Automatique, Électronique
                <input id="GB" type="checkbox" name='Génie Biochimique' onClick={this.handleCheckGB}/> Génie Biochimique

                <input id="GPE" type="checkbox" name='Génie des Procédés' onClick={this.handleCheckGPE}/> Génie des Procédés
                <input id="GMM" type="checkbox" name='Génie Mathématique et Modélisation' onClick={this.handleCheckGMM}/> Génie Mathématique et Modélisation

                <input id="GM" type="checkbox" name='Génie Mécanique' onClick={this.handleCheckGM}/> Génie Mécanique
                <input id="GP" type="checkbox" name='Génie Physique' onClick={this.handleCheckGP}/> Génie Physique

                <input id="IR" type="checkbox" name='Informatique et Réseaux' onClick={this.handleCheckIR}/> Informatique et Réseaux
                <input id="AS" type="checkbox" name='Aucune spécialité' onClick={this.handleCheckAS}/> Aucune spécialité

Années :

                <input id="A1" type="checkbox" name='1' onClick={this.handleCheckA1}/> 1e année
                <input id="A2" type="checkbox" name='2' onClick={this.handleCheckA2}/> 2e année
                <input id="A3" type="checkbox" name='3' onClick={this.handleCheckA3}/> 3e année

                <input id="A4" type="checkbox" name='4' onClick={this.handleCheckA4}/> 4e année
                <input id="A5" type="checkbox" name='5' onClick={this.handleCheckA5}/> 5e année
                <input id="All" type="checkbox" name='toutes' onClick={this.handleCheckAll}/> toutes

Avec CV :

<input id="frCV" type="checkbox" name='withFrCv' onClick={this.handleCheckFrCV}/>français

<input id="enCV" type="checkbox" name='withFrCv' onClick={this.handleCheckEnCV}/>anglais

          <button id="btn_react" type="submit">Rechercher</button>
        </form>

    );
  }
});

//---------------------------------------------------
var CVDownloadForm = React.createClass({
  render : function() {

    var value, id;
    if (this.props.language == 'fr') {
      value="fr";
      id="downloadFormFR";
    } else if (this.props.language == 'en') {
      value="en";
      id="downloadFormEN";
    }

    return (
      <form class="pure-form" id={id} method="post" action="/file/download">
        <input type="hidden" name="dl" value={value}/>
        <input type="hidden" name="cvLogin" value={this.props.cvLogin}/>
        <input type="submit" value="Télécharger"/>
      </form>
    );
  }
});

//---------------------------------------------------

var CvList = React.createClass({

  render : function () {
    var cvListDisplay = this.props.cvList.map(function(cv) {
      var frCV, enCV, personalWebsite, linkedin, viadeo, github;

      if (cv.frCVPath == "")
        frCV = "-";
      else
        frCV = <CVDownloadForm language="fr" cvLogin={cv.login}/>;

      if (cv.enCVPath == "")
        enCV = "-";
      else
        enCV = <CVDownloadForm language="en" cvLogin={cv.login}/>;

      if (cv.personalWebsite == "")
        personalWebsite = "-";
      else {
        var httpPersonalWebsite = "http://" + cv.personalWebsite;
        personalWebsite = {cv.personalWebsite};
      }
      if (cv.linkedin == "")
        linkedin = "-";
      else
        linkedin = Linkedin;

      if (cv.viadeo == "")
        viadeo = "-";
      else
        viadeo = Viadeo;

      if (cv.github == "")
        github = "-";
      else
        github = github;
      return (

          {cv.year}
          {cv.speciality}
          {cv.lastName}
          {cv.firstName}
          {frCV}
          {enCV}
          {personalWebsite}
          {linkedin}
          {viadeo}
          {github}

      );
    });

    return (

Liste des CV

              Année
              Spécialité
              Nom
              Prénom
              CV français
              CV anglais
              Site personnel
              Linkedin
              Viadeo
              Github

            {cvListDisplay}

    );
  }
});

//---------------------------------------------------

var CvBox = React.createClass({

  getInitialState : function() {
    return {cvList : [], cvListFound :[], yearDown:true, specialityDown:true, lastNameDown:true, firstNameDown:true}
  },

  componentDidMount: function() {
    $.ajax({
      url:'/Student/Students',
      dataType: 'json',
      cache: false,
      success : function(list) {
        this.setState({cvList: list});
      }.bind(this),
      error : function(xhr, status, err) {
        console.error('/Student/Students', status, err.toString());
      }.bind(this)
    });
  },

  sortByLastName:function() {
    var newList = this.state.cvListFound;
    if (this.state.lastNameDown)
      newList.sort(function (a, b) {return a.lastName.localeCompare(b.lastName);});
    else
      newList.sort(function (a, b) {return b.lastName.localeCompare(a.lastName);});

    this.setState({cvListFound:newList, lastNameDown:!this.state.lastNameDown});
  },

  sortByFirstName:function() {
    var newList = this.state.cvListFound;
    if (this.state.firstNameDown)
      newList.sort(function (a, b) {return a.firstName.localeCompare(b.firstName);});
    else
      newList.sort(function (a, b) {return b.firstName.localeCompare(a.firstName);});

    this.setState({cvListFound:newList, firstNameDown:!this.state.firstNameDown});
  },

  sortByYear:function() {
    var newList = this.state.cvListFound;
    if (this.state.yearDown)
      newList.sort(function (a, b) {return a -b;});
    else
      newList.sort(function (a, b) {return b -a;});

    this.setState({cvListFound:newList, yearDown:!this.state.yearDown});
  },

  sortBySpeciality:function() {
    var newList = this.state.cvListFound;
    if (this.state.specialityDown)
      newList.sort(function (a, b) {return a.speciality.localeCompare(b.speciality);});
    else
      newList.sort(function (a, b) {return b.speciality.localeCompare(a.speciality);});

    this.setState({cvListFound:newList, specialityDown:!this.state.specialityDown});
  },

  search: function(specialitiesSearch,yearsSearch,All,frCV,enCV) {
    var newList=[];
    this.state.cvList.forEach(function(person){
      var goodSpeciality = false, goodYear = false;

      //Si cvfr demandé et person n'a pas de cvfr, alors person suivante
      if (frCV && person.frCVPath=="")
        return;

      if (enCV && person.enCVPath=="")
        return;

      //Is the person among the search specialities ?
      specialitiesSearch.some(function(speciality){
        if (speciality == person.speciality) {
          goodSpeciality = true;
          return true;//break the loop
        }
        return false;
      });

      if (!goodSpeciality) //On passe à la personne suivante
        return;
      if (!All) {
        //Is the person among the search years ?
        yearsSearch.some(function(year){
          if (year == person.year) {
            goodYear = true;
            return true; //break the loop
          }
          return false;
        });
      } else
        goodYear = true;

      if (goodYear) //Tout est respecté
        newList.push(person);
    });
    this.setState({cvListFound: newList});
  },

  render : function () {
    return (

CVThèque

La CVThèque se remplit au fur et à mesure que les étudiants upload leur CV.

        <CriteriaBox  onSearch={this.search}/>
        <CvList
          cvList={this.state.cvListFound}
          onSortByLastName={this.sortByLastName}
          onSortByFirstName={this.sortByFirstName}
          onSortByYear={this.sortByYear}
          onSortBySpeciality={this.sortBySpeciality}
        />

    );
  }
});

ReactDOM.render(<CvBox />, document.getElementById('subBody'));
<commit_msg>oublie style cvthèque<commit_after>var CriteriaBox =  React.createClass({

  getInitialState: function() {
    //return {specialities: []};
    return {AE:false, GB:false, GPE:false, GMM:false, GM:false, GP:false, IR:false, AS:false, A1:false, A2:false, A3:false, A4:false, A5:false, All:false, frCV:false, enCV:false}
  },
/*
  componentDidMount : function() {
    $.ajax({
      url:'/Student/Specialities',
      dataType: 'json',
      cache: false,
      success : function(specialities) {
        this.setState({specialities: specialities});
      }.bind(this),
      error : function(xhr, status, err) {
        console.error('/Student/Specialities', status, err.toString());
      }.bind(this)
    });
  }, */

  handleCheckAE : function(e) {this.setState({AE:e.target.checked});},
  handleCheckGB : function(e) {this.setState({GB:e.target.checked});},
  handleCheckGPE : function(e) {this.setState({GPE:e.target.checked});},
  handleCheckGMM : function(e) {this.setState({GMM:e.target.checked});},
  handleCheckGM : function(e) {this.setState({GM:e.target.checked});},
  handleCheckGP : function(e) {this.setState({GP:e.target.checked});},
  handleCheckIR : function(e) {this.setState({IR:e.target.checked});},
  handleCheckAS : function(e) {this.setState({AS:e.target.checked});},
  handleCheckA1 : function(e) {this.setState({A1:e.target.checked});},
  handleCheckA2 : function(e) {this.setState({A2:e.target.checked});},
  handleCheckA3 : function(e) {this.setState({A3:e.target.checked});},
  handleCheckA4 : function(e) {this.setState({A4:e.target.checked});},
  handleCheckA5 : function(e) {this.setState({A5:e.target.checked});},
  handleCheckAll : function(e) {this.setState({All:e.target.checked});},
  handleCheckFrCV : function(e) {this.setState({frCV:e.target.checked});},
  handleCheckEnCV : function(e) {this.setState({enCV:e.target.checked});},

  onSearchSubmit : function(e) {
    e.preventDefault();
    var specialitiesSearch = [];
    var yearsSearch = [];

    if (this.state.AE)
      specialitiesSearch.push('Automatique, Électronique');
    if (this.state.GB)
      specialitiesSearch.push('Génie Biochimique');
    if (this.state.GPE)
      specialitiesSearch.push('Génie des Procédés');
    if (this.state.GMM)
      specialitiesSearch.push('Génie Mathématique et Modélisation');
    if (this.state.GM)
      specialitiesSearch.push('Génie Mécanique');
    if (this.state.GP)
      specialitiesSearch.push('Génie Physique');
    if (this.state.IR)
      specialitiesSearch.push('Informatique et Réseaux');
    if (this.state.AS)
      specialitiesSearch.push('Aucune spécialité');

    var All = this.state.All;

    if (this.state.A1)
      yearsSearch.push('1');
    if (this.state.A2)
      yearsSearch.push('2');
    if (this.state.A3)
      yearsSearch.push('3');
    if (this.state.A4)
      yearsSearch.push('4');
    if (this.state.A5)
      yearsSearch.push('5');

    var frCV=this.state.frCV;
    var enCV=this.state.enCV;

    console.log("specialitiesSearch : " + specialitiesSearch);
    console.log("yearSearch : " + yearsSearch);
    this.props.onSearch(specialitiesSearch,yearsSearch,All,frCV,enCV);
  },

  render : function() {
    /* var criteriaList = this.state.specialities.map(function(speciality){
      return (

            <input type="checkbox" name={speciality}/> {speciality}

      );
    }); */

    return( //Todo : A automatiser

Critères

        <form onSubmit={this.onSearchSubmit}>

Spécialités :

                <input id="AE" type="checkbox" name='Automatique, Électronique' onClick={this.handleCheckAE}/> Automatique, Électronique
                <input id="GB" type="checkbox" name='Génie Biochimique' onClick={this.handleCheckGB}/> Génie Biochimique

                <input id="GPE" type="checkbox" name='Génie des Procédés' onClick={this.handleCheckGPE}/> Génie des Procédés
                <input id="GMM" type="checkbox" name='Génie Mathématique et Modélisation' onClick={this.handleCheckGMM}/> Génie Mathématique et Modélisation

                <input id="GM" type="checkbox" name='Génie Mécanique' onClick={this.handleCheckGM}/> Génie Mécanique
                <input id="GP" type="checkbox" name='Génie Physique' onClick={this.handleCheckGP}/> Génie Physique

                <input id="IR" type="checkbox" name='Informatique et Réseaux' onClick={this.handleCheckIR}/> Informatique et Réseaux
                <input id="AS" type="checkbox" name='Aucune spécialité' onClick={this.handleCheckAS}/> Aucune spécialité

Années :

                <input id="A1" type="checkbox" name='1' onClick={this.handleCheckA1}/> 1e année
                <input id="A2" type="checkbox" name='2' onClick={this.handleCheckA2}/> 2e année
                <input id="A3" type="checkbox" name='3' onClick={this.handleCheckA3}/> 3e année

                <input id="A4" type="checkbox" name='4' onClick={this.handleCheckA4}/> 4e année
                <input id="A5" type="checkbox" name='5' onClick={this.handleCheckA5}/> 5e année
                <input id="All" type="checkbox" name='toutes' onClick={this.handleCheckAll}/> toutes

Avec CV :

<input id="frCV" type="checkbox" name='withFrCv' onClick={this.handleCheckFrCV}/>français

<input id="enCV" type="checkbox" name='withFrCv' onClick={this.handleCheckEnCV}/>anglais

          <button id="btn_react" type="submit">Rechercher</button>
        </form>

    );
  }
});

//---------------------------------------------------
var CVDownloadForm = React.createClass({
  render : function() {

    var value, id;
    if (this.props.language == 'fr') {
      value="fr";
      id="downloadFormFR";
    } else if (this.props.language == 'en') {
      value="en";
      id="downloadFormEN";
    }

    return (
      <form class="pure-form" id={id} method="post" action="/file/download">
        <input type="hidden" name="dl" value={value}/>
        <input type="hidden" name="cvLogin" value={this.props.cvLogin}/>
        <input type="submit" value="Télécharger"/>
      </form>
    );
  }
});

//---------------------------------------------------

var CvList = React.createClass({

  render : function () {
    var cvListDisplay = this.props.cvList.map(function(cv) {
      var frCV, enCV, personalWebsite, linkedin, viadeo, github;

      if (cv.frCVPath == "")
        frCV = "-";
      else
        frCV = <CVDownloadForm language="fr" cvLogin={cv.login}/>;

      if (cv.enCVPath == "")
        enCV = "-";
      else
        enCV = <CVDownloadForm language="en" cvLogin={cv.login}/>;

      if (cv.personalWebsite == "")
        personalWebsite = "-";
      else {
        var httpPersonalWebsite = "http://" + cv.personalWebsite;
        personalWebsite = {cv.personalWebsite};
      }
      if (cv.linkedin == "")
        linkedin = "-";
      else
        linkedin = Linkedin;

      if (cv.viadeo == "")
        viadeo = "-";
      else
        viadeo = Viadeo;

      if (cv.github == "")
        github = "-";
      else
        github = github;
      return (

          {cv.year}
          {cv.speciality}
          {cv.lastName}
          {cv.firstName}
          {frCV}
          {enCV}
          {personalWebsite}
          {linkedin}
          {viadeo}
          {github}

      );
    });

    return (

Liste des CV

              Année
              Spécialité
              Nom
              Prénom
              CV français
              CV anglais
              Site personnel
              Linkedin
              Viadeo
              Github

            {cvListDisplay}

    );
  }
});

//---------------------------------------------------

var CvBox = React.createClass({

  getInitialState : function() {
    return {cvList : [], cvListFound :[], yearDown:true, specialityDown:true, lastNameDown:true, firstNameDown:true}
  },

  componentDidMount: function() {
    $.ajax({
      url:'/Student/Students',
      dataType: 'json',
      cache: false,
      success : function(list) {
        this.setState({cvList: list});
      }.bind(this),
      error : function(xhr, status, err) {
        console.error('/Student/Students', status, err.toString());
      }.bind(this)
    });
  },

  sortByLastName:function() {
    var newList = this.state.cvListFound;
    if (this.state.lastNameDown)
      newList.sort(function (a, b) {return a.lastName.localeCompare(b.lastName);});
    else
      newList.sort(function (a, b) {return b.lastName.localeCompare(a.lastName);});

    this.setState({cvListFound:newList, lastNameDown:!this.state.lastNameDown});
  },

  sortByFirstName:function() {
    var newList = this.state.cvListFound;
    if (this.state.firstNameDown)
      newList.sort(function (a, b) {return a.firstName.localeCompare(b.firstName);});
    else
      newList.sort(function (a, b) {return b.firstName.localeCompare(a.firstName);});

    this.setState({cvListFound:newList, firstNameDown:!this.state.firstNameDown});
  },

  sortByYear:function() {
    var newList = this.state.cvListFound;
    if (this.state.yearDown)
      newList.sort(function (a, b) {return a -b;});
    else
      newList.sort(function (a, b) {return b -a;});

    this.setState({cvListFound:newList, yearDown:!this.state.yearDown});
  },

  sortBySpeciality:function() {
    var newList = this.state.cvListFound;
    if (this.state.specialityDown)
      newList.sort(function (a, b) {return a.speciality.localeCompare(b.speciality);});
    else
      newList.sort(function (a, b) {return b.speciality.localeCompare(a.speciality);});

    this.setState({cvListFound:newList, specialityDown:!this.state.specialityDown});
  },

  search: function(specialitiesSearch,yearsSearch,All,frCV,enCV) {
    var newList=[];
    this.state.cvList.forEach(function(person){
      var goodSpeciality = false, goodYear = false;

      //Si cvfr demandé et person n'a pas de cvfr, alors person suivante
      if (frCV && person.frCVPath=="")
        return;

      if (enCV && person.enCVPath=="")
        return;

      //Is the person among the search specialities ?
      specialitiesSearch.some(function(speciality){
        if (speciality == person.speciality) {
          goodSpeciality = true;
          return true;//break the loop
        }
        return false;
      });

      if (!goodSpeciality) //On passe à la personne suivante
        return;
      if (!All) {
        //Is the person among the search years ?
        yearsSearch.some(function(year){
          if (year == person.year) {
            goodYear = true;
            return true; //break the loop
          }
          return false;
        });
      } else
        goodYear = true;

      if (goodYear) //Tout est respecté
        newList.push(person);
    });
    this.setState({cvListFound: newList});
  },

  render : function () {
    return (

CVThèque

La CVThèque se remplit au fur et à mesure que les étudiants upload leur CV.

        <CriteriaBox  onSearch={this.search}/>
        <CvList
          cvList={this.state.cvListFound}
          onSortByLastName={this.sortByLastName}
          onSortByFirstName={this.sortByFirstName}
          onSortByYear={this.sortByYear}
          onSortBySpeciality={this.sortBySpeciality}
        />

    );
  }
});

ReactDOM.render(<CvBox />, document.getElementById('subBody'));
<|endoftext|>


<commit_before>(function (window) {
    'use strict';
jQuery(document).ready(function() {

jQuery.getJSON('/octocat.json', function(json) {
    var user = json;
    $('#login').html(user.login);
    $('#email').html(user.email);
    $('#location').html(user.location);
    $('#website').html(user.blog);
    $('#company').html(user.company);
    $('#joined').html(user.created_at);
    $('aside').prepend('');
    $('#followers').html(user.followers + '
 Followers');
    $('#following').html(user.following + '
 Following');
    console.log('mic check 1 2');
   });
});

})(window);<commit_msg>not yet..<commit_after>(function (window) {
    'use strict';
jQuery(document).ready(function() {

jQuery.getJSON('/octocat.json', function(json) {
    var user = json;
    $('#login').html(user.login);
    $('#email').html(user.email);
    $('#location').html(user.location);
    $('#website').html(user.blog);
    $('#company').html(user.company);
    $('#joined').html(user.created_at);
    $('aside').prepend('');
    $('#followers').html(user.followers + '
 Followers');
    $('#following').html(user.following + '
 Following');
    console.log('mic check 1 2');

    var userRepos = user.repos_url;
    console.log(userRepos);
})
});
})(window);<|endoftext|>


<commit_before>'use strict';

const Jovo = require('../../jovo');
/**
 * Class
 * Analytics (alpha)
 */
class Analytics {

    /**
     * Initializes stuff
     */
    constructor() {
        this.services = {};
        this.intentsToSkip = [];
        this.usersToSkip = [];
        this.intentsToTrack = [];
        this.enable();
    }

    /**
     * Adds analytics service to analytics module
     * @param {String} name
     * @param {*} implementation
     */
    addAnalytics(name, implementation) {
        this.services[name] = implementation;
    }

    /**
     * Enables analytics
     */
    enable() {
        this.analyticsEnabled = true;
    }

    /**
     * Disables analytics
     */
    disable() {
        this.analyticsEnabled = false;
    }

    /**
     * Checks if analytics is enabled
     * @return {boolean}
     */
    isEnabled() {
        return Object.keys(this.services).length > 0 && this.analyticsEnabled;
    }

    /**
     * Array of intents where tracking
     * will be skipped
     * @param {Array} intents
     */
    skipIntents(intents) {
        this.intentsToSkip = intents;
    }

    /**
     * Initiates tracking
     * @param {Jovo} app
     */
    track(app) {
        if (this.isEnabled()) {
            for (let i = 0; i < Object.keys(this.services).length; i++) {
                let service = this.services[Object.keys(this.services)[i]];
                if (this.intentsToSkip.length > 0 &&
                    this.intentsToSkip.indexOf(app.getHandlerPath()) !== -1) {
                    continue;
                }
                if (app.getPlatform().getType() === service.platformType ) {
                    service.track(app);
                }
            }
        }
    }
}

/** DEFAULT INTEGRATIONS VOICELABS AND DASHBOT */

/**
 * Implementation of Voicelabs' analytics module for alexa
 */
class VoiceLabsAlexaAnalytics {

    /**
     * Constructor
     * @param {string} token token-app at insights.voicelabs.co
     * @param {boolean} trackSlots true tracks slots too
     * @param {boolean} trackSpeechText true tracks speechtext too
     */
    constructor(token, trackSlots, trackSpeechText) {
        try {
            this.voiceLabsAlexa = require('voicelabs');
            this.voiceLabsAlexa.initialize(token);
            this.trackSlots = trackSlots;
            this.trackSpeechText = trackSpeechText;
            this.platformType = Jovo.PLATFORM_ENUM.ALEXA_SKILL;
        } catch (err) {
           console.log('\nPlease install VoiceLabs: npm install voicelabs\n');
        }
    }

    /**
     * Calls the voicelabs track method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.voiceLabsAlexa.track(
            app.alexaSkill().getSession(),
            app.getHandlerPath(),
            this.trackSlots ? app.alexaSkill().request.getSlots() : null,
            this.trackSpeechText ? app.alexaSkill().getSpeechText() : null
        );
    };
}

/**
 * Implementation of Voicelabs' analytics module for google action
 */
class VoiceLabsGoogleActionAnalytics {

    /**
     * Constructor
     * @param {string} token token-app at insights.voicelabs.co
     */
    constructor(token) {
        try {
            this.voiceInsights = require('voicelabs-assistant-sdk');
            this.voiceInsights.initialize(token);
            this.platformType = Jovo.PLATFORM_ENUM.GOOGLE_ACTION;
        } catch (err) {
            console.log('\nPlease install VoiceLabs: npm install voicelabs-assistant-sdk\n');
        }
    }

    /**
     * Calls the voicelabs track method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        let request = app.googleAction().getRequest().getOriginalRequest() ?
            app.googleAction().getRequest().getOriginalRequest() : null;

        this.voiceInsights.track(
            app.getIntentName(),
            request.data,
            app.googleAction().getResponse().getSpeechText()
        );
    };
}

/**
 * Implementation of dashbot's analytics module for google action
 */
class DashbotGoogleActionAnalytics {

    /**
     * Constructor
     * @param {string} apiKey apiKey
     */
    constructor(apiKey) {
        try {
            this.dashbot = require('dashbot')(apiKey).google;
            this.platformType = Jovo.PLATFORM_ENUM.GOOGLE_ACTION;
        } catch (err) {
            console.log('\nPlease install dashbot: npm install dashbot\n');
        }
    }

    /**
     * Calls the dashbot log method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.dashbot.logIncoming(app.googleAction().getRequest()
            .getRequestObject());
        this.dashbot.logOutgoing(app.googleAction().getRequest()
                .getRequestObject(),
            app.googleAction().getResponse().getResponseObject());
    };
}

/**
 * Implementation of dashbot's analytics module for alexa
 */
class DashbotAlexaAnalytics {

    /**
     * Constructor
     * @param {string} apiKey apiKey
     */
    constructor(apiKey) {
        try {
            this.dashbot = require('dashbot')(apiKey).alexa;
            this.platformType = Jovo.PLATFORM_ENUM.ALEXA_SKILL;
        } catch (err) {
            console.log('\nPlease install dashbot: npm install dashbot\n');
        }
    }

    /**
     * TODO: request object is not correct
     * Calls the dashbot log method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.dashbot.logIncoming(app.alexaSkill()
            .getRequest().getRequestObject());
        this.dashbot.logOutgoing(app.alexaSkill()
                .getRequest().getRequestObject(),
            app.alexaSkill().getResponse().getResponseObject());
    };
}

module.exports.Analytics = Analytics;
module.exports.VoiceLabsAlexaAnalytics = VoiceLabsAlexaAnalytics;
module.exports.VoiceLabsGoogleActionAnalytics = VoiceLabsGoogleActionAnalytics;
module.exports.DashbotAlexaAnalytics = DashbotAlexaAnalytics;
module.exports.DashbotGoogleActionAnalytics = DashbotGoogleActionAnalytics;
<commit_msg>:construction: Added skipUsers to analytics.js<commit_after>'use strict';

const Jovo = require('../../jovo');
/**
 * Class
 * Analytics (alpha)
 */
class Analytics {

    /**
     * Initializes stuff
     */
    constructor() {
        this.services = {};
        this.intentsToSkip = [];
        this.usersToSkip = [];
        this.intentsToTrack = [];
        this.enable();
    }

    /**
     * Adds analytics service to analytics module
     * @param {String} name
     * @param {*} implementation
     */
    addAnalytics(name, implementation) {
        this.services[name] = implementation;
    }

    /**
     * Enables analytics
     */
    enable() {
        this.analyticsEnabled = true;
    }

    /**
     * Disables analytics
     */
    disable() {
        this.analyticsEnabled = false;
    }

    /**
     * Checks if analytics is enabled
     * @return {boolean}
     */
    isEnabled() {
        return Object.keys(this.services).length > 0 && this.analyticsEnabled;
    }

    /**
     * Array of intents where tracking
     * will be skipped
     * @param {Array} intents
     */
    skipIntents(intents) {
        this.intentsToSkip = intents;
    }

    /**
     * Array of users where tracking
     * will be skipped
     * @param {Array} userIds
     */
    skipUsers(userIds) {
        this.usersToSkip = userIds;
    }

    /**
     * Initiates tracking
     * @param {Jovo} app
     */
    track(app) {
        if (this.isEnabled()) {
            for (let i = 0; i < Object.keys(this.services).length; i++) {
                let service = this.services[Object.keys(this.services)[i]];
                if (this.intentsToSkip.length > 0 &&
                    this.intentsToSkip.indexOf(app.getHandlerPath()) !== -1) {
                    continue;
                }
                if (this.usersToSkip.length > 0 &&
                    this.usersToSkip.indexOf(app.getUserId()) !== -1) {
                    continue;
                }
                if (app.getPlatform().getType() === service.platformType ) {
                    service.track(app);
                }
            }
        }
    }
}

/** DEFAULT INTEGRATIONS VOICELABS AND DASHBOT */

/**
 * Implementation of Voicelabs' analytics module for alexa
 */
class VoiceLabsAlexaAnalytics {

    /**
     * Constructor
     * @param {string} token token-app at insights.voicelabs.co
     * @param {boolean} trackSlots true tracks slots too
     * @param {boolean} trackSpeechText true tracks speechtext too
     */
    constructor(token, trackSlots, trackSpeechText) {
        try {
            this.voiceLabsAlexa = require('voicelabs');
            this.voiceLabsAlexa.initialize(token);
            this.trackSlots = trackSlots;
            this.trackSpeechText = trackSpeechText;
            this.platformType = Jovo.PLATFORM_ENUM.ALEXA_SKILL;
        } catch (err) {
           console.log('\nPlease install VoiceLabs: npm install voicelabs\n');
        }
    }

    /**
     * Calls the voicelabs track method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.voiceLabsAlexa.track(
            app.alexaSkill().getSession(),
            app.getHandlerPath(),
            this.trackSlots ? app.alexaSkill().request.getSlots() : null,
            this.trackSpeechText ? app.alexaSkill().getSpeechText() : null
        );
    };
}

/**
 * Implementation of Voicelabs' analytics module for google action
 */
class VoiceLabsGoogleActionAnalytics {

    /**
     * Constructor
     * @param {string} token token-app at insights.voicelabs.co
     */
    constructor(token) {
        try {
            this.voiceInsights = require('voicelabs-assistant-sdk');
            this.voiceInsights.initialize(token);
            this.platformType = Jovo.PLATFORM_ENUM.GOOGLE_ACTION;
        } catch (err) {
            console.log('\nPlease install VoiceLabs: npm install voicelabs-assistant-sdk\n');
        }
    }

    /**
     * Calls the voicelabs track method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        let request = app.googleAction().getRequest().getOriginalRequest() ?
            app.googleAction().getRequest().getOriginalRequest() : null;

        this.voiceInsights.track(
            app.getIntentName(),
            request.data,
            app.googleAction().getResponse().getSpeechText()
        );
    };
}

/**
 * Implementation of dashbot's analytics module for google action
 */
class DashbotGoogleActionAnalytics {

    /**
     * Constructor
     * @param {string} apiKey apiKey
     */
    constructor(apiKey) {
        try {
            this.dashbot = require('dashbot')(apiKey).google;
            this.platformType = Jovo.PLATFORM_ENUM.GOOGLE_ACTION;
        } catch (err) {
            console.log('\nPlease install dashbot: npm install dashbot\n');
        }
    }

    /**
     * Calls the dashbot log method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.dashbot.logIncoming(app.googleAction().getRequest()
            .getRequestObject());
        this.dashbot.logOutgoing(app.googleAction().getRequest()
                .getRequestObject(),
            app.googleAction().getResponse().getResponseObject());
    };
}

/**
 * Implementation of dashbot's analytics module for alexa
 */
class DashbotAlexaAnalytics {

    /**
     * Constructor
     * @param {string} apiKey apiKey
     */
    constructor(apiKey) {
        try {
            this.dashbot = require('dashbot')(apiKey).alexa;
            this.platformType = Jovo.PLATFORM_ENUM.ALEXA_SKILL;
        } catch (err) {
            console.log('\nPlease install dashbot: npm install dashbot\n');
        }
    }

    /**
     * TODO: request object is not correct
     * Calls the dashbot log method
     * @param {Jovo} app jovo app object
     */
    track(app) {
        this.dashbot.logIncoming(app.alexaSkill()
            .getRequest().getRequestObject());
        this.dashbot.logOutgoing(app.alexaSkill()
                .getRequest().getRequestObject(),
            app.alexaSkill().getResponse().getResponseObject());
    };
}

module.exports.Analytics = Analytics;
module.exports.VoiceLabsAlexaAnalytics = VoiceLabsAlexaAnalytics;
module.exports.VoiceLabsGoogleActionAnalytics = VoiceLabsGoogleActionAnalytics;
module.exports.DashbotAlexaAnalytics = DashbotAlexaAnalytics;
module.exports.DashbotGoogleActionAnalytics = DashbotGoogleActionAnalytics;
<|endoftext|>


<commit_before>
darjeelingApp.filter('removeSpam', function () {
    return function (string) {
        var thingsToRemove = [];
        var doc = document.implementation.createHTMLDocument("");
        doc.documentElement.innerHTML = string;

        var qcRss = doc.getElementsByTagName("map");
        for (var i = 0; i < qcRss.length; i++) {
            var node = qcRss[i];
            if (node.name.startsWith("admap")) {
                thingsToRemove = thingsToRemove.concat(node.parentNode);
                if (node.parentNode.nextSibling.tagName == "TABLE") {
                    thingsToRemove = thingsToRemove.concat(node.parentNode.nextSibling);
                }
            }
        }

        thingsToRemove = thingsToRemove.concat([].slice.call(doc.getElementsByClassName('feedflare')));

        for (var i = 0; i < thingsToRemove.length; i++) {
            thingsToRemove[i].parentNode.removeChild(thingsToRemove[i]);
        }

        return doc.documentElement.innerHTML;
    };
});

darjeelingApp.filter('trust', function ($sce) {
    return function (raw) {
        return $sce.trustAsHtml(raw);
    };
});

darjeelingApp.filter('prettyDate', function () {
    var msPerMinute = 1000 * 60;
    var msPerHour = 1000 * 60 * 60;
    var msPerDay = 1000 * 60 * 60 * 24;

    function pluralize(qty, label) {
        return qty + label.replace("(s)", qty > 1 ? "s" : "");
    }

    return function (rawDate) {
        var date = new Date(rawDate);
        var dateDiff = new Date() - date;

        if (dateDiff / msPerMinute < 60) {
            return pluralize(Math.floor(dateDiff / msPerMinute), " minute(s) ago");
        } else if (dateDiff / msPerHour < 24) {
            return pluralize(Math.floor(dateDiff / msPerHour), " hour(s) ago");
        } else if (dateDiff / msPerDay < 4) {
            return pluralize(Math.floor(dateDiff / msPerDay), " day(s) ago");
        }

        return date.toDateString();
    };
});

darjeelingApp.filter('fullDate', function () {
    return function (rawDate) {
        return new Date(rawDate).toString();
    }
});
<commit_msg>Fix #10: Handle future dates<commit_after>
darjeelingApp.filter('removeSpam', function () {
    return function (string) {
        var thingsToRemove = [];
        var doc = document.implementation.createHTMLDocument("");
        doc.documentElement.innerHTML = string;

        var qcRss = doc.getElementsByTagName("map");
        for (var i = 0; i < qcRss.length; i++) {
            var node = qcRss[i];
            if (node.name.startsWith("admap")) {
                thingsToRemove = thingsToRemove.concat(node.parentNode);
                if (node.parentNode.nextSibling.tagName == "TABLE") {
                    thingsToRemove = thingsToRemove.concat(node.parentNode.nextSibling);
                }
            }
        }

        thingsToRemove = thingsToRemove.concat([].slice.call(doc.getElementsByClassName('feedflare')));

        for (var i = 0; i < thingsToRemove.length; i++) {
            thingsToRemove[i].parentNode.removeChild(thingsToRemove[i]);
        }

        return doc.documentElement.innerHTML;
    };
});

darjeelingApp.filter('trust', function ($sce) {
    return function (raw) {
        return $sce.trustAsHtml(raw);
    };
});

darjeelingApp.filter('prettyDate', function () {
    var msPerMinute = 1000 * 60;
    var msPerHour = 1000 * 60 * 60;
    var msPerDay = 1000 * 60 * 60 * 24;

    function format(qty, label) {
    	var unit = label.replace("(s)", Math.abs(qty) > 1 ? "s" : "");

        return qty<0 ? "in " + Math.abs(qty) + unit : qty + unit + " ago";
    }

    return function (rawDate) {
        var date = new Date(rawDate);
        var dateDiff = new Date() - date;

        if (Math.abs(dateDiff / msPerMinute) < 60) {
            return format(Math.floor(dateDiff / msPerMinute), " minute(s)");
        } else if (Math.abs(dateDiff / msPerHour) < 24) {
            return format(Math.floor(dateDiff / msPerHour), " hour(s)");
        } else if (Math.abs(dateDiff / msPerDay) < 4) {
            return format(Math.floor(dateDiff / msPerDay), " day(s)");
        }

        return date.toDateString();
    };
});

darjeelingApp.filter('fullDate', function () {
    return function (rawDate) {
        return new Date(rawDate).toString();
    }
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var env = process.env.NODE_ENV || 'development';
  if (env === 'development') {
    require('dotenv').load();
  }

   var database = require('./server/config/database')[env];
    var mongoose = require('mongoose'),
    path = require('path'),
    express = require('express'),
    app = require('./server/config/express'),
    initDb =  require('./seeds/user'),

    port = process.env.PORT || 5555;

    mongoose.Promise = global.Promise;
  // connection to the database;
    mongoose.connect(database.url, function(err) {
    if (err) {
    console.log('Error connecting to the database');
    console.log(err);
  } else {
    console.log('Connected to the database...');
    if (env === 'test' || process.argv[2] === 'initDb' ) {
      mongoose.connection.db.dropDatabase(function(err) {
        if (err) {
          return err;
        } else {
          console.log('Dropped database...');
          console.log('Seeding database...');
          initDb();
        }
      });
    }
  }
 });
  // view engine setup
  app.set('views', path.join(__dirname, 'app/views'));
  app.set('view engine', 'jade');

  // error handlers
  // development error handler
  // will print stacktrace
  if (env === 'development') {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500).send(err.message);
      next();
    });
  }
  app.use(express.static(path.join(__dirname, './public')));
  app.route('/*').get(function (req, res) {
   return res.sendFile(path.join(__dirname, './public/index.html'));
 });

  var server = app.listen(port, function() {
    console.log('Express server listening on %d, in %s' +
      ' mode', server.address().port, app.get('env'));
  });

  // expose the  server to app
  module.exports = app;
})();
<commit_msg>Prepare prod environment to be seeded<commit_after>(function() {
  'use strict';

  var env = process.env.NODE_ENV || 'development';
  if (env === 'development') {
    require('dotenv').load();
  }

   var database = require('./server/config/database')[env];
    var mongoose = require('mongoose'),
    path = require('path'),
    express = require('express'),
    app = require('./server/config/express'),
    initDb =  require('./seeds/user'),

    port = process.env.PORT || 5555;

    mongoose.Promise = global.Promise;
  // connection to the database;
    mongoose.connect(database.url, function(err) {
    if (err) {
    console.log('Error connecting to the database');
    console.log(err);
  } else {
    console.log('Connected to the database...');
    if (env === 'production' || process.argv[2] === 'initDb' ) {
      mongoose.connection.db.dropDatabase(function(err) {
        if (err) {
          return err;
        } else {
          console.log('Dropped database...');
          console.log('Seeding database...');
          initDb();
        }
      });
    }
  }
 });
  // view engine setup
  app.set('views', path.join(__dirname, 'app/views'));
  app.set('view engine', 'jade');

  // error handlers
  // development error handler
  // will print stacktrace
  if (env === 'development') {
    app.use(function(err, req, res, next) {
      res.status(err.status || 500).send(err.message);
      next();
    });
  }
  app.use(express.static(path.join(__dirname, './public')));
  app.route('/*').get(function (req, res) {
   return res.sendFile(path.join(__dirname, './public/index.html'));
 });

  var server = app.listen(port, function() {
    console.log('Express server listening on %d, in %s' +
      ' mode', server.address().port, app.get('env'));
  });

  // expose the  server to app
  module.exports = app;
})();
<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', {
    preload: preload, create: create, update: update });

// Declare the sprites globally so we can modify them later
var background;
var plots;
var flowers;
var weeds;
var weapons;

// Declare the text fields
var flowerText;
var weedText;

// Declare our buttons
var acid_button;
var fireball_button;
var sawblade_button;
var uav_button;

// Declare our score trackers
var flowerCount = 0;
var weedCount = 0;

// Set our default weapon
var currentWeapon = 0;

// Declare the game timers
var time;
var weaponLastFired;

function preload() {
    // Load the background image and game sprites
    // TODO: Combine sprites into an atlas
    game.load.image('background', 'assets/background.png');
    game.load.image('acid_icon', 'assets/acid_icon.png');
    game.load.image('fireball_icon', 'assets/fireball_icon.png');
    game.load.image('sawblade_icon', 'assets/sawblade_icon.png');
    game.load.image('uav_icon', 'assets/uav_icon.png');
    game.load.image('plot', 'assets/plot.png');
    game.load.image('flower_1', 'assets/flower_1.png');
    game.load.image('flower_2', 'assets/flower_2.png');
    game.load.image('weed_1', 'assets/weed_1.png');
    game.load.image('acid_weapon', 'assets/acid_weapon.png');
    game.load.image('fireball_weapon', 'assets/fireball_weapon.png');
    game.load.image('sawblade_weapon', 'assets/sawblade_weapon.png');
    game.load.image('uav_weapon', 'assets/uav_weapon.png');
}

function create() {
    // Enable the physics engine
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Apply the background sprite and set the initial background color
    background = game.add.sprite(0,0, 'background');
    background.tint = 0x0EE68;

    // Add the weapon selection buttons
    acid_button = game.add.sprite(25, 479, 'acid_icon');
    fireball_button = game.add.sprite(146, 479, 'fireball_icon');
    sawblade_button = game.add.sprite(558, 479, 'sawblade_icon');
    uav_button = game.add.sprite(679, 479, 'uav_icon');

    // Add and configure the score text fields
    flowerText = game.add.text(5, 0, 'Flowers: 0');
    weedText = game.add.text(5, 25, 'Weeds: 0');

    // Generate the flower/weed plots
    // TODO: Prevent overlapping plots during generation
    plots = game.add.group();
    for (var i = 0; i < 10; i++) {
        // Determine valid X/Y coordinates in the game area
        var x = Math.floor(Math.random() * (800 - (i * 8)) + 1);
        var y = Math.floor(Math.random() * (600 - (i * 6)) + 1);

        // Prevent sprite from extending off of the right or bottom
        if (x > 736) {
            x = 736;
        }
        if (y > 400) {
            // Leave room for bottom text and interaction area
            y = 400;
        } else if (y < 110) {
            // Leave enough room for flower to prevent clipping
            y = 110;
        }

        plot = plots.create(x, y, 'plot');
        plot.occupied = false;
    }

    // Define the flowers group and add physics properties
    flowers = game.add.group();
    flowers.enableBody = true;
    flowers.physicsBodyType = Phaser.Physics.ARCADE;
    // Spawn 10 random flowers outside the viewport
    for (var i = 0; i < 10; i++) {
        var whichFlower = Math.floor(Math.random() * 2 + 1);
        flower = flowers.create(-100, -100, 'flower_' + whichFlower);
    }

    // Define the weeds group and add physics properties
    weeds = game.add.group();
    weeds.enableBody = true;
    weeds.physicsBodyType = Phaser.Physics.ARCADE;
    // Spawn 10 random weeds outside the viewport
    for (var i = 0; i < 10; i++) {
        var whichWeed = Math.floor(Math.random() * 1 + 1);
        weed = weeds.create(-100, -100, 'weed_' + whichWeed);
    }

    // Define the weaopns group and add physics properties
    weapons = game.add.group();
    weapons.enableBody = true;
    weapons.physicsBodyType = Phaser.Physics.ARCADE;
    weapons.create(-100, -100, 'acid_weapon');
    weapons.create(-100, -100, 'fireball_weapon');
    weapons.create(-100, -100, 'sawblade_weapon');
    weapons.create(-100, -100, 'uav_weapon');

    // Set up inital clock for update();
    time = game.time.now;
    // Set up initial clock for weapon firing
    weaponLastFired = game.time.now;
}

function update() {
    // Every two seconds, spawn a flower or weed
    if (game.time.now > time + 2000) {
        // Modify a random plot
        // TODO: Refactor to generate an index between 0 and 9
        var currentPlot = Math.floor(Math.random() * 10 + 1);
        if (currentPlot > 9) {
            currentPlot = 0;
        }

        // Save the plot's position and modify y for flower/weed placement
        var x = plots.children[currentPlot].x;
        var y = plots.children[currentPlot].y - 110;

        // If the plot isn't occupied, add a flower or weed
        if (plots.children[currentPlot].occupied === false) {
            var determineOccupant = Math.floor(Math.random() * 2);
            if (determineOccupant === 0) {
                // Spawn a flower
                flowers.children[currentPlot].x = x;
                flowers.children[currentPlot].y = y;

                flowerCount++;
                flowerText.text = 'Flowers: ' + flowerCount;
            } else {
                // Spawn a weed
                weeds.children[currentPlot].x = x;
                weeds.children[currentPlot].y = y;

                weedCount++;
                weedText.text = 'Weeds: ' + weedCount;
            }

            plots.children[currentPlot].occupied = true;
        }

        time = game.time.now;
    }

    // Tint the background based on how many flowers vs. weeds
    var ratioFlowersToWeeds = flowerCount / weedCount;
    if (ratioFlowersToWeeds < 1.0) {
        background.tint = 0x869E82;
    } else if (ratioFlowersToWeeds < 0.43) {
        background.tint = 0xA6AB79;
    } else if (ratioFlowersToWeeds < 0.12) {
        background.tint = 0x917B56;
    } else {
        background.tint = 0x0EE68;
    }

    // Detect input
    if (game.input.activePointer.isDown) {
        // Get tap/click position
        var xInput = game.input.activePointer.x;
        var yInput = game.input.activePointer.y;

        // If y < 470, shoot the current weapon
        if (yInput < 470 && game.time.now > (weaponLastFired + 1000)) {
            // Shoot selected weapon in direction of tap/click
            var weapon = weapons.children[currentWeapon];
            weapon.x = 400;
            weapon.y = 500;
            game.physics.arcade.moveToPointer(weapon, 300);

            weaponLastFired = game.time.now;
        } else if (yInput > 470) {
            // Detect weapon selection
            if (xInput > 25 && xInput < 121) {
                currentWeapon = 0;
                resetButtons();
                acid_button.tint = 0xAABBCC;
            } else if (xInput > 146 && xInput < 242) {
                currentWeapon = 1;
                resetButtons();
                fireball_button.tint = 0xAABBCC;
            } else if (xInput > 558 && xInput < 654) {
                currentWeapon = 2;
                resetButtons();
                sawblade_button.tint = 0xAABBCC;
            } else if (xInput > 679 && xInput < 775) {
                currentWeapon = 3;
                resetButtons();
                uav_button.tint = 0xAABBCC;
            }
        }
    }
}

function resetButtons() {
    acid_button.tint = 0xFFFFFF;
    fireball_button.tint = 0xFFFFFF;
    sawblade_button.tint = 0xFFFFFF;
    uav_button.tint = 0xFFFFFF;
}<commit_msg>Slightly increase projectile speed<commit_after>var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', {
    preload: preload, create: create, update: update });

// Declare the sprites globally so we can modify them later
var background;
var plots;
var flowers;
var weeds;
var weapons;

// Declare the text fields
var flowerText;
var weedText;

// Declare our buttons
var acid_button;
var fireball_button;
var sawblade_button;
var uav_button;

// Declare our score trackers
var flowerCount = 0;
var weedCount = 0;

// Set our default weapon
var currentWeapon = 0;

// Declare the game timers
var time;
var weaponLastFired;

function preload() {
    // Load the background image and game sprites
    // TODO: Combine sprites into an atlas
    game.load.image('background', 'assets/background.png');
    game.load.image('acid_icon', 'assets/acid_icon.png');
    game.load.image('fireball_icon', 'assets/fireball_icon.png');
    game.load.image('sawblade_icon', 'assets/sawblade_icon.png');
    game.load.image('uav_icon', 'assets/uav_icon.png');
    game.load.image('plot', 'assets/plot.png');
    game.load.image('flower_1', 'assets/flower_1.png');
    game.load.image('flower_2', 'assets/flower_2.png');
    game.load.image('weed_1', 'assets/weed_1.png');
    game.load.image('acid_weapon', 'assets/acid_weapon.png');
    game.load.image('fireball_weapon', 'assets/fireball_weapon.png');
    game.load.image('sawblade_weapon', 'assets/sawblade_weapon.png');
    game.load.image('uav_weapon', 'assets/uav_weapon.png');
}

function create() {
    // Enable the physics engine
    game.physics.startSystem(Phaser.Physics.ARCADE);

    // Apply the background sprite and set the initial background color
    background = game.add.sprite(0,0, 'background');
    background.tint = 0x0EE68;

    // Add the weapon selection buttons
    acid_button = game.add.sprite(25, 479, 'acid_icon');
    fireball_button = game.add.sprite(146, 479, 'fireball_icon');
    sawblade_button = game.add.sprite(558, 479, 'sawblade_icon');
    uav_button = game.add.sprite(679, 479, 'uav_icon');

    // Add and configure the score text fields
    flowerText = game.add.text(5, 0, 'Flowers: 0');
    weedText = game.add.text(5, 25, 'Weeds: 0');

    // Generate the flower/weed plots
    // TODO: Prevent overlapping plots during generation
    plots = game.add.group();
    for (var i = 0; i < 10; i++) {
        // Determine valid X/Y coordinates in the game area
        var x = Math.floor(Math.random() * (800 - (i * 8)) + 1);
        var y = Math.floor(Math.random() * (600 - (i * 6)) + 1);

        // Prevent sprite from extending off of the right or bottom
        if (x > 736) {
            x = 736;
        }
        if (y > 400) {
            // Leave room for bottom text and interaction area
            y = 400;
        } else if (y < 110) {
            // Leave enough room for flower to prevent clipping
            y = 110;
        }

        plot = plots.create(x, y, 'plot');
        plot.occupied = false;
    }

    // Define the flowers group and add physics properties
    flowers = game.add.group();
    flowers.enableBody = true;
    flowers.physicsBodyType = Phaser.Physics.ARCADE;
    // Spawn 10 random flowers outside the viewport
    for (var i = 0; i < 10; i++) {
        var whichFlower = Math.floor(Math.random() * 2 + 1);
        flower = flowers.create(-100, -100, 'flower_' + whichFlower);
    }

    // Define the weeds group and add physics properties
    weeds = game.add.group();
    weeds.enableBody = true;
    weeds.physicsBodyType = Phaser.Physics.ARCADE;
    // Spawn 10 random weeds outside the viewport
    for (var i = 0; i < 10; i++) {
        var whichWeed = Math.floor(Math.random() * 1 + 1);
        weed = weeds.create(-100, -100, 'weed_' + whichWeed);
    }

    // Define the weaopns group and add physics properties
    weapons = game.add.group();
    weapons.enableBody = true;
    weapons.physicsBodyType = Phaser.Physics.ARCADE;
    weapons.create(-100, -100, 'acid_weapon');
    weapons.create(-100, -100, 'fireball_weapon');
    weapons.create(-100, -100, 'sawblade_weapon');
    weapons.create(-100, -100, 'uav_weapon');

    // Set up inital clock for update();
    time = game.time.now;
    // Set up initial clock for weapon firing
    weaponLastFired = game.time.now;

    // Tint acid_button since it's our default weapon
    acid_button.tint = 0xAABBCC;
}

function update() {
    // Every two seconds, spawn a flower or weed
    if (game.time.now > time + 2000) {
        // Modify a random plot
        // TODO: Refactor to generate an index between 0 and 9
        var currentPlot = Math.floor(Math.random() * 10 + 1);
        if (currentPlot > 9) {
            currentPlot = 0;
        }

        // Save the plot's position and modify y for flower/weed placement
        var x = plots.children[currentPlot].x;
        var y = plots.children[currentPlot].y - 110;

        // If the plot isn't occupied, add a flower or weed
        if (plots.children[currentPlot].occupied === false) {
            var determineOccupant = Math.floor(Math.random() * 2);
            if (determineOccupant === 0) {
                // Spawn a flower
                flowers.children[currentPlot].x = x;
                flowers.children[currentPlot].y = y;

                flowerCount++;
                flowerText.text = 'Flowers: ' + flowerCount;
            } else {
                // Spawn a weed
                weeds.children[currentPlot].x = x;
                weeds.children[currentPlot].y = y;

                weedCount++;
                weedText.text = 'Weeds: ' + weedCount;
            }

            plots.children[currentPlot].occupied = true;
        }

        time = game.time.now;
    }

    // Tint the background based on how many flowers vs. weeds
    var ratioFlowersToWeeds = flowerCount / weedCount;
    if (ratioFlowersToWeeds < 1.0) {
        background.tint = 0x869E82;
    } else if (ratioFlowersToWeeds < 0.43) {
        background.tint = 0xA6AB79;
    } else if (ratioFlowersToWeeds < 0.12) {
        background.tint = 0x917B56;
    } else {
        background.tint = 0x0EE68;
    }

    // Detect input
    if (game.input.activePointer.isDown) {
        // Get tap/click position
        var xInput = game.input.activePointer.x;
        var yInput = game.input.activePointer.y;

        // If y < 470, shoot the current weapon
        if (yInput < 470 && game.time.now > (weaponLastFired + 1000)) {
            // Shoot selected weapon in direction of tap/click
            var weapon = weapons.children[currentWeapon];
            weapon.x = 400;
            weapon.y = 500;
            game.physics.arcade.moveToPointer(weapon, 500);

            weaponLastFired = game.time.now;
        } else if (yInput > 470) {
            // Detect weapon selection
            if (xInput > 25 && xInput < 121) {
                currentWeapon = 0;
                resetButtons();
                acid_button.tint = 0xAABBCC;
            } else if (xInput > 146 && xInput < 242) {
                currentWeapon = 1;
                resetButtons();
                fireball_button.tint = 0xAABBCC;
            } else if (xInput > 558 && xInput < 654) {
                currentWeapon = 2;
                resetButtons();
                sawblade_button.tint = 0xAABBCC;
            } else if (xInput > 679 && xInput < 775) {
                currentWeapon = 3;
                resetButtons();
                uav_button.tint = 0xAABBCC;
            }
        }
    }
}

function resetButtons() {
    acid_button.tint = 0xFFFFFF;
    fireball_button.tint = 0xFFFFFF;
    sawblade_button.tint = 0xFFFFFF;
    uav_button.tint = 0xFFFFFF;
}<|endoftext|>


<commit_before>var hasOwnProperty = Object.prototype.hasOwnProperty
var slice = Array.prototype.slice

function xtend () {
  var i, l, key, source
  var tar = {}
  for (i = 0, l = arguments.length; i < l; i++) {
    source = arguments[i]
    for (key in source) {
      if (hasOwnProperty.call(source, key)) {
        tar[key] = source[key]
      }
    }
  }
  return tar
}
function isFunction (val) {
  return val && typeof val === 'function'
}
function isGenerator (val) {
  return val && isFunction(val.next) && isFunction(val.throw)
}
function isGeneratorFunction (val) {
  if (!val || !val.constructor) return false
  if (val.constructor.name === 'GeneratorFunction' || val.constructor.displayName === 'GeneratorFunction') return true
  return isGenerator(val.constructor.prototype)
}
function isPromise (val) {
  return val && isFunction(val.then)
}
function noop () {}

/**
 * yieldable resolver
 *
 * @param {*} val - value to resolve
 * @param {function} cb - callback function
 * @returns {boolean} denote yieldable
 */
function yieldable (val, cb, opts) {
  if (isPromise(val)) {
    // Promise
    val.then(function (value) {
      cb(null, value)
    }, function (err) {
      cb(err || new Error())
    })
    return true
  } else if (isGeneratorFunction(val) || isGenerator(val)) {
    // Generator
    _raco.call(this, val, null, cb, opts)
    return true
  } else if (isFunction(val)) {
    // Thunk
    val(cb)
    return true
  } else {
    // Not yieldable
    return false
  }
}

/**
 * internal raco resolver
 *
 * @param {function} genFn - generator function
 * @param {array} args - arguments in real array form
 * @returns {promise} if no callback provided
 */
function _raco (iter, args, callback, opts) {
  var self = this
  var trycatch = true
  var ticking = false

  /**
   * internal callback stepper
   *
   * @param {object} err - callback error object
   * @param {...*} val - callback value(s)
   */
  function step (err, val) {
    if (iter) {
      // generator step
      var state
      if (trycatch) {
        try {
          state = err ? iter.throw(err) : iter.next(val)
        } catch (err) {
          // catch err, break iteration
          iter = null
          return step(err)
        }
      } else {
        state = err ? iter.throw(err) : iter.next(val)
      }
      if (state && state.done) iter = null
      // resolve yieldable
      var isYieldable = yieldable.call(self, state.value, step, opts)
      if (!isYieldable && opts.yieldable) {
        isYieldable = opts.yieldable.call(self, state.value, step)
      }
      // next if generator returned non-yieldable
      if (!isYieldable && !iter) next(null, state.value)
    } else {
      if (callback) {
        callback.apply(self, arguments)
        callback = null
      }
    }
  }

  /**
   * next, callback stepper with nextTick
   *
   * @param {object} err - callback error object
   * @param {...*} val - callback value(s)
   */
  function next () {
    var args = slice.call(arguments)
    if (!ticking) {
      ticking = true
      process.nextTick(function () {
        ticking = false
        step.apply(self, args)
      })
    } else if (iter) {
      // error on multiple callbacks wthin one iteration
      iter = null
      step(new Error('Multiple callbacks within one iteration'))
    }
  }

  // prepend or append next arg
  if (args) opts.prepend ? args.unshift(next) : args.push(next)
  else args = [next]

  if (!isGenerator(iter)) iter = iter.apply(self, args)

  if (callback) {
    // callback mode
    step()
  } else if (opts.Promise) {
    // return promise if callback not exists
    return new opts.Promise(function (resolve, reject) {
      callback = function (err, val) {
        if (err) reject(err)
        else resolve(val)
      }
      step()
    })
  } else {
    // callback and promise not exists,
    // no try catch wrap
    trycatch = false
    callback = noop
    step()
  }
}

module.exports = (function factory (_opts) {
  _opts = xtend({
    Promise: Promise,
    prepend: false,
    yieldable: null
  }, _opts)
  /**
   * raco resolver
   * returns factory if no arguments
   *
   * @param {function} genFn - generator function or factory options
   * @param {object} [opts] - options object
   * @returns {promise} if no callback provided
   */
  function raco (genFn, opts) {
    if (!isGeneratorFunction(genFn)) {
      if (isFunction(genFn)) throw new Error('Generator function required')
      else if (!isGenerator(genFn)) return factory(genFn)
    }
    opts = xtend(_opts, opts)
    opts.Promise = null
    return _raco.call(this, genFn, null, null, opts)
  }

  /**
   * wraps a generator function into regular function that
   * optionally accepts callback or returns a promise.
   *
   * @param {function} genFn - generator function
   * @param {object} [opts] - options object
   * @returns {function} regular function
   */
  raco.wrap = function (genFn, opts) {
    if (!isGeneratorFunction(genFn)) throw new Error('Generator function required')
    opts = xtend(_opts, opts)
    return function () {
      var args = slice.call(arguments)
      var cb = args.length && isFunction(args[args.length - 1]) ? args.pop() : null
      return _raco.call(this, genFn, args, cb, opts)
    }
  }

  /**
   * wraps generator function properties of object
   *
   * @param {object} obj - object to raco.wrap
   * @param {object} [opts] - options object
   * @returns {object} original object
   */
  raco.wrapAll = function (obj, opts) {
    var props = Object.getOwnPropertyNames(obj)
    for (var key of props) {
      if (isGeneratorFunction(obj[key])) {
        obj[key] = raco.wrap(obj[key], opts)
      }
    }
    return obj
  }

  return raco
})()
<commit_msg>use strict<commit_after>'use strict'
var hasOwnProperty = Object.prototype.hasOwnProperty
var slice = Array.prototype.slice

function xtend () {
  var i, l, key, source
  var tar = {}
  for (i = 0, l = arguments.length; i < l; i++) {
    source = arguments[i]
    for (key in source) {
      if (hasOwnProperty.call(source, key)) {
        tar[key] = source[key]
      }
    }
  }
  return tar
}
function isFunction (val) {
  return val && typeof val === 'function'
}
function isGenerator (val) {
  return val && isFunction(val.next) && isFunction(val.throw)
}
function isGeneratorFunction (val) {
  if (!val || !val.constructor) return false
  if (val.constructor.name === 'GeneratorFunction' || val.constructor.displayName === 'GeneratorFunction') return true
  return isGenerator(val.constructor.prototype)
}
function isPromise (val) {
  return val && isFunction(val.then)
}
function noop () {}

/**
 * yieldable resolver
 *
 * @param {*} val - value to resolve
 * @param {function} cb - callback function
 * @returns {boolean} denote yieldable
 */
function yieldable (val, cb, opts) {
  if (isPromise(val)) {
    // Promise
    val.then(function (value) {
      cb(null, value)
    }, function (err) {
      cb(err || new Error())
    })
    return true
  } else if (isGeneratorFunction(val) || isGenerator(val)) {
    // Generator
    _raco.call(this, val, null, cb, opts)
    return true
  } else if (isFunction(val)) {
    // Thunk
    val(cb)
    return true
  } else {
    // Not yieldable
    return false
  }
}

/**
 * internal raco resolver
 *
 * @param {function} genFn - generator function
 * @param {array} args - arguments in real array form
 * @returns {promise} if no callback provided
 */
function _raco (iter, args, callback, opts) {
  var self = this
  var trycatch = true
  var ticking = false

  /**
   * internal callback stepper
   *
   * @param {object} err - callback error object
   * @param {...*} val - callback value(s)
   */
  function step (err, val) {
    if (iter) {
      // generator step
      var state
      if (trycatch) {
        try {
          state = err ? iter.throw(err) : iter.next(val)
        } catch (err) {
          // catch err, break iteration
          iter = null
          return step(err)
        }
      } else {
        state = err ? iter.throw(err) : iter.next(val)
      }
      if (state && state.done) iter = null
      // resolve yieldable
      var isYieldable = yieldable.call(self, state.value, step, opts)
      if (!isYieldable && opts.yieldable) {
        isYieldable = opts.yieldable.call(self, state.value, step)
      }
      // next if generator returned non-yieldable
      if (!isYieldable && !iter) next(null, state.value)
    } else {
      if (callback) {
        callback.apply(self, arguments)
        callback = null
      }
    }
  }

  /**
   * next, callback stepper with nextTick
   *
   * @param {object} err - callback error object
   * @param {...*} val - callback value(s)
   */
  function next () {
    var args = slice.call(arguments)
    if (!ticking) {
      ticking = true
      process.nextTick(function () {
        ticking = false
        step.apply(self, args)
      })
    } else if (iter) {
      // error on multiple callbacks wthin one iteration
      iter = null
      step(new Error('Multiple callbacks within one iteration'))
    }
  }

  // prepend or append next arg
  if (args) opts.prepend ? args.unshift(next) : args.push(next)
  else args = [next]

  if (!isGenerator(iter)) iter = iter.apply(self, args)

  if (callback) {
    // callback mode
    step()
  } else if (opts.Promise) {
    // return promise if callback not exists
    return new opts.Promise(function (resolve, reject) {
      callback = function (err, val) {
        if (err) reject(err)
        else resolve(val)
      }
      step()
    })
  } else {
    // callback and promise not exists,
    // no try catch wrap
    trycatch = false
    callback = noop
    step()
  }
}

module.exports = (function factory (_opts) {
  _opts = xtend({
    Promise: Promise,
    prepend: false,
    yieldable: null
  }, _opts)
  /**
   * raco resolver
   * returns factory if no arguments
   *
   * @param {function} genFn - generator function or factory options
   * @param {object} [opts] - options object
   * @returns {promise} if no callback provided
   */
  function raco (genFn, opts) {
    if (!isGeneratorFunction(genFn)) {
      if (isFunction(genFn)) throw new Error('Generator function required')
      else if (!isGenerator(genFn)) return factory(genFn)
    }
    opts = xtend(_opts, opts)
    opts.Promise = null
    return _raco.call(this, genFn, null, null, opts)
  }

  /**
   * wraps a generator function into regular function that
   * optionally accepts callback or returns a promise.
   *
   * @param {function} genFn - generator function
   * @param {object} [opts] - options object
   * @returns {function} regular function
   */
  raco.wrap = function (genFn, opts) {
    if (!isGeneratorFunction(genFn)) throw new Error('Generator function required')
    opts = xtend(_opts, opts)
    return function () {
      var args = slice.call(arguments)
      var cb = args.length && isFunction(args[args.length - 1]) ? args.pop() : null
      return _raco.call(this, genFn, args, cb, opts)
    }
  }

  /**
   * wraps generator function properties of object
   *
   * @param {object} obj - object to raco.wrap
   * @param {object} [opts] - options object
   * @returns {object} original object
   */
  raco.wrapAll = function (obj, opts) {
    var props = Object.getOwnPropertyNames(obj)
    for (var key of props) {
      if (isGeneratorFunction(obj[key])) {
        obj[key] = raco.wrap(obj[key], opts)
      }
    }
    return obj
  }

  return raco
})()
<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(player, apple);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50);

        randY = Math.floor(Math.random()*(800-50+1)+50);
        randX = Math.floor(Math.random()*(300-50+1)+50);

        if ( apple.alive == true){
            if ( game.physics.arcade.collide(apple, player) == true ){
                score = score + 1;
                apple.kill();
                console.log(score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                score = score - 1;
                apple.kill();
                console.log(score);
            }
        }
        else{
            apple = game.add.sprite(randX, randY, 'apple');
            game.physics.arcade.enable(apple);
            game.physics.arcade.enableBody(apple);
            apple.body.collideWorldBounds = true;
            game.physics.arcade.collide(player, apple);
            game.physics.arcade.collide(ocean, apple);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Gen on apple get()<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        apple = game.add.sprite(game.world.width / 2, game.world.height / 2, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        game.physics.arcade.enable(apple);
        game.physics.arcade.enableBody(apple);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        apple.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);
        game.physics.arcade.collide(player, apple);
        game.physics.arcade.collide(ocean, apple);
        game.physics.arcade.collide(horse, ocean);
        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, apple, 50, 50, 50);

        if ( apple.alive == true){
            if ( game.physics.arcade.collide(apple, player) == true ){
                score = score + 1;
                apple.kill();
                console.log(score);
            }
            if ( game.physics.arcade.collide(apple, horse) == true ){
                score = score - 1;
                apple.kill();
                console.log(score);
            }
        }
        else{
            randY = Math.floor(Math.random()*(800-50+1)+50);
            randX = Math.floor(Math.random()*(300-50+1)+50);
            apple = game.add.sprite(randX, randY, 'apple');
            game.physics.arcade.enable(apple);
            game.physics.arcade.enableBody(apple);
            apple.body.collideWorldBounds = true;
            game.physics.arcade.collide(player, apple);
            game.physics.arcade.collide(ocean, apple);
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>


<commit_before>// Empty
<commit_msg>Make npm package actually usable<commit_after>module.exports = require('./lib/spec');
<|endoftext|>


<commit_before>var roleHealer = require('role.healer');
var roleHarvester = require('role.harvester');

var roleBuilder = {

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var storage = creep.room.find(FIND_STRUCTURES, {
				filter: (structure) => {
					return (
						(structure.structureType == STRUCTURE_CONTAINER) &&
						(structure.store[RESOURCE_ENERGY] > creep.carryCapacity));
				}
			});

			if (storage.length == 0) {
				var storage = creep.room.find(FIND_STRUCTURES, {
					filter: (structure) => {
						return (
									 (structure.structureType == STRUCTURE_SPAWN) &&
									 (Game.spawns.Spawn1.room.energyAvailable > 700));
					}
				});
			}

			if (storage.length > 0) {
				var target = creep.pos.findClosestByRange(storage);

				if (!(creep.pos.isNearTo(target))) {
					creep.moveTo(target);
				}
				else {
					(creep.withdraw(target, RESOURCE_ENERGY,
												(creep.carryCapacity - _.sum(creep.carry)))) ||
					(creep.withdraw(target, RESOURCE_ENERGY, target.energy));
				}
			}
			else {
				var sources = creep.room.find(FIND_SOURCES);
				creep.memory.source = 0;

				if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
					creep.moveTo(sources[creep.memory.source]);
				}
			}
			if (creep.carry.energy == creep.carryCapacity) {
					creep.say('Building');
			    creep.memory.harvesting = false;
			}
		}
		else {
		  var sites = creep.room.find(FIND_CONSTRUCTION_SITES);

			if (sites.length > 0) {
				var targets = sites.sort(function(site1, site2) {
					return (
						parseFloat(site2.progressTotal) -
						parseFloat(site1.progressTotal));
				}
				if (creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
					creep.say('BL Collecting');
					creep.memory.harvesting = true;
			}
			else {
					roleHealer.run(creep);
			}
		}

	} // function

}; // roleBuilder

module.exports = roleBuilder;<commit_msg>Minor changes<commit_after>var roleHealer = require('role.healer');
var roleHarvester = require('role.harvester');

var roleBuilder = {

	/** @param {Creep} creep **/
	run: function(creep) {

		if (creep.memory.harvesting) {
			var storage = creep.room.find(FIND_STRUCTURES, {
				filter: (structure) => {
					return (
						(structure.structureType == STRUCTURE_CONTAINER) &&
						(structure.store[RESOURCE_ENERGY] > creep.carryCapacity));
				}
			});

			if (storage.length == 0) {
				var storage = creep.room.find(FIND_STRUCTURES, {
					filter: (structure) => {
						return (
									 (structure.structureType == STRUCTURE_SPAWN) &&
									 (Game.spawns.Spawn1.room.energyAvailable > 700));
					}
				});
			}

			if (storage.length > 0) {
				var target = creep.pos.findClosestByRange(storage);

				if (!(creep.pos.isNearTo(target))) {
					creep.moveTo(target);
				}
				else {
					(creep.withdraw(target, RESOURCE_ENERGY,
												(creep.carryCapacity - _.sum(creep.carry)))) ||
					(creep.withdraw(target, RESOURCE_ENERGY, target.energy));
				}
			}
			else {
				var sources = creep.room.find(FIND_SOURCES);
				creep.memory.source = 0;

				if (creep.harvest(sources[creep.memory.source]) == ERR_NOT_IN_RANGE) {
					creep.moveTo(sources[creep.memory.source]);
				}
			}
			if (creep.carry.energy == creep.carryCapacity) {
					creep.say('Building');
			    creep.memory.harvesting = false;
			}
		}
		else {
		  var sites = creep.room.find(FIND_CONSTRUCTION_SITES);

			if (sites.length > 0) {
				var targets = sites.sort(function(site1, site2) {
					return (
						parseFloat(site2.progressTotal) -
						parseFloat(site1.progressTotal));
				});

				if (creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
					creep.moveTo(targets[0]);
				}
			}
			if (creep.carry.energy == 0) {
					creep.say('BL Collecting');
					creep.memory.harvesting = true;
			}
			else {
					roleHealer.run(creep);
			}
		}

	} // function

}; // roleBuilder

module.exports = roleBuilder;<|endoftext|>