<commit_before>var request = require('request');
var utils = require('./db/utils');
var proj4 = require('proj4');
proj4.defs("ESRI:102243","+proj=lcc +lat_1=37.06666666666667 +lat_2=38.43333333333333 +lat_0=36.5 +lon_0=-120.5 +x_0=2000000 +y_0=500000 +ellps=GRS80 +units=m +no_defs");

var port = process.env.PORT || 8080;
var io = require('socket.io')(port);

var CHECK_CONFLICT_INTERVAL = 12000;
var CHECK_IF_PATH_IS_UPDATED_INTERVAL = 30000;
var UPDATE_INTERVAL = 4000;

var dSay = function(msg) {
  console.log(msg);
  // push to some MQ or other storages for TTS
}

var tSay = function(msg) {
  console.log(msg);
  // push to some MQ or other storages for TTS
}

// Drones that we are currently connected with
var drones = {
  /*
  <callSign>: {
                <callSign>:,
                <location>:,
                <speed>:,
                <prevPathPtInd>:,
                <dist>:,
                <statusCode>:,
                <transcript>:
              },
              ...
  */
};
var pendingPathUpdates = {
  /*
  <callSign>: {
    <callSign>,
    <path>,
    <timeBufPrevPtInd>
  }
  */
};

io.on('connection', function(socket){

  // socket.emit('whoYouAre',{});

  // Simple test socket communication
  socket.on('tellMyName', function(msg){
    socket.emit('greetings', 'hello world ' + msg.name); // emit with a string!
  });

//*********************************************************
// Client Server Communication
//*********************************************************

  socket.on('CT_allDronesStates', function(msg){
    tSay('Sending drone list to Client Server');
    for(callSign in drones){
      // if (!drones[callSign].locationWGS84)
      drones[callSign].locationWGS84 = [];
      drones[callSign].locationWGS84 = proj4("ESRI:102243", "WGS84", drones[callSign].location);
      console.log(drones[callSign].locationWGS84);
    }
    socket.emit('TC_update', drones);
  });

//*********************************************************
// Drone Communication
//*********************************************************

  socket.on('DT_update', function(msg){
    dSay(msg.transcript);
    tSay("Tower received "+msg.callSign+"'s update.");
    drones[msg.callSign] = msg;
  });

  socket.on('DT_ack', function(msg){
    dSay(msg.transcript);
    tSay("Tower acknowledges "+msg.callSign+".");
  });

  socket.on('DT_register', function(msg){
    dSay(msg.transcript);
    tSay("Tower registering "+msg.callSign+".");
    // Put drone in local storage
    drones[msg.callSign] = msg;

    // Put drone in database
    utils.addDrone(msg.callSign, 1, 10)
    .then(function(result){
      console.log('REGISTERED/UPDATED A DRONE')
      socket.emit('TD_fileInFlightPlan');
    })
    .catch(function(error){
      console.log('Add Drone Error: ',error)
    })

  });

  socket.on('DT_fileInFlightPlan', function(msg){
    dSay(msg.transcript);
    drones[msg.callSign] = msg;

    // check flight path
    // var approved = utils.checkPathConflicts(path stuff);
    utils.getPathConflicts(msg).exec(function(err, pathConflicts) {
      if (err) {
        console.log('first error', err);
        tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan error.");
        socket.emit('TD_flightPlanDecision', {approved: false, error: err});
      }
      else if (pathConflicts.length === 0) {
        utils.addFlightPath(msg).exec(function(err, pathInfo) {
          if (err) {
            console.log('second error', err);
            tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan error.");
            socket.emit('TD_flightPlanDecision', {approved: false, error: err});
          } else {
            tSay("Tower received and approves "+msg.callSign+"'s flight plan.");
            socket.emit('TD_flightPlanDecision', {approved: true});
          }
        });
      } else {
        console.log("error: ",err);
        console.log("pathConflicts: ",pathConflicts);
        tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan restricted parcel conflicts.")
        socket.emit('TD_flightPlanDecision', {approved: false, pathConflicts: pathConflicts});
      }
    });

  });

  socket.on('DT_readyTakeOff', function(msg){
    dSay(msg.transcript);
    tSay("Acknowledged. "+msg.callSign+", initiate take off.");
    drones[msg.callSign] = msg;

    // maybe add some checks/tests b4 take off
    socket.emit('TD_takeOff')
  });

  socket.on("DT_updateAck",function(msg){
    dSay(msg.transcript);
    tSay("Tower now updating flight path in database");

    // store route into the database
    var pathUpdate = pendingPathUpdates[msg.callSign];

    utils.getFlightData(msg.callSign)
    .then(function(pathData){
      var originalPath = JSON.parse(pathData[0].path_geom);
      var newPath = originalPath.coordinates.slice(0,pathUpdate.timeBufPrevPtInd).concat(pathUpdate.path);
      var newPathGeoJSON = JSON.stringify({"type":"LineString","coordinates":newPath});
      return utils.updateFlightPath(msg.callSign, newPathGeoJSON)
    })
    .then(function(result){
      console.log('updated database')
      console.log(result)
      delete pendingPathUpdates[msg.callSign];
    })
    .catch(function(error){
      console.log(error);
    });
  });

  // Tower requests all drones for an update every N milliseconds
  setInterval(function(){
    tSay("Tower requesting updates from all drones.");
    socket.emit('TD_update', {});
  }, UPDATE_INTERVAL);

  // Tower checks for path conflicts every N milliseconds
  setInterval(function(){
    for(var i in drones){
      utils.checkForPathConflicts(drones[i].callSign, drones[i].timeBufPrevPtInd)
      .then(function(fullReroutePackage){
        if (fullReroutePackage) {
          pendingPathUpdates[drones[i].callSign] = {
            "callSign": drones[i].callSign,
            "path": JSON.parse(fullReroutePackage.reroute.flightPath).coordinates,
            "timeBufPrevPtInd": drones[i].timeBufPrevPtInd
          }
          socket.emit("TD_changeRoute", pendingPathUpdates[drones[i].callSign]);
          socket.emit("TTC_update", fullReroutePackage);
        }
      });
    }
  }, CHECK_CONFLICT_INTERVAL);

  // Tower resubmits messages for drones to update paths
  setInterval(function(){
    for(var i in pendingPathUpdates){
      socket.emit("TD_changeRoute", pendingPathUpdates[i]);
    }
  }, CHECK_IF_PATH_IS_UPDATED_INTERVAL);

});

// Client Example
// var socket = io.connect('http://server:port');
//
// socket.on('whoYouAre', function(msg){
//   socket.emit('tellMyName', { name:"Bob" }); // emit with an object!
// });

// socket.on('greetings', function(msg){
//   console.log(msg);
// });

// FlightPathCheck() {
//   pull restriction data from db;
//   calculate
//   notifies drones if anything goes wrong
// }
// setInterval(FlightPathCheck, 1500);
<commit_msg>(fix) no longer checks path of drones that are not flying<commit_after>var request = require('request');
var utils = require('./db/utils');
var proj4 = require('proj4');
proj4.defs("ESRI:102243","+proj=lcc +lat_1=37.06666666666667 +lat_2=38.43333333333333 +lat_0=36.5 +lon_0=-120.5 +x_0=2000000 +y_0=500000 +ellps=GRS80 +units=m +no_defs");

var port = process.env.PORT || 8080;
var io = require('socket.io')(port);

var CHECK_CONFLICT_INTERVAL = 12000;
var CHECK_IF_PATH_IS_UPDATED_INTERVAL = 30000;
var UPDATE_INTERVAL = 4000;

var dSay = function(msg) {
  console.log(msg);
  // push to some MQ or other storages for TTS
}

var tSay = function(msg) {
  console.log(msg);
  // push to some MQ or other storages for TTS
}

// Drones that we are currently connected with
var drones = {
  /*
  <callSign>: {
                <callSign>:,
                <location>:,
                <speed>:,
                <prevPathPtInd>:,
                <dist>:,
                <statusCode>:,
                <transcript>:
              },
              ...
  */
};
var pendingPathUpdates = {
  /*
  <callSign>: {
    <callSign>,
    <path>,
    <timeBufPrevPtInd>
  }
  */
};

io.on('connection', function(socket){

  // socket.emit('whoYouAre',{});

  // Simple test socket communication
  socket.on('tellMyName', function(msg){
    socket.emit('greetings', 'hello world ' + msg.name); // emit with a string!
  });

//*********************************************************
// Client Server Communication
//*********************************************************

  socket.on('CT_allDronesStates', function(msg){
    tSay('Sending drone list to Client Server');
    for(callSign in drones){
      // if (!drones[callSign].locationWGS84)
      drones[callSign].locationWGS84 = [];
      drones[callSign].locationWGS84 = proj4("ESRI:102243", "WGS84", drones[callSign].location);
      console.log(drones[callSign].locationWGS84);
    }
    socket.emit('TC_update', drones);
  });

//*********************************************************
// Drone Communication
//*********************************************************

  socket.on('DT_update', function(msg){
    dSay(msg.transcript);
    tSay("Tower received "+msg.callSign+"'s update.");
    drones[msg.callSign] = msg;
  });

  socket.on('DT_ack', function(msg){
    dSay(msg.transcript);
    tSay("Tower acknowledges "+msg.callSign+".");
  });

  socket.on('DT_register', function(msg){
    dSay(msg.transcript);
    tSay("Tower registering "+msg.callSign+".");
    // Put drone in local storage
    drones[msg.callSign] = msg;

    // Put drone in database
    utils.addDrone(msg.callSign, 1, 10)
    .then(function(result){
      console.log('REGISTERED/UPDATED A DRONE')
      socket.emit('TD_fileInFlightPlan');
    })
    .catch(function(error){
      console.log('Add Drone Error: ',error)
    })

  });

  socket.on('DT_fileInFlightPlan', function(msg){
    dSay(msg.transcript);
    drones[msg.callSign] = msg;

    // check flight path
    // var approved = utils.checkPathConflicts(path stuff);
    utils.getPathConflicts(msg).exec(function(err, pathConflicts) {
      if (err) {
        console.log('first error', err);
        tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan error.");
        socket.emit('TD_flightPlanDecision', {approved: false, error: err});
      }
      else if (pathConflicts.length === 0) {
        utils.addFlightPath(msg).exec(function(err, pathInfo) {
          if (err) {
            console.log('second error', err);
            tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan error.");
            socket.emit('TD_flightPlanDecision', {approved: false, error: err});
          } else {
            tSay("Tower received and approves "+msg.callSign+"'s flight plan.");
            socket.emit('TD_flightPlanDecision', {approved: true});
          }
        });
      } else {
        console.log("error: ",err);
        console.log("pathConflicts: ",pathConflicts);
        tSay("Tower received and rejects "+msg.callSign+"'s flight plan. Flight plan restricted parcel conflicts.")
        socket.emit('TD_flightPlanDecision', {approved: false, pathConflicts: pathConflicts});
      }
    });

  });

  socket.on('DT_readyTakeOff', function(msg){
    dSay(msg.transcript);
    tSay("Acknowledged. "+msg.callSign+", initiate take off.");
    drones[msg.callSign] = msg;

    // maybe add some checks/tests b4 take off
    socket.emit('TD_takeOff')
  });

  socket.on("DT_updateAck",function(msg){
    dSay(msg.transcript);
    tSay("Tower now updating flight path in database");

    // store route into the database
    var pathUpdate = pendingPathUpdates[msg.callSign];

    utils.getFlightData(msg.callSign)
    .then(function(pathData){
      var originalPath = JSON.parse(pathData[0].path_geom);
      var newPath = originalPath.coordinates.slice(0,pathUpdate.timeBufPrevPtInd).concat(pathUpdate.path);
      var newPathGeoJSON = JSON.stringify({"type":"LineString","coordinates":newPath});
      return utils.updateFlightPath(msg.callSign, newPathGeoJSON)
    })
    .then(function(result){
      console.log('updated database')
      console.log(result)
      delete pendingPathUpdates[msg.callSign];
    })
    .catch(function(error){
      console.log(error);
    });
  });

  // Tower requests all drones for an update every N milliseconds
  setInterval(function(){
    tSay("Tower requesting updates from all drones.");
    socket.emit('TD_update', {});
  }, UPDATE_INTERVAL);

  // Tower checks for path conflicts every N milliseconds
  setInterval(function(){
    for(var i in drones){
      // If the drone is not in flight, move on to next drone
      if(drones[i].statusCode !== 2){
        continue;
      }
      utils.checkForPathConflicts(drones[i].callSign, drones[i].timeBufPrevPtInd)
      .then(function(fullReroutePackage){
        if (fullReroutePackage) {
          pendingPathUpdates[drones[i].callSign] = {
            "callSign": drones[i].callSign,
            "path": JSON.parse(fullReroutePackage.reroute.flightPath).coordinates,
            "timeBufPrevPtInd": drones[i].timeBufPrevPtInd
          }
          socket.emit("TD_changeRoute", pendingPathUpdates[drones[i].callSign]);
          socket.emit("TTC_update", fullReroutePackage);
        }
      });
    }
  }, CHECK_CONFLICT_INTERVAL);

  // Tower resubmits messages for drones to update paths
  setInterval(function(){
    for(var i in pendingPathUpdates){
      socket.emit("TD_changeRoute", pendingPathUpdates[i]);
    }
  }, CHECK_IF_PATH_IS_UPDATED_INTERVAL);

});

// Client Example
// var socket = io.connect('http://server:port');
//
// socket.on('whoYouAre', function(msg){
//   socket.emit('tellMyName', { name:"Bob" }); // emit with an object!
// });

// socket.on('greetings', function(msg){
//   console.log(msg);
// });

// FlightPathCheck() {
//   pull restriction data from db;
//   calculate
//   notifies drones if anything goes wrong
// }
// setInterval(FlightPathCheck, 1500);
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const body_parser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;

app.use(body_parser.json());

app.use('/', require('./routes/home.js')(express));
app.user('/users', require('./routes/users.js')(express));
app.user('/meals', require('./routes/meals.js')(express));
app.user('/trends', require('./routes/trends.js')(express));
app.user('/intolerances', require('./routes/intolerances.js')(express));

const server = app.listen(port, () => {
  console.log('Listening on port ' + port + '...');
});

module.exports = server;
<commit_msg>app.user is not a thing<commit_after>'use strict';

const express = require('express');
const body_parser = require('body-parser');

const app = express();
const port = process.env.PORT || 3000;

app.use(body_parser.json());

app.use('/', require('./routes/home.js')(express));
app.use('/users', require('./routes/users.js')(express));
app.use('/meals', require('./routes/meals.js')(express));
app.use('/trends', require('./routes/trends.js')(express));
app.use('/intolerances', require('./routes/intolerances.js')(express));

const server = app.listen(port, () => {
  console.log('Listening on port ' + port + '...');
});

module.exports = server;
<|endoftext|>


<commit_before>const webpack = require('webpack');
const { env } = require('process');
const isProd = env.NODE_ENV === 'production';
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const isNonNil = x => x != null;
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const isProfile = env.PROFILE == 'true';

const envVars = ['NODE_ENV', 'PC_URL', 'FACTOID_URL'];

let conf = {
  entry: './src/client/index.js',

  output: {
    filename: './build/bundle.js'
  },

  devtool: 'inline-source-map',
  module: {
    rules: [
      { test: /node_modules\/cytoscape\/.*/, loader: 'babel-loader'},
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
    ]
  },
  plugins: [
    isProfile ? new BundleAnalyzerPlugin() : null,

    new webpack.EnvironmentPlugin(envVars),

    new webpack.optimize.CommonsChunkPlugin({
      name: 'deps',
      filename: './build/deps.js',
      minChunks( module ){
        let context = module.context || '';

        return context.indexOf('node_modules') >= 0;
      }
    }),

    isProd ? new UglifyJSPlugin() : null
  ].filter( isNonNil )
};

module.exports = conf;
<commit_msg>Don't run babel on cytoscape<commit_after>const webpack = require('webpack');
const { env } = require('process');
const isProd = env.NODE_ENV === 'production';
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const isNonNil = x => x != null;
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const isProfile = env.PROFILE == 'true';

const envVars = ['NODE_ENV', 'PC_URL', 'FACTOID_URL'];

let conf = {
  entry: './src/client/index.js',

  output: {
    filename: './build/bundle.js'
  },

  devtool: 'inline-source-map',
  module: {
    rules: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
    ]
  },
  plugins: [
    isProfile ? new BundleAnalyzerPlugin() : null,

    new webpack.EnvironmentPlugin(envVars),

    new webpack.optimize.CommonsChunkPlugin({
      name: 'deps',
      filename: './build/deps.js',
      minChunks( module ){
        let context = module.context || '';

        return context.indexOf('node_modules') >= 0;
      }
    }),

    isProd ? new UglifyJSPlugin() : null
  ].filter( isNonNil )
};

module.exports = conf;
<|endoftext|>


<commit_before>import { expect } from 'chai'
import flow from 'lodash/flow'
import {
  init,
  setItems,
  setSelection,
  toggle,
  getSelection,
  getChangedSelection,
  getChangedDeselection,
  getItems,
} from 'yourchoice'

import * as selectors from '../src/selectors'

describe('selectors', () => {
  let initialState = undefined

  beforeEach(() => {
    initialState = {
      selectionA: flow(
        setItems(['itemA', 'itemB', 'itemC']),
        setSelection(['itemA', 'itemC']),
        toggle('itemC')
      )(init()),
    }
  })

  describe('getSelection', () => {
    it('should return the same selection as yourchoice', () => {
      expect(selectors.getSelection(initialState.selectionA))
        .to.deep.equal(getSelection(initialState.selectionA))
    })
  })

  describe('getChangedSelection', () => {
    it('should return the same changed selection as yourchoice', () => {
      expect(selectors.getChangedSelection(initialState.selectionA))
        .to.deep.equal(getChangedSelection(initialState.selectionA))
    })
  })

  describe('getChangedDeselection', () => {
    it('should return the same changed deselection as yourchoice', () => {
      expect(selectors.getChangedDeselection(initialState.selectionA))
        .to.deep.equal(getChangedDeselection(initialState.selectionA))
    })
  })

  describe('getItems', () => {
    it('should return the same selectable items as yourchoice', () => {
      expect(selectors.getItems(initialState.selectionA))
        .to.deep.equal(getItems(initialState.selectionA))
    })
  })
})
<commit_msg>Change initialization<commit_after>import { expect } from 'chai'
import flow from 'lodash/flow'
import {
  init,
  setItems,
  setSelection,
  toggle,
  getSelection,
  getChangedSelection,
  getChangedDeselection,
  getItems,
} from 'yourchoice'

import * as selectors from '../src/selectors'

describe('selectors', () => {
  let initialState = null

  beforeEach(() => {
    initialState = {
      selectionA: flow(
        setItems(['itemA', 'itemB', 'itemC']),
        setSelection(['itemA', 'itemC']),
        toggle('itemC')
      )(init()),
    }
  })

  describe('getSelection', () => {
    it('should return the same selection as yourchoice', () => {
      expect(selectors.getSelection(initialState.selectionA))
        .to.deep.equal(getSelection(initialState.selectionA))
    })
  })

  describe('getChangedSelection', () => {
    it('should return the same changed selection as yourchoice', () => {
      expect(selectors.getChangedSelection(initialState.selectionA))
        .to.deep.equal(getChangedSelection(initialState.selectionA))
    })
  })

  describe('getChangedDeselection', () => {
    it('should return the same changed deselection as yourchoice', () => {
      expect(selectors.getChangedDeselection(initialState.selectionA))
        .to.deep.equal(getChangedDeselection(initialState.selectionA))
    })
  })

  describe('getItems', () => {
    it('should return the same selectable items as yourchoice', () => {
      expect(selectors.getItems(initialState.selectionA))
        .to.deep.equal(getItems(initialState.selectionA))
    })
  })
})
<|endoftext|>


<commit_before>var express = require("express");
var bodyParser = require("body-parser");
var _ = require("underscore");

module.exports = function(port, middleware, callback) {
    var app = express();

    if (middleware) {
        app.use(middleware);
    }
    app.use(express.static("public"));
    app.use(bodyParser.json());

    var latestId = 0;
    var todos = [];

    // Create
    app.post("/api/todo", function(req, res) {
        var todo = req.body;
        todo.id = latestId.toString();
        latestId++;
        todos.push(todo);
        res.set("Location", "/api/todo/" + todo.id);
        res.sendStatus(201);
    });

    // Read
    app.get("/api/todo", function(req, res) {
        res.json(todos);
    });

    // Delete
    app.delete("/api/todo/:id", function(req, res) {
        var id = req.params.id;
        var todo = getTodo(id);
        if (todo) {
            todos = todos.filter(function(otherTodo) {
                return otherTodo !== todo;
            });
            res.sendStatus(200);
        } else {
            res.sendStatus(404);
        }
    });

    // Update
    app.put("/api/todo/:id", function(req, res) {
        var todo = getTodo(req.params.id);
        if (todo) {
            todo.title = req.body.title;
            res.set("Location", "/api/todo/" + todo.id);
            res.sendStatus(200);
        } else {
            res.sendStatus(404);
        }
    });

    function getTodo(id) {
        return _.find(todos, function(todo) {
            return todo.id === id;
        });
    }

    var server = app.listen(port, callback);

    // We manually manage the connections to ensure that they're closed when calling close().
    var connections = [];
    server.on("connection", function(connection) {
        connections.push(connection);
    });

    return {
        close: function(callback) {
            connections.forEach(function(connection) {
                connection.destroy();
            });
            server.close(callback);
        }
    };
};
<commit_msg>Add isComplete field to todo item on server<commit_after>var express = require("express");
var bodyParser = require("body-parser");
var _ = require("underscore");

module.exports = function(port, middleware, callback) {
    var app = express();

    if (middleware) {
        app.use(middleware);
    }
    app.use(express.static("public"));
    app.use(bodyParser.json());

    var latestId = 0;
    var todos = [];

    // Create
    app.post("/api/todo", function(req, res) {
        var todo = req.body;
        todo.id = latestId.toString();
        todo.isComplete = false;
        latestId++;
        todos.push(todo);
        res.set("Location", "/api/todo/" + todo.id);
        res.sendStatus(201);
    });

    // Read
    app.get("/api/todo", function(req, res) {
        res.json(todos);
    });

    // Delete
    app.delete("/api/todo/:id", function(req, res) {
        var id = req.params.id;
        var todo = getTodo(id);
        if (todo) {
            todos = todos.filter(function(otherTodo) {
                return otherTodo !== todo;
            });
            res.sendStatus(200);
        } else {
            res.sendStatus(404);
        }
    });

    // Update
    app.put("/api/todo/:id", function(req, res) {
        var todo = getTodo(req.params.id);
        if (todo) {
            todo.title = req.body.title;
            res.set("Location", "/api/todo/" + todo.id);
            res.sendStatus(200);
        } else {
            res.sendStatus(404);
        }
    });

    function getTodo(id) {
        return _.find(todos, function(todo) {
            return todo.id === id;
        });
    }

    var server = app.listen(port, callback);

    // We manually manage the connections to ensure that they're closed when calling close().
    var connections = [];
    server.on("connection", function(connection) {
        connections.push(connection);
    });

    return {
        close: function(callback) {
            connections.forEach(function(connection) {
                connection.destroy();
            });
            server.close(callback);
        }
    };
};
<|endoftext|>


<commit_before>//conditions for winning
// 1-2-3, 4-5-6, 7-8-9
// 1-4-7, 2-5-8, 3-6-9
// 1-5-9, 3-5-7
var blues = [];

$('.square').click(function(){
  var $result = $(this).attr('class');
  //alert($result);
  blues.push($(this).attr('id'));
  $(this).click(false);
  $(this).toggleClass('filledBlue');

  console.log(blues);

  counter();

});
var tally = function(){
  var blues = [];

};

var counter = function(){
  if(
    ($('.one').hasClass('filledBlue') && $('.two').hasClass('filledBlue') && $('.three').hasClass('filledBlue'))
    ||
    ($('.four').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.six').hasClass('filledBlue'))
    ||
    ($('.seven').hasClass('filledBlue') && $('.eight').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.four').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))
    ||
    ($('.two').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.eight').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.six').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.three').hasClass('seven'))

    // $('.filledBlue').is('.three' && '.two' )
    // ||
    // $('.filledBlue').is('.four' && '.five' && '.six')
    // ||
    // $('.filledBlue').is('.seven' && '.eight' && '.nine')

    // ||
    //
    // $('.filledBlue').is('.one' && '.four' && '.seven')
    // ||
    // $('.filledBlue').is('.two' && '.five' && '.eight')
    // ||
    // $('.filledBlue').is('.three' && '.six' && '.nine')
    //
    // ||
    //
    // $('.filledBlue').is('.one' && '.five' && '.nine')
    // ||
    // $('.filledBlue').is('.three' && '.five' && '.seven')

  ){
    alert('A WINNER IS YOU!');
    reset();
  }
  // var arr = $('.filledBlue');
  // for(i = 0; i < arr.length; i++)
  // {
  //   if(arr[i] )
  //   alert('A WINNER IS YOU!')
  // };
};

var reset = function(){
  $('.square').removeClass('filledBlue');
  blues = [];
};
<commit_msg>created rules for redplayer to move<commit_after>//conditions for winning
// 1-2-3, 4-5-6, 7-8-9
// 1-4-7, 2-5-8, 3-6-9
// 1-5-9, 3-5-7

var blues = [];
var reds = [];

var blueMove = function(){

  //ALERT Blue player to move!
  $('#p1').show();
  $('#p2').hide();

  // register blue players input
  $('.square').click(function(){
    var $result = $(this).attr('class');
    //alert($result);
    blues.push($(this).attr('id'));
    $(this).click(false);
    $(this).toggleClass('filledBlue');

    console.log(blues);

    blueCounter();

  });

  // check if blue wins:
  //    yes --> reset
  //    no --> prompt red player to move
};

var redMove = function(){

  //ALERT red player to move!
  $('#p2').show();
  $('#p1').hide();

  // register blue players input
  $('.square').click(function(){
    var $result = $(this).attr('class');
    //alert($result);
    reds.push($(this).attr('id'));
    $(this).click(false);
    $(this).toggleClass('filledRed');

    console.log(reds);

    redCounter();

  });

  // check if red wins:
  //    yes --> reset
  //    no --> prompt blue player to move

};

// $('.square').click(function(){
//   var $result = $(this).attr('class');
//   //alert($result);
//   blues.push($(this).attr('id'));
//   $(this).click(false);
//   $(this).toggleClass('filledBlue');
//
//   console.log(blues);
//
//   counter();
//
// });

var blueCounter = function(){
  if(
    ($('.one').hasClass('filledBlue') && $('.two').hasClass('filledBlue') && $('.three').hasClass('filledBlue'))
    ||
    ($('.four').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.six').hasClass('filledBlue'))
    ||
    ($('.seven').hasClass('filledBlue') && $('.eight').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.four').hasClass('filledBlue') && $('.seven').hasClass('filledBlue'))
    ||
    ($('.two').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.eight').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.six').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))

    ||

    ($('.one').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.nine').hasClass('filledBlue'))
    ||
    ($('.three').hasClass('filledBlue') && $('.five').hasClass('filledBlue') && $('.three').hasClass('filledBlue'))

    // $('.filledBlue').is('.three' && '.two' )
    // ||
    // $('.filledBlue').is('.four' && '.five' && '.six')
    // ||
    // $('.filledBlue').is('.seven' && '.eight' && '.nine')

    // ||
    //
    // $('.filledBlue').is('.one' && '.four' && '.seven')
    // ||
    // $('.filledBlue').is('.two' && '.five' && '.eight')
    // ||
    // $('.filledBlue').is('.three' && '.six' && '.nine')
    //
    // ||
    //
    // $('.filledBlue').is('.one' && '.five' && '.nine')
    // ||
    // $('.filledBlue').is('.three' && '.five' && '.seven')

  ){
    alert('A WINNER IS YOU!');
    reset();
  }
  // var arr = $('.filledBlue');
  // for(i = 0; i < arr.length; i++)
  // {
  //   if(arr[i] )
  //   alert('A WINNER IS YOU!')
  // };
};

var redCounter = function(){
  if(
    ($('.one').hasClass('filledRed') && $('.two').hasClass('filledRed') && $('.three').hasClass('filledRed'))
    ||
    ($('.four').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.six').hasClass('filledRed'))
    ||
    ($('.seven').hasClass('filledRed') && $('.eight').hasClass('filledRed') && $('.nine').hasClass('filledRed'))

    ||

    ($('.one').hasClass('filledRed') && $('.four').hasClass('filledRed') && $('.seven').hasClass('filledRed'))
    ||
    ($('.two').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.eight').hasClass('filledRed'))
    ||
    ($('.three').hasClass('filledRed') && $('.six').hasClass('filledRed') && $('.nine').hasClass('filledRed'))

    ||

    ($('.one').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.nine').hasClass('filledRed'))
    ||
    ($('.three').hasClass('filledRed') && $('.five').hasClass('filledRed') && $('.three').hasClass('filledRed'))

    // $('.filledRed').is('.three' && '.two' )
    // ||
    // $('.filledRed').is('.four' && '.five' && '.six')
    // ||
    // $('.filledRed').is('.seven' && '.eight' && '.nine')

    // ||
    //
    // $('.filledRed').is('.one' && '.four' && '.seven')
    // ||
    // $('.filledRed').is('.two' && '.five' && '.eight')
    // ||
    // $('.filledRed').is('.three' && '.six' && '.nine')
    //
    // ||
    //
    // $('.filledRed').is('.one' && '.five' && '.nine')
    // ||
    // $('.filledRed').is('.three' && '.five' && '.seven')

  ){
    alert('A WINNER IS YOU!');
    reset();
  }

};

var reset = function(){
  $('.square').removeClass('filledBlue');
  $('.square').removeClass('filledRed');
  blues = [];
  reds=[];
};
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
    entry: './src/index.ts',

    output: {
        path: path.resolve('build'),
        filename: 'index.js',
        library: 'docx',
        libraryTarget: 'umd'
    },

    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: ["awesome-typescript-loader"],
            }
        ],
    },

    target: 'node'
};
<commit_msg>Enable dirname<commit_after>const path = require('path');

module.exports = {
    entry: './src/index.ts',

    output: {
        path: path.resolve('build'),
        filename: 'index.js',
        library: 'docx',
        libraryTarget: 'umd'
    },

    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: ["awesome-typescript-loader"],
            }
        ],
    },

    target: 'node',

    node: {
        __dirname: true
    }
};
<|endoftext|>


<commit_before>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var pg = require('pg');
var bodyParser = require('body-parser')
var player = require('play-sound') ( opts = {} );

var conString = "postgres://akreps@localhost/automatic-pancake";

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:7999');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

pg.connect(conString, function(err, client, done) {
    if(err) {
        return console.error('error fetching client from pool', err);
    }
    client.query('SELECT $1::int AS number', ['1'], function(err, result) {
        //call `done()` to release the client back to the pool
        done();

        if(err) {
            return console.error('error running query', err);
        }
        console.log(result.rows[0].number);
        //output: 1
    });

    var handleError = function (err) {
        // no error occurred, continue with the request
        console.log('handleError handling: ' + err);
        if (!err) return false;

        // An error occurred, remove the client from the connection pool.
        // A truthy value passed to done will remove the connection from the pool
        // instead of simply returning it to be reused.
        // In this case, if we have successfully received a client (truthy)
        // then it will be removed from the pool.
        if (client) {
            done(client);
        }
        //res.writeHead(500, {'content-type': 'text/plain'});
        //res.end('An error occurred');
        return true;
    };

    var play = function (id) {
        var fullpath = __dirname + '/files/';
        client.query('SELECT filename FROM files WHERE id = $1', [id], function (err, result) {
            handleError(err);
            fullpath += result.rows[0].filename;
            console.log("Playing " + fullpath);

            player.play(fullpath, function (err) {
                // Nulls show up a lot.  ¯\_(ツ)_/¯
                console.log('Play error ' + err);
            });
            done();
        });
        console.log(fullpath + " done!");
    };

    var getIp = function(req) {
        return req.headers['x-forwarded-for'] || req.connection.remoteAddress
    };

    var track = function(req, id) {
        client.query('INSERT INTO tracking (ip_address, file_id) VALUES ($1, $2)', [getIp(req), id], function (err, result) {
            handleError(err);
            console.log(result);
            done();
        });
    };

    app.get('/', function (req, res) {
        res.send('Hello World!');
    });

    app.get('/files', function (req, res) {
        client.query('SELECT * FROM files WHERE id > 1', [], function (err, result) {
            if (handleError(err)) return;
            res.send(result.rows);
            done();
        });
    });

    app.post('/play/:id', function (req, res) {
        console.log('Playing ' + req.params.id);
        // Check that filename exists in db.
        track(req, req.params.id);
        play(req.params.id);
        res.send();
    });

    app.post('/upload', function (req, res) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file) {
            console.log("Uploading: " + fieldname);
            fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
            file.pipe(fstream);
            client.query('INSERT INTO files (filename, created) VALUES ($1, $2)', [fieldname, new Date()], function (err, result) {
                if (handleError(err)) return;
                done();
            });
        });
        res.send();
    });

    app.post('/kill', function (req, res) {
        track(req, 'KILL');
        exec('killall mplayer', function (error, stdout, stderr) {
            console.log(stdout);
        });
        res.send();
    });

    app.listen(app.get('port'), function () {
        console.log('Server started: http://localhost:' + app.get('port') + '/');
    });
});
<commit_msg>Allowing others.<commit_after>/*
 Automatic Pancake
 */
var fs = require('fs');
//var path = require('path');
var express = require('express');
var busboy = require('connect-busboy');
var exec = require('child_process').exec;
var app = express();
var pg = require('pg');
var bodyParser = require('body-parser')
var player = require('play-sound') ( opts = {} );

var conString = "postgres://akreps@localhost/automatic-pancake";

app.set('port', 3456);
app.use(busboy());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    next();
});

pg.connect(conString, function(err, client, done) {
    if(err) {
        return console.error('error fetching client from pool', err);
    }
    client.query('SELECT $1::int AS number', ['1'], function(err, result) {
        //call `done()` to release the client back to the pool
        done();

        if(err) {
            return console.error('error running query', err);
        }
        console.log(result.rows[0].number);
        //output: 1
    });

    var handleError = function (err) {
        // no error occurred, continue with the request
        console.log('handleError handling: ' + err);
        if (!err) return false;

        // An error occurred, remove the client from the connection pool.
        // A truthy value passed to done will remove the connection from the pool
        // instead of simply returning it to be reused.
        // In this case, if we have successfully received a client (truthy)
        // then it will be removed from the pool.
        if (client) {
            done(client);
        }
        //res.writeHead(500, {'content-type': 'text/plain'});
        //res.end('An error occurred');
        return true;
    };

    var play = function (id) {
        var fullpath = __dirname + '/files/';
        client.query('SELECT filename FROM files WHERE id = $1', [id], function (err, result) {
            handleError(err);
            fullpath += result.rows[0].filename;
            console.log("Playing " + fullpath);

            player.play(fullpath, function (err) {
                // Nulls show up a lot.  ¯\_(ツ)_/¯
                console.log('Play error ' + err);
            });
            done();
        });
        console.log(fullpath + " done!");
    };

    var getIp = function(req) {
        return req.headers['x-forwarded-for'] || req.connection.remoteAddress
    };

    var track = function(req, id) {
        client.query('INSERT INTO tracking (ip_address, file_id) VALUES ($1, $2)', [getIp(req), id], function (err, result) {
            handleError(err);
            console.log(result);
            done();
        });
    };

    app.get('/', function (req, res) {
        res.send('Hello World!');
    });

    app.get('/files', function (req, res) {
        client.query('SELECT * FROM files WHERE id > 1', [], function (err, result) {
            if (handleError(err)) return;
            res.send(result.rows);
            done();
        });
    });

    app.post('/play/:id', function (req, res) {
        console.log('Playing ' + req.params.id);
        // Check that filename exists in db.
        track(req, req.params.id);
        play(req.params.id);
        res.send();
    });

    app.post('/upload', function (req, res) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file) {
            console.log("Uploading: " + fieldname);
            fstream = fs.createWriteStream(__dirname + '/files/' + fieldname);
            file.pipe(fstream);
            client.query('INSERT INTO files (filename, created) VALUES ($1, $2)', [fieldname, new Date()], function (err, result) {
                if (handleError(err)) return;
                done();
            });
        });
        res.send();
    });

    app.post('/kill', function (req, res) {
        track(req, 'KILL');
        exec('killall mplayer', function (error, stdout, stderr) {
            console.log(stdout);
        });
        res.send();
    });

    app.listen(app.get('port'), function () {
        console.log('Server started: http://localhost:' + app.get('port') + '/');
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const { upload } = require('now-storage');
const { promisify } = require('util');

async function uploadImage(name, content) {
  const { url } = await upload(process.env.NOW_TOKEN, {
    name,
    content,
  });
  return url;
}

const NOW_TOKEN = process.env.NOW_TOKEN;

const isTravis = process.env.TRAVIS;
// let filesToUpload = [];

// async function finishUploading() {
//   const { url } = await multiUpload(process.env.NOW_TOKEN, filesToUpload, {
//     deploymentName: 'bolt-jest-vrt',
//   });
//   return url;
// }
async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    // eslint-disable-next-line no-await-in-loop
    await callback(array[index], index, array);
  }
}

class JestScreenshotReporter {
  constructor(globalConfig, options) {
    this._globalConfig = globalConfig;
    this._options = options;
    this.allImagePromises = [];
  }

  async onTestResult(test, testResult, aggregateResults) {
    const self = this;
    if (
      testResult.numFailingTests &&
      testResult.failureMessage.match(/different from snapshot/)
    ) {
      await new Promise(async (resolve, reject) => {
        const testingDir = path.dirname(testResult.testFilePath);
        const filesToProcess = fs.readdirSync(
          path.join(testingDir, '/__image_snapshots__/__diff_output__/'),
        );

        filesToProcess.forEach(file => {
          const filePromise = new Promise(async function(resolve, reject) {
            const imageData = fs.readFileSync(
              path.join(
                testingDir,
                `/__image_snapshots__/__diff_output__/${file}`,
              ),
            );
            if (NOW_TOKEN) {
              await uploadImage(file, imageData).then(url => {
                const urlToDisplay = `https://${url}/${file}`;
                resolve(urlToDisplay);
              });
            } else {
              resolve(
                `${path.join(
                  testingDir,
                  `/__image_snapshots__/__diff_output__/${file}`,
                )}`,
              );
            }
          });
          resolve(self.allImagePromises.push(filePromise));
        });
      });
    }
  }

  onRunComplete(contexts, results) {
    if (NOW_TOKEN) {
      return Promise.all(this.allImagePromises)
        .then(function(values) {
          console.log(
            chalk.red.bold(`Uploaded image diff(s) to: \n${values.join('\n')}`),
          );
        })
        .catch(err => {
          console.log(
            chalk.red.bold(`Error uploading image diffs to now.sh: ${err}`),
          );
        });
    }
  }
}

module.exports = JestScreenshotReporter;
<commit_msg>fix: don't report on screenshot VRT results if none have failed<commit_after>#!/usr/bin/env node
const chalk = require('chalk');
const fs = require('fs');
const path = require('path');
const { upload } = require('now-storage');
const { promisify } = require('util');

async function uploadImage(name, content) {
  const { url } = await upload(process.env.NOW_TOKEN, {
    name,
    content,
  });
  return url;
}

const NOW_TOKEN = process.env.NOW_TOKEN;

const isTravis = process.env.TRAVIS;
// let filesToUpload = [];

// async function finishUploading() {
//   const { url } = await multiUpload(process.env.NOW_TOKEN, filesToUpload, {
//     deploymentName: 'bolt-jest-vrt',
//   });
//   return url;
// }
async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    // eslint-disable-next-line no-await-in-loop
    await callback(array[index], index, array);
  }
}

class JestScreenshotReporter {
  constructor(globalConfig, options) {
    this._globalConfig = globalConfig;
    this._options = options;
    this.allImagePromises = [];
  }

  async onTestResult(test, testResult, aggregateResults) {
    const self = this;
    if (
      testResult.numFailingTests &&
      testResult.failureMessage.match(/different from snapshot/)
    ) {
      await new Promise(async (resolve, reject) => {
        const testingDir = path.dirname(testResult.testFilePath);
        const filesToProcess = fs.readdirSync(
          path.join(testingDir, '/__image_snapshots__/__diff_output__/'),
        );

        filesToProcess.forEach(file => {
          const filePromise = new Promise(async function(resolve, reject) {
            const imageData = fs.readFileSync(
              path.join(
                testingDir,
                `/__image_snapshots__/__diff_output__/${file}`,
              ),
            );
            if (NOW_TOKEN) {
              await uploadImage(file, imageData).then(url => {
                const urlToDisplay = `https://${url}/${file}`;
                resolve(urlToDisplay);
              });
            } else {
              resolve(
                `${path.join(
                  testingDir,
                  `/__image_snapshots__/__diff_output__/${file}`,
                )}`,
              );
            }
          });
          resolve(self.allImagePromises.push(filePromise));
        });
      });
    }
  }

  onRunComplete(contexts, results) {
    if (NOW_TOKEN && this.allImagePromises.length > 0) {
      return Promise.all(this.allImagePromises)
        .then(function(values) {
          console.log(
            chalk.red.bold(`Uploaded image diff(s) to: \n${values.join('\n')}`),
          );
        })
        .catch(err => {
          console.log(
            chalk.red.bold(`Error uploading image diffs to now.sh: ${err}`),
          );
        });
    }
  }
}

module.exports = JestScreenshotReporter;
<|endoftext|>


<commit_before>'use strict';

var charImgTopLeft = document.getElementById('char-img-top-left');
var charImgTopRight = document.getElementById('char-img-top-right');
var charImgBtmLeft = document.getElementById('char-img-btm-left');
var charImgBtmRight = document.getElementById('char-img-btm-right');
var gameboard = document.getElementById('gameboard');
var roundHeader = document.getElementById('round-header');
var clicksInRound = document.getElementById('clicks-in-round');
var nextRoundButton = document.getElementById('next-round-button');
var playAgainButton = document.getElementById('play-again-button');

var clickCount = 0;
var round = 1;
var positionArray = [];

function playRound(){
  nextRoundButton.style.display = 'none';
  roundHeader.textContent = 'Round ' + round;
  clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  var randomPosition = getRandomPosition();
  if (randomPosition === 0){
    positionArray.push(charImgTopLeft);
  }
  if (randomPosition === 1){
    positionArray.push(charImgTopRight);
  }
  if (randomPosition === 2){
    positionArray.push(charImgBtmLeft);
  }
  if (randomPosition === 3){
    positionArray.push(charImgBtmRight);
  }
  renderPositionArray(positionArray, 300, 150);
  gameboard.addEventListener('click', handleUserClick);
  nextRoundButton.addEventListener('click', playRound);
}

function getRandomPosition() {
  var min = Math.ceil(0);
  var max = Math.floor(3);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function renderPosition(position, timeToShow, timeToHide) {
  window.setTimeout(function(){
    position.style.display = 'inline-block';
  }, timeToHide);
  window.setTimeout(function(){
    position.style.display = 'none';
  }, timeToShow);
}

function renderPositionArray(array, showTime, hideTime){
  for (var i = 0; i < array.length; i++){
    renderPosition(array[i], (showTime * (i + 1)) + (hideTime * i), (showTime + hideTime) * i);
  }
}

function handleUserClick(event) {
  event.preventDefault();

  var userSelection;

  if (event.target.id === 'img-top-left') {
    userSelection = 'char-img-top-left';
  }
  if (event.target.id === 'img-top-right') {
    userSelection = 'char-img-top-right';
  }
  if (event.target.id === 'img-btm-left') {
    userSelection = 'char-img-btm-left';
  }
  if (event.target.id === 'img-btm-right') {
    userSelection = 'char-img-btm-right';
  }

  if (userSelection === positionArray[clickCount].id) {
    clickCount += 1;
    clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  } else {
    loseGame();
  }

  if (clickCount === positionArray.length) {
    round += 1;
    console.log('round: ' + round);
    clickCount = 0;
    console.log('user win');
    nextRoundButton.style.display = 'block';
    gameboard.removeEventListener('click', handleUserClick);
  }

  console.log(clickCount);
}

function loseGame() {
  nextRoundButton.removeEventListener('click', playRound);
  gameboard.removeEventListener('click', handleUserClick);
  playAgainButton.style.display = 'block';
  playAgainButton.addEventListener('click', playGame);
}

function playGame(){
  clickCount = 0;
  round = 1;
  positionArray = [];

  nextRoundButton.style.display = 'block';
  nextRoundButton.addEventListener('click', playRound);

  playAgainButton.style.display = 'none';
}

//Function Calls
playAgainButton.addEventListener('click', playGame);
nextRoundButton.addEventListener('click', playRound);
playGame();
<commit_msg>update score for user<commit_after>'use strict';

var charImgTopLeft = document.getElementById('char-img-top-left');
var charImgTopRight = document.getElementById('char-img-top-right');
var charImgBtmLeft = document.getElementById('char-img-btm-left');
var charImgBtmRight = document.getElementById('char-img-btm-right');
var gameboard = document.getElementById('gameboard');
var roundHeader = document.getElementById('round-header');
var clicksInRound = document.getElementById('clicks-in-round');
var nextRoundButton = document.getElementById('next-round-button');
var playAgainButton = document.getElementById('play-again-button');
var userScore;

var scoreArray = retrieveLocalStorage(localStorage.scoreArray);

var clickCount = 0;
var round = 1;
var positionArray = [];

function storeLocalStorage() {

}

function retrieveLocalStorage(jsonArgument) {
  return JSON.parse(jsonArgument);
}

function playRound(){
  nextRoundButton.style.display = 'none';
  roundHeader.textContent = 'Round ' + round;
  clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  var randomPosition = getRandomPosition();
  if (randomPosition === 0){
    positionArray.push(charImgTopLeft);
  }
  if (randomPosition === 1){
    positionArray.push(charImgTopRight);
  }
  if (randomPosition === 2){
    positionArray.push(charImgBtmLeft);
  }
  if (randomPosition === 3){
    positionArray.push(charImgBtmRight);
  }
  renderPositionArray(positionArray, 300, 150);
  gameboard.addEventListener('click', handleUserClick);
  nextRoundButton.addEventListener('click', playRound);
}

function getRandomPosition() {
  var min = Math.ceil(0);
  var max = Math.floor(3);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function renderPosition(position, timeToShow, timeToHide) {
  window.setTimeout(function(){
    position.style.display = 'inline-block';
  }, timeToHide);
  window.setTimeout(function(){
    position.style.display = 'none';
  }, timeToShow);
}

function renderPositionArray(array, showTime, hideTime){
  for (var i = 0; i < array.length; i++){
    renderPosition(array[i], (showTime * (i + 1)) + (hideTime * i), (showTime + hideTime) * i);
  }
}

function handleUserClick(event) {
  event.preventDefault();

  var userSelection;

  if (event.target.id === 'img-top-left') {
    userSelection = 'char-img-top-left';
  }
  if (event.target.id === 'img-top-right') {
    userSelection = 'char-img-top-right';
  }
  if (event.target.id === 'img-btm-left') {
    userSelection = 'char-img-btm-left';
  }
  if (event.target.id === 'img-btm-right') {
    userSelection = 'char-img-btm-right';
  }

  if (userSelection === positionArray[clickCount].id) {
    clickCount += 1;
    clicksInRound.textContent = 'Click Count: ' + clickCount + ' / ' + round;

  } else {
    loseGame();
  }

  if (clickCount === positionArray.length) {
    round += 1;
    console.log('round: ' + round);
    clickCount = 0;
    console.log('user win');
    nextRoundButton.style.display = 'block';
    gameboard.removeEventListener('click', handleUserClick);
  }

  console.log(clickCount);
}

function loseGame() {
  nextRoundButton.removeEventListener('click', playRound);
  gameboard.removeEventListener('click', handleUserClick);
  playAgainButton.style.display = 'block';
  playAgainButton.addEventListener('click', playGame);
  userScore = round - 1;

  //user last score object score
  scoreArray[scoreArray.length - 1].score = userScore;
  console.log(scoreArray);

}

function playGame(){
  clickCount = 0;
  round = 1;
  positionArray = [];

  nextRoundButton.style.display = 'block';
  nextRoundButton.addEventListener('click', playRound);

  playAgainButton.style.display = 'none';
}

//Function Calls
playAgainButton.addEventListener('click', playGame);
nextRoundButton.addEventListener('click', playRound);
playGame();
<|endoftext|>


<commit_before>var after = require('after');
var assert = require('assert');
var Msgs = require('../src/Msgs');

suite('serialization');

test('should not have null byte if no body', function() {
    var msg = new Msgs.Logout();

    var out = msg.serialize();

    var expected = [
        '8=FIX.4.2',
        '9=57',
        '35=5',
        '52=undefined',
        '49=undefined',
        '56=undefined',
        '34=undefined',
        '10=067',
        ''
    ];

    var actual = Buffer(out).toString().split('\u0001');
    assert.deepEqual(actual, expected);
});

<commit_msg>test: fix require case mismatch<commit_after>var after = require('after');
var assert = require('assert');
var Msgs = require('../src/msgs');

suite('serialization');

test('should not have null byte if no body', function() {
    var msg = new Msgs.Logout();

    var out = msg.serialize();

    var expected = [
        '8=FIX.4.2',
        '9=57',
        '35=5',
        '52=undefined',
        '49=undefined',
        '56=undefined',
        '34=undefined',
        '10=067',
        ''
    ];

    var actual = Buffer(out).toString().split('\u0001');
    assert.deepEqual(actual, expected);
});

<|endoftext|>


<commit_before>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');

var app = express();
var phrases = ["There's no such thing as a free lunch",
"The pen is mightier than the sword",
"Keep your friends close and your enemies closer",
"There's no place like home",
"The early bird catches the worm",
"Actions speak louder than words",
"Don't bite the hand that feeds you",
"There's no time like the present",
"A penny saved is a penny earned",
"You can't judge a book by its cover",
"Two heads are better than one",
"A chain is only as strong as its weakest link",
"You can lead a horse to water, but you can't make him drink",
"It's a small world",
"Over the hill",
"Put in my two cents",
"Make love, not war",
"An apple a day keeps the doctor away",
"April showers bring May flowers",
"Somewhere over the rainbow",
"The grass is always greener on the other side",
"You cannot open a book without learning",
"Silence is a friend who never betrays",
"When anger rises, think of the consequences",]

var gameStates = {};
app.use(bodyParser.json());
app.use(express.static(path.resolve("../frontend")));

app.get("/about", function(req, res) {
    res.sendFile("about.html", { root: __dirname + "/../frontend" });
});

//Actual game page
app.get("/[a-z]{4}\\\\?", function(req, res) {
    var game = get_url(req.url);
    if(!isCurrentGame(game) || gameStates[game]["turn"] != -1)
        res.sendFile("nogame.html", { root: __dirname + "/../frontend" });
    else
        res.sendFile("game.html", { root: __dirname + "/../frontend" });
});

app.get("/[a-z]{4}/get_response.json", function(req, res) {
    var game = get_url(req.url);
    var id = req.query.num;
    var ret = {};
    if(id == -1) {
        ret["response"] = gameStates[game]["phrase"];
    } else {
        ret["response"] = gameStates[game]["players"][id]["response"];
    }
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_players.json", function(req, res) {
    var game = get_url(req.url);
    var handles = [];
    gameStates[game]["players"].forEach(function(p) {
        handles.push(p["handle"]);
    });
    var ret = {
        "players" : handles
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_results.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "results" : gameStates[game]["players"],
        "phrase" : gameStates[game]["phrase"]
    }
    res.send(JSON.stringify(ret));
    gameStates[game]["deathCounter"]--;
    console.log("Player finished. %d players left.", gameStates[game]["deathCounter"]);
    if(gameStates[game]["deathCounter"] == 0){
        removeGame(game);
    }
});

app.get("/[a-z]{4}/get_turn.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "turn" : gameStates[game]["turn"]
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_maxPlayers.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "maxPlayers" : gameStates[game]["size"]
    };
    res.send(JSON.stringify(ret));
});

app.post("/request_room.json", function(req, res) {
    var size = req.body.size;
    var url = getRandomURL();
    gameStates[url] = {};
    gameStates[url]["turn"] = -1;
    gameStates[url]["phrase"] = getRandomPhrase();
    gameStates[url]["finished"] = false;
    gameStates[url]["size"] = size;
    gameStates[url]["num_players"] = 0;
    gameStates[url]["deathCounter"] = gameStates[url]["size"];
    gameStates[url].players = [];
    console.log(JSON.stringify(gameStates));
    var ret = {
        "url" : url
    };
    res.send(JSON.stringify(ret));
});

app.post("/[a-z]{4}/join", function(req, res) {
    var game = get_url(req.url);
    var handle = req.body.handle;
    var id = gameStates[game]["num_players"];
    gameStates[game]["players"][id] = {"handle" : handle};
    console.log("Player Joined: %s with id %d", handle, id);
    var ret = {
        "id" : id
    };
    res.send(ret)
    gameStates[game]["num_players"]++;

    if(gameStates[game]["num_players"] == gameStates[game]["size"]) {
        gameStates[game]["turn"] = 0;
    }
});

app.post("/[a-z]{4}/send_response", function(req, res) {
    var game = get_url(req.url);
    var id = gameStates[game]["turn"];
    gameStates[game]["players"][id]["response"] = req.body.response;
    console.log("Revieved response from %d: %s", id, req.body.response);
    gameStates[game]["turn"]++;
    res.send({});
});

var removeGame = function(game) {
    gameStates[game] = null;
    delete gameStates[game];
    console.log("removed game: %s", game);
}

//returns
var isCurrentGame = function(game) {
    if(gameStates[game]) {
        return true;
    }
    return false;
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
}

/*
 * Obtain a random string of four lowercase alpha characters.
 * Use intended for URL generation for a room.
 */
var getRandomURL = function() {
    var text = "";
    var possible = "abcdefghhijklmnopqrstuvwxyz";
    do{
        for (var i = 0; i < 4; ++i) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
    }while(isCurrentGame(text));

    return text;
};

var getRandomPhrase = function() {
    return phrases[Math.floor(Math.random() * phrases.length)];
};

var server = app.listen(80, function() {
    console.log("Server started.");
});
<commit_msg>added another phrase<commit_after>var url = require("url");
var express = require("express");
var bodyParser = require("body-parser");
var path = require('path');

var app = express();
var phrases = ["There's no such thing as a free lunch",
"The pen is mightier than the sword",
"Keep your friends close and your enemies closer",
"There's no place like home",
"The early bird catches the worm",
"Actions speak louder than words",
"Don't bite the hand that feeds you",
"There's no time like the present",
"A penny saved is a penny earned",
"You can't judge a book by its cover",
"Two heads are better than one",
"A chain is only as strong as its weakest link",
"You can lead a horse to water, but you can't make him drink",
"It's a small world",
"Over the hill",
"Put in my two cents",
"Make love, not war",
"An apple a day keeps the doctor away",
"April showers bring May flowers",
"Somewhere over the rainbow",
"The grass is always greener on the other side",
"You cannot open a book without learning",
"Silence is a friend who never betrays",
"When anger rises, think of the consequences",
"It's raining cats and dogs"
]

var gameStates = {};
app.use(bodyParser.json());
app.use(express.static(path.resolve("../frontend")));

app.get("/about", function(req, res) {
    res.sendFile("about.html", { root: __dirname + "/../frontend" });
});

//Actual game page
app.get("/[a-z]{4}\\\\?", function(req, res) {
    var game = get_url(req.url);
    if(!isCurrentGame(game) || gameStates[game]["turn"] != -1)
        res.sendFile("nogame.html", { root: __dirname + "/../frontend" });
    else
        res.sendFile("game.html", { root: __dirname + "/../frontend" });
});

app.get("/[a-z]{4}/get_response.json", function(req, res) {
    var game = get_url(req.url);
    var id = req.query.num;
    var ret = {};
    if(id == -1) {
        ret["response"] = gameStates[game]["phrase"];
    } else {
        ret["response"] = gameStates[game]["players"][id]["response"];
    }
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_players.json", function(req, res) {
    var game = get_url(req.url);
    var handles = [];
    gameStates[game]["players"].forEach(function(p) {
        handles.push(p["handle"]);
    });
    var ret = {
        "players" : handles
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_results.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "results" : gameStates[game]["players"],
        "phrase" : gameStates[game]["phrase"]
    }
    res.send(JSON.stringify(ret));
    gameStates[game]["deathCounter"]--;
    console.log("Player finished. %d players left.", gameStates[game]["deathCounter"]);
    if(gameStates[game]["deathCounter"] == 0){
        removeGame(game);
    }
});

app.get("/[a-z]{4}/get_turn.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "turn" : gameStates[game]["turn"]
    };
    res.send(JSON.stringify(ret));
});

app.get("/[a-z]{4}/get_maxPlayers.json", function(req, res) {
    var game = get_url(req.url);
    var ret = {
        "maxPlayers" : gameStates[game]["size"]
    };
    res.send(JSON.stringify(ret));
});

app.post("/request_room.json", function(req, res) {
    var size = req.body.size;
    var url = getRandomURL();
    gameStates[url] = {};
    gameStates[url]["turn"] = -1;
    gameStates[url]["phrase"] = getRandomPhrase();
    gameStates[url]["finished"] = false;
    gameStates[url]["size"] = size;
    gameStates[url]["num_players"] = 0;
    gameStates[url]["deathCounter"] = gameStates[url]["size"];
    gameStates[url].players = [];
    console.log(JSON.stringify(gameStates));
    var ret = {
        "url" : url
    };
    res.send(JSON.stringify(ret));
});

app.post("/[a-z]{4}/join", function(req, res) {
    var game = get_url(req.url);
    var handle = req.body.handle;
    var id = gameStates[game]["num_players"];
    gameStates[game]["players"][id] = {"handle" : handle};
    console.log("Player Joined: %s with id %d", handle, id);
    var ret = {
        "id" : id
    };
    res.send(ret)
    gameStates[game]["num_players"]++;

    if(gameStates[game]["num_players"] == gameStates[game]["size"]) {
        gameStates[game]["turn"] = 0;
    }
});

app.post("/[a-z]{4}/send_response", function(req, res) {
    var game = get_url(req.url);
    var id = gameStates[game]["turn"];
    gameStates[game]["players"][id]["response"] = req.body.response;
    console.log("Revieved response from %d: %s", id, req.body.response);
    gameStates[game]["turn"]++;
    res.send({});
});

var removeGame = function(game) {
    gameStates[game] = null;
    delete gameStates[game];
    console.log("removed game: %s", game);
}

//returns
var isCurrentGame = function(game) {
    if(gameStates[game]) {
        return true;
    }
    return false;
}

var get_url = function(x) {
    var path = url.parse(x).pathname;
    return path.split("/")[1];
}

/*
 * Obtain a random string of four lowercase alpha characters.
 * Use intended for URL generation for a room.
 */
var getRandomURL = function() {
    var text = "";
    var possible = "abcdefghhijklmnopqrstuvwxyz";
    do{
        for (var i = 0; i < 4; ++i) {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
    }while(isCurrentGame(text));

    return text;
};

var getRandomPhrase = function() {
    return phrases[Math.floor(Math.random() * phrases.length)];
};

var server = app.listen(80, function() {
    console.log("Server started.");
});
<|endoftext|>


<commit_before>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = this.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {
        //bad guys
        var zombie = this.add.sprite(this.game.width, 0, 'zombie');
        var limp = zombie.animations.add('limp');
        zombie.animations.play('limp', 12, true);

        var zomkabob = this.add.sprite(this.game.width, 0, 'zomkabob');
        var chomp = zomkabob.animations.add('chomp');
        zomkabob.animations.play('chomp', 12, true);

        var hand = this.add.sprite(this.game.width, 0, 'hand');
        var crawl = hand.animations.add('crawl');
        hand.animations.play('crawl', 12, true);

        var town = this.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        this.waterParticle = this.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = this.add.sprite(0, 0, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = this.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 15, 30);
        }
        else
        {
            item.body.setSize(16, 8, 0, 5);
        }
 if (frame === 'zomkabob')
        {
            item.body.setSize(32, 14, 24, 24);
        }
        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 495)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 495;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<commit_msg>Create game.js<commit_after>//!REMEMBER! the husky took the name of man and the man took the name of husky REMEMBER!!!!
var Aquaplane = {};

Aquaplane.Preloader = function () {};

Aquaplane.Preloader.prototype = {

    init: function () {

        this.input.maxPointers = 1;

        this.scale.pageAlignHorizontally = true;

    },

    preload: function () {

        this.load.path = 'assets/';

        this.load.bitmapFont('fat-and-tiny');
        this.load.bitmapFont('interfont');

        this.load.images([ 'logo']);
        this.load.spritesheet('town', 'town1.png', 700, 700, 22);
        this.load.spritesheet('husky', 'man.png', 92, 92);
        this.load.spritesheet('man', 'husky.png', 96, 96);
        this.load.spritesheet('zombie', 'zombie.png', 96, 96);
         this.load.spritesheet('zomkabob', 'zomkabob.png', 96, 96);
          this.load.spritesheet('hand', 'hand.png', 32, 32);
    },

    create: function () {

        this.state.start('Aquaplane.MainMenu');

    }

};

Aquaplane.MainMenu = function () {};

Aquaplane.MainMenu.prototype = {

    create: function () {

        var town = this.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        var logo = this.add.image( this.world.centerX, 20, 'logo');
        logo.anchor.x = 0.5;

        var start = this.add.bitmapText(this.world.centerX, 460, 'fat-and-tiny', 'CLICK TO PLAY', 64);
        start.anchor.x = 0.5;
        start.smoothed = false;
        start.tint = 0x990000;

        this.input.onDown.addOnce(this.start, this);

    },

    start: function () {

        this.state.start('Aquaplane.Game');

    }

};

Aquaplane.Game = function (game) {

    this.score = 0;
    this.scoreText = null;

    this.lives = 3;
    this.livesText = null;

    this.speed = 420;
    this.lastKey = 0;
    this.ready = false;

    this.layer = null;
    this.itemDist = ['zomkabob', 'zomkabob', 'zomkabob', 'hand', 'hand', 'hand', 'zombie'];

    this.man = null;
    this.husky = null;
    this.rope = null;

    this.timer = null;
    this.itemInterval = { count: 0, min: 500, max: 1500 };

    this.pauseKey = null;
    this.debugKey = null;
    this.showDebug = false;

};

Aquaplane.Game.prototype = {

    init: function () {

        this.score = 0;
        this.lives = 3;
        this.speed = 420;

        this.ready = false;
        this.lastKey = 0;

        this.timer = this.time.create(false);
        this.itemInterval = { count: 0, min: 500, max: 1500 };

        this.physics.startSystem(Phaser.Physics.P2JS);
        this.physics.p2.gravity.y = 0;

        this.showDebug = false;

    },

    create: function () {
        //bad guys
        var zombie = this.add.sprite(this.game.width, 0, 'zombie');
        var limp = zombie.animations.add('limp');
        zombie.animations.play('limp', 12, true);

        var zomkabob = this.add.sprite(this.game.width, 0, 'zomkabob');
        var chomp = zomkabob.animations.add('chomp');
        zomkabob.animations.play('chomp', 12, true);

        var hand = this.add.sprite(this.game.width, 0, 'hand');
        var crawl = hand.animations.add('crawl');
        hand.animations.play('crawl', 12, true);

        var town = this.add.sprite(0, -50, 'town');
        var scroll = town.animations.add('scroll');
        town.animations.play('scroll', 12, true);

        //this.waterParticle = this.make.bitmapData(2, 2);
        //this.waterParticle.rect(0, 0, 2, 2, '#ffffff');
        //this.waterParticle.update();

        this.emitter = this.add.emitter(128, 128, 128);
        this.emitter.makeParticles(this.waterParticle);

        this.emitter.gravity = 0;
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);

        this.emitter.setAlpha(1, 0.2, 500);

        this.emitter.flow(500, 20, 2, -1, true);

        this.layer = this.add.group();

        this.man = this.layer.create(0, 0, 'man');
        var man = this.add.sprite(0, 0, 'man');
        var walk = man.animations.add('walk');
            man.animations.play('walk', 12, true)

        this.physics.p2.enable(this.man, false);

        this.man.body.mass = 0.5;
        this.man.body.damping = 0.01;
        this.man.body.fixedRotation = true;
        this.man.body.collideWorldBounds = false;

        this.husky = this.layer.create(0, 0, 'husky');
        var husky = this.add.sprite(0, 0, 'husky');
        var run = husky.animations.add('run');
        husky.animations.play('run', 12, true);

        this.physics.p2.enable(this.husky, false);

        this.husky.body.mass = 0.05;
        this.husky.body.damping = 0.01;
        this.husky.body.fixedRotation = true;
        this.husky.body.collideWorldBounds = false;

        this.manBounds = new Phaser.Rectangle(0, 0, 23, 23);
        this.huskyBounds = new Phaser.Rectangle(0, 0, 24, 24);

        var rev = new p2.RevoluteConstraint(this.man.body.data, this.husky.body.data, {
                localPivotA: [9, 0],
                localPivotB: [2, 0],
                collideConnected: false
            });

        this.physics.p2.world.addConstraint(rev);

        rev.setLimits(this.math.degToRad(-40), this.math.degToRad(40));

        rev.setStiffness(2.0);

        this.line = new Phaser.Line(this.man.x - 28, this.man.y, this.husky.x + 6, this.husky.y - 1);

        //  The rope that attaches the husky to the man
        this.rope = this.add.graphics(0, 0);

        this.scoreText = this.add.bitmapText(16, 0, 'fat-and-tiny', 'SCORE: 0', 32);
        this.scoreText.smoothed = false;

        this.livesText = this.add.bitmapText(580, 0, 'fat-and-tiny', 'LIVES: ' + this.lives, 32);
        this.livesText.smoothed = false;

        this.cursors = this.input.keyboard.createCursorKeys();

        //  Press P to pause and resume the game
        this.pauseKey = this.input.keyboard.addKey(Phaser.Keyboard.P);
        this.pauseKey.onDown.add(this.togglePause, this);

        //  Press D to toggle the debug display
        this.debugKey = this.input.keyboard.addKey(Phaser.Keyboard.D);
        this.debugKey.onDown.add(this.toggleDebug, this);

        this.bringManOn();

    },

    togglePause: function () {

        this.game.paused = (this.game.paused) ? false : true;

    },

    toggleDebug: function () {

        this.showDebug = (this.showDebug) ? false : true;

    },

    bringManOn: function () {

        this.ready = false;

        this.man.body.x = -64;
        this.man.body.y = 300;

        this.husky.visible = true;
        this.husky.body.x = -264;
        this.husky.body.y = 300;

        this.husky.body.velocity.x = 300;

    },

    manReady: function () {

        this.ready = true;

        this.man.body.setZeroVelocity();

        this.timer.add(this.itemInterval.max, this.releaseItem, this);
        this.timer.start();

    },

    releaseItem: function (x, y) {

        if (x === undefined) { x = 700; }
        if (y === undefined) { y = this.rnd.between(80, 487); }

        var frame = this.rnd.pick(this.itemDist);

        var item = this.layer.getFirstDead(true, x, y, frame);

        this.physics.arcade.enable(item);

        if (frame === 'zombie')
        {
            item.body.setSize(32, 14, 15, 30);
        }
        else
        {
            item.body.setSize(16, 8, 0, 5);
        }
 if (frame === 'zomkabob')
        {
            item.body.setSize(32, 14, 24, 24);
        }
        var i = this.math.snapToFloor(y, 65) / 65;

        item.body.velocity.x = -120 + (i * -30);

        this.itemInterval.count++;

        //  Every 10 new items we'll speed things up a bit
        if (this.itemInterval.min > 100 && this.itemInterval.count % 10 === 0)
        {
            this.itemInterval.min -= 10;
            this.itemInterval.max -= 10;
        }

        //  Is the player idle? Then release another item directly towards them
        if ((this.time.time - this.lastKey) > 200)
        {
            this.lastKey = this.time.time;
            this.releaseItem(700, this.husky.y - 16);
        }
        else
        {
            this.timer.add(this.rnd.between(this.itemInterval.min, this.itemInterval.max), this.releaseItem, this);
        }

    },

    update: function () {

        this.layer.sort('y', Phaser.Group.SORT_ASCENDING);

        if (this.ready)
        {
            this.updateMan();

            //  Score based on their position on the screen
            this.score += (this.math.snapToFloor(this.husky.y, 65) / 65);
            this.scoreText.text = "SCORE: " + this.score;
        }
        else
        {
            if (this.husky.visible)
            {
                if (this.man.x >= 250)
                {
                    this.manReady();
                }
            }
            else
            {
                if (this.man.x >= 832)
                {
                    this.bringManOn();
                }
            }
        }

        this.manBounds.centerOn(this.man.x + 4, this.man.y + 8);
        this.huskyBounds.centerOn(this.husky.x + 2, this.husky.y + 10);

        this.emitter.emitX = this.man.x - 16;
        this.emitter.emitY = this.man.y + 10;

        //  Let's sort and collide
        this.layer.forEachAlive(this.checkItem, this);

    },

    updateMan: function () {

        if (this.man.x < 200)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 200;
        }
        else if (this.man.x > 650)
        {
            this.man.body.setZeroForce();
            this.man.body.x = 650;
        }

        if (this.man.y < 100)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 100;
        }
        else if (this.man.y > 495)
        {
            this.man.body.setZeroForce();
            this.man.body.y = 495;
        }

        if (this.cursors.left.isDown)
        {
            this.man.body.force.x = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.right.isDown)
        {
            this.man.body.force.x = this.speed;
            this.lastKey = this.time.time;
        }

        if (this.cursors.up.isDown)
        {
            this.man.body.force.y = -this.speed;
            this.lastKey = this.time.time;
        }
        else if (this.cursors.down.isDown)
        {
            this.man.body.force.y = this.speed;
            this.lastKey = this.time.time;
        }

    },

    checkItem: function (item) {

        if (item === this.man || item === this.husky)
        {
            return;
        }

        if (item.x < -32)
        {
            if (item.key === 'crack')
            {
                item.x = this.rnd.between(700, 764);
            }
            else
            {
                item.kill();
            }
        }
        else
        {
            //   Check for collision
            if (this.ready && item.key !== 'crack' && this.huskyBounds.intersects(item.body))
            {
                this.loseLife();
            }
        }

    },

    loseLife: function () {

        if (this.lives === 0)
        {
            this.gameOver();
        }
        else
        {
            this.lives--;

            this.livesText.text = "LIVES: " + this.lives;

            this.ready = false;

            //  Kill the dog!
            this.husky.visible = false;

            //  Hide the rope
            this.rope.clear();

            //  Speed the man away
            this.man.body.setZeroVelocity();
            this.man.body.velocity.x = 600;

            this.itemInterval.min += 200;
            this.itemInterval.max += 200;
        }

    },

    gameOver: function () {

        this.state.start('Aquaplane.MainMenu');

    },

    preRender: function () {

        this.line.setTo(this.man.x - 48, this.man.y, this.husky.x + 46, this.husky.y - 1);

        if (this.husky.visible)
        {
            this.rope.clear();
        }

    },

    render: function () {

        if (this.showDebug)
        {
            this.game.debug.geom(this.manBounds);
            this.game.debug.geom(this.huskyBounds);
            this.layer.forEachAlive(this.renderBody, this);
            this.game.debug.geom(this.husky.position, 'rgba(255,255,0,1)');
        }

    },

    renderBody: function (sprite) {

        if (sprite === this.man || sprite === this.husky || sprite.key === 'crack')
        {
            return;
        }

        this.game.debug.body(sprite);

    }

};

var game = new Phaser.Game(700, 525, Phaser.AUTO, 'game');

game.state.add('Aquaplane.Preloader', Aquaplane.Preloader);
game.state.add('Aquaplane.MainMenu', Aquaplane.MainMenu);
game.state.add('Aquaplane.Game', Aquaplane.Game);

game.state.start('Aquaplane.Preloader');
<|endoftext|>