<commit_before>const scripts = document.getElementsByTagName('script');
let thisScript = null;
let i = scripts.length;
while (i--) {
  if (scripts[i].src && (scripts[i].src.indexOf('formio.embed') !== -1)) {
    thisScript = scripts[i];
    break;
  }
}

if (thisScript) {
  const query = {};
  let scriptSrc = thisScript.src.replace(/^([^?]+).*/, '$1').split('/');
  scriptSrc.pop();
  scriptSrc = scriptSrc.join('/');
  const queryString = thisScript.src.replace(/^[^?]+\??/,'');
  queryString.replace(/\?/g, '&').split('&').forEach((item) => {
    query[item.split('=')[0]] = item.split('=')[1] && decodeURIComponent(item.split('=')[1]);
  });

  query.script = query.script || (`${scriptSrc}/formio.form.min.js`);
  query.styles = query.styles || (`${scriptSrc}/formio.form.min.css`);
  const cdn = query.cdn || 'https://cdn.jsdelivr.net/npm';
  const config = Object.assign({
    script: query.script,
    style: query.styles,
    libs: {
      uswds: {
        js: `${cdn}/uswds@2.10.0/dist/js/uswds.min.js`,
        css: `${cdn}/uswds@2.10.0/dist/css/uswds.min.css`
      },
      fontawesome: {
        css: `${cdn}/font-awesome@4.7.0/css/font-awesome.min.css`
      },
      bootstrap: {
        css: `${cdn}/bootstrap@4.6.0/dist/css/bootstrap.min.css`
      }
    },
    class: (query.class || 'formio-form-wrapper'),
    src: query.src,
    form: null,
    submission: null,
    project: query.project,
    base: query.base,
    submit: query.submit,
    includeLibs: (query.libs === 'true' || query.libs === '1'),
    template: query.template,
    debug: (query.debug === 'true' || query.debug === '1'),
    config: {},
    redirect: (query.return || query.redirect),
    before: () => {},
    after: () => {}
  }, (window[query.c || 'FormioConfig'] || {}));

  /**
   * Print debug statements.
   *
   * @param  {...any} args Arguments to pass to the console.log method.
   */
  const debug = (...args) => {
    if (config.debug) {
      console.log(...args);
    }
  };

  /**
   * Creates a new DOM element.
   *
   * @param {string} tag The HTMLElement to add to the wrapper or shadow dom.
   * @param {Object} attrs The attributes to add to this element.
   * @param {Array<Object>} children The children attached to this element.
   */
  const createElement = (tag, attrs, children) => {
    const element = document.createElement(tag);
    for (const attr in attrs) {
      if (attrs.hasOwnProperty(attr)) {
        element.setAttribute(attr, attrs[attr]);
      }
    }
    (children || []).forEach(child => {
      element.appendChild(createElement(child.tag, child.attrs, child.children));
    });
    return element;
  };

  debug('Embeding Configuration', config);

  // The id for this embedded form.
  const id = `formio-${Math.random().toString(36).substring(7)}`;

  debug('Creating form wrapper');
  document.write(`<div id="${id}-wrapper"></div>`);
  let wrapper = document.getElementById(`${id}-wrapper`);

  // If we include the libraries, then we will attempt to run this in shadow dom.
  if (config.includeLibs && (typeof wrapper.attachShadow === 'function')) {
    wrapper = wrapper.attachShadow({ mode: 'open' });
  }

  const global = (name) => {
    const globalValue = window[name];
    debug(`Getting global ${name}`, globalValue);
    return globalValue;
  };

  const addStyles = (href, global) => {
    if (!href) {
      return;
    }
    debug('Adding Styles', href);
    const link = createElement('link', {
      rel: 'stylesheet',
      href
    });
    if (global) {
      // Add globally as well.
      document.head.appendChild(link);
    }
    wrapper.appendChild(createElement('link', {
      rel: 'stylesheet',
      href
    }));
  };

  const addScript = (src, globalProp, onReady) => {
    if (!src) {
      return;
    }
    if (globalProp && global(globalProp)) {
      debug(`${globalProp} already loaded.`);
      return global(globalProp);
    }
    debug('Adding Script', src);
    wrapper.appendChild(createElement('script', {
      src
    }));
    if (globalProp && onReady) {
      debug(`Waiting to load ${globalProp}`);
      const wait = setInterval(() => {
        if (global(globalProp)) {
          clearInterval(wait);
          debug(`${globalProp} loaded.`);
          onReady(global(globalProp));
        }
      }, 100);
    }
  };

  // Create a loader
  addStyles(`${scriptSrc}/formio.embed.min.css`);
  debug('Creating loader');
  const loader = createElement('div', {
    'class': 'formio-loader'
  }, [
    {
      tag: 'div',
      attrs: { class: 'loader-wrapper' },
      children: [
        {
          tag: 'div',
          attrs: { class: 'loader text-center' }
        }
      ]
    }
  ]);
  wrapper.appendChild(loader);

  // Add the wrapper for the rendered form.
  debug('Creating form element');
  const formElement = createElement('div', {
    class: config.class
  });
  wrapper.appendChild(formElement);

  // Add the main formio script.
  addScript(config.script, 'Formio', (Formio) => {
    const renderForm = () => {
      addStyles(config.style);
      config.before(config);
      const form = (config.form || config.src);
      debug('Creating form', form, config.config);
      Formio.createForm(formElement, form, config.config).then((instance) => {
        const submitDone = (submission) => {
          debug('Submision Complete', submission);
          let returnUrl = config.redirect;

          // Allow form based configuration for return url.
          if (
            !returnUrl &&
            (
              instance._form &&
              instance._form.settings &&
              (
                instance._form.settings.returnUrl ||
                instance._form.settings.redirect
              )
            )
          ) {
            debug('Return url found in form configuration');
            returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;
          }

          if (returnUrl) {
            const formSrc = instance.formio ? instance.formio.formUrl : '';
            const hasQuery = !!returnUrl.match(/\?/);
            const isOrigin = returnUrl.indexOf(location.origin) === 0;
            returnUrl += hasQuery ? '&' : '?';
            returnUrl += `sub=${submission._id}`;
            if (!isOrigin && formSrc) {
              returnUrl += `&form=${encodeURIComponent(formSrc)}`;
            }
            debug('Return URL', returnUrl);
            window.location.href = returnUrl;
            if (isOrigin) {
              window.location.reload();
            }
          }
        };

        if (config.submit) {
          instance.nosubmit = true;
        }

        debug('Form created', instance);

        // Remove the loader.
        debug('Removing loader');
        wrapper.removeChild(loader);

        // Adding offline mode support if the plugin is provided.
        if (global('FormioOfflineProject')) {
          const projectUrl = config.project || (new Formio(config.src)).projectUrl;
          const FormioOfflineProject = global('FormioOfflineProject');
          const offlinePlugin = new FormioOfflineProject(projectUrl);
          debug('Registring offline plugin for project.', projectUrl);
          Formio.registerPlugin(offlinePlugin, `${id}-offline`);
          offlinePlugin.ready.then(() => {
            debug('Offline Ready: Searching for previous submission...');
            offlinePlugin.db.search('submissionCache', instance._form._id, {
              sort: { created: -1 }
            }).then((subs) => {
              // Set this submission to the last captured submission.
              if (subs && subs.length) {
                debug('Setting Offline Submission', subs[0]);
                instance.submission = subs[0];
              }
            });
          });
        }

        // Set the default submission data.
        if (config.submission) {
          debug('Setting submission', config.submission);
          instance.submission = config.submission;
        }

        // Allow them to provide additional configs.
        debug('Triggering embed event');
        Formio.events.emit('formEmbedded', instance);

        debug('Calling ready callback');
        config.after(instance, config);

        // Configure a redirect.
        instance.on('submit', (submission) => {
          debug("on('submit')", submission);
          if (config.submit) {
            debug(`Sending submission to ${config.submit}`);
            const headers = {
              'content-type': 'application/json'
            };
            const token = Formio.getToken();
            if (token) {
              headers['x-jwt-token'] = token;
            }
            Formio.fetch(config.submit, {
              body: JSON.stringify(submission),
              headers: headers,
              method: 'POST',
              mode: 'cors',
            })
            .then(resp => resp.json())
            .then(submission => submitDone(submission));
          }
          else {
            submitDone(submission);
          }
        });
      });
    };

    if (config.base) {
      Formio.setBaseUrl(config.base);
    }
    if (config.project) {
      Formio.setProjectUrl(config.project);
    }

    // Add premium modules
    if (global('premium')) {
      debug('Using premium module.');
      Formio.use(global('premium'));
    }

    if (global('vpat')) {
      debug('Using vpat module.');
      Formio.use(global('vpat'));
    }

    if (config.template) {
      if (config.includeLibs) {
        addStyles(config.libs[config.template].css);
        addScript(config.libs[config.template].js);
      }
      addScript(`https://cdn.form.io/${config.template}/${config.template}.min.js`, config.template, (template) => {
        debug(`Using ${config.template}`);
        Formio.use(template);
        renderForm();
      });
    }
    else if (global('uswds')) {
      debug('Using uswds module.');
      Formio.use(global('uswds'));
    }
    // Default bootstrap + fontawesome.
    else if (config.includeLibs) {
      addStyles(config.libs.fontawesome.css, true);
      addStyles(config.libs.bootstrap.css);
    }

    // Render the form if no template is provided.
    if (!config.template) {
      renderForm();
    }
  });
}
else {
  // Show an error if the script cannot be found.
  document.write('Could not locate the Embedded form.');
}
<commit_msg>Make sure we pass the Formio instance, element, and config to the before handler.<commit_after>const scripts = document.getElementsByTagName('script');
let thisScript = null;
let i = scripts.length;
while (i--) {
  if (scripts[i].src && (scripts[i].src.indexOf('formio.embed') !== -1)) {
    thisScript = scripts[i];
    break;
  }
}

if (thisScript) {
  const query = {};
  let scriptSrc = thisScript.src.replace(/^([^?]+).*/, '$1').split('/');
  scriptSrc.pop();
  scriptSrc = scriptSrc.join('/');
  const queryString = thisScript.src.replace(/^[^?]+\??/,'');
  queryString.replace(/\?/g, '&').split('&').forEach((item) => {
    query[item.split('=')[0]] = item.split('=')[1] && decodeURIComponent(item.split('=')[1]);
  });

  query.script = query.script || (`${scriptSrc}/formio.form.min.js`);
  query.styles = query.styles || (`${scriptSrc}/formio.form.min.css`);
  const cdn = query.cdn || 'https://cdn.jsdelivr.net/npm';
  const config = Object.assign({
    script: query.script,
    style: query.styles,
    libs: {
      uswds: {
        js: `${cdn}/uswds@2.10.0/dist/js/uswds.min.js`,
        css: `${cdn}/uswds@2.10.0/dist/css/uswds.min.css`
      },
      fontawesome: {
        css: `${cdn}/font-awesome@4.7.0/css/font-awesome.min.css`
      },
      bootstrap: {
        css: `${cdn}/bootstrap@4.6.0/dist/css/bootstrap.min.css`
      }
    },
    class: (query.class || 'formio-form-wrapper'),
    src: query.src,
    form: null,
    submission: null,
    project: query.project,
    base: query.base,
    submit: query.submit,
    includeLibs: (query.libs === 'true' || query.libs === '1'),
    template: query.template,
    debug: (query.debug === 'true' || query.debug === '1'),
    config: {},
    redirect: (query.return || query.redirect),
    before: () => {},
    after: () => {}
  }, (window[query.c || 'FormioConfig'] || {}));

  /**
   * Print debug statements.
   *
   * @param  {...any} args Arguments to pass to the console.log method.
   */
  const debug = (...args) => {
    if (config.debug) {
      console.log(...args);
    }
  };

  /**
   * Creates a new DOM element.
   *
   * @param {string} tag The HTMLElement to add to the wrapper or shadow dom.
   * @param {Object} attrs The attributes to add to this element.
   * @param {Array<Object>} children The children attached to this element.
   */
  const createElement = (tag, attrs, children) => {
    const element = document.createElement(tag);
    for (const attr in attrs) {
      if (attrs.hasOwnProperty(attr)) {
        element.setAttribute(attr, attrs[attr]);
      }
    }
    (children || []).forEach(child => {
      element.appendChild(createElement(child.tag, child.attrs, child.children));
    });
    return element;
  };

  debug('Embeding Configuration', config);

  // The id for this embedded form.
  const id = `formio-${Math.random().toString(36).substring(7)}`;

  debug('Creating form wrapper');
  document.write(`<div id="${id}-wrapper"></div>`);
  let wrapper = document.getElementById(`${id}-wrapper`);

  // If we include the libraries, then we will attempt to run this in shadow dom.
  if (config.includeLibs && (typeof wrapper.attachShadow === 'function')) {
    wrapper = wrapper.attachShadow({ mode: 'open' });
  }

  const global = (name) => {
    const globalValue = window[name];
    debug(`Getting global ${name}`, globalValue);
    return globalValue;
  };

  const addStyles = (href, global) => {
    if (!href) {
      return;
    }
    debug('Adding Styles', href);
    const link = createElement('link', {
      rel: 'stylesheet',
      href
    });
    if (global) {
      // Add globally as well.
      document.head.appendChild(link);
    }
    wrapper.appendChild(createElement('link', {
      rel: 'stylesheet',
      href
    }));
  };

  const addScript = (src, globalProp, onReady) => {
    if (!src) {
      return;
    }
    if (globalProp && global(globalProp)) {
      debug(`${globalProp} already loaded.`);
      return global(globalProp);
    }
    debug('Adding Script', src);
    wrapper.appendChild(createElement('script', {
      src
    }));
    if (globalProp && onReady) {
      debug(`Waiting to load ${globalProp}`);
      const wait = setInterval(() => {
        if (global(globalProp)) {
          clearInterval(wait);
          debug(`${globalProp} loaded.`);
          onReady(global(globalProp));
        }
      }, 100);
    }
  };

  // Create a loader
  addStyles(`${scriptSrc}/formio.embed.min.css`);
  debug('Creating loader');
  const loader = createElement('div', {
    'class': 'formio-loader'
  }, [
    {
      tag: 'div',
      attrs: { class: 'loader-wrapper' },
      children: [
        {
          tag: 'div',
          attrs: { class: 'loader text-center' }
        }
      ]
    }
  ]);
  wrapper.appendChild(loader);

  // Add the wrapper for the rendered form.
  debug('Creating form element');
  const formElement = createElement('div', {
    class: config.class
  });
  wrapper.appendChild(formElement);

  // Add the main formio script.
  addScript(config.script, 'Formio', (Formio) => {
    const renderForm = () => {
      addStyles(config.style);
      config.before(Formio, formElement, config);
      const form = (config.form || config.src);
      debug('Creating form', form, config.config);
      Formio.createForm(formElement, form, config.config).then((instance) => {
        const submitDone = (submission) => {
          debug('Submision Complete', submission);
          let returnUrl = config.redirect;

          // Allow form based configuration for return url.
          if (
            !returnUrl &&
            (
              instance._form &&
              instance._form.settings &&
              (
                instance._form.settings.returnUrl ||
                instance._form.settings.redirect
              )
            )
          ) {
            debug('Return url found in form configuration');
            returnUrl = instance._form.settings.returnUrl || instance._form.settings.redirect;
          }

          if (returnUrl) {
            const formSrc = instance.formio ? instance.formio.formUrl : '';
            const hasQuery = !!returnUrl.match(/\?/);
            const isOrigin = returnUrl.indexOf(location.origin) === 0;
            returnUrl += hasQuery ? '&' : '?';
            returnUrl += `sub=${submission._id}`;
            if (!isOrigin && formSrc) {
              returnUrl += `&form=${encodeURIComponent(formSrc)}`;
            }
            debug('Return URL', returnUrl);
            window.location.href = returnUrl;
            if (isOrigin) {
              window.location.reload();
            }
          }
        };

        if (config.submit) {
          instance.nosubmit = true;
        }

        debug('Form created', instance);

        // Remove the loader.
        debug('Removing loader');
        wrapper.removeChild(loader);

        // Adding offline mode support if the plugin is provided.
        if (global('FormioOfflineProject')) {
          const projectUrl = config.project || (new Formio(config.src)).projectUrl;
          const FormioOfflineProject = global('FormioOfflineProject');
          const offlinePlugin = new FormioOfflineProject(projectUrl);
          debug('Registring offline plugin for project.', projectUrl);
          Formio.registerPlugin(offlinePlugin, `${id}-offline`);
          offlinePlugin.ready.then(() => {
            debug('Offline Ready: Searching for previous submission...');
            offlinePlugin.db.search('submissionCache', instance._form._id, {
              sort: { created: -1 }
            }).then((subs) => {
              // Set this submission to the last captured submission.
              if (subs && subs.length) {
                debug('Setting Offline Submission', subs[0]);
                instance.submission = subs[0];
              }
            });
          });
        }

        // Set the default submission data.
        if (config.submission) {
          debug('Setting submission', config.submission);
          instance.submission = config.submission;
        }

        // Allow them to provide additional configs.
        debug('Triggering embed event');
        Formio.events.emit('formEmbedded', instance);

        debug('Calling ready callback');
        config.after(instance, config);

        // Configure a redirect.
        instance.on('submit', (submission) => {
          debug("on('submit')", submission);
          if (config.submit) {
            debug(`Sending submission to ${config.submit}`);
            const headers = {
              'content-type': 'application/json'
            };
            const token = Formio.getToken();
            if (token) {
              headers['x-jwt-token'] = token;
            }
            Formio.fetch(config.submit, {
              body: JSON.stringify(submission),
              headers: headers,
              method: 'POST',
              mode: 'cors',
            })
            .then(resp => resp.json())
            .then(submission => submitDone(submission));
          }
          else {
            submitDone(submission);
          }
        });
      });
    };

    if (config.base) {
      Formio.setBaseUrl(config.base);
    }
    if (config.project) {
      Formio.setProjectUrl(config.project);
    }

    // Add premium modules
    if (global('premium')) {
      debug('Using premium module.');
      Formio.use(global('premium'));
    }

    if (global('vpat')) {
      debug('Using vpat module.');
      Formio.use(global('vpat'));
    }

    if (config.template) {
      if (config.includeLibs) {
        addStyles(config.libs[config.template].css);
        addScript(config.libs[config.template].js);
      }
      addScript(`https://cdn.form.io/${config.template}/${config.template}.min.js`, config.template, (template) => {
        debug(`Using ${config.template}`);
        Formio.use(template);
        renderForm();
      });
    }
    else if (global('uswds')) {
      debug('Using uswds module.');
      Formio.use(global('uswds'));
    }
    // Default bootstrap + fontawesome.
    else if (config.includeLibs) {
      addStyles(config.libs.fontawesome.css, true);
      addStyles(config.libs.bootstrap.css);
    }

    // Render the form if no template is provided.
    if (!config.template) {
      renderForm();
    }
  });
}
else {
  // Show an error if the script cannot be found.
  document.write('Could not locate the Embedded form.');
}
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function() {
    var connected = false;
    var disconnectMessage = "Unknown (could be unexpected server shutdown, internet outage, etc.)";
    var isKeyDown = [];
    var context;
    var canvas;
    var playerData = {
        name: "",
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        color: "#000000"
    };
    var entityNum = 0;
    var entities;
    var tilesWidth;
    var tilesHeight;
    var tiles;
    var singleTileWidth = 32; //MAGIC NUMBERS (i.e. 32 is width of tile image and draw)
    var frameLength = 1; // in milliseconds
    var gameIP = "167.88.120.57";
    var gamePort = "38734";
    var connectionInfo = "ws:" + gameIP + ":" + gamePort;
    var socket;
    var user = "";
    var pass = "";
    var windowWidth = $(window).innerWidth();
    var windowHeight = $(window).innerHeight();
    var textures = new Object();
    var errs = {
        100: "failedLogin"
    };

    function init() {
        document.body.scroll = "no"; // ie only

        pass = document.getElementById("loginInfo").pass.value;
        user = document.getElementById("loginInfo").user.value;
        if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0) {
            document.getElementById("loginInfo").user.value = "INVALID INPUT";
            return;
        }

        socket = new WebSocket(connectionInfo);

        socket.onopen = function() {
            connected = true;
            var ret = {
                "login": {
                    "user": user,
                    "pass": pass
                }
            };
            socket.send(JSON.stringify(ret));
        }

        socket.onmessage = function(message) {
            var msg = JSON.parse(message.data);
            if ("kicked" in msg) {
                connected = false;
                disconnectMessage = msg.kicked;
            }
            if ("err" in msg && msg.err in errs) {
                msg.err(); //I hope this works!
            }
            if ("validated" in msg) {
                if (msg.validated) {
                    gameInitialize();
                    gameLoop();
                }
            }
            if ("entities" in msg && "enum" in msg) {
                entities = msg.entities;
                entityNum = msg.enum;
            }
            if ("player" in msg) {
                playerData = msg.player;
            }
            if ("level" in msg) {
                tiles = msg.level.tiles;
                tilesWidth = msg.level.width;
                tilesHeight = msg.level.height;
            }
        };

        socket.onclose = function() {
            connected = false;
            $("body").empty();
            $('body').append('
Disconnected

Reason: ' + disconnectMessage);
        };

        socket.onerror = function() {

        };

        window.addEventListener("keydown", keyPress, false);
        window.addEventListener("keyup", keyRelease, false);

        $(window).resize(function() {
            windowWidth = $(window).innerWidth();
            windowHeight = $(window).innerHeight();
            canvasElement.attr({
                width: windowWidth,
                height: windowHeight,
            });
        });
    }

    function gameInitialize() {
        $("body").empty();

        clearInput();

        $('body').append('<canvas id="GameCanvas">');
        canvasElement = $('#GameCanvas');
        canvasElement.attr({
            width: windowWidth,
            height: windowHeight,
            tabIndex: 0,
            onblur: clearInput,
        }).focus();
        window.onblur = clearInput;

        canvas = canvasElement[0];
        context = canvas.getContext('2d');
        context.globalCompositeOperation = "normal";
    }

    function gameLoop() {
        if (!connected) {
            return;
        }
        var keyData = "";
        try {
            var ret = {
                "keys": isKeyDown
            };
            socket.send(JSON.stringify(ret));
        } catch (err) {}
        context.clearRect(0, 0, windowWidth, windowHeight);
        context.fillStyle = "#FFFFFF";
        context.fillRect(0, 0, windowWidth, windowHeight);
        //draw Tiles
        for (a = 0; a < tilesWidth; a++) {
            for (b = 0; b < tilesHeight; b++) {
                if (tiles[a][b].id >= 0) {
                    drawImageSection("tilesheet", gPIVX(a * singleTileWidth), gPIVY(b * singleTileWidth), tiles[a][b].id, singleTileWidth, singleTileWidth);
                }
            }
        }
        //draw entities
        var entityNameOffsetY = 5;
        for (i = 0; i < entityNum; i++) {
            var e = entities[i];
            context.fillStyle = e.color;
            drawImageMasked("player", e.color, gPIVX(e.x), gPIVY(e.y), e.width, e.height);
            context.fillText(e.name, (gPIVX(e.x) - (context.measureText(e.name).width / 2)) + (e.width / 2), gPIVY(e.y) - entityNameOffsetY);
        }
        context.fillText("Pos: (" + playerData.x + ", " + playerData.y + ")", 5, 15);

        setTimeout(gameLoop, frameLength);
    }

    function gPIVX(x) {
        //getPositionInViewportX
        return ((x - (playerData.x + (playerData.width / 2))) + (windowWidth / 2));
    }

    function gPIVY(y) {
        //getPositionInViewportY
        return ((y - (playerData.y + (playerData.height / 2))) + (windowHeight / 2));
    }

    function clearInput() {
        for (i = 0; i < 256; i++) {
            isKeyDown[i] = false;
        }
    }

    function keyPress(e) {
        if (e.keyCode < 265) {
            e.preventDefault();
            isKeyDown[e.keyCode] = true;
        }
        return false;
    }

    function keyRelease(e) {
        if (e.keyCode < 265) {
            e.preventDefault();
            isKeyDown[e.keyCode] = false;
        }
    }

    function isKeyPressed(c) {
        return isKeyDown[c.charCodeAt(0)];
    }

    function drawImageSection(name, x, y, id, spriteWidth, spriteHeight, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : spriteWidth;
        ySize = typeof ySize !== 'undefined' ? ySize : spriteHeight;
        sheetCols = Math.floor(getImage(name).width / (spriteWidth + 2));
        sheetRows = Math.floor(getImage(name).height / (spriteHeight + 2));
        context.drawImage(getImage(name), ((id % sheetCols) * (spriteWidth + 2)) + 1, (Math.floor(id / sheetRows) * (spriteHeight + 2)) + 1, spriteWidth, spriteHeight, x, y, xSize, ySize);
    }

    function drawImage(name, x, y, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : getImage(name).width;
        ySize = typeof ySize !== 'undefined' ? ySize : getImage(name).height;
        context.drawImage(getImage(name), x, y, xSize, ySize);
    }

    function drawImageMasked(name, color, x, y, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : getImage(name).width;
        ySize = typeof ySize !== 'undefined' ? ySize : getImage(name).height;
        context.drawImage(getImageMasked(name, color), x, y, xSize, ySize);
    }

    function getImageData(image) {
        var tempCanv = document.createElement('canvas');
        tempCanv.width = image.width;
        tempCanv.height = image.height;
        var tempCTX = tempCanv.getContext('2d');
        tempCTX.drawImage(image, 0, 0, image.width, image.height);
        return tempCTX.getImageData(0, 0, image.width, image.height);
    }

    function getImageFromData(data) {
        var tempCanv = document.createElement('canvas');
        tempCanv.width = data.width;
        tempCanv.height = data.height;
        var tempCTX = tempCanv.getContext('2d');
        tempCTX.putImageData(data, 0, 0);
        var src = tempCanv.toDataURL("image/png");
        var img = new Image();
        img.src = src;
        return img;
    }

    function getImage(name) {
        if ((name) in textures) {
            return textures[name];
        } else {
            textures[name] = new Image;
            textures[name].src = '/res/tex/' + name + '.png';
            return textures[name];
        }
    }

    function getImageMasked(name, color) {
        if ((name + "-mask" + color) in textures) {
            return textures[name + "-mask" + color];
        }
        var image = getImage(name);
        var mask = getImage(name + "-mask");
        if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0) {
            return new Image();
        }
        var maskData = getImageData(mask);
        var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
        var colorRGBS = regex.exec(color);
        var colorRGB = [];
        for (i = 0; i < 3; i++) {
            colorRGB[i] = parseInt(colorRGBS[i + 1], 16);
        }
        for (i = 0; i < maskData.data.length; i += 4) {
            maskData.data[i] = colorRGB[0];
            maskData.data[i + 1] = colorRGB[1];
            maskData.data[i + 2] = colorRGB[2];
        }
        var tempCanv = document.createElement('canvas');
        tempCanv.width = image.width;
        tempCanv.height = image.height;
        var tempCTX = tempCanv.getContext("2d");
        tempCTX.drawImage(image, 0, 0, image.width, image.height);
        tempCTX.drawImage(getImageFromData(maskData), 0, 0, maskData.width, maskData.height);
        var ret = new Image();
        ret.src = tempCanv.toDataURL("image/png");
        textures[name + "-mask" + color] = ret;
        return ret;
    }

    function failedLogin() {
        alert("login failed"); //Just testing it out. I'll make it pretty later.
    }

    return {
        init: init,
        textures: textures
    };
})();

$(document).ready(function() {
    $("#loginInfo").submit(function(e) {
        e.preventDefault();
        JS_GAME.game.init();
        return false;
    });
});<commit_msg>mouse position<commit_after>var JS_GAME = {};

JS_GAME.game = (function() {
    var connected = false;
    var disconnectMessage = "Unknown (could be unexpected server shutdown, internet outage, etc.)";
    var isKeyDown = [];
    var mx = 0;
    var my = 0;
    var context;
    var canvas;
    var playerData = {
        name: "",
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        color: "#000000"
    };
    var entityNum = 0;
    var entities;
    var tilesWidth;
    var tilesHeight;
    var tiles;
    var singleTileWidth = 32; //MAGIC NUMBERS (i.e. 32 is width of tile image and draw)
    var frameLength = 1; // in milliseconds
    var gameIP = "167.88.120.57";
    var gamePort = "38734";
    var connectionInfo = "ws:" + gameIP + ":" + gamePort;
    var socket;
    var user = "";
    var pass = "";
    var windowWidth = $(window).innerWidth();
    var windowHeight = $(window).innerHeight();
    var textures = new Object();
    var errs = {
        100: "failedLogin"
    };

    function init() {
        document.body.scroll = "no"; // ie only

        pass = document.getElementById("loginInfo").pass.value;
        user = document.getElementById("loginInfo").user.value;
        if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0) {
            document.getElementById("loginInfo").user.value = "INVALID INPUT";
            return;
        }

        socket = new WebSocket(connectionInfo);

        socket.onopen = function() {
            connected = true;
            var ret = {
                "login": {
                    "user": user,
                    "pass": pass
                }
            };
            socket.send(JSON.stringify(ret));
        }

        socket.onmessage = function(message) {
            var msg = JSON.parse(message.data);
            if ("kicked" in msg) {
                connected = false;
                disconnectMessage = msg.kicked;
            }
            if ("err" in msg && msg.err in errs) {
                msg.err(); //I hope this works!
            }
            if ("validated" in msg) {
                if (msg.validated) {
                    gameInitialize();
                    gameLoop();
                }
            }
            if ("entities" in msg && "enum" in msg) {
                entities = msg.entities;
                entityNum = msg.enum;
            }
            if ("player" in msg) {
                playerData = msg.player;
            }
            if ("level" in msg) {
                tiles = msg.level.tiles;
                tilesWidth = msg.level.width;
                tilesHeight = msg.level.height;
            }
        };

        socket.onclose = function() {
            connected = false;
            $("body").empty();
            $('body').append('
Disconnected

Reason: ' + disconnectMessage);
        };

        socket.onerror = function() {

        };

        window.addEventListener("keydown", keyPress, false);
        window.addEventListener("keyup", keyRelease, false);

        $(window).resize(function() {
            windowWidth = $(window).innerWidth();
            windowHeight = $(window).innerHeight();
            canvasElement.attr({
                width: windowWidth,
                height: windowHeight,
            });
        });
    }

    function gameInitialize() {
        $("body").empty();

        clearInput();

        $('body').append('<canvas id="GameCanvas">');
        canvasElement = $('#GameCanvas');
        canvasElement.attr({
            width: windowWidth,
            height: windowHeight,
            tabIndex: 0,
            onblur: clearInput,
        }).focus();
        window.onblur = clearInput;

        canvas = canvasElement[0];
        context = canvas.getContext('2d');
        context.globalCompositeOperation = "normal";

        function getMousePos(canvas, evt) {
            var rect = canvas.getBoundingClientRect();
            return {
                x: Math.round((evt.clientX-rect.left)/(rect.right-rect.left)*canvas.width),
                y: Math.round((evt.clientY-rect.top)/(rect.bottom-rect.top)*canvas.height)
            };
        }

        canvas.addEventListener("mousemove", function(evt) {
            var mousePos = getMousePos(canvas, evt);
            mx = mousePos.x;
            my = mousePos.y;
        }, false);
    }

    function gameLoop() {
        if (!connected) {
            return;
        }
        var keyData = "";
        try {
            var ret = {
                "keys": isKeyDown
            };
            socket.send(JSON.stringify(ret));
        } catch (err) {}
        context.clearRect(0, 0, windowWidth, windowHeight);
        context.fillStyle = "#FFFFFF";
        context.fillRect(0, 0, windowWidth, windowHeight);
        //draw Tiles
        for (a = 0; a < tilesWidth; a++) {
            for (b = 0; b < tilesHeight; b++) {
                if (tiles[a][b].id >= 0) {
                    drawImageSection("tilesheet", gPIVX(a * singleTileWidth), gPIVY(b * singleTileWidth), tiles[a][b].id, singleTileWidth, singleTileWidth);
                }
            }
        }
        //draw entities
        var entityNameOffsetY = 5;
        for (i = 0; i < entityNum; i++) {
            var e = entities[i];
            context.fillStyle = e.color;
            drawImageMasked("player", e.color, gPIVX(e.x), gPIVY(e.y), e.width, e.height);
            context.fillText(e.name, (gPIVX(e.x) - (context.measureText(e.name).width / 2)) + (e.width / 2), gPIVY(e.y) - entityNameOffsetY);
        }
        context.fillText("Pos: (" + playerData.x + ", " + playerData.y + ")", 5, 15);
        context.fillText("Mouse: (" + mx + ", " + my + ")", mx, my);

        setTimeout(gameLoop, frameLength);
    }

    function gPIVX(x) {
        //getPositionInViewportX
        return ((x - (playerData.x + (playerData.width / 2))) + (windowWidth / 2));
    }

    function gPIVY(y) {
        //getPositionInViewportY
        return ((y - (playerData.y + (playerData.height / 2))) + (windowHeight / 2));
    }

    function clearInput() {
        for (i = 0; i < 256; i++) {
            isKeyDown[i] = false;
        }
    }

    function keyPress(e) {
        if (e.keyCode < 265) {
            e.preventDefault();
            isKeyDown[e.keyCode] = true;
        }
        return false;
    }

    function keyRelease(e) {
        if (e.keyCode < 265) {
            e.preventDefault();
            isKeyDown[e.keyCode] = false;
        }
    }

    function isKeyPressed(c) {
        return isKeyDown[c.charCodeAt(0)];
    }

    function drawImageSection(name, x, y, id, spriteWidth, spriteHeight, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : spriteWidth;
        ySize = typeof ySize !== 'undefined' ? ySize : spriteHeight;
        sheetCols = Math.floor(getImage(name).width / (spriteWidth + 2));
        sheetRows = Math.floor(getImage(name).height / (spriteHeight + 2));
        context.drawImage(getImage(name), ((id % sheetCols) * (spriteWidth + 2)) + 1, (Math.floor(id / sheetRows) * (spriteHeight + 2)) + 1, spriteWidth, spriteHeight, x, y, xSize, ySize);
    }

    function drawImage(name, x, y, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : getImage(name).width;
        ySize = typeof ySize !== 'undefined' ? ySize : getImage(name).height;
        context.drawImage(getImage(name), x, y, xSize, ySize);
    }

    function drawImageMasked(name, color, x, y, xSize, ySize) {
        xSize = typeof xSize !== 'undefined' ? xSize : getImage(name).width;
        ySize = typeof ySize !== 'undefined' ? ySize : getImage(name).height;
        context.drawImage(getImageMasked(name, color), x, y, xSize, ySize);
    }

    function getImageData(image) {
        var tempCanv = document.createElement('canvas');
        tempCanv.width = image.width;
        tempCanv.height = image.height;
        var tempCTX = tempCanv.getContext('2d');
        tempCTX.drawImage(image, 0, 0, image.width, image.height);
        return tempCTX.getImageData(0, 0, image.width, image.height);
    }

    function getImageFromData(data) {
        var tempCanv = document.createElement('canvas');
        tempCanv.width = data.width;
        tempCanv.height = data.height;
        var tempCTX = tempCanv.getContext('2d');
        tempCTX.putImageData(data, 0, 0);
        var src = tempCanv.toDataURL("image/png");
        var img = new Image();
        img.src = src;
        return img;
    }

    function getImage(name) {
        if ((name) in textures) {
            return textures[name];
        } else {
            textures[name] = new Image;
            textures[name].src = '/res/tex/' + name + '.png';
            return textures[name];
        }
    }

    function getImageMasked(name, color) {
        if ((name + "-mask" + color) in textures) {
            return textures[name + "-mask" + color];
        }
        var image = getImage(name);
        var mask = getImage(name + "-mask");
        if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0) {
            return new Image();
        }
        var maskData = getImageData(mask);
        var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
        var colorRGBS = regex.exec(color);
        var colorRGB = [];
        for (i = 0; i < 3; i++) {
            colorRGB[i] = parseInt(colorRGBS[i + 1], 16);
        }
        for (i = 0; i < maskData.data.length; i += 4) {
            maskData.data[i] = colorRGB[0];
            maskData.data[i + 1] = colorRGB[1];
            maskData.data[i + 2] = colorRGB[2];
        }
        var tempCanv = document.createElement('canvas');
        tempCanv.width = image.width;
        tempCanv.height = image.height;
        var tempCTX = tempCanv.getContext("2d");
        tempCTX.drawImage(image, 0, 0, image.width, image.height);
        tempCTX.drawImage(getImageFromData(maskData), 0, 0, maskData.width, maskData.height);
        var ret = new Image();
        ret.src = tempCanv.toDataURL("image/png");
        textures[name + "-mask" + color] = ret;
        return ret;
    }

    function failedLogin() {
        alert("login failed"); //Just testing it out. I'll make it pretty later.
    }

    return {
        init: init,
        textures: textures
    };
})();

$(document).ready(function() {
    $("#loginInfo").submit(function(e) {
        e.preventDefault();
        JS_GAME.game.init();
        return false;
    });
});<|endoftext|>


<commit_before>'use strict';

module.exports = {
  print: console.log.bind(console),
  push: function(list, val, key) {
    if (Array.isArray(list)) {
      list.push(val);
      return list;
    }
    if ('object' === typeof list && null !== list) {
      if (!key) throw new SyntaxError('push needs a key as the last arg when used with a hashmap');
      list[key] = val;
      return list;
    }
    throw new SyntaxError('push can only be used with arrays and hashmaps');
  },
  pop: function(list) {
    if (Array.isArray(list)) return list.pop();
    throw new SyntaxError('pop can only be used with arrays');
  }
};
<commit_msg>Add map fn<commit_after>'use strict';

module.exports = {
  print: console.log.bind(console),
  push: function(list, val, key) {
    if (Array.isArray(list)) {
      list.push(val);
      return list;
    }
    if ('object' === typeof list && null !== list) {
      if (!key) throw new SyntaxError('push needs a key as the last arg when used with a hashmap');
      list[key] = val;
      return list;
    }
    throw new SyntaxError('push can only be used with arrays and hashmaps');
  },
  pop: function(list) {
    if (Array.isArray(list)) return list.pop();
    throw new SyntaxError('pop can only be used with arrays');
  },
  map: function(fn, list) {

    if('function' === typeof fn) {
      if (Array.isArray(list)) return list.map(fn);
      throw new SyntaxError('map needs an array as its second parameter');
    }
    else throw new SyntaxError('map needs a function as first parameter');
  }
};
<|endoftext|>


<commit_before>"use strict";

const Tree = {
    type: "tree",
    display: 't',
    weapon: null,
    health: null,
    block: true
};

const Empty = {
    type: 'empty',
    display: '',
    weapon: null,
    health: null,
    block: false
};

let Game = React.createClass({
    getInitialState: function () {
        let player = {
            type: 'player',
            display: 'P',
            weapon: { name: 'sword', strength: 1 },
            health: 3,
            level: 1,
            block: true,
            currentPosition: { y: 10, x: 15 }
        }

        return {
            board: this._generateBoard(25, 25, player),
            player: player
        };
    },
    componentWillMount: function () {
        let self = this;
        document.addEventListener('keydown', function (e) {
            self._move(e.keyCode);
        });
    },
    componentWillUnmount: function () {
        document.removeEventListener('keydown');
    },
    render: function () {
        return (

                <Board board={this.state.board}/>
                <Stats
                    health={this.state.player.health}
                    level={this.state.player.level}
                    weapon={this.state.player.weapon.name}
                    />

        );

    },
    _move: function (keyCode) {
        let player = Object.assign({}, this.state.player),
            y = player.currentPosition.y,
            x = player.currentPosition.x,
            board = _.cloneDeep(this.state.board),
            interactions = [];

        switch (keyCode) {
            case 38:
                if (!this.state.board[y - 1][x].block) {
                    board[y][x] = Empty;
                    board[y - 1][x] = player;
                    y -= 1;
                }
                break;
            case 40:
                if (!this.state.board[y + 1][x].block) {
                    board[y][x] = Empty;
                    board[y + 1][x] = player;
                    y += 1;
                }
                break;
            case 39:
                if (!this.state.board[y][x + 1].block) {
                    board[y][x] = Empty;
                    board[y][x + 1] = player;
                    x += 1;
                }
                break;
            case 37:
                if (!this.state.board[y][x - 1].block) {
                    board[y][x] = Empty;
                    board[y][x - 1] = player;
                    x -= 1;
                }
                break;

        }

        player.currentPosition = { y: y, x: x };

        interactions.push(this.state.board[y][x]);
        getSurroundingPositions(player.currentPosition)
            .forEach(pos => {
                if (this.state.board[pos.y][pos.x].type === 'monster') {
                    interactions.push(this.state.board[pos.y][pos.x]);
                }
            });

        interactions.forEach(obj => {
            switch (obj.type) {
                case 'monster':
                    console.log('holy cow');
                    break;
                case 'heart':
                    player.health = player.health < 10 ? player.health + 1 : player.health;
                    break;
            }
        });

        this.setState({
            player: player,
            board: board
        });

    },
    _generateBoard: function (height, width, player) {

        let board = [];

        for (let i = 0; i < height; i++) {
            let row = [];
            for (let j = 0; j < width; j++) {
                let cell;

                if (i === 0 || j === 0 || i === (height - 1) || j === (width - 1)) {
                    cell = Tree;
                } else {
                    cell = createRandomCell();
                }

                row.push(cell);
            }
            board.push(row);
        }

        board[player.currentPosition.y][player.currentPosition.x] = player;

        return board;
    }
});

let Board = function (props) {
    let rows = [];
    props.board.forEach(function (row, index) {
        let cells = [];
        row.forEach(function (cell, index) {
            cells.push(<Cell key={index} display={cell.display}/>);
        });
        rows.push(
{cells}
);
    });
    return (

{rows}

);
}

let Cell = function (props) {
    return ({props.display}	);
};

let Stats = function (props) {
    return (

                    level
                    health
                    weapon

                    {props.level}
                    {props.health}
                    {props.weapon}

)
};

ReactDOM.render(<Game/>, document.getElementById('game'));

function createRandomCell() {
    let i = Math.ceil(Math.random() * 100);

    if (i < 5) {
        return createMonster();
    }

    if (i >= 10 && i < 20) {
        return Tree
    }

    if (i >= 20 && i < 40) {
        return createItem();
    }

    return Empty;
}

function createMonster() {
    return {
        type: "monster",
        display: 'm',
        weapon: { name: 'claws', strength: Math.ceil(Math.random() * 10) },
        health: 10,
        block: true
    };
}

function createItem() {
    let i = Math.ceil(Math.random() * 100),
        type = '',
        display = '';

    if (i < 5) {
        type = 'heart';
        display = 'h'
    } else if (i >= 10 && i < 20) {
        type = 'axe';
        display = 'a';
    } else if (i >= 20 && i < 40) {
        type = 'bat';
        display = 'b';
    } else {
        type = 'zebra';
        display = 'z';
    }

    return {
        type: type,
        display: display,
        weapon: null,
        health: null,
        block: false
    };
}

function getSurroundingPositions(pos) {
    let positions = [];

    positions.push({ x: pos.x, y: pos.y + 1 });
    positions.push({ x: pos.x, y: pos.y - 1 });
    positions.push({ x: pos.x + 1, y: pos.y });
    positions.push({ x: pos.x - 1, y: pos.y });

    return positions;
}

function fight(player, monster){
    while(player.health > 0 && monster.health > 0){
        monster.health -= Math.ceil(Math.random() * player.weapon.strength);

        if(monster.health > 0){
            player.health -= Math.ceil(Math.random() * monster.weapon.strength);
        }
    }

    return [player, monster];
}<commit_msg>fixed error<commit_after>let React = require('react');
let ReactDOM = require('react-dom');

var Cell = React.createClass({
    shouldComponentUpdate: function(){
        return this.props.lastModified.includes(this.props.id);
    },
    render: function(){
        return (

            );
    }
});

var Board = function (props) {
    var rows = [];

    for (let i = 1; i <= props.boardHeight; i++) {
        let cells = [];

        for (let j = 1; j <= props.boardWidth; j++) {
            let id = createId(j, i),
                alive = props.cells[id].alive ? true : false;
            cells.push(
                <Cell
                    id={id}
                    key={id}
                    alive={alive}
                    handleCellClick={props.handleCellClick}
                    lastModified={props.lastModified}
                />
            );
        }
        rows.push(
{cells}
);
    }

    return (

{rows}

);
};

var Form = React.createClass({
    getInitialState: function () {
        return {
            boardWidth: this.props.boardWidth,
            boardHeight: this.props.boardHeight
        };
    },
    render: function () {
        return (
            <form onSubmit={this._onSubmit}>

                    <input
                        id="boardHeight"
                        value={this.state.boardHeight}
                        type="text"
                        onChange={this._onHeightInput}
                        />

                    <input
                        id="boardWidth"
                        value={this.state.boardWidth}
                        type="text"
                        onChange={this._onWidthInput}
                        />
                    <button type="submit">regenerate board</button>

                    <button type="button" onClick={this.props.handleStartClick}></button>
                    <button type="button" onClick={this.props.handleStopClick}></button>
                    <button type="button" onClick={this.props.handleClearClick}></button>

            </form>
        );
    },
    _onWidthInput: function (e) {
        if (typeof e.target.value === "string") {
            this.setState({ boardWidth: e.target.value });
        }
    },
    _onHeightInput: function (e) {
        if (typeof e.target.value === "string") {
            this.setState({ boardHeight: e.target.value });
        }
    },
    _onSubmit: function (e) {
        e.preventDefault();
        this.props.onBoardSizeChange({
            boardHeight: this.state.boardHeight,
            boardWidth: this.state.boardWidth
        });
    }
});

var Game = React.createClass({
    getInitialState: function () {
        let height = 25,
            width = 50,
            cells = this._populateCells(width, height, true),
            lastModified = [];

        for (let id in cells) {
            if (cells[id].alive) {
                lastModified.push(id);
            }
        }

        return {
            boardHeight: height,
            boardWidth: width,
            cells: cells,
            lastModified: lastModified,
            generation: 0
        };
    },
    componentDidMount: function () {
        this._handleStartClick();
    },
    render: function () {
        return (

Conway's Game of Life

Generation: {this.state.generation}

                <Board
                    boardWidth={this.state.boardWidth}
                    boardHeight={this.state.boardHeight}
                    handleCellClick={this._handleCellClick}
                    cells={this.state.cells}
                    lastModified={this.state.lastModified}
                    />
                <Form
                    onBoardSizeChange={this._updateBoard}
                    boardWidth={this.state.boardWidth}
                    boardHeight={this.state.boardHeight}
                    handleStartClick={this._handleStartClick}
                    handleStopClick={this._handleStopClick}
                    handleClearClick={this._handleClearClick}
                    />

        );
    },
    _runGeneration: function () {
        let cells = Object.assign({}, this.state.cells);
        let nextModified = [];

        this.state.lastModified.forEach(function (id) {
            cells[id].neighbors.forEach(function (nId) {
                let cell = cells[nId];
                if (cell) {
                    cell.liveNeighbors += cells[id].alive ? 1 : -1;
                }
            });
        });

        this.state.lastModified.forEach(function (id) {
            cells[id].neighbors.forEach(function (nId) {
                let cell = cells[nId];
                if (cell) {
                    if (cell.alive && cell.liveNeighbors < 2) {
                        cell.alive = false;
                        nextModified.push(nId);

                    }

                    if (cell.alive && cell.liveNeighbors > 3) {
                        cell.alive = false;
                        nextModified.push(nId);

                    }

                    if (!cell.alive && cell.liveNeighbors === 3) {
                        cell.alive = true;
                        nextModified.push(nId);

                    }
                }
            });
            let cell = cells[id];
            if (cell) {
                if (cell.alive && cell.liveNeighbors < 2) {
                    cell.alive = false;
                    nextModified.push(id);
                }

                if (cell.alive && cell.liveNeighbors > 3) {
                    cell.alive = false;
                    nextModified.push(id);
                }

                if (!cell.alive && cell.liveNeighbors === 3) {
                    cell.alive = true;
                    nextModified.push(id);
                }
            }
        });

        this.setState({
            cells: cells,
            lastModified: nextModified,
            generation: this.state.generation + 1
        });
    },
    _updateBoard: function (boardSize) {
        let  lastModified = [],
             cells = this._populateCells(boardSize.boardWidth, boardSize.boardHeight, true);

        for (let id in cells) {
            if (cells[id].alive) {
                lastModified.push(id);
            }
        }

        this.setState({
            cells: cells,
            boardWidth: boardSize.boardWidth,
            boardHeight: boardSize.boardHeight,
            generation: 0,
            lastModified: lastModified
        });
    },
    _handleCellClick: function (e) {
        let cells = Object.assign({}, this.state.cells),
            modified = this.state.lastModified;

        cells[e.target.id].alive = cells[e.target.id].alive ? false : true;

        if (modified.indexOf(e.target.id) < 0) {
            modified.push(e.target.id);
        }

        this.setState({ cells: cells, lastModified: modified });
    },
    _populateCells: function (width, height, random) {
        let cells = {};

        for (let i = 1; i <= width; i++) {
            for (let j = 1; j <= height; j++) {
                let id = createId(i, j);
                cells[id] = cell(i, j);
                cells[id].alive = random ? Math.random() > .5 ? true : false : false;
            }
        }

        return cells;
    },
    _handleStartClick: function () {
        let self = this;
        let interval = setInterval(function () {
            self._runGeneration();
        }, 0);

        this.setState({ interval: interval });
    },
    _handleStopClick: function () {
        clearInterval(this.state.interval);
    },
    _handleClearClick: function () {
        this.setState({
            cells: this._populateCells(this.state.boardWidth, this.state.boardHeight),
            lastModified: [],
            generation: 0
        });
    }

});

function createId(x, y) {
    return .5 * (x + y) * (x + y + 1) + y;
}

function cell(x, y) {
    return {
        alive: false,
        liveNeighbors: 0,
        neighbors: findNeighbors(x, y)
    };

    function findNeighbors(x, y) {
        return [
            createId(x - 1, y - 1),
            createId(x + 1, y),
            createId(x, y + 1),
            createId(x + 1, y + 1),
            createId(x, y - 1),
            createId(x + 1, y - 1),
            createId(x - 1, y + 1),
            createId(x - 1, y)
        ];
    }

}

ReactDOM.render(<Game/>, document.getElementById('game'));

<|endoftext|>


<commit_before>import Promise from 'bluebird';
import Email from '../models/email.model';
import Box from '../models/box.model';
import config from '../../config/env';
import User from '../models/user.model';
import Analyzer from '../core/engine/analyzer';
import fs from 'fs';
import Socket from '../routes/socket';

function sendEmail(req, res) {
  req.user.createSMTPConnector().sendMail(req.body)
    .then(result => {
      return Box.findOne({name: config.gmail.send, user: req.user});
    })
    .then(box => {
      return req.user.createIMAPConnector().fetchBoxes(storeEmail, [box]);
    })
    .then(() => {
      res.status(200).send({message: 'Finished fetching'});
    })
    .catch((err) => {
      console.log(err);
      res.status(400).send(err);
    });
}

/** Adds a box and updates the client via socket */
function addBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  emailConnector.addBox(req.body.boxName)
    .then(() => {
      return syncIMAPBoxes(user, emailConnector);
    })
    .then(() => {
      res.status(200).send({message: 'Box added'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Deletes a box and updates the client via Socket */
function delBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId}).populate('parent')
    .then(boxToDelete => {
      return [boxToDelete, emailConnector.delBox(boxToDelete.name)]
    })
    .spread(boxToDelete => {
      return [boxToDelete, Box.cascadeDeleteBoxById(boxToDelete._id, user._id, false)]
    })
    .spread((boxDeleted, msg) => {
      Socket.deleteBox(user._id, boxDeleted);
    })
    .then(() => {
      res.status(200).send({message: 'Box deleted'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

function renameBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  Box.findOne({_id: req.body.oldBoxId}).populate('parent')
    .then(oldBox => {
      const shortName = req.body.newBoxShortName;
      const newBoxName = oldBox.parent != null ? oldBox.parent.name + '/' + shortName : shortName;
      return [oldBox, emailConnector.renameBox(oldBox.name, newBoxName)]
    })
    .spread((oldBox, newBoxName) => {
      return Box.rename(oldBox._id, newBoxName);
    })
    .then(box => {
      Socket.updateBox(user._id, box);
      res.status(200).send({message: `Renamed box: ${box.name}`});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

function append(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({name: req.body.box, user: req.user})
    .then(box => {
      return [box, emailConnector.append(req.body.box, req.body.args, req.body.to, req.body.from, req.body.subject, req.body.msgData)]
    })
    .spread((box, msgData) => {
      return [msgData, emailConnector.fetchBoxes(storeEmail, [box])]
    })
    .spread((msgData, result) => {
      res.status(200).send({msgData: msgData});
    })
    .catch((err) => {
      console.log(err);
      res.status(400).send(err);
    });
}

function move(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Email.findOne({_id: req.body.emailId}).populate('box')
    .then(email => {
      return [email, Box.findOne({_id: req.body.newBoxId, user: req.user})]
    })
    .spread((email, destBox) => {
      const srcBox = email.box;
      return [srcBox, destBox, emailConnector.move(email.uid, srcBox.name, destBox.name)]
    })
    .spread((srcBox, destBox, msgId) => {
      return emailConnector.fetchBoxes(storeEmail, [srcBox, destBox])
    })
    .then((messages) => {
      res.status(200).send({messages: messages});
    })
    .catch(err => {
      console.log(err);
      res.status(400).send(err);
    });
}

function addFlags(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId, user: req.user})
    .then(box => {
      return [box, emailConnector.addFlags(req.body.msgId, req.body.flags, box.name)]
    })
    .spread((box, msgId) => {
      return Email.findOne({uid: req.body.msgId, box: box})
    })
    .then((email) => {
      email.flags = email.flags.concat(req.body.flags);
      return email.save();
    })
    .then(() => {
      res.status(200).send({message: 'Successfully added Flags'});
    })
    .catch(err => {
      res.status(400).send(err);
    });
}

function delFlags(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId, user: req.user})
    .then(box => {
      return [box, emailConnector.delFlags(req.body.msgId, req.body.flags, box.name)]
    })
    .spread((box, msgId) => {
      return Email.findOne({uid: req.body.msgId, box: box})
    })
    .then((email) => {
      req.body.flags.forEach((f) => {
        const index = email.flags.indexOf(f);
        if (index > -1)
          email.flags.splice(index, 1);
      });
      return email.save()
    })
    .then(() => {
      res.status(200).send({message: 'Successfully deleted Flags'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Returns one single mail with all details */
function getSingleMail(req, res) {
  Email.findOne({_id: req.params.id}).lean()
    .then((mail) => {
      return (mail && (req.user.trello || req.user.sociocortex)) ? new Analyzer(mail, req.user).getEmailTasks() : mail;
    })
    .then(email => {
      res.status(200).send(email);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Stores an email in the database and
 *  pushs upates via socket to the client */
function storeEmail(mail) {
  return new Promise((resolve, reject) => {
    Email.updateAndGetOldAndUpdated(mail)
      .spread((emailOld, boxOld, emailUpdated, boxUpdated) => {
        // TODO new box numbers do not work properly
        console.log('inside storeEmail...');
        console.log(JSON.stringify(boxOld));
        console.log(JSON.stringify(boxUpdated));
        Socket.pushEmailUpdateToClient(emailOld, boxOld, emailUpdated, boxUpdated);
        resolve(emailUpdated);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/** Search emails either for box or user serach */
function searchMails(req, res) {

  const options = {
    boxId: req.query.boxId,
    sort: req.query.sort, // ASC or DESC
    search: req.query.search,
    lastEmailDate: new Date(req.query.lastEmailDate)
  };

  Email.search(req.user._id, options)
    .then(emails => {
      res.status(200).send(emails);
    })
    .catch(err => {
      res.status(400).send(err);
    });
}

/** Returns the current boxes from the database */
function getBoxes(req, res) {
  Box.getBoxesByUserId(req.user._id)
    .then(boxes => {
      res.status(200).send(boxes);
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

/** Syncronizes the boxes of the user via IMAP */
function syncIMAPBoxes(user, emailConnector) {
  return new Promise((resolve, reject) => {
    emailConnector
      .getBoxes(false)
      .then(boxes => {
        console.log(boxes);
        return Promise.each(boxes, (box) => {
          return new Promise((resolve, reject) => {
            Box.updateAndGetOldAndUpdated(box, user)
              .spread((oldBox, updatedBox) => {
                Socket.pushBoxUpdateToClient(oldBox, updatedBox);
                resolve()
              })
              .catch(err => {
                reject(err);
              });
          });
        });
      })
      .then(() => {
        return Box.deleteUpdatedAtOlderThan(user._id, user.lastSync);
      })
      .then(delBoxes => {
        delBoxes.forEach(box => {
          Socket.pushBoxUpdateToClient(box, null);
        });
        resolve();
      })
      .catch(err => {
        reject(err);
      });
  })
}

/** Syncronizes the emails of the user via IMAP */
function syncIMAPMails(user, emailConnector) {
  const before = new Date();
  console.log('--> syncIMAPMails');
  return new Promise((resolve, reject) => {
    Box.find({user: user})
      .then(boxes => {
        return emailConnector.fetchBoxes(storeEmail, boxes)
      })
      .then(() => {
        console.log('Time for fetching: ', new Date() - before);
        resolve();
      })
      .catch(err => {
        reject(err)
      });
  })
}

/** Syncronizes the boxes and emails of the user via IMAP */
function syncIMAP(req, res) {
  console.log('-> syncIMAP');
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  user.lastSync = new Date();
  user.save()
    .then(() => {
      return syncIMAPBoxes(user, emailConnector)
    })
    .then(() => {
      return syncIMAPMails(user, emailConnector);
    })
    .then(() => {
      console.log('all synced!');
      res.status(200).send({message: 'Finished syncing'});
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

/** Creates autocomplete suggestions for email addresses */
function autocomplete(req, res) {
  Email.autocomplete(req.user._id)
    .then(suggestions => {
      res.status(200).send(suggestions);
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

export default {
  addBox,
  delBox,
  renameBox,
  append,
  move,
  sendEmail,
  addFlags,
  delFlags,
  searchMails,
  getSingleMail,
  getBoxes,
  syncIMAP
};
<commit_msg>Refactor addBox - use parentBoxId instead of name<commit_after>import Promise from 'bluebird';
import Email from '../models/email.model';
import Box from '../models/box.model';
import config from '../../config/env';
import User from '../models/user.model';
import Analyzer from '../core/engine/analyzer';
import fs from 'fs';
import Socket from '../routes/socket';

function sendEmail(req, res) {
  req.user.createSMTPConnector().sendMail(req.body)
    .then(result => {
      return Box.findOne({name: config.gmail.send, user: req.user});
    })
    .then(box => {
      return req.user.createIMAPConnector().fetchBoxes(storeEmail, [box]);
    })
    .then(() => {
      res.status(200).send({message: 'Finished fetching'});
    })
    .catch((err) => {
      console.log(err);
      res.status(400).send(err);
    });
}

/** Adds a box and updates the client via socket */
function addBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  const parentBoxId = req.body.parentBoxId != 'NONE' ? req.body.parentBoxId : null;
  Box.findOne({_id: parentBoxId})
    .then((parentBox) => {
      const newBoxName = parentBox ? parentBox.name + '/' + req.body.boxName : req.body.boxName;
      return emailConnector.addBox(newBoxName);
    })
    .then(() => {
      return syncIMAPBoxes(user, emailConnector);
    })
    .then(() => {
      res.status(200).send({message: 'Box added'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Deletes a box and updates the client via Socket */
function delBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId}).populate('parent')
    .then(boxToDelete => {
      return [boxToDelete, emailConnector.delBox(boxToDelete.name)]
    })
    .spread(boxToDelete => {
      return [boxToDelete, Box.cascadeDeleteBoxById(boxToDelete._id, user._id, false)]
    })
    .spread((boxDeleted, msg) => {
      Socket.deleteBox(user._id, boxDeleted);
    })
    .then(() => {
      res.status(200).send({message: 'Box deleted'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

function renameBox(req, res) {
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  Box.findOne({_id: req.body.oldBoxId}).populate('parent')
    .then(oldBox => {
      const shortName = req.body.newBoxShortName;
      const newBoxName = oldBox.parent != null ? oldBox.parent.name + '/' + shortName : shortName;
      return [oldBox, emailConnector.renameBox(oldBox.name, newBoxName)]
    })
    .spread((oldBox, newBoxName) => {
      return Box.rename(oldBox._id, newBoxName);
    })
    .then(box => {
      Socket.updateBox(user._id, box);
      res.status(200).send({message: `Renamed box: ${box.name}`});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

function append(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({name: req.body.box, user: req.user})
    .then(box => {
      return [box, emailConnector.append(req.body.box, req.body.args, req.body.to, req.body.from, req.body.subject, req.body.msgData)]
    })
    .spread((box, msgData) => {
      return [msgData, emailConnector.fetchBoxes(storeEmail, [box])]
    })
    .spread((msgData, result) => {
      res.status(200).send({msgData: msgData});
    })
    .catch((err) => {
      console.log(err);
      res.status(400).send(err);
    });
}

function move(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Email.findOne({_id: req.body.emailId}).populate('box')
    .then(email => {
      return [email, Box.findOne({_id: req.body.newBoxId, user: req.user})]
    })
    .spread((email, destBox) => {
      const srcBox = email.box;
      return [srcBox, destBox, emailConnector.move(email.uid, srcBox.name, destBox.name)]
    })
    .spread((srcBox, destBox, msgId) => {
      return emailConnector.fetchBoxes(storeEmail, [srcBox, destBox])
    })
    .then((messages) => {
      res.status(200).send({messages: messages});
    })
    .catch(err => {
      console.log(err);
      res.status(400).send(err);
    });
}

function addFlags(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId, user: req.user})
    .then(box => {
      return [box, emailConnector.addFlags(req.body.msgId, req.body.flags, box.name)]
    })
    .spread((box, msgId) => {
      return Email.findOne({uid: req.body.msgId, box: box})
    })
    .then((email) => {
      email.flags = email.flags.concat(req.body.flags);
      return email.save();
    })
    .then(() => {
      res.status(200).send({message: 'Successfully added Flags'});
    })
    .catch(err => {
      res.status(400).send(err);
    });
}

function delFlags(req, res) {
  const emailConnector = req.user.createIMAPConnector();
  Box.findOne({_id: req.body.boxId, user: req.user})
    .then(box => {
      return [box, emailConnector.delFlags(req.body.msgId, req.body.flags, box.name)]
    })
    .spread((box, msgId) => {
      return Email.findOne({uid: req.body.msgId, box: box})
    })
    .then((email) => {
      req.body.flags.forEach((f) => {
        const index = email.flags.indexOf(f);
        if (index > -1)
          email.flags.splice(index, 1);
      });
      return email.save()
    })
    .then(() => {
      res.status(200).send({message: 'Successfully deleted Flags'});
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Returns one single mail with all details */
function getSingleMail(req, res) {
  Email.findOne({_id: req.params.id}).lean()
    .then((mail) => {
      return (mail && (req.user.trello || req.user.sociocortex)) ? new Analyzer(mail, req.user).getEmailTasks() : mail;
    })
    .then(email => {
      res.status(200).send(email);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
}

/** Stores an email in the database and
 *  pushs upates via socket to the client */
function storeEmail(mail) {
  return new Promise((resolve, reject) => {
    Email.updateAndGetOldAndUpdated(mail)
      .spread((emailOld, boxOld, emailUpdated, boxUpdated) => {
        // TODO new box numbers do not work properly
        console.log('inside storeEmail...');
        console.log(JSON.stringify(boxOld));
        console.log(JSON.stringify(boxUpdated));
        Socket.pushEmailUpdateToClient(emailOld, boxOld, emailUpdated, boxUpdated);
        resolve(emailUpdated);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/** Search emails either for box or user serach */
function searchMails(req, res) {

  const options = {
    boxId: req.query.boxId,
    sort: req.query.sort, // ASC or DESC
    search: req.query.search,
    lastEmailDate: new Date(req.query.lastEmailDate)
  };

  Email.search(req.user._id, options)
    .then(emails => {
      res.status(200).send(emails);
    })
    .catch(err => {
      res.status(400).send(err);
    });
}

/** Returns the current boxes from the database */
function getBoxes(req, res) {
  Box.getBoxesByUserId(req.user._id)
    .then(boxes => {
      res.status(200).send(boxes);
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

/** Syncronizes the boxes of the user via IMAP */
function syncIMAPBoxes(user, emailConnector) {
  return new Promise((resolve, reject) => {
    emailConnector
      .getBoxes(false)
      .then(boxes => {
        console.log(boxes);
        return Promise.each(boxes, (box) => {
          return new Promise((resolve, reject) => {
            Box.updateAndGetOldAndUpdated(box, user)
              .spread((oldBox, updatedBox) => {
                Socket.pushBoxUpdateToClient(oldBox, updatedBox);
                resolve()
              })
              .catch(err => {
                reject(err);
              });
          });
        });
      })
      .then(() => {
        return Box.deleteUpdatedAtOlderThan(user._id, user.lastSync);
      })
      .then(delBoxes => {
        delBoxes.forEach(box => {
          Socket.pushBoxUpdateToClient(box, null);
        });
        resolve();
      })
      .catch(err => {
        reject(err);
      });
  })
}

/** Syncronizes the emails of the user via IMAP */
function syncIMAPMails(user, emailConnector) {
  const before = new Date();
  console.log('--> syncIMAPMails');
  return new Promise((resolve, reject) => {
    Box.find({user: user})
      .then(boxes => {
        return emailConnector.fetchBoxes(storeEmail, boxes)
      })
      .then(() => {
        console.log('Time for fetching: ', new Date() - before);
        resolve();
      })
      .catch(err => {
        reject(err)
      });
  })
}

/** Syncronizes the boxes and emails of the user via IMAP */
function syncIMAP(req, res) {
  console.log('-> syncIMAP');
  const user = req.user;
  const emailConnector = user.createIMAPConnector();
  user.lastSync = new Date();
  user.save()
    .then(() => {
      return syncIMAPBoxes(user, emailConnector)
    })
    .then(() => {
      return syncIMAPMails(user, emailConnector);
    })
    .then(() => {
      console.log('all synced!');
      res.status(200).send({message: 'Finished syncing'});
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

/** Creates autocomplete suggestions for email addresses */
function autocomplete(req, res) {
  Email.autocomplete(req.user._id)
    .then(suggestions => {
      res.status(200).send(suggestions);
    })
    .catch(err => {
      res.status(500).send(err);
    });
}

export default {
  addBox,
  delBox,
  renameBox,
  append,
  move,
  sendEmail,
  addFlags,
  delFlags,
  searchMails,
  getSingleMail,
  getBoxes,
  syncIMAP
};
<|endoftext|>