text
stringlengths 7
3.69M
|
|---|
import {
Vector3, Float32BufferAttribute,Vector4, Matrix4
} from 'three';
export class Tension {
constructor( origin, target ) {
this.target = target || origin;
this.baseGeometry = origin.geometry;
this.geometry = this.target.geometry;
this.V = [ new Vector3(), new Vector3(), new Vector3() ];
this.X = [ new Vector4(), new Vector4(), new Matrix4() ];
this.isMorph = this.target.morphTargetInfluences ? true : false;
this.isSkin = this.target.isSkinnedMesh ? true : false;
this.init();
}
init(){
this.length = this.baseGeometry.attributes.position.count;
if(this.geometry.attributes.position.count !== this.length){
console.log('object not have same number of vertices !!')
return
}
this.originEdges = new Array(this.length).fill(0);
this.targetEdges = new Array(this.length).fill(0);
if( this.isSkin ) this.back = new Array(this.length*3).fill(0);
if( this.isMorph ) this.back2 = new Array(this.length*3).fill(0);
this.getEdge( this.baseGeometry, this.originEdges, false )
this.addColor();
setTimeout( this.start.bind(this), 100 );
}
start(){
this.ready = true;
this.update()
}
addColor(){
const g = this.geometry
//if( g.attributes.color ) return;
let lng = g.attributes.position.array.length;
g.setAttribute( 'color', new Float32BufferAttribute( new Array(lng).fill(0), 3 ) );
}
resetEdge( edges )
{
let j = edges.length
while(j--) edges[j] = 0
}
getEdge( g, edges, isSkin, isMorph )
{
let positions = g.attributes.position.array;
const indices = g.index.array;
let vA = this.V[0], vB = this.V[1], vC = this.V[2];
let j, i=0, a, b, c, ab, ac, bc, si, sy;
if( isMorph ){
positions = this.getMorph()
this.resetEdge(edges);
}
if( isSkin ){
positions = this.getSkinned()
this.resetEdge(edges);
}
j = g.index.count/3;
while( j-- )
{
a = indices[i];
b = indices[i+1];
c = indices[i+2];
vA.fromArray( positions, a * 3 );
vB.fromArray( positions, b * 3 );
vC.fromArray( positions, c * 3 );
/*if(isSkin){
vA = this.target.boneTransform( a, vA )
vB = this.target.boneTransform( b, vB )
vC = this.target.boneTransform( c, vC )
}*/
ab = vA.distanceTo(vB);
ac = vA.distanceTo(vC);
bc = vB.distanceTo(vC);
edges[a] += (ab + ac)*0.5;
edges[b] += (ab + bc)*0.5;
edges[c] += (ac + bc)*0.5;
i+=3;
}
}
isZero(v){
if(v.x===0 && v.y===0 && v.z ===0 ) return true
return false
}
getMorph()
{
const morphTarget = this.target.morphTargetInfluences;
const morphRef = this.geometry.morphAttributes.position
const morphsMax = morphTarget.length
const position = this.geometry.attributes.position.array;
let lng = this.geometry.attributes.position.count, id, i, j;
let vertex = this.V[0];
let temp = this.V[2];
i = lng;
while(i--)
{
id = i*3;
vertex.fromArray( position, id )
j = morphsMax;
while(j--){
if ( morphTarget[ j ] != 0.0 ){
vertex.addScaledVector( temp.fromArray( morphRef[j].data.array, id ), morphTarget[ j ] );
}
}
vertex.toArray( this.back2, id )
}
return this.back2
}
getSkinned()
{
const skeleton = this.target.skeleton;
const boneMatrices = skeleton.boneMatrices;
const geometry = this.geometry;
const position = geometry.attributes.position.array;
const skinIndex = geometry.attributes.skinIndex.array;
const skinWeigth = geometry.attributes.skinWeight.array;
const bindMatrix = this.target.bindMatrix;
const bindMatrixInverse = this.target.bindMatrixInverse;
let vertex = this.V[0];
let skin = this.V[1];
let temp = this.V[2];
let skinIndices = this.X[0];
let skinWeights = this.X[1];
let boneMatrix = this.X[2];
let lng = geometry.attributes.position.count
let i, j, boneIndex, weight, id;
// the following code section is normally implemented in the vertex shader
i = lng;
while(i--)
{
id = i*3;
skinIndices.fromArray( skinIndex, i*4 );
skinWeights.fromArray( skinWeigth, i*4 );
vertex.fromArray( position, id ).applyMatrix4( bindMatrix ); // transform to bind space
skin.set( 0, 0, 0 );
j = 4;
while(j--)
{
weight = skinWeights.getComponent( j );
if ( weight > 0 ) {
boneIndex = skinIndices.getComponent( j );
boneMatrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
// weighted vertex transformation
skin.addScaledVector( temp.copy( vertex ).applyMatrix4( boneMatrix ), weight );
}
}
skin.applyMatrix4( bindMatrixInverse ) // back to local space
skin.toArray( this.back, id )
}
return this.back
}
update()
{
if(!this.ready) return
this.getEdge( this.geometry, this.targetEdges, this.isSkin, this.isMorph );
const color = this.geometry.attributes.color.array;
let o, t, delta, n, i = this.length;
while( i-- )
{
o = this.originEdges[i];
delta = ( ( o - this.targetEdges[i] ) / o ) + 0.5;
n = i*3;
color[n] = delta > 0.5 ? (delta-0.5)*2 : 0;
color[n+1] = 0;
color[n+2] = delta < 0.5 ? (1-(delta*2)) : 0;
}
this.geometry.attributes.color.needsUpdate = true;
}
}
|
import test from 'ava'
import AdoptionApplication from '../../src/js/views/adoption-application'
test('should render component', function (t) {
const vnode = AdoptionApplication.view()
t.is(vnode.children.length, 1)
t.is(vnode.children[0].tag, 'h2')
t.is(vnode.children[0].text, 'Adoption Application')
t.pass()
})
|
import React, { Component } from 'react';
import Reviews from '../Reviews/Reviews'
import HeaderForPopup from '../../Header/HeaderForPopup'
import RatingFiveStars from '../../Helpers/RatingFiveStars'
import VendorLogo from '../../Helpers/VendorLogo'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
class Reviews4andMore extends Component {
number_of_times=3;
offset=0;
constructor(props) {
super(props);
this.state = {
number_of_more: this.props.reviews.length ,
reviews: this.props.reviews.slice(this.offset, this.number_of_times),
andmore: false
}
}
render() {
let _this = this;
let rotate= () => {
_this.offset=_this.offset+this.number_of_times;
if(_this.offset>=_this.props.reviews.length){
_this.offset=0;
}
_this.setState({
number_of_more: _this.props.reviews.length ,
reviews: _this.props.reviews.slice(_this.offset, _this.number_of_times+_this.offset),
andmore: false
});
}
let add_more = () => {
_this.setState({
number_of_more: _this.props.reviews.length ,
reviews: _this.props.reviews,
andmore: true
});
}
let remove_more = () => {
_this.setState({
number_of_more: _this.props.reviews.length ,
reviews: _this.props.reviews.slice(_this.offset, _this.number_of_times+_this.offset),
andmore: false
});
}
let fullClass = '';
if (this.state.andmore) {
fullClass = 'popup';
}
return (
<div className={fullClass}>
<div id="reviews_ancor" className="reviews_4_and_more">
{this.state.reviews.map(review =>
<div className="review">
<ul className="reviews_per_platfrom">
<li>
<RatingFiveStars number_of_stars={review.rating} number_of_reviews={review.number_of_reviews} text_reviews="reviews"/>
</li>
<li>
<VendorLogo source={review.source}/>
</li>
</ul>
<div>
{review.reviews.length > 0 ?
(<Link to={window.location.pathname + '/read_reviews/' + review.inner_id}>
read reviews
{review.reviews[0].photo_url?'(with photos!!!!)':''}
</Link>)
:
(<div>
reading reviews is impossible
</div>)}
</div>
</div>
)}
{this.state.number_of_more > 0 ?
<div className="and_more">
{!this.state.andmore ?
<p>
<div onClick={rotate}>
<strong> total {this.state.number_of_more} ratings,<span className="clickable"> click to see other >>> </span> </strong>
</div>
</p>
:
<HeaderForPopup name="Reviews by :TODO" back={remove_more} />
}
</div>
:
''
}
<Route path="*/read_reviews/:review_platfrom_inner_id" render={({ match }) => (
<Reviews reviews={this.state.reviews} review_platfrom_inner_id={match.params.review_platfrom_inner_id} />
)} />
</div>
</div>
)
}
}
export default Reviews4andMore;
|
var _ = require('underscore');
var Production = require('./production.js');
function Grammar(grammarData) {
this.symbols = null;
this.hasTerminal = null;
this.hasNonterminal = null;
this.productionsFor = {};
this.maxRHSLength = 0;
this._productions = null;
this._reductions = null;
this._initialize(grammarData);
this._analyzeProductions();
}
_.extend(Grammar, {
newProduction : function(productionString) {
return new Production(productionString);
}
});
_.extend(Grammar.prototype, {
getProduction : function(index) {
return this._productions[index];
},
getProductions : function() {
return this._productions;
},
getReduction : function(index) {
return this._reductions[index];
},
index : function(production) {
var i = null;
for (i = 0; i < this._productions.length; i++) {
if (this._productions[i].isEqual(production)) {
return i;
}
}
},
_initialize : function(grammarData) {
var self = this;
self._productions = [];
self._reductions = []
_.each(grammarData, function(grammarDatum) {
var productionString = grammarDatum.production;
self._productions.push(new Production(productionString));
self._reductions.push(grammarDatum.reduction);
});
},
_analyzeProductions : function() {
var self = this;
self.symbols = {};
self.hasTerminal = {};
self.hasNonterminal = {};
_.each(self._productions, function(production) {
self._analyzeProduction(production);
if (!self.productionsFor[production.lhs]) {
self.productionsFor[production.lhs] = [];
}
self.productionsFor[production.lhs].push(production);
if (production.rhs.length > self.maxRHSLength) {
self.maxRHSLength = production.rhs.length;
}
});
},
_analyzeProduction : function(production) {
var self = this;
var lhs = production.lhs;
var rhs = production.rhs;
var symbols = [lhs].concat(rhs);
_.each(symbols, function(symbol) {
self.symbols[symbol] = 1;
if (!self.hasNonterminal[symbol]) {
self.hasTerminal[symbol] = 1;
}
if (symbol === lhs) {
self.hasNonterminal[lhs] = 1;
delete self.hasTerminal[symbol];
}
});
}
});
module.exports = Grammar;
|
// Note: This borrows heavily from the example Todo app in Backbone.js source
$(function(){
// plt Model
// ----------
window.Plt = Backbone.Model.extend({
// Default attributes for the template (plt).
defaults: {
type: 'mailto',
name: 'Empty plt'
//to: '',
//subject: '',
//body: '',
},
initialize: function() {
ds = this.defaults;
for (var k in ds) {
if (!this.get(k)) {
obj = {};
obj[k] = ds[k];
this.set(obj);
}
}
},
// Remove this from *localStorage* and delete its view.
clear: function() {
this.destroy();
this.view.remove();
}
});
// options Model
// ----------
window.Options = Backbone.Model.extend({
localStorage: new Store("empltzOptions"),
// Default attributes for the template (plt).
defaults: {
sms: false
}
});
// Create the user Options
window.userOptions = new Options();
// plt Collection
// ---------------
// The collection of items is backed by *localStorage* instead of a remote
// server.
window.PltList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Plt,
// Save all of the plts items under the `"pltz"` namespace.
localStorage: new Store("pltz"),
// We keep the pltz in sequential order, despite being saved by unordered
// GUID in the database. This generates the next order number for new items.
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Plts are sorted by their original insertion order.
comparator: function(plt) {
return plt.get('order');
}
});
// Create our global collection of **pltz**.
window.Pltz = new PltList();
// Item View
// --------------
window.PltView = Backbone.View.extend({
// Backbone view element definitions
tagName: "li",
className: "plt",
// Cache the template function for a single item.
template: _.template($('#item-template').html()),
// The DOM events specific to an item.
events: {
"click .pltEdit" : "editForm"
},
initialize: function() {
_.bindAll(this, 'changeRender', 'render');
// Any changes (edits) to an item need to be re-rendered with a special function
this.model.bind('change', this.changeRender);
// Set this view as the view for the model
this.model.view = this;
},
// This creates the mailto or sms URL from the underlying attributes.
// TODO not the most efficient place to put it, since we have to determine every time we display,
// rather than just on updates.
createURL: function() {
plt = this.model.toJSON();
if (!plt.to & !plt.subject & !plt.body) {
return 'mailto:empltz@onmachine.org';
}
var url = "";
if (plt.type === 'sms') {
url += plt.type + ':' + plt.to + '?';
}
else {
url += plt.type + ':' + plt.to + '?' +
'subject=' + plt.subject + '&';
}
url += 'body=' + plt.body;
return encodeURI(url);
},
render: function() {
p = this.model.toJSON();
p.url = this.createURL();
$(this.el).html(this.template(p));
return this;
},
// On edit have to remove all the jQM classes or jQM won't know that it needs
// to be refreshed in listview('refresh')
changeRender: function() {
$(this.el).removeAttr('class').addClass('plt');
this.render();
return this;
},
// This supports the edit form
editForm: function() {
$editform = $('form#editForm');
// start out making sure that submit is not bound from earlier calls.
// Need to do this because you can close the dialog box without submitting.
$('form#editForm').unbind('submit.edit');
thisPlt = this.model;
var plt = thisPlt.toJSON();
var pltType;
// Set the fields to the existing values
_.each(plt, function(v, k){
if (k === 'type') {
$('form#editForm input[value="' + plt[k] + '"]')
.attr('checked',true);
pltType = v;
}
// for SMS, set the value on the right input column
else if (k === 'to') {
var toelement;
if (pltType === 'sms') {
toelement = '#tosms';
}
else {
toelement = '#' + k;
}
$(toelement).val(plt[k]);
}
// for everything else
else {
var element = '#' + k;
$(element).val(plt[k]);
}
});
// if SMS is enabled, show the fieldset and update the values.
if (userOptions.get('sms')) {
$editform.find('fieldset').show();
$("form#editForm input[type='radio']").checkboxradio();
$("form#editForm input[type='radio']").checkboxradio("refresh");
// Decide which input field to show for "to"
// this is complicated by the fact that you can't change the input type dynamically
// in at least some browsers.
$('#edit').live('pageshow',function(event, ui){
$('form#editForm label[for="tosms"]').show();
$('form#editForm input#tosms').show();
$('form#editForm label[for="to"]').show();
$('form#editForm input#to').show();
if (pltType === 'sms') {
$('form#editForm label[for="to"]').hide();
$('form#editForm input#to').hide();
}
if (pltType === 'mailto') {
$('form#editForm label[for="tosms"]').hide();
$('form#editForm input#tosms').hide();
}
});
// handle live changes to the type
$('form#editForm label[for="sms"]').bind('click.type', function(e) {
$('form#editForm label[for="tosms"]').show();
$('form#editForm input#tosms').show();
$('form#editForm label[for="to"]').hide();
$('form#editForm input#to').hide();
});
$('form#editForm label[for="mailto"]').bind('click.type', function(e) {
$('form#editForm label[for="to"]').show();
$('form#editForm input#to').show();
$('form#editForm label[for="tosms"]').hide();
$('form#editForm input#tosms').hide();
});
}
else {
$editform.find('fieldset').hide();
$('form#editForm label[for="tosms"]').hide();
$('form#editForm input#tosms').hide();
}
$('form#editForm').bind('submit.edit', function(e) {
var fields = $(this).serializeArray();
_.each(fields, function(field, i){
var name = field.name;
plt[name] = field.value;
});
// Choose which "to" input to accept
if (plt.type === 'sms') {
plt.to = plt.tosms;
}
delete plt.tosms;
thisPlt.save(plt);
$.mobile.changePage('#list','pop',true);
$('this').unbind('submit.edit');
return false;
});
},
// Remove this view from the DOM.
remove: function() {
$(this.el).remove();
},
// Remove the item, destroy the model.
clear: function() {
this.model.clear();
}
});
// The Application
// ---------------
// Our overall **AppView** is the top-level piece of UI.
window.AppView = Backbone.View.extend({
// Instead of generating a new element, bind to the existing skeleton of
// the App already present in the HTML.
el: $("#list"),
events: {
"click #addButton" : "addPlt",
"click #optionsButton" : "optionsForm"
},
initialize: function() {
_.bindAll(this, 'addNew', 'addOne', 'addAll',
'updateList', 'render');
Pltz.bind('add', this.addNew);
Pltz.bind('refresh', this.addAll);
Pltz.bind('change', this.updateList);
Pltz.bind('remove', this.updateList);
Pltz.bind('all', this.render);
Pltz.fetch();
userOptions.fetch();
},
render: function() {
if (Pltz.length === 0) {
$('#listart').hide();
$('#liend').hide();
}
else {
$('#listart').show();
$('#liend').show();
}
},
// Add a single plt right before the ending list divider
addOne: function(plt) {
var view = new PltView({model: plt});
this.$('#liend').before(view.render().el);
},
// adds all on refresh or initial load
addAll: function() {
Pltz.each(this.addOne);
$('.ui-listview').listview('refresh');
},
addNew: function(plt) {
this.addOne(plt);
$('.ui-listview').listview();
$('.ui-listview').listview('refresh');
},
updateList: function() {
$('.ui-listview').listview('refresh');
},
// TODO have issue with list corners refreshing when deleting
// trying to write something that will correct them after a removal
// this clears everything and re-writes, but can't get the swipe delete to bind
// after that.
// I don't use this since it doesn't work, just added list dividers around the list
// and the corners are not an issue.
updateRemoved: function() {
if ($('.ui-listview')[0]) {
$('.ui-listview').children().remove();
}
this.trigger('refresh');
$('.ui-page').trigger('pageshow');
},
addPlt: function() {
var $addform = $('form#addForm');
$addform.unbind('submit.add');
$addform[0].reset();
// SMS handling, if needed
if (userOptions.get('sms')) {
$('form#addForm input[value="mailto"]').attr("checked",true);
$("form#addForm input[type='radio']").checkboxradio();
$("form#addForm input[type='radio']").checkboxradio("refresh");
$('#add').live('pageshow',function(event, ui){
$('form#addForm label[for="tosms"]').hide();
$('form#addForm input#tosms').hide();
$('form#addForm label[for="to"]').show();
$('form#addForm input#to').show();
});
// handle live changes to the type
$('form#addForm label[for="sms"]').bind('click.type', function(e) {
$('form#addForm label[for="tosms"]').show();
$('form#addForm input#tosms').show();
$('form#addForm label[for="to"]').hide();
$('form#addForm input#to').hide();
});
$('form#addForm label[for="mailto"]').bind('click.type', function(e) {
$('form#addForm label[for="to"]').show();
$('form#addForm input#to').show();
$('form#addForm label[for="tosms"]').hide();
$('form#addForm input#tosms').hide();
});
}
else {
$addform.find('fieldset').hide();
$('form#addForm label[for="tosms"]').hide();
$('form#addForm input#tosms').hide();
}
$addform.bind('submit.add', function(e) {
e.preventDefault();
var plt = {};
var fields = $(this).serializeArray();
_.each(fields, function(field, i){
var name = field.name;
plt[name] = field.value;
});
// Add the order
plt.order = Pltz.nextOrder();
// Choose which "to" input to accept
if (plt.type === 'sms') {
plt.to = plt.tosms;
}
delete plt.tosms;
// Create the new plt
Pltz.create(plt);
$.mobile.changePage('#list','pop',true);
return false;
});
},
optionsForm: function() {
// start out making sure that submit is not bound from earlier calls.
// Need to do this because you can close the dialog box without submitting.
$('form#optionsForm').unbind('submit.options');
opts = userOptions.toJSON();
_.each(opts, function(v, k){
var smsSlider = $("select#slider");
if (k === 'sms') {
if (v) {
smsSlider[0].selectedIndex = 1;
}
else {
smsSlider[0].selectedIndex = 0;
}
smsSlider.slider();
smsSlider.slider("refresh");
}
});
$('form#optionsForm').bind('submit.options', function(e) {
var fields = $(this).serializeArray();
_.each(fields, function(field, i){
var name = field.name;
userOptions.attributes[name] = (field.value === 'true');
});
userOptions.save();
$.mobile.changePage('#list','flip',true);
$('this').unbind('submit.options');
return false;
});
}
});
// Deal with jQM issue of not deactivating buttons
$('.ui-page').live('pagehide', function(){
$('a[href="#"]').removeClass('ui-btn-active');
});
// Swipe to Delete
// ---------------
// Not a very 'Backbone' implementation but works.
// There were many issues binding to particular page IDs or classes
// but works if you use * or the jQM class for the page.
// This was not an issue in the pre-Backbone implementation.
$('.ui-page').live('pageshow',function(event, ui){
$('.plt').bind('swipe', function(e){
var $plt = $(this);
var id = $plt.find('a.pltLink').attr('id');
// if there are
if (!$plt.children('.aDeleteBtn')[0]) {
$('.swipedelete').bind('click.delete', function(e){
$('.aDeleteBtn').remove();
$('.swipedelete').unbind('click.delete');
return false;
});
$('.aDeleteBtn').remove();
var $aDeleteBtn = $('<a>Delete</a>')
.attr({
'class': 'aDeleteBtn ui-btn-up-r',
'id': $plt.attr('id')
});
$plt.prepend($aDeleteBtn);
$('.aDeleteBtn').bind('click.delButton', function (e) {
e.preventDefault();
var modelToDel = Pltz.get(id);
modelToDel.clear();
});
}
else {
$('.aDeleteBtn').remove();
$('.swipedelete').unbind('click.delete');
}
});
});
//update any pre-Backbone plts
(function updateOld() {
if (!localStorage.versionEmpltz || localStorage.versionEmpltz === '0.8') {
for (var j = 0; j < localStorage.length; j++) {
var key = localStorage.key(j);
if (key.indexOf('empltz.') !== -1) {
var p = {};
p = JSON.parse(localStorage.getItem(localStorage.key(j)));
if (p.type === undefined) {
p.type = 'mailto';
}
p.to = p.To;
delete p.To;
p.subject = p.Subject;
delete p.Subject;
p.body = p.Body;
delete p.Body;
p.order = Pltz.nextOrder();
Pltz.create(p);
localStorage.versionEmpltz = '0.9';
}
}
}
})();
// Finally, we kick things off by creating the **App**.
window.App = new AppView();
});
|
AngularApp.factory('appFactory',
['modalService', 'userService', 'errorService', 'Notification',
function (modalService, userService, errorService, Notification) {
return {
getUserService: function () {
return userService;
},
getModalService: function () {
return modalService;
},
getErrorService: function () {
return errorService;
},
getNotificationService: function () {
return Notification;
}
};
}]);
|
demo = window.demo || (window.demo = {});
//let players = [];
//let socket = io();
/*
mghosty for ghost
scott for scott
comp for dummy/foreign player
*/
let dude, comp;
//Get player
const getPlayer = (data) => {
console.log(data);
dude = new Character(data.dude, 10, 100, 800);
comp = new Opponent(data.comp, 10, 100, 800);
};
/* send this to other player through sockets?
* this object will be send to the other player
* and will update them with the keys that have been pressed
*/
const act = {
runRight: false,
runLeft: false,
holdUp: false,
holdDown: false,
//can either be 'jump', 'kick', 'punch', 'evade',
decision: '',
}
//comp = new Character('mghosty', 10, 100, 800);
let manager;
let emitter;
let projectile;
let stage = '';
let lives;
let music;
let flipFlop;
// sound vars need for global use for player 1
let airRec;
let slash;
let ejectBall;
let ghostDodge;
let sdodge;
let barr;
let natk1;
let jumpSnd;
let ghAirRec;
let ghRunAtk;
let ghDownKick;
let ghAtk2;
let foxKicks;
let ghAirNeu;
let ghWhip;
let ghMeteor;
let stKick;
let sldKick;
let stRunAtk;
let stSpecKick;
let stUpNeu;
let shieldHit;
let normalHit;
let shadowHit;
let ghostSpecialAtk;
let cpuB1;
let cpuB2;
//sound control for playing sounds at the right moments
let bar = new soundCtrl('holdShield');
let natk1C = new soundCtrl('neutralPunch1');
let jumpSndC = new soundCtrl('startJump');
let ghAirRecC = new soundCtrl('airRecovery');
let ghRunAtkC = new soundCtrl('runAttack');
let ghDownKickC = new soundCtrl('loopDwnKick');
let ghAtk2C = new soundCtrl('neutralPunch2');
let natk2C = new soundCtrl('neutralPunch3');
let ghAtk4 = new soundCtrl('neutralPunch4');
let ghUpKickC = new soundCtrl('upAir');
let ghbackKickC = new soundCtrl('foxKick');
let ghAirNeuC = new soundCtrl('airNeutral');
let ghAirDodgeC = new soundCtrl('airDodge');
let ghWhipC = new soundCtrl('neutralPunch5');
let ghMeteorC = new soundCtrl('meteorSmash');
let stKickC = new soundCtrl('neutralKick');
let sldKickC = new soundCtrl('slideKick');
let stRunAtkC = new soundCtrl('runAttack');
let stSpecKickC = new soundCtrl('specialKick1');
//hit effect renderers for player 1
let nullHitEffect = new hitEffectCtrl(true);
let normHit = new hitEffectCtrl(false);
let grghostHit = new hitEffectCtrl(false);
//sound controls for CPU
let CPUbar = new soundCtrl('holdShield');
let CPUnatk1C = new soundCtrl('neutralPunch1');
let CPUjumpSndC = new soundCtrl('startJump');
let CPUghAirRecC = new soundCtrl('airRecovery');
let CPUghRunAtkC = new soundCtrl('runAttack');
let CPUghDownKickC = new soundCtrl('loopDwnKick');
let CPUghAtk2C = new soundCtrl('neutralPunch2');
let CPUnatk2C = new soundCtrl('neutralPunch3');
let CPUghAtk4 = new soundCtrl('neutralPunch4');
let CPUghUpKickC = new soundCtrl('upAir');
let CPUghbackKickC = new soundCtrl('foxKick');
let CPUghAirNeuC = new soundCtrl('airNeutral');
let CPUghAirDodgeC = new soundCtrl('airDodge');
let CPUghWhipC = new soundCtrl('neutralPunch5');
let CPUghMeteorC = new soundCtrl('meteorSmash');
let CPUstKickC = new soundCtrl('neutralKick');
let CPUsldKickC = new soundCtrl('slideKick');
let CPUstRunAtkC = new soundCtrl('runAttack');
let CPUstSpecKickC = new soundCtrl('specialKick1');
//hit effect renderers for CPU
let CPUnullHitEffect = new hitEffectCtrl(true);
let CPUnormHit = new hitEffectCtrl(false);
let CPUgrghostHit = new hitEffectCtrl(false);
//contains all our booleans and stats for a character
function Character(name, power, gravity, jumpResistance) {
this.name = name;
this.combo = [];
this.getHitWith = '';
this.isHurt = false;
this.lives = {
left: 3
}
this.stats = {
damage: 0,
lives: 3,
power: power,
evades: 5,
gravity: gravity,
jumpR: jumpResistance,
jumpH: 0,
};
this.isLeft = false;
this.keyPressed = '';
this.isGrounded = false;
this.isJumping = false;
this.isAirAttack = false;
this.isAirDodging = false;
this.isDodging = false;
this.canAirDodge = true;
this.airDownChecks = {
downAirAtk1: false,
downAirAtk2: false,
downAirAtk3: false,
};
this.canPlayerJump = true;
this.completedJump = true;
this.startedJump = false;
this.onlyDoOnce = false;
this.canPlayerJump = true;
this.airDodgeDirect = '';
this.shield = {
shieldHp: 100,
shieldActive: false,
shieldX: 0,
shieldY: 0,
};
this.hitbox = {
X: 0,
Y: 0,
isOverlapping: false,
isAtkBoxActive: false,
};
this.canAirRecover = true;
this.isAirRecovering = false;
this.isInvincible = false;
this.isBulletFired = false;
this.isShotLeft = false;
this.timedBonusAnim;
this.timedBonus = false;
this.velocityStall = false;
this.stallChecked = false;
this.stopMotion = false;
this.flipFlop = false;
this.setupRelations = function () {
switch (this.name) {
case 'ghostStock':
this.relatives.stockname = 'ghostStock';
break;
case 'sStock':
this.relatives.stockname = 'sStock';
default:
break;
}
};
this.glideDownJump = function (sprite, fallingGravity, postGravity) {
if (!this.isGrounded || this.combo[0] === 'jump') {
sprite.body.gravity.y = this.stats.gravity;
} else {
sprite.body.gravity.y = this.stats.jumpR;
}
};
this.jumpAnimLoop = function (sprite) {
if (this.completedJump) {
if (!this.isAirAttack && !this.isAirDodging && this.canPlayerJump && !(['airDodge', 'airRecovery', 'airNeutral', 'upAir', 'foxKick', 'meteorSmash'].includes(sprite.animations.currentAnim.name))) {
if ((this.isGrounded && this.startedJump) || (this.isGrounded && this.startedJump && this.combo[0] == 'jump')) {
sprite.animations.play('endJump');
this.startedJump = false;
this.isJumping = false;
this.canPlayerJump = false;
}
else if (!this.isGrounded && this.startedJump) {
sprite.animations.play('loopJump');
} else if (this.combo[0] == 'jump' && !this.isGrounded && !this.startedJump) {
this.startedJump = true;
this.isJumping = true;
//sprite.animations.stop('idle');
sprite.animations.play('startJump');
//completedJump = false;
} else {
return false;
}
} else {
return;
}
}
};
this.downAerialMotion = function (sprite, intensity) {
if (intensity.toLowerCase() == 'low') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 7;
} else {
sprite.x += 7;
}
sprite.y -= 7;
} else {
return;
}
} else if (intensity.toLowerCase() == 'med') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 9;
} else {
sprite.x += 9;
}
sprite.y -= 7;
} else {
return;
}
} else if (intensity.toLowerCase() == 'high') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 11;
} else {
sprite.x += 11;
}
sprite.y -= 8;
} else {
return;
}
} else if (intensity.toLowerCase() == 'ghost') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 7;
} else {
sprite.x += 7;
}
//sprite.y += 5;
sprite.body.velocity.y = 300;
} else {
return;
}
}
};
this.downAerial = function (sprite) {
if (this.isAirAttack) {
if (!this.airDownChecks.isDownAirAtk1) {
this.airDownChecks.isDownAirAtk1 = true;
sprite.animations.play('startDwnKick');
/* if (player.animations.currentAnim.isFinished) { */
this.airDownChecks.isDownAirAtk2 = true;
} else if (this.airDownChecks.isDownAirAtk2 && !this.isGrounded) {
sprite.animations.play('loopDwnKick');
this.combo[0] = 'loopDwnKick';
/* if (player.animations.currentAnim.isFinished) { */
this.airDownChecks.isDownAirAtk2 = false;
this.airDownChecks.isDownAirAtk3 = true;
} else if (this.airDownChecks.isDownAirAtk3 && this.isGrounded && this.completedJump) {
sprite.animations.play('endDwnKick');
this.airDownChecks.isDownAirAtk2 = true;
this.airDownChecks.isDownAirAtk3 = false;
this.airDownChecks.isDownAirAtk1 = false;
this.isAirAttack = false;
}
} else {
return;
}
};
this.jump = function (sprite, maxHeight) {
if (!this.isAirDodging && game.input.keyboard.isDown(Phaser.Keyboard.X) && this.stats.jumpH < 30) {
this.stats.jumpH++;
sprite.y -= 15;
} else {
return;
}
};
this.runIdleControl = function (sprite) {
if (!this.stopMotion) {
if (sprite.animations.currentAnim.isFinished) {
if (this.isDodging && (['startJump', 'loopJump', 'dodge', 'block', 'moveDodge'].includes(sprite.animations.currentAnim.name))) {
sprite.animations.stop('idle');
//spriteCombo = [];
this.keyPressed = '';
} else if ((!this.isDodging || !this.isAirDodging) && !game.input.keyboard.isDown(Phaser.Keyboard.Z) && !game.input.keyboard.isDown(Phaser.Keyboard.X) && this.completedJump || (!game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) && sprite.animations.currentAnim.name == 'run' || !game.input.keyboard.isDown(Phaser.Keyboard.LEFT) && sprite.animations.currentAnim.name == 'run')) {
this.onlyDoOnce = false;
this.canPlayerJump = true;
if (!this.isGrounded && !(['knockback', 'pushback1', 'pushback2', 'pushback3'].includes(sprite.animations.currentAnim.name))) {
sprite.animations.play('notloopJump');
} else if (this.isGrounded) {
//sprite.animations.stop('notloopJump');
if (['notloopjump', 'loopJump'].includes(sprite.animations.currentAnim.name)/* && sprite.animations.currentAnim.name == 'notloopjump' */ && sprite.animations.currentAnim.isFinished) {
sprite.animations.play('endJump');
}
sprite.animations.play('idle');
}
this.combo = [];
this.canAirRecover = true;
this.keyPressed = '';
this.timedBonusAnim = '';
this.stallChecked = false;
}
//HANDLES RUN ANIM isspriteAirDodging
} else if (((!this.shield.shieldActive || !this.isAirDodging) && sprite.animations.currentAnim.name == 'idle' || sprite.animations.currentAnim.name == 'run' || sprite.animations.currentAnim.name == 'jump' || this.isGrounded) && !['neutralKick', 'neutralPunch1', 'neutralPunch2', 'neutralPunch3', 'neutralPunch4'].includes(sprite.animations.currentAnim.name) || (!sprite.animations.currentAnim.isFinished)) {
if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) && ((!['s', 'a'].includes(this.keyPressed)) && sprite.animations.currentAnim.name !== 'runAttack' && (!this.isAirDodging && !this.shield.shieldActive))) {
if (sprite.animations.currentAnim.name !== 'knockback') {
//testing for ghost's foxKick
sprite.scale.setTo(1, 1);
this.isLeft = false;
if (sprite.animations.currentAnim.name == 'airNeutral') {
sprite.x += 13;
//sprite.body.velocity.x = 200;
} else {
sprite.x += 8;
//sprite.body.velocity.x = 400;
}
if ((!['jump', 'startJump', 'loopJump', 'endJump', 'dodge', 'block', 'moveDodge', 'loopDwnKick', 'airDodge'].includes(sprite.animations.currentAnim.name)) && (!game.input.keyboard.isDown(Phaser.Keyboard.X) && this.isGrounded !== false && this.startedJump == false)) {
sprite.animations.play('run');
}
} else {
return;
}
} else if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT) && ((!['s', 'a'].includes(this.keyPressed)) && sprite.animations.currentAnim.name !== 'runAttack' && (!this.isAirDodging && !this.shield.shieldActive))) {
if (sprite.animations.currentAnim.name !== 'knockback') {
sprite.scale.setTo(-1, 1);
this.isLeft = true;
if (sprite.animations.currentAnim.name == 'airNeutral') {
sprite.x -= 13;
//sprite.body.velocity.x = -200;
} else {
sprite.x -= 8;
//sprite.body.velocity.x = -400;
}
if ((!['jump', 'startJump', 'loopJump', 'endJump', 'dodge', 'block', 'moveDodge', 'loopDwnKick', 'airDodge'].includes(sprite.animations.currentAnim.name)) && (!game.input.keyboard.isDown(Phaser.Keyboard.X) && this.isGrounded !== false && this.startedJump == false)) {
sprite.animations.play('run');
}
} else {
return;
}
} else if ((!game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) || (!game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) || this.keyPressed || game.input.keyboard.isDown(Phaser.Keyboard.Z) || game.input.keyboard.isDown(Phaser.Keyboard.A) || game.input.keyboard.isDown(keys.d) || game.input.keyboard.isDown(keys.w) || game.input.keyboard.isDown(keys.x) || this.startedJump) {
sprite.animations.stop('run');
} else {
}
}
} else {
return;
}
};
this.moveAttackBox = function (atkBox, sprite, charObj) {
let posX = sprite.x + this.hitbox.X;
let posY = sprite.y + this.hitbox.Y;
atkBox.x = posX;
atkBox.y = posY;
atkBox.alpha = 0;
atkBox.angle = 0;
//sets the position of the hitbox
atkBox.position = {
x: posX,
y: posY,
type: 25
}
switch (this.combo[0]) {
case 'neutralPunch1':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -50;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch2':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
//atkBox.height = 45;
//atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
//atkBox.height = 45;
// atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
//this.hitbox.X = -110;
//this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
// this.hitbox.X = 80;
//this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch3':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
//this.hitbox.X = -110;
// this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch4':
if (this.isLeft) {
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
///atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'neutralPunch5':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 30;
atkBox.width = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 20;
atkBox.height = 30;
atkBox.width = 30;
///atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -20;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 20;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralKick':
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 25;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'specialKick1':
if (this.name == "mghosty") {
if (this.isLeft) {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 10;
atkBox.height = 30;
atkBox.width = 75;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = -25;
this.hitbox.Y = 10;
atkBox.height = 30;
atkBox.width = 75;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'runAttack':
if (this.name == "mghosty") {
if (this.isLeft) {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 0;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 0;
this.hitbox.Y = 0;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 0;
atkBox.height = 40;
atkBox.width = 55;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 10;
this.hitbox.Y = 0;
atkBox.height = 40;
atkBox.width = 55;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'loopDwnKick':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -40;
this.hitbox.X = -34;
this.hitbox.Y = 67;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 25;
this.hitbox.X = 4;
this.hitbox.Y = 40;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -25;
this.hitbox.X = -70;
this.hitbox.Y = 65;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 25;
this.hitbox.X = 30;
this.hitbox.Y = 50;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'slideKick':
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 80;
atkBox.height = 15;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 40;
this.hitbox.Y = 80;
atkBox.height = 15;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'upNeutral':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -45;
this.hitbox.X = -90;
this.hitbox.Y = 10;
atkBox.height = 60;
atkBox.width = 150;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 35;
this.hitbox.X = -40;
this.hitbox.Y = -85;
atkBox.height = 60;
atkBox.width = 150;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -75;
this.hitbox.X = -40;
this.hitbox.Y = 30;
atkBox.height = 50;
atkBox.width = 90;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
atkBox.angle = 75;
this.hitbox.X = 30;
this.hitbox.Y = -60;
atkBox.height = 50;
atkBox.width = 90;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'airNeutral':
//for scott, its a spike
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -50;
this.hitbox.Y = 40;
atkBox.height = 15;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 0;
this.hitbox.Y = 40;
atkBox.height = 15;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -45;
this.hitbox.Y = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 23;
this.hitbox.Y = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'airRecovery':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -95;
this.hitbox.X = -50;
this.hitbox.Y = 40;
atkBox.height = 30;
atkBox.width = 65;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = -50;
this.hitbox.X = 0;
this.hitbox.Y = 40;
atkBox.height = 30;
atkBox.width = 65;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -75;
this.hitbox.X = -50;
this.hitbox.Y = 30;
atkBox.height = 60;
atkBox.width = 120;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
atkBox.angle = 75;
this.hitbox.X = 27;
this.hitbox.Y = -90;
atkBox.height = 60;
atkBox.width = 120;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'meteorSmash':
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'upAir':
if (this.isLeft) {
this.hitbox.X = 0;
this.hitbox.Y = -80;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = -25;
this.hitbox.Y = -80;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'foxKick':
if (this.isLeft) {
this.hitbox.X = 45;
this.hitbox.Y = 25;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = -65;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'haduken':
if (this.isLeft) {
this.hitbox.X = -55;
this.hitbox.Y = 10;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 40;
this.hitbox.Y = 10;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
default:
break;
}
};
this.moveRunAttack = function (sprite, animName, speed) {
if (sprite.animations.currentAnim.name == animName && game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
sprite.x += speed;
} else if (sprite.animations.currentAnim.name == animName && game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
sprite.x -= speed;
}
};
this.moveDodge = function (sprite) {
if (!game.input.keyboard.isDown(Phaser.Keyboard.X) && !this.isAirDodging && this.isDodging && !this.shield.shieldActive) {
sprite.animations.play('moveDodge');
this.timedBonusAnim = (sprite.animations.currentAnim.name);
if (this.isLeft) {
sprite.body.velocity.setTo(-420, 0);
} else {
sprite.body.velocity.setTo(420, 0);
}
}
this.isDodging = false;
};
this.airDodged = function (sprite) {
if (this.isAirDodging && sprite.animations.currentAnim.name !== 'airDodge') {
this.toggleSpriteMotion(scott);
if (this.airDodgeDirect === 'right') {
sprite.animations.play('airDodge');
game.add.tween(sprite).to({ x: '-80' }, 500, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 500, scott);
//sprite.body.velocity.setTo(-125, 0);
//game.add.tween(sprite).onComplete.add(toggleSpriteMotion, this);
this.isAirDodging = false;
this.airDodgeDirect = '';
} else if (this.airDodgeDirect === 'left') {
sprite.animations.play('airDodge');
game.add.tween(sprite).to({ x: '80' }, 500, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 500, scott);
//game.add.tween(sprite).onComplete.add(toggleSpriteMotion, this);
//sprite.body.velocity.setTo(125, 0);
this.isAirDodging = false;
this.airDodgeDirect = '';
} else {
return;
}
}
};
this.upRecovery = function (sprite) {
if (this.isAirRecovering && sprite.animations.currentAnim.name !== 'airRecovery') {
//change param to sprite
this.toggleSpriteMotion(scott);
if (!this.isLeft) {
sprite.animations.play('airRecovery');
this.combo[0] = (sprite.animations.currentAnim.name);
game.add.tween(sprite).to({ x: '80', y: '-180' }, 400, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 400, scott);
this.isAirRecovering = false;
} else if (this.isLeft) {
sprite.animations.play('airRecovery');
this.combo[0] = (sprite.animations.currentAnim.name);
game.add.tween(sprite).to({ x: '-80', y: '-180' }, 400, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 400, scott);
this.isAirRecovering = false;
} else {
return;
}
}
};
this.resetAirDodge = function (sprite) {
if (this.isGrounded && sprite.animations.currentAnim.name !== 'airDodge') {
this.canAirDodge = true;
}
if (sprite.animations.currentAnim.name == 'airDodge' && sprite.animations.currentAnim.loopCount >= 1) {
sprite.animations.stop('airDodge');
}
};
this.toggleSpriteMotion = function (sprite) {
sprite.body.gravity.y > 0 ? sprite.body.gravity.y = 0 : sprite.body.gravity.y = 1000;
sprite.body.moves ? sprite.body.moves = false : sprite.body.moves = true;
this.stopMotion ? this.stopMotion = true : this.stopMotion = false;
};
this.doTimeout = function (func, time, param1) {
setTimeout(function () {
func(param1);
}, time);
};
//shield = sprite name for shield
//sprite = sprite name of user
this.showShield = function (shield, sprite) {
let posX = sprite.x + this.shield.shieldX;
let posY = sprite.y + this.shield.shieldY;
shield.x = posX;
shield.y = posY;
shield.position = {
x: posX,
y: posY,
type: 25
}
// if the the shield is active and the Z key is held down
if (this.isGrounded && this.shield.shieldActive && game.input.keyboard.isDown(Phaser.Keyboard.Z)) {
//play the shield animation
sprite.animations.play('holdShield');
shield.animations.play('on');
if (this.isLeft) {
this.shield.shieldX = -10;
this.shield.shieldY = 0;
} else {
this.shield.shieldX = -20;
this.shield.shieldY = 0;
}
if (this.shield.shieldActive && this.shield.shieldHP > 76) {
//set the alpha to 1
shield.alpha = 1;
} else if (this.shield.shieldActive && 50 <= this.shield.shieldHP <= 75) {
//set alpha to 0.7 if shieldHP is between 50 and 75
//the idea here is the the shield will appear 'weaker' or 'more tranasparent', the less HP it has
shield.alpha = 0.7;
} else if (this.shield.shieldActive && 25 <= this.shield.shieldHP <= 50) {
shield.alpha = 0.5;
} else if (this.shield.shieldActive && 0 < this.shield.shieldHP < 24) {
shield.alpha = 0.3;
} else if (this.shield.shieldActive && this.shield.shieldHP <= 0) {
shield.alpha = 0;
shieldActive = false;
shield.destroy();
}
} else {
shield.animations.stop('on');
shield.alpha = 0;
this.shield.shieldActive = false;
return;
}
};
//this object's assigned sprite
this.velocityStallControl = function (sprite) {
if (this.isHurt) {
if (-1 < sprite.body.speed < 100 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
//this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1000);
} else if (100 < sprite.body.speed < 200 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1200);
} else if (200 < sprite.body.speed < 300 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1300);
}
else if (300 < sprite.body.speed && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1800);
} else {
return;
}
} else {
return;
}
};
this.resetGetHit = function (charObj) {
setTimeout(function () {
charObj.getHitWith = '';
}, 1000);
}
this.pushbackControl = function (sprite) {
if (['upNeutral', 'airRecovery', 'airNeutral'].includes(this.getHitWith)) {
if (50 <= this.stats.damage <= 98) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('knockback');
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else if (99 <= this.stats.damage <= 199) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
sprite.animations.play('pushback3');
}
} else if (200 <= this.stats.damage <= 299) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else if (this.stats.damage > 300) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('knockback');
}
}
} else {
sprite.animations.play('knockback');
}
};
this.resetHitbox = function (hitbox) {
setTimeout(function () {
hitbox.width = 25;
hitbox.height = 25;
hitbox.alpha = 0;
hitbox.angle = 0;
atkBoxCanHurt = false;
}, 100);
};
this.loadStock = function () {
switch (this.name) {
case 'scott':
game.load.spritesheet('sStk', '../assets/art/sStock.png', 32, 32);
break;
case 'mghosty':
game.load.spritesheet('gStk', '../assets/art/ghostStock.png', 32, 32);
break;
default:
break;
}
};
this.invincibilityCtrl = function (sprite) {
if (sprite.animations.currentAnim.name == 'airDodge') {
this.isInvincible = true;
} else {
this.isInvincible = false;
}
}
this.addSFX = function () {
if (this.name == 'mghosty') {
slash = game.add.audio('sword');
ejectBall = game.add.audio('throwball');
ghostDodge = game.add.audio('gdodge');
barr = game.add.audio('barrier');
natk1 = game.add.audio('gnatk1');
jumpSnd = game.add.audio('jumpa');
ghAirRec = game.add.audio('ghAir');
ghRunAtk = game.add.audio('ghRunAtk');
ghDownKick = game.add.audio('ghDownKick');
ghAtk2 = game.add.audio('ghAtk2');
foxKicks = game.add.audio('foxKicks');
ghAirNeu = game.add.audio('ghAirNeu');
ghWhip = game.add.audio('ghWhip');
ghMeteor = game.add.audio('ghMeteor');
shieldHit = game.add.audio('nullHit');
normalHit = game.add.audio('elecHit');
} else {
slash = game.add.audio('sword');
ejectBall = game.add.audio('throwball');
ghostDodge = game.add.audio('grDodge');
sdodge = game.add.audio('grDodge');
barr = game.add.audio('barrier');
natk1 = game.add.audio('stPunch');
jumpSnd = game.add.audio('jumpa');
ghAirRec = game.add.audio('airRecov');
ghRunAtk = game.add.audio('stRunAtk');
ghDownKick = game.add.audio('ghDownKick');
ghAtk2 = game.add.audio('ghAtk2');
foxKicks = game.add.audio('foxKicks');
ghAirNeu = game.add.audio('ghAirNeu');
ghWhip = game.add.audio('stPunch');
ghMeteor = game.add.audio('ghMeteor');
stKick = game.add.audio('stKick');
sldKick = game.add.audio('stSlideKick');
stRunAtk = game.add.audio('stRunAtk');
stSpecKick = game.add.audio('stSpecKick');
stUpNeu = game.add.audio('stUpNeu');
shieldHit = game.add.audio('nullHit');
normalHit = game.add.audio('elecHit');
}
};
// theres a copy of this function on the demo.create object. delte when complete
this.createFighter = function () {
let name = this.name;
switch (name) {
case 'scott':
scott = game.add.sprite(400, 100, 'tester');
scott.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7], 12, true);
scott.animations.add('run', [8, 9, 10, 11, 12, 13, 14, 15], 14, false);
scott.animations.add('startJump', [17, 18, 19, 20, 21, 22, 23, 24], 18, false);
scott.animations.add('loopJump', [24, 25], 12, true);
scott.animations.add('notloopJump', [24, 25], 12, false);
scott.animations.add('endJump', [27], 12, false);
scott.animations.add('neutralPunch1', [28, 29, 30, 31], 11, false);
scott.animations.add('neutralPunch2', [32, 33, 34, 35], 11, false);
scott.animations.add('neutralPunch3', [36, 37, 38], 11, false);
scott.animations.add('neutralPunch4', [39, 40], 11, false);
scott.animations.add('neutralPunch5', [41, 42, 43, 44], 11, false);
scott.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
scott.animations.add('specialKick1', [63, 64, 65, 66, 67, 68, 69], 14, false);
scott.animations.add('runAttack', [70, 71, 72, 73, 74, 75, 76, 77, 78], 16, false);
scott.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
scott.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
scott.animations.add('dodge', [92, 93, 94, 95], 14, false);
scott.animations.add('knockback', [96, 97, 98, 99, 100], 14, false);
scott.animations.add('startDwnKick', [100, 101, 102], 12, false);
scott.animations.add('loopDwnKick', [103, 104, 105], 12, true);
scott.animations.add('endDwnKick', [106], 12, false);
scott.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
scott.animations.add('moveDodge', [114, 115, 116, 117, 118, 119, 120], 20, false);
scott.animations.add('holdShield', [121, 122, 123, 124], 15, false);
scott.animations.add('airDodge', [125, 126, 127], 14, true);
scott.animations.add('airRecovery', [136, 137, 138, 139, 140, 141, 142], 14, false);
scott.animations.add('upNeutral', [128, 129, 130, 131, 132, 133, 134, 135], 18, false);
scott.animations.add('airNeutral', [142, 143, 144, 145, 146, 147], 18, false);
scott.animations.add('pushback1', [148], 10, false);
scott.animations.add('pushback2', [149], 10, false);
scott.animations.add('pushback3', [150], 10, false);
scott.animations.play('idle');
break;
case 'mghosty':
scott = game.add.sprite(400, 100, 'ghosty');
scott.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7, 8], 12, true);
scott.animations.add('run', [9, 10, 11, 12, 13], 14, false);
//player.animations.add('jump', [16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 12, false);
scott.animations.add('startJump', [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], 20, false);
scott.animations.add('loopJump', [49, 50, 51, 52, 53, 54], 15, true);
scott.animations.add('notloopJump', [49, 50, 51, 52, 53, 54], 12, false);
scott.animations.add('endJump', [164, 165, 166, 167, 168, 169, 170, 171, 39, 38, 37, 36, 35, 34, 33, 32], 60, false);
//neutralpunch2 would follow nuetralpunch1 after it finishes running, like a combo
//would require input, let's say that hitting 'a' for example, would trigger neutralPunch1, if pressed again at the right...
//..moment, would trigger neutralPunch2, and so forth
scott.animations.add('neutralPunch1', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
scott.animations.add('neutralPunch2', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
scott.animations.add('neutralPunch3', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
scott.animations.add('neutralPunch4', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
scott.animations.add('neutralPunch5', [123, 124, 125, 126, 127, 128, 129, 130, 131, 132], 25, false);
//scott.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
scott.animations.add('specialKick1', [32, 33, 34, 35, 36, 37, 38, 39, 189, 39, 38, 37, 36, 35, 34, 33, 32], 35, false);
scott.animations.add('runAttack', [139, 140, 141, 142, 143, 144, 145, 146], 16, false);
//scott.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
//scott.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
//scott.animations.add('dodge', [92, 93, 94, 95], 14, false);
scott.animations.add('knockback', [156, 157, 158, 159], 14, false);
scott.animations.add('startDwnKick', [84], 12, false);
scott.animations.add('loopDwnKick', [85, 86, 87], 12, true);
//warning, ghost has to transform back to his old self, this anim may be absolete
scott.animations.add('endDwnKick', [88, 90], 12, false);
//scott.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
//testing to see if we can run anims like this
//may not to splite this anim to two and call them sequentially
scott.animations.add('moveDodge', [32, 33, 34, 35, 36, 37, 38, 39, 38, 37, 36, 35, 34, 33, 32], 20, false);
scott.animations.add('holdShield', [172, 173, 174, 175, 176, 177, 178, 179], 15, false);
scott.animations.add('airDodge', [116, 117, 118, 119, 120], 14, true);
scott.animations.add('airRecovery', [76, 77, 78, 79, 80, 81, 82], 14, false);
scott.animations.add('upNeutral', [148, 149, 150, 151, 152, 153, 154], 18, false);
scott.animations.add('airNeutral', [55, 56, 57, 58, 59, 60, 61, 62, 63, 64], 25, false);
scott.animations.add('pushback1', [148], 10, false);
scott.animations.add('pushback2', [149], 10, false);
scott.animations.add('pushback3', [150], 10, false);
//UNIQUE TO GHOST
scott.animations.add('airKnockback', [160, 161, 162, 163], 13, false);
scott.animations.add('meteorSmash', [93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103], 27, false);
scott.animations.add('upAir', [105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115], 20, false);
scott.animations.add('foxKick', [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], 15, false);
scott.animations.add('haduken', [182, 183, 184, 185, 186, 187, 188], 15, false);
scott.animations.play('idle');
break;
default:
break;
};
this.enablePhysics = function (sprite) {
if (this.name == 'scott') {
sprite.body.setSize(60, 120, 20, 69);
} else if (this.name == 'mghosty') {
sprite.body.setSize(60, 120, 20, 47);
}
sprite.body.drag.x = 500;
};
this.enableSoundControls = function () {
bar.run(barr, scott).listen(scott);
jumpSndC.run(jumpSnd, scott).listen(scott);
natk1C.run(natk1, scott).listen(scott);
ghAirRecC.run(ghAirRec, scott).listen(scott);
ghRunAtkC.run(ghRunAtk, scott).listen(scott);
ghDownKickC.run(ghDownKick, scott).listen(scott);
ghAtk2C.run(ghAtk2, scott).listen(scott);
natk2C.run(natk1, scott).listen(scott);
ghUpKickC.run(foxKicks, scott).listen(scott);
ghbackKickC.run(ghAirNeu, scott).listen(scott);
ghAirNeuC.run(ghAirNeu, scott).listen(scott);
ghWhipC.run(ghWhip, scott).listen(scott);
ghMeteorC.run(ghMeteor, scott).listen(scott);
stKickC.run(stKick, scott).listen(scott);
sldKickC.run(sldKick, scott).listen(scott);
if (this.name == 'scott') {
stRunAtkC.run(stRunAtk, scott).listen(scott);
stSpecKickC.run(stSpecKick, scott).listen(scott);
}
//hbFxKickCtrl.run(scott, atkBox).listen(scott, atkBox);
}
};
this.ghostLand = function (sprite) {
if (this.name == 'mghosty' && this.isGrounded && ['notloopJump'].includes(sprite.animations.currentAnim.name)) {
sprite.animations.play('endJump');
} else {
return;
}
};
this.ghSpecialListener = function (sprite, enemy, sound) {
let done = false;
if (this.name == 'mghosty' && sprite.animations.currentFrame.index == 189) {
ghostSpecialAtk.x = enemy.x;
ghostSpecialAtk.y = sprite.y - 65;
ghostSpecialAtk.alpha = 1;
ghostSpecialAtk.revive();
game.add.tween(ghostSpecialAtk).to({ alpha: 0 }, 800, "Linear", true);
ghostSpecialAtk.animations.play('show');
} else {
return;
}
};
this.createOther = function () {
let name = this.name;
console.log(name);
switch (name) {
case 'scott':
dummy = game.add.sprite(400, 100, 'tester');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7], 12, true);
dummy.animations.add('run', [8, 9, 10, 11, 12, 13, 14, 15], 14, false);
dummy.animations.add('startJump', [17, 18, 19, 20, 21, 22, 23, 24], 18, false);
dummy.animations.add('loopJump', [24, 25], 12, true);
dummy.animations.add('notloopJump', [24, 25], 12, false);
dummy.animations.add('endJump', [27], 12, false);
dummy.animations.add('neutralPunch1', [28, 29, 30, 31], 11, false);
dummy.animations.add('neutralPunch2', [32, 33, 34, 35], 11, false);
dummy.animations.add('neutralPunch3', [36, 37, 38], 11, false);
dummy.animations.add('neutralPunch4', [39, 40], 11, false);
dummy.animations.add('neutralPunch5', [41, 42, 43, 44], 11, false);
dummy.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [63, 64, 65, 66, 67, 68, 69], 14, false);
dummy.animations.add('runAttack', [70, 71, 72, 73, 74, 75, 76, 77, 78], 16, false);
dummy.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
dummy.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
dummy.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [96, 97, 98, 99, 100], 14, false);
dummy.animations.add('startDwnKick', [100, 101, 102], 12, false);
dummy.animations.add('loopDwnKick', [103, 104, 105], 12, true);
dummy.animations.add('endDwnKick', [106], 12, false);
dummy.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
dummy.animations.add('moveDodge', [114, 115, 116, 117, 118, 119, 120], 20, false);
dummy.animations.add('holdShield', [121, 122, 123, 124], 15, false);
dummy.animations.add('airDodge', [125, 126, 127], 14, true);
dummy.animations.add('airRecovery', [136, 137, 138, 139, 140, 141, 142], 14, false);
dummy.animations.add('upNeutral', [128, 129, 130, 131, 132, 133, 134, 135], 18, false);
dummy.animations.add('airNeutral', [142, 143, 144, 145, 146, 147], 18, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
dummy.animations.play('idle');
break;
case 'mghosty':
dummy = game.add.sprite(400, 100, 'ghosty');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7, 8], 12, true);
dummy.animations.add('run', [9, 10, 11, 12, 13], 14, false);
//player.animations.add('jump', [16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 12, false);
dummy.animations.add('startJump', [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], 20, false);
dummy.animations.add('loopJump', [49, 50, 51, 52, 53, 54], 15, true);
dummy.animations.add('notloopJump', [49, 50, 51, 52, 53, 54], 12, false);
dummy.animations.add('endJump', [164, 165, 166, 167, 168, 169, 170, 171, 39, 38, 37, 36, 35, 34, 33, 32], 60, false);
//neutralpunch2 would follow nuetralpunch1 after it finishes running, like a combo
//would require input, let's say that hitting 'a' for example, would trigger neutralPunch1, if pressed again at the right...
//..moment, would trigger neutralPunch2, and so forth
dummy.animations.add('neutralPunch1', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch2', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch3', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch4', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch5', [123, 124, 125, 126, 127, 128, 129, 130, 131, 132], 25, false);
//scott.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [32, 33, 34, 35, 36, 37, 38, 39, 189, 39, 38, 37, 36, 35, 34, 33, 32], 14, false);
dummy.animations.add('runAttack', [139, 140, 141, 142, 143, 144, 145, 146], 16, false);
//scott.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
//scott.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
//scott.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [156, 157, 158, 159], 14, false);
dummy.animations.add('startDwnKick', [84], 12, false);
dummy.animations.add('loopDwnKick', [85, 86, 87], 12, true);
//warning, ghost has to transform back to his old self, this anim may be absolete
dummy.animations.add('endDwnKick', [88, 90], 12, false);
//scott.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
//testing to see if we can run anims like this
//may not to splite this anim to two and call them sequentially
dummy.animations.add('moveDodge', [32, 33, 34, 35, 36, 37, 38, 39, 38, 37, 36, 35, 34, 33, 32], 20, false);
dummy.animations.add('holdShield', [172, 173, 174, 175, 176, 177, 178, 179], 15, false);
dummy.animations.add('airDodge', [116, 117, 118, 119, 120], 14, true);
dummy.animations.add('airRecovery', [76, 77, 78, 79, 80, 81, 82], 14, false);
dummy.animations.add('upNeutral', [148, 149, 150, 151, 152, 153, 154], 18, false);
dummy.animations.add('airNeutral', [55, 56, 57, 58, 59, 60, 61, 62, 63, 64], 25, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
//UNIQUE TO GHOST
dummy.animations.add('airKnockback', [160, 161, 162, 163], 13, false);
dummy.animations.add('meteorSmash', [93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103], 27, false);
dummy.animations.add('upAir', [105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115], 20, false);
dummy.animations.add('foxKick', [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], 15, false);
dummy.animations.add('haduken', [182, 183, 184, 185, 186, 187, 188], 15, false);
dummy.animations.play('idle');
break;
default:
break;
}
};
this.resetFilp = function () {
this.flipFlop = false;
};
}
function Opponent(name, power, gravity, jumpResistance) {
this.name = name;
this.combo = [];
this.getHitWith = '';
this.isHurt = false;
this.actions = {
runRight: false,
runLeft: false,
holdUp: false,
holdDown: false,
};
this.decision = '';
this.lives = {
left: 3
};
this.stats = {
damage: 0,
lives: 3,
power: power,
evades: 5,
gravity: gravity,
jumpR: jumpResistance,
jumpH: 0,
};
this.isLeft = false;
this.keyPressed = '';
this.isGrounded = false;
this.isJumping = false;
this.isAirAttack = false;
this.isAirDodging = false;
this.isDodging = false;
this.canAirDodge = true;
this.airDownChecks = {
downAirAtk1: false,
downAirAtk2: false,
downAirAtk3: false,
};
this.canPlayerJump = true;
this.completedJump = true;
this.startedJump = false;
this.onlyDoOnce = false;
this.canPlayerJump = true;
this.airDodgeDirect = '';
this.shield = {
shieldHp: 100,
shieldActive: false,
shieldX: 0,
shieldY: 0,
};
this.hitbox = {
X: 0,
Y: 0,
isOverlapping: false,
isAtkBoxActive: false,
};
this.canAirRecover = true;
this.isAirRecovering = false;
this.isInvincible = false;
this.isBulletFired = false;
this.isShotLeft = false;
this.timedBonusAnim;
this.timedBonus = false;
this.velocityStall = false;
this.stallChecked = false;
this.stopMotion = false;
//pass in the act object sent from the other player
//this will update the opponents sprite on our screen based
//on what key they pressed
//call this property in the update function of the demo.game obj
this.updateActions = function (obj) {
this.actions.runRight = obj.runRight;
this.actions.runLeft = obj.runLeft;
this.actions.holdUp = obj.holdUp;
this.actions.holdDown = obj.holdDown;
this.decision = obj.decision;
//then send this ob
};
this.setupRelations = function () {
switch (this.name) {
case 'ghostStock':
this.relatives.stockname = 'ghostStock';
break;
case 'sStock':
this.relatives.stockname = 'sStock';
default:
break;
}
};
this.glideDownJump = function (sprite, fallingGravity, postGravity) {
if (!this.isGrounded || this.combo[0] === 'jump') {
sprite.body.gravity.y = this.stats.gravity;
} else {
sprite.body.gravity.y = this.stats.jumpR;
}
};
this.jumpAnimLoop = function (sprite) {
if (this.completedJump) {
if (!this.isAirAttack && !this.isAirDodging && this.canPlayerJump && !(['airDodge', 'airRecovery', 'airNeutral', 'upAir', 'foxKick', 'meteorSmash'].includes(sprite.animations.currentAnim.name))) {
if ((this.isGrounded && this.startedJump) || (this.isGrounded && this.startedJump && this.combo[0] == 'jump')) {
sprite.animations.play('endJump');
this.startedJump = false;
this.isJumping = false;
this.canPlayerJump = false;
}
else if (!this.isGrounded && this.startedJump) {
sprite.animations.play('loopJump');
} else if (this.combo[0] == 'jump' && !this.isGrounded && !this.startedJump) {
this.startedJump = true;
this.isJumping = true;
//sprite.animations.stop('idle');
sprite.animations.play('startJump');
//completedJump = false;
} else {
return false;
}
} else {
return;
}
}
};
this.downAerialMotion = function (sprite, intensity) {
if (intensity.toLowerCase() == 'low') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 7;
} else {
sprite.x += 7;
}
sprite.y -= 7;
} else {
return;
}
} else if (intensity.toLowerCase() == 'med') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 9;
} else {
sprite.x += 9;
}
sprite.y -= 7;
} else {
return;
}
} else if (intensity.toLowerCase() == 'high') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 11;
} else {
sprite.x += 11;
}
sprite.y -= 8;
} else {
return;
}
} else if (intensity.toLowerCase() == 'ghost') {
if (sprite.animations.currentAnim.name == 'loopDwnKick') {
if (this.isLeft) {
sprite.x -= 7;
} else {
sprite.x += 7;
}
//sprite.y += 5;
sprite.body.velocity.y = 300;
} else {
return;
}
}
};
this.downAerial = function (sprite) {
if (this.isAirAttack) {
if (!this.airDownChecks.isDownAirAtk1) {
this.airDownChecks.isDownAirAtk1 = true;
sprite.animations.play('startDwnKick');
/* if (player.animations.currentAnim.isFinished) { */
this.airDownChecks.isDownAirAtk2 = true;
} else if (this.airDownChecks.isDownAirAtk2 && !this.isGrounded) {
sprite.animations.play('loopDwnKick');
this.combo[0] = 'loopDwnKick';
/* if (player.animations.currentAnim.isFinished) { */
this.airDownChecks.isDownAirAtk2 = false;
this.airDownChecks.isDownAirAtk3 = true;
} else if (this.airDownChecks.isDownAirAtk3 && this.isGrounded && this.completedJump) {
sprite.animations.play('endDwnKick');
this.airDownChecks.isDownAirAtk2 = true;
this.airDownChecks.isDownAirAtk3 = false;
this.airDownChecks.isDownAirAtk1 = false;
this.isAirAttack = false;
}
} else {
return;
}
};
this.jump = function (sprite, maxHeight) {
if (!this.isAirDodging && this.decision == 'jump' && this.stats.jumpH < 30) {
this.stats.jumpH++;
sprite.y -= 15;
} else {
return;
}
};
this.runIdleControl = function (sprite) {
if (!this.stopMotion) {
if (sprite.animations.currentAnim.isFinished) {
if (this.isDodging && (['startJump', 'loopJump', 'dodge', 'block', 'moveDodge'].includes(sprite.animations.currentAnim.name))) {
sprite.animations.stop('idle');
//spriteCombo = [];
this.keyPressed = '';
} else if ((!this.isDodging || !this.isAirDodging) && !this.actions.evade && !this.actions.jump && this.completedJump || (!this.actions.runRight && sprite.animations.currentAnim.name == 'run' || !this.actions.runLeft && sprite.animations.currentAnim.name == 'run')) {
this.onlyDoOnce = false;
this.canPlayerJump = true;
if (!this.isGrounded && !(['knockback', 'pushback1', 'pushback2', 'pushback3'].includes(sprite.animations.currentAnim.name))) {
sprite.animations.play('notloopJump');
} else if (this.isGrounded) {
//sprite.animations.stop('notloopJump');
if (['notloopjump', 'loopJump'].includes(sprite.animations.currentAnim.name)/* && sprite.animations.currentAnim.name == 'notloopjump' */ && sprite.animations.currentAnim.isFinished) {
sprite.animations.play('endJump');
}
sprite.animations.play('idle');
}
this.combo = [];
this.canAirRecover = true;
this.keyPressed = '';
this.timedBonusAnim = '';
this.stallChecked = false;
}
//HANDLES RUN ANIM isspriteAirDodging
} else if (((!this.shield.shieldActive || !this.isAirDodging) && sprite.animations.currentAnim.name == 'idle' || sprite.animations.currentAnim.name == 'run' || sprite.animations.currentAnim.name == 'jump' || this.isGrounded) && !['neutralKick', 'neutralPunch1', 'neutralPunch2', 'neutralPunch3', 'neutralPunch4'].includes(sprite.animations.currentAnim.name) || (!sprite.animations.currentAnim.isFinished)) {
if (this.actions.runRight && ((!['s', 'a'].includes(this.keyPressed)) && sprite.animations.currentAnim.name !== 'runAttack' && (!this.isAirDodging && !this.shield.shieldActive))) {
if (sprite.animations.currentAnim.name !== 'knockback') {
//testing for ghost's foxKick
sprite.scale.setTo(1, 1);
this.isLeft = false;
if (sprite.animations.currentAnim.name == 'airNeutral') {
sprite.x += 13;
//sprite.body.velocity.x = 200;
} else {
sprite.x += 8;
//sprite.body.velocity.x = 400;
}
if ((!['jump', 'startJump', 'loopJump', 'endJump', 'dodge', 'block', 'moveDodge', 'loopDwnKick', 'airDodge'].includes(sprite.animations.currentAnim.name)) && (!game.input.keyboard.isDown(Phaser.Keyboard.X) && this.isGrounded !== false && this.startedJump == false)) {
sprite.animations.play('run');
}
} else {
return;
}
} else if (this.actions.runLeft && ((!['s', 'a'].includes(this.keyPressed)) && sprite.animations.currentAnim.name !== 'runAttack' && (!this.isAirDodging && !this.shield.shieldActive))) {
if (sprite.animations.currentAnim.name !== 'knockback') {
sprite.scale.setTo(-1, 1);
this.isLeft = true;
if (sprite.animations.currentAnim.name == 'airNeutral') {
sprite.x -= 13;
//sprite.body.velocity.x = -200;
} else {
sprite.x -= 8;
//sprite.body.velocity.x = -400;
}
if ((!['jump', 'startJump', 'loopJump', 'endJump', 'dodge', 'block', 'moveDodge', 'loopDwnKick', 'airDodge'].includes(sprite.animations.currentAnim.name)) && (!game.input.keyboard.isDown(Phaser.Keyboard.X) && this.isGrounded !== false && this.startedJump == false)) {
sprite.animations.play('run');
}
} else {
return;
}
} else if ((!this.actions.runRight) || (!this.actions.runRight) || this.keyPressed || this.actions.evade || this.actions.punch || this.actions.special || game.input.keyboard.isDown(keys.w) || this.actions.special || this.startedJump) {
sprite.animations.stop('run');
}
}
} else {
return;
}
};
this.moveAttackBox = function (atkBox, sprite, charObj) {
let posX = sprite.x + this.hitbox.X;
let posY = sprite.y + this.hitbox.Y;
atkBox.x = posX;
atkBox.y = posY;
atkBox.alpha = 0;
atkBox.angle = 0;
//sets the position of the hitbox
atkBox.position = {
x: posX,
y: posY,
type: 25
}
switch (this.combo[0]) {
case 'neutralPunch1':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -50;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch2':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
//atkBox.height = 45;
//atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
//atkBox.height = 45;
// atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
//this.hitbox.X = -110;
//this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
// this.hitbox.X = 80;
//this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch3':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 25;
atkBox.height = 45;
atkBox.width = 45;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
//this.hitbox.X = -110;
// this.hitbox.Y = 104;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralPunch4':
if (this.isLeft) {
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
///atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'neutralPunch5':
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 30;
atkBox.width = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 30;
this.hitbox.Y = 20;
atkBox.height = 30;
atkBox.width = 30;
///atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -20;
this.hitbox.Y = 20;
// atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 20;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'neutralKick':
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 25;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'specialKick1':
if (this.name == "mghosty") {
if (this.isLeft) {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 20;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 10;
atkBox.height = 30;
atkBox.width = 75;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = -25;
this.hitbox.Y = 10;
atkBox.height = 30;
atkBox.width = 75;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'runAttack':
if (this.name == "mghosty") {
if (this.isLeft) {
//atkBox.angle = 45;
this.hitbox.X = -70;
this.hitbox.Y = 0;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 0;
this.hitbox.Y = 0;
atkBox.height = 60;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 0;
atkBox.height = 40;
atkBox.width = 55;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 10;
this.hitbox.Y = 0;
atkBox.height = 40;
atkBox.width = 55;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'loopDwnKick':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -40;
this.hitbox.X = -34;
this.hitbox.Y = 67;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 25;
this.hitbox.X = 4;
this.hitbox.Y = 40;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -25;
this.hitbox.X = -70;
this.hitbox.Y = 65;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 25;
this.hitbox.X = 30;
this.hitbox.Y = 50;
atkBox.height = 25;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'slideKick':
if (this.isLeft) {
this.hitbox.X = -60;
this.hitbox.Y = 80;
atkBox.height = 15;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
this.hitbox.X = 40;
this.hitbox.Y = 80;
atkBox.height = 15;
atkBox.width = 60;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'upNeutral':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -45;
this.hitbox.X = -90;
this.hitbox.Y = 10;
atkBox.height = 60;
atkBox.width = 150;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = 35;
this.hitbox.X = -40;
this.hitbox.Y = -85;
atkBox.height = 60;
atkBox.width = 150;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -75;
this.hitbox.X = -40;
this.hitbox.Y = 30;
atkBox.height = 50;
atkBox.width = 90;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
atkBox.angle = 75;
this.hitbox.X = 30;
this.hitbox.Y = -60;
atkBox.height = 50;
atkBox.width = 90;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'airNeutral':
//for scott, its a spike
if (this.name == "mghosty") {
if (this.isLeft) {
this.hitbox.X = -50;
this.hitbox.Y = 40;
atkBox.height = 15;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 0;
this.hitbox.Y = 40;
atkBox.height = 15;
atkBox.width = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
this.hitbox.X = -45;
this.hitbox.Y = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 23;
this.hitbox.Y = 50;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'airRecovery':
if (this.name == "mghosty") {
if (this.isLeft) {
atkBox.angle = -95;
this.hitbox.X = -50;
this.hitbox.Y = 40;
atkBox.height = 30;
atkBox.width = 65;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
atkBox.angle = -50;
this.hitbox.X = 0;
this.hitbox.Y = 40;
atkBox.height = 30;
atkBox.width = 65;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
} else {
if (this.isLeft) {
atkBox.angle = -75;
this.hitbox.X = -50;
this.hitbox.Y = 30;
atkBox.height = 60;
atkBox.width = 120;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
//atkBox.angle = 45;
atkBox.angle = 75;
this.hitbox.X = 27;
this.hitbox.Y = -90;
atkBox.height = 60;
atkBox.width = 120;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
}
break;
case 'meteorSmash':
if (this.isLeft) {
this.hitbox.X = -40;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 20;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'upAir':
if (this.isLeft) {
this.hitbox.X = 0;
this.hitbox.Y = -80;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = -25;
this.hitbox.Y = -80;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'foxKick':
if (this.isLeft) {
this.hitbox.X = 45;
this.hitbox.Y = 25;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = -65;
this.hitbox.Y = 30;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
case 'haduken':
if (this.isLeft) {
this.hitbox.X = -55;
this.hitbox.Y = 10;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
} else {
this.hitbox.X = 40;
this.hitbox.Y = 10;
//atkBox.alpha = 0.6;
this.resetHitbox(atkBox);
}
break;
default:
break;
}
};
this.moveRunAttack = function (sprite, animName, speed) {
if (sprite.animations.currentAnim.name == animName && this.actions.runRight) {
sprite.x += speed;
} else if (sprite.animations.currentAnim.name == animName && this.actions.runLeft) {
sprite.x -= speed;
}
};
this.moveDodge = function (sprite) {
if (!this.actions && !this.isAirDodging && this.isDodging && !this.shield.shieldActive) {
sprite.animations.play('moveDodge');
this.timedBonusAnim = (sprite.animations.currentAnim.name);
if (this.isLeft) {
sprite.body.velocity.setTo(-420, 0);
} else {
sprite.body.velocity.setTo(420, 0);
}
}
this.isDodging = false;
};
this.airDodged = function (sprite) {
if (this.isAirDodging && sprite.animations.currentAnim.name !== 'airDodge') {
this.toggleSpriteMotion(sprite);
if (this.airDodgeDirect === 'right') {
sprite.animations.play('airDodge');
game.add.tween(sprite).to({ x: '-80' }, 500, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 500, sprite);
//sprite.body.velocity.setTo(-125, 0);
//game.add.tween(sprite).onComplete.add(toggleSpriteMotion, this);
this.isAirDodging = false;
this.airDodgeDirect = '';
} else if (this.airDodgeDirect === 'left') {
sprite.animations.play('airDodge');
game.add.tween(sprite).to({ x: '80' }, 500, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 500, sprite);
//game.add.tween(sprite).onComplete.add(toggleSpriteMotion, this);
//sprite.body.velocity.setTo(125, 0);
this.isAirDodging = false;
this.airDodgeDirect = '';
} else {
return;
}
}
};
this.upRecovery = function (sprite) {
if (this.isAirRecovering && sprite.animations.currentAnim.name !== 'airRecovery') {
//change param to sprite
this.toggleSpriteMotion(scott);
if (!this.isLeft) {
sprite.animations.play('airRecovery');
this.combo[0] = (sprite.animations.currentAnim.name);
game.add.tween(sprite).to({ x: '80', y: '-180' }, 400, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 400, scott);
this.isAirRecovering = false;
} else if (this.isLeft) {
sprite.animations.play('airRecovery');
this.combo[0] = (sprite.animations.currentAnim.name);
game.add.tween(sprite).to({ x: '-80', y: '-180' }, 400, Phaser.Easing.Cubic.Out, true);
this.doTimeout(this.toggleSpriteMotion, 400, scott);
this.isAirRecovering = false;
} else {
return;
}
}
};
this.resetAirDodge = function (sprite) {
if (this.isGrounded && sprite.animations.currentAnim.name !== 'airDodge') {
this.canAirDodge = true;
}
if (sprite.animations.currentAnim.name == 'airDodge' && sprite.animations.currentAnim.loopCount >= 1) {
sprite.animations.stop('airDodge');
}
};
this.toggleSpriteMotion = function (sprite) {
sprite.body.gravity.y > 0 ? sprite.body.gravity.y = 0 : sprite.body.gravity.y = this.stats.gravity;
sprite.body.moves ? sprite.body.moves = false : sprite.body.moves = true;
this.stopMotion ? this.stopMotion = true : this.stopMotion = false;
};
this.doTimeout = function (func, time, param1) {
setTimeout(function () {
func(param1);
}, time);
};
//shield = sprite name for shield
//sprite = sprite name of user
this.showShield = function (shield, sprite) {
let posX = sprite.x + this.shield.shieldX;
let posY = sprite.y + this.shield.shieldY;
shield.x = posX;
shield.y = posY;
shield.position = {
x: posX,
y: posY,
type: 25
}
// if the the shield is active and the Z key is held down
if (this.isGrounded && this.shield.shieldActive && this.actions.evade) {
//play the shield animation
sprite.animations.play('holdShield');
shield.animations.play('on');
if (this.isLeft) {
this.shield.shieldX = -10;
this.shield.shieldY = 0;
} else {
this.shield.shieldX = -20;
this.shield.shieldY = 0;
}
if (this.shield.shieldActive && this.shield.shieldHP > 76) {
//set the alpha to 1
shield.alpha = 1;
} else if (this.shield.shieldActive && 50 <= this.shield.shieldHP <= 75) {
//set alpha to 0.7 if shieldHP is between 50 and 75
//the idea here is the the shield will appear 'weaker' or 'more tranasparent', the less HP it has
shield.alpha = 0.7;
} else if (this.shield.shieldActive && 25 <= this.shield.shieldHP <= 50) {
shield.alpha = 0.5;
} else if (this.shield.shieldActive && 0 < this.shield.shieldHP < 24) {
shield.alpha = 0.3;
} else if (this.shield.shieldActive && this.shield.shieldHP <= 0) {
shield.alpha = 0;
shieldActive = false;
shield.destroy();
}
} else {
shield.animations.stop('on');
shield.alpha = 0;
this.shield.shieldActive = false;
return;
}
};
//this object's assigned sprite
this.velocityStallControl = function (sprite) {
if (this.isHurt) {
if (-1 < sprite.body.speed < 100 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
//this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1000);
} else if (100 < sprite.body.speed < 200 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1200);
} else if (200 < sprite.body.speed < 300 && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1300);
}
else if (300 < sprite.body.speed && ['airRecovery', 'upNeutral', 'airNeutral'].includes(this.getHitWith) && !this.stallChecked) {
this.stopMotion = true;
this.stallChecked = true;
setTimeout(function () {
this.stopMotion = false;
this.getHitWith = '';
this.isHurt = false;
}, 1800);
} else {
return;
}
} else {
return;
}
};
this.resetGetHit = function (charObj) {
setTimeout(function () {
charObj.getHitWith = '';
}, 1000);
}
this.pushbackControl = function (sprite) {
if (['upNeutral', 'airRecovery', 'airNeutral'].includes(this.getHitWith)) {
if (50 <= this.stats.damage <= 98) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('knockback');
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else if (99 <= this.stats.damage <= 199) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
sprite.animations.play('pushback3');
}
} else if (200 <= this.stats.damage <= 299) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else if (this.stats.damage > 300) {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('pushback1');
sprite.animations.play('pushback2');
}
} else {
if (this.name == 'mghosty' && !this.isGrounded) {
sprite.animations.play('airKnockback');
} else {
sprite.animations.play('knockback');
}
}
} else {
sprite.animations.play('knockback');
}
};
this.resetHitbox = function (hitbox) {
setTimeout(function () {
hitbox.width = 25;
hitbox.height = 25;
hitbox.alpha = 0;
hitbox.angle = 0;
atkBoxCanHurt = false;
}, 100);
};
this.loadStock = function () {
switch (this.name) {
case 'scott':
game.load.spritesheet('sStk', '../assets/art/sStock.png', 32, 32);
break;
case 'mghosty':
game.load.spritesheet('gStk', '../assets/art/ghostStock.png', 32, 32);
break;
default:
break;
}
};
this.invincibilityCtrl = function (sprite) {
if (sprite.animations.currentAnim.name == 'airDodge') {
this.isInvincible = true;
} else {
this.isInvincible = false;
}
}
this.addSFX = function () {
if (this.name == 'mghosty') {
slash = game.add.audio('sword');
ejectBall = game.add.audio('throwball');
ghostDodge = game.add.audio('gdodge');
barr = game.add.audio('barrier');
natk1 = game.add.audio('gnatk1');
jumpSnd = game.add.audio('jumpa');
ghAirRec = game.add.audio('ghAir');
ghRunAtk = game.add.audio('ghRunAtk');
ghDownKick = game.add.audio('ghDownKick');
ghAtk2 = game.add.audio('ghAtk2');
foxKicks = game.add.audio('foxKicks');
ghAirNeu = game.add.audio('ghAirNeu');
ghWhip = game.add.audio('ghWhip');
ghMeteor = game.add.audio('ghMeteor');
shieldHit = game.add.audio('nullHit');
normalHit = game.add.audio('elecHit');
} else {
slash = game.add.audio('sword');
ejectBall = game.add.audio('throwball');
ghostDodge = game.add.audio('grDodge');
sdodge = game.add.audio('grDodge');
barr = game.add.audio('barrier');
natk1 = game.add.audio('stPunch');
jumpSnd = game.add.audio('jumpa');
ghAirRec = game.add.audio('airRecov');
ghRunAtk = game.add.audio('stRunAtk');
ghDownKick = game.add.audio('ghDownKick');
ghAtk2 = game.add.audio('ghAtk2');
foxKicks = game.add.audio('foxKicks');
ghAirNeu = game.add.audio('ghAirNeu');
ghWhip = game.add.audio('stPunch');
ghMeteor = game.add.audio('ghMeteor');
stKick = game.add.audio('stKick');
sldKick = game.add.audio('stSlideKick');
stRunAtk = game.add.audio('stRunAtk');
stSpecKick = game.add.audio('stSpecKick');
stUpNeu = game.add.audio('stUpNeu');
shieldHit = game.add.audio('nullHit');
normalHit = game.add.audio('elecHit');
}
}
// theres a copy of this function on the demo.create object. delte when complete
this.createFighter = function () {
let name = this.name;
console.log(name);
switch (name) {
case 'scott':
dummy = game.add.sprite(700, 400, 'tester');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7], 12, true);
dummy.animations.add('run', [8, 9, 10, 11, 12, 13, 14, 15], 14, false);
dummy.animations.add('startJump', [17, 18, 19, 20, 21, 22, 23, 24], 18, false);
dummy.animations.add('loopJump', [24, 25], 12, true);
dummy.animations.add('notloopJump', [24, 25], 12, false);
dummy.animations.add('endJump', [27], 12, false);
dummy.animations.add('neutralPunch1', [28, 29, 30, 31], 11, false);
dummy.animations.add('neutralPunch2', [32, 33, 34, 35], 11, false);
dummy.animations.add('neutralPunch3', [36, 37, 38], 11, false);
dummy.animations.add('neutralPunch4', [39, 40], 11, false);
dummy.animations.add('neutralPunch5', [41, 42, 43, 44], 11, false);
dummy.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [63, 64, 65, 66, 67, 68, 69], 14, false);
dummy.animations.add('runAttack', [70, 71, 72, 73, 74, 75, 76, 77, 78], 16, false);
dummy.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
dummy.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
dummy.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [96, 97, 98, 99, 100], 10, false);
dummy.animations.add('startDwnKick', [100, 101, 102], 12, false);
dummy.animations.add('loopDwnKick', [103, 104, 105], 12, true);
dummy.animations.add('endDwnKick', [106], 12, false);
dummy.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
dummy.animations.add('moveDodge', [114, 115, 116, 117, 118, 119, 120], 20, false);
dummy.animations.add('holdShield', [121, 122, 123, 124], 15, false);
dummy.animations.add('airDodge', [125, 126, 127], 14, true);
dummy.animations.add('airRecovery', [136, 137, 138, 139, 140, 141, 142], 14, false);
dummy.animations.add('upNeutral', [128, 129, 130, 131, 132, 133, 134, 135], 18, false);
dummy.animations.add('airNeutral', [142, 143, 144, 145, 146, 147], 18, false);
dummy.animations.add('pushback1', [148], 3, false);
dummy.animations.add('pushback2', [149], 3, false);
dummy.animations.add('pushback3', [150], 3, false);
dummy.animations.play('idle');
break;
case 'deku':
break;
case 'mghosty':
dummy = game.add.sprite(400, 400, 'ghosty');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7, 8], 12, true);
dummy.animations.add('run', [9, 10, 11, 12, 13], 14, false);
//player.animations.add('jump', [16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 12, false);
dummy.animations.add('startJump', [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], 20, false);
dummy.animations.add('loopJump', [49, 50, 51, 52, 53, 54], 15, true);
dummy.animations.add('notloopJump', [49, 50, 51, 52, 53, 54], 12, false);
dummy.animations.add('endJump', [164, 165, 166, 167, 168, 169, 170, 171, 39, 38, 37, 36, 35, 34, 33, 32], 60, false);
//neutralpunch2 would follow nuetralpunch1 after it finishes running, like a combo
//would require input, let's say that hitting 'a' for example, would trigger neutralPunch1, if pressed again at the right...
//..moment, would trigger neutralPunch2, and so forth
dummy.animations.add('neutralPunch1', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch2', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch3', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch4', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch5', [123, 124, 125, 126, 127, 128, 129, 130, 131, 132], 25, false);
//scott.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [32, 33, 34, 35, 36, 37, 38, 39, 189, 39, 38, 37, 36, 35, 34, 33, 32], 14, false);
dummy.animations.add('runAttack', [139, 140, 141, 142, 143, 144, 145, 146], 16, false);
//scott.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
//scott.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
//scott.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [156, 157, 158, 159], 14, false);
dummy.animations.add('startDwnKick', [84], 12, false);
dummy.animations.add('loopDwnKick', [85, 86, 87], 12, true);
//warning, ghost has to transform back to his old self, this anim may be absolete
dummy.animations.add('endDwnKick', [88, 90], 12, false);
//scott.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
//testing to see if we can run anims like this
//may not to splite this anim to two and call them sequentially
dummy.animations.add('moveDodge', [32, 33, 34, 35, 36, 37, 38, 39, 38, 37, 36, 35, 34, 33, 32], 20, false);
dummy.animations.add('holdShield', [172, 173, 174, 175, 176, 177, 178, 179], 15, false);
dummy.animations.add('airDodge', [116, 117, 118, 119, 120], 14, true);
dummy.animations.add('airRecovery', [76, 77, 78, 79, 80, 81, 82], 14, false);
dummy.animations.add('upNeutral', [148, 149, 150, 151, 152, 153, 154], 18, false);
dummy.animations.add('airNeutral', [55, 56, 57, 58, 59, 60, 61, 62, 63, 64], 25, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
//UNIQUE TO GHOST
dummy.animations.add('airKnockback', [160, 161, 162, 163], 13, false);
dummy.animations.add('meteorSmash', [93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103], 27, false);
dummy.animations.add('upAir', [105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115], 20, false);
dummy.animations.add('foxKick', [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], 15, false);
dummy.animations.add('haduken', [182, 183, 184, 185, 186, 187, 188], 15, false);
dummy.animations.play('idle');
break;
default:
break;
};
this.enablePhysics = function (sprite) {
if (this.name == 'scott') {
sprite.body.setSize(60, 120, 20, 69);
} else if (this.name == 'mghosty') {
sprite.body.setSize(60, 120, 20, 47);
}
sprite.body.drag.x = 500;
};
this.resetFilp = function () {
this.flipFlop = false;
};
this.enableSoundControls = function () {
CPUbar.run(barr, dummy).listen(dummy);
CPUjumpSndC.run(jumpSnd, dummy).listen(dummy);
CPUnatk1C.run(natk1, dummy).listen(dummy);
CPUghAirRecC.run(ghAirRec, dummy).listen(dummy);
CPUghRunAtkC.run(ghRunAtk, dummy).listen(dummy);
CPUghDownKickC.run(ghDownKick, dummy).listen(dummy);
CPUghAtk2C.run(ghAtk2, dummy).listen(dummy);
CPUnatk2C.run(natk1, dummy).listen(dummy);
CPUghUpKickC.run(foxKicks, dummy).listen(dummy);
CPUghbackKickC.run(ghAirNeu, dummy).listen(dummy);
CPUghAirNeuC.run(ghAirNeu, dummy).listen(dummy);
CPUghWhipC.run(ghWhip, dummy).listen(dummy);
CPUghMeteorC.run(ghMeteor, dummy).listen(dummy);
CPUstKickC.run(stKick, dummy).listen(dummy);
CPUsldKickC.run(sldKick, dummy).listen(dummy);
if (this.name == 'scott') {
CPUstRunAtkC.run(stRunAtk, dummy).listen(dummy);
CPUstSpecKickC.run(stSpecKick, dummy).listen(dummy);
}
//hbFxKickCtrl.run(scott, atkBox).listen(scott, atkBox);
}
};
this.ghostLand = function (sprite) {
if (this.name == 'mghosty' && this.isGrounded && ['notloopJump'].includes(sprite.animations.currentAnim.name)) {
sprite.animations.play('endJump');
} else {
return;
}
};
this.ghSpecialListener = function (sprite, enemy, sound) {
let done = false;
if (this.name == 'mghosty' && sprite.animations.currentFrame.index == 189) {
ghostSpecialAtk.x = enemy.x;
ghostSpecialAtk.y = sprite.y - 65;
ghostSpecialAtk.alpha = 1;
ghostSpecialAtk.revive();
game.add.tween(ghostSpecialAtk).to({ alpha: 0 }, 800, "Linear", true);
ghostSpecialAtk.animations.play('show');
} else {
return;
}
};
this.createOther = function () {
let name = this.name;
console.log(name);
switch (name) {
case 'scott':
dummy = game.add.sprite(400, 100, 'tester');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7], 12, true);
dummy.animations.add('run', [8, 9, 10, 11, 12, 13, 14, 15], 14, false);
dummy.animations.add('startJump', [17, 18, 19, 20, 21, 22, 23, 24], 18, false);
dummy.animations.add('loopJump', [24, 25], 12, true);
dummy.animations.add('notloopJump', [24, 25], 12, false);
dummy.animations.add('endJump', [27], 12, false);
dummy.animations.add('neutralPunch1', [28, 29, 30, 31], 11, false);
dummy.animations.add('neutralPunch2', [32, 33, 34, 35], 11, false);
dummy.animations.add('neutralPunch3', [36, 37, 38], 11, false);
dummy.animations.add('neutralPunch4', [39, 40], 11, false);
dummy.animations.add('neutralPunch5', [41, 42, 43, 44], 11, false);
dummy.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [63, 64, 65, 66, 67, 68, 69], 14, false);
dummy.animations.add('runAttack', [70, 71, 72, 73, 74, 75, 76, 77, 78], 16, false);
dummy.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
dummy.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
dummy.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [96, 97, 98, 99, 100], 14, false);
dummy.animations.add('startDwnKick', [100, 101, 102], 12, false);
dummy.animations.add('loopDwnKick', [103, 104, 105], 12, true);
dummy.animations.add('endDwnKick', [106], 12, false);
dummy.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
dummy.animations.add('moveDodge', [114, 115, 116, 117, 118, 119, 120], 20, false);
dummy.animations.add('holdShield', [121, 122, 123, 124], 15, false);
dummy.animations.add('airDodge', [125, 126, 127], 14, true);
dummy.animations.add('airRecovery', [136, 137, 138, 139, 140, 141, 142], 14, false);
dummy.animations.add('upNeutral', [128, 129, 130, 131, 132, 133, 134, 135], 18, false);
dummy.animations.add('airNeutral', [142, 143, 144, 145, 146, 147], 18, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
dummy.animations.play('idle');
break;
case 'mghosty':
dummy = game.add.sprite(400, 100, 'ghosty');
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7, 8], 12, true);
dummy.animations.add('run', [9, 10, 11, 12, 13], 14, false);
//player.animations.add('jump', [16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 12, false);
dummy.animations.add('startJump', [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48], 20, false);
dummy.animations.add('loopJump', [49, 50, 51, 52, 53, 54], 15, true);
dummy.animations.add('notloopJump', [49, 50, 51, 52, 53, 54], 12, false);
dummy.animations.add('endJump', [164, 165, 166, 167, 168, 169, 170, 171, 39, 38, 37, 36, 35, 34, 33, 32], 60, false);
//neutralpunch2 would follow nuetralpunch1 after it finishes running, like a combo
//would require input, let's say that hitting 'a' for example, would trigger neutralPunch1, if pressed again at the right...
//..moment, would trigger neutralPunch2, and so forth
dummy.animations.add('neutralPunch1', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch2', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch3', [14, 15, 16, 17, 18, 19, 20, 21], 15, false);
dummy.animations.add('neutralPunch4', [22, 23, 24, 25, 26, 27, 28, 29, 30], 25, false);
dummy.animations.add('neutralPunch5', [123, 124, 125, 126, 127, 128, 129, 130, 131, 132], 25, false);
//scott.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 14, false);
dummy.animations.add('specialKick1', [32, 33, 34, 35, 36, 37, 38, 39, 189, 39, 38, 37, 36, 35, 34, 33, 32], 14, false);
dummy.animations.add('runAttack', [139, 140, 141, 142, 143, 144, 145, 146], 16, false);
//scott.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
//scott.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
//scott.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [156, 157, 158, 159], 14, false);
dummy.animations.add('startDwnKick', [84], 12, false);
dummy.animations.add('loopDwnKick', [85, 86, 87], 12, true);
//warning, ghost has to transform back to his old self, this anim may be absolete
dummy.animations.add('endDwnKick', [88, 90], 12, false);
//scott.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
//testing to see if we can run anims like this
//may not to splite this anim to two and call them sequentially
dummy.animations.add('moveDodge', [32, 33, 34, 35, 36, 37, 38, 39, 38, 37, 36, 35, 34, 33, 32], 20, false);
dummy.animations.add('holdShield', [172, 173, 174, 175, 176, 177, 178, 179], 15, false);
dummy.animations.add('airDodge', [116, 117, 118, 119, 120], 14, true);
dummy.animations.add('airRecovery', [76, 77, 78, 79, 80, 81, 82], 14, false);
dummy.animations.add('upNeutral', [148, 149, 150, 151, 152, 153, 154], 18, false);
dummy.animations.add('airNeutral', [55, 56, 57, 58, 59, 60, 61, 62, 63, 64], 25, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
//UNIQUE TO GHOST
dummy.animations.add('airKnockback', [160, 161, 162, 163], 13, false);
dummy.animations.add('meteorSmash', [93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103], 27, false);
dummy.animations.add('upAir', [105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115], 20, false);
dummy.animations.add('foxKick', [64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74], 15, false);
dummy.animations.add('haduken', [182, 183, 184, 185, 186, 187, 188], 15, false);
dummy.animations.play('idle');
break;
default:
break;
}
};
this.resetFilp = function () {
this.flipFlop = false;
};
}
//key listener that riggers animations and boolean changes
//sprite = name of sprite
//charObj =
function keyListener(sprite, charObj, isCustom, kick, special, std, jump, evade) {
game.input.keyboard.onPressCallback = function (e) {
switch (e) {
//standard kick
case kick:
act.decision = 'kick';
//if the player is'nt jumping or running
//then the player will kick normally
if (!charObj.isJumping && sprite.animations.currentAnim.name !== 'run' && charObj.name !== 'mghosty') {
if (sprite.animations.currentAnim.name == 'moveDodge' && [114, 115, 116, 117, 118, 119, 120].includes(sprite.animations.currentAnim.currentFrame.index)) {
charObj.timedBonus = true;
}
sprite.animations.play('neutralKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
charObj.keyPressed = 's';
//if he is jumping, then will set isPlayerAirAttack to true
//charObj will allow downAerial() to run and the initiate the DownAirKick animation
} else if (charObj.isJumping) {
charObj.isAirAttack = true;
//if the player is running either to the left or right side, and if the current animation is not already 'slidekick'
//then play the 'slideKick' animation
//would not want to play the same animation if its already playing....
} else if ((game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) || game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) && sprite.animations.currentAnim.name != 'slideKick' && sprite.animations.currentAnim.name == 'run' && charObj.name !== 'mghosty') {
charObj.keyPressed = 's';
sprite.animations.play('slideKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
break;
// 'd' will be the special button. Hit charObj button attack the right time, and you might unleash a speciall attack or combo
case special:
//will only play if the last attack(animation) was neutralPunch3
act.decision = 'special';
if (charObj.combo[0] == 'neutralPunch3' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch3' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'd';
sprite.animations.play('specialKick1');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
//forward attack OR attack while running
} else if ((game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) || game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) && sprite.animations.currentAnim.name != 'runAttack' && sprite.animations.currentAnim.name == 'run') {
charObj.keyPressed = 'd';
sprite.animations.play('runAttack');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else if ((game.input.keyboard.isDown(Phaser.Keyboard.UP) && !charObj.flipFlop)) {
if (charObj.canAirRecover) {
charObj.isAirRecovering = true;
charObj.canAirRecover = false;
charObj.flipFlop = true;
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch5' && sprite.animations.currentAnim.name !== 'idle') {
charObj.keyPressed = 'd';
if (charObj.name == 'mghosty') {
slash.play();
} else {
stUpNeu.play();
}
sprite.animations.play('upNeutral');
charObj.combo[0] = (sprite.animations.currentAnim.name);
/* charObj.combo[0] = (sprite.animations.currentAnim.name); */
} else if (charObj.name == 'mghosty' && charObj.isGrounded) {
if (charObj.isLeft) {
charObj.isShotLeft = true;
} else {
charObj.isShotLeft = false;
}
charObj.keyPressed = 'd';
charObj.isBulletFired = true;
sprite.animations.play('haduken');
ejectBall.play();
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else if (charObj.name == 'mghosty' && !charObj.isGrounded && !game.input.keyboard.isDown(Phaser.Keyboard.UP) && !game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
charObj.keyPressed = 'd';
sprite.animations.play('foxKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
break;
//standard attack
case std:
act.decision = 'punch';
//charObj.keyPressed = 'a';
if (charObj.combo[0] == 'neutralPunch1' && sprite.animations.currentAnim.name != 'idle' && sprite.animations.currentAnim.name != 'jump') {
if (sprite.animations.currentAnim.name === 'neutralPunch1' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch2');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch2' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch2' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch3');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch3' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch3' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch4');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch4' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch4' || sprite.animations.currentAnim.isFinished) {
sprite.animations.play('neutralPunch5');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (sprite.animations.currentAnim.name != 'idle' && !charObj.isGrounded && game.input.keyboard.isDown(Phaser.Keyboard.UP) && charObj.name == 'mghosty') {
sprite.animations.play('upAir');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else if (charObj.name == 'mghosty' && !charObj.isGrounded && game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
sprite.animations.play('meteorSmash');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else if (sprite.animations.currentAnim.name != 'idle' && !charObj.isGrounded && !game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
sprite.animations.play('airNeutral');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else {
if ((sprite.animations.currentAnim.name === 'idle' || sprite.animations.currentAnim.name === 'run') || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch1');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
console.log('not ready');
}
}
break;
case jump:
act.decision = 'jump';
//initizates the jumping animation by setting charObj.isJumping to true
//stoping the 'idle anim if its currently playing
//sets charObj.isGrounded to false since the player is not longer on the floor
if (!charObj.onlyDoOnce && !charObj.flipFlop) {
charObj.isJumping = true;
sprite.animations.stop('idle');
charObj.isGrounded = false;
charObj.combo[0] = 'jump';
//charObj.keyPressed = '';
charObj.onlyDoOnce = true;
charObj.flipFlop = true;
//player.animations.play('jump');
} else {
return;
}
break;
case evade:
act.decision = 'evade';
//initiates the 'block' anim
//will be used to block attacks
//possibly counter them as well, might add another mechanic for that soon
charObj.keyPressed = 'z';
if (game.input.keyboard.isDown(Phaser.Keyboard.D) && charObj.name !== 'mghosty') {
sprite.animations.stop('idle');
sprite.animations.play('dodge');
} else if (!charObj.isAirDodging && charObj.isGrounded && (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) || game.input.keyboard.isDown(Phaser.Keyboard.LEFT))) {
charObj.isDodging = true;
if (charObj.name == 'mghosty') {
ghostDodge.play();
} else {
sdodge.play();
}
} else if (charObj.canAirDodge && !charObj.isGrounded && (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT) || game.input.keyboard.isDown(Phaser.Keyboard.LEFT))) {
if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
charObj.isAirDodging = true;
charObj.airDodgeDirect = 'right';
charObj.canAirDodge = false;
} else if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
charObj.isAirDodging = true;
charObj.airDodgeDirect = 'left';
charObj.canAirDodge = false;
}
} else if (charObj.isGrounded) {
//bar.reset().listen(sprite).run(barr);
//console.log(bar);
charObj.shield.shieldActive = true;
}
break;
default:
act.decision = '';
break;
}
}
};
function COMPListener(sprite, charObj) {
//charObj === COMP
//Sprite === dummy
//this will handle what the oppoent on our end will do
//If our oponent does something, it will look for the decision in the COMP obj
switch (charObj.decision) {
//standard kick
case 'kick':
//if the player is'nt jumping or running
//then the player will kick normally
if (!charObj.isJumping && sprite.animations.currentAnim.name !== 'run' && charObj.name !== 'mghosty') {
if (sprite.animations.currentAnim.name == 'moveDodge' && [114, 115, 116, 117, 118, 119, 120].includes(sprite.animations.currentAnim.currentFrame.index)) {
charObj.timedBonus = true;
}
sprite.animations.play('neutralKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
charObj.keyPressed = 's';
//if he is jumping, then will set isPlayerAirAttack to true
//charObj will allow downAerial() to run and the initiate the DownAirKick animation
} else if (charObj.isJumping) {
charObj.isAirAttack = true;
//if the player is running either to the left or right side, and if the current animation is not already 'slidekick'
//then play the 'slideKick' animation
//would not want to play the same animation if its already playing....
} else if ((charObj.actions.runRight || charObj.actions.runLeft) && sprite.animations.currentAnim.name != 'slideKick' && sprite.animations.currentAnim.name == 'run' && charObj.name !== 'mghosty') {
charObj.keyPressed = 's';
sprite.animations.play('slideKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
break;
// 'd' will be the special button. Hit charObj button attack the right time, and you might unleash a speciall attack or combo
case 'special':
//will only play if the last attack(animation) was neutralPunch3
if (charObj.combo[0] == 'neutralPunch3' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch3' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'd';
sprite.animations.play('specialKick1');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
//forward attack OR attack while running
} else if ((charObj.actions.runRight || charObj.actions.runLeft) && sprite.animations.currentAnim.name != 'runAttack' && sprite.animations.currentAnim.name == 'run') {
charObj.keyPressed = 'd';
sprite.animations.play('runAttack');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else if ((charObj.actions.holdUp && !flipFlop)) {
if (charObj.canAirRecover) {
charObj.isAirRecovering = true;
charObj.canAirRecover = false;
flipFlop = true;
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch5' && sprite.animations.currentAnim.name !== 'idle') {
charObj.keyPressed = 'd';
if (charObj.name == 'mghosty') {
slash.play();
} else {
stUpNeu.play();
}
sprite.animations.play('upNeutral');
charObj.combo[0] = (sprite.animations.currentAnim.name);
/* charObj.combo[0] = (sprite.animations.currentAnim.name); */
} else if (charObj.name == 'mghosty' && charObj.isGrounded) {
if (charObj.isLeft) {
charObj.isShotLeft = true;
} else {
charObj.isShotLeft = false;
}
charObj.keyPressed = 'd';
charObj.isBulletFired = true;
sprite.animations.play('haduken');
ejectBall.play();
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else if (charObj.name == 'mghosty' && !charObj.isGrounded && !charObj.actions.holdUp && !charObj.actions.holdDown) {
charObj.keyPressed = 'd';
sprite.animations.play('foxKick');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
break;
//standard attack
case 'punch':
//charObj.keyPressed = 'a';
if (charObj.combo[0] == 'neutralPunch1' && sprite.animations.currentAnim.name != 'idle' && sprite.animations.currentAnim.name != 'jump') {
if (sprite.animations.currentAnim.name === 'neutralPunch1' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch2');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch2' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch2' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch3');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch3' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch3' || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch4');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (charObj.combo[0] == 'neutralPunch4' && sprite.animations.currentAnim.name != 'idle') {
if (sprite.animations.currentAnim.name === 'neutralPunch4' || sprite.animations.currentAnim.isFinished) {
sprite.animations.play('neutralPunch5');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
return;
}
} else if (sprite.animations.currentAnim.name != 'idle' && !charObj.isGrounded && charObj.actions.holdUp && charObj.name == 'mghosty') {
sprite.animations.play('upAir');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else if (charObj.name == 'mghosty' && !charObj.isGrounded && charObj.actions.holdDown) {
sprite.animations.play('meteorSmash');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else if (sprite.animations.currentAnim.name != 'idle' && !charObj.isGrounded && !charObj.actions.holdUp) {
sprite.animations.play('airNeutral');
charObj.combo[0] = (sprite.animations.currentAnim.name);
}
else {
if ((sprite.animations.currentAnim.name === 'idle' || sprite.animations.currentAnim.name === 'run') || sprite.animations.currentAnim.isFinished) {
charObj.keyPressed = 'a';
sprite.animations.play('neutralPunch1');
charObj.combo[0] = (sprite.animations.currentAnim.name);
} else {
console.log('not ready');
}
}
break;
case 'jump':
//initizates the jumping animation by setting charObj.isJumping to true
//stoping the 'idle anim if its currently playing
//sets charObj.isGrounded to false since the player is not longer on the floor
if (!charObj.onlyDoOnce && !flipFlop) {
charObj.isJumping = true;
sprite.animations.stop('idle');
charObj.isGrounded = false;
charObj.combo[0] = 'jump';
//charObj.keyPressed = '';
charObj.onlyDoOnce = true;
flipFlop = true;
//player.animations.play('jump');
} else {
return;
}
break;
case 'evade':
//initiates the 'block' anim
//will be used to block attacks
//possibly counter them as well, might add another mechanic for that soon
charObj.keyPressed = 'z';
if (charObj.actions.doSpecial && charObj.name !== 'mghosty') {
sprite.animations.stop('idle');
sprite.animations.play('dodge');
} else if (!charObj.isAirDodging && charObj.isGrounded && (charObj.actions.runRight || charObj.actions.runLeft)) {
charObj.isDodging = true;
if (charObj.name == 'mghosty') {
ghostDodge.play();
} else {
sdodge.play();
}
} else if (charObj.canAirDodge && !charObj.isGrounded && (charObj.actions.runRight || charObj.actions.runLeft)) {
if (charObj.actions.runRight) {
charObj.isAirDodging = true;
charObj.airDodgeDirect = 'right';
charObj.canAirDodge = false;
} else if (charObj.actions.runLeft) {
charObj.isAirDodging = true;
charObj.airDodgeDirect = 'left';
charObj.canAirDodge = false;
}
} else if (charObj.isGrounded) {
//bar.reset().listen(sprite).run(barr);
//console.log(bar);
charObj.shield.shieldActive = true;
}
break;
//TESTING ENEMY ATTACKS
/* case 't':
dummyCombo[0] = 'hit';
dummy.animations.play('neutralPunch1');
setTimeout(function () {
dummyCombo = [];
}, 100);
break; */
default:
break;
}
};
let player,
players = [],
scott,
dummy,
ghost,
//var containing the hitbox that we will render whwnever the plaer lanches an attack
atkBox,
scndBox,
//var that will contain the most recent anim name of an attack
//var that will contain the stages platform
platform,
platform1,
platform2,
platform3,
battlefield,
cpuHit,
//checks to see if player is currently touching a platform
//isGrounded = false,
dummyGrounded = false;
//checks to see if player is currenlty jumping
//meant for hitboxes, position relative to the sprite its a hitbox for
const lzzzzs = {
'up': Phaser.KeyCode.UP,
'down': Phaser.KeyCode.DOWN,
'left': Phaser.KeyCode.LEFT,
'right': Phaser.KeyCode.RIGHT,
'a': Phaser.KeyCode.A,
's': Phaser.KeyCode.S,
'w': Phaser.KeyCode.W,
'd': Phaser.KeyCode.D,
'x': Phaser.KeyCode.X
};
demo.game = function () { };
demo.game.prototype = {
preload: function () {
//preloads spritesheets to be used in create
game.load.spritesheet('tester', '../assets/art/scott-final.png', 142, 184, 151);
game.load.spritesheet('tester2', '../assets/art/test-scott-2.png', 142, 184, 151);
game.load.spritesheet('ground', '../assets/art/big-platform.png');
game.load.spritesheet('hbox', '../assets/art/hbox.png', 25, 25);
game.load.spritesheet('platform1', '../assets/art/platform1.png', 50, 11);
game.load.spritesheet('battlestage1', '../assets/art/base-stage1.png', 321, 126);
game.load.spritesheet('barrier', '../assets/art/barrier.png', 108, 94, 6);
game.load.spritesheet('elecHit', '../assets/art/hit.png', 50, 28, 3);
game.load.spritesheet('pred', '../assets/art/particlered.png', 4, 4);
game.load.spritesheet('back', '../assets/art/background1.png', 500, 700, 34);
game.load.spritesheet('bonusPtcl', '../assets/art/particleStar.png', 30, 30);
game.load.spritesheet('ghosty', '../assets/art/MarshUmbra.png', 160, 160, 190);
game.load.spritesheet('shBall', '../assets/art/umbraball.png', 60, 63);
game.load.spritesheet('spectre', '../assets/art/UmbraAttack.png', 160, 160, 23);
game.load.spritesheet('sStock', '../assets/art/umbraball.png', 60, 63);
game.load.spritesheet('ghostStock', '../assets/art/ghostStock.png', 32, 32);
game.load.spritesheet('scottStock', '../assets/art/sStock.png', 32, 32);
game.load.spritesheet('shieldHit', '../assets/art/nullHit.png', 45, 45);
game.load.spritesheet('hardHit', '../assets/art/hardHit.png', 57, 57);
game.load.spritesheet('ballHit', '../assets/art/ghost_impact.png', 53, 58);
game.load.spritesheet('hardHit2', '../assets/art/hardHit2.png', 57, 57);
game.load.spritesheet('dbox', '../assets/art/2pbox.png', 25, 25);
game.load.spritesheet('b1', '../assets/art/cpuBlock.png');
game.load.spritesheet('b2', '../assets/art/cpuBlock2.png');
//soundControl.loadSFX();
game.load.audio('airRecov', '../assets/sfx/airRecov.wav');
game.load.audio('criticalHit', '../assets/sfx/critical.wav');
game.load.audio('grDodge', '../assets/sfx/grDodge.wav');
game.load.audio('hit', '../assets/sfx/hit1.wav');
game.load.audio('hit2', '../assets/sfx/deppSounds.wav');
game.load.audio('die', '../assets/sfx/Deleted.wav');
game.load.audio('enter', '../assets/sfx/enter.wav');
game.load.audio('throwball', '../assets/sfx/energyballthrow.wav');
game.load.audio('block', '../assets/sfx/AttackBounce.wav');
game.load.audio('sword', '../assets/sfx/SwordSwing.wav');
game.load.audio('gdodge', '../assets/sfx/Shield.wav');
game.load.audio('barrier', '../assets/sfx/barrier.wav');
game.load.audio('gnatk1', '../assets/sfx/ghAtk1.wav');
game.load.audio('jumpa', '../assets/sfx/jump.wav');
game.load.audio('ghRun', '../assets/sfx/ghRunAtk.wav');
game.load.audio('ghAir', '../assets/sfx/ghAirRec.wav');
game.load.audio('ghRunAtk', '../assets/sfx/ghRunAtk.wav');
game.load.audio('ghDownKick', '../assets/sfx/ghDownKick.wav');
game.load.audio('ghAtk2', '../assets/sfx/ghAtk2.wav');
game.load.audio('foxKicks', '../assets/sfx/ghFoxKicks.wav');
game.load.audio('ghAirNeu', '../assets/sfx/ghAirKick.wav');
game.load.audio('ghWhip', '../assets/sfx/ghWhip.wav');
game.load.audio('ghMeteor', '../assets/sfx/meteorS.wav');
game.load.audio('stKick', '../assets/sfx/stKick.wav');
game.load.audio('stRunAtk', '../assets/sfx/stRunAtk.wav');
game.load.audio('stSlideKick', '../assets/sfx/stSlideKick.wav');
game.load.audio('stSpecKick', '../assets/sfx/stSpecialKick.wav');
game.load.audio('stPunch', '../assets/sfx/stPunch.wav');
game.load.audio('stUpNeu', '../assets/sfx/stUpNeu.wav');
game.load.audio('nullHit', '../assets/sfx/AttackBounce.wav');
game.load.audio('elecHit', '../assets/sfx/Hurt.wav');
game.load.audio('explosion', '../assets/sfx/expl.wav');
game.load.audio('battle1', '../assets/music/Ambush.mp3');
//sound, sprite, atkBox, charObj
},
create: function () {
// Starting game physics
game.physics.startSystem(Phaser.Physics.ARCADE);
music = game.add.audio('battle1');
//music.play();
game.stage.backgroundColor = '#800080'
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
bfBackground = game.add.sprite(0, 0, 'back');
//dummy = game.add.sprite(200, 100, 'tester2');
dude.createFighter();
comp.createOther();
dude.addSFX();
resizeToSprite(bfBackground, game, 0, 0);
bfBackground.animations.add('on', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33], 30, true);
bfBackground.animations.play('on');
/* cpuB1 = game.add.sprite
cpuB2 = game.add.asprite */
lives = game.add.group();
let lifename;
if (dude.name == 'mghosty') {
lifename = 'ghostStock';
} else {
lifename = 'scottStock';
}
for (var i = 0; i < 3; i++) {
// This creates a new Phaser.Sprite instance within the group
// It will be randomly placed within the world and use the 'baddie' image to display
life = lives.create(45 + (i * 50), 700, lifename, i);
life.name = 'life' + i;
}
dummy.animations.add('idle', [0, 1, 2, 3, 4, 5, 6, 7], 12, true);
dummy.animations.add('run', [8, 9, 10, 11, 12, 13, 14, 15], 12, false);
//player.animations.add('jump', [16, 17, 18, 19, 20, 21, 22, 23, 24, 25], 12, false);
dummy.animations.add('startJump', [17, 18, 19, 20, 21, 22, 23, 24], 18, false);
dummy.animations.add('loopJump', [24, 25], 12, true);
dummy.animations.add('endJump', [27], 12, false);
//neutralpunch2 would follow nuetralpunch1 after it finishes running, like a combo
//would require input, let's say that hitting 'a' for example, would trigger neutralPunch1, if pressed again at the right...
//..moment, would trigger neutralPunch2, and so forth
dummy.animations.add('neutralPunch1', [28, 29, 30, 31], 11, false);
dummy.animations.add('neutralPunch2', [32, 33, 34, 35], 11, false);
dummy.animations.add('neutralPunch3', [36, 37, 38], 11, false);
dummy.animations.add('neutralPunch4', [39, 40], 11, false);
dummy.animations.add('neutralPunch5', [41, 42, 43, 44], 11, false);
dummy.animations.add('neutralKick', [45, 46, 47, 48, 49, 50, 51], 12, false);
dummy.animations.add('specialKick1', [63, 64, 65, 66, 67, 68, 69], 14, false);
dummy.animations.add('runAttack', [70, 71, 72, 73, 74, 75, 76, 77, 78], 16, false);
dummy.animations.add('block', [79, 80, 81, 82, 83, 84, 85], 14, false);
dummy.animations.add('lowKick', [86, 87, 88, 89, 90, 91], 14, false);
dummy.animations.add('dodge', [92, 93, 94, 95], 14, false);
dummy.animations.add('knockback', [96, 97, 98, 99, 100], 13, false);
dummy.animations.add('startDwnKick', [100, 101, 102], 12, false);
dummy.animations.add('loopDwnKick', [103, 104, 105], 12, true);
dummy.animations.add('endDwnKick', [106], 12, false);
dummy.animations.add('slideKick', [107, 108, 109, 110, 111, 112, 113], 16, false);
dummy.animations.add('notloopJump', [24, 25], 12, false);
dummy.animations.add('pushback1', [148], 10, false);
dummy.animations.add('pushback2', [149], 10, false);
dummy.animations.add('pushback3', [150], 10, false);
//creates hitbox when player attacks
//gets attack animname passed in playerCombo
//based on what attack it is, it renders around the attack point, and disappears after 1 second
//creates a hitbox group
hitboxes = game.add.group();
hitboxes.enableBody = true;
//creates an instance of hitbox;
atkBox = hitboxes.create(0, 0, 'hbox');
scndBox = hitboxes.create(0, 0, 'dbox');
projectiles = game.add.group();
projectiles.enableBody = true;
projectile = projectiles.create(0, 0, 'shBall');
projectile.alpha = 0;
shields = game.add.group();
shields.enableBody = true;
shield = shields.create(0, 0, 'barrier');
shield.animations.add('on', [0, 1, 2, 3, 4, 5, 6], 25, false);
shield.alpha = 0;
//atkBox.body.setSize(15, 15, 0, 0);
hitEffects = game.add.group();
let hitEffectName;
if (dude.name == 'mghosty') {
hitEffectName = 'hardHit'
} else {
hitEffectName = 'hardHit2'
}
elec = hitEffects.create(0, 0, hitEffectName);
elec.animations.add('show', [0, 1, 2, 3, 4, 5], 20, false);
elec.animations.currentAnim.killOnComplete = true;
let cpuHitEffect;
if (comp.name == 'mghosty') {
cpuHitEffect = 'hardHit'
} else {
cpuHitEffect = 'hardHit2'
}
cpuHit = hitEffects.create(0, 0, cpuHitEffect);
cpuHit.animations.add('show', [0, 1, 2, 3, 4, 5], 20, false);
cpuHit.animations.currentAnim.killOnComplete = true;
shadowHit = hitEffects.create(0, 0, 'ballHit');
shadowHit.animations.add('show', [0, 1, 2, 3, 4, 5], 20, false);
shadowHit.animations.currentAnim.killOnComplete = true;
shieldHitS = hitEffects.create(0, 0, 'shieldHit');
shieldHitS.animations.add('show', [0, 1, 2, 3, 4, 5], 20, false);
shieldHitS.animations.currentAnim.killOnComplete = true;
shieldHitS.alpha = 0;
ghostSpecialAtk = hitEffects.create(0, 0, 'spectre');
ghostSpecialAtk.animations.add('show', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22], 90, false);
ghostSpecialAtk.animations.currentAnim.killOnComplete = true;
ghostSpecialAtk.enableBody = true;
ghostSpecialAtk.alpha = 0;
//shieldHitS.play();
//plays added animaiton
//dummy.animations.play('idle');
// Creating platform
platform = game.add.sprite(400, 200, 'platform1');
platform2 = game.add.sprite(500, 300, 'platform1');
platform3 = game.add.sprite(800, 200, 'platform1');
battlefield = game.add.sprite(200, 500, 'battlestage1');
//enables gravity on player but not on platform
game.physics.arcade.enable([scott, dummy, platform, platform2, platform3, battlefield, atkBox, ghostSpecialAtk]);
dude.enablePhysics(scott);
platform.enableBody = true;
platform2.enableBody = true;
platform3.enableBody = true;
battlefield.enableBody = true;
battlefield.scale.setTo(2, 2);
battlefield.body.setSize(321, 126, 0, 25);
//scott
//scott.body.setSize(60, 120, 20, 69);
//ghost
//scott.body.setSize(60, 120, 20, 47);
scott.anchor.setTo(0.5, 0.5);
shield.anchor.setTo(0.5, 0.5);
dummy.anchor.setTo(0.5, 0.5);
dummy.body.gravity.y = 2100;
dummy.body.drag.x = 400;
dummy.body.drag.y = 0;
dummy.body.setSize(60, 120, 20, 60);
platform.body.immovable = true;
platform2.body.immovable = true;
platform3.body.immovable = true;
battlefield.body.immovable = true;
console.log(atkBox);
console.log(scott);
console.log(dude.isGrounded);
},
update: function () {
game.physics.arcade.collide(scott, battlefield, function () {
dude.resetFilp();
});
game.physics.arcade.collide(dummy, battlefield, function () {
comp.resetFilp();
});
//dummy will collide with the stage
game.physics.arcade.collide(dummy, [/* platform, platform1, platform2, platform3, */ battlefield]);
//dummy will be damaged by the projectile
game.physics.arcade.overlap(dummy, projectile, function () {
runBulletCollide(dude, comp, dummy, projectile);
});
//hitbox on dummy, runs hit();
//dummy will be hit when player hits him
game.physics.arcade.overlap(dummy, atkBox, function () {
//hits++;
hit(dude, scott, comp, dummy);
//elec hiteffect will play on dummy when hit
normHit.run(normalHit, elec, atkBox, dummy, scott, dude);
});
//if ghost,dummy will be hit when player'specialKick1 hits him
game.physics.arcade.overlap(dummy, ghostSpecialAtk, function () {
hit(dude, scott, comp, dummy);
grghostHit.run(normalHit, elec, dummy, dummy, scott, dude);
});
//sound, sprite, atkBox, charObj
//testing for dummy hiting player
game.physics.arcade.overlap(scott, scndBox, function () {
hit(comp, dummy, dude, scott);
CPUnormHit.run(normalHit, cpuHit, scndBox, scott, dummy, comp);
});
//sound, sprite, atkBox, charObj
//testing for dummy hiting player
//game.physics.arcade.overlap(scott, scndBox, dummyhit);
//EVERYTHING WE NEED TO HAVE SCOTT ACTIVE***************************
//game.debug.body(scott);
updateGrounded(scott, dude);
keyListener(scott, dude, true, 's', 'd', 'a', 'x', 'z');
updateActs(act);
decisionReset(act);
dude.setupRelations();
dude.runIdleControl(scott);
dude.jump(scott, 15);
dude.glideDownJump(scott);
dude.jumpAnimLoop(scott);
dude.downAerialMotion(scott, 'ghost');
dude.downAerial(scott);
dude.moveAttackBox(atkBox, scott);
dude.moveRunAttack(scott, 'runAttack', 10);
dude.moveRunAttack(scott, 'slideKick', 12);
dude.moveDodge(scott);
dude.airDodged(scott);
dude.resetAirDodge(scott);
dude.showShield(shield, scott);
dude.upRecovery(scott);
dude.ghostLand(scott);
dude.ghSpecialListener(scott, dummy);
shootBullet(dude, scott, atkBox, projectile, -900, 0);
hurt(scott, dummy, dude, comp);
resizeToSprite(shield, scott, 0, 0);
//trajectoryBounce(dummy, comp);
getLoser(dude, scott);
//getLoser(comp, dummy);
dude.enableSoundControls();
/*************************TESTING DUMMY (2PLAYER )*********** */
updateGrounded(dummy, comp);
socket.on('get-updates', (compAct) => {
/*set comp = new Opponent before uncommenting the line below */
comp.updateActions(compAct);
});
/*set comp = new Opponent before uncommenting the line below */
comp.runIdleControl(dummy);
//looks into the obj sent through sockets containg the boolenas and strong that
//determine what our opponenet does on our screen
COMPListener(dummy, comp);
comp.jump(dummy, 15);
comp.glideDownJump(dummy, 1000, comp.stats.gravity);
comp.jumpAnimLoop(dummy);
comp.downAerialMotion(dummy, 'low');
comp.downAerial(dummy);
comp.moveAttackBox(scndBox, dummy);
comp.moveRunAttack(dummy, 'runAttack', 10);
comp.moveRunAttack(dummy, 'slideKick', 12);
comp.moveDodge(dummy);
comp.airDodged(dummy);
comp.resetAirDodge(dummy);
comp.showShield(shield, dummy);
comp.upRecovery(dummy);
//comp.velocityStallControl(dummy);
//END***************************************
//**************** H E L P E R F U N C T I O N S*******************//
function updateGrounded(sprite, charObj) {
if (sprite.body.touching.down) {
charObj.isGrounded = true;
charObj.stats.jumpH = 0;
charObj.resetFilp();
} else {
charObj.isGrounded = false;
}
}
//********************************************HIT LOGIC*********************************************************** */
//the following code is extemely crude and is only used for testing purposes
//this entire file will be refactored soon.
//make tthis dymanic
function hit(charObj, sprite, inCharObj, inSprite) {
if (game.physics.arcade.overlap(dummy, ghostSpecialAtk) || sprite.animations.currentAnim.name != 'idle' && (['foxKick', 'upAir', 'meteorSmash', 'neutralKick', 'neutralPunch1', 'neutralPunch2',
'neutralPunch3', 'neutralPunch4', 'specialKick1', 'runAttack', 'slideKick', 'loopDwnKick', 'upNeutral', 'airRecovery', 'airNeutral'].includes(sprite.animations.currentAnim.name))) {
charObj.hitbox.isOverlapping = true;
charObj.hitbox.isAtkBoxActive = true;
alertIsHurt(sprite, inSprite, inCharObj);
} else {
charObj.hitbox.isOverlapping = false;
charObj.hitbox.isAtkBoxActive = false;
}
}
//sprite = opponent sprite
//charobj for the sprite that got hit with an attack
function alertIsHurt(sprite, injSprite, charObj) {
if (!charObj.stallChecked) {
charObj.getHitWith = sprite.animations.currentAnim.name;
charObj.isHurt = true;
charObj.stallChecked = true;
//comp.velocityStallControl(injSprite);
charObj.resetGetHit(charObj);
} else {
return;
}
}
}
};
//********************GLOBAL FUNCTIONS************* */
// sprite = sprite that is attacking
// injSprite = sprite that is hurt
// charObj = char obj for the sprite that is attacking
// hurtCharObj = char obj for the sprite that is hurt
function hurt(sprite, injSprite, charObj, hurtCharObj) {
if (charObj.hitbox.isOverlapping && charObj.hitbox.isAtkBoxActive) {
hurtCharObj.stats.damage += 0.93;
console.log(hurtCharObj.stats.damage);
injSprite.animations.play('knockback');
hurtCharObj.pushbackControl(injSprite);
hitParticle(charObj, hurtCharObj);
getLaunchAmount(sprite, injSprite, charObj, hurtCharObj);
charObj.hitbox.isOverlapping = false;
charObj.hitbox.isAtkBoxActive = false;
//sprite.body.velocity = 0;
} else {
return;
}
}
function renderEffect(effectSprite, contactSprite, charObj, amount) {
let tweena = game.add.tween(effectSprite);
let sound = game.add.audio('explosion');
effectSprite.alpha = 1;
effectSprite.scale.setTo(2, 2);
effectSprite.revive();
if (charObj.isShotLeft) {
console.log(charObj.isShotLeft)
effectSprite.x = contactSprite.x;
effectSprite.y = contactSprite.y - 50;
} else {
console.log(charObj.isShotLeft)
effectSprite.x = contactSprite.x;
effectSprite.y = contactSprite.y - 50;
}
tweena.to({ x: amount }, 500, Phaser.Easing.Out, true);
effectSprite.animations.play('show');
sound.play();
tweena.start();
}
function runBulletCollide(charObj, injCharObj, injSprite, bulletSprite) {
injCharObj.stats.damage += 40;
if (charObj.isShotLeft) {
Xvector = -120 - injCharObj.stats.damage;
Yvector = -40 - injCharObj.stats.damage;
injSprite.animations.play('knockback')
injSprite.body.velocity.setTo(Xvector, Yvector);
renderEffect(shadowHit, bulletSprite, charObj, -100);
bulletSprite.destroy();
//charObj.isShotLeft = false;
charObj.isBulletFired = false;
projectile = projectiles.create(0, 0, 'shBall');
projectile.alpha = 0;
console.log('beep')
} else {
Xvector = 120 + injCharObj.stats.damage;
Yvector = -40 - injCharObj.stats.damage;
console.log('boop');
injSprite.animations.play('knockback')
injSprite.body.velocity.setTo(Xvector, Yvector);
renderEffect(shadowHit, bulletSprite, charObj, 100);
bulletSprite.destroy();
//charObj.isShotLeft = false;
charObj.isBulletFired = false;
projectile = projectiles.create(0, 0, 'shBall');
projectile.alpha = 0;
}
}
function shootBullet(charObj, sprite, atkBox, bulletSprite, velX, velY) {
let x;
let y = velY;
if (charObj.isBulletFired && sprite.animations.currentAnim.name == 'haduken' && sprite.animations.currentFrame.index == 185) {
charObj.isLeft ? x = velX : x = velX * -1;
bulletSprite.position = {
x: atkBox.x,
y: atkBox.y,
type: 25
}
bulletSprite.alpha = 0.5;
bulletSprite.body.velocity.setTo(x, y);
} else {
return;
}
}
//attacker = sprite that is attacking
//injured = sprite that is getting hit
//charObj = Character obj for the sprite that is attacking
//injCharObj = Character obj for the sprite that is getting hit
function getLaunchAmount(attacker, injured, charObj, injCharObj) {
let Xvector;
let Yvector;
console.log(attacker.animations.currentAnim.name);
if (charObj.hitbox.isOverlapping && charObj.hitbox.isAtkBoxActive) {
if (attacker.animations.currentAnim.name == 'slideKick') {
if (charObj.isLeft) {
Xvector = -24 - injCharObj.stats.damage;
Yvector = -500 - injCharObj.stats.damage;
} else {
Xvector = 24 + injCharObj.stats.damage;
Yvector = -500 - injCharObj.stats.damage;
}
} else if ((['neutralPunch1', 'neutralPunch2', 'neutralPunch3'].includes(attacker.animations.currentAnim.name))) {
if (charObj.isLeft) {
Xvector = -1 - injCharObj.stats.damage;
} else {
Xvector = 1 + injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'neutralPunch4') {
if (charObj.isLeft) {
Xvector = -25 - injCharObj.stats.damage;
Yvector = -100 - injCharObj.stats.damage;
} else {
Xvector = 25 + injCharObj.stats.damage;
Yvector = -100 - injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'specialKick1' && charObj.name !== 'mghosty') {
if (charObj.isLeft) {
Xvector = -50 - injCharObj.stats.damage;
Yvector = -140 - injCharObj.stats.damage;
} else {
Xvector = 50 + injCharObj.stats.damage;
Yvector = -140 - injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'neutralKick') {
let bonus = 0;
if (charObj.timedBonus) {
console.log('time bonus', charObj.timedBonus);
bonus = 200;
}
if (charObj.isLeft) {
console.log(bonus);
Xvector = (-90 - bonus) - injCharObj.stats.damage;
charObj.timedBonus = false;
} else {
Xvector = (90 + bonus) + injCharObj.stats.damage;
charObj.timedBonus = false;
}
} else if (attacker.animations.currentAnim.name == 'runAttack') {
if (charObj.isLeft) {
Xvector = -300 - injCharObj.stats.damage;
Yvector = -200 - injCharObj.stats.damage;
} else {
Xvector = 300 + injCharObj.stats.damage;
Yvector = -200 - injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'loopDwnKick') {
if (charObj.isLeft) {
Xvector = -300 - injCharObj.stats.damage;
Yvector = 280 + injCharObj.stats.damage;
} else {
Xvector = 300 + injCharObj.stats.damage;
Yvector = 280 + injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'upNeutral') {
if (charObj.isLeft) {
Xvector = -100 - injCharObj.stats.damage;
Yvector = -680 - injCharObj.stats.damage;
} else {
Xvector = 100 + injCharObj.stats.damage;
Yvector = -680 - injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'airNeutral' && charObj.name !== 'mghosty') {
if (charObj.isLeft) {
Xvector = -250 - injCharObj.stats.damage;
Yvector = 550 + injCharObj.stats.damage;
} else {
Xvector = 250 + injCharObj.stats.damage;
Yvector = 550 + injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'airNeutral' && charObj.name == 'mghosty') {
if (charObj.isLeft) {
Xvector = -200 - injCharObj.stats.damage;
Yvector = 30 + injCharObj.stats.damage;
} else {
Xvector = 200 + injCharObj.stats.damage;
Yvector = 30 + injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'airRecovery') {
if (charObj.isLeft) {
Xvector = -115 - injCharObj.stats.damage;
Yvector = -400 - injCharObj.stats.damage;
} else {
Xvector = 115 + injCharObj.stats.damage;
Yvector = -400 - injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'meteorSmash') {
if (charObj.isLeft) {
Xvector = -1 - injCharObj.stats.damage;
Yvector = 500 + injCharObj.stats.damage;
} else {
Xvector = 1 + injCharObj.stats.damage;
Yvector = 500 - injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'upAir') {
if (charObj.isLeft) {
//Xvector = -1 - injCharObj.stats.damage;
Yvector = -340 - injCharObj.stats.damage;
} else {
//Xvector = 1 + injCharObj.stats.damage;
Yvector = -340 - injCharObj.stats.damage;
}
}
else if (attacker.animations.currentAnim.name == 'foxKick') {
if (charObj.isLeft) {
Xvector = 511 + injCharObj.stats.damage;
Yvector = -25 - injCharObj.stats.damage;
} else {
Xvector = -511 - injCharObj.stats.damage;
Yvector = -25 - injCharObj.stats.damage;
}
} else if (attacker.animations.currentAnim.name == 'specialKick1' && charObj.name == 'mghosty') {
if (charObj.isLeft) {
Yvector = -700 - injCharObj.stats.damage;
} else {
Yvector = -700 - injCharObj.stats.damage;
}
}
}
launchSprite(null, injured, true, Xvector, Yvector);
}
//hitbox = name of attacker's hitbox
//injured = the name of the sprite that recived the hit
//isSpec = boolean, if there ther is a specified velocity from an attack anim
//if so, then add those coords to x and y (these amounts are acutally passed with getLaunchAmount)
function launchSprite(hitbox, injured, isSpec, x, y) {
if (isSpec) {
injured.body.velocity.setTo(x, y);
} else {
Xvector = ((hitbox.x - injured.x) * (3));
Yvector = ((hitbox.y - injured.y) * (3));
injured.body.velocity.setTo(Xvector, Yvector);
}
}
//sprite = sprite name of the one getting hurt
//charObj = Character Object of the attacker
//hurtcharObj = Characte Object of the hurt sprite
function resizeToSprite(sprite, example, wOffset, hOffset) {
if ((sprite.width < example.width) &&
(sprite.height < example.height)) {
sprite.width = (example.width + wOffset);
sprite.height = (example.height + hOffset);
} else {
return;
}
}
function hitParticle(charObj, hurtcharObj) {
let amt = hurtcharObj.stats.damage;
if (charObj.timedBonus) {
let bonusEmit;
bonusEmit = game.add.emitter(atkBox.x, atkBox.y, 50);
bonusEmit.makeParticles('bonusPtcl', [0], 90);
//emitter.minParticleSpeed = (1);
bonusEmit.setYSpeed(-10, 40);
bonusEmit.setXSpeed(-10, 80);
bonusEmit.minParticleScale = 0.3;
bonusEmit.maxParticleScale = 1;
bonusEmit.start(false, 600, null, 0.5);
} else {
emitter = game.add.emitter(atkBox.x, atkBox.y, 25 + amt);
//emitter.width = game.world.width;
emitter.makeParticles('pred', [0], 25);
//emitter.minParticleSpeed = (1);
emitter.setYSpeed(-10, 40);
emitter.setXSpeed(-10, 80);
emitter.minParticleScale = 0.7;
emitter.maxParticleScale = 1;
emitter.start(false, 400, null, 0.2);
}
}
function trajectoryBounce(injSprite, injcharObj) {
if (60 < injcharObj.stats.damage < 100) {
injSprite.body.bounce.set(0.3);
} else if (100 < injcharObj.stats.damage < 300) {
injSprite.body.bounce.set(10);
}
else {
return;
}
}
let once = false;
function getLoser(charObj, sprite) {
if (sprite.world.y > 2000 || sprite.world.y < -200 || sprite.world.x < -300 || sprite.world.x > 1500) {
if (!once) {
alert(`${charObj.name} has lost a life`);
once = true;
}
//alert(`${charObj.name} has lost a life`);
sprite.x = 500;
sprite.y = 100;
removeStock(charObj, lives);
resetStats(charObj);
setTimeout(function () {
once = false;
}, 1000)
}
}
function soundCtrl(anim) {
this.animName = anim;
this.hasPlayed = false;
this.canReset = false;
this.run = function (sound, sprite) {
if (!this.hasPlayed && this.animName == sprite.animations.currentAnim.name) {
sound.play();
this.hasPlayed = true;
}
return this;
};
this.listen = function (sprite) {
if (this.animName !== sprite.animations.currentAnim.name) {
this.reset();
}
return this;
};
this.reset = function () {
this.hasPlayed = false;
this.canReset = false;
return this;
};
}
function hitEffectCtrl(isForShield) {
this.forShield = isForShield;
this.hasPlayed = false;
this.canReset = false;
this.hitterAnim = '';
//sound = sound that should be play
//sprite = sprite of hit effect
//atkBox = attack box sprite
//charObj = char obj
this.run = function (sound, sprite, atkBox, charObj, attacker, atkCharObj) {
if (this.forShield) {
if (charObj.shield.shieldActive && !this.hasPlayed) {
sprite.revive(100);
sprite.x = atkBox.x;
sprite.y = atkBox.y;
sound.play();
sprite.alpha = 1
sprite.animations.play('show');
this.hitterAnim = attacker.animations.currentAnim.name;
this.hasPlayed = true;
}
} else {
if (!this.hasPlayed && atkCharObj.hitbox.isAtkBoxActive) {
sprite.revive(100);
sprite.x = atkBox.x;
sprite.y = atkBox.y;
sound.play();
sprite.alpha = 1
sprite.animations.play('show');
this.hitterAnim = attacker.animations.currentAnim.name;
this.hasPlayed = true;
}
}
if (sprite.animations.currentAnim.isFinished || !sprite.animations.currentAnim.isPlaying && this.hasPlayed && attacker.animations.currentAnim.name !== this.hitterAnim) {
this.checkReset(sprite/* , attacker, atkCharObj */);
}
}
this.checkReset = function (sprite, attacker, atkCharObj) {
sprite.alpha = 0;
this.hitterAnim = false;
this.hasPlayed = false;
return this;
};
}
function removeStock(charObj, groupname) {
if (charObj.lives.left > 0) {
let num = charObj.lives.left - 1;
if (groupname.children[num].name == `life${num}`) {
groupname.children[num].visible = false;
charObj.lives.left--;
} else {
return;
}
} else {
alert(`${charObj.name} has lost the battle!`);
}
}
function resetStats(charObj) {
charObj.stats.damage = 0;
}
function getDistance(x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
function decisionReset(act) {
if (!game.input.keyboard.isDown(Phaser.Keyboard.S) && !game.input.keyboard.isDown(Phaser.Keyboard.D)
&& !game.input.keyboard.isDown(Phaser.Keyboard.A) && !game.input.keyboard.isDown(Phaser.Keyboard.X)
&& !game.input.keyboard.isDown(Phaser.Keyboard.Z)) {
act.decision = '';
}
}
function updateActs(act) {
if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
act.runRight = true;
} else {
act.runRight = false;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
act.runLeft = true;
} else {
act.runLeft = false;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
act.holdUp = true;
} else {
act.holdUp = false;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
act.holdDown = true;
} else {
act.holdDown = false;
}
//****************Socket.emit to update character on the other end**********
socket.emit('send-updates', act);
}
|
//select the first iframe that has a src that starts with "//www.youtube"
var firstIframe = document.querySelector('iframe[src^="//www.youtube"]');
//get the current source
var src = firstIframe.src;
//update the src with "autoplay=1"
var newSrc = src+'?autoplay=1';
//change iframe's src
firstIframe.src = newSrc;
|
// list of emoticons that don't match a simple \W+ regex
// extracted using:
// require('emojibase-data/en/data.json').map(_ => _.emoticon).filter(Boolean).filter(_ => !/^\W+$/.test(_))
const irregularEmoticons = new Set([
':D', 'xD', ":'D", 'o:)',
':x', ':p', ';p', 'xp',
':l', ':z', ':j', '8D',
'xo', '8)', ':B', ':o',
':s', ":'o", 'Dx', 'x(',
'D:', ':c', '>0)', ':3',
'</3', '<3', '\\m/', ':E',
'8#'
])
export function extractTokens (str) {
return str
.split(/[\s_]+/)
.map(word => {
if (!word.match(/\w/) || irregularEmoticons.has(word)) {
// for pure emoticons like :) or :-), just leave them as-is
return word.toLowerCase()
}
return word
.replace(/[)(:,]/g, '')
.replace(/’/g, "'")
.toLowerCase()
}).filter(Boolean)
}
|
'use strict'
var Sprite = function(loc, w, h, json){
this.w = w;
this.h = h;
this.loc = loc;
this.frames = [];
this.currentIndex = 0;
this.count = 0;
this.currentTime = 0;
this.lastTime = Date.now();
this.max = countProperties(json.frames);
for (let i = 0; i < countProperties(json.frames); i++){
let image = new Image();
image.src = "images/spritesheets/enemy.png"
let f = json.frames["Rocket" + i].frame;
image.info = {"x": f.x, "y": f.y, "w": f.w, "h": f.h}
this.frames.push(image);
}
this.run = function(){
this.update();
this.render();
}
this.update = function(){
this.loc.x*=1.01;
this.loc.y/=1.005;
}
this.render = function(){
if (this.currentIndex >= this.max){
this.currentIndex = 0;
}
towerGame.context.drawImage(this.frames[this.currentIndex], this.frames[this.currentIndex].info.x, this.frames[this.currentIndex].info.y, this.frames[this.currentIndex].info.w, this.frames[this.currentIndex].info.h, this.loc.x, this.loc.y, this.w, this.h);
var millis = Date.now();
if(millis - this.lastTime >= 50) {
this.gameTime++;
this.lastTime = millis;
this.currentIndex++;
}
}
}
|
var app = app || {};
(module => {
const bookListPage = {}
bookListPage.init = (books) => {
console.log(books)
$('#book-list').empty();
let bookSource = $('#book-template').html();
let template = Handlebars.compile(bookSource);
books.forEach(book => {
$('#book-list').append(template(book));
})
$('#view-details').on('click', event => {
let = bookId = $(event.target).data('id');
page(`/books/${bookId}`);
})
$('#book-list-page').show();
}
module.bookListPage = bookListPage;
})(app);
|
import { combineReducers } from 'redux';
import pressReducers from './press.reducers';
export default combineReducers({
pressReducers
});
|
import { Fragment } from "react";
import _ from "lodash";
import styled from "styled-components";
import { withTranslation } from "~/i18n";
const RemoveIcon = styled.span`
position: absolute;
right: 3px;
`;
const AttachMentList = styled.ul`
position: relative;
`;
const handleSliceAttachmentName = attachmentName => {
const ext = attachmentName.lastIndexOf(".");
const attachmentNameWithoutExt = attachmentName.substr(0, ext);
if (attachmentNameWithoutExt.length > 15) {
const charArray = [...attachmentNameWithoutExt];
const newattachmentName =
charArray[0] +
charArray[1] +
charArray[2] +
charArray[3] +
"...." +
charArray[charArray.length - 4] +
charArray[charArray.length - 3] +
charArray[charArray.length - 2] +
charArray[charArray.length - 1];
return newattachmentName + attachmentName.substr(ext);
} else {
return attachmentName;
}
};
/**
* Component for render detail field
*
* @param [field] is a field, we need property
* {
* condition: is condition for display value
* defaultValue: is value for display when condition is true
* }
* @param [datas] is a data of field (required)
*/
const AttachmentsField = ({ field, datas, lang, t }) => (
<Fragment>
{field.canEdit ? (
<Fragment>
<div className="nopadding form-group d-inline-flex custom-fileUpload">
<input
type="text"
name={`attach_${field.key}`}
disabled
className="form-control"
/>
{/* {datas[`${field.key}AllowAction`] &&
datas[`${field.key}AllowAction`].includes("Add") && ( */}
<div className="upload-btn-wrapper">
<button type="button" className="btn btn--transparent btnUpload">
{t(`${lang}:${"Browse"}`)}
</button>
<input
type="file"
name={field.key}
onChange={event => field.onFileAdded.call(this, event)}
/>
</div>
{/* )} */}
</div>
<div className="nopadding">
<small id={`${field.key}-label-format`}>
{t(`${lang}:${"File type"}`)}: {datas[`${field.key}Format`]},{" "}
</small>
<small id={`${field.key}-label-count`}>
{t(`${lang}:${"Required"}`)}: {datas[`${field.key}RequiredTooltip`]}{" "}
{t(`${lang}:${"files"}`)}
</small>
</div>
<AttachMentList
id={`attach_${field.key}_list`}
className="uploadedList px-0"
>
{_.map(
datas[field.key],
({ name, hash, attachmentName, attachmentHash, owner }, index) => (
(name = name ? name : attachmentName),
(hash = hash ? hash : attachmentHash),
(owner = owner ? owner : ""),
(
<li key={index}>
{hash !== undefined && hash !== null ? (
<a
href={`/download/${hash}/${name}?filename=${name}&owner=${owner}`}
className="gray-1"
target="_blank"
>
{handleSliceAttachmentName(name)}
</a>
) : (
handleSliceAttachmentName(name)
)}
<RemoveIcon>
{/* {datas[`${field.key}AllowAction`] &&
datas[`${field.key}AllowAction`].includes("Remove") && ( */}
<a href="javascript:void(0);">
<i
className="fa fa-times purple"
onClick={() =>
field.onRemove.call(this, `${field.key}`, index)
}
/>
</a>
{/* )} */}
</RemoveIcon>
</li>
)
)
)}
</AttachMentList>
</Fragment>
) : (
<div id={`attach_${field.key}_list`} className="uploadedList px-0">
{datas[field.key] && datas[field.key].length > 0
? _.map(
datas[field.key],
(
{ name, hash, attachmentName, attachmentHash, owner },
index
) => (
(name = name ? name : attachmentName),
(hash = hash ? hash : attachmentHash),
(owner = owner ? owner : ""),
(
<div key={hash + index}>
{handleSliceAttachmentName(name)}{" "}
<span>
{field.download && hash !== undefined && hash !== null && (
<a
href={`/download/${hash}/${name}?filename=${name}&owner=${owner}`}
target="_blank"
>
{t(`${lang}:${"Download"}`)}
</a>
)}
</span>
</div>
)
)
)
: field.defaultValue || ""}
</div>
)}
</Fragment>
);
export default withTranslation(["request-create"])(AttachmentsField);
|
module.exports = {
template: function (item, id) {
$container = $('<div data-type="dataCriacao" class="form-inline">');
$('<input type="text" class="form-control input-sm" size=2 maxlength=2 placeholder="Dia" id="diaCriacao" name="diaCriacao">').appendTo($container);
$('<input type="text" class="form-control input-sm" size=2 maxlength=2 placeholder="Mês" id="mesCriacao" name="mesCriacao">').appendTo($container);
$('<input type="text" class="form-control input-sm" size=4 maxlength=4 placeholder="Ano" id="anoCriacao" name="anoCriacao">').appendTo($container);
return $container[0].outerHTML;
},
show: function(item, model) {
var ret = '';
if (model.diaCriacao) {
ret += model.diaCriacao + '/';
}
if (model.mesCriacao) {
ret += model.mesCriacao + '/';
}
if (model.anoCriacao) {
ret += model.anoCriacao + '/';
}
return ret.substring(0, ret.length - 1);
}
};
|
import React from 'react'
import classes from './Input.module.css'
const input = (props) => {
let inputElement = null ;
switch (props.ElementType){
case('input') :
inputElement=<input className={classes.FormInput} onChange={props.changed} value={props.val} {...props.elementConfig}></input>
break;
default :
inputElement = <input className={classes.FormInput} onChange={props.changed} value={props.val} {...props.elementConfig}></input>
}
return (
<div>
{inputElement}
</div>
)
}
export default input;
|
import styled from "styled-components";
import { MasterStyles } from "../../masterStyles";
export const TitleContainer = styled.div`
width: 100%;
height: 10px;
display: flex;
align-items: center;
justify-content: center;
// flexDirection: column;
`;
export const Title = styled.span`
font-weight: bolder;
font-size: ${MasterStyles.fontSize.large};
`;
|
const listingElement = document.querySelector("#listing");
console.log(listingElement);
getProductList()
.then(response => {
response.products
.map(product => renderProduct(product))
.forEach(html => listingElement.innerHTML += html);
});
|
function getAddPromise(a, b) {
return new Promise(function(resolve, reject) {
if (typeof a === 'number' && typeof b === 'number') {
resolve(a + b);
} else {
reject('A and B need to both be numbers');
}
});
}
getAddPromise(111, 222).then(function (sum) {
console.log('promise success', sum);
}, function (err) {
console.log('promise error', err);
});
getAddPromise(1, 'jeff').then(function (sum) {
console.log('promise success', sum);
}, function (err) {
console.log('promise error', err);
});
|
import React from 'react';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Lista from './Lista.jsx';
import Form from './Form.jsx';
import Button from '@material-ui/core/Button';
import axios from 'axios';
class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
listData: [],
selected: {}
};
this.loadData();
this.onNewData();
}
loadData = () => axios.get('https://protected-shelf-19067.herokuapp.com/games/')
.then(response => this.setState({listData: response.data}));
onNewData = () => this.setState({
selected: {
'id': 0,
'name': '',
'release_date': '',
'publisher': '',
'platform': '',
'category': ''
}
});
onListSelect = (data) => this.setState({
selected: data
});
onItemSave = () => {
console.log(this.state.selected);
if(this.state.selected.id == 0)
axios.post('https://protected-shelf-19067.herokuapp.com/games', {...this.state.selected}).then( () =>
{
console.log('post to api successful');
this.onNewData();
this.loadData();
}
).catch((e) =>
console.log('post to api unsuccessful!!!', e)
);
else
axios.put('https://protected-shelf-19067.herokuapp.com/games/' + this.state.selected.id.toString(), this.state.selected).then( () =>
{
console.log('put to api successful');
this.onNewData();
this.loadData();
}
).catch((e) =>
console.log('put to api unsuccessful!!!', e)
);
};
onItemDelete = () => {
if(this.state.selected.id == 0) return;
axios.delete('https://protected-shelf-19067.herokuapp.com/games/' + this.state.selected.id.toString()).then( () =>
{
console.log('delete to api successful');
this.onNewData();
this.loadData();
}
).catch((e) =>
console.log('delete to api unsuccessful!!!')
);
}
handleChanges = name => event => {
this.setState({ selected: { ...this.state.selected, [name]: event.target.value }});
};
render() {
return (
<div>
<Grid container spacing={24}>
<Grid item xs={5}>
<Paper>
<Lista lista={ this.state.listData } onListSelect={ this.onListSelect }></Lista>
</Paper>
</Grid>
<Grid item xs={7}>
<Paper>
<Form item={ this.state.selected }
onSave={ this.onItemSave } handleChanges={ this.handleChanges }></Form>
<Button variant="contained" color="primary" style={{marginLeft: '30px', marginBottom: '10px'}} onClick={ this.onNewData }>
Novo
</Button>
<Button variant="contained" color="secondary" style={{marginLeft: '30px', marginBottom: '10px'}} onClick={ this.onItemDelete }>
Deletar
</Button>
<Button variant="contained" style={{color: 'white', backgroundColor: '#37C337', marginLeft: '30px', marginBottom: '10px'}} onClick={ this.onItemSave }>
Salvar
</Button>
</Paper>
</Grid>
</Grid>
</div>
);
}
}
export default Board;
|
var User = require('../models/user');
exports.userId = function(req, res, next, userId) {
User.findById(userId, function(err, user) {
if (err) return next(err);
if (!user) return res.send(404);
req.params.user = user;
next();
});
};
exports.show = function(req, res) {
res.render('users/show', {
_user: req.params.user,
settings: JSON.stringify({
user: req.user,
_user: req.params.user
})
});
};
|
ListCtrl = function(listView, store){
store.on("itemAdded", function(item){
listView.addItem(item);
})
listView.on("changeStatus", function(id, status){
var item = {'status': status};
store.update(id, item);
})
}
|
module.exports={
globalNav : function(to,from,next){
if(localStorage.getItem('token')){
next({
name : 'HomeRoute'
})
} else{
next()
}
},
authNav : function(to,form,next){
if(!localStorage.getItem('token')){
next({
name : 'LoginRoute'
})
} else {
next()
}
}
}
|
// libs
import React, { useEffect, useState, useContext } from 'react';
import { FaRegMoneyBillAlt } from 'react-icons/fa';
import { BiTimeFive, BiTask } from 'react-icons/bi';
import { AiOutlineStar } from 'react-icons/ai';
import Slider from 'react-slick';
import { useDispatch, useSelector } from 'react-redux';
import { FirebaseContext } from 'common';
// styles
import '../styles/Home.scss';
// components
import Navbar from '../components/Home/Navbar';
import Heading from '../components/Home/Heading';
import Services from '../components/Home/Services';
import Fleet from '../components/Home/Fleet';
import ContactUs from '../components/Home/ContactUs';
import withPage from '../utils/withPage';
const Home = ({ page }) => {
// const { homepage} = page.pagesData
// slider settings
var settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
arrows: false,
swipeToSlie: true
};
const [ pageData, setPageData ] = useState({});
const { api } = useContext(FirebaseContext);
const contactPage = useSelector((state) => state.pagesData.contactUs || {});
const { pageLoad } = api;
const dispatch = useDispatch();
useEffect(() => {
dispatch(pageLoad('contactUs'));
}, []);
useEffect(
() => {
let collectData = {};
if (page.items && page.items[0].fields) {
const fields = page.items[0].fields;
const {
clientApproaches,
header,
infoSlider,
ourFleets,
sellingPoints,
subHeader,
servicesWrapper,
whoAreWeLabel,
whoAreWeDetail,
whatWeDoLabel,
whatWeDoDetail,
whyChooseUsLabel,
whyChooseUsDetail
} = fields;
collectData = {
clientApproaches: clientApproaches.map((item) => item.fields),
infoSlider: infoSlider.map((item) => item.fields),
fleets: ourFleets.map((item) => ({
detail: item.fields.detail,
name: item.fields.name,
image: 'https:' + item.fields.image.fields.file.url
})),
sellingPoints,
header,
subHeader,
servicesWrapper,
whoAreWeLabel,
whoAreWeDetail,
whatWeDoLabel,
whatWeDoDetail,
whyChooseUsLabel,
whyChooseUsDetail
};
}
setPageData({ ...collectData });
// dispatch({ type: 'SET_FLEETS_DATA', payload: collectData.fleets });
},
[ page ]
);
const {
clientApproaches,
infoSlider,
fleets,
sellingPoints,
header,
subHeader,
servicesWrapper,
whoAreWeLabel,
whoAreWeDetail,
whatWeDoLabel,
whatWeDoDetail,
whyChooseUsLabel,
whyChooseUsDetail
} = pageData;
const { heading, subHeading, appList } =
(contactPage.items && contactPage.items[0] && contactPage.items[0].fields) || {};
return (
<div>
<Navbar />
<Heading heading={header} subHeading={subHeader} />
<Services sellingPoints={sellingPoints} servicesWrapper={servicesWrapper} />
<Fleet fleets={fleets} />
<div className="d-flex flex-column">
<div className="home-text-section">
<h6>{whoAreWeLabel}</h6>
<p>{whoAreWeDetail}</p>
</div>
<div className="home-text-section-special">
<h6>{whatWeDoLabel}</h6>
<p>{whatWeDoDetail}</p>
</div>
<div className="home-text-section">
<h6>{whyChooseUsLabel}</h6>
<p>{whyChooseUsDetail}</p>
</div>
</div>
<div className="home-client">
<h6 className="home-client-heading">Our Client First Approach</h6>
<div className="m-0 row">
{Array.isArray(clientApproaches) && clientApproaches.length > 0 ? (
clientApproaches.map((clientItem) => (
<div className="col-12 col-md-6 d-flex home-client-item">
{clientItem.iconName === 'priceIcon' && <FaRegMoneyBillAlt />}
{clientItem.iconName === 'watchIcon' && <BiTimeFive />}
{clientItem.iconName === 'starIcon' && <AiOutlineStar />}
{clientItem.iconName === 'noticeIcon' && <BiTask />}
<div>
<h6>{clientItem.name}</h6>
<p>{clientItem.details}</p>
</div>
</div>
))
) : null}
</div>
</div>
<div className="home-know">
<Slider {...settings} className="m-0 p-0">
{Array.isArray(infoSlider) &&
infoSlider.map((slide) => (
<div className="home-know-item">
<h6>{slide.label} </h6>
<p>{slide.detail}</p>
</div>
))}
</Slider>
</div>
<ContactUs heading={heading} appList={appList} />
</div>
);
};
const pageSlug = 'homepage';
export default withPage(Home, pageSlug);
|
import React from 'react';
import ReactDOM from 'react-dom';
import {hashHistory} from 'react-router'
import RouterMap from './router/routerMap';
import {Provider} from 'react-redux';
import store from './store/store';
import './static/css/common.scss';
import './static/css/font.css';
ReactDOM.render(
<Provider store={store}>
<RouterMap history={hashHistory} />
</Provider>,
document.getElementById('root')
);
|
var should = require('should')
var setup = require('../src/setup.js')
describe('maths_setup', function(){
var number_object
beforeEach(function(){
number_object = {
created : 2015,
number : 8
}
})
it('should add 3 to number', function(){
setup(number_object, 3, 'add')
number_object.should.have.property('number', 11);
})
it('should multiply by 4', function(){
setup(number_object, 4, 'multiply')
number_object.should.have.property('number', 32);
})
it('should do 3 third root of number', function(){
setup(number_object, 3, 'root')
number_object.should.have.property('number', 2);
})
})
|
import {
GraphQLInt,
GraphQLObjectType,
GraphQLString,
GraphQLNonNull,
GraphQLList,
GraphQLBoolean,
GraphQLFloat
} from 'graphql';
let loanType = new GraphQLObjectType({
name: 'Loan',
fields: () => ({
AccountNumber: { type: GraphQLString },
GroupId: { type: GraphQLString },
LoanNumber: { type: GraphQLInt },
LoanType: { type: GraphQLString },
LenderId: { type: GraphQLString },
Status: { type: GraphQLString },
InterestRate: { type: GraphQLInt },
InterestRateReduction: { type: GraphQLFloat },
EffectiveInterestRate: { type: GraphQLFloat },
CurrentPrincipal: { type: GraphQLInt },
OutstandingInterest: { type: GraphQLFloat },
OutstandingFees: { type: GraphQLInt },
TotalBalance: { type: GraphQLFloat },
DelinquentAmount: { type: GraphQLInt },
OriginalTerm: { type: GraphQLInt },
TermRemaining: { type: GraphQLInt },
RepaymentPlan: { type: GraphQLString },
CurrentPaymentAmount: { type: GraphQLFloat },
HasAch: { type: GraphQLBoolean },
AchAlternateAmount: { type: GraphQLInt },
DueDate: { type: GraphQLString },
School: { type: GraphQLString },
IsPrivate: { type: GraphQLBoolean },
IsActive: { type: GraphQLBoolean },
DeferEligibility: { type: GraphQLString },
ConvertToRepayDate: { type: GraphQLString },
OriginalLoanBalance: { type: GraphQLInt },
CappedInterestAmount: { type: GraphQLInt },
PrincipalPaidYTD: { type: GraphQLInt },
InterestPaidYTD: { type: GraphQLInt },
GuarantorId: { type: GraphQLString },
PeriodStartDate: { type: GraphQLString },
PeriodEndDate: { type: GraphQLString },
IsPlusConsol: { type: GraphQLBoolean },
IsSpousalConsol: { type: GraphQLBoolean },
PurchaseDate: { type: GraphQLString },
GovernmentSubsidyStatus: { type: GraphQLString },
FirstDisbursementDate: { type: GraphQLString },
LastDisbursementDate: { type: GraphQLString },
DaysPastDue: { type: GraphQLInt },
})
});
export default loanType;
|
import React from 'react';
import PropTypes from 'prop-types';
import NotesItem from './NotesItem';
function NotesList({
deletingIds,
items,
onNoteDelete
}) {
return (items.length > 0 && (
<div className="Notes-list">
{items.map(item => (
<div
key={item.id}
className="Notes-listItem"
>
<NotesItem
content={item.content}
id={item.id}
isDeleting={deletingIds.findIndex(id => id === item.id) !== -1}
onDelete={onNoteDelete}
/>
</div>
))}
</div>
));
}
NotesList.propTypes = {
deletingIds: PropTypes.arrayOf(PropTypes.number),
items: PropTypes.arrayOf(PropTypes.shape({
content: PropTypes.string.isRequired,
id: PropTypes.number.isRequired
})),
onNoteDelete: PropTypes.func
};
NotesList.defaultProps = {
deletingIds: [],
items: [],
onNoteDelete: () => null
};
export default NotesList;
|
/* Math is a library in javascript used to use Maths functions like random etc... */
var num =0;
num = Math.random()
num = Math.floor(Math.random()*6 + 1)
console.log(num)
|
async function loadJSON (url) {
const res = await fetch(url);
return await res.json();
}
let selectedFund = null;
const funds = [];
loadJSON('./phones.json')
.then(data => funds.push(...data))
.catch(err => console.error(err));
function findMatches(wordToMatch, funds) {
return funds.filter(fund => {
const regex = new RegExp(wordToMatch, 'gi');
return fund.city.match(regex) || fund.state.match(regex)
})
}
function displayMatches(e) {
const matchArray = findMatches(this.value, funds);
const html = matchArray.map(fund => {
const regex = new RegExp(this.value, 'gi');
const cityName = fund.city.replace(regex, `<span class="hl">${this.value}</span>`)
const stateName = fund.state.replace(regex, `<span class="hl">${this.value}</span>`)
return `
<p class='listResults'>
<span class='place'>${cityName}, ${stateName}:</br> </span>
<button class='selectFundBtn' value="${fund.id}">${fund.name} -
<a class='phone' href="${fund.number}">${fund.number}</a>
</button>
</p>
`
}).join('');
suggestions.innerHTML = html;
}
const search = document.querySelector('.search')
const suggestions = document.querySelector('.suggestions');
search.addEventListener("input", displayMatches);
suggestions.addEventListener('click', e => {
const thirdPage = document.querySelector('.thirdPage');
const secondPage = document.querySelector('.secondPage');
if (e.target.tagName == 'BUTTON') {
const id = parseInt(e.target.value);
const fund = funds.find(currentFund => currentFund.id === id);
handleFundSelection(fund);
secondPage.style.display = "none";
thirdPage.style.display = "block";
}
})
function handleFundSelection(fund) {
selectedFund = fund.id;
console.log('the selected fund is: ', fund.id);
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Text, View, Image, TouchableOpacity, Linking } from 'react-native';
import WaitTime from './common/WaitTime';
import TotalTime from './common/TotalTime';
class MapCallout extends Component {
render() {
const { name, image, location, popular_times } = this.props
return (
<TouchableOpacity onPress={() => Linking.openURL(`maps://app?daddr=${location[0]}+${location[1]}`)}>
<View>
<Image
style={styles.thumbnailStyle}
source={{ uri: image }}
/>
<Text style={styles.title}>
{ name }
</Text>
<WaitTime times={popular_times} />
<TotalTime times={popular_times} />
</View>
</TouchableOpacity>
);
}
}
const styles = {
thumbnailStyle: {
flex: 1,
height: 70,
width: 100,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center'
},
title: {
flex: 1,
fontSize: 16,
paddingBottom: 5,
fontWeight: 'bold',
flexWrap: 'wrap',
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center'
}
};
MapCallout.propTypes = {
name: PropTypes.string,
image: PropTypes.string,
location: PropTypes.array,
popular_times: PropTypes.array
}
export default MapCallout;
|
const jwt = require('jsonwebtoken');
const bcrypt = require("bcrypt");
const { secret } = require('./../config/jwt-config')
let generateHash = (password) => {
return new Promise((resolve, reject) => {
const rounds = 1; //for test
bcrypt.hash(password, rounds, function (err, hash) {
if (err) {
reject(err);
}
resolve(hash);
});
});
};
const compareHash = (password, hash) => {
return new Promise((resolve, reject) => {
bcrypt.compare(password, hash, function (err, res) {
if (err) {
reject(err);
}
if (res == false) {
reject("invalid password");
}
resolve(res);
});
});
};
let generateToken = (id) => {
const expiresIn = '1d';
const payload = {
id: id,
iat: Date.now()
};
const signedToken = jwt.sign(payload, secret, { expiresIn: expiresIn });
return {
token: signedToken,
expires: expiresIn
}
};
let validateToken = (token) => {
try {
var decoded = jwt.verify(token, JWT_SECRET);
return decoded;
} catch (error) {
throw error;
}
};
module.exports = {
validateToken, generateHash, compareHash, generateToken
}
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import angular from 'angular';
import tinycolor from 'tinycolor2';
import downloadDialogTemplate from './downloadDialog.html';
import watchListPageTemplate from './watchListPage.html';
import watchListChartAndStatsTemplate from './watchListChartAndStats.html';
import watchListTableTemplate from './watchListTable.html';
import './watchListPage.css';
const NO_STATS = '\u2014';
class WatchListPageController {
static get $$ngIsClass() { return true; }
static get $inject() {
return [
'$mdMedia',
'localStorageService',
'$state',
'maUiDateBar',
'$mdDialog',
'maStatistics',
'$scope',
'$mdColorPicker',
'$timeout',
'maUser'
];
}
constructor(
$mdMedia,
localStorageService,
$state,
maUiDateBar,
$mdDialog,
maStatistics,
$scope,
$mdColorPicker,
$timeout,
User) {
this.$mdMedia = $mdMedia;
this.localStorageService = localStorageService;
this.$state = $state;
this.dateBar = maUiDateBar;
this.$mdDialog = $mdDialog;
this.maStatistics = maStatistics;
this.$scope = $scope;
this.$mdColorPicker = $mdColorPicker;
this.$timeout = $timeout;
this.User = User;
this.selected = [];
this.selectedStats = [];
this.watchListParams = {};
this.selectFirstWatchList = false;
this.numberOfRows = $mdMedia('gt-sm') ? 100 : 25;
this.pageNumber = 1;
this.sortOrder = 'name';
this.downloadStatus = {};
this.chartOptions = {
selectedAxis: 'left',
axes: {}
};
this.axisOptions = [
{name: 'left', translation: 'ui.app.left'},
{name: 'right', translation: 'ui.app.right'},
{name: 'left-2', translation: 'ui.app.farLeft'},
{name: 'right-2', translation: 'ui.app.farRight'}
];
this.columns = [
{name: 'xid', label: 'ui.app.xidShort'},
{name: 'dataSourceName', label: 'ui.app.dataSource'},
{name: 'deviceName', label: 'common.deviceName', selectedByDefault: true},
{name: 'name', label: 'common.name', selectedByDefault: true},
{name: 'value', label: 'ui.app.value', selectedByDefault: true, disableSort: true},
{name: 'time', label: 'ui.app.time', selectedByDefault: true, disableSort: true},
{name: 'enabled', label: 'common.enabled'},
{name: 'dataType', label: 'dsEdit.pointDataType'},
{name: 'readPermission', label: 'pointEdit.props.permission.read'},
{name: 'setPermission', label: 'pointEdit.props.permission.set'},
{name: 'editPermission', label: 'pointEdit.props.permission.edit'},
{name: 'unit', label: 'pointEdit.props.unit'},
{name: 'chartColour', label: 'pointEdit.props.chartColour'},
{name: 'plotType', label: 'pointEdit.plotType'},
{name: 'rollup', label: 'common.rollup'},
{name: 'integralUnit', label: 'pointEdit.props.integralUnit'}
];
this.columns.forEach((c, i) => c.order = i);
this.loadLocalStorageSettings();
// bound functions for md-data-table attributes
this.selectedPointsChangedBound = (...args) => this.selectedPointsChanged(...args);
this.sortOrPageChangedBound = (...args) => this.sortOrPageChanged(...args);
}
$onInit() {
const localStorage = this.localStorageService.get('watchListPage') || {};
const params = this.$state.params;
if (params.watchListXid || !(params.dataSourceXid || params.deviceName || params.tags) && localStorage.watchListXid) {
const watchListXid = params.watchListXid || localStorage.watchListXid;
this.pointBrowserLoadItem = {watchListXid};
} else if (params.dataSourceXid || !(params.deviceName || params.tags) && localStorage.dataSourceXid) {
const dataSourceXid = params.dataSourceXid || localStorage.dataSourceXid;
this.pointBrowserLoadItem = {dataSourceXid};
} else if (params.deviceName || !params.tags && localStorage.deviceName) {
const deviceName = params.deviceName || localStorage.deviceName;
this.pointBrowserLoadItem = {deviceName};
} else if (params.tags || localStorage.tags) {
if (params.tags) {
this.pointBrowserLoadItem = {tags: this.parseTagsParam(params.tags)};
} else {
const tags = {};
// copy the tag values over in order specified by the tagKeys array
// also copies undefined values into the tag object (which could not be stored in local storage JSON)
if (Array.isArray(localStorage.tagKeys)) {
localStorage.tagKeys.forEach(k => tags[k] = localStorage.tags[k]);
} else {
Object.assign(tags, localStorage.tags);
}
this.pointBrowserLoadItem = {tags};
}
} else if (this.$mdMedia('gt-md')) {
// select first watch list automatically for large displays
this.pointBrowserLoadItem = {firstWatchList: true};
}
this.dateBar.subscribe((event, changedProperties) => {
this.updateStats();
}, this.$scope);
}
loadLocalStorageSettings() {
const settings = this.localStorageService.get('watchListPage') || {};
this.selectedTags = settings.selectedTags || [];
if (Array.isArray(settings.selectedColumns)) {
this.selectedColumns = settings.selectedColumns.map(name => this.columns.find(c => c.name === name)).filter(c => !!c);
} else {
this.selectedColumns = this.columns.filter(c => c.selectedByDefault);
}
this.numberOfRows = settings.numberOfRows || (this.$mdMedia('gt-sm') ? 100 : 25);
this.sortOrder = settings.sortOrder != null ? settings.sortOrder : 'name';
}
saveLocalStorageSettings() {
if (this.watchList && this.watchList.isNew()) {
const settings = this.localStorageService.get('watchListPage') || {};
settings.selectedTags = this.selectedTags;
settings.selectedColumns = this.selectedColumns.map(c => c.name);
settings.numberOfRows = this.numberOfRows;
settings.sortOrder = this.sortOrder;
this.localStorageService.set('watchListPage', settings);
}
}
watchListSettingChanged() {
// copy the local settings to the watch list data
this.copyLocalSettingsToWatchList();
// save the settings to local storage (if its not a saved watch list)
this.saveLocalStorageSettings();
}
copyLocalSettingsToWatchList() {
this.watchList.data.selectedTags = this.selectedTags;
this.watchList.data.selectedColumns = this.selectedColumns.map(c => c.name);
this.watchList.data.sortOrder = this.sortOrder;
this.watchList.data.numberOfRows = this.numberOfRows;
}
parseTagsParam(param) {
const tags = {};
const paramArray = Array.isArray(param) ? param : [param];
paramArray.forEach(p => {
const parts = p.split(':');
const tagKey = parts[0];
if (tagKey) {
if (!tags[tagKey]) {
tags[tagKey] = [];
}
if (parts.length > 1) {
const values = parts[1].split(',');
tags[tagKey].push(...values);
}
}
});
return tags;
}
formatTagsParam(tags) {
const param = [];
Object.keys(tags).forEach(tagKey => {
const tagValue = tags[tagKey];
if (tagValue == null) {
param.push(tagKey);
} else {
const tagValueArray = Array.isArray(tagValue) ? tagValue : [tagValue];
if (tagValueArray.length) {
const paramValue = tagValueArray.join(',');
param.push(`${tagKey}:${paramValue}`);
}
}
});
return param;
}
updateState(state) {
const localStorageParams = this.localStorageService.get('watchListPage') || {};
['watchListXid', 'dataSourceXid', 'deviceName', 'tags'].forEach(key => {
const value = state[key];
if (value) {
localStorageParams[key] = value;
this.$state.params[key] = value;
} else {
delete localStorageParams[key];
this.$state.params[key] = null;
}
});
if (state.tags) {
this.$state.params.tags = this.formatTagsParam(state.tags);
// when the tags object is stored to local storage as JSON any tag keys with a value of undefined
// will be lost, so we store an array of tag keys too
localStorageParams.tagKeys = Object.keys(state.tags);
}
this.localStorageService.set('watchListPage', localStorageParams);
this.$state.go('.', this.$state.params, {location: 'replace', notify: false});
}
clearWatchList() {
this.watchList = null;
// clear checked points from table/chart
this.clearSelected();
}
clearSelected() {
this.selected = [];
this.selectedStats = [];
this.chartConfig.selectedPoints = [];
}
rebuildChart() {
// shallow copy causes the chart to update
this.chartWatchList = Object.assign(Object.create(this.watchList.constructor.prototype), this.watchList);
}
watchListChanged() {
// clear checked points from table/chart
this.selected = [];
this.selectedStats = [];
// ensure the watch list point configs are up to date, also ensures there is data and chart config
this.watchList.updatePointConfigs();
this.chartConfig = this.watchList.data.chartConfig;
this.watchList.defaultParamValues(this.watchListParams);
this.loadLocalStorageSettings();
if (Array.isArray(this.watchList.data.selectedColumns)) {
this.selectedColumns = this.watchList.data.selectedColumns.map(name => this.columns.find(c => c.name === name)).filter(c => !!c);
}
if (Array.isArray(this.watchList.data.selectedTags)) {
this.selectedTags = this.watchList.data.selectedTags;
}
if (this.watchList.data.sortOrder != null) {
this.sortOrder = this.watchList.data.sortOrder;
}
if (Number.isFinite(this.watchList.data.numberOfRows) && this.watchList.data.numberOfRows >= 0) {
this.numberOfRows = this.watchList.data.numberOfRows;
}
// we might have just copied settings from watch list to local but some watch list settings might not be there, populate them
this.copyLocalSettingsToWatchList();
this.getPoints();
const stateUpdate = {};
if (!this.watchList.isNew()) {
stateUpdate.watchListXid = this.watchList.xid;
} else if (this.watchList.type === 'query' && this.watchList.deviceName) {
stateUpdate.deviceName = this.watchList.deviceName;
} else if (this.watchList.type === 'query' && this.watchList.dataSource) {
stateUpdate.dataSourceXid = this.watchList.dataSource.xid;
} else if (this.watchList.type === 'tags' && this.watchList.tags) {
stateUpdate.tags = this.watchList.tags;
}
this.updateState(stateUpdate);
this.rebuildChart();
}
getPoints() {
if (this.wlPointsPromise) {
this.wlPointsPromise.cancel();
}
this.points = [];
this.wlPointsPromise = this.watchList.getPoints(this.watchListParams);
this.pointsPromise = this.wlPointsPromise.then(null, angular.noop).then(points => {
this.points = points || [];
const pointNameCounts = this.pointNameCounts = {};
this.points.forEach(pt => {
const count = pointNameCounts[pt.name];
pointNameCounts[pt.name] = (count || 0) + 1;
if (!pt.tags) pt.tags = {};
pt.tags.name = pt.name;
pt.tags.device = pt.deviceName;
});
// applies sort and limit to this.points and saves as this.filteredPoints
this.filterPoints();
// select points based on the watch list data chart config
this.selected = this.watchList.findSelectedPoints(this.points);
this.updateStats();
});
}
sortOrPageChanged() {
this.watchListSettingChanged();
this.filterPoints();
}
filterPoints() {
const limit = this.numberOfRows;
const offset = (this.pageNumber - 1) * limit;
const order = this.sortOrder;
const points = this.points.slice();
if (order) {
let propertyName = order;
let desc = false;
if ((desc = propertyName.indexOf('-') === 0 || propertyName.indexOf('+') === 0)) {
propertyName = propertyName.substring(1);
}
let tag = false;
if (propertyName.indexOf('tags.') === 0) {
tag = true;
propertyName = propertyName.substring(5);
}
points.sort((a, b) => {
const valA = tag ? a.tags[propertyName] : a[propertyName];
const valB = tag ? b.tags[propertyName] : b[propertyName];
if (valA === valB || Number.isNaN(valA) && Number.isNaN(valB)) return 0;
if (valA == null || Number.isNaN(valA) || valA > valB) return desc ? -1 : 1;
if (valB == null || Number.isNaN(valB) || valA < valB) return desc ? 1 : -1;
return 0;
});
}
this.filteredPoints = points.slice(offset, offset + limit);
}
editWatchList(watchList) {
this.$state.go('ui.settings.watchListBuilder', {watchListXid: watchList ? watchList.xid : null});
}
saveSettings() {
// this.chartConfig is already mapped to this.watchList.data.chartConfig and so is saved too
this.watchList.data.paramValues = angular.copy(this.watchListParams);
if (this.watchList.isNew()) {
this.$state.go('ui.settings.watchListBuilder', {watchList: this.watchList});
} else {
this.watchList.$update().then(wl => {
this.chartConfig = wl.data.chartConfig;
this.rebuildChart();
});
}
}
selectedPointsChanged(point) {
const removed = !this.selected.includes(point);
const tagKeys = this.watchList.nonStaticTags(this.points);
const pointConfigs = this.watchList.pointConfigs();
if (removed) {
const pointsToRemove = [point];
const watchListConfig = point.watchListConfig;
delete point.watchListConfig;
const configIndex = pointConfigs.indexOf(watchListConfig);
if (configIndex >= 0) {
pointConfigs.splice(configIndex, 1);
}
// remove other selected points which were selected using the same config
this.selected = this.selected.filter(pt => {
if (pt.watchListConfig !== watchListConfig) {
return true;
}
pointsToRemove.push(pt);
delete pt.watchListConfig;
});
this.removeStatsForPoints(pointsToRemove);
} else {
pointConfigs.push(this.newPointConfig(point, tagKeys));
this.updateStats(point);
}
this.rebuildChartDebounced();
}
rebuildChartDebounced() {
if (this.rebuildChartPromise) {
this.$timeout.cancel(this.rebuildChartPromise);
delete this.rebuildChartPromise;
}
this.rebuildChartPromise = this.$timeout(() => {
delete this.rebuildChartPromise;
this.$scope.$applyAsync(() => {
this.rebuildChart();
});
}, 1000, false);
}
newPointConfig(point, selectedTags) {
const pointConfig = {};
point.watchListConfig = pointConfig;
if (this.chartOptions.configNextPoint) {
if (this.chartOptions.pointColor)
pointConfig.lineColor = this.chartOptions.pointColor;
if (this.chartOptions.pointChartType)
pointConfig.type = this.chartOptions.pointChartType;
if (this.chartOptions.pointAxis)
pointConfig.valueAxis = this.chartOptions.pointAxis;
}
pointConfig.xid = point.xid;
pointConfig.tags = {};
selectedTags.forEach(tagKey => pointConfig.tags[tagKey] = point.tags[tagKey]);
return pointConfig;
}
removeStatsForPoints(points) {
points.forEach(point => {
const pointIndex = this.selectedStats.findIndex(stat => stat.xid === point.xid);
if (pointIndex >= 0) {
this.selectedStats.splice(pointIndex, 1);
}
});
}
updateStats(point) {
if (!this.selected) {
return;
}
let pointsToUpdate;
if (!point) {
// doing a full rebuild of stats
this.selectedStats = [];
pointsToUpdate = this.selected;
} else {
// single point added or removed
pointsToUpdate = [point];
}
pointsToUpdate.forEach(point => {
const ptStats = {
name: point.name,
device: point.deviceName,
xid: point.xid
};
this.selectedTags.forEach(tagKey => {
ptStats[`tags.${tagKey}`] = point.tags[tagKey];
});
this.selectedStats.push(ptStats);
this.maStatistics.getStatisticsForXid(point.xid, {
from: this.dateBar.from,
to: this.dateBar.to,
rendered: true
}).then(stats => {
ptStats.average = stats.average ? stats.average.value : NO_STATS;
ptStats.minimum = stats.minimum ? stats.minimum.value : NO_STATS;
ptStats.maximum = stats.maximum ? stats.maximum.value : NO_STATS;
ptStats.sum = stats.sum ? stats.sum.value : NO_STATS;
ptStats.first = stats.first ? stats.first.value : NO_STATS;
ptStats.last = stats.last ? stats.last.value : NO_STATS;
ptStats.count = stats.count;
ptStats.averageValue = parseFloat(stats.average && stats.average.value);
ptStats.minimumValue = parseFloat(stats.minimum && stats.minimum.value);
ptStats.maximumValue = parseFloat(stats.maximum && stats.maximum.value);
ptStats.sumValue = parseFloat(stats.sum && stats.sum.value);
ptStats.firstValue = parseFloat(stats.first && stats.first.value);
ptStats.lastValue = parseFloat(stats.last && stats.last.value);
});
});
let seenXids = {};
this.selectedStats.forEach(s => {
if (seenXids[s.xid]) throw new Error();
seenXids[s.xid] = true;
});
}
columnIsSelected(name) {
return !!this.selectedColumns.find(c => c.name === name);
}
chooseAxisColor($event, axisName) {
if (!this.chartConfig.valueAxes) {
this.chartConfig.valueAxes = {};
}
if (!this.chartConfig.valueAxes[axisName]) {
this.chartConfig.valueAxes[axisName] = {};
}
this.showColorPicker($event, this.chartConfig.valueAxes[axisName], 'color', true);
}
showColorPicker($event, object, propertyName, rebuild) {
if (!object) return;
this.$mdColorPicker.show({
value: object[propertyName] || tinycolor.random().toHexString(),
defaultValue: '',
random: false,
clickOutsideToClose: true,
hasBackdrop: true,
skipHide: false,
preserveScope: false,
mdColorAlphaChannel: true,
mdColorSpectrum: true,
mdColorSliders: false,
mdColorGenericPalette: true,
mdColorMaterialPalette: false,
mdColorHistory: false,
mdColorDefaultTab: 0,
$event: $event
}).then(color => {
object[propertyName] = color;
if (rebuild) {
this.rebuildChart();
}
});
}
showDownloadDialog($event) {
this.$mdDialog.show({
controller: ['maUiDateBar', 'maPointValues', 'maUtil', 'MA_ROLLUP_TYPES', 'MA_DATE_TIME_FORMATS',
'maUser', '$mdDialog', 'localStorageService',
function(maUiDateBar, pointValues, Util, MA_ROLLUP_TYPES, MA_DATE_TIME_FORMATS,
maUser, $mdDialog, localStorageService) {
this.dateBar = maUiDateBar;
this.rollupTypes = MA_ROLLUP_TYPES;
this.rollupType = 'NONE';
this.timeFormats = MA_DATE_TIME_FORMATS;
this.timezones = [{
translation: 'ui.app.timezone.user',
value: maUser.current.getTimezone(),
id: 'user'
}, {
translation: 'ui.app.timezone.server',
value: maUser.current.systemTimezone,
id: 'server'
}, {
translation: 'ui.app.timezone.utc',
value: 'UTC',
id: 'utc'
}];
this.loadSettings = function() {
const settings = localStorageService.get('watchlistDownload') || {};
this.allPoints = settings.allPoints != null ? settings.allPoints : !this.selected.length;
this.rollupType = settings.rollupType || 'NONE';
this.timeFormat = settings.timeFormat || this.timeFormats[0].format;
this.timezone = settings.timezone && this.timezones.find(t => t.id === settings.timezone) || this.timezones[0];
this.customTimeFormat = !this.timeFormats.find(f => f.format === this.timeFormat);
};
this.loadSettings();
this.saveSettings = function() {
localStorageService.set('watchlistDownload', {
allPoints: this.allPoints,
rollupType: this.rollupType,
timeFormat: this.timeFormat,
timezone: this.timezone.id
});
};
this.customTimeFormatChanged = function() {
if (!this.customTimeFormat) {
if (!this.timeFormats.find(f => f.format === this.timeFormat)) {
this.timeFormat = this.timeFormats[0].format;
}
}
};
this.downloadData = function downloadData(downloadType) {
const points = this.allPoints ? this.points : this.selected;
const xids = points.map(pt => pt.xid);
const functionName = downloadType.indexOf('COMBINED') > 0 ? 'getPointValuesForXidsCombined' : 'getPointValuesForXids';
const mimeType = downloadType.indexOf('CSV') === 0 ? 'text/csv' : 'application/json';
const extension = downloadType.indexOf('CSV') === 0 ? 'csv' : 'json';
const fileName = this.watchList.name + '_' + maUiDateBar.from.toISOString() + '_' + maUiDateBar.to.toISOString() + '.' + extension;
let fields;
if (downloadType === 'CSV_COMBINED') {
fields = ['TIMESTAMP', 'VALUE'];
} else {
fields = ['XID', 'DATA_SOURCE_NAME', 'DEVICE_NAME', 'NAME', 'TIMESTAMP', 'VALUE', 'RENDERED'];
}
this.downloadStatus.error = null;
this.downloadStatus.downloading = true;
this.downloadStatus.queryPromise = pointValues[functionName](xids, {
mimeType: mimeType,
responseType: 'blob',
from: maUiDateBar.from,
to: maUiDateBar.to,
rollup: this.rollupType,
rollupInterval: maUiDateBar.rollupIntervals,
rollupIntervalType: maUiDateBar.rollupIntervalPeriod,
limit: -1,
timeout: 0,
dateTimeFormat: this.timeFormat,
timezone: this.timezone.value,
fields: fields
}).then(response => {
this.downloadStatus.downloading = false;
Util.downloadBlob(response, fileName);
}, error => {
this.downloadStatus.error = error.mangoStatusText;
this.downloadStatus.downloading = false;
});
};
this.cancelDownload = function cancelDownload() {
this.downloadStatus.queryPromise.cancel();
};
this.cancel = function cancel() {
$mdDialog.cancel();
};
}],
template: downloadDialogTemplate,
parent: angular.element(document.body),
targetEvent: $event,
clickOutsideToClose: true,
fullscreen: this.$mdMedia('xs') || this.$mdMedia('sm'),
bindToController: true,
controllerAs: '$ctrl',
locals: {
watchList: this.watchList,
selected: this.selected,
downloadStatus: this.downloadStatus,
points: this.points
}
});
}
}
watchListPageFactory.$inject = ['$templateCache'];
function watchListPageFactory($templateCache) {
$templateCache.put('watchList.chartAndStats.html', watchListChartAndStatsTemplate);
$templateCache.put('watchList.table.html', watchListTableTemplate);
return {
restrict: 'E',
template: watchListPageTemplate,
scope: {},
controller: WatchListPageController,
controllerAs: '$ctrl',
bindToController: {
watchList: '<?'
}
};
}
export default watchListPageFactory;
|
export const Reducer = ( state, action ) => {
if( action.type === "addItem" ){
const newPerson = [...state.people, action.payload ]
return {
...state,
people:newPerson,
showModal: true,
modalContent: "Item Added",
nameValue:""
}
}
if( action.type === "setNewName" ){
return {
...state,nameValue:action.payload
}
// let newList = state.person.filter( (person) => person.id !== id );
}
throw new Error("No matching options")
console.log( state, action );
};
|
import React, {Component} from 'react';
import {Header} from './header';
import {Title} from './title';
import {Techs} from './techs/techs';
import {Footer} from './footer';
const styles = {
container: {
display: 'flex',
flexDirection: 'column',
minHeight: '100%'
},
main: {
flex: 1,
display: 'flex',
flexDirection: 'column'
}
};
export class Main extends Component {
render() {
return (
<div style={styles.container}>
<Header/>
<main style={styles.main}>
<Title/>
<Techs/>
</main>
<Footer/>
</div>
);
}
}
|
import React from "react";
import { useRouter } from 'next/router'
import { LoadingOverlay, Loader } from "react-overlay-loader";
import 'react-overlay-loader/styles.css';
export default function callback() {
const router = useRouter();
if (router.query.hasOwnProperty("event_id")) {
router.replace("event/" + router.query["event_id"]);
}
return (
<div className="flex flex-wrap">
<Loader loading text="Redirecting ..."/>
</div>
);
}
|
function setDimension( source, target){ //set element target dimension is equal to element source dimension
const myWidth = source.clientWidth;
target.style.width = myWidth + "px";
const myHeight = source.clientHeight;
target.style.height = myHeight + "px";
}
function fixBody(){
let scrollBarWidth;
if (document.body.offsetHeight > window.innerHeight){
scrollBarWidth = window.innerWidth - document.body.clientWidth;
}
else scrollBarWidth = 0;
document.querySelector('.navbar-desktop').style.paddingRight = `${scrollBarWidth}px`;
document.body.style.paddingRight = `${scrollBarWidth}px`;
document.body.style.overflow = "hidden";
}
function releaseBody(){
document.querySelector('.navbar-desktop').style.paddingRight = "0px";
document.body.style.paddingRight = "0px";
document.body.style.overflow = "auto";
}
function checkAreAllInputFilled(){
const inputs = document.querySelectorAll('input');
for (let i = 0; i < inputs.length; i++){
if ( inputs[i].value === "" ) return false
}
return true
}
function checkInput(inputCheck){
const errors = {}
for (let inputName in inputCheck){
errors[inputName] = eval(inputCheck[inputName])(inputName);// execute function to check
}
return errors
}
function checkIfThereAreAnyError(errors){
for (let error in errors){
if (errors[error] !== "") {
return true
}
}
return false
}
function emailCheck(inputName){
const testRegex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
const input = document.querySelector(`#${inputName}`).value;
const error = "Email này không đúng định dạng"
if (testRegex.test(input) === false) return error
else return "";
}
function phoneCheck(inputName){
const testRegex = /^\d{10}$/;
const input = document.querySelector(`#${inputName}`).value;
const error = "Số điện thoại phải là 10 chữ số"
if (testRegex.test(input) === false) return error
else return "";
}
function passwordCheck(inputName){
const testRegex = /^\S{6,}$/;
const input = document.querySelector(`#${inputName}`).value;
const error = "Mật khẩu có ít nhất 6 kí tự"
if (testRegex.test(input) === false) return error;
else return "";
}
function checkRetype(inputName){
const input = document.querySelector(`#${inputName}`).value;
const inputCheck = document.querySelector(`#${inputName.replace(/Retype/,"")}`).value;
const error = "Mật khẩu không khớp"
if (input !== inputCheck) return error
else return "";
}
function checkhtmlHeight(){
const htmlHieght = document.documentElement.offsetHeight;
const windowHeight = window.innerHeight;
if (htmlHieght < windowHeight) document.querySelector('footer').classList.add('fixed');
else document.querySelector('footer').classList.remove('fixed');
}
export default {
setDimension,
fixBody,
releaseBody,
checkAreAllInputFilled,
checkInput,
checkIfThereAreAnyError,
checkhtmlHeight
}
|
/* HomePage ️ */
// dev imports
import PropTypes from "prop-types";
import Link from "next/link";
import CookieConsent from "react-cookie-consent";
import styled from "styled-components";
// file imports
import Header from "../components/Home/Header";
import Services from "../components/Home/Services";
import Clients from "../components/Home/Clients";
import Testimonial from "../components/Home/Testimonial";
import Address from "../components/Home/Address";
import Footers from "../components/Home/Footers";
//Home Component
const Home = props => {
return (
<>
<Header />
<Services /> <br />
<Clients /> <br />
<Testimonial />
<Address />
<Footers />
<CookieConsent
location="bottom"
buttonText="Got it!"
cookieName="myAwesomeCookieName2"
style={{ background: "#2B373B" }}
buttonStyle={{
color: "#4e503b",
fontSize: "13px",
borderRadius: "10px",
}}
expires={150}
>
This website uses cookies to enhance the user experience.{" "}
</CookieConsent>
</>
);
};
Home.propTypes = {};
export default Home;
/* HomePage ️ */
/* <Link href="/">
<a>Home</a>
</Link> */
|
export class ShowContact extends React.Component{
constructor(props){
super(props);
this.edit=this.handleEdit.bind(this);
this.deleteContact=this.deleteContact.bind(this);
}
handleEdit(){
this.props.handleEdit();
}
deleteContact(){
this.props.deleteContact();
}
render(){
return (
<div className="view-details">
<div className="details-header">
<div className="details-heading name">{this.props.contact.Name}</div>
<div className="options">
<button className="option" onClick={this.edit}><i className="fa fa-edit"></i> Edit</button>
<button className="option" onClick={this.deleteContact} ><i className="fa fa-trash"></i> Delete</button>
</div>
</div>
<div className="details">
<div className="table">
<div className="tr">
<div className="td">Email</div>
<div className="td email">{this.props.contact.Email}</div>
</div>
<div className="tr">
<div className="td">Phone</div>
<div className="td phone">{this.props.contact.Phone}</div>
</div>
<div className="tr">
<div className="td">Landline</div>
<div className="td landLine">{this.props.contact.Landline}</div>
</div>
<div className="tr">
<div className="td">Website</div>
<div className="td website">{this.props.contact.Url}</div>
</div>
<div className="tr">
<div className="td">Address</div>
<div className="td address">{this.props.contact.Address}</div>
</div>
</div>
</div>
</div>
);
}
}
|
/**
* Created by wen on 2016/8/16.
*/
import React from 'react';
import Order from './order';
import {serverFetch} from '../../../utils/clientFetch';
export default {
path: '/',
async action({cookie,state}) {
let list = (state && state.list) || await serverFetch(cookie,'/order/findlistpage',{page: 1,pagesize: 10});
return <Order list={{...list}}/>;
}
};
|
const countOnly = function(allItems, itemsToCount) {
return Object.keys(itemsToCount).reduce((output, key) => {
//assign new key property to count object if value set to true
return itemsToCount[key] ? Object.assign(output, {[key]: allItems.filter(str => key === str).length}) : output;
}, {});
};
module.exports = countOnly;
|
import React from 'react';
import * as THREE from 'three';
import Stats from './three/stats.min.js';
var container, stats;
var camera, scene, renderer;
var cube, plane;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
class Scene extends React.Component {
constructor() {
super();
}
componentDidMount() {
this.init();
this.animate();
}
init = () => {
container = document.querySelector( '.scene' );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'Drag to spin the cube';
container.appendChild( info );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xf0f0f0 );
// Cube
var geometry = new THREE.BoxGeometry( 200, 200, 200 );
for ( var i = 0; i < geometry.faces.length; i += 2 ) {
var hex = Math.random() * 0xffffff;
geometry.faces[ i ].color.setHex( hex );
geometry.faces[ i + 1 ].color.setHex( hex );
}
var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, overdraw: 0.5 } );
cube = new THREE.Mesh( geometry, material );
cube.position.y = 150;
scene.add( cube );
// Plane
var geometry = new THREE.PlaneBufferGeometry( 200, 200 );
geometry.rotateX( - Math.PI / 2 );
var material = new THREE.MeshBasicMaterial( { color: 0xe0e0e0, overdraw: 0.5 } );
plane = new THREE.Mesh( geometry, material );
scene.add( plane );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
document.addEventListener( 'mousedown', this.onDocumentMouseDown, false );
document.addEventListener( 'touchstart', this.onDocumentTouchStart, false );
document.addEventListener( 'touchmove', this.onDocumentTouchMove, false );
//
window.addEventListener( 'resize', this.onWindowResize, false );
}
onWindowResize = () => {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//
onDocumentMouseDown = ( event ) => {
event.preventDefault();
document.addEventListener( 'mousemove', this.onDocumentMouseMove, false );
document.addEventListener( 'mouseup', this.onDocumentMouseUp, false );
document.addEventListener( 'mouseout', this.onDocumentMouseOut, false );
mouseXOnMouseDown = event.clientX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
onDocumentMouseMove = ( event ) => {
mouseX = event.clientX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
}
onDocumentMouseUp = ( event ) => {
document.removeEventListener( 'mousemove', this.onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', this.onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', this.onDocumentMouseOut, false );
}
onDocumentMouseOut = ( event ) => {
document.removeEventListener( 'mousemove', this.onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', this.onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', this.onDocumentMouseOut, false );
}
onDocumentTouchStart = ( event ) => {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
}
onDocumentTouchMove = ( event ) => {
if ( event.touches.length === 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
}
}
//
animate = () => {
requestAnimationFrame( this.animate );
stats.begin();
this.loop();
stats.end();
}
loop = () => {
plane.rotation.y = cube.rotation.y += ( targetRotation - cube.rotation.y ) * 0.05;
renderer.render( scene, camera );
}
render() {
return (
<div className="scene"></div>
)
}
}
export default Scene;
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
/**
* @ngdoc service
* @name ngMangoServices.maDataSource
*
* @description
* Provides a service for getting list of data sources from the Mango system.
* - Used by <a ui-sref="ui.docs.ngMango.maDataSourceList">`<ma-data-source-list>`</a> and
* <a ui-sref="ui.docs.ngMango.maDataSourceQuery">`<ma-data-source-query>`</a> directives.
* - All methods return [$resource](https://docs.angularjs.org/api/ngResource/service/$resource) objects that can call the
* following methods available to those objects:
* - `$save`
* - `$remove`
* - `$delete`
* - `$get`
*
* # Usage
*
* <pre prettyprint-mode="javascript">
* const DS = DataSource.getById(xid)
* DS.name = 'New Name';
* DS.$save();
* </pre>
*
* You can also access the raw `$http` promise via the `$promise` property on the object returned:
* <pre prettyprint-mode="javascript">
* promise = DataSource.objQuery(value).$promise;
* promise.then(function(dataSources) {
* $scope.dataSources = dataSources;
*
* console.log('Data Sources retunrned from server:', dataSources);
* }
* </pre>
*
* Or just assign the return value from a DataSource method to a scope variable:
* <pre prettyprint-mode="javascript">
* $scope.dataSources = DataSource.objQuery(value);
* </pre>
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#get
*
* @description
* A default action provided by $resource. Makes a http GET call to the rest endpoint `/rest/latest/data-sources/:xid`
* @param {object} query Object containing a `xid` property which will be used in the query.
* @returns {object} Returns a data source object. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#save
*
* @description
* A default action provided by $resource. Makes a http POST call to the rest endpoint `/rest/latest/data-sources/:xid`
* @param {object} query Object containing a `xid` property which will be used in the query.
* @returns {object} Returns a data source object. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#remove
*
* @description
* A default action provided by $resource. Makes a http DELETE call to the rest endpoint `/rest/latest/data-sources/:xid`
* @param {object} query Object containing a `xid` property which will be used in the query.
* @returns {object} Returns a data source object. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#delete
*
* @description
* A default action provided by $resource. Makes a http DELETE call to the rest endpoint `/rest/latest/data-sources/:xid`
* @param {object} query Object containing a `xid` property which will be used in the query.
* @returns {object} Returns a data source object. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#query
*
* @description
* Passed an object in the format `{query: 'query', start: 0, limit: 50, sort: ['-xid']}` and returns an Array of datasource objects matching the query.
* @param {object} query xid name for the query. Format: `{query: 'query', start: 0, limit: 50, sort: ['-xid']}`
* @returns {array} Returns an Array of datasource objects matching the query. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#rql
*
* @description
* Passed a string containing RQL for the query and returns an array of data source objects.
* @param {string} RQL RQL string for the query
* @returns {array} An array of data source objects. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#getById
*
* @description
* Query the REST endpoint `/rest/latest/data-sources/by-id/:id` with the `GET` method.
* @param {object} query Object containing a `id` property which will be used in the query.
* @returns {object} Returns a data source object. Objects will be of the resource class and have resource actions available to them.
*
*/
/**
* @ngdoc method
* @methodOf ngMangoServices.maDataSource
* @name DataSource#objQuery
*
* @description
* Passed an object in the format `{query: 'query', start: 0, limit: 50, sort: ['-xid']}` and returns an Array of datasource objects matching the query.
* @param {object} query Format: `{query: 'query', start: 0, limit: 50, sort: ['-xid']}`
* @returns {array} Returns an Array of datasource objects matching the query. Objects will be of the resource class and have resource actions available to them.
*
*/
import angular from 'angular';
dataSourceProvider.$inject = [];
function dataSourceProvider() {
const types = [];
this.registerType = function(type) {
const existing = types.find(t => t.type === type.type);
if (existing) {
console.error('Tried to register data source type twice', type);
return;
}
types.push(type);
};
this.$get = dataSourceFactory;
dataSourceFactory.$inject = ['$resource', 'maUtil', '$templateCache', '$http', 'maPoint'];
function dataSourceFactory($resource, Util, $templateCache, $http, Point) {
const defaultProperties = {
name: '',
enabled: false,
polling: true,
modelType: 'VIRTUAL',
descriptionKey: 'VIRTUAL.dataSource',
pollPeriod: {
periods: 1,
type: 'MINUTES'
},
editPermission: [],
purgeSettings: {
override: false,
frequency: {
periods: 1,
type: 'YEARS'
}
},
eventAlarmLevels: [
{eventType: 'POLL_ABORTED', level: 'INFORMATION', duplicateHandling: 'IGNORE', descriptionKey: 'event.ds.pollAborted'}
],
quantize: false,
useCron: false
};
const DataSource = $resource('/rest/latest/data-sources/:xid', {
xid: data => data && (data.originalId || data.xid)
}, {
query: {
method: 'GET',
isArray: true,
transformResponse: Util.transformArrayResponse,
interceptor: {
response: Util.arrayResponseInterceptor
}
},
getById: {
url: '/rest/latest/data-sources/by-id/:id',
method: 'GET',
isArray: false
},
save: {
method: 'POST',
url: '/rest/latest/data-sources',
params: {
xid: null
}
},
update: {
method: 'PUT'
}
}, {
defaultProperties,
xidPrefix: 'DS_'
});
Object.assign(DataSource.notificationManager, {
webSocketUrl: '/rest/latest/websocket/data-sources'
});
Object.assign(DataSource.prototype, {
enable(enabled = true, restart = false) {
this.$enableToggling = true;
const url = '/rest/latest/data-sources/enable-disable/' + encodeURIComponent(this.xid);
return $http({
url,
method: 'PUT',
params: {
enabled: !!enabled,
restart
}
}).then(() => {
this.enabled = enabled;
}).finally(() => {
delete this.$enableToggling;
});
},
getStatus() {
const url = '/rest/latest/data-sources/status/' + encodeURIComponent(this.xid);
return $http({
url,
method: 'GET'
}).then(response => response.data);
}
});
Object.defineProperty(DataSource.prototype, 'isEnabled', {
get() {
return this.enabled;
},
set(value) {
this.enable(value);
}
});
class DataSourceType {
constructor(defaults = {}) {
Object.assign(this, defaults);
// put the templates in the template cache so we can ng-include them
if (this.template && !this.templateUrl) {
this.templateUrl = `dataSourceEditor.${this.type}.html`;
$templateCache.put(this.templateUrl, this.template);
}
}
createDataSource() {
const properties = {
modelType: this.type,
name: '',
enabled: false,
readPermission: [],
editPermission: [],
purgeSettings: {
override: false,
frequency: {
periods: 1,
type: 'YEARS'
}
},
eventAlarmLevels: []
};
// can be a function (e.g. virtual DS), but doesn't matter for setting defaults
if (this.polling) {
Object.assign(properties, {
pollPeriod: {
periods: 1,
type: 'MINUTES'
},
quantize: false,
useCron: false
});
}
if (this.defaultDataSource) {
Object.assign(properties, angular.copy(this.defaultDataSource));
}
return new DataSource(properties);
}
createDataPoint() {
const properties = {
dataSourceTypeName: this.type,
pointLocator: {
modelType: `PL.${this.type}`,
dataType: 'NUMERIC'
},
settable: false
};
if (this.defaultDataPoint) {
const defaultDataPoint = angular.copy(this.defaultDataPoint);
defaultDataPoint.pointLocator = Object.assign(properties.pointLocator, defaultDataPoint.pointLocator);
Object.assign(properties, defaultDataPoint);
}
// create a new data point with default properties
const newPoint = new Point();
// set the data type so it gets default properties for that data type
newPoint.dataType = properties.pointLocator.dataType;
// assign default properties defined by data source type
Object.assign(newPoint, properties);
return newPoint;
}
}
const typeInstances = types.map(type => Object.freeze(new DataSourceType(type)));
const typesByName = Util.createMapObject(typeInstances, 'type');
DataSource.types = Object.freeze(typeInstances);
DataSource.typesByName = Object.freeze(typesByName);
return DataSource;
}
}
export default dataSourceProvider;
|
class Lecture {
constructor(
id,
name,
start,
end,
capacity,
booked_students,
course,
lecturer
) {
Object.assign(this, {
id,
name,
start,
end,
capacity,
booked_students,
course,
lecturer,
});
}
}
|
(function(){
//angular
//.module('linguine.documentation')
//.controller('DocumentationTutorialController', DocumentationTutorialController);
function DocumentationTutorialController($http, $scope, $state) {
$scope.back = function () {
$window.history.back();
};
}
})();
|
import { Component } from 'react'
import Page from '../../layouts/main'
import { play, stop } from '../../experiments/dark-crystal'
const metaData = {
title: 'Nipher - Dark Crystal',
description: 'A generative animated crystal which is generated using the Delaunay triangulation algorithm.',
url: 'https://nipher.io/experiments/dark-crystal'
}
export default class extends Component {
componentDidMount() {
play()
}
componentWillUnmount() {
stop()
}
render() {
return (
<Page meta={metaData}>
<div className='experiment-container'>
<canvas className='dark-crystal-experiment'></canvas>
<style jsx>{`
.dark-crystal-experiment {
height: 100%;
width: 100%;
}
`}</style>
</div>
</Page>
)
}
}
|
$('#btnEdit').on('click', function (e) {
e.preventDefault();
var isDisable = $('#form-name').prop("disabled");
//console.log(isDisable);
if (isDisable) {
$('#form-name').prop("disabled", false);
$('#form-phone').prop("disabled", false);
$('#form-email').prop("disabled", false);
$('#form-password').val('');
$('#form-password').prop("disabled", false);
$('#btnSave').prop("disabled", false);
$('#form-address').prop("disabled", false);
$('#form-gender').prop("disabled", false);
$('#confirm-pass').prop("hidden", false);
$('#btn-edit').text('Hủy');
$('#form-course').prop("disabled", false);
$('#form-major').prop("disabled", false);
$('#form-degree').prop("disabled", false);
} else {
$('#form-name').prop("disabled", true);
$('#form-phone').prop("disabled", true);
$('#form-email').prop("disabled", true);
$('#form-password').val('Khong xem dc dau');
$('#form-password').prop("disabled", true);
$('#btnSave').prop("disabled", true);
$('#btn-edit').text('Thay đổi thông tin');
$('#form-address').prop("disabled", true);
$('#form-gender').prop("disabled", true);
$('#confirm-pass').prop("hidden", true);
$('#form-course').prop("disabled", true);
$('#form-major').prop("disabled", true);
$('#form-degree').prop("disabled", true);
}
});
function validatePhoneNumber(phone) {
var stripped = phone.replace(/[\(\)\.\-\ ]/g, '');
if (phone.length == 0) {
return true;
}
else if (isNaN(parseInt(stripped))) {
$('#phone-error').text("Số điện thoại chứa kí tự không hợp lệ");
return false;
} else if (!(stripped.length == 10)) {
$('#phone-error').text("Số điện thoại không hợp lệ");
return false;
}
return true;
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (email.length == 0) {
return true;
} else if (!re.test(String(email).toLowerCase())) {
$('#email-error').text("Email không hợp lệ");
return false;
}
return true;
}
function validateForm() {
// validate phone
var phone = $('#form-phone').val().trim();
if (validatePhoneNumber(phone)) {
$('#form-phone').val(phone);
document.getElementById("phone-error").style.display="none";
} else {
document.getElementById("phone-error").style.display="block";
return false;
}
// validate email
var email = $('#form-email').val().trim().toLowerCase();
if (validateEmail(email)) {
$('#form-email').val(email);
document.getElementById("email-error").style.display="none";
} else {
document.getElementById("email-error").style.display="block";
return false;
}
return true;
}
$('#btnSave').on('click', function (e) {
if (validateForm()) {
$('#myForm').submit();
}
});
|
import React from 'react'
import styled, { keyframes } from 'styled-components'
import { black, gray30, gray60 } from './colors'
import { Flex, Box } from 'grid-styled'
const spin = keyframes`
0% {
transform: perspective(120px) rotateX(0deg) rotateY(0deg);
} 50% {
transform: perspective(120px) rotateX(-180.1deg) rotateY(0deg);
} 100% {
transform: perspective(120px) rotateX(-180deg) rotateY(-179.9deg);
}
`
export const Spinner = styled(Box)`
height: 100%;
max-width: 40px;
max-height: 40px;
background-color: ${black};
animation: ${spin} 1.2s infinite ease-in-out;
z-index: 3;
`
const Overlay = styled(Flex)`
position: fixed;
display: flex;
top: 0;
left: 0;
height: 100%;
background-color: ${gray60};
z-index: 5000;
`
export const LoadFlex = styled(Flex)`
position: absolute;
height: 100%;
background-color: ${gray30};
z-index: 2;
`
export const Waiting = () => (
<LoadFlex w={1} justifyContent={'center'} alignItems={'center'}>
<Spinner w={1} />
</LoadFlex>
)
export const Loading = () => (
<Overlay w={1} justifyContent={'center'} alignItems={'center'}>
<Spinner w={1} />
</Overlay>
)
|
//Convert the information in the input field into a JSON through an API
|
import React from 'react'
import { NavLink } from 'react-router-dom';
import Navbar from '../assets/Navbar';
import StyleSwitcher from '../assets/StyleSwitcher'
const Portfolio = () => {
return (
<>
<StyleSwitcher />
<Navbar />
<section class="title-section text-left text-sm-center revealator-slideup revealator-once revealator-delay1">
<h1>my<span>portfolio</span></h1>
<span class="title-bg">works</span>
</section>
<section class="main-content text-center revealator-slideup revealator-once revealator-delay1">
<div id="grid-gallery" class="container grid-gallery">
<section class="grid-wrap">
<ul class="row grid">
<li>
<figure>
<img src="img/projects/project-1.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-2.jpg" alt="Portolio " />
<div><span>Youtube Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-3.jpg" alt="Portolio " />
<div><span>Slider Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-4.jpg" alt="Portolio " />
<div><span>Local Video Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-5.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-6.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-7.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-8.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
<li>
<figure>
<img src="img/projects/project-9.jpg" alt="Portolio " />
<div><span>Image Project</span></div>
</figure>
</li>
</ul>
</section>
<section class="slideshow">
<ul>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-12 col-sm-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-12 col-sm-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-12 col-sm-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-12 col-sm-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-1.jpg" alt="Portolio" />
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Youtube Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Video</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Videohive</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">Adobe After Effects</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.videohive.net</NavLink></span>
</div>
</div>
</figcaption>
<div class="videocontainer">
<iframe class="youtube-video" src="https://www.youtube.com/embed/7e90gBu4pas?enablejsapi=1&version=3&playerapiid=ytplayer" allowfullscreen title="video"></iframe>
</div>
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Slider Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Themeforest</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.themeforest.net</NavLink></span>
</div>
</div>
</figcaption>
<div id="slider" class="carousel slide portfolio-slider" data-ride="carousel" data-interval="false">
<ol class="carousel-indicators">
<li data-target="#slider" data-slide-to="0" class="active"></li>
<li data-target="#slider" data-slide-to="1"></li>
<li data-target="#slider" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="img/projects/project-3.jpg" alt="slide 1" />
</div>
<div class="carousel-item">
<img src="img/projects/project-2.jpg" alt="slide 2" />
</div>
<div class="carousel-item">
<img src="img/projects/project-1.jpg" alt="slide 3" />
</div>
</div>
</div>
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Local Video Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Video</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Videohive</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">Adobe Premium</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<video id="video" class="responsive-video" controls poster="img/projects/project-1.jpg">
<source src="img/projects/video.mp4" type="video/mp4" />
</video>
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-5.jpg" alt="Portolio" />
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-6.jpg" alt="Portolio" />
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-7.jpg" alt="Portolio" />
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-8.jpg" alt="Portolio" />
</figure>
</li>
<li>
<figure>
<figcaption>
<h3>Image Project</h3>
<div class="row open-sans-font">
<div class="col-6 mb-2">
<i class="fa fa-file-text-o pr-2"></i><span class="project-label">Project </span>: <span class="ft-wt-600 uppercase">Website</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-user-o pr-2"></i><span class="project-label">Client </span>: <span class="ft-wt-600 uppercase">Envato</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-code pr-2"></i><span class="project-label">Langages </span>: <span class="ft-wt-600 uppercase">HTML, CSS, Javascript</span>
</div>
<div class="col-6 mb-2">
<i class="fa fa-external-link pr-2"></i><span class="project-label">Preview </span>: <span class="ft-wt-600 uppercase"><NavLink to="#" target="_blank">www.envato.com</NavLink></span>
</div>
</div>
</figcaption>
<img src="img/projects/project-9.jpg" alt="Portolio " />
</figure>
</li>
</ul>
<nav>
<span class="icon nav-prev"><img src="img/projects/navigation/left-arrow.png" alt="previous" /></span>
<span class="icon nav-next"><img src="img/projects/navigation/right-arrow.png" alt="next" /></span>
<span class="nav-close"><img src="img/projects/navigation/close-button.png" alt="close" /> </span>
</nav>
</section>
</div>
</section>
</>
)
}
export default Portfolio;
|
import React, { Fragment } from "react";
import InputField from "./InputField";
import Table from "./table";
import calculatePayments from "../utils/math";
export default class Calculator extends React.Component {
state = {
amount: 1000,
duration: 4,
rate: 2,
payments: {
schedule: [],
totals: {}
}
};
handleValueChange = (value, type) => {
this.setState(() => ({ [type]: value }), this.calculatePayments);
};
calculatePayments = () => {
const { amount, duration, rate } = this.state;
const payments = calculatePayments(amount, duration, rate);
this.setState({ payments });
};
componentDidMount = () => {
this.calculatePayments();
};
render() {
return (
<Fragment>
<h1 className="mainTitle">Loan interest calculator</h1>
<p className="infoText">
Interest is charged daily on outstanding balance.
</p>
<div className="inputs">
<div className="inputs__input">
<InputField
varType="amount"
unit="Eur"
handleValueChange={this.handleValueChange}
defValue={this.state.amount}
min={500}
max={10000}
step={100}
key="amount"
/>
</div>
<div className="inputs__input inputs__input--two">
<div className="inputs__input__two">
<InputField
varType="duration"
unit="Months"
handleValueChange={this.handleValueChange}
defValue={this.state.duration}
key="duration"
min={2}
max={18}
step={1}
/>
</div>
<div className="inputs__input__two">
<InputField
varType="rate"
unit="%"
handleValueChange={this.handleValueChange}
defValue={this.state.rate}
key="rate"
min={0.5}
max={7.5}
step={0.1}
/>
</div>
</div>
</div>
<Table payments={this.state.payments} />
</Fragment>
);
}
}
|
class Wall {
bounceDirection;
pos; // top left corner
dimension;
constructor(bounceDirection, x, y, width, height) {
this.bounceDirection = bounceDirection;
this.pos = new Vector(x, y);
this.dimension = new Vector(width, height);
}
get x() {
return this.pos.x;
}
get y() {
return this.pos.y;
}
get width() {
return this.dimension.x;
}
get height() {
return this.dimension.y;
}
isCollideWithBall(ball) {
// Adapted from
// http://jeffreythompson.org/collision-detection/circle-rect.php
let cornerPos = ball.pos.copy();
if (ball.x < this.x) {
cornerPos.x = this.x;
} else if (ball.x > this.x + this.width) {
cornerPos.x = this.x + this.width;
}
if (ball.y < this.y) {
cornerPos.y = this.y;
} else if (ball.y > this.y + this.height) {
cornerPos.y = this.y + this.height;
}
let delta = Vector.subtract(ball.pos, cornerPos);
return delta.magnitude <= ball.radius;
}
draw(scale=1) {
ctx.save();
ctx.fillStyle = data.wall.colour;
ctx.fillRect(this.x*scale, this.y*scale, this.width*scale,
this.height*scale);
ctx.restore();
}
}
|
#pragma strict
import UnityEngine.UI;
import UnityEngine.Events;
var DialogueArea : GameObject;
var Image1Area : Image;
var Image2Area : Image;
var Speaker : Text;
var Dialogue : Text;
var Option1Button : Button;
var Option2Button : Button;
var Option3Button : Button;
var Option1TextArea : Text;
var Option2TextArea : Text;
var Option3TextArea : Text;
private var options = [Option1Button,Option2Button,Option3Button];
public class dialogueSnipitObject {
public var speaker : String;
public var dialogue : String;
public var imageAmount : int;
public var image1 : String;
public var image2 : String;
public var optionAmount : int;
public var option1_text : String;
public var option1_action : UnityAction;
public var option2_text : String;
public var option2_action : UnityAction;
public var option3_text : String;
public var option3_action : UnityAction;
//dialogueSnipitObject constructor
public function dialogueSnipitObject (newSpeaker : String, newDialogue : String, newImageAmount : int, newImage1 : String, newImage2 : String, newOptionAmount : int, newOption1_text : String, newOption1_action : UnityAction, newOption2_text : String, newOption2_action : UnityAction, newOption3_text : String, newOption3_action : UnityAction) {
speaker = newSpeaker;
dialogue = newDialogue;
imageAmount = newImageAmount;
image1 = newImage1;
image2 = newImage2;
optionAmount = newOptionAmount;
option1_text = newOption1_text;
option1_action = newOption1_action;
option2_text = newOption2_text;
option2_action = newOption2_action;
option3_text = newOption3_text;
option3_action = newOption3_action;
}
}
function Start() {
//print('hit');
//start hidden
closeDialogueArea();
}
function loadDialogue(item : dialogueSnipitObject) {
//print('loading dialogue');
//print(item);
//Set up images
var image1Choice = null;
var image2Choice = null;
//load image 1
if(item.imageAmount > 0) {
image1Choice = Resources.Load(item.image1, Sprite);
print(image1Choice);
}
//load image 2
if(item.imageAmount > 1) {
image2Choice = Resources.Load(item.image2, Sprite);
}
//Set up options
var option1Text = '';
var option1Action = null;
var option2Text = '';
var option2Action = null;
var option3Text = '';
var option3Action = null;
//Set up option 1
if(item.optionAmount > 0) {
option1Text = item.option1_text;
option1Action = item.option1_action;
}
//Set up option 2
if(item.optionAmount > 1) {
option2Text = item.option2_text;
option2Action = item.option2_action;
}
//Set up option 3
if(item.optionAmount > 2) {
option3Text = item.option3_text;
option3Action = item.option3_action;
}
UpdateDialogueArea(item.speaker, item.dialogue, item.imageAmount, image1Choice, image2Choice, item.optionAmount, option1Text, option2Text, option3Text, option1Action, option2Action, option3Action);
};
function UpdateDialogueArea(speakerText: String, dialogueText: String, imageAmount: int, image1 : Sprite, image2 : Sprite, optionAmount : int, option1Text: String, option2Text: String, option3Text: String, option1Event : UnityAction, option2Event : UnityAction, option3Event : UnityAction) {
//print('updating Dialogue area');
DialogueArea.SetActive(true);
Speaker.text = speakerText;
Dialogue.text = dialogueText;
//set up option1
Option1Button.onClick.RemoveAllListeners();
Option1Button.onClick.AddListener (option1Event);
Option1TextArea.text = option1Text;
//check if there should be an option 2
if(optionAmount > 1) {
//set up option2
Option2Button.gameObject.SetActive(true);
Option2Button.onClick.RemoveAllListeners();
Option2Button.onClick.AddListener (option2Event);
Option2TextArea.text = option2Text;
} else {
//hide option2
Option2Button.gameObject.SetActive(false);
}
//check if there should be an option 3
if(optionAmount > 2) {
//set up option3
Option3Button.gameObject.SetActive(true);
Option3Button.onClick.RemoveAllListeners();
Option3Button.onClick.AddListener (option3Event);
Option3TextArea.text = option3Text;
} else {
//hide option 3
Option3Button.gameObject.SetActive(false);
}
if(imageAmount > 0) {
Image1Area.gameObject.SetActive(true);
Image1Area.sprite = image1;
} else {
Image1Area.gameObject.SetActive(false);
}
if(imageAmount > 1) {
Image2Area.gameObject.SetActive(true);
Image2Area.sprite = image2;
} else {
Image2Area.gameObject.SetActive(false);
}
}
function closeDialogueArea() {
DialogueArea.SetActive(false);
}
|
import flyout from './modules/flyout.js'
import objectFitImages from 'object-fit-images'
import SmoothScroll from 'smooth-scroll'
import ChangeOnIntersect from './modules/change-on-intersect.js'
import Rellax from 'rellax'
document.addEventListener('DOMContentLoaded', () => {
// run polyfill for object-fit on older browsers
objectFitImages('img[data-ui-aspect-image]')
// set up flyout toggle buttons
flyout('data-js-toggle')
// change bg color of featured projects on scroll
const featureBG = document.querySelector('[data-js-feature-bg-target]')
ChangeOnIntersect('[data-js-feature-bg]', (entry) => {
if (entry.isIntersecting) {
featureBG.style['background'] = entry.target.dataset.jsFeatureBg
}
})
// fade in certain elements when they are scrolled inside the window
ChangeOnIntersect('[data-js-scroll-reveal]', (entry) => {
const types = entry.target.dataset.jsScrollReveal.split(' ')
const toggleClass = entry.target.dataset.jsScrollRevealToggleClass || 'hide-opacity'
const targetName = entry.target.dataset.jsScrollRevealTargets
const targetList = Array.from(document.querySelectorAll(`[data-js-scroll-reveal-target='${targetName}']`))
if (targetList.length > 0) {
targetList.forEach((target) => {
if (entry.isIntersecting) {
types.includes('show') && target.classList.remove(toggleClass)
return
}
types.includes('hide') && target.classList.add(toggleClass)
})
}
})
})
// -> need to declare this variable per SmoothScroll's API
// -> https://github.com/cferdinandi/smooth-scroll
// eslint-disable-next-line no-unused-vars
const scroll = new SmoothScroll('[data-js-scroll], a[href*="#"]', {
speed: 600,
easing: 'easeInOutCubic'
})
// eslint-disable-next-line no-unused-vars
const rellax = new Rellax('[data-js-rellax]')
|
import React from 'react'
import Toggle from './Toggle.jsx'
import Formsy from 'formsy-react'
export const component = Toggle
export const demos = [
{
name: 'Example Toggle Switch',
render: () => (
<Formsy.Form>
<Toggle name='exampleName' />
</Formsy.Form>
)
}, {
name: 'Toggle Switch with different label names',
render: () => (
<Formsy.Form>
<Toggle name='exampleName' labelOn={'Yes'} labelOff={'No'} />
</Formsy.Form>
)
}
]
|
const path = require('path');
var config = {
module: {},
};
var mainConfig = Object.assign({}, config, {
name: 'main',
entry: [
'./source/js/burger-menu.js',
'./source/js/accordion.js',
'./source/js/modal.js',
'./source/js/filter-menu.js',
],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'source/js'),
iife: false,
},
devtool: false
});
var vendorConfig = Object.assign({}, config, {
name: 'vendors',
entry: './source/js/swiper.js',
output: {
filename: 'vendors.js',
path: path.resolve(__dirname, 'source/js'),
iife: false,
},
devtool: false
});
module.exports = [
mainConfig, vendorConfig
];
|
import React from 'react';
import { Router, Route, Link, hashHistory } from 'react-router';
import Loader from '../widgets/Loader.jsx';
import Modal from '../widgets/Modal.jsx';
import BlockTypes from '../blocktypes';
import Api from '../../services/Api';
class TrashBin extends React.Component {
constructor(props) {
super(props);
this.state = {
modal: true,
blocks: [],
selectedBlock: '',
modalState: false,
tooltipState: false,
tooltipMovesState: false,
confirm: false,
activeRow: null,
error: null
};
}
componentDidMount() {
this.serverRequest = $.get('/pages/' + this.props.page.id + '/deletedblocks', function(result) {
this.setState({ blocks: result });
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
handleModalState = (st) => {
this.setState({ modalState: st });
}
selectBlock = (block, i) => {
this.setState({
selectedBlock: block,
activeRow: i,
confirm: true
});
}
iconBox = () => {
this.setState({ toolboxState: !this.state.toolboxState });
if(this.state.editBlock == true){
this.setState({ editBlock: false});
}
}
restoreBlock = () => {
var self = this;
Api
.put('/blocks/restore', this.state.selectedBlock)
.then(function(item) {
//self.setState({ modal: false });
self.props.restored(item);
})
.catch(function () {
self.setState({ error: 'There was a problem restoring a block' });
});
this.props.active(false);
}
closeModal = (st) => {
this.setState({ modal: !this.state.modal });
this.props.active(false);
}
render() {
var that = this;
return (
<Modal active={this.closeModal} mystyle={"trashBin"} title={"Blocs supprimés"}>
<div id="trashBin-table">
<table id="trashBin-files">
<thead>
<tr>
<th>Type</th>
<th>Nom</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{ this.state.blocks.map(function(block, i) {
return(
i === that.state.activeRow
? <tr className={"row deleted-block row-active"} key={block.id} onClick={that.selectBlock.bind(that, block, i)}>
<td>
<div className={"icon " + BlockTypes[block.blocktype_id].color}>
<i className={BlockTypes[block.blocktype_id].icon}></i>
</div>
</td>
<td>
{ block.name !== ""
? block.name
: BlockTypes[block.blocktype_id].title
}
</td>
<td>{block.updated_at.split("T")[0].split("-").reverse().join("/")}</td>
</tr>
: <tr className={"row deleted-block"} key={block.id} onClick={that.selectBlock.bind(that, block, i)}>
<td>
<div className={"icon " + BlockTypes[block.blocktype_id].color}>
<i className={BlockTypes[block.blocktype_id].icon}></i>
</div>
</td>
<td>
{ block.name !== ""
? block.name
: BlockTypes[block.blocktype_id].title
}
</td>
<td>{block.updated_at.split("T")[0].split("-").reverse().join("/")}</td>
</tr>
);
})}
</tbody>
</table>
</div>
<div id="trashBin-preview">
<p>coucou je suis l’appercu</p>
{ that.state.confirm
? <button className="btn btn-defaul" onClick={that.restoreBlock}>Restaurer</button>
: null
}
</div>
</Modal>
);
}
}
export default TrashBin;
|
import dotenv from 'dotenv';
import { eventNames } from 'cluster';
dotenv.config();
let envConfig = {};
envConfig.db_username = process.env.DATABASE_USERNAME_DEV;
envConfig.db_password = process.env.DATABASE_PASSWORD_DEV;
envConfig.port = process.env.PORT || 7000;
envConfig.db_username_test = process.env.DATABASE_USERNAME_TEST;
envConfig.db_password_test = process.env.DATABASE_PASSWORD_TEST;
envConfig.db_username_pro = process.env.HEROKU_DATABASE_USERNAME;
envConfig.db_password_pro = process.env.HEROKU_SECRET_KEY;
envConfig.db_host_pro = process.env.HEROKU_HOST;
envConfig.db_database_pro = process.env.HEROKU_DATABASE;
envConfig.send_grid_key = process.env.SendGridApiKey;
envConfig.host = process.env.HOST;
envConfig.token = process.env.SECRET_JWT_KEY;
envConfig.email = process.env.EMAIL;
envConfig.password = process.env.PASSWORD;
envConfig.facebook_app_id = process.env.FACEBOOK_APP_ID;
envConfig.facebook_app_secret = process.env.FACEBOOK_APP_SECRET;
envConfig.secret = process.env.SECRET;
envConfig.google_app_id = process.env.GMAIL_APP_ID;
envConfig.google_app_secret = process.env.GMAIL_APP_SECRET;
envConfig.twitter_app_id = process.env.TWITTER_APP_ID;
envConfig.twitter_app_secret = process.env.TWITTER_APP_SECRET;
envConfig.twitter_access_token = process.env.TWITTER_ACCESS_TOKEN;
envConfig.twitter_access_secret = process.env.TWITTER_ACCESS_SECRET;
envConfig.twitter_callback = process.env.CALLBACK;
export default envConfig;
|
import request from '@/utils/request'
// 获取资源分类列表
export const getResourceCategoryList = () => {
return request({
url: '/resourceCategory/listAll',
})
}
|
import React, { Component } from "react";
import { Text, TouchableHighlight } from "react-native";
import quizPageStyles from "../../styles/QuizPageStyle";
export default class SubmitButton extends Component {
constructor(props){
super(props)
}
checkAns=()=>{
console.log("ami hoici");
}
handleChange=()=>{
console.log(props);
}
render() {
return (
<TouchableHighlight
underlayColor="#DCEDC8"
style={quizPageStyles.submitButton}
onClick={this.changeColor}
onPress={this.handleChange.bind(this)}
>
<Text style={quizPageStyles.buttonTextStyle}>Submit</Text>
</TouchableHighlight>
);
}
}
|
// module
function makeFormSexyToy(material) {
return new Promise((resolve, reject) => {
try {
let hasError = false;
if (hasError) throw 'error!!!'
console.log('creating toy\'s form... with material:' + material)
let form = 'toy form'
setTimeout(() => {
// form is completed
resolve(form)
}, 1000)
} catch (e) {
reject(e)
}
})
}
function fillSexyToy(form, material) {
return new Promise(resolve => {
let toy = 'toy';
console.log('filling toy... with material:' + material)
setTimeout(() => {
resolve(toy)
}, 1000)
});
}
function wrapSexyToy(toy) {
return new Promise(resolve => {
console.log('wrapping toy...')
let wrapedToy = 'wraped toy';
setTimeout(() => {
resolve(wrapedToy)
}, 1000)
});
}
async function startSexyToysConveer() {
let form = await makeFormSexyToy('пластик');
let toy = await fillSexyToy(form, 'selicone');
let wrapedToy = await wrapSexyToy(toy);
console.log('fatality motherfucker')
}
// client
startSexyToysConveer();
let interval = setInterval(() => {
console.log('some another work!')
}, 1000);
setTimeout(() => {
clearInterval(interval)
}, 4000)
|
const test = require('../../test');
module.exports = function(argv) {
let options = {
fnName: 'getLongest',
esVersion: 5,
allowHigherOrderFns: false
};
let test1 = {
input: 'getLongest(["",""])',
expected: ''
};
let test2 = {
input: 'getLongest(["sam","jake","jill"])',
expected: 'jake'
};
let test3 = {
input: 'getLongest(["-5","-7","-94"])',
expected: '-94'
};
test(argv, [test1, test2, test3], options);
};
|
import React from 'react';
import { Icon } from 'antd';
import { graphql } from 'react-apollo';
import { LikeQuestionToggleMutation } from '../../graphql/mutations';
const styles = {
flex: {
display: 'flex',
flexDirection: 'row',
},
};
const LikeButton = ({ likesCount, isLiked, like }) => (
<div style={styles.flex}>
<Icon
onClick={like}
type="heart"
style={{
paddingRight: 5,
cursor: 'pointer',
fontSize: 24,
color: !isLiked ? 'rgb(205, 205, 217)' : '#FF643C',
}}
/>
<p style={{ color: '#000' }}> {likesCount} </p>
</div>
);
export default graphql(LikeQuestionToggleMutation, {
props: ({ ownProps, mutate }) => ({
like() {
return mutate({
variables: { questionID: ownProps.id },
optimisticResponse: {
__typename: 'Mutation',
likeQuestionToggle: {
__typename: 'QuestionResponse',
question: {
__typename: 'Question',
_id: ownProps.id,
likesCount: ownProps.isLiked ? ownProps.likesCount - 1 : ownProps.likesCount + 1,
isLiked: !ownProps.isLiked,
},
},
},
});
},
}),
})(LikeButton);
|
import actionTypes from "../constants/actionTypes";
function eventsReceived(events) {
return {
type: actionTypes.EVENTS_RECEIVED,
events: events
};
}
function eventItemReceived(eventItem) {
return {
type: actionTypes.EVENTITEM_RECEIVED,
eventItem: eventItem
};
}
function eventItemLoading() {
return {
type: actionTypes.EVENTITEM_LOADING
};
}
function addParticipant(username, attendance) {
return {
type: actionTypes.EVENTS_ADDPARTICIPANT,
username: username,
attendance: attendance
};
}
export function fetchEvents() {
return dispatch => {
return fetch(`/events`)
.then(response => response.json())
.then(data => dispatch(eventsReceived(data.data)))
.catch(e => console.log(e));
};
}
export function fetchEventItem(id) {
return dispatch => {
return fetch(`/events/${id}`)
.then(response => response.json())
.then(data => dispatch(eventItemReceived(data.data)))
.catch(e => console.log(e));
};
}
export function submitEvent(data) {
return dispatch => {
return fetch("/events/", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data),
mode: "cors"
}).catch(e => console.log(e));
};
}
export function submitSignUp(eventItemID, username, data) {
var token = localStorage.getItem("token") || null;
return dispatch => {
return fetch(`/events/${eventItemID}/signup`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(data),
mode: "cors"
})
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
} else {
dispatch(addParticipant(username, data.attendance));
}
})
.catch(e => console.log(e));
};
}
|
var DL_URL = "http://10.178.1.235:8080/hisservice/download/download.txt";
var DL_CLASSID = "C7D9243C-85E8-4C4A-8995-77F682FA3336";
var DL_CAB = "yh_down.CAB#version=1,0,0,0";
var DL_EXE = "yh_ax_install.EXE";
function getDlHtml() {
//return document.write('<div id="div_download" style="position:absolute;width:500px;height:300px;left:50%;top:50%;margin-left:-250px;margin-top: -150px; z-index:9999999999"><OBJECT ID="yh_down" CLASSID="CLSID:' + DL_CLASSID + '" codebase="' + DL_CAB + '"'
// + '<param name="URL" value="' + DL_URL + '"></OBJECT></div>');
return document.write('<div id="div_download" style="position:absolute;width:500px;height:300px;left:50%;top:50%;margin-left:-250px;margin-top: -150px; z-index:9999999999"><OBJECT ID="yh_down" CLASSID="CLSID:' + DL_CLASSID
+ '"></OBJECT></div>');
}
function checkInstall() {
try {
var comActiveX = new ActiveXObject("yh_down.download");
} catch (e) {
return false;
}
return true;
}
function getDownHtml() {
return document.write('<div id="div_dwsetup" style="vertical-align:middle;position:absolute;width:300px;height:100px;left:50%;top:50%;margin-left:-150px;margin-top: -50px; z-index:9999999999"><a href="' + DL_EXE + '"><img src ="setup.png" /></a></div>');
}
function dw_hide_div(){
var div_dl = document.getElementById("div_download");
if (div_dl) {
div_dl.parentNode.removeChild(div_dl);
}
}
function dw_hide() {
window.setTimeout(dw_hide_div,2000);
}
function yh_dw_init() {
if (!checkInstall()) {
getDownHtml();
} else {
getDlHtml();
var yh_down = document.getElementById("yh_down");
if (navigator.appName == "Microsoft Internet Explorer" && (navigator.appVersion.match(/8./i) == "8." || navigator.userAgent.indexOf("MSIE 8.0") > 0 || navigator.appVersion.match(/7./i) == "7.")){
yh_down.attachEvent("hide", dw_hide);
} else {
window.addEventListener("hide", dw_hide);
}
yh_down.init(DL_URL);
}
}
function getOcxObject(name,bz){
try {
var comActiveX = new ActiveXObject("yh_down.download");
var OcxObject = null;
if (bz=='0'){
OcxObject = new ActiveXObject(comActiveX.getOcx(DL_URL,name,bz));
}else{
OcxObject = document.getElementById("yh_ocx_" + name);
}
comActiveX = null;
return OcxObject;
} catch (e) {
return null;
}
}
function getOcxhtml(name){
try {
var comActiveX = new ActiveXObject("yh_down.download");
return document.write('<OBJECT ID="yh_ocx_' + name + '" CLASSID="CLSID:' + comActiveX.getOcx(DL_URL,name,"1") + '"></OBJECT>');
comActiveX = null;
} catch (e) {
return null;
}
}
|
export { TruncatedText } from './truncated-text';
|
import * as UserController from "../user.controller";
import * as AuthController from "../../auth/auth.controller";
import {Users, Configuration} from "../../../db/models";
import HTTPStatus from "http-status";
import {
buildNext,
buildReq,
buildRes,
createNewUser,
returnExpectations,
} from "../../../utils/test-helpers";
var configuration = null;
beforeEach(async () => {
jest.resetAllMocks();
await Users.destroy({where: {}});
// configuration = await Configuration.create( {name: 'SMS GLOBAL', user: 'kwamekert', password: 'password', apiKey: '23asdf23423', stat: 'active'});
});
async function clearUsers() {
await Users.destroy({where: {}});
// await Configuration.destroy({ where: {} });
}
describe("Fetch All Users", () => {
test("should return 200", async () => {
let req1 = buildReq({
body: {
email: "kwames@gmail.com",
username: "kwamekert",
password: "password",
},
});
let req2 = buildReq({
body: {
email: "kwame@gmail.com",
username: "kwameker",
password: "password",
},
});
let res1 = buildRes();
let nxtFxn = buildNext();
// await AuthController.register(req1, res1, nxtFxn);
// await AuthController.register(req2, res1, nxtFxn);
// let req = buildReq();
// let res = buildRes();
// await UserController.gellAllUsers(req, res, nxtFxn);
// returnExpectations(res, HTTPStatus.OK);
});
});
|
const { describe, it } = global
import expect from 'expect'
import skipReducer from './skip.js'
import { skipActions } from './../constants/actiontypes'
describe('Reducers – skip', () => {
it('should return the initial state', () => {
expect(
skipReducer(undefined, {})
).toEqual({skip: 0})
})
it('should set a skip amount', () => {
expect(
skipReducer(skipActions.SET, {type: skipActions.SET, skip: 0})
).toEqual({skip: 0})
expect(
skipReducer(skipActions.SET, {type: skipActions.SET, skip: 1})
).toEqual({skip: 1})
expect(
skipReducer(skipActions.SET, {type: skipActions.SET, skip: 10})
).toEqual({skip: 10})
})
it('should reset a skip amount', () => {
expect(
skipReducer(skipActions.RESET, {})
).toEqual({skip: 0})
expect(
skipReducer(skipActions.RESET, {skip: 100})
).toEqual({skip: 0})
})
})
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import styled from 'styled-components';
import { space, width } from 'styled-system';
import Icons from '../../icons';
import Icon from '../icon/Icon';
import IconsStore from '../icon/IconsStore';
import Text from '../text/Text';
import Calendar from '../calendar/Calendar';
import withDisplayName from '../WithDisplayName';
import { FONT_TYPES } from '../base/Typography';
import { COLORS } from '../base/Colors';
import './DateInput.scss';
const DateInputContainer = styled.div`
${width};
${space};
${props => (props.extendInputDate ? props.extendInputDate : '')};
`;
const InputContainerCalendar = styled.div`
${props => (props.extendInputContainerCalendar ? props.extendInputContainerCalendar : '')};
`;
class DateInput extends Component {
constructor(props) {
super(props);
this.iconsStore = new IconsStore(Icons);
this.state = {
isCalendarOpened: this.props.showCalendar,
date: this.props.date,
errorMessage: '',
iconClassName: undefined,
isDanger: false,
enableValidation: true,
};
}
componentDidMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillReceiveProps(nextProps) {
if (nextProps.date === undefined || nextProps.date === null) {
if (nextProps.resetOnUndefined) {
this.resetSelect();
}
} else {
const stateObj = {};
let check = false;
if (nextProps.showCalendar === false) {
stateObj.showCalendar = false;
check = true;
}
if (nextProps.date !== this.props.date) {
stateObj.date = nextProps.date;
check = true;
}
if (check) {
this.setState(stateObj);
}
}
}
componentDidUpdate(_, prevState) {
if (
(prevState.showCalendar && !this.state.isCalendarOpened) ||
this.state.date !== prevState.date
) {
this.validate();
}
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
onChange = e => {
this.setState(
{
date: this.props.enableClear && this.state.date ? '' : e.date,
enableValidation: true,
},
() => {
this.hideCalendar();
if (this.props.onChange) {
this.props.onChange({ date: e.date });
}
},
);
};
setWrapperRef = node => {
this.wrapperRef = node;
};
toggleCalendar = () => {
if (!this.props.disabled) {
if (this.state.isCalendarOpened) {
this.hideCalendar();
} else {
this.showCalendar();
}
}
};
showCalendar = () => {
if (!this.props.disabled) {
this.setState({
isCalendarOpened: true,
iconClassName: 'icon--up',
enableValidation: true,
});
}
};
hideCalendar = () => {
if (!this.props.disabled) {
this.setState({
isCalendarOpened: false,
iconClassName: 'icon--down',
enableValidation: true,
});
}
};
handleClickOutside = event => {
const isVisibleScrollBar = window.innerWidth > document.documentElement.clientWidth;
const isClickOnScrollBar = window.outerWidth - 18 <= event.x;
if (
this.wrapperRef &&
!this.wrapperRef.contains(event.target) &&
(!isVisibleScrollBar || (isVisibleScrollBar && !isClickOnScrollBar)) &&
this.state.isCalendarOpened
) {
this.setState({
isCalendarOpened: false,
iconClassName: 'icon--down',
enableValidation: true,
});
}
};
/**
* Changes the error message and shows it
* @param {string} message
*/
showErrorMessage = message => {
this.setState({
errorMessage: message,
isDanger: true,
enableValidation: true,
});
};
/**
* Removes error message
*/
hideErrorMessage = () => {
this.setState({
errorMessage: '',
isDanger: false,
enableValidation: true,
});
};
/**
* Checks if input is valid
*/
isValid = () => {
if (this.props.isRequired && this.state.enableValidation) {
if (this.state.date === '' || this.state.date === undefined) {
return false;
}
}
return true;
};
/**
* Validates input
*/
validate = () => {
if (!this.isValid()) {
this.showErrorMessage(
this.props.isArabic
? `${this.props.placeholder} مطلوب`
: `${this.props.placeholder} required`,
);
} else {
this.hideErrorMessage();
}
};
focus = () => {
this.showCalendar();
};
resetSelect = () => {
this.setState({
date: '',
enableValidation: false,
});
};
localizeDate = (date, locale) => {
if (date !== '' && date !== undefined) {
let dateArr;
if (date.includes('/')) {
dateArr = `${date}`.split('/');
} else if (date.includes('-')) {
dateArr = `${date}`.split('-');
}
const selectedYear = dateArr[2];
const selectedMonth = dateArr[0] - 1;
const selectedDay = dateArr[1];
const localized = new Date(selectedYear, selectedMonth, selectedDay).toLocaleDateString(
locale,
{
year: 'numeric',
month: 'numeric',
day: 'numeric',
},
);
return date !== undefined ? localized : '';
}
return date;
};
render() {
const {
onChange,
isArabic,
reverse,
className,
extendInputDate,
extendInputContainerCalendar,
...filteredProps
} = this.props;
const calendarInputContainerClasses = classnames('input-date-container', className, {
'input-date-container--disabled': this.props.disabled,
});
const calendarContainerClasses = classnames(
'calendar',
{
'calendar-show': this.state.isCalendarOpened,
},
{
'calendar-hide': !this.state.isCalendarOpened,
},
);
return (
<DateInputContainer
innerRef={div => {
this.wrapperRef = div;
}}
className={calendarInputContainerClasses}
{...filteredProps}
extendInputDate={extendInputDate}
>
<InputContainerCalendar
className={classnames('input-container--calendar', {
'input-container--active': this.state.isCalendarOpened,
'input-date-container--danger': this.state.isDanger,
})}
tabIndex="0"
onClick={this.toggleCalendar}
onKeyDown={() => {}}
extendInputContainerCalendar={extendInputContainerCalendar}
>
<input
className={isArabic || reverse ? 'input-value-reverse' : 'input-value'}
placeholder={this.props.placeholder}
value={this.localizeDate(this.state.date, isArabic ? 'ar-EG' : 'en-US')}
readOnly="readonly"
autoComplete="off"
/>
<div className={classnames('icon-container', this.state.iconClassName)}>
<Icon icon={this.iconsStore.getIcon('dropdown')} width={18} color={COLORS.TEXT} />
</div>
</InputContainerCalendar>
<Text tag="span" type={FONT_TYPES.CAPTION} className="date-input-error">
{this.state.errorMessage}
</Text>
<div className={calendarContainerClasses}>
<Calendar
onChange={this.onChange}
date={this.state.date}
type="single"
minDate={this.props.minDate}
maxDate={this.props.maxDate}
dateFormat={this.props.dateFormat}
id={this.props.id}
isArabic={isArabic}
/>
</div>
</DateInputContainer>
);
}
}
DateInput.propTypes = {
className: PropTypes.string,
id: PropTypes.string,
placeholder: PropTypes.string, // show, if label empty
onChange: PropTypes.func,
date: PropTypes.string,
minDate: PropTypes.string,
maxDate: PropTypes.string,
dateFormat: PropTypes.oneOf(['yyyy-mm-dd', 'mm/dd/yyyy', '']),
showCalendar: PropTypes.bool, // false: hide Calendar
enableClear: PropTypes.bool, // false: each click- input, true: first click- input, second- clear
isRequired: PropTypes.bool,
disabled: PropTypes.bool,
resetOnUndefined: PropTypes.bool,
isArabic: PropTypes.bool,
reverse: PropTypes.bool,
};
DateInput.defaultProps = {
enableClear: false,
resetOnUndefined: false,
className: undefined,
id: undefined,
placeholder: undefined,
onChange: () => {},
date: undefined,
minDate: undefined,
maxDate: undefined,
dateFormat: 'mm/dd/yyyy',
showCalendar: false,
isRequired: false,
disabled: false,
isArabic: false,
reverse: false,
};
export default withDisplayName(DateInput, 'DateInput');
|
const { red, blue, yellow, cyan, green } = require("colorette")
var index = require("../daos/IndexDAO");
function saludar(req,res) {
res.json({
mensaje:index.mensaje()
});
}
module.exports = {
saludar:saludar,
};
|
setInterval(function() {
var elements = document.getElementsByClassName("heading style-scope tf-collapsable-pane");
var requiredElement = elements[0];
requiredElement.click();
requiredElement.click();
}, 5000);
|
var sendContact = ( function($) {
'use strict';
var URL = 'https://od3wrrb5ne.execute-api.us-east-1.amazonaws.com/prod/siteContact'
const GENERIC_FAILURE_MESSAGE = 'Sorry, We can not process your request at this time. Please resubmit at a later time.';
function onSubmitContactForm() {
// grecaptcha.execute();
$('#contact-form').submit();
}
function objectifyForm(form) {//serialize data function
var formArray = form.serializeArray();
var returnArray = {};
for (var i = 0; i < formArray.length; i++){
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
function processContactFormSubmit(e) {
var $form = $("#contact-form");
var data = objectifyForm($form);
$.ajax({
type: 'POST',
url: URL,
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json',
success: function(data) {
// $("#success-message").show();
$form.data('bootstrapValidator').resetForm();
},
error: function(err) {
if(err.status === 400) {
// $("#failure-message-text").text(err.responseText);
} else {
// $("#failure-message-text").text(GENERIC_FAILURE_MESSAGE);
}
// $("#failure-message").show();
$form.data('bootstrapValidator').resetForm();
}
});
}
$(document).ready(function() {
$(document).on('click', '.close', function () {
$(this).parent().hide();
});
$('#contact-form').bootstrapValidator({
container: "#validation-messages",
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
name: {
validators: {
notEmpty: {
message: 'Please enter your name'
}
}
},
email: {
validators: {
notEmpty: {
message: 'Please enter your email address'
},
emailAddress: {
message: 'Please enter a valid email address'
}
}
},
message: {
validators: {
stringLength: {
max: 500,
message:'Please enter at least 10 characters and no more than 500'
},
notEmpty: {
message: 'Please enter a message'
}
}
}
}
})
.on('success.form.bv', function(e) {
// $("#success-message").hide();
// $("#failure-message").hide();
e.preventDefault();
processContactFormSubmit(e);
});
});
return {
onSubmitContactForm: onSubmitContactForm
};
})(jQuery);
var onSubmitContactForm = sendContact.onSubmitContactForm; // Needs a global function for reCaptcha
|
const Controller = require('egg').Controller
const path = require('path')
const loadCSV = require('../util/loadCSV')
class GoodController extends Controller {
async index () {
await this.ctx.render('page/good/list.njk')
}
async list () {
const { ctx } = this
const { sort } = ctx.request.query
if (sort) {
const [ type, order ] = sort.split('-')
ctx.body = await ctx.service.good.list({
type: order
})
} else {
ctx.body = await ctx.service.good.list()
}
}
async create () {
// const { ctx, service } = this
// const res = await service.material.create(req)
// // 设置响应内容和响应状态码
// ctx.body = { id: res.id }
// ctx.status = 201
}
// 导入
async leadIn () {
const { ctx, service } = this
const goods = await loadCSV(path.resolve(ctx.app.config.baseDir, 'app/record/good.csv'))
const result = await service.good.leadIn(goods)
ctx.body = result
}
}
module.exports = GoodController
|
import React from 'react'
import { browserHistory, Router, Route } from 'react-router'
import App from "./containers/App"
import Game from './components/Game'
import Home from './components/Home'
export default class Routes extends React.Component {
render() {
return (
<Router history={browserHistory}>
<Route path='/' component={App}>
<Route path='/home' component={Home} />
<Route path='/game' component={Game}>
<Route path='/game/:id' component={Game} />
</Route>
</Route>
</Router>
)
}
}
|
function timer(){
if(seg!=0)
{
seg=seg-1;
}
if(seg==0)
{
if(min==0)
{
clearInterval(eliminar);
clearInterval(newdulces);
clearInterval(intervalo);
clearInterval(tiempo);
$( ".panel-tablero" ).hide("drop","slow",callback);
$( ".time" ).hide();
}
seg=59;
min=min-1;
}
$("#timer").html("0"+min+":"+seg)
}
|
/**
* Module for displaying "Waiting for..." dialog using Bootstrap
*
* @author Eugene Maslovich <ehpc@em42.ru>
*/
var waitingDialog = (function ($) {
// Creating modal dialog's DOM
var $dialog = $(
'<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-hidden="true" style="padding-top:15%; overflow-y:visible;">' +
'<div class="modal-dialog modal-m">' +
'<div class="modal-content">' +
'<div class="modal-header"><h3 style="margin:0;"></h3></div>' +
'<div class="modal-body">' +
'<div class="progress progress-striped active" style="margin-bottom:0;"><div class="progress-bar" style="width: 100%"></div></div>' +
'</div>' +
'</div></div></div>');
return {
/**
* Opens our dialog
* @param message Custom message
* @param options Custom options:
* options.dialogSize - bootstrap postfix for dialog size, e.g. "sm", "m";
* options.progressType - bootstrap postfix for progress bar type, e.g. "success", "warning".
*/
show: function (message, options) {
// Assigning defaults
var settings = $.extend({
dialogSize: 'm',
progressType: ''
}, options);
if (typeof message === 'undefined') {
message = 'Loading';
}
if (typeof options === 'undefined') {
options = {};
}
// Configuring dialog
$dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
$dialog.find('.progress-bar').attr('class', 'progress-bar');
if (settings.progressType) {
$dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
}
$dialog.find('h3').text(message);
// Opening dialog
$dialog.modal();
},
/**
* Closes dialog
*/
hide: function () {
$dialog.modal('hide');
}
}
})(jQuery);
$(document).ajaxStart(function () {
waitingDialog.show('Waiting...');
});
$(document).ajaxSuccess(function () {
waitingDialog.hide();
});
function callAsyncAjaxMethod(requestUrl, requestParam, callbackFunction, errorFunction)
{
if (requestUrl == '' || requestUrl === undefined) return null;
if (requestParam === null || requestParam === undefined) requestParam = '';
try {
$.ajax({
type: 'POST',
data: JSON.stringify(requestParam),
contentType: "application/json; charset=utf-8",
dataType: "json",
url: requestUrl,
async: true,
cache: false,
success: callbackFunction,
error: function (jqXHR, status, error) {
console.log(requestUrl, jqXHR, status, error);
if (errorFunction !== undefined)
errorFunction(jqXHR, status, error);
}
});
} catch (err) {
console.log(err.message);
}
return true;
}
$('.number-only').keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
|
var basepath = $("#basepath").val();
var json;
$(document).ready(function() {
$.ajax({
type: "GET",
url: basepath + "/manage/organization/rest/init",
dataType: "json",
success: function(result) {
var data = [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" , "type" : "organization" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" ,"type" : "organization" ,'state':{'opened': 'true'} },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" ,"type" : "work" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" ,"type" : "work" },
];
json = data;
$('#jstree1').jstree({
"core": {
//激活删除节点功能
'check_callback': true,
//用于生成tree的数据
"data": data
},
'plugins': ['types', 'dnd', 'contextmenu'],
'types': {
'default': {
'icon': 'fa fa-folder'
},
'html': {
'icon': 'fa fa-file-code-o'
},
'svg': {
'icon': 'fa fa-file-picture-o'
},
'css': {
'icon': 'fa fa-file-code-o'
},
'img': {
'icon': 'fa fa-file-image-o'
},
'js': {
'icon': 'fa fa-file-text-o'
}
},
'contextmenu': {
select_node: false,
show_at_node: true,
'items': {
'create': {
//Create这一项在分割线之前
'separator_before': false,
//Create这一项在分割线之后
'separator_after': true,
//false表示 create 这一项可以使用; true表示不能使用
'_disabled': false,
'label': '添加用户',
'icon': 'fa fa-plus',
//点击Create这一项触发该方法,这理还是蛮有用的
'action': function(data) {
//增加组织机构div显示
$("#ibox1").css("display", "none");
//提示div隐藏
$("#ibox2").css("display", "");
//焦点移动至输入名称项
$("#userLoginName").focus();
//获得当前节点,可以拿到当前节点所有属性
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
$("#parentUuid").val(obj.id);
//新加节点,以下三行代码注释掉就不会添加节点
/* inst.create_node(obj, {},"last",function(new_node) {
//新加节点后触发 重命名方法,即 创建节点完成后可以立即重命名节点
setTimeout(function() {inst.edit(new_node);},0);
}); */
}
},
'rename': {
//rename这一项在分割线之前
'separator_before': false,
//rename这一项在分割线之后
'separator_after': true,
//false表示 create 这一项可以使用; true表示不能使用
'_disabled': false,
'label': '重命名',
//点击Create这一项触发该方法,这理还是蛮有用的
'action': function(data) {
//获得当前节点,可以拿到当前节点所有属性
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
inst.edit(obj);
}
},
'delete': {
//delete这一项在分割线之前
'separator_before': false,
//delete这一项在分割线之后
'separator_after': true,
//false表示 create 这一项可以使用; true表示不能使用
'_disabled': false,
'label': '刪除',
//点击delete这一项触发该方法,这理还是蛮有用的
'action': function(data) {
//获得当前节点,可以拿到当前节点所有属性
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
if(inst.is_selected(obj)) {
inst.delete_node(inst.get_selected());
} else {
inst.delete_node(obj);
}
$.ajax()
}
}
}
}
});
}
});
//按钮增加节点用
/* $("#bumen").click(function(){
.bind("loaded.jstree", function () {
jQuery("#jstree1").jstree("open_all");
}).bind("create_node.jstree",function(event,data){
createCategory(event,data);
})
$('#jstree1').jstree("create");
}); */
});
function createSubmit() {
$.ajax({
type: 'post',
url: basepath + '/manage/user/rest/create',
data: {
userLoginName: $("#userLoginName").val(),
userName: $("#userName").val()
},
beforeSend: function() {
// todo check
},
success: function(result) {
alert(result.message);
refreshTree();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
function refreshTree(){
var tree = $('#jstree1');
tree.jstree({'core':{data:null}});
var obj = { "id" : "ajson5", "parent" : "ajson2", "text" : "Child 3" }
json.push(obj);
var node = tree.jstree("get_node","ajson2");
tree.jstree(true).settings.core.data = json;
tree.jstree(true).refresh(node.id);
}
$("#add").click(function() {
createSubmit();
});
|
import React, { Component, Fragment } from 'react';
import { Button, TextField } from '@material-ui/core';
import SelectMenu from '../../../components/Select/';
import { getAspiranteById, saveAspirante, getRamas, getEstudios, getPuestos, getZonas, getFolio, editAspirante, handleSnackbar } from "../../actions";
import { connect } from 'react-redux';
import { numericCharacters, camelizeString } from "../../../utils"
import moment from 'moment';
import AlertDialog from '../../../components/DialogConfirm';
import { GUARDAR_OTRO_A, EDITAR_AGAIN_A } from '../../../constants';
import "./edit.css"
const initialState = { folio: "", id: false, birthday: "", maternal: "", paternal: "", name: "", studies: "", branch: "", position: "", zone: "", reason: "", list: "", scholarship: 0, relationship: 0, registry: 0, service: 0 }
class Edit extends Component {
state = {
...initialState,
loading: true,
isSave: false,
estatus: "ACTIVO"
}
async componentDidMount() {
const { match, getAspiranteById } = this.props;
if (match.params && match.params.id) {
await getAspiranteById(match.params.id);
} else {
const folio = await this.props.getFolio();
if (folio && typeof folio == "string") {
this.setState({ folio })
}
}
await this.props.getEstudios();
await this.props.getPuestos();
await this.props.getRamas();
await this.props.getZonas();
this.setState({ loading: false })
}
UNSAFE_componentWillReceiveProps(nextProps) {
const { aspirante } = nextProps
if (this.props.aspirante !== aspirante && aspirante && aspirante.data && aspirante.status === 200) {
const { puntaje: { escolaridad, tiempoServicio, tiempoRegistro, parentesco }, id, motivo_baja, estatus, folio, fecha, apellidoPaterno, nombre, apellidoMaterno, idEstudios, idRama, idPuesto, idZona, listado } = aspirante.data;
this.setState({
folio: folio, reason: motivo_baja, estatus, id: parseInt(id), birthday: moment(fecha).format("YYYY-MM-DD"), name: nombre, maternal: apellidoMaterno, paternal: apellidoPaterno, studies: idEstudios, branch: idRama, position: idPuesto, zone: idZona, list: listado, scholarship: escolaridad, relationship: parentesco, registry: tiempoRegistro, service: tiempoServicio
});
}
}
handleChange = ({ target: { value, id, name } }) => {
this.setState({ [name || id]: value });
}
saveAspirante = async () => {
const { folio, birthday, estatus, name, maternal, reason, id, paternal, studies, branch, position, zone, list, scholarship, relationship, registry, service } = this.state;
const data = {
aspirante: {
id: id || null,
folio,
idEstudios: studies,
idRama: branch,
idPuesto: position,
idZona: zone,
nombre: camelizeString(name),
apellidoPaterno: camelizeString(paternal),
apellidoMaterno: camelizeString(maternal),
listado: list,
fecha: birthday,
estatus,
},
puntaje: {
escolaridad: scholarship,
tiempoRegistro: registry,
tiempoServicio: service,
parentesco: relationship,
total: parseInt(scholarship) + parseInt(registry) + parseInt(service) + parseInt(relationship)
}
}
let save = {}
const { match } = this.props;
if (match.params && match.params.id) {
save = await this.props.editAspirante(data);
await getAspiranteById(match.params.id);
} else {
save = await this.props.saveAspirante(data)
}
if (save && save.status === 200) {
this.setState({ isSave: { failed: false, message: !id ? GUARDAR_OTRO_A : EDITAR_AGAIN_A, title: "Se guardo con exito el aspirante" } })
return
}
this.setState({ isSave: { failed: true, message: "Desea intentar de nuevo o ir a listados?", title: "No se guardo con exito el aspirante" } })
}
closeSave = () => {
if (!this.state.id && !this.state.isSave.failed) {
this.setState({ ...initialState, isSave: false })
return
}
this.setState({ isSave: false })
}
goToHome = () => {
this.props.history.push("/home");
}
removeAspirant = async () => {
const a = this.props.aspirante.data
const data = {
aspirante: {
id: a.id || null,
folio: a.folio,
idEstudios: a.idEstudios,
idRama: a.idRama,
idPuesto: a.idPuesto,
idZona: a.idZona,
nombre: a.nombre,
apellidoPaterno: a.apellidoPaterno,
apellidoMaterno: a.apellidoMaterno,
listado: a.listado,
fecha: a.fecha,
motivo_baja: this.state.reason,
estatus: "INACTIVO"
},
puntaje: a.puntaje
}
const response = await this.props.editAspirante(data)
this.props.handleSnackbar({ message: response.message, type: response.status === 200 ? "success" : "error", open: true })
await getAspiranteById(this.state.id);
}
checkEmpty = (array) => {
return array.every(item => item.toString().trim().length > 0)
}
render() {
const { folio, birthday, name, paternal, maternal, studies, branch, position, zone, list, isSave, scholarship, relationship, registry, service, reason } = this.state;
const { estudios, ramas, puestos, zonas } = this.props;
const total = parseInt(scholarship || 0) + parseInt(registry || 0) + parseInt(service || 0) + parseInt(relationship || 0)
const areEmpty = this.checkEmpty([folio, birthday, name, paternal, studies, branch, position, zone, list, scholarship, relationship, registry, service])
return (
<Fragment>
<div className="container-btn-action">
<Button variant="outlined" color="primary" onClick={this.saveAspirante} disabled={!areEmpty} className="btn-action" >Guardar aspirante </Button></div>
<div className="card-container-edit card-container">
<div className="card card-name">
<TextField id="folio" className="txt-start"
label="Folio" value={folio} onChange={this.handleChange} variant="filled" />
<TextField
id="birthday"
label="Fecha de ingreso"
variant="filled"
type="date"
onChange={this.handleChange}
value={birthday}
className="txt-start"
InputLabelProps={{
shrink: true,
}}
/>
<TextField id="name" className="txt-start" value={name} label="Nombre(s)" onChange={this.handleChange} variant="filled" />
<TextField id="paternal" className="txt-start" value={paternal} label="Apellido paterno" onChange={this.handleChange} variant="filled" />
<TextField id="maternal" className="txt-start" value={maternal} label="Apellido materno" onChange={this.handleChange} variant="filled" />
</div>
<div className="card card-zone">
<SelectMenu items={estudios && estudios.data || []} className="txt-start" value={studies} onChange={this.handleChange} label="Nivel de estudios" id="studies" />
<SelectMenu items={ramas && ramas.data || []} className="txt-start" value={branch} onChange={this.handleChange} label="Rama" id="branch" />
<SelectMenu items={puestos && puestos.data || []} className="txt-start" value={position} onChange={this.handleChange} label="Puesto" id="position" />
<SelectMenu items={zonas && zonas.data || []} className="txt-start" value={zone} onChange={this.handleChange} label="Zona" id="zone" />
<SelectMenu items={[{ id: "INSTITUTO", nombre: "INSTITUTO" }, { id: "SINDICATO", nombre: "SINDICATO" }]} className="txt-start" value={list} onChange={this.handleChange} label="Listado" id="list" />
</div>
<div className="card card-points">
<TextField id="scholarship" className="txt-ponts" onChange={this.handleChange} value={scholarship} label="Escolaridad" variant="filled" onKeyPress={numericCharacters} />
<TextField id="relationship" className="txt-ponts" onChange={this.handleChange} value={relationship} label="Parentesco" variant="filled" onKeyPress={numericCharacters} />
<TextField id="registry" className="txt-ponts" onChange={this.handleChange} value={registry} label="Tiempo de servicio" variant="filled" onKeyPress={numericCharacters} />
<TextField id="service" className="txt-ponts" onChange={this.handleChange} value={service} label="Tiempo de registro" variant="filled" onKeyPress={numericCharacters} />
<div className="total-points txt-color-gray" >Total:  <span>{total}</span></div>
</div>
{this.props.match.params && this.props.match.params.id && <div className="card card-down">
<TextField id="reason" className="v" onChange={this.handleChange} value={reason} label="Motivo de baja" variant="filled" />
<Button variant="outlined" color="primary" onClick={this.removeAspirant} className="btn-red" >Dar de baja al aspirante </Button></div>
}
</div>
<AlertDialog id="dialog-reason" open={Boolean(isSave)} title={isSave.title} noAgreeClick={this.closeSave} agreeClick={this.goToHome} btnAgree="Ir a listado" btnNoAgree="Permanecer en la pantalla">
{isSave.message}
</AlertDialog>
</Fragment>
);
}
}
const mapStateToProps = (state) => ({
aspirante: state.usuarios.aspiranteById,
ramas: state.usuarios.ramas,
estudios: state.usuarios.estudios,
puestos: state.usuarios.puestos,
zonas: state.usuarios.zonas
})
const mapDispatchToProps = dispatch => {
return {
getAspiranteById: (props) => { return getAspiranteById(props)(dispatch) },
saveAspirante: (data) => { return saveAspirante(data)(dispatch) },
editAspirante: (data) => { return editAspirante(data)(dispatch) },
getRamas: () => { return getRamas("?estatus=ACTIVO")(dispatch) },
getEstudios: () => { return getEstudios("?estatus=ACTIVO")(dispatch) },
getPuestos: () => { return getPuestos("?estatus=ACTIVO")(dispatch) },
getZonas: () => { return getZonas()(dispatch) },
getFolio: () => { return getFolio()(dispatch) },
handleSnackbar: (props) => { handleSnackbar(props)(dispatch) },
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Edit);
|
import Ember from 'ember';
import layout from './template';
const {Component, computed} = Ember;
export default Component.extend({
layout,
tagName: 'li',
id: computed('fieldName', function () {
return 'cd-' + this.get('fieldName');
})
});
|
var http = require("http");
var url = require("url");
/**
* Creating and instantiating our server
*/
var server = http.createServer(function(req, res) {
/**
* 1) Ensure the requested route is
* /hello.
*/
var pathName = url.parse(req.url).pathname;
var trimmedPath = pathName.replace(/^\/+|\/+$/g, "");
var handler = routes[trimmedPath];
/**
* 2) Determine if this is a post request.
*/
var method = req.method;
var validMethod = method.toUpperCase() === "POST";
if (typeof routes[trimmedPath] !== "undefined" && validMethod) {
/**
* 3) Set the appropriate content-type
* application / json headers
*/
res.setHeader("Content-Type", "application/json");
/**
* 4) Set our Response and send
*/
handler(function(statusCode, content) {
res.statusCode = statusCode;
res.end(JSON.stringify(content));
});
} else {
res.statusCode = 404;
res.end();
}
});
server.listen(3000, function() {
console.log("Listening on port 3000");
});
/**
* Defining the handlers
*/
var handlers = {};
handlers.hello = function(callback) {
callback(200, { data: "Welcome To Our Awesome API" });
};
/**
* Defining our routes
*/
var routes = {
hello: handlers.hello
};
|
'use strict';
angular.module('adaptmt')
.factory('aptAptmtBsPtnrPresentService',['sessionManager','$translate','genericResource','$q', '$http',function(sessionManager,$translate,genericResource,$q,$http){
var service = {};
service.urlBase='/adaptmt.server/rest/aptaptmtbsptnrpresents';
service.bnsptnrUrlBase = '/adbnsptnr.server/rest/bpbnsptnrs';
service.create = function(entity){
var deferred = $q.defer();
genericResource.create(service.urlBase, entity).success(function(data){
deferred.resolve(data);
}).error(function(error){
deferred.reject("Can not create, be sure that the aptAptmtBsPtnrPresents property( id of appointment and of bsnptnr) name is not null!")
});
return deferred.promise;
};
service.deleteById = function(id){
var deferred = $q.defer();
genericResource.deleteById(service.urlBase, id).success(function(data){
deferred.resolve(data);
}).error(function(error){
deferred.reject("Can not create, be sure that the aptAptmtBsPtnrPresents property( id of appointment and of bsnptnr) name is not null!")
});
return deferred.promise;
};
service.updateaptAptmtBsPtnrPresents = function(entity){
var deferred = $q.defer();
genericResource.update(service.urlBase, entity).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject("Can not update")
});
return deferred.promise;
};
service.loadAptAptmtBsPtnrPresent = function(aptmtIdentify){
var searchInput = {
entity : {
aptmtIdentify : aptmtIdentify
},
fieldNames : [ "aptmtIdentify" ],
start : 0,
max:10
}
var deferred = $q.defer();
genericResource.findByLike(service.urlBase, searchInput).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject("Can not update")
});
/* var deferred = $q.defer();
$http.get(service.urlBase, searchInput)
.success(function(data){
deferred.resolve(data);
}).error(function(data){
deferred.reject("no more aptmtbnsptnr !")
});*/
return deferred.promise;
};
service.loadAptAptmtContact = function(aptmtIdentify,contactnNbr){
var searchInput = {
entity : {
aptmtIdentify : aptmtIdentify,
contactnNbr : contactnNbr
},
fieldNames : [ "aptmtIdentify"],
start : 0,
max:10
}
var deferred = $q.defer();
genericResource.findByLike(service.urlBase, searchInput).success(function(data){
deferred.resolve(data);
}).error(function(){
deferred.reject("Can not load")
});
return deferred.promise;
};
service.findAptAptmtBsPtnrPresents = function(searchInput){
var deferred = $q.defer();
genericResource.findByLike(service.urlBase, searchInput)
.success(function(data, status, headers, config){
deferred.resolve(data);
}).error(function(data, status, headers, config){
deferred.reject("An error occured while fetching aptAptmtBsPtnrPresents");
});
return deferred.promise;
};
service.nextAptAptmtBsPtnrPresents = function(id){
var deferred = $q.defer();
$http.get(service.urlBase+'/nextLogin/'+id)
.success(function(data){
deferred.resolve(data);
}).error(function(data){
deferred.reject("no more aptAptmtBsPtnrPresents !")
});
return deferred.promise;
}
service.previousAptAptmtBsPtnrPresents = function(id){
var deferred = $q.defer();
$http.get(service.urlBase+'/previousLogin/'+id)
.success(function(data){
deferred.resolve(data);
}).error(function(data){
deferred.reject("no more appointment !")
});
return deferred.promise;
}
service.loadPartnersByName = function(fullName){
return genericResource.findByLikePromissed(service.bnsptnrUrlBase, 'fullName', fullName)
.then(function(entitySearchResult){
if(!angular.isUndefined(entitySearchResult))
return entitySearchResult.resultList;
else return "";
});
};
return service;
}]);
|
import axios from "axios";
export default axios.create({
// defined in .env-file in project root directory
baseURL: process.env.REACT_APP_API_URL
});
|
import Col from 'react-bootstrap/Col';
const Content = ( { theme, playing, mobile, setTheme }) => {
const opacity = playing ? 0.3 : 1
return (
<div style={{ fontSize: '16px', height: '100%', zIndex: '1', position: 'absolute'}}>
<div className="container" style={{ padding: '30px' }}>
<Col xs={7} md={3} lg={2} style={{ padding: 0}}>
<img style={{ opacity: opacity, width: `${mobile ? '100%' : '100%'}` }} src={`/${theme ? 'black' : 'white'}-logo.svg`}></img>
</Col>
{/* Content */}
<Col xs={12} md={6} lg={4} style={{ padding: 0, opacity: opacity }}>
<p>We are a software development and services company that specialises in building oracle technology. We connect any external data to blockchain applications through the technology we build.</p>
<p><a target={"_blank"} href={"https://github.com/mrpowerpoint/relayer-landing"}>GitHub</a></p>
</Col>
{mobile ? <a style={{ zIndex: 1, position: 'absolute', right: '20px', bottom: '20px'}} onClick={() => { setTheme(!theme)}}>{theme ? 'Light' : 'Dark'} mode</a>
: <></> // if its not mobile it will be rendered in the game
}
</div>
</div>
)
}
export default Content
|
import axios from 'axios';
import { Button } from 'bootstrap';
import React from 'react';
const DeleteReview = (props) => {
const deleteReviewfunc = async () => {
const NewReviews = props.reviews.filter(review => review.Original_Id !== props.reviewID);
//console.log(props.reviewID);
//console.log(NewReviews);
//console.log(NewReviews)
//const res1 = await Axios.delete('http://localhost:5000/reviews/' + props.reviewID);
console.log(props.postID);
axios.delete('http://localhost:5000/reviews/' + props.reviewID)
.then(response => {console.log(response)
axios.patch('http://localhost:5000/posts/update/' + props.postID , { "reviews": NewReviews });
window.location.reload();
})
.catch(error => console.log(error));
//const res2 = await Axios.patch('http://localhost:5000/posts/update/' + props.postID , { "reviews": NewReviews });
//console.log(props.reviews);
//console.log(props.postID);
}
return (
<div>
<button onClick={()=>deleteReviewfunc()}>
delete review
</button>
</div>
)
}
export default DeleteReview
|
import React from 'react';
import './Cart.css';
const Cart = (props) => {
const cart = props.cart;
console.log(cart);
const total = cart.reduce((total,prd)=> total + prd.Price ,0);
return (
<div className= "cart-style">
<h2>Order Summary</h2>
<p>Courses Enroll: {cart.length}</p>
<p> Total Price:{total}</p>
<button className= "cart-button"> Sign Up</button>
</div>
);
};
export default Cart;
|
function calc(ope){
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
switch(ope){
case 'add':
message = num1+ " + " +num2+ " = " +(num1+num2);
break;
case 'sub':
message = num1+ " - " +num2+ " = " +(num1-num2);
break;
case 'mul':
message = num1+ " * " +num2+ " = " +(num1*num2);
break;
case 'div':
message = num1+ " / " +num2+ " = " +(num1/num2);
break;
case 'mod':
message = num1+ " % " +num2+ " = " +(num1%num2);
break;
default: message = "please provide valid input";
}
document.getElementById("res").innerHTML=message;
}
|
const _ = {
//implement clamp
clamp(number, lower, upper){
const lowerClampedValue = Math.max(number, lower);
const clampedValue = Math.min(lowerClampedValue, upper);
return clampedValue
},
//implementing in range
inRange(number, start, end){
if(end === undefined){
end = start;
start = 0;
}
if(start > end){
let temp = end;
end = start;
start = temp;
}
let isInRange = true;
if(number >= start && number < end){
isInRange;
} else{
isInRange = false;
}
return isInRange;
},
//implement words
words(word){
return word.split(' ');
},
//implement pad methods
pad(word, length){
if(length <= word.length){
return word;
};
const startPaddingLength = Math.floor((length - word.length)/2);
const endPaddingLength = length - (word.length + startPaddingLength);
const paddedString = ' '.repeat(startPaddingLength) + word + ' '.repeat(endPaddingLength);
return paddedString;
},
//implement has method
has(object, key){
const hasValue = object[key];
if(hasValue !== undefined){
return true;
}
return false;
},
//implement invert method
invert(object){
let invertedObject = {};
for(let key in object){
const originalValue = object[key];
invertedObject = {originalValue: key};
}
return invertedObject;
},
//implement findKey method
findKey(object, predicate){
for(let key in object){
let value = object[key];
let predicateReturnValue = predicate(value);
if(predicateReturnValue){
return key;
}
} return undefined;
},
//drop array method
drop(array, n){
if(n === undefined){
n = 1;
}
let droppedArray = array.slice(n, array.length);
return droppedArray;
},
//dropwhile method
dropWhile(array, predicate){
const cb= (element, index) => {
return !predicate(element, index, array);
}
let dropNumber = array.findIndex(cb);
let droppedArray = this.drop(array, dropNumber)
return droppedArray;
},
//implementing chunk method
chunk(array, size){
if(size === undefined){
size = 1;
};
let arrayChunks = [];
for(let i = 0; i < array.length; i+=size){
let arrayChunk = array.slice(i, i + size);
arrayChunks.push(arrayChunk)};
return arrayChunks;
},
}
|
import React, { Component } from 'react'
import axios from 'axios'
import { Row, Col, Card, Button, Table, message, Modal } from 'antd'
import DropOption from '@/components/DropOption'
import AddModal from './AddModal'
import SearchBox from './SearchBox'
import Authorize from './Authorize'
import TerminalModal from './TerminalModal'
import QrCreat from './QrCreat'
import Qrname from './Qrname'
import WxqrModal from './WxqrModal'
import { paginat } from '@/utils/pagination'
const confirm = Modal.confirm;
class Qr extends Component {
state = {
total: 0, //总数
current: 1, //当前页数
searchParams: {}, //查询参数
loading: true, //表格是否加载中
data: [],
pageSize: 10, //每页数量
qrVisible: false, //生产二维码modal显示与否
visible: false,
qrnameVisible: false, //维护码名modal
authorizeViseble: false,
selectedRowKeys: [], // 当前有哪些行被选中, 这里只保存key
selectedRows: [], //选中行的具体信息
item: {},
isAddModal: true,
record: '',
terminalViseble: false, //设备终端显示
}
componentDidMount() {
this.getPageList()
}
/**
*
* @param {Number} limit 每页条数默认10条
* @param {Number} offset 第几页,如果当前页数超过可分页的最后一页按最后一页算默认第1页
* @param {Object} params 其他参数
*/
getPageList(limit = this.state.pageSize, offset = 1, params) {
if (!this.state.loading) {
this.setState({ loading: true })
}
axios.get('/back/qr/qrs', {
params: {
limit,
offset,
...params,
}
}).then(({ data }) => {
this.setState({
total: data.total,
data: data.rows,
current: offset,
loading: false,
})
}).catch(err => console.log(err))
}
//增加按钮
addHandle = () => {
this.setState({
item: {},
isAddModal: true,
visible: true
})
}
/**
* 点击删除按钮, 弹出一个确认对话框
* 注意区分单条删除和批量删除
* @param e
*/
onClickDelete = (e) => {
e.preventDefault();
Modal.confirm({
title: this.state.selectedRowKeys.length > 1 ? '确认批量删除?' : '确认删除?',
onOk: () => {
axios.all(this.state.selectedRows.map((item) => {
return axios.delete(`/back/industry/remove/${item.id}`)
})).then(axios.spread((acct, perms) => {
console.log(acct, perms)
if (!acct.data.rel) {
message.error('删除失败')
return
}
message.success('删除成功')
this.getPageList()
}))
},
});
}
/**
* 模态框提交按钮--增加
* @param values
*/
handleOk = (values) => {
const { pageSize, current, searchParams } = this.state
if (this.state.isAddModal) {
// 添加功能
axios.post('/back/qr/createQuickResponse', {
quantity: values.quantity,
codeType: values.codeType,
}).then(({ data }) => {
if (data.rel) {
message.success('添加成功!')
this.getPageList()
} else {
message.error(data.msg)
}
})
} else {
//修改功能
const id = this.state.item.id
axios.get('/back/qr/update', {
params: {
id,
codeType: values.codeType,
merId: values.merId
}
}).then(res => res.data).then(res => {
if (res.rel) {
message.success(res.msg)
this.getPageList(pageSize, current, searchParams)
} else {
message.error(res.msg)
}
})
}
//这里无论提交成功失败,都要关闭模态框,清空表单内容
this.setState({
visible: false,
});
// 清空表单
this.addModal.resetFields()
}
/**
* 模态框取消按钮
*/
handleCancel = () => {
this.setState({
visible: false,
});
}
/**
* 处理表格的选择事件
*
* @param selectedRowKeys
*/
onTableSelectChange = (selectedRowKeys, selectedRows) => {
console.log(selectedRowKeys)
this.setState({ selectedRowKeys, selectedRows });
};
/**
* 页码改变的回调,参数是改变后的页码及每页条数
* @param page 改变后的页码
* @param pageSize 改变页的条数
*/
pageChange = (page, pageSize) => {
this.setState({
pageSize: pageSize,
current: page
})
this.getPageList(pageSize, page, this.state.searchParams)
}
/**
* pageSize 变化的回调
* @param current 当前页码
* @param pageSize 改变后每页条数
*/
onShowSizeChange = (current, pageSize) => {
this.setState({
pageSize: pageSize,
current: current
})
this.getPageList(pageSize, current, this.state.searchParams)
}
/**
* 查询功能
* @param values
*/
search = (values) => {
this.setState({
searchParams: values
})
this.getPageList(this.state.pageSize, 1, values)
}
/*********** 批量授权 ***************/
authorizeHandle = () => {
if (this.state.selectedRowKeys.length === 0) {
message.info('请选择一行')
return
}
this.setState({
authorizeViseble: true,
})
}
authorizeCancel = () => {
this.setState({
authorizeViseble: false,
})
}
authorizeOk = (merId) => {
axios.post('/back/qr/authorize', {
ids: this.state.selectedRowKeys.join(','),
merId: merId,
}).then(res => res.data).then(res => {
if (res.rel) {
message.success('授权成功')
this.getPageList()
} else {
message.error(res.msg)
}
this.authorizeCancel()
})
}
/*********** 批量授权 ***************/
/**
* 表格最后一列操作按钮
*/
itmeEdit = (text, record, index) => {
this.setState({
isAddModal: false,
item: record,
visible: true,
})
}
/**
* 下拉按钮组件
*/
handleMenuClick = (record, e) => {
switch (e.key) {
case '1':
//修改按钮
this.setState({
isAddModal: false,
item: record,
visible: true,
})
break;
case '2':
//生成二维码
if (record.codeType == 3) {
this.setState({
record: record,
})
this.wxqrModal.showModal()
return
}
this.setState({
record: record,
qrVisible: true,
})
break;
case '3':
// 维护码名
this.setState({
qrnameVisible: true,
item: record
})
break;
case 'del':
this.delteItem(record.id)
break;
}
}
delteItem(id) {
confirm({
title: '确认删除',
// content: 'Some descriptions',
onOk: () => {
axios.delete(`/back/qr/del/${id}`).then(res => {
const data = res.data
if (data.rel) {
message.success('删除成功')
this.getPageList()
} else {
message.error('删除失败')
}
})
}
});
}
/** 绑定设备终端 */
handleTerminal = (e) => {
if (this.state.selectedRowKeys.length === 0) {
message.info('请选择一行')
return
}
this.setState({
terminalViseble: true,
})
}
terminalCancel = () => {
this.setState({
terminalViseble: false,
})
}
terminalOk = (merId) => {
axios.post('/back/qr/bind', {
ids: this.state.selectedRowKeys.join(','),
terminalId: merId,
}).then(res => res.data).then(res => {
if (res.rel) {
message.success('绑定成功')
this.getPageList()
this.terminalCancel()
} else {
message.error(res.msg)
}
})
}
// 维护码名
updateqrname = (value) => {
const { pageSize, current, searchParams } = this.state
axios.post('/back/qr/updateqrname', value).then(({ data }) => {
if (data.rel) {
message.success(data.msg)
this.qrnameCancael()
this.getPageList(pageSize, current, searchParams)
} else {
// 错误
}
})
}
// 维护码名modal取消
qrnameCancael = () => {
this.setState({
qrnameVisible: false
})
}
/** 绑定设备终端 */
render() {
const rowSelection = {
selectedRowKeys: this.state.selectedRowKeys,
onChange: this.onTableSelectChange,
};
const hasSelected = this.state.selectedRowKeys.length > 0; // 是否选择
const pagination = paginat(this, (pageSize, current, searchParams) => {
this.getPageList(pageSize, current, searchParams)
})
//表格表头信息
const columns = [{
title: '商户名称',
dataIndex: 'merName'
}, {
title: '设备名称',
dataIndex: 'terminalName',
}, {
title: '机构名称',
dataIndex: 'orgName'
}, {
title: "二维码类型",
dataIndex: "codeTypeValue",
// className: 'table_text_center',
}, {
title: "授权状态",
dataIndex: "authStatusValue",
}, {
title: '码名',
dataIndex: 'qrName'
}, {
title: "码值",
dataIndex: "id",
},
{
title: "操作",
fixed: 'right',
width: 72,
render: (text, record) => (
<DropOption
onMenuClick={(e) => this.handleMenuClick(record, e)}
menuOptions={[
{ key: '1', name: '修改' },
{ key: 'del', name: '删除' },
{ key: '2', name: '生成二维码' },
{ key: '3', name: '维护码名' }
]}
/>
)
}]
return (
<div className="foundation-category">
<div>
<Card
bordered={false}
bodyStyle={{ backgroundColor: "#f8f8f8", marginRight: 32 }}
noHovering
>
<SearchBox loading={this.state.loading} search={this.search} />
</Card>
<Card bordered={false} noHovering bodyStyle={{ paddingLeft: 0 }}>
<Row gutter={40} style={{ marginBottom: 20 }}>
<Col span={24} style={{ marginLeft: 14 }}>
<Button
title="创建二维码"
className="btn-add"
size="large"
shape="circle"
type="primary"
icon="plus"
onClick={this.addHandle}
/>
<Button
title="批量授权"
className="btn-limit"
size="large"
shape="circle"
type="primary"
icon="lock"
onClick={this.authorizeHandle}
/>
<Button
title="绑定设备终端"
className="btn-add-user"
size="large"
shape="circle"
type="primary"
icon="link"
onClick={this.handleTerminal}
/>
{/* 添加二维码modal */}
<AddModal
ref={e => this.addModal = e}
onOk={this.handleOk}
modalProps={{
title: this.state.isAddModal ? "新增-二维码" : "修改-二维码",
okText: "提交",
width: "50%",
item: this.state.item,
wrapClassName: "vertical-center-modal",
visible: this.state.visible,
onCancel: this.handleCancel
}}
/>
{/* 授权modal */}
<Authorize
onOk={this.authorizeOk}
modalProps={{
title: "批量授权",
okText: "提交",
wrapClassName: "vertical-center-modal",
visible: this.state.authorizeViseble,
onCancel: this.authorizeCancel,
}}
/>
{/* 绑定设备modal */}
<TerminalModal
onOk={this.terminalOk}
modalProps={{
title: "绑定设备终端",
okText: "提交",
wrapClassName: "vertical-center-modal",
visible: this.state.terminalViseble,
onCancel: this.terminalCancel,
}}
/>
{/* 创建二维码modal */}
<Modal
width={1120}
footer={null}
visible={this.state.qrVisible}
onCancel={() => {
this.setState({ qrVisible: false })
}}
>
<QrCreat row={this.state.record} />
</Modal>
{/* 创建小程序二维码 */}
<WxqrModal ref={e => this.wxqrModal = e} record={this.state.record} />
{/* 维护码名modal */}
<Qrname
onOk={this.updateqrname}
modalProps={{
title: "维护码名",
okText: "提交",
item: this.state.item,
visible: this.state.qrnameVisible,
wrapClassName: "vertical-center-modal",
onCancel: this.qrnameCancael,
}}
/>
</Col>
</Row>
<Row>
<Col>
<Table
scroll={{ x: true }}
loading={this.state.loading}
columns={columns}
dataSource={this.state.data}
rowSelection={rowSelection}
pagination={pagination}
rowKey="id"
/>
</Col>
</Row>
</Card>
</div>
</div >
)
}
}
export default Qr
|
/* eslint-disable no-undef */
import configureStore from '../../lib/ConfigureStore'
import { facebookLoginRequest, resetLogin, setLogin, registerNewUser } from '../AuthActions'
import { facebookLoginManager } from '../../../libs/FacebookSDK'
import { setUserAuthenticated } from '../../../libs/Storage/Handlers/Auth'
const store = configureStore({
auth: {
user: {},
authenticated: false,
},
})
// mock FbHelper
jest.mock('../../../libs/FacebookSDK')
// mock Storage
jest.mock('../../../libs/Storage/Handlers/Auth')
let isValidUser = true
const FBfakeUser = {
email: 'aethiss@gmail.com',
id: '1522353421192808',
picture: {
data: {
is_silhouette: false,
width: 50,
url: 'https://platform-lookaside.fbsbx.com/platform/profilepic/',
height: 50,
},
},
name: 'Enzo D\'Onofrio',
}
facebookLoginManager.mockImplementation(() =>
new Promise((resolve, reject) => {
if (isValidUser) {
return resolve(FBfakeUser)
}
return reject(new Error('bad user'))
}))
setUserAuthenticated.mockImplementation(() => new Promise(resolve => resolve(true)))
describe('Auth Actions', () => {
describe('Login Request ', () => {
it('login request', () => {
expect.assertions(1)
return store.dispatch(facebookLoginRequest())
.then((data) => {
expect(data)
.toMatchObject(FBfakeUser)
})
})
it('login error', () => {
isValidUser = false
return store.dispatch(facebookLoginRequest())
.catch((data) => {
expect(data.name)
.toBe('Error')
expect(data.message)
.toBe('Error: bad user')
})
})
it('reset login', () => {
store.dispatch(resetLogin())
expect(store.getState().auth.authorized).toBe(false)
expect(store.getState().auth.user).toMatchObject({})
})
it('expect Auth -> authorized = register after facebook request', () => {
isValidUser = true
const newStore = configureStore()
expect.assertions(3)
return newStore.dispatch(facebookLoginRequest())
.then(() => {
expect(newStore.getState().auth.user).toMatchObject(FBfakeUser)
expect(newStore.getState().auth.authorized).toBe(true)
expect(newStore.getState().auth.isNewUser).toBe(true)
})
})
})
describe('Register User', () => {
it('register new user', () => {
const registerStore = configureStore()
registerStore.dispatch(setLogin({ name: 'Enzo', fb: '111333' }, true))
expect.assertions(3)
return registerStore.dispatch(registerNewUser('004465322', { name: 'uk', some: 'bla' }))
.then(() => {
expect(registerStore.getState().auth.isNewUser).toBe(false)
expect(registerStore.getState().auth.user).toMatchObject({
name: 'Enzo',
fb: '111333',
})
expect(registerStore.getState().auth.phone).toMatch('004465322')
})
})
})
})
|
//Hard coded inital Locations
var myLocations = [
{
name: 'Empire State Building Experience',
address: '',
img: "img/22.jpg",
lat: 40.748441,
long: -73.985664
},
{
name: 'Statue of Liberty',
address: '',
img: "img/33.jpg",
lat: 40.6892,
long: -74.044502
},
{
name: 'Ellis Island Immigration Museum',
address: '',
img: 'img/44.jpg',
lat: 40.6997222 ,
long: -74.0394444
},
{
name: 'American Museum of Natural History',
address: '',
img: "img/55.jpg",
lat: 40.7813241,
long: -73.9739882
},
{
name: 'The Metropolitan Museum of Art ',
address: '',
img: "img/66.jpg",
lat: 40.774399,
long: -73.965604
}
];
var map;
var ko;
var google;
var alert;
var clientID="MGNZSQQCETXG5MYA0NPCIQOIJ3L1JXRCPT04ATGXYCMEM2Y1";
var clientSecret="C1TRHKKRNTDJWGLF4WYTLMFJFOBYTUF2BYU5YBKVC2FHD44R";
// tells the view model what to do when a change occurs
// Declaring global variables now to satisfy strict mode
var Location = function (data) {
var self = this;
this.name = data.name;
this.lat = data.lat;
this.long = data.long;
this.url = "";
this.street="";
this.address = "";
this.img = data.img;
this.visible = ko.observable(true);
var cont='https://api.foursquare.com/v2/venues/search?ll='+ this.lat + ',' + this.long + '&client_id=' + clientID + '&client_secret=' + clientSecret + '&v=20161016' + '&query=' + this.name;
$.getJSON(cont).done(function(data) {
var results = data.response.venues[0];
self.url= results.url;
if (typeof self.url === 'undefined'){
self.url = "";
}
self.street = results.location.formattedAddress[0];
self.street = results.location.formattedAddress[1];
}).fail(function() {
alert("There was an error with the Foursquare API call. Please refresh the page and try again to load Foursquare data.");
});
this.contentString = '<div class="info-window-content"><div class="title"><b>' + data.name + "</b></div>" +
'<div class="content"><a href="' + self.url +'">' + self.url+ "</a></div>" +
'<div class="content">' + self.street + "</div>";
'<div class="content"><img src="' + self.img + '">' + "</div>" +
'<div class="content">' + self.address + "</div></div>";
this.infoWindow = new google.maps.InfoWindow({ content: self.contentString });
//Adds new markers at each location in the initialLocations Array
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.long),
map: map,
icon: 'img/marker.png',
animation: google.maps.Animation.DROP,
title: data.name
});
this.showMarker = ko.computed(function () {
if (this.visible() === true) {
this.marker.setMap(map);
} else {
this.marker.setMap(null);
}
return true;
}, this);
//Map info windows to each item in the markers array
//Add click event to each marker to open info window
this.marker.addListener('click', function () {
self.contentString = '<div class="info-window-content"><div class="title"><b>' + data.name + "</b></div>" +
'<div class="content"><a href="' + self.url +'">' + self.url + "</a></div>" +
'<div class="content">' + self.address + "</div>" +
'<div class="content">' + self.street + "</div>"+
'<div class="content"><img src="' + self.img + '">' + "</div></div>";
self.infoWindow.setContent(self.contentString);
self.infoWindow.open(map, this); // Open info window on correct marker when list item is clicked
self.marker.setAnimation(google.maps.Animation.BOUNCE); //Markers will bounce when clicked
setTimeout(function () {
self.marker.setAnimation(null);
}, 1400); //Change value to null after 2 seconds and stop markers from bouncing
});
//Markers will bounce when clicked
this.bounce = function (place) {
google.maps.event.trigger(self.marker, 'click');
};
};
//ViewModel
function AppViewModel() {
var self = this;
this.searchTerm = ko.observable("");
this.locationList = ko.observableArray([]);
//Create Instance of a map from the Google maps api
//Grab the reference to the "map" id to display map
//Set the map options object properties
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: { lat: 40.7813241, lng: -73.9739882 },
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
});
//Copies the values of myLocations and stores them in LocationList(); observableArray
myLocations.forEach(function (locationItem) {
self.locationList.push(new Location(locationItem));
});
//Filter through observableArray and filter results using knockouts
this.filteredList = ko.computed(function () {
var filter = self.searchTerm().toLowerCase();
if (!filter) {
self.locationList().forEach(function (locationItem) {
locationItem.visible(true);
});
return self.locationList();
} else {
return ko.utils.arrayFilter(self.locationList(), function (locationItem) {
var string = locationItem.name.toLowerCase();
var result = (string.search(filter) >= 0);
locationItem.visible(result);
return result;
});
}
}, self);
this.mapElem = document.getElementById('map');
}
function startApp() {
ko.applyBindings(new AppViewModel());
}
//Error Handing
function errorHandling() {
alert("Google Maps has failed to load.");
}
|
import React, { useEffect, useState, Fragment, useCallback } from 'react';
import axios from 'axios';
import InputButton from '../components/shared/InputButton';
import Mission from '../components/shared/Mission';
import Head from 'next/head';
import Year from '../components/yearData/year';
function App({ data }) {
const [launch, setLaunch] = useState(data);
const [launchSuccess, setLaunchSuccess] = useState('');
const [landSuccess, setLandSuccess] = useState('');
const [launchYear, setLaunchYear] = useState('');
useEffect( ()=>{
let url = `https://api.spaceXdata.com/v3/launches?limit=100&launch_success=${launchSuccess}&land_success=${landSuccess}&launch_year=${launchYear}`;
axios.get(url)
.then(response => setLaunch(response.data));
},[launchSuccess, landSuccess, launchYear]);
const successfulLaunchHandler = (event) => {
let value = event.target.value === 'True'? true : false;
setLaunchSuccess(value)
}
const successfullLandHandler = (event) => {
let value = event.target.value === 'True'? true : false;
setLandSuccess(value)
}
const launchYearHandler = (event) => {
setLaunchYear(event.target.value)
}
return (
<Fragment>
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SpaceX Mission</title>
</Head>
<div className='heading'>SpaceX Launch Programs</div>
<div className="App">
<div className="filter">
<div>Filters</div>
<div>Launch Year</div>
<div className="launch_year">
{Year.map(e => <InputButton key={e.id} value={e.year} selected={launchYear == e.year ? launchYear : ''} onClickEvent={launchYearHandler}/> )}
</div>
<div className="launch_success">Successful Launch</div>
<div className="launch_successfull">
<InputButton value='True' selected={launchSuccess !== '' && launchSuccess ? "True":''} onClickEvent={successfulLaunchHandler}/>
<InputButton value='False' selected={launchSuccess !== '' && !launchSuccess ? "False":''} onClickEvent={successfulLaunchHandler}/>
</div>
<div className="land_success">Successful Land</div>
<div className="land_successfull">
<InputButton value='True' selected={landSuccess !== '' && landSuccess ? "True":'' } onClickEvent={successfullLandHandler}/>
<InputButton value='False' selected={landSuccess !== '' && !landSuccess ? "False":'' } onClickEvent={successfullLandHandler}/>
</div>
</div>
<div className="parent_result">
{ launch && launch.map((e, i) => <Mission key={i} index={i} data={e} /> ) }
</div>
</div>
<div className="fixed_footer">Developed By: Manish Yadav</div>
</Fragment>
)
}
App.getInitialProps = async (ctx) => {
const response = await fetch(`https://api.spaceXdata.com/v3/launches?limit=100`)
const data = await response.json();
return { data }
}
export default App;
|
'use strict';
/**
* @ngdoc function
* @name laoshiListApp.controller:JobviewCtrl
* @description
* # JobviewCtrl
* Controller of the laoshiListApp
*/
angular.module('laoshiListApp')
.controller('JobviewCtrl', ['jobs__', 'llConstants', 'User_', 'Job_', 'currentAuth', '$routeParams', '$scope', 'firebasePath', '$firebaseArray', '$cookies', '$location', function (jobs__, llConstants, User_, Job_, currentAuth, $routeParams, $scope, firebasePath, $firebaseArray, $cookies, $location) {
// set job
var jobq = Job_($routeParams.jobid);
jobq.then(function(job) {
if (job == null) $location.path('/jobs');
console.log(job.data[0]);
$scope.job = job.data[0];
});
// // include the client's name -- if there is one
// $scope.job.then(function(job) {
// if(job.clientID) {
// var client = User_(job.clientID);
// client.$loaded().then(function(client_) {
// $scope.job.clientName = client_.getFullestName();
// })
// }
// })
// if logged in
if(currentAuth) {
// set user
$scope.user = User_(currentAuth.uid);
// if previously applied without logging in
} else if ($cookies.get('applicant_id')) {
// set user
$scope.user = User_($cookies.get('applicant_id'));
// $scope.applicant.name = $scope.user.firstName;
// $scope.applicant.email = $scope.user.email;
}
// if any kind of user
if($scope.user) {
// check to see if admin
$scope.user.$loaded().then(function() {
$scope.isAdmin = $scope.user.isAdmin();
});
}
$scope.edit = function() {
$location.path('/job-edit/' + $routeParams.jobid);
}
function alreadyApplied() {
// if a logged in user already applied
$scope.user.$loaded.then(function() {
$scope.alreadyApplied = $scope.user.hasApplied($routeParams.jobid);
});
// if a user who is not logged in already applied
}
$scope.status = llConstants.jobstatus();
$scope.cities = llConstants.cities();
$scope.ages = llConstants.ages();
$scope.subjects = llConstants.subjects();
var jobsq = jobs__.getJobs();
jobsq.then(function(jobs) {
$scope.jobs = jobs.data;
})
}]);
|
/* eslint-env jest */
import React from 'react';
import ReactDOM from 'react-dom';
import TestRenderer from 'react-test-renderer';
import HomePage from '../components/HomePage';
import Header from '../components/Header';
describe('<HomePage />', () => {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<HomePage />, div);
ReactDOM.unmountComponentAtNode(div);
});
const testRenderer = TestRenderer.create(<HomePage />);
it('renders correctly', () => {
const snapshot = testRenderer.toJSON();
expect(snapshot).toMatchSnapshot();
});
const testInstance = testRenderer.root;
expect(testInstance.findByType(Header).props.children).toBe('Tag Cloud');
});
|
export const styles = {
container: {
backgroundColor: "transparent",
width: "100%",
margin: "0px",
marginBottom: "20px",
padding: "30px 3%",
borderBottom: "2px solid gray",
},
paper: {
backgroundColor: "white",
width: "100%",
minHeight: "100px",
borderRadius: "6px",
overflow: "hidden",
},
innerPaper: {
...this.paper,
padding: "0px 5%",
margin: "0px",
overflow: "hidden",
},
userName: {
margin: "30px auto 10px auto",
},
profileHead: {
backgroundColor: "#1479fb",
width: "100%",
padding: "5%",
},
profileImage: {
borderRadius: "100%",
margin: "0px auto",
display: "block",
},
};
|
import React from 'react'
// eslint-disable-next-line
import {Container, Dropdown, Grid as SUI_Grid, List, Menu} from 'semantic-ui-react'
import LogoutButton from "./LogoutButton";
import axios from 'axios';
import config from '../url_config.json';
import Icon from "semantic-ui-react/dist/commonjs/elements/Icon";
import {Redirect} from "react-router-dom";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardActionArea from '@material-ui/core/CardActionArea';
import Typography from "@material-ui/core/Typography";
import MUI_Grid from '@material-ui/core/Grid';
import Measure from './Measure';
import Paper from "@material-ui/core/Paper";
import {
Button,
createMuiTheme,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
TextField
} from "@material-ui/core";
import {ThemeProvider} from "@material-ui/styles"
class Bunker extends React.Component {
state = {
measures: [],
bunker: {},
user_obj: null,
create_measure_form_text: null,
create_measure_default_score: 0,
bunker_name: "",
go_back: false,
go_to_measure: false,
select_measure_name: null,
select_measure_id: null,
select_measure_obj: null,
users_for_bunker: null,
past_users_for_bunker: null,
adding_measure: false,
inviting_others: false,
theme: this.props.theme ? this.props.theme : this.props.location.state.theme
};
constructor(props) {
super(props);
// Set user upon return
let bunker_id;
try {
bunker_id = this.props.location.state.bunker_id
} catch (e) { // Transition coming from a measure
bunker_id = this.props.bunker_id
}
this.getBunker(bunker_id).then(r => this.__completeStateInitialization())
}
buildLeaderboard = (ratings, users) => {
let sorted_ratings = ratings;
sorted_ratings.sort((a, b) => (a.score > b.score) ? -1 : 1);
let leaderboard = [];
for (let i = 0; i < sorted_ratings.length; i++) {
const users_object = users.filter(entry => entry.user_id === sorted_ratings[i].user)[0];
if (users_object) {
const name = users.filter(entry => entry.user_id === sorted_ratings[i].user)[0].name;
const rank = i + 1;
const score = sorted_ratings[i].score;
leaderboard.push({rank, name, score})
}
}
return leaderboard
};
// Page change prep functions
setGoBack = () => {
this.setState({go_back: true})
};
setGoToMeasure = (measure_obj) => {
console.log("Go to measure:", measure_obj);
this.setState({
select_measure_name: measure_obj.name,
select_measure_id: measure_obj._id,
select_measure_obj: measure_obj,
go_to_measure: true
});
};
// Back end call functions
async createNewMeasure(name, default_score) {
let url = config.bunkers_url + "/measure/" + this.state.bunker._id + "/" + name + "/" + default_score;
url = encodeURI(url);
console.log('Post new measure url: ', url);
try {
await axios.post(
url,
{},
{headers: {'Content-Type': 'application/json'}}
).then(e => this.setGoToMeasure(e.data.measure))
} catch (e) {
console.log(e.response)
}
}
async getBunker(bunker_id) {
let url = config.bunkers_url + "/" + bunker_id;
url = encodeURI(url);
console.log('Get bunker url: ', url);
try {
await axios.get(url).then(r => {
this.setState({bunker: r.data.bunker});
this.getMeasuresFromBunker(r.data.bunker._id);
console.log("Retrieved bunker data: ", r.data.bunker)
})
} catch (e) {
console.log("Bunker doesn't exist", e);
return null
}
}
async getMeasuresFromBunker(bunker_id) {
let url = config.bunkers_url + "/measures/" + bunker_id;
url = encodeURI(url);
console.log('Get measures from bunker url: ', url);
try {
await axios.get(url).then(r => {
this.setState({measures: r.data.measures});
this.getUsersFromBunker(bunker_id)
}
);
console.log("Retrieved bunker's measures")
} catch (e) {
console.log("Couldn't get bunker's measures", e);
return null
}
}
async getMeasure(measure_id) {
let url = config.measures_url + "/" + measure_id;
url = encodeURI(url);
console.log('Get measure url: ', url);
try {
await axios.get(url).then(r => {
console.log("Retrieved measure data: ", r.data.measure);
this.setGoToMeasure(r.data.measure)
})
} catch (e) {
console.log("Measure doesn't exist", e);
return null
}
}
async getUsersFromBunker(bunker_id) {
let url = config.bunkers_url + "/users/" + bunker_id;
url = encodeURI(url);
console.log('Get users from bunker url: ', url);
try {
await axios.get(url).then(r => {
console.log("Retrieved users from bunker: ", r.data.users);
this.setState({
users_for_bunker: r.data.users,
past_users_for_bunker: r.data.past_users
});
})
} catch (e) {
console.log("Failed getting users from bunker", e);
return null
}
}
__completeStateInitialization() {
// Set active user obj
try {
this.setState({user_obj: this.props.location.state.user})
} catch (e) { // Transitioning from a measure
this.setState({user_obj: this.props.user_obj})
}
// Set bunker users
try {
this.setState({
users_for_bunker: this.props.location.state.users_for_bunker,
past_users_for_bunker: this.props.past_users_for_bunker
})
} catch (e) { // Transitioning from a measure
this.setState({
users_for_bunker: this.props.users_for_bunker,
past_users_for_bunker: this.props.past_users_for_bunker
})
}
this.setState({bunker_name: this.state.bunker.name});
console.log("User object: ", this.state.user_obj)
}
// On click/change functions
__onCreateMeasureNameFormChange = (value) => {
this.setState({create_measure_form_text: value})
};
__onAddMeasureClick = () => {
this.createNewMeasure(this.state.create_measure_form_text, this.state.create_measure_default_score).then(r => console.log("Measure created:", r))
};
// Render functions
renderEmptyMeasureListItem = () => {
return (
<List.Item>
<List.Icon name='bug' size='large' verticalAlign='middle'/>
<List.Content>
<List.Header as='a'>You're in no measures!</List.Header>
<List.Description as='a'>...boringgggg...</List.Description>
</List.Content>
</List.Item>
);
};
renderMeasureListItem = (measure) => {
let lb = this.buildLeaderboard(measure.ratings, this.state.users_for_bunker);
return (
<Paper color={"grey"}>
<Card onClick={() => this.getMeasure(measure._id)} id={measure._id} raised>
<CardActionArea>
<CardContent>
<Typography variant="h5" component="h2">
{measure.name}
</Typography>
<Typography color="textSecondary" gutterBottom>
Rankings:
</Typography>
<Typography variant="body2" component="p">
1. {lb[0].name}
<br/>
2. {lb[1] ? lb[1].name : " "}
<br/>
3. {lb[2] ? lb[2].name : " "}
</Typography>
</CardContent>
</CardActionArea>
</Card>
</Paper>
);
};
genMeasureList = () => {
let data = [];
if (this.state.measures.length === 0) {
data.push(this.renderEmptyMeasureListItem())
} else {
this.state.measures.forEach(measure => data.push(this.renderMeasureListItem(measure)))
}
return data
};
render() {
let measureDataForDisplay = this.genMeasureList();
if (this.state.go_back) {
return (
< Redirect to={{pathname: "/home", state: {user: this.state.user_obj}}}/>
)
} else if (this.state.go_to_measure) {
return (
<Measure measure_name={this.state.select_measure_name}
measure_id={this.state.select_measure_id}
measure_obj={this.state.select_measure_obj}
user_obj={this.state.user_obj}
bunker_id={this.state.bunker._id}
users_for_bunker={this.state.users_for_bunker}
past_users_for_bunker={this.state.past_users_for_bunker}
buildLeaderboard={this.buildLeaderboard}
theme={this.state.theme}
/>
)
} else {
return (
<div className="full-height" style={{
backgroundColor: '#EB4D55',
backgroundSize: "cover",
position: 'absolute',
minHeight: '100%',
minWidth: '100%'
}}>
<ThemeProvider
theme={createMuiTheme(this.state.theme)}>
<SUI_Grid divided='vertically'>
<SUI_Grid.Row columns={1}>
<Container>
<Menu fixed='top' inverted borderless>
<Container>
<Menu.Item position={"left"}>
<Dropdown item
icon=''
text={<span><Icon name={'arrow left'}/> {this.state.user_obj == null ? "" : this.state.user_obj.name}</span>}
simple>
<Dropdown.Menu style={{background: "#5c5c5c"}}>
<Dropdown.Item onClick={this.setGoBack}>
<Typography
variant={'button'}
color={'textPrimary'}
>
Back to home
</Typography>
</Dropdown.Item>
<LogoutButton/>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
<Menu.Item header>
<Typography variant={'h4'}>
{this.state.bunker_name}
</Typography>
</Menu.Item>
<Menu.Item position={"right"}>
<Dropdown item icon='align justify' position={'right'} simple
direction={'left'}>
<Dropdown.Menu style={{background: "#5c5c5c"}}>
<Dropdown.Item>
<Typography
onClick={() => this.setState({adding_measure: true})}
variant={'button'}
color={'textPrimary'}
>
<Icon name='add'/>Add Measure...
</Typography>
</Dropdown.Item>
<Dropdown.Item>
<Typography
onClick={() => this.setState({inviting_others: true})}
variant={'button'}
color={'textPrimary'}
>
<Icon name='add'/>Invite Others...
</Typography>
</Dropdown.Item>
<Dialog open={this.state.adding_measure}
onClose={() => this.setState({adding_measure: false})}
aria-labelledby="add-measure-title"
aria-describedby="add-measure-description"
>
<DialogTitle
id='add-measure-title'>{"Add a measure"}</DialogTitle>
<DialogContent>
<DialogContentText id='add-measure-description'>
Create a new measure to start ranking the survivors
in your bunker!
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Measure name"
type='text'
fullWidth
color={'secondary'}
onChange={(event) => this.__onCreateMeasureNameFormChange(event.target.value)}
/>
</DialogContent>
<DialogActions>
<Button onClick={this.__onAddMeasureClick}>
Create
</Button>
</DialogActions>
</Dialog>
<Dialog open={this.state.inviting_others}
onClose={() => this.setState({inviting_others: false})}
aria-labelledby='inviting-others-title'
aria-describedby='inviting-others-description'
>
<DialogTitle id='inviting-others-title'>Invite
Others</DialogTitle>
<DialogContent>
<DialogContentText id='inviting-others-description'>
Copy and send the access code below to your friends
so
they can join you in your bunker and help you
survive!
</DialogContentText>
<Typography color={'secondary'} variant={'h5'}
align={'center'}><b>{this.state.bunker._id}</b></Typography>
</DialogContent>
<DialogActions>
<Button
onClick={() => this.setState({inviting_others: false})}>
Done
</Button>
</DialogActions>
</Dialog>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Container>
</Menu>
</Container>
</SUI_Grid.Row>
<SUI_Grid.Row columns={1}>
<MUI_Grid container spacing={5} style={{marginTop: '48px'}} direction={"row"}>
<MUI_Grid item xs={12}>
<MUI_Grid container justify="center" spacing={4}>
{measureDataForDisplay.map(value => (
<MUI_Grid item>
{value}
</MUI_Grid>
))}
</MUI_Grid>
</MUI_Grid>
</MUI_Grid>
</SUI_Grid.Row>
</SUI_Grid>
</ThemeProvider>
</div>
)
}
}
}
export default Bunker
|
module.exports = function(config){
config.set({
basePath : './',
preprocessors: {
'app/**/*.js': ['babel']
},
babelPreprocessor: {
options: {
presets: ['es2015'],
plugins: ['transform-es2015-modules-umd'],
sourceMap: 'inline'
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
}
},
frameworks: ['jasmine'],
files : [
'node_modules/angular/angular.js',
'node_modules/angular-route/angular-route.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/**/*.js'
],
autoWatch : true,
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter',
'karma-babel-preprocessor',
'karma-phantomjs-launcher'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
// console.log("hi")
// let firstName = customers.map((person)=> person.name.first)
// console.log(firstName)
// let lastName = customers.map((person)=> person.name.last)
// console.log(lastName)
// let fullName = firstName.map((fn, i)=>
// fn + " " + lastName[i] )
// console.log(fullName)
// let profileImg = customers.map((person)=> person.picture.large)
// global elements in DOM
const insertionPoint = document.querySelector('#output')
// const nameCard = document.createElement('div')
// ***** test: get the first person ******
// const person = customers[0]
// console.log(person)
//****** P1 NAME ******
//create a new div for name
// // put namecardDiv in a new class;
// // it should look like: <div class = "name-card">
// nameCard.classList.add("name-card")
// // put namecard under id output
// insertionPoint.appendChild(nameCard)
// const customerName = person.name.first + " " + person.name.last
// console.log(customerName)
// nameCard.innerHTML = `<h2>${customerName}</h2>`
// loop parts
//****** P2 Img ******
// const personImg = document.createElement ('img')
// personImg.src = person.picture.large
// console.log('person img',personImg)
// nameCard.appendChild(personImg)
//****** P3 Email Address ******
// const emailAdress = document.createElement('p')
// emailAdress.innerText = person.email
// console.log(emailAdress)
// nameCard.appendChild(emailAdress)
//****** P4 Address ******
// console.log(person.location.street.number)
// const adress = document.createElement('p')
// adress.setAttribute('id', 'Address')
// adress.innerText = person.location.street.number + " " + person.location.street.name + " " +
// person.location.city + " " + nameToAbbr(person.location.state) + " " +
// person.location.postcode
// console.log(adress)
// nameCard.appendChild(adress)
for (let person of customers) {
const nameCard = document.createElement('div')
nameCard.classList.add("name-card")
insertionPoint.appendChild(nameCard)
//name
const customerName = person.name.first + " " + person.name.last
nameCard.innerHTML = `<h2>${customerName}</h2>`
//img
const personImg = document.createElement ('img')
personImg.src = person.picture.large
console.log('person img',personImg)
nameCard.appendChild(personImg)
//email
const emailAdress = document.createElement('p')
emailAdress.setAttribute('id', 'email-address')
emailAdress.innerText = person.email
console.log(emailAdress)
nameCard.appendChild(emailAdress)
//adress
console.log(person.location.street.number)
const adress = document.createElement('p')
adress.setAttribute('id', 'Address')
adress.innerText = person.location.street.number + " " + person.location.street.name + " \n" +
person.location.city + " " + nameToAbbr(person.location.state) + " " +
person.location.postcode
console.log(adress)
nameCard.appendChild(adress)
//back slash/n \n
//DOB
const dob = document.createElement('p')
dob.setAttribute('id', 'date-of-birth')
dob.innerText = "DOB:" + moment(person.dob.date).format("MMM, D, YYYY")
console.log(dob)
nameCard.appendChild(dob)
//reg Date
const regDate = document.createElement('p')
regDate.setAttribute('id', 'customer-since')
regDate.innerText = "Customer since:" + moment(person.registered.date).format("MMM, D, YYYY")
console.log(regDate)
nameCard.appendChild(regDate)
}
|
//button function generates the password
//prompts for criteria
//prompt for length between 8-128
//prompt for character type
//window.prompt 'Would you like lower case?'
//if yes then lower case string
function name(params) {
}
var generate = function () {
/*var promptStart = window.prompt('Pick a password length between 8 and 128 characters');
if (promptStart === */
}
|
Vue.directive('fallback-image', {
bind: function (el) {
el.addEventListener('error', function() {
// 画像のロードに失敗したら実行される処理
el.src = 'https://dummyimage.com/400x400/000/ffffff.png&text-no+image'
})
}
})
new Vue({
el: '#app'
})
|
let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let BookList = require('../models/bookModel');
router.get('/', function(req, res, next){
console.log(req.query, 'url params');
let filters = { ...req.query };
console.log(filters, 'filter');
let query = {};
if(filters.title){
query.title = filters.title
}
if(filters.author){
query.bookInfo = {$regex: filters.author}
}
BookList.paginate(query, { page: Number(filters.pageNum), limit: Number(filters.pageSize) }, function(err, data) {
if(err){
res.status(500).json({ error: err });
}else{
res.json({ code: 1, data: data });
}
});
// console.log(filters.pageSize, (filters.pageNum - 1) * filters.pageNum);
//
// let limit = Number(filters.pageSize);
// let skip = Number((filters.pageNum - 1) * filters.pageNum);
//
// BookList.find(query, null, {
// limit: limit,
// skip: skip
// }, (err, data) => { //查找所有
// if(err){
// res.status(500).json({ error: err });
// }else{
// res.json({ code: 1, data: data });
// }
// })
// BookList.find(query).limit(limit).skip(skip).exec( function(err, data){ //查找所有
// if(err){
// res.status(500).json({ error: err });
// }else{
// res.json({ code: 1, data: data });
// }
// })
});
module.exports = router;
|
"use strict";
export const ALL = "all";
export const READY = "ready";
export default {
ALL,
READY
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.