Loads the player code and returns the playTurn function.

@param {string} playerCode The code of the player.

@returns {Function} The playTurn function.
973579
function loadPlayer(playerCode) {
  const sandbox = vm.createContext();

  // Do not collect stack frames for errors in the player code.
  vm.runInContext('Error.stackTraceLimit = 0;', sandbox);

  try {
    vm.runInContext(playerCode, sandbox, {
      filename: playerCodeFilename,
      timeout: playerCodeTimeout,
    });
  } catch (err) {
    const error = new Error(`Check your syntax and try again!\n\n${err.stack}`);
    error.code = 'InvalidPlayerCode';
    throw error;
  }

  try {
    const player = vm.runInContext('new Player();', sandbox, {
      timeout: playerCodeTimeout,
    });
    assert(typeof player.playTurn === 'function', 'playTurn is not defined');
    const playTurn = turn => {
      try {
        player.playTurn(turn);
      } catch (err) {
        const error = new Error(err.message);
        error.code = 'InvalidPlayerCode';
        throw error;
      }
    };
    return playTurn;
  } catch (err) {
    if (err.message === 'Player is not defined') {
      const error = new Error('You must define a Player class!');
      error.code = 'InvalidPlayerCode';
      throw error;
    } else if (err.message === 'playTurn is not defined') {
      const error = new Error(
        'Your Player class must define a playTurn method!',
      );
      error.code = 'InvalidPlayerCode';
      throw error;
    }

    throw err;
  }
}
433872
function loadUnit(
  {
    name,
    character,
    color,
    maxHealth,
    reward,
    enemy,
    bound,
    abilities,
    effects,
    playTurn,
    position,
  },
  floor,
) {
  const unit = new Unit(
    name,
    character,
    color,
    maxHealth,
    reward,
    enemy,
    bound,
  );
  loadAbilities(unit, abilities);
  loadEffects(unit, effects);
  unit.playTurn = playTurn;
  floor.addUnit(unit, position);
}
1284474
function drawTurnInfo(pdata) {
    var my_game = $.cookie("game");
    var my_player = pdata[$.cookie("player")];

    $(PIECES).empty();
    $(ADDPIECE).show();

    // allow player to end his turn
    if (my_player.has_turn) {
        $(ENDTURN).removeAttr('disabled');
        $(TURN).html("It's your turn! You have " +
                     "<span id='countdown'>0m 0s</span> left.");
        $(ENDTURN)[0].onclick = function() {
            $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() {
                getPlayers();

                /* Typically we let HAVETURN get updated from the server
                 * in onGetPlayers(), but if there is only one player this
                 * doesn't work very well (the player has to refresh manually).
                 * So we force it to false here in this special case.
                 */
                if (Object.keys(pdata).length === 1) {
                    HAVETURN = false;
                    clearTimeout(COUNTDOWNTID);
                }
            });
        };
    } else {
        $(ENDTURN).attr('disabled', '');
        $(TURN).html("It's not your turn.");
    }
    getPiecesLeft();
    getBoard();
    getMyPieces(my_player);
}
19198
function (hands, table, dead) {
		// Preprocesses the input data.
		table = table ? _.map(table, getCode) : [];
		dead = dead ? _.map(dead, getCode) : [];
		hands = _.map(hands, function (hand) {
			return _.map(hand, getCode);
		});
		var res = deckSize + 1;
		for (var c = 0; c < table.length; c++)
			res = evaluator[res + table[c]];
		var deck = _.chain(_.range(1, deckSize + 1)).difference(table)
				.difference(_.flatten(hands)).difference(dead).value();
		var player = _.map(hands, function (hand) {
			return evaluator[evaluator[res + hand[0]] + hand[1]];
		});
		var combinations = function (n, k, res, callback) {
			if (k <= 0) {
				callback(res);
			} else {
				while (n < deck.length) {
					var parcial = evaluator[res + deck[n++]];
					combinations(n, k - 1, parcial, callback);
				}
			}
		};
		
		// Calculates the outcome of each play.
		var remaining = 5 - table.length;
		var plays = deck.length / remaining;
		for (var c = 1; c < remaining; c++)
			plays *= (deck.length - c) / c;
		var values = new Array(hands.length);
		for (var p = 0; p < hands.length; p++) {
			var s = 0;
			values[p] = new Int32Array(plays);
			combinations(0, remaining, player[p], function (res) {
				values[p][s++] = res;
			});
		}
		
		// Determines the results.
		var wins = new Int32Array(hands.length);
		var splits = new Int32Array(hands.length);
		for (var s = 0; s < plays; s++) {
			var winner = [0];
			for (var p = 1; p < hands.length; p++) {
				if (values[p][s] > values[winner[0]][s])
					winner = [p];
				else if (values[p][s] == values[winner[0]][s])
					winner.push(p);
			}
			if (winner.length == 1) {
				wins[winner[0]]++;
			} else {
				for (var p = 0; p < winner.length; p++)
					splits[winner[p]]++;
			}
		}
		
		// Formats odds output.
		var odds = [];
		for (var p = 0; p < hands.length; p++)
			odds[p] = {win: wins[p] / plays, split: splits[p] / plays};
		return odds;
	}
736148
function(fn) {
  var code = fn.toString();
  var match = code.match(/^(?:(?:function)?[\s]*\(([^)]*)\)|([^\=\(]+))/);
  var args = (match[1] || match[2]);
  if (typeof args === 'undefined') {
    return [];
  }
  return args.split(',').map(function(item) {
    return item.trim();
  }).filter(function(item) {
    return item;
  });
}
252160
function(game, fn) {
    if (!game || (typeof game !== 'number' &&
        typeof game !== 'string')) {
      return fn('Error getting Move. You did not specify the ' +
        'id number of the game you want to retrieve.');
    }

    game = game.toString();
    var apiCall = 'http://pokeapi.co/api/v' + defaults.version +
      '/game/' + game;
    makeTheCall(game, 'game', apiCall, function(err, data) {
      return fn(err, data);
    });
  }
1279956
function generateClient(clientObj) {
    var client;
    client = new Player(clientObj);
    if ('undefined' === typeof client.valid) client.valid = true;
    if ('undefined' === typeof client.connected) client.connected = false;
    // if ('undefined' === typeof client.history) client.history = [];
    if ('undefined' === typeof client.checkedOut) client.checkedOut = false;
    if ('undefined' === typeof client.dropOut) client.dropOut = false;
    return client;
}
1091122
function getNodeFromCode(code) {
    if (convert.mapFileCommentRegex.test(code)) {
        try {
            return SourceNode.fromStringWithSourceMap(
                convertCode2Script(code),
                new SourceMapConsumer(convert.fromComment(code).toObject())
            );
        } catch (error) {
            console.error('getNodeFromCode() error: ' + error);
            const node = new SourceNode();
            node.add(convertCode2Script(code));
            return node;
        }
    } else {
        const node = new SourceNode();
        node.add(convertCode2Script(code));
        return node;
    }
}
922236
function Stager(stateObj) {

        // ## Properties

        /**
         * #### Stager.steps
         *
         * Step object container
         *
         * key: step ID,  value: step object
         *
         * @see Stager.addStep
         */
        this.steps = {};

        /**
         * #### Stager.stages
         *
         * Stage object container
         *
         * key: stage ID,  value: stage object
         *
         * Stage aliases are stored the same way, with a reference to
         * the original stage object as the value.
         *
         * @see Stager.addStage
         */
        this.stages = {};

        /**
         * #### Stager.sequence
         *
         * Sequence block container
         *
         * Stores the game plan in 'simple mode'.
         *
         * @see Stager.gameover
         * @see Stager.next
         * @see Stager.repeat
         * @see Stager.loop
         * @see Stager.doLoop
         */
        this.sequence = [];

        /**
         * #### Stager.generalNextFunction
         *
         * General next-stage decider function
         *
         * Returns the id of the next game step.
         * Available only when nodegame is executed in _flexible_ mode.
         *
         * @see Stager.registerGeneralNext
         */
        this.generalNextFunction = null;

        /**
         * #### Stager.nextFunctions
         *
         * Per-stage next-stage decider function
         *
         * key: stage ID,  value: callback function
         *
         * Stores functions to be called to yield the id of the next
         * game stage for a specific previous stage.
         *
         * @see Stager.registerNext
         */
        this.nextFunctions = {};

        /**
         * #### Stager.defaultStepRule
         *
         * Default step-rule function
         *
         * This function decides whether it is possible to proceed to
         * the next step/stage. If a step/stage object defines a
         * `steprule` property, then that function is used instead.
         *
         * @see Stager.getDefaultStepRule
         * @see GamePlot.getStepRule
         */
        this.setDefaultStepRule();

        /**
         * #### Stager.defaultGlobals
         *
         * Defaults of global variables
         *
         * This map holds the default values of global variables. These
         * values are overridable by more specific version in step and
         * stage objects.
         *
         * @see Stager.setDefaultGlobals
         * @see GamePlot.getGlobal
         */
        this.defaultGlobals = {};

        /**
         * #### Stager.defaultProperties
         *
         * Defaults of properties
         *
         * This map holds the default values of properties. These values
         * are overridable by more specific version in step and stage
         * objects.
         *
         * @see Stager.setDefaultProperties
         * @see GamePlot.getProperty
         */
        this.defaultProperties = {};

        /**
         * #### Stager.onInit
         *
         * Initialization function
         *
         * This function is called as soon as the game is instantiated,
         * i.e. at stage 0.0.0.
         *
         * Event listeners defined here stay valid throughout the whole
         * game, unlike event listeners defined inside a function of the
         * gamePlot, which are valid only within the specific function.
         */
        this.onInit = null;

        /**
         * #### Stager.onGameover
         *
         * Cleaning up function
         *
         * This function is called after the last stage of the gamePlot
         * is terminated.
         */
        this.onGameover = null;

        /**
         * #### Stager.blocks
         *
         * Array of blocks as they in the order they were added to the stager
         */
        this.blocks = [];

        /**
         * #### Stager.blocksIds
         *
         * Map block-id to block-position in the blocks array
         *
         * @see blocks
         */
        this.blocksIds = {};

        /**
         * #### Stager.unfinishedBlocks
         *
         * List of all Blocks stager might still modify
         */
        this.unfinishedBlocks = [];

        /**
         * #### Stager.finalized
         *
         * Flag indicating if the hierarchy of has been set
         *
         * Indicates if the hierarchy of stages and steps has been set.
         */
        this.finalized = false;

        /**
         * #### Stager.currentType
         *
         * Name of the stage currently worked with in building hierarchy
         */
        this.currentType = blockTypes.BLOCK_DEFAULT;

        /**
         * #### Stager.currentBlockType
         *
         * Indicates what type of Block was added last
         */
        this.currentBlockType = blockTypes.BLOCK_DEFAULT;

        /**
         * #### Stager.toSkip
         *
         * List of stages and steps to skip when building the sequence
         */
        this.toSkip = {
            stages: {},
            steps: {}
        };

        /**
         * #### Stager.defaultCallback
         *
         * Default callback assigned to a step if none is provided
         */
        this.defaultCallback = Stager.defaultCallback;

        /**
         * #### Stager.cacheReset
         *
         * Cache used to reset the state of the stager after finalization
         */
        this.cacheReset = {
            unfinishedBlocks: []
        };

        /**
         * #### Stager.log
         *
         * Default standard output. Override to redirect.
         */
        this.log = console.log;

        // Set the state if one is passed.
        if (stateObj) {
            if ('object' !== typeof stateObj) {
                throw new TypeError('Stager: stateObj must be object.');
            }
            this.setState(stateObj);
        }
        else {
            // Add first block.
            this.stageBlock(blockTypes.BLOCK_DEFAULT, 'linear');
        }
    }
121247
function Game() {

        // un-populated instance of Array2d
        this.map = new RL.Map(this);
        this.entityManager = new RL.ObjectManager(this, RL.Entity);
        this.renderer = new RL.Renderer(this);
        this.console = new RL.Console(this);
        this.lighting = new RL.LightingROT(this);

        // player purposefully not added to entity manager (matter of preference)
        this.player = new RL.Player(this);

        // make sure "this" is this instance of Game when this.onKeyAction is called
        this.onKeyAction = this.onKeyAction.bind(this);
        this.onClick = this.onClick.bind(this);
        this.onHover = this.onHover.bind(this);

        this.input = new RL.Input(this.onKeyAction);
        this.mouse = new RL.Mouse(this.onClick, this.onHover);

        var el = this.renderer.canvas;
        this.mouse.startListening(el);
    }
651372
function ErrorDisplay(player, options) {
    _classCallCheck(this, ErrorDisplay);

    var _this = _possibleConstructorReturn(this, _ModalDialog.call(this, player, options));

    _this.on(player, 'error', _this.open);
    return _this;
  }
490640
function pongSrcCodeDivRenderHTML( divId, resourceURL, params, cfg ) {
	log( "Pong-SrcCode", "load source code" );
	if ( ! cfg.type ) {  cfg.type = "plain"; }
	$.get( resourceURL, params  )
		.done( 
			function ( srcData ) {
				jQuerySyntaxInsertCode( divId, srcData, cfg.type, cfg.options||{} );	
			}
		).fail( function() { alert( "Failed to load source code." ) } ); 
}
543318
function transformCode(code, url, options) {
  try {
    var transformed = transformReact(code, options);
  } catch(e) {
    e.message += '\n    at ';
    if (url) {
      if ('fileName' in e) {
        // We set `fileName` if it's supported by this error object and
        // a `url` was provided.
        // The error will correctly point to `url` in Firefox.
        e.fileName = url;
      }
      e.message += url + ':' + e.lineNumber + ':' + e.column;
    } else {
      e.message += location.href;
    }
    e.message += createSourceCodeErrorMessage(code, e);
    throw e;
  }

  if (!transformed.sourceMap) {
    return transformed.code;
  }

  var map = transformed.sourceMap.toJSON();
  var source;
  if (url == null) {
    source = "Inline JSX script";
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += ' (' + inlineScriptCount + ')';
    }
  } else if (dummyAnchor) {
    // Firefox has problems when the sourcemap source is a proper URL with a
    // protocol and hostname, so use the pathname. We could use just the
    // filename, but hopefully using the full path will prevent potential
    // issues where the same filename exists in multiple directories.
    dummyAnchor.href = url;
    source = dummyAnchor.pathname.substr(1);
  }
  map.sources = [source];
  map.sourcesContent = [code];

  return (
    transformed.code +
    '\n//# sourceMappingURL=data:application/json;base64,' +
    buffer.Buffer(JSON.stringify(map)).toString('base64')
  );
}
208629
function init() {
        CodeMirror.defineExtension("foldCode", function (pos, options, force) {
            return doFold(this, pos, options, force);
        });

        CodeMirror.defineExtension("unfoldCode", function (pos, options) {
            return doFold(this, pos, options, "unfold");
        });

        CodeMirror.defineExtension("isFolded", function (line) {
            return this._lineFolds && this._lineFolds[line];
        });

        /**
          * Checks the validity of the ranges passed in the parameter and returns the foldranges
          * that are still valid in the current document
          * @param {object} folds the dictionary of lines in the current document that should be folded
          * @returns {object} valid folds found in those passed in parameter
          */
        CodeMirror.defineExtension("getValidFolds", function (folds) {
            var keys, rf = CodeMirror.fold.auto, cm = this, result = {}, range, cachedRange;
            if (folds && (keys = Object.keys(folds)).length) {
                keys.forEach(function (lineNumber) {
                    lineNumber = +lineNumber;
                    if (lineNumber >= cm.firstLine() && lineNumber <= cm.lastLine()) {
                        range = rf(cm, CodeMirror.Pos(lineNumber, 0));
                        cachedRange = folds[lineNumber];
                        if (range && cachedRange && range.from.line === cachedRange.from.line &&
                                range.to.line === cachedRange.to.line) {
                            result[lineNumber] = folds[lineNumber];
                        }
                    }
                });
            }
            return result;
        });

        /**
          * Utility function to fold the region at the current cursor position in  a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?options} options extra options to pass to the fold function
          */
        CodeMirror.commands.fold = function (cm, options) {
            cm.foldCode(cm.getCursor(), options, "fold");
        };

        /**
          * Utility function to unfold the region at the current cursor position in  a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?options} options extra options to pass to the fold function
          */
        CodeMirror.commands.unfold = function (cm, options) {
            cm.foldCode(cm.getCursor(), options, "unfold");
        };

        /**
          * Utility function to fold all foldable regions in a document
          * @param {CodeMirror} cm the CodeMirror instance
          */
        CodeMirror.commands.foldAll = function (cm) {
            cm.operation(function () {
                var i, e;
                for (i = cm.firstLine(), e = cm.lastLine(); i <= e; i++) {
                    cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
                }
            });
        };

        /**
          * Utility function to unfold all folded regions in a document
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?number} from the line number for the beginning of the region to unfold
          * @param {?number} to the line number for the end of the region to unfold
          */
        CodeMirror.commands.unfoldAll = function (cm, from, to) {
            from = from || cm.firstLine();
            to = to || cm.lastLine();
            cm.operation(function () {
                var i, e;
                for (i = from, e = to; i <= e; i++) {
                    if (cm.isFolded(i)) { cm.unfoldCode(i, {range: cm._lineFolds[i]}); }
                }
            });
        };

        /**
          * Folds the specified range. The descendants of any fold regions within the range are also folded up to
          * a level set globally in the `maxFoldLevel' preferences
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {?number} start the line number for the beginning of the region to fold
          * @param {?number} end the line number for the end of the region to fold
          */
        CodeMirror.commands.foldToLevel = function (cm, start, end) {
            var rf = CodeMirror.fold.auto;
            function foldLevel(n, from, to) {
                if (n > 0) {
                    var i = from, range;
                    while (i < to) {
                        range = rf(cm, CodeMirror.Pos(i, 0));
                        if (range) {
                            //call fold level for the range just folded
                            foldLevel(n - 1, range.from.line + 1, range.to.line - 1);
                            cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
                            i = range.to.line + 1;
                        } else {
                            i++;
                        }
                    }
                }
            }
            cm.operation(function () {
                start = start === undefined ? cm.firstLine() : start;
                end = end || cm.lastLine();
                foldLevel(prefs.getSetting("maxFoldLevel"), start, end);
            });
        };

        /**
          * Helper to combine an array of fold range finders into one. This goes through the
          * list of fold helpers in the parameter arguments and returns the first non-null
          * range found from calling the fold helpers in order.
          */
        CodeMirror.registerHelper("fold", "combine", function () {
            var funcs = Array.prototype.slice.call(arguments, 0);
            return function (cm, start) {
                var i;
                for (i = 0; i < funcs.length; ++i) {
                    var found = funcs[i] && funcs[i](cm, start);
                    if (found) {
                        return found;
                    }
                }
            };
        });

        /**
          * Creates a helper which returns the appropriate fold function based on the mode of the current position in
          * a document.
          * @param {CodeMirror} cm the CodeMirror instance
          * @param {number} start the current position in the document
          */
        CodeMirror.registerHelper("fold", "auto", function (cm, start) {
            var helpers = cm.getHelpers(start, "fold"), i, range;
            //ensure mode helper is loaded if there is one
            var mode = cm.getMode().name;
            var modeHelper = CodeMirror.fold[mode];
            if (modeHelper && helpers.indexOf(modeHelper) < 0) {
                helpers.push(modeHelper);
            }
            for (i = 0; i < helpers.length; i++) {
                range = helpers[i](cm, start);
                if (range && range.to.line - range.from.line >= prefs.getSetting("minFoldSize")) { return range; }
            }
        });
    }
1146140
function getKeys(code) {
		var reKeys = /KEYS\[\s*(\d+)\s*\]/g
		,	match
		,	max = 0, d = 1000;
		while ((match = reKeys.exec(code)) && d > 0) {
			if (parseInt(match[1], 10) > max)
				max = parseInt(match[1], 10);
			d--;
		}
		self._keys[scriptName] = max;
		done(code);
	}
658023
function handleGame(request, response, game, path) {
    var resp;
    switch(path[0]) {
    case 'board':
        // add pieces to the board
        if (request.method === "POST") {
            requestBody(request, function(form) {

                var player = playerFromReq(request, response, game);
                // console.info('adding pieces, player:'+player.name);
                // console.info('form info:'+JSON.stringify(form));

                if (form && form.shape && form.color &&
                    form.row && form.column && player) {

                    // TODO should do form check?
                    var row = parseInt(form.row, 10);
                    var column = parseInt(form.column, 10);
                    var piece = new Piece(form.shape, form.color);

                    // check player has piece
                    var idx = -1, _idx = 0;
                    for (var p in player.pieces) {
                        var _piece = player.pieces[p];
                        //console.log('check:'+JSON.stringify(p)+', and:'+
                        //          JSON.stringify(piece));
                        if (piece.equals(_piece)) {
                            idx = _idx;
                            break;
                        }
                        _idx += 1;
                    }

                    if (idx > -1) {
                        var gp = new GamePiece(piece, row, column);
                        // console.info('adding piece:'+JSON.stringify(gp));
                        resp = addGamePiece(game, gp);
                        if (typeof resp === "string") {
                            // add gamepiece failed
                            response.writeHead(409, {'Content-Type': 'text/json'});
                            response.write(resp, 'utf-8');
                            response.end();
                            return;
                        } else {
                            // add gamepiece succeeded
                            player.points += resp;
                            player.pieces.splice(idx, 1);
                            respOk(response, '', 'text/json');
                        }
                    }
                }
            });
            return;
        }
        // get pieces on the board
        resp = JSON.stringify(game.board);
        break;
    case 'players':
        handlePlayers(request, response, game, path.slice(1));
        return;
    case 'pieces':
        // get pieces in the bag
        resp = JSON.stringify(game.pieces);
        break;
    case 'chat':
        handleChat(request, response, game.chat);
        break;
    case 'dimensions':
        resp = JSON.stringify(game.dimensions);
    }
    respOk(response, resp, 'text/json');
}
1063186
function (mode, code, tokens, flags, scope, parseMode) {
    var index = code.index + 2,
        length = code.length;

    if ( /* ! */
        code.codePointAt(index) === 0x0021
    ) {
        if (
            code.codePointAt(++index) === 0x002d &&
            code.codePointAt(++index) === 0x002d
        ) {
            index++;

            for (; index < length; index++) {
                if ( /* --}} */
                    code.codePointAt(index) === 0x002d &&
                    code.codePointAt(index + 1) === 0x002d &&
                    code.codePointAt(index + 2) === 0x007d &&
                    code.codePointAt(index + 3) === 0x007d
                ) {
                    index += 4; /* for --}} */
                    code.index = index;

                    parseMode.close();

                    if (flags.keepComments) {
                        // make a CommentToken and return that.
                    }

                    return true;
                }
            }

            throw code.makeError(
                'Unclosed Comment: Expected "--}}" to fallow "{{!--".',
                5
            );
        }

        index++;

        for (; index < length; index++) {

            if ( /* }} */
                code.codePointAt(index) === 0x007d &&
                code.codePointAt(index + 1) === 0x007d
            ) {
                index += 2; /* for }} */
                code.index = index;

                parseMode.close();

                if (flags.keepComments) {
                    // make a CommentToken and return that.
                }

                return true;
            }
        }

        throw code.makeError(
            code.index, code.index + 3,
            'Unclosed Comment: Expected "}}" to fallow "{{!".'
        );
    }

    return null;
}