<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

// Bracket extension. Permite que o desenvolvedor crie atalhos para os comandos de console.
define(function (require, exports, module) {
    "use strict";

    var AppInit             = brackets.getModule('utils/AppInit'),
        ExtensionUtils      = brackets.getModule('utils/ExtensionUtils'),
        NodeConnection      = brackets.getModule('utils/NodeConnection'),
        NodeDomain          = brackets.getModule('utils/NodeDomain'),
        CommandManager      = brackets.getModule('command/CommandManager'),
        KeyBindingManager   = brackets.getModule('command/KeyBindingManager'),
        Menus               = brackets.getModule('command/Menus'),
        QuickOpen           = brackets.getModule('search/QuickOpen'),
        ProjectManager      = brackets.getModule('project/ProjectManager'),
        StatusBar           = brackets.getModule('widgets/StatusBar'),
        FileSystem          = brackets.getModule('filesystem/FileSystem'),
        FileUtils           = brackets.getModule('file/FileUtils'),
        PanelManager        = brackets.getModule('view/PanelManager'),
        Resizer             = brackets.getModule('utils/Resizer'),
        DocumentManager     = brackets.getModule('document/DocumentManager'),
        CodeHintManager     = brackets.getModule('editor/CodeHintManager');

    var providersCache = [];

    var BASE_PROVIDERS = {
        'JSONProvider': true,
        'CasperJSProvider': true
    };

    /**
     * Inicia os providers registrados no arquivo cch.json.
     *
     * @provider array provider Array com os providers configurados no arquivo cch.json.
     */
    function initProviders(providers) {
        var rootPath   = ProjectManager.getProjectRoot().fullPath;

        // Nome dos providers.
        var provsNames = providers.map(function(elem) {
            var name = elem.name;

            if (!BASE_PROVIDERS[name]) {
                name = FileSystem.getFileForPath(rootPath + name + '.js').fullPath;

                return name;
            }

            return elem.name;
        });

        // Carregando, via require, os providers e criando uma instancia de execucao de cada.
        require(provsNames, function() {
            Array.prototype.slice.call(arguments, 0).forEach(function(provider, i) {
                console.log(i, providers[i]);

                try {
                    providersCache.push(new provider.create(providers[i].opts || {}));
                } catch (err) {
                    console.log('Err loading provider: ', err);
                }
            });
        });
    }

    /**
     * Carrega as configuracoes a partir do arquivo cch.json.
     *
     * @param string rawText Conteudo do arquivo cch.json.
     */
    function loadConfigs(rawText) {
        var config = { providers: [] };

        try {
            config = JSON.parse(rawText);

            initProviders(config.providers || []);
        } catch (err) {
            console.error('Err on load config: ' + err);
        }
    }

    /**
     * Realiza a leitura do arquivo de configuracao cch.json e inicia o processo de configuracao.
     */
    function readConfigFile() {
        var rootPath   = ProjectManager.getProjectRoot().fullPath,
            cmdCfgFile = FileSystem.getFileForPath(rootPath + 'cch.json');

        FileUtils.readAsText(cmdCfgFile).done(function (rawText) {
            loadConfigs(rawText);
        });
    }

    $(ProjectManager).on('projectOpen projectRefresh', readConfigFile);
    $(DocumentManager).on('documentSaved', function(evt, doc) {
        if (doc.file.name == 'cmdrunner.json') {
            readConfigFile();
        }
    });

    AppInit.appReady(function () {
        CodeHintManager.registerHintProvider({
            hasHints: function(editor, implicitChar) {

                this.editor = editor;

                var cursor = editor.getCursorPos();

                var lineBeginning = { line: cursor.line, ch: 0 };

                var line = editor.document.getRange(lineBeginning, cursor);

                this.line = line;

                this.providers = providersCache.filter(function(prov) {
                    return prov.hasHints && prov.hasHints(line, implicitChar);
                });

                return this.providers.length > 0;
            },

            getHints: function(implicitChar) {
                if (this.providers.length == 0) {
                    return {};
                }

                var hints = [];

                var cursor = this.editor.getCursorPos();

                var lineBeginning = { line: cursor.line, ch: 0 };

                var line = this.editor.document.getRange(lineBeginning, cursor);

                this.providers.forEach(function(prov) {
                    var provHints = prov.getHints(line, implicitChar);

                    hints.concat(provHints.map(function(hint) {
                        var jqObject = $('' + (hint.label || '') + '');

                        jqObject.data('hint', hint);

                        hints.push(jqObject);
                    }));
                });

                hints.sort(function(jq1, jq2) {
                    var elem1 = jq1.data('hint'),
                        elem2 = jq2.data('hint');

                    return elem1.text > elem2.text ? 1 : elem1.text < elem2.text ? -1 : 0;
                });

                console.log(hints);

                return {
                    hints: hints,
                    match: null,
                    selectInicial: true,
                    handleWideResults: true
                };
            },

            insertHint: function(jqHint) {
                if (!this.editor) {
                    return;
                }

                var cursor = this.editor.getCursorPos();

                var hint = jqHint.data('hint') || {};

                if (hint.text) {
                    this.editor.document.replaceRange(hint.text, cursor);
                }
            }

        }, ["all"], 0);
    });
});
<commit_msg>Ajuste de prioridade<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window */

// Bracket extension. Permite que o desenvolvedor crie atalhos para os comandos de console.
define(function (require, exports, module) {
    "use strict";

    var AppInit             = brackets.getModule('utils/AppInit'),
        ExtensionUtils      = brackets.getModule('utils/ExtensionUtils'),
        NodeConnection      = brackets.getModule('utils/NodeConnection'),
        NodeDomain          = brackets.getModule('utils/NodeDomain'),
        CommandManager      = brackets.getModule('command/CommandManager'),
        KeyBindingManager   = brackets.getModule('command/KeyBindingManager'),
        Menus               = brackets.getModule('command/Menus'),
        QuickOpen           = brackets.getModule('search/QuickOpen'),
        ProjectManager      = brackets.getModule('project/ProjectManager'),
        StatusBar           = brackets.getModule('widgets/StatusBar'),
        FileSystem          = brackets.getModule('filesystem/FileSystem'),
        FileUtils           = brackets.getModule('file/FileUtils'),
        PanelManager        = brackets.getModule('view/PanelManager'),
        Resizer             = brackets.getModule('utils/Resizer'),
        DocumentManager     = brackets.getModule('document/DocumentManager'),
        CodeHintManager     = brackets.getModule('editor/CodeHintManager');

    var providersCache = [];

    var BASE_PROVIDERS = {
        'JSONProvider': true,
        'CasperJSProvider': true
    };

    /**
     * Inicia os providers registrados no arquivo cch.json.
     *
     * @provider array provider Array com os providers configurados no arquivo cch.json.
     */
    function initProviders(providers) {
        var rootPath   = ProjectManager.getProjectRoot().fullPath;

        // Nome dos providers.
        var provsNames = providers.map(function(elem) {
            var name = elem.name;

            if (!BASE_PROVIDERS[name]) {
                name = FileSystem.getFileForPath(rootPath + name + '.js').fullPath;

                return name;
            }

            return elem.name;
        });

        // Carregando, via require, os providers e criando uma instancia de execucao de cada.
        require(provsNames, function() {
            Array.prototype.slice.call(arguments, 0).forEach(function(provider, i) {
                console.log(i, providers[i]);

                try {
                    providersCache.push(new provider.create(providers[i].opts || {}));
                } catch (err) {
                    console.log('Err loading provider: ', err);
                }
            });
        });
    }

    /**
     * Carrega as configuracoes a partir do arquivo cch.json.
     *
     * @param string rawText Conteudo do arquivo cch.json.
     */
    function loadConfigs(rawText) {
        var config = { providers: [] };

        try {
            config = JSON.parse(rawText);

            initProviders(config.providers || []);
        } catch (err) {
            console.error('Err on load config: ' + err);
        }
    }

    /**
     * Realiza a leitura do arquivo de configuracao cch.json e inicia o processo de configuracao.
     */
    function readConfigFile() {
        var rootPath   = ProjectManager.getProjectRoot().fullPath,
            cmdCfgFile = FileSystem.getFileForPath(rootPath + 'cch.json');

        FileUtils.readAsText(cmdCfgFile).done(function (rawText) {
            loadConfigs(rawText);
        });
    }

    $(ProjectManager).on('projectOpen projectRefresh', readConfigFile);
    $(DocumentManager).on('documentSaved', function(evt, doc) {
        if (doc.file.name == 'cmdrunner.json') {
            readConfigFile();
        }
    });

    AppInit.appReady(function () {
        CodeHintManager.registerHintProvider({
            hasHints: function(editor, implicitChar) {

                this.editor = editor;

                var cursor = editor.getCursorPos();

                var lineBeginning = { line: cursor.line, ch: 0 };

                var line = editor.document.getRange(lineBeginning, cursor);

                this.line = line;

                this.providers = providersCache.filter(function(prov) {
                    return prov.hasHints && prov.hasHints(line, implicitChar);
                });

                return this.providers.length > 0;
            },

            getHints: function(implicitChar) {
                if (this.providers.length == 0) {
                    return {};
                }

                var hints = [];

                var cursor = this.editor.getCursorPos();

                var lineBeginning = { line: cursor.line, ch: 0 };

                var line = this.editor.document.getRange(lineBeginning, cursor);

                this.providers.forEach(function(prov) {
                    var provHints = prov.getHints(line, implicitChar);

                    hints.concat(provHints.map(function(hint) {
                        var jqObject = $('' + (hint.label || '') + '');

                        jqObject.data('hint', hint);

                        hints.push(jqObject);
                    }));
                });

                hints.sort(function(jq1, jq2) {
                    var elem1 = jq1.data('hint'),
                        elem2 = jq2.data('hint');

                    return elem1.text > elem2.text ? 1 : elem1.text < elem2.text ? -1 : 0;
                });

                console.log(hints);

                return {
                    hints: hints,
                    match: null,
                    selectInicial: true,
                    handleWideResults: true
                };
            },

            insertHint: function(jqHint) {
                if (!this.editor) {
                    return;
                }

                var cursor = this.editor.getCursorPos();

                var hint = jqHint.data('hint') || {};

                if (hint.text) {
                    this.editor.document.replaceRange(hint.text, cursor);
                }
            }

        }, ["all"], 2);
    });
});
<|endoftext|>


<commit_before>import React from 'react'
import dynamic from 'next/dynamic'
import * as hljs from 'highlight.js'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'
import SpinnerWrapper from './SpinnerWrapper'

import WindowControls from './WindowControls'
import {
  COLORS,
  LANGUAGE_MODE_HASH,
  LANGUAGE_NAME_HASH,
  LANGUAGE_MIME_HASH,
  DEFAULT_SETTINGS,
  THEMES_HASH
} from '../lib/constants'

const Watermark = dynamic(() => import('./svg/Watermark'), {
  loading: () => null
})

function searchLanguage(l) {
  const config = LANGUAGE_NAME_HASH[l] || LANGUAGE_MODE_HASH[l] || LANGUAGE_MIME_HASH[l]

  if (config) {
    return config.mime || config.mode
  }
}

class Carbon extends React.PureComponent {
  static defaultProps = {
    onChange: () => {}
  }

  handleLanguageChange = debounce(
    (newCode, language) => {
      if (language === 'auto') {
        // try to set the language
        const detectedLanguage = hljs.highlightAuto(newCode).language
        const languageMode = searchLanguage(detectedLanguage)

        if (languageMode) {
          return languageMode
        }
      }

      const languageMode = searchLanguage(language)

      if (languageMode) {
        return languageMode
      }

      return language
    },
    ms('300ms'),
    {
      leading: true,
      trailing: true
    }
  )

  onBeforeChange = (editor, meta, code) => {
    if (!this.props.readOnly) {
      this.props.onChange(code)
    }
  }

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }

    const languageMode = this.handleLanguageChange(
      this.props.children,
      config.language && config.language.toLowerCase()
    )

    const options = {
      lineNumbers: config.lineNumbers,
      mode: languageMode || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      },
      // negative values removes the cursor, undefined means default (530)
      cursorBlinkRate: this.props.readOnly ? -1 : undefined,
      // needs to be able to refresh every 16ms to hit 60 frames / second
      pollInterval: 16
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const themeConfig = THEMES_HASH[config.theme]

    const content = (

        {config.windowControls ? (
          <WindowControls
            theme={config.windowTheme}
            code={this.props.children}
            copyable={this.props.copyable}
            light={themeConfig.light}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark light={themeConfig.light} />}

    )

    return (

          <SpinnerWrapper loading={this.props.loading}>{content}</SpinnerWrapper>

    )
  }
}

export default React.forwardRef((props, ref) => <Carbon {...props} innerRef={ref} />)
<commit_msg>improve watermark contrast<commit_after>import React from 'react'
import dynamic from 'next/dynamic'
import * as hljs from 'highlight.js'
import debounce from 'lodash.debounce'
import ms from 'ms'
import { Controlled as CodeMirror } from 'react-codemirror2'
import SpinnerWrapper from './SpinnerWrapper'

import WindowControls from './WindowControls'
import {
  COLORS,
  LANGUAGE_MODE_HASH,
  LANGUAGE_NAME_HASH,
  LANGUAGE_MIME_HASH,
  DEFAULT_SETTINGS,
  THEMES_HASH
} from '../lib/constants'

const Watermark = dynamic(() => import('./svg/Watermark'), {
  loading: () => null
})

function searchLanguage(l) {
  const config = LANGUAGE_NAME_HASH[l] || LANGUAGE_MODE_HASH[l] || LANGUAGE_MIME_HASH[l]

  if (config) {
    return config.mime || config.mode
  }
}

class Carbon extends React.PureComponent {
  static defaultProps = {
    onChange: () => {}
  }

  handleLanguageChange = debounce(
    (newCode, language) => {
      if (language === 'auto') {
        // try to set the language
        const detectedLanguage = hljs.highlightAuto(newCode).language
        const languageMode = searchLanguage(detectedLanguage)

        if (languageMode) {
          return languageMode
        }
      }

      const languageMode = searchLanguage(language)

      if (languageMode) {
        return languageMode
      }

      return language
    },
    ms('300ms'),
    {
      leading: true,
      trailing: true
    }
  )

  onBeforeChange = (editor, meta, code) => {
    if (!this.props.readOnly) {
      this.props.onChange(code)
    }
  }

  render() {
    const config = { ...DEFAULT_SETTINGS, ...this.props.config }

    const languageMode = this.handleLanguageChange(
      this.props.children,
      config.language && config.language.toLowerCase()
    )

    const options = {
      lineNumbers: config.lineNumbers,
      mode: languageMode || 'plaintext',
      theme: config.theme,
      scrollBarStyle: null,
      viewportMargin: Infinity,
      lineWrapping: true,
      extraKeys: {
        'Shift-Tab': 'indentLess'
      },
      // negative values removes the cursor, undefined means default (530)
      cursorBlinkRate: this.props.readOnly ? -1 : undefined,
      // needs to be able to refresh every 16ms to hit 60 frames / second
      pollInterval: 16
    }
    const backgroundImage =
      (this.props.config.backgroundImage && this.props.config.backgroundImageSelection) ||
      this.props.config.backgroundImage

    const themeConfig = THEMES_HASH[config.theme]

    const content = (

        {config.windowControls ? (
          <WindowControls
            theme={config.windowTheme}
            code={this.props.children}
            copyable={this.props.copyable}
            light={themeConfig.light}
          />
        ) : null}
        <CodeMirror
          className={`CodeMirror__container window-theme__${config.windowTheme}`}
          onBeforeChange={this.onBeforeChange}
          value={this.props.children}
          options={options}
        />
        {config.watermark && <Watermark light={themeConfig.light} />}

    )

    return (

          <SpinnerWrapper loading={this.props.loading}>{content}</SpinnerWrapper>

    )
  }
}

export default React.forwardRef((props, ref) => <Carbon {...props} innerRef={ref} />)
<|endoftext|>


<commit_before><commit_msg>add back new<commit_after><|endoftext|>


<commit_before>const Promise = require('bluebird');
const Discord = require('discord.js');
const client = new Discord.Client();

const util = require('./util');
const cmd = require('./commands');
const scv = require('./modules/scv');
const defaults = require('./modules/defaults');

const config = require('./config.json');
const cmdData = require('./data/commands.json');

// If the command line argument 'test' is given, log in to the test account
const test = process.argv[2] === 'test',
    loginToken = test ? config.test_token : config.token;

// Global variables
let variablesLoaded = {},
    allPrefixes = {},
    allCustomAliases = {};

/**
 * A function to deal with retrieving channel variables. If the variable is undefined, this function returns its
 * default value.
 *
 * @param channelID The current channel ID.
 * @param variable The name of the channel variable to be fetched.
 * @returns {Promise} A promise that resolves with the value to be assigned to this variable in the current context.
 */
const getVariableWithFallback = (channelID, variable) => {
    // I HATE THIS ASYNC HYPE GARBAGE
    // WHY DOES EVERYTHING IN THIS LANGUAGE HAVE TO BE ASYNC
    // THE SIMPLEST THINGS ABSOLUTELY MUST BE ASYNC
    // BECAUSE IF THEY'RE NOT THEN IT WOULD ACTUALLY BE CONVENIENT AND WE CAN'T HAVE THAT CAN WE
    // ASYNC IS USEFUL BUT NOT FOR LITERALLY EVERY LITTLE THING
    // AND NOW I NEED 10 LAYERS OF PROMISES FOR EVERYTHING I DO TO DEAL WITH ASYNC RACE CONDITIONS
    // REEEEEEEEEEEEEEEEEEEEEEE
    return new Promise((resolve, reject) => {
        scv.get(channelID, variable).then(val => {
            if (val) {
                resolve(val);
            } else {
                resolve(defaults.get(variable));
            }
        }).catch(err => {
            reject(err);
        });
    });
};

/**
 * Updates all channel variables.
 * TODO: fix this so it doesn't just update prefix but can iterate over a list of variables to update. Maybe use Promise.all?
 *
 * @param channelID The current channel ID.
 * @returns {Promise} A promise that resolves when the variables have been updated.
 */
const updateVariables = (channelID) => {
    return new Promise((resolve, reject) => {
        getVariableWithFallback(channelID, 'prefix').then(val => {
            allPrefixes[channelID + ''] = val;
            resolve();
        }).catch(err => {
            reject(err);
        });
    });
};

/**
 * Checks if the string is an alias for some command. This checks the default aliases in commands.json, and the custom
 * channel aliases from SCV.
 * TODO: make this return a special string in case of no applicable command being found, for consistency
 *
 * @param channelID The current channel ID.
 * @param keyword The string to be cross-checked.
 * @returns {*} The relevant command name if the string is an alias for some command, or false if not.
 */
const checkForAlias = (channelID, keyword) => {
    const cmdNames = Object.keys(cmdData);

    let aliasFound = false,
        out = '';

    // first, check the default aliases
    for (let i in cmdNames) {
        let cmdName = cmdNames[i],
            cmdObj = cmdData[cmdName],
            aliases = cmdObj.aliases;
        if (Array.isArray(aliases)) {
            if (aliases.indexOf(keyword) !== -1) {
                aliasFound = true;
                out = cmdName;
            }
        }
    }

    if(!aliasFound) {
        // haven't found any matching default aliases, so now check SCV
        const customAliases = allCustomAliases[channelID];

        if(typeof customAliases === 'undefined') {
            scv.get(channelID, 'aliases').then(val => {
                if(!val) {
                    // no aliases defined for this channel
                    allCustomAliases[channelID] = {};
                } else {
                    // aliases are defined, we just haven't fetched them yet
                    // TODO: implement fetching using the Datum class
                }
            });
        }
    }

    if (!aliasFound) {
        return false;
    } else {
        return out;
    }
};

client.once('ready', () => {
    console.log('Bot is online!');
    console.log(`Ready: serving ${client.guilds.size} guilds, in ${client.channels.size} channels, for ${client.users.size} users.`);
});

/*
 * This triggers on every message. Use this to listen to commands and master commands.
 */
client.on('message', msg => {
    const channelID = msg.channel.id;
    //scv.listTable();
    // scv.get(channelID, 'aliases').then(val => {
    //     //console.log(val);
    // });

    /*
     * Update all variables if we're just starting up; if not then just resolve.
     */
    const varRequest = new Promise((resolve, reject) => {
        if (!variablesLoaded[channelID]) {
            updateVariables(channelID).then(() => {
                variablesLoaded[channelID] = true;
                resolve();
            });
        } else {
            resolve();
        }
    });

    // once we've updated our variables (if we need to), try to parse a command
    varRequest.then(() => {
        // TODO: find some way to update this after setprefix
        let prefix = allPrefixes[channelID + ''];

        if (typeof prefix === 'undefined') {
            let p = defaults.get('prefix');
            allPrefixes[channelID + ''] = p;
            prefix = p;
        }

        switch (msg.content) {
            /*
             * Master commands. These commands do not depend on the prefix.
             */
            case 'bloobotprefix':
                // Master command that lists the prefix. This command must be independent of
                // the current prefix and therefore cannot be handled by regular command logic.
                msg.channel.send(`**Command prefix currently in use**: ${prefix}`);
                break;

            case 'resetprefix':
                // Master command that resets the prefix to ~.

                // admins only (and me)
                if (util.sentByAdminOrMe(msg)) {
                    const sendingFunction = (text) => msg.channel.send.call(msg.channel, text);
                    cmd.setPrefix(client, msg, sendingFunction, '~').then(() => {
                        return updateVariables(channelID);
                    }).then(() => {
                        // done
                        // TODO: maybe change this so that execution is paused until promise is complete
                    });
                }
                break;
            default:
                if (msg.author === client.user) {
                    // make sure the bot doesn't respond to its own messages

                } else if (!msg.content.startsWith(prefix)) {
                    // message doesn't start with the prefix so do nothing

                } else {
                    console.log(msg.content); // for debugging and just making sure it works
                    let parsedCmd = cmdParse(msg, prefix), // parse out the command and args
                        output;
                    if (parsedCmd) {
                        cmdExe(msg, parsedCmd.cmdName, parsedCmd.cmdArgs, prefix)
                            .then(out => {
                                output = out;
                                console.log(parsedCmd); // same as above

                                // if we need to output something that was returned from the command, then do so
                                if (output.length !== 0) {
                                    // send the message
                                    if (!util.safeSendMsg(msg.channel, output.join('\n'), '```')) {
                                        msg.channel.send(`Outbound message length greater than ${util.MY_CHAR_LIMIT} character limit.`);
                                    }
                                }
                            })
                            .catch(err => {
                                // an error was caught by cmdExe (most likely a permissions error)
                                util.sendErrorMessage(msg.channel, err);
                            });
                    } else {
                        // do nothing? idk
                    }
                }
                break;
        }
    });
});

// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
    // Send the message to a designated channel on a server:
    const channel = member.guild.channels.find('name', 'member-log');
    // Do nothing if the channel wasn't found on this server
    if (!channel) return;
    // Send the message, mentioning the member
    channel.send(`Welcome to the server, ${member}`);
});

client.login(loginToken);

/**
 * Executes a command using the function reference found in the command documentation file. This function is supposed to
 * be called after cmdParse, and take the command name and command args from its output.
 *
 * @param msg The message that requested the command to be executed.
 * @param cmdName The name of the command specified.
 * @param args The arguments given to the command.
 * @param prefix The command prefix currently in use.
 * @returns {Promise} A promise that resolves with an array of the text to be messaged inside ``, if any, line by line.
 */
function cmdExe(msg, cmdName, args, prefix) {
    const currCmd = cmdData[cmdName],
        // note: paramsCount DOES include default parameters!!!
        paramsCount = typeof currCmd.params === 'undefined' ? 0 : Object.keys(currCmd.params).length,
        defaultsCount = typeof currCmd.defaults === 'undefined' ? 0 : currCmd.defaults,
        argsCount = args.length,
        channelID = msg.channel.id;

    let outText = [];

    return new Promise((resolve, reject) => {
        new Promise((res, rej) => {
            if (args.length === 0 && paramsCount !== 0) {
                outText = cmd.descString(prefix, cmdName);
                res();
            } else {
                // Check for a permissions error, and if positive reject the promise:
                if (currCmd.permissions === 'admin' && !util.sentByAdminOrMe(msg)) { // check for privileges if the command requires them
                    rej(`The command "${cmdName}" requires administrator privileges.`);
                } else if (currCmd.permissions === 'me' && !util.sentByMe(msg)) { // check for privileges if the command requires them
                    rej(`The command "${cmdName}" can only be run by the bot admin.`);
                } else if (args.length < paramsCount - defaultsCount) { // check if the number of args is correct
                    rej(`The command "${cmdName}" requires at least ${paramsCount - defaultsCount} arguments; received ${args.length}.`);
                } else {
                    const func = cmd[currCmd.fn],
                        fnParams = currCmd.params,
                        fullArgs = args.slice(0),
                        sendingFunction = (text) => msg.channel.send.call(msg.channel, text);
                    // for some reason this is necessary, instead of just msg.channel.send :(

                    // type checking:
                    let typeMismatch = false,
                        typeMismatchDesc = {}; // initialising so WebStorm doesn't complain

                    if (typeof fnParams !== 'undefined') {
                        let i = 0, // TODO: this seems to work, but just in case, rewrite the API to not rely on key ordering
                            paramNames = Object.keys(fnParams);

                        // using every instead of forEach lets me break out of the loop when a mismatch is detected
                        paramNames.every(key => {
                            if (i === argsCount) {
                                // If a default argument has not been provided, we don't need to util.TypeCheck. That means,
                                // we need to break out of the loop as soon as we have processed all provided arguments.
                                return false;
                            }
                            const value = fnParams[key].type,
                                typesArray = Array.isArray(value) ? value : [value],
                                argument = fullArgs[i++],
                                t = typesArray.filter(elem => util.TypeCheck[elem](argument));

                            // There is a type mismatch if and only if the argument input does not match any of the
                            // types specified for it. In this case, the filter above will trim all elements from the
                            // array, and return [].
                            typeMismatch = t.length === 0;

                            if (typeMismatch) {
                                typeMismatchDesc = {
                                    argument: argument,
                                    parameter: key,
                                    expected: typesArray
                                };
                                return false;
                            } else {
                                return true;
                            }
                        });
                    }

                    if (!typeMismatch) {
                        // input passed type checking
                        fullArgs.unshift(sendingFunction);
                        fullArgs.unshift(msg);
                        fullArgs.unshift(client);

                        // call the command function:
                        const moreText = func.apply(this, fullArgs);

                        // process result
                        if (typeof moreText === 'string') {
                            outText.push(moreText);
                            res();
                        } else if (Array.isArray(moreText)) {
                            outText = outText.concat(moreText);
                            res();
                        } else if (moreText instanceof Promise) {
                            moreText.then((out) => {
                                if (typeof out === 'string') {
                                    outText.push(out);
                                } else if (Array.isArray(out)) {
                                    outText = outText.concat(out);
                                }
                                res();
                            });
                        }
                    } else {
                        // input failed type checking, handle the error
                        const p = typeMismatchDesc.parameter,
                            a = typeMismatchDesc.argument,
                            expected = typeMismatchDesc.expected,
                            t = Array.isArray(expected) ? expected.join(', ') : expected;
                        msg.channel.send(`Invalid input "${a}" for parameter **${p}** (${t} expected).`);
                    }
                }
            }
        }).then(() => {
            // command execution successful
            // update global variables if required, then return
            new Promise((res, rej) => {
                if (currCmd.update) {
                    console.log('updating for ' + channelID);
                    updateVariables(channelID).then(() => {
                        res();
                    }).catch(() => {
                        rej();
                    });
                } else {
                    res();
                }
            }).then(() => {
                resolve(outText);
            });
        }).catch(err => {
            reject(err);
        });
    });
}

/**
 * Parses a command from a message into the command name and a list of arguments.
 *
 * @param msg The message that requested the command to be executed.
 * @param prefix The command prefix currently in use.
 * @returns {*} An object containing the command name and command arguments, to be passed to cmdExe, or false if no such
 * command exists.
 */
function cmdParse(msg, prefix) {
    const cmdString = msg.content,
        cmdText = cmdString.slice(prefix.length), // take out the prefix
        firstSpace = cmdText.indexOf(' ');

    let commandName,
        commandArgs;

    if (firstSpace !== -1) {
        commandName = cmdText.slice(0, firstSpace).toLowerCase();  // get the command name

        if (typeof cmdData[commandName] === 'undefined') {
            const aliasCommand = checkForAlias(msg.channel.id, commandName);
            if (aliasCommand) {
                commandName = aliasCommand;
            } else {
                msg.channel.send('**Undefined command name** "' + commandName + '"');
                return false;
            }
        }

        // parse out the command args
        commandArgs = cmdText.slice(firstSpace).match(/"(?:\\"|\\\\|[^"])*"|\S+/g)
            .map((elem) => {
                let out;
                // check if it's in quotes
                if (elem.charAt(0) === '"' && elem.charAt(elem.length - 1) === '"') {
                    out = elem.slice(1, elem.length - 1);
                } else {
                    out = elem;
                }
                // convert to number if numerical
                return isNaN(out) ? out : +out;
            });

        // if too many args have been received:
        let paramsCount = Object.keys(cmdData[commandName].params).length;

        if (commandArgs.length > paramsCount) {
            // too many args received, so condense the remainder into one argument
            const remainingArgs = commandArgs.slice(paramsCount - 1, commandArgs.length);

            commandArgs = commandArgs.slice(0, paramsCount - 1);
            commandArgs.push(remainingArgs.join(' '));
        }
    } else {
        commandName = cmdText.toLowerCase();
        commandArgs = [];

        if (typeof cmdData[commandName] === 'undefined') {
            const aliasCommand = checkForAlias(msg.channel.id, commandName);
            console.log(commandName, aliasCommand);
            if (aliasCommand) {
                commandName = aliasCommand;
            } else {
                msg.channel.send('**Undefined command name** "' + commandName + '"');
                return false;
            }
        }
    }

    return {
        'cmdName': commandName,
        'cmdArgs': commandArgs
    };
}<commit_msg>Rewrite cmdExe to use async/await<commit_after>const Promise = require('bluebird');
const Discord = require('discord.js');
const client = new Discord.Client();

const util = require('./util');
const cmd = require('./commands');
const scv = require('./modules/scv');
const defaults = require('./modules/defaults');

const config = require('./config.json');
const cmdData = require('./data/commands.json');

// If the command line argument 'test' is given, log in to the test account
const test = process.argv[2] === 'test',
    loginToken = test ? config.test_token : config.token;

// Global variables
let variablesLoaded = {},
    allPrefixes = {},
    allCustomAliases = {};

/**
 * A function to deal with retrieving channel variables. If the variable is undefined, this function returns its
 * default value.
 *
 * @param channelID The current channel ID.
 * @param variable The name of the channel variable to be fetched.
 * @returns {Promise} A promise that resolves with the value to be assigned to this variable in the current context.
 */
const getVariableWithFallback = (channelID, variable) => {
    // I HATE THIS ASYNC HYPE GARBAGE
    // WHY DOES EVERYTHING IN THIS LANGUAGE HAVE TO BE ASYNC
    // THE SIMPLEST THINGS ABSOLUTELY MUST BE ASYNC
    // BECAUSE IF THEY'RE NOT THEN IT WOULD ACTUALLY BE CONVENIENT AND WE CAN'T HAVE THAT CAN WE
    // ASYNC IS USEFUL BUT NOT FOR LITERALLY EVERY LITTLE THING
    // AND NOW I NEED 10 LAYERS OF PROMISES FOR EVERYTHING I DO TO DEAL WITH ASYNC RACE CONDITIONS
    // REEEEEEEEEEEEEEEEEEEEEEE
    return new Promise((resolve, reject) => {
        scv.get(channelID, variable).then(val => {
            if (val) {
                resolve(val);
            } else {
                resolve(defaults.get(variable));
            }
        }).catch(err => {
            reject(err);
        });
    });
};

/**
 * Updates all channel variables.
 * TODO: fix this so it doesn't just update prefix but can iterate over a list of variables to update. Maybe use Promise.all?
 *
 * @param channelID The current channel ID.
 * @returns {Promise} A promise that resolves when the variables have been updated.
 */
const updateVariables = (channelID) => {
    return new Promise((resolve, reject) => {
        getVariableWithFallback(channelID, 'prefix').then(val => {
            allPrefixes[channelID + ''] = val;
            resolve();
        }).catch(err => {
            reject(err);
        });
    });
};

/**
 * Checks if the string is an alias for some command. This checks the default aliases in commands.json, and the custom
 * channel aliases from SCV.
 * TODO: make this return a special string in case of no applicable command being found, for consistency
 *
 * @param channelID The current channel ID.
 * @param keyword The string to be cross-checked.
 * @returns {*} The relevant command name if the string is an alias for some command, or false if not.
 */
const checkForAlias = (channelID, keyword) => {
    const cmdNames = Object.keys(cmdData);

    let aliasFound = false,
        out = '';

    // first, check the default aliases
    for (let i in cmdNames) {
        let cmdName = cmdNames[i],
            cmdObj = cmdData[cmdName],
            aliases = cmdObj.aliases;
        if (Array.isArray(aliases)) {
            if (aliases.indexOf(keyword) !== -1) {
                aliasFound = true;
                out = cmdName;
            }
        }
    }

    if(!aliasFound) {
        // haven't found any matching default aliases, so now check SCV
        const customAliases = allCustomAliases[channelID];

        if(typeof customAliases === 'undefined') {
            scv.get(channelID, 'aliases').then(val => {
                if(!val) {
                    // no aliases defined for this channel
                    allCustomAliases[channelID] = {};
                } else {
                    // aliases are defined, we just haven't fetched them yet
                    // TODO: implement fetching using the Datum class
                }
            });
        }
    }

    if (!aliasFound) {
        return false;
    } else {
        return out;
    }
};

client.once('ready', () => {
    console.log('Bot is online!');
    console.log(`Ready: serving ${client.guilds.size} guilds, in ${client.channels.size} channels, for ${client.users.size} users.`);
});

/*
 * This triggers on every message. Use this to listen to commands and master commands.
 */
client.on('message', msg => {
    const channelID = msg.channel.id;
    //scv.listTable();
    // scv.get(channelID, 'aliases').then(val => {
    //     //console.log(val);
    // });

    /*
     * Update all variables if we're just starting up; if not then just resolve.
     */
    const varRequest = new Promise((resolve, reject) => {
        if (!variablesLoaded[channelID]) {
            updateVariables(channelID).then(() => {
                variablesLoaded[channelID] = true;
                resolve();
            });
        } else {
            resolve();
        }
    });

    // once we've updated our variables (if we need to), try to parse a command
    varRequest.then(async () => { // TODO: the async annotation will get removed eventually when everything is rewritten as async/await
        // TODO: find some way to update this after setprefix
        let prefix = allPrefixes[channelID + ''];

        if (typeof prefix === 'undefined') {
            let p = defaults.get('prefix');
            allPrefixes[channelID + ''] = p;
            prefix = p;
        }

        switch (msg.content) {
            /*
             * Master commands. These commands do not depend on the prefix.
             */
            case 'bloobotprefix':
                // Master command that lists the prefix. This command must be independent of
                // the current prefix and therefore cannot be handled by regular command logic.
                msg.channel.send(`**Command prefix currently in use**: ${prefix}`);
                break;

            case 'resetprefix':
                // Master command that resets the prefix to ~.

                // admins only (and me)
                if (util.sentByAdminOrMe(msg)) {
                    const sendingFunction = (text) => msg.channel.send.call(msg.channel, text);
                    cmd.setPrefix(client, msg, sendingFunction, '~').then(() => {
                        return updateVariables(channelID);
                    }).then(() => {
                        // done
                        // TODO: maybe change this so that execution is paused until promise is complete
                    });
                }
                break;
            default:
                if (msg.author === client.user) {
                    // make sure the bot doesn't respond to its own messages

                } else if (!msg.content.startsWith(prefix)) {
                    // message doesn't start with the prefix so do nothing

                } else {
                    console.log(msg.content); // for debugging and just making sure it works
                    let parsedCmd = cmdParse(msg, prefix), // parse out the command and args
                        output;
                    if (parsedCmd) {
                        try {
                            let out = await cmdExe(msg, parsedCmd.cmdName, parsedCmd.cmdArgs, prefix);
                            output = out;
                            console.log(parsedCmd); // same as above

                            // if we need to output something that was returned from the command, then do so
                            if (output.length !== 0) {
                                // send the message
                                if (!util.safeSendMsg(msg.channel, output.join('\n'), '```')) {
                                    msg.channel.send(`Outbound message length greater than ${util.MY_CHAR_LIMIT} character limit.`);
                                }
                            }
                        } catch(err) {
                            // an error was thrown by cmdExe (most likely a permissions error)
                            console.log(err);
                            console.log(err.stack);
                            util.sendErrorMessage(msg.channel, err);
                        };
                    } else {
                        // do nothing? idk
                    }
                }
                break;
        }
    });
});

// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
    // Send the message to a designated channel on a server:
    const channel = member.guild.channels.find('name', 'member-log');
    // Do nothing if the channel wasn't found on this server
    if (!channel) return;
    // Send the message, mentioning the member
    channel.send(`Welcome to the server, ${member}`);
});

client.login(loginToken);

/**
 * Executes a command using the function reference found in the command documentation file. This function is supposed to
 * be called after cmdParse, and take the command name and command args from its output.
 *
 * @async
 * @param msg The message that requested the command to be executed.
 * @param cmdName The name of the command specified.
 * @param args The arguments given to the command.
 * @param prefix The command prefix currently in use.
 * @returns {Promise} A promise that resolves with an array of the text to be messaged inside ``, if any, line by line.
 */
async function cmdExe(msg, cmdName, args, prefix) {
    const currCmd = cmdData[cmdName],
        // note: paramsCount DOES include default parameters!!!
        paramsCount = typeof currCmd.params === 'undefined' ? 0 : Object.keys(currCmd.params).length,
        defaultsCount = typeof currCmd.defaults === 'undefined' ? 0 : currCmd.defaults,
        argsCount = args.length,
        channelID = msg.channel.id;

    let outText = [];
    console.log(args);
    if (args.length === 0 && paramsCount !== 0) {
        return outText = cmd.descString(prefix, cmdName);
    } else {
        // Check for a permissions error, and if positive reject the promise:
        if (currCmd.permissions === 'admin' && !util.sentByAdminOrMe(msg)) { // check for privileges if the command requires them
            throw new Error(`The command "${cmdName}" requires administrator privileges.`);
        } else if (currCmd.permissions === 'me' && !util.sentByMe(msg)) { // check for privileges if the command requires them
            throw new Error(`The command "${cmdName}" can only be run by the bot admin.`);
        } else if (args.length < paramsCount - defaultsCount) { // check if the number of args is correct
            throw new Error(`The command "${cmdName}" requires at least ${paramsCount - defaultsCount} arguments; received ${args.length}.`);
        } else {
            const func = cmd[currCmd.fn],
                fnParams = currCmd.params,
                fullArgs = args.slice(0),
                sendingFunction = (text) => msg.channel.send.call(msg.channel, text);
            // for some reason this is necessary, instead of just msg.channel.send :(

            // type checking:
            let typeMismatch = false,
                typeMismatchDesc = {}; // initialising so WebStorm doesn't complain

            if (typeof fnParams !== 'undefined') {
                let i = 0, // TODO: this seems to work, but just in case, rewrite the API to not rely on key ordering
                    paramNames = Object.keys(fnParams);

                // using every instead of forEach lets me break out of the loop when a mismatch is detected
                paramNames.every(key => {
                    if (i === argsCount) {
                        // If a default argument has not been provided, we don't need to util.TypeCheck. That means,
                        // we need to break out of the loop as soon as we have processed all provided arguments.
                        return false;
                    }
                    const value = fnParams[key].type,
                        typesArray = Array.isArray(value) ? value : [value],
                        argument = fullArgs[i++],
                        t = typesArray.filter(elem => util.TypeCheck[elem](argument));

                    // There is a type mismatch if and only if the argument input does not match any of the
                    // types specified for it. In this case, the filter above will trim all elements from the
                    // array, and return [].
                    typeMismatch = t.length === 0;

                    if (typeMismatch) {
                        typeMismatchDesc = {
                            argument: argument,
                            parameter: key,
                            expected: typesArray
                        };
                        return false;
                    } else {
                        return true;
                    }
                });
            }

            if (!typeMismatch) {
                // input passed type checking
                fullArgs.unshift(sendingFunction);
                fullArgs.unshift(msg);
                fullArgs.unshift(client);

                // call the command function:
                const moreText = func.apply(this, fullArgs);

                // process result
                if (typeof moreText === 'string') {
                    outText.push(moreText);
                } else if (Array.isArray(moreText)) {
                    outText = outText.concat(moreText);
                } else if (moreText instanceof Promise) {
                    let out = await moreText;
                    if (typeof out === 'string') {
                        outText.push(out);
                    } else if (Array.isArray(out)) {
                        outText = outText.concat(out);
                    }
                }
            } else {
                // input failed type checking, handle the error
                const p = typeMismatchDesc.parameter,
                    a = typeMismatchDesc.argument,
                    expected = typeMismatchDesc.expected,
                    t = Array.isArray(expected) ? expected.join(', ') : expected;
                msg.channel.send(`Invalid input "${a}" for parameter **${p}** (${t} expected).`);
            }
        }

        return outText;
    }

    // no errors thrown
    // command execution successful
    // update global variables if required, then return
    if (currCmd.update) {
        console.log('updating for ' + channelID);
        await updateVariables(channelID);
    }
    return outText;
}

/**
 * Parses a command from a message into the command name and a list of arguments.
 *
 * @param msg The message that requested the command to be executed.
 * @param prefix The command prefix currently in use.
 * @returns {*} An object containing the command name and command arguments, to be passed to cmdExe, or false if no such
 * command exists.
 */
function cmdParse(msg, prefix) {
    const cmdString = msg.content,
        cmdText = cmdString.slice(prefix.length), // take out the prefix
        firstSpace = cmdText.indexOf(' ');

    let commandName,
        commandArgs;

    if (firstSpace !== -1) {
        commandName = cmdText.slice(0, firstSpace).toLowerCase();  // get the command name

        if (typeof cmdData[commandName] === 'undefined') {
            const aliasCommand = checkForAlias(msg.channel.id, commandName);
            if (aliasCommand) {
                commandName = aliasCommand;
            } else {
                msg.channel.send('**Undefined command name** "' + commandName + '"');
                return false;
            }
        }

        // parse out the command args
        commandArgs = cmdText.slice(firstSpace).match(/"(?:\\"|\\\\|[^"])*"|\S+/g)
            .map((elem) => {
                let out;
                // check if it's in quotes
                if (elem.charAt(0) === '"' && elem.charAt(elem.length - 1) === '"') {
                    out = elem.slice(1, elem.length - 1);
                } else {
                    out = elem;
                }
                // convert to number if numerical
                return isNaN(out) ? out : +out;
            });

        // if too many args have been received:
        let paramsCount = Object.keys(cmdData[commandName].params).length;

        if (commandArgs.length > paramsCount) {
            // too many args received, so condense the remainder into one argument
            const remainingArgs = commandArgs.slice(paramsCount - 1, commandArgs.length);

            commandArgs = commandArgs.slice(0, paramsCount - 1);
            commandArgs.push(remainingArgs.join(' '));
        }
    } else {
        commandName = cmdText.toLowerCase();
        commandArgs = [];

        if (typeof cmdData[commandName] === 'undefined') {
            const aliasCommand = checkForAlias(msg.channel.id, commandName);
            console.log(commandName, aliasCommand);
            if (aliasCommand) {
                commandName = aliasCommand;
            } else {
                msg.channel.send('**Undefined command name** "' + commandName + '"');
                return false;
            }
        }
    }

    return {
        'cmdName': commandName,
        'cmdArgs': commandArgs
    };
}<|endoftext|>


<commit_before>// this class creates player on the playscreen; spritewidth and spriteheight sets size of player.
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				// height and width size of rectangle where player is located
				return(new me.Rect(0,0,64,64)).toPolygon();
			}
		}]);

		// sets were player is at
		this.body.setVelocity(5, 20);

		// animation when standing
		this.renderable.addAnimation("idle", [78]);

		// animation when walking
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);

		// animation that player starts with
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if (me.input.isKeyPressed("right")) {
			// adds to the position of my x by velocity define above in setVelocity() and multiplying it by me.timertick: makes the movemnt look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;

			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;
		}

		if (this.body.vel.x = 0) {
		// makes animation happend
			if (!this.renderable.isCurrentAnimation("walk")) {

				this.renderable.setCurrentAnimation("walk");
			};
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}
		// if dont update the player wont know what to do with code above
		this.body.update(delta);

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

});<commit_msg>video 10 code and comments and error fixed<commit_after>// this class creates player on the playscreen; spritewidth and spriteheight sets size of player.
game.PlayerEntity = me.Entity.extend({
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				// height and width size of rectangle where player is located
				return(new me.Rect(0,0,64,64)).toPolygon();
			}
		}]);

		// sets were player is at
		this.body.setVelocity(5, 20);

		// animation when standing
		this.renderable.addAnimation("idle", [78]);

		// animation when walking
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);

		// animation that player starts with
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		if (me.input.isKeyPressed("right")) {
			// adds to the position of my x by velocity define above in setVelocity() and multiplying it by me.timertick: makes the movemnt look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;

			this.flipX(true);
		}
		else{
			this.body.vel.x = 0;
		}

		if (this.body.vel.x !== 0) {
		// makes animation happend
			if (!this.renderable.isCurrentAnimation("walk")) {

				this.renderable.setCurrentAnimation("walk");
			}
		}
		else{
			this.renderable.setCurrentAnimation("idle");
		}
		// if dont update the player wont know what to do with code above
		this.body.update(delta);

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

});<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'

export default class Header extends Component {
  render() {

    return (

Home

Automotive Brands

Introduction

About Us

About Us - Layout 2

About Me

Team Members

Careers

Side Navigation

Page Submenu

Sitemap

Utility

Services - Layout 1

Services - Layout 2

Services - Layout 3

FAQs - Layout 1

FAQs - Layout 2

FAQs - Layout 3

FAQs - Layout 4

Maintenance Page

Layout Grids

Full Width

Full Width - Wide

Right Sidebar

Left Sidebar

Both Sidebar

Both Right Sidebar

Both Left Sidebar

Blank Page

Miscellaneous

Login/Register

Login/Register - Style 2

Login/Register - Style 3

Login - Style 1

Login - Style 2

404 - Simple Layout

404 - Parallax Image

404 - HTML5 Video

About

  							<form action="search.html" method="get">
  								<input type="text" name="q" className="form-control" value="" placeholder="Type & Hit Enter.."/>
  							</form>

    )
  }
}
<commit_msg>header style<commit_after>import React, { Component, PropTypes } from 'react'

export default class Header extends Component {
  render() {

    return (

Home

Automotive Brands

Introduction

About Us

About Us - Layout 2

About Me

Team Members

Careers

Side Navigation

Page Submenu

Sitemap

Utility

Services - Layout 1

Services - Layout 2

Services - Layout 3

FAQs - Layout 1

FAQs - Layout 2

FAQs - Layout 3

FAQs - Layout 4

Maintenance Page

Layout Grids

Full Width

Full Width - Wide

Right Sidebar

Left Sidebar

Both Sidebar

Both Right Sidebar

Both Left Sidebar

Blank Page

Miscellaneous

Login/Register

Login/Register - Style 2

Login/Register - Style 3

Login - Style 1

Login - Style 2

404 - Simple Layout

404 - Parallax Image

404 - HTML5 Video

About

  							<form action="search.html" method="get">
  								<input type="text" name="q" className="form-control" value="" placeholder="Type & Hit Enter.."/>
  							</form>

    )
  }
}
<|endoftext|>


<commit_before>/*-------------------
 a friend entity
 -------------------------------- */
game.FriendEntity = me.ObjectEntity.extend({

    /* -----

     constructor

     ------ */

    init: function(x, y, settings) {
        this.chosenDirection = 1; // right
        // call the constructor
        this.parent(x, y, settings);
        console.log('FriendEntity.init, settings = ' + JSON.stringify(settings));

        this.framesOnLadder = 0;
        this.framesOffLadder = 15;

        this.collidable = true;
        this.collisionBox.width = 16;
        this.doWalk();

    },

    doWalk: function (goLeft) {
        var xVelocity;
        if (this.chosenDirection === 0) {
            this.choseDirection();
        }
        this.setVelocity(1, 3);
        this.vel.x = this.getXVelocity();
        this.parent(this.chosenDirection === -1); // param = walk left
    },

    choseDirection: function () {
        this.chosenDirection = -1 + _.random(0, 1) * 2; // Randomize either -1 or 1
        console.log('decided ' + this.chosenDirection);
    },

    getXVelocity: function () {
        return 1 * this.chosenDirection;
    },

    /* -----

     update the player pos

     ------ */
    update: function() {

        if (this.onladder) {
            this.framesOnLadder += 1;
            if (this.framesOnLadder === 1) {
                this.framesOffLadder = 0;
                this.setVelocity(this.getXVelocity(), 1);
                this.doClimb(true);
            }
            if (this.framesOnLadder === 15) {
                console.log('undecide');
                this.chosenDirection = 0; // undecided
                this.doClimb(true);
                this.setVelocity(this.getXVelocity(), 1);
            }
        } else {
            this.framesOffLadder += 1;
            if (this.framesOffLadder === 1) {
                this.choseDirection();
                this.doWalk();
            }
            if (this.framesOffLadder === 20) {
                this.framesOnLadder = 0;
            }
        }
        if (this.initialX === this.pos.x) {
            this.chosenDirection = 1;
            this.doWalk();
        }

        // check & update player movement
        this.updateMovement();
        if (!this.initialX) {
            this.initialX = this.pos.x;
        }

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        return false;
    }

});<commit_msg>don't stop if we're near the ladder top<commit_after>/*-------------------
 a friend entity
 -------------------------------- */
game.FriendEntity = me.ObjectEntity.extend({

    /* -----

     constructor

     ------ */

    init: function(x, y, settings) {
        this.chosenDirection = 1; // right
        // call the constructor
        this.parent(x, y, settings);
        console.log('FriendEntity.init, settings = ' + JSON.stringify(settings));

        this.framesOnLadder = 0;
        this.framesOffLadder = 15;

        this.collidable = true;
        this.collisionBox.width = 16;
        this.doWalk();

    },

    doWalk: function (goLeft) {
        var xVelocity;
        if (this.chosenDirection === 0) {
            this.choseDirection();
        }
        this.setVelocity(1, 3);
        this.vel.x = this.getXVelocity();
        this.parent(this.chosenDirection === -1); // param = walk left
    },

    choseDirection: function () {
        this.chosenDirection = -1 + _.random(0, 1) * 2; // Randomize either -1 or 1
        console.log('decided ' + this.chosenDirection);
    },

    getXVelocity: function () {
        return 1 * this.chosenDirection;
    },

    /* -----

     update the player pos

     ------ */
    update: function() {

        if (this.onladder) { //todo: check if object on ladder top
            this.framesOnLadder += 1;
            if (this.framesOnLadder === 1) {
                this.framesOffLadder = 0;
                this.setVelocity(this.getXVelocity(), 1);
                this.doClimb(true);
            }
            if (this.framesOnLadder === 15) {
                console.log('undecide');
                this.chosenDirection = 0; // undecided
                this.doClimb(true);
                this.setVelocity(this.getXVelocity(), 1);
            }
        } else {
            this.framesOffLadder += 1;
            if (this.framesOffLadder === 1) {
                this.choseDirection();
                this.doWalk();
            }
            if (this.framesOffLadder === 20) {
                this.framesOnLadder = 0;
            }
        }
        if (this.initialX === this.pos.x) {
            this.chosenDirection = 1;
            this.doWalk();
        }

        // check & update player movement
        this.updateMovement();
        if (!this.initialX) {
            this.initialX = this.pos.x;
        }

        // update animation if necessary
        if (this.vel.x !== 0 || this.vel.y !== 0) {
            // update object animation
            this.parent();
            return true;
        }

        // else inform the engine we did not perform
        // any update (e.g. position, animation)
        this.choseDirection();
        this.doWalk();
        return true;
        //return false;
    }

});<|endoftext|>


<commit_before>define([
    'knockout',
    'underscore',
    'viewmodels/widget'
], function(ko, _, WidgetViewModel) {
    /**
     * A viewmodel used for domain widgets
     *
     * @constructor
     * @name DomainWidgetViewModel
     *
     * @param  {string} params - a configuration object
     */
    var DomainWidgetViewModel = function(params) {
        var self = this;

        WidgetViewModel.apply(this, [params]);

        if (this.node.config.options) {
            this.options = this.node.config.options;
            this.options().forEach(function(option) {
                if (!ko.isObservable(option.text)) {
                    option.text = ko.observable(option.text);
                }
            })
            this.node.configKeys.valueHasMutated();
        }

        this.flatOptions = ko.computed(function() {
            var options = self.options();
            var flatOptions = [];
            var value = self.value();
            if (!Array.isArray(value)) {
                var valueArray = [];
                if (value) {
                    valueArray.push(value);
                }
                value = valueArray
            }
            var setupOption = function(option) {
                option.selected = ko.computed({
                    read: function() {
                        var selected = false;
                        var value = self.value();
                        if (value && value.indexOf) {
                            selected = value.indexOf(option.id) >= 0;
                        }
                        return selected;
                    },
                    write: function(selected) {
                        if (self.multiple) {
                            var value = self.value();
                            self.value(
                                selected ?
                                _.union(value, [option.id]) :
                                _.without(value, option.id)
                            );
                        } else if (selected) {
                            self.value(option.id);
                        }
                    }
                });
            }
            options.forEach(function(option) {
                setupOption(option);
                gatherChildren(option, flatOptions, setupOption);
            });
            return flatOptions;
        });

        this.multiple = false;

        this.displayValue = ko.computed(function() {
            var value = self.value();
            var options = ko.unwrap(self.flatOptions);
            var displayValue = null;
            if (value) {
                if (!Array.isArray(value)) {
                    value = [value];
                }
                displayValue = _.map(value, function(id) {
                    var text = null;
                    var option = _.find(options, function(option) {
                        return option.id === id;
                    });
                    if (option) {
                        text = ko.unwrap(option.text);
                    }
                    return text;
                })
                displayValue = _.without(displayValue, null).join(', ');
            }
            return displayValue;
        });
    };

    var gatherChildren = function(current, list, callback) {
        list.push(current);
        if (current.children) {
            current.children.forEach(function(child) {
                gatherChildren(child, list, callback);
            });
        }
        callback(current);
        return list;
    };

    return DomainWidgetViewModel;
});
<commit_msg>more widget refactoring<commit_after>define([
    'knockout',
    'underscore',
    'viewmodels/widget'
], function(ko, _, WidgetViewModel) {
    /**
     * A viewmodel used for domain widgets
     *
     * @constructor
     * @name DomainWidgetViewModel
     *
     * @param  {string} params - a configuration object
     */
    var DomainWidgetViewModel = function(params) {
        var self = this;

        WidgetViewModel.apply(this, [params]);

        if (this.node.config.options) {
            this.options = this.node.config.options;
            this.options().forEach(function(option) {
                if (!ko.isObservable(option.text)) {
                    option.text = ko.observable(option.text);
                }
            });
            // force the node config to refresh (so it detects text observables)
            this.node.configKeys.valueHasMutated();
        }

        var flattenOptions = function(opt, allOpts) {
            allOpts.push(opt);
            if (opt.children) {
                opt.children.forEach(function(child) {
                    flattenOptions(child, allOpts);
                });
            }
            if (typeof opt.selected !== 'function') {
                opt.selected = ko.computed({
                    read: function() {
                        var selected = false;
                        var val = self.value();
                        if (val && val.indexOf) {
                            selected = val.indexOf(opt.id) >= 0;
                        }
                        return selected;
                    },
                    write: function(selected) {
                        if (self.multiple) {
                            var val = self.value();
                            self.value(
                                selected ?
                                _.union([opt.id], val) :
                                _.without(val ? val : [], opt.id)
                            );
                        } else if (selected) {
                            self.value(opt.id);
                        }
                    }
                });
            }
            return allOpts;
        };

        this.flatOptions = ko.computed(function() {
            var options = self.options();
            var flatOptions = [];
            options.forEach(function(option) {
                flattenOptions(option, flatOptions);
            });
            return flatOptions;
        });

        this.multiple = false;

        this.displayValue = ko.computed(function() {
            var val = self.value();
            var opts = ko.unwrap(self.flatOptions);
            var displayVal = null;
            if (val) {
                Array.isArray(val) || (val = [val]);
                displayVal = _.without(
                    _.map(val, function(id) {
                        var opt = _.find(opts, function(opt) {
                            return opt.id === id;
                        });
                        return opt ? ko.unwrap(opt.text) : null;
                    }),
                    null
                ).join(', ');
            }
            return displayVal;
        });
    };

    return DomainWidgetViewModel;
});
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
            image: "player",
            width: 64,
            height: 64,
            spritewidth: "64",
            spriteheight: "64",
            getShape: function(){
                return(new me.Rect(0, 0, 64, 64)).toPolygon();
            }

        }]);

        this.body.setVelocity(5, 20);
        //Keeps track of which direction your character is going
        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();  //Haven't used this
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

        this.renderable.setCurrentAnimation("idle");

    },

    update: function(delta) {
        this.now = new Date().getTime();
        if(me.input.isKeyPressed("right")){
             //adds to the position of my x by the velocity define above in
             //setVelocity() and mutiplying it by me.timer.tick.
             //mme.timer.tick makes the movement look smooth
             this.body.vel.x += this.body.accel.x * me.timer.tick;
             this.facing = "right";
             this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
             this.facing = "left";
             this.body.vel.x -=this.body.accel.x * me.timer.tick;
             this.flipX(false);
    }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){
            this.jumping = true;
            this.body.vel.y -= this.body.
                accel.y * me.timer.tick;
        }

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

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

        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);

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

    collideHandler: function(responce) {
        if(responce.b.type==='EnemyBaseEntity'){
            var ydif = this.pos.y - responce.b.pos.y;
            var xdif = this.pos.x - responce.b.pos.x;

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

            if(ydif<-40 && xdif< 70 && xdif>-35 && ydif<0){
                this.body.falling = false;
                this.body.vel.y = -1;
            }

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

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
                console.log("tower Hit");
                this.lastHit = this.now;
                response.b.loseHealth();
            }
        }
    }
    });

game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "tower",
            width: 100,
            height: 100,
            spritewidth: "100",
            spriteheight: "100",
            getShape: function(){
                return (new me.Rect(0, 0, 100, 70)).toPolygon();
            }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);
        this.type = "PlayerBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },

    update:function(delta){
        if(this.health<=0){
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }

        this.body.update(delta);

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

    loseHealth: function(damage){
        this.health = this.health - damage;
    },

      onCollision: function(){

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "tower",
            width: 100,
            height: 100,
            spritewidth: "100",
            spriteheight: "100",
            getShape: function(){
                return (new me.Rect(0, 0, 100, 70)).toPolygon();
            }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },

    update:function(delta){
        if(this.health<=0){
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);

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

    loseHealth: function(){
        this.health--;
    }

});

game.EnemyCreep = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "creep1",
            width: 32,
            height: 64,
            spritewidth: "32",
            spriteheight: "64",
            getShape: function(){
                return (new me.Rect(0, 0, 32, 64)).toPolygon();
            }
        }]);
        this.health = 10;
        this.alwaysUpdate = true;
        // this.attacking lets us know if the enemy is currently attacking
        this.attacking = false;
        //keeps track of when our creep last attacked anything
        this.lastAttacking = new Date().getTime();
        //keeps track of the last time our creep hit anything
        this.lastHit = new Date().getTime();
        this.now = new Date().getTime();
        this.body.setVelocity(3, 20);

        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");
    },

    update: function(delta){
        this.now = new Date().getTime();

        this.body.vel.x-= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true)

        this.body.update(delta);

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

    collideHandler: function(responce){
        if(response.b.type==='PlayerBase'){
            this.attacking=true;
            //this.lastAttacking=this.now;
            this.body.vel.x = 0;
            //keeps moving the creep to thr right to maintain his poition
            this.pos.x = this.pos.x + 1;
            //checks that it has been at least 1 second since this creep hit a base
            if((this.now-this.lastHit >= 1000)){
                //update the lasthit timer
                this.lastHit = this.now;
                //makes the player base call its loseHealth function and passes it a
                //damage of
                responce.b.loseHealth(1);
            }
        }
    }
});

game.GameManager = Object.extend({
    init: function(x, y, settings){
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;
    },

    update: function(){
        this.now = new Date().getTime();

        if(Math.round(this.now/1000%10 ===0 && (this.now - this.lastCreep >= 1000))){
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }

        return true;
    }

});<commit_msg>allowing player to kill creeps<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
            image: "player",
            width: 64,
            height: 64,
            spritewidth: "64",
            spriteheight: "64",
            getShape: function(){
                return(new me.Rect(0, 0, 64, 64)).toPolygon();
            }

        }]);
        this.type = "PlayerEntity";
        this.health = 20;
        this.body.setVelocity(5, 20);
        //Keeps track of which direction your character is going
        this.facing = "right";
        this.now = new Date().getTime();
        this.lastHit = this.now;
        this.lastAttack = new Date().getTime();  //Haven't used this
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

        this.renderable.setCurrentAnimation("idle");

    },

    update: function(delta) {
        this.now = new Date().getTime();
        if(me.input.isKeyPressed("right")){
             //adds to the position of my x by the velocity define above in
             //setVelocity() and mutiplying it by me.timer.tick.
             //mme.timer.tick makes the movement look smooth
             this.body.vel.x += this.body.accel.x * me.timer.tick;
             this.facing = "right";
             this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
             this.facing = "left";
             this.body.vel.x -=this.body.accel.x * me.timer.tick;
             this.flipX(false);
    }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){
            this.jumping = true;
            this.body.vel.y -= this.body.
                accel.y * me.timer.tick;
        }

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

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

        me.collision.check(this, true, this.collideHandler.bind(this), true);
        this.body.update(delta);

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

    collideHandler: function(responce) {
        if(responce.b.type==='EnemyBaseEntity'){
            var ydif = this.pos.y - responce.b.pos.y;
            var xdif = this.pos.x - responce.b.pos.x;

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

            if(ydif<-40 && xdif< 70 && xdif>-35 && ydif<0){
                this.body.falling = false;
                this.body.vel.y = -1;
            }

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

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000){
                console.log("tower Hit");
                this.lastHit = this.now;
                response.b.loseHealth();
            }
        }else if(response.b.type==='EnemyCreep'){
            var xdif = this.pos.x - response.b.pos.x;
            var ydif = this.pos.y - response.b.pos.y;

            if (xdif>0){
                this.pos.x = this.pos.x + 1;
                if(this.facing==="left"){
                    this.vel.x = 0;
                }
            }else{
                this.pos.x = this.pos.x - 1;
                if(this.facing==="right"){
                    this.vel.x = 0;
                }
            }

            if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= 1000
                   && (Math.abs(ydif) <=40) &&
                   ((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")
                   ){
                this.lastHit = this.now;
                response.b.loseHealth(1);
            }
        }
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "tower",
            width: 100,
            height: 100,
            spritewidth: "100",
            spriteheight: "100",
            getShape: function(){
                return (new me.Rect(0, 0, 100, 70)).toPolygon();
            }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);
        this.type = "PlayerBase";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },

    update:function(delta){
        if(this.health<=0){
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }

        this.body.update(delta);

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

    loseHealth: function(damage){
        this.health = this.health - damage;
        console.log(this.health);
    },

      onCollision: function(){

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "tower",
            width: 100,
            height: 100,
            spritewidth: "100",
            spriteheight: "100",
            getShape: function(){
                return (new me.Rect(0, 0, 100, 70)).toPolygon();
            }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },

    update:function(delta){
        if(this.health<=0){
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
        }
        this.body.update(delta);

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

    onCollision: function(){

    },

    loseHealth: function(){
        this.health--;
    }

});

game.EnemyCreep = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
            image: "creep1",
            width: 32,
            height: 64,
            spritewidth: "32",
            spriteheight: "64",
            getShape: function(){
                return (new me.Rect(0, 0, 32, 64)).toPolygon();
            }
        }]);
        this.health = 10;
        this.alwaysUpdate = true;
        // this.attacking lets us know if the enemy is currently attacking
        this.attacking = false;
        //keeps track of when our creep last attacked anything
        this.lastAttacking = new Date().getTime();
        //keeps track of the last time our creep hit anything
        this.lastHit = new Date().getTime();
        this.now = new Date().getTime();
        this.body.setVelocity(3, 20);

        this.type = "EnemyCreep";

        this.renderable.addAnimation("walk", [3, 4, 5], 80);
        this.renderable.setCurrentAnimation("walk");

    },

    loseHealth: function(damage){
        this.health = this.health - damage;
    },

    update: function(delta){
        console.log(this.health);
        if(this.health <= 0){
            me.game.world.removeChild(this);
        }

        this.now = new Date().getTime();

        this.body.vel.x-= this.body.accel.x * me.timer.tick;

        me.collision.check(this, true, this.collideHandler.bind(this), true);

        this.body.update(delta);

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

    collideHandler: function(responce){
        if(response.b.type==='PlayerBase'){
            this.attacking=true;
            //this.lastAttacking=this.now;
            this.body.vel.x = 0;
            //keeps moving the creep to thr right to maintain his poition
            this.pos.x = this.pos.x + 1;
            //checks that it has been at least 1 second since this creep hit a base
            if((this.now-this.lastHit >= 1000)){
                //update the lasthit timer
                this.lastHit = this.now;
                //makes the player base call its loseHealth function and passes it a
                //damage of 1
                responce.b.loseHealth(1);
            }
        }else if (responce.b.type==='PlayerEntity'){
            var xdif = this.pos.x - responce.b.pos.x;

            this.attacking=true;
            //this.lastAttacking=this.now;

            if(xdif>0){
                //keeps moving the creep to thr right to maintain his poition
                this.pos.x = this.pos.x + 1;
                this.body.vel.x = 0;
            }
            this.pos.x = this.pos.x + 1;
            //checks that it has been at least 1 second since this creep hit something
            if((this.now-this.lastHit >= 1000) &&  xdif>0){
                //update the lasthit timer
                this.lastHit = this.now;
                //makes the player call its loseHealth function and passes it a
                //damage of 1
                responce.b.loseHealth(1);
            }
        }
    }
});

game.GameManager = Object.extend({
    init: function(x, y, settings){
        this.now = new Date().getTime();
        this.lastCreep = new Date().getTime();

        this.alwaysUpdate = true;
    },

    update: function(){
        this.now = new Date().getTime();

        if(Math.round(this.now/1000%10 ===0 && (this.now - this.lastCreep >= 1000))){
            this.lastCreep = this.now;
            var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
            me.game.world.addChild(creepe, 5);
        }

        return true;
    }

});<|endoftext|>