Surprise! We've been running on hardware provided by BuyVM for a few months and wanted to show them a little appreciation.
Running a paste site comes with unique challenges, ones that aren't always obvious and hard to control. As such, BuyVM offered us a home where we could worry less about the hosting side of things and focus on maintaining a clean and useful service! Go check them out and show them some love!
Description: Adventure system
Submitted on February 2, 2018 at 05:13 PM

New Paste 1 (JavaScript)

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
/**
 * adventureSystem.js
 *
 * It's an improved bankheist, basically.
 *
 * Viewers can start/join an adventure using the commands.
 * A random story will then bee chosen from the available stories.
 * This means this heist can have more than one story, in fact it can have pretty much
 * an infinite amount of different locations, events etc...
 *
 * When a user joins the adventure the module will check if
 * the Tamagotchi module is active and attempt to retrieve the user's tamagotchi.
 * If the user owns a tamagotchi and it's feeling good enough it wil join
 * the adventure with it's own entry of half of its owner's bet.
 * If the tamagotchi survives it wil then give it's price to it's owner.
 */
(function() {
    var joinTime = $.getSetIniDbNumber('adventureSettings', 'joinTime', 5),
        coolDown = $.getSetIniDbNumber('adventureSettings', 'coolDown', 900),
        gainPercent = $.getSetIniDbNumber('adventureSettings', 'gainPercent', 30),
        minBet = $.getSetIniDbNumber('adventureSettings', 'minBet', 10),
        maxBet = $.getSetIniDbNumber('adventureSettings', 'maxBet', 1000),
        enterMessage = $.getSetIniDbBoolean('adventureSettings', 'enterMessage', false),
        warningMessage = $.getSetIniDbBoolean('adventureSettings', 'warningMessage', false),
        coolDownAnnounce = $.getSetIniDbBoolean('adventureSettings', 'coolDownAnnounce', false),
        tgFunIncr = 1,
        tgExpIncr = 0.5,
        tgFoodDecr = 0.25,
        currentAdventure = {},
        stories = [],
        moduleLoaded = false,
        lastStory;


    function reloadAdventure() {
        joinTime = $.getIniDbNumber('adventureSettings', 'joinTime');
        coolDown = $.getIniDbNumber('adventureSettings', 'coolDown');
        gainPercent = $.getIniDbNumber('adventureSettings', 'gainPercent');
        minBet = $.getIniDbNumber('adventureSettings', 'minBet');
        maxBet = $.getIniDbNumber('adventureSettings', 'maxBet');
        enterMessage = $.getIniDbBoolean('adventureSettings', 'enterMessage');
        warningMessage = $.getIniDbBoolean('adventureSettings', 'warningMessage');
        coolDownAnnounce = $.getIniDbBoolean('adventureSettings', 'coolDownAnnounce');
    };

    /**
     * @function loadStories
     */
    function loadStories() {
        var storyId = 1,
            chapterId,
            lines;
        currentAdventure.users = [];
        currentAdventure.survivors = [];
        currentAdventure.caught = [];
        currentAdventure.gameState = 0;

        stories = [];

        for (storyId; $.lang.exists('adventuresystem.stories.' + storyId + '.title'); storyId++) {
            lines = [];
            for (chapterId = 1; $.lang.exists('adventuresystem.stories.' + storyId + '.chapter.' + chapterId); chapterId++) {
                lines.push($.lang.get('adventuresystem.stories.' + storyId + '.chapter.' + chapterId));
            }

            stories.push({
                game: ($.lang.exists('adventuresystem.stories.' + storyId + '.game') ? $.lang.get('adventuresystem.stories.' + storyId + '.game') : null),
                title: $.lang.get('adventuresystem.stories.' + storyId + '.title'),
                lines: lines,
            });
        }

        $.consoleDebug($.lang.get('adventuresystem.loaded', storyId - 1));

        for (var i in stories) {
            if (stories[i].game === null) {
                return;
            }
        }

        $.log.warn('You must have at least one adventure that doesn\'t require a game to be set.');
        currentAdventure.gameState = 2;
    };

    /**
     * @function top5
     */
    function top5() {
        var payoutsKeys = $.inidb.GetKeyList('adventurePayouts', ''),
            temp = [],
            counter = 1,
            top5 = [],
            i;

        if (payoutsKeys.length == 0) {
            $.say($.lang.get('adventuresystem.top5.empty'));
        }

        for (i in payoutsKeys) {
            if (payoutsKeys[i].equalsIgnoreCase($.ownerName) || payoutsKeys[i].equalsIgnoreCase($.botName)) {
                continue;
            }
            temp.push({
                username: payoutsKeys[i],
                amount: parseInt($.inidb.get('adventurePayouts', payoutsKeys[i])),
            });
        }

        temp.sort(function(a, b) {
            return (a.amount < b.amount ? 1 : -1);
        });

        for (i in temp) {
            if (counter <= 5) {
                top5.push(counter + '. ' + temp[i].username + ': ' + $.getPointsString(temp[i].amount));
                counter++;
            }
        }
        $.say($.lang.get('adventuresystem.top5', top5.join(', ')));
    };

    /**
     * @function checkUserAlreadyJoined
     * @param {string} username
     * @returns {boolean}
     */
    function checkUserAlreadyJoined(username) {
        var i;
        for (i in currentAdventure.users) {
            if (currentAdventure.users[i].username == username) {
                return true;
            }
        }
        return false;
    };
	
	/**
	* @function Fetches the players who have died during a (caught) sequence
	*/
	function getDeaths() {
		var i;
		currentAdventure.caught = [];
		// $.consoleLn('Starting the death loop.');
		for (i in currentAdventure.users) {
			range = $.randRange(0, 25);
			//$.consoleLn('random range: ' + range);
			if (range <= 5) {
				// $.consoleLn('Adding a death: ' + currentAdventure.users[i].username);
				currentAdventure.caught.push(currentAdventure.users[i]);
			}
		}
	};

    /**
     * @function adventureUsersListJoin
     * @param {Array} list
     * @returns {string}
     */
    function adventureUsersListJoin(list) {
        var temp = [],
            i;
        for (i in list) {
            temp.push($.username.resolve(list[i].username));
        }
        return temp.join(', ');
    };

    /**
     * @function calculateResult
     */
    function calculateResult() {
        var i;
		getDeaths();
		var death;
        for (i = currentAdventure.survivors.length - 1; i >= 0; i--) {
			//$.consoleLn('Looping through the survivors to find who to remove.');
			for (death in currentAdventure.caught) {
				//$.consoleLn('Looping through the deaths to find who to remove.');
				if (currentAdventure.caught[death].username == currentAdventure.survivors[i].username) {
					//$.consoleLn('Found a death: ' + currentAdventure.caught[death].username);
					currentAdventure.caught.push(currentAdventure.survivors[i]);
					currentAdventure.survivors.splice(i, 1);
					//$.consoleLn('Successfully removed: ' + currentAdventure.caught[death].username);
				}
			}
        }
    };

    /**
     * @function replaceTags
     * @param {string} line
     * @returns {string}
     */
    function replaceTags(line) {
        if (line.indexOf('(caught)') > -1) {
			calculateResult();
            if (currentAdventure.caught.length > 0) {
                return line.replace('(caught)', adventureUsersListJoin(currentAdventure.caught));
            } else {
                return '';
            }
        }
        if (line.indexOf('(survivors)') > -1) {
            if (currentAdventure.survivors.length > 0) {
                return line.replace('(survivors)', adventureUsersListJoin(currentAdventure.survivors));
            } else {
                return '';
            }
        }
        return line
    };

    /**
     * @function inviteTamagotchi
     * @param {string} username
     * @param {Number} bet
     */
    function inviteTamagotchi(username, bet) {
        if ($.bot.isModuleEnabled('./games/tamagotchi.js')) {
            //noinspection JSUnresolvedVariable,JSUnresolvedFunction
            var userTG = $.tamagotchi.getByOwner(username);
            if (userTG) {
                //noinspection JSUnresolvedFunction
                if (userTG.isHappy()) {
                    //noinspection JSUnresolvedFunction
                    userTG
                        .incrFunLevel(tgFunIncr)
                        .incrExpLevel(tgExpIncr)
                        .decrFoodLevel(tgFoodDecr)
                        .save();
                    $.say($.lang.get('adventuresystem.tamagotchijoined', userTG.name));
                    currentAdventure.users.push({
                        username: userTG.name,
                        tgOwner: username,
                        bet: (bet / 2),
                    });
                } else {
                    //noinspection JSUnresolvedFunction
                    userTG.sayFunLevel();
                }
            }
        }
    };

    /**
     * @function startHeist
     * @param {string} username
     */
    function startHeist(username) {
        currentAdventure.gameState = 1;

        var t = setTimeout(function() {
            runStory();
        }, joinTime * 1e3);

        $.say($.lang.get('adventuresystem.start.success', $.resolveRank(username), $.pointNameMultiple));
    };

    /**
     * @function joinHeist
     * @param {string} username
     * @param {Number} bet
     * @returns {boolean}
     */
    function joinHeist(username, bet) {
        if (stories.length < 1) {
            $.log.error('No quests found; cannot start an quest.');
            return;
        }

        if (currentAdventure.gameState > 1) {
            if (!warningMessage) return;
            $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.join.notpossible'));
            return;
        }

        if (checkUserAlreadyJoined(username)) {
            if (!warningMessage) return;
            $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.alreadyjoined'));
            return;
        }

        if (bet > $.getUserPoints(username)) {
            if (!warningMessage) return;
            $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.join.needpoints', $.getPointsString(bet), $.getPointsString($.getUserPoints(username))));
            return;
        }

        if (bet < minBet) {
            if (!warningMessage) return;
            $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.join.bettoolow', $.getPointsString(bet), $.getPointsString(minBet)));
            return;
        }

        if (bet > maxBet) {
            if (!warningMessage) return;
            $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.join.bettoohigh', $.getPointsString(bet), $.getPointsString(maxBet)));
            return;
        }

        if (currentAdventure.gameState == 0) {
            startHeist(username);
        } else {
            if (enterMessage) {
                $.say($.whisperPrefix(username) + $.lang.get('adventuresystem.join.success', $.getPointsString(bet)));
            }
        }

        currentAdventure.users.push({
            username: username,
            bet: parseInt(bet),
        });

        $.inidb.decr('points', username, bet);
        inviteTamagotchi(username, bet);
        return true;
    };

    /**
     * @function runStory
     */
    function runStory() {
        var progress = 0,
            temp = [],
            story,
            line,
            t;

        currentAdventure.gameState = 2;
		var i;
		for (i in currentAdventure.users) { 
			currentAdventure.survivors.push(currentAdventure.users[i]);
		}
        var game = $.getGame($.channelName);

        for (var i in stories) {
            if (stories[i].game != null) {
                if (game.equalsIgnoreCase(stories[i].game)) {
                    //$.consoleLn('gamespec::' + stories[i].title);
                    temp.push({
                        title: stories[i].title,
                        lines: stories[i].lines
                    });
                }
            } else {
                //$.consoleLn('normal::' + stories[i].title);
                temp.push({
                    title: stories[i].title,
                    lines: stories[i].lines
                });
            }
        }

        do {
            story = $.randElement(temp);
        } while (story == lastStory && stories.length != 1);

        $.say($.lang.get('adventuresystem.runstory', story.title, currentAdventure.users.length));

        t = setInterval(function() {
            if (progress < story.lines.length && currentAdventure.survivors.length > 0) {
                line = replaceTags(story.lines[progress]);
                if (line != '') {
                    $.say(line.replace(/\(game\)/g, $.twitchcache.getGameTitle() + ''));
                }
            } else {
                endHeist();
                clearInterval(t);
            }
            progress++;
        }, 7e3);
    };

    /**
     * @function endHeist
     */
    function endHeist() {
        var i, pay, username, maxlength = 0;
        var temp = [];

        for (i in currentAdventure.survivors) {
            if (currentAdventure.survivors[i].tgOwner) {
                currentAdventure.survivors[i].username = currentAdventure.survivors[i].tgOwner;
            }
            pay = (currentAdventure.survivors[i].bet * (gainPercent / 100));
            $.inidb.incr('adventurePayouts', currentAdventure.survivors[i].username, pay);
            $.inidb.incr('adventurePayoutsTEMP', currentAdventure.survivors[i].username, pay);
            $.inidb.incr('points', currentAdventure.survivors[i].username, currentAdventure.survivors[i].bet + pay);
        }

        for (i in currentAdventure.survivors) {
            username = currentAdventure.survivors[i].username;
            maxlength += username.length();
            temp.push($.username.resolve(username) + ' (+' + $.getPointsString($.inidb.get('adventurePayoutsTEMP', currentAdventure.survivors[i].username)) + ')');
        }

        if (temp.length == 0) {
            $.say($.lang.get('adventuresystem.completed.no.win'));
        } else if (((maxlength + 14) + $.channelName.length) > 512) {
            $.say($.lang.get('adventuresystem.completed.win.total', currentAdventure.survivors.length, currentAdventure.caught.length)); //in case too many people enter.
        } else {
            $.say($.lang.get('adventuresystem.completed', temp.join(', ')));
        }

        clearCurrentAdventure();
        temp = "";
        $.coolDown.set('adventure', false, coolDown, false);
        if (coolDownAnnounce) {
            setTimeout(function() {
                $.say($.lang.get('adventuresystem.reset', $.pointNameMultiple));
            }, coolDown*1000);
        }
    };

    /**
     * @function clearCurrentAdventure
     */
    function clearCurrentAdventure() {
        currentAdventure = {
            gameState: 0,
            users: [],
            tgOwners: [],
            survivors: [],
            caught: [],
        }
        $.inidb.RemoveFile('adventurePayoutsTEMP');
    };

    /**
     * @event command
     */
    $.bind('command', function(event) {
        var sender = event.getSender().toLowerCase(),
            command = event.getCommand(),
            args = event.getArgs(),
            action = args[0],
            actionArg1 = args[1],
            actionArg2 = args[2];

        /**
         * @commandpath adventure - Adventure command for starting, checking or setting options
         * @commandpath adventure [amount] - Start/join an adventure
         */
        if (command.equalsIgnoreCase('quest')) {
            if (!action) {
                $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.adventure.usage', $.pointNameMultiple));
                return;
            }

            if (!isNaN(parseInt(action))) {
                joinHeist(sender, parseInt(action));
                return;
            }

            /**
             * @commandpath adventure top5 - Announce the top 5 adventurers in the chat (most points gained)
             */
            if (action.equalsIgnoreCase('top5')) {
                top5();
            }

            /**
             * @commandpath adventure set - Base command for controlling the adventure settings
             */
            if (action.equalsIgnoreCase('set')) {
                if (actionArg1 === undefined || actionArg2 === undefined) {
                    $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                    return;
                }

                /**
                 * @commandpath adventure set jointime [seconds] - Set the join time
                 */
                if (actionArg1.equalsIgnoreCase('joinTime')) {
                    if (isNaN(parseInt(actionArg2))) {
                        $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                        return;
                    }
                    joinTime = parseInt(actionArg2);
                    $.inidb.set('adventureSettings', 'joinTime', parseInt(actionArg2));
                }

                /**
                 * @commandpath adventure set cooldown [seconds] - Set cooldown time
                 */
                if (actionArg1.equalsIgnoreCase('coolDown')) {
                    if (isNaN(parseInt(actionArg2))) {
                        $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                        return;
                    }
                    coolDown = parseInt(actionArg2);
                    $.inidb.set('adventureSettings', 'coolDown', parseInt(actionArg2));
                }

                /**
                 * @commandpath adventure set gainpercent [value] - Set the gain percent value
                 */
                if (actionArg1.equalsIgnoreCase('gainPercent')) {
                    if (isNaN(parseInt(actionArg2))) {
                        $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                        return;
                    }
                    gainPercent = parseInt(actionArg2);
                    $.inidb.set('adventureSettings', 'gainPercent', parseInt(actionArg2));
                }

                /**
                 * @commandpath adventure set minbet [value] - Set the minimum bet
                 */
                if (actionArg1.equalsIgnoreCase('minBet')) {
                    if (isNaN(parseInt(actionArg2))) {
                        $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                        return;
                    }
                    minBet = parseInt(actionArg2);
                    $.inidb.set('adventureSettings', 'minBet', parseInt(actionArg2));
                }

                /**
                 * @commandpath adventure set maxbet [value] - Set the maximum bet
                 */
                if (actionArg1.equalsIgnoreCase('maxBet')) {
                    if (isNaN(parseInt(actionArg2))) {
                        $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.usage'));
                        return;
                    }
                    maxBet = parseInt(actionArg2);
                    $.inidb.set('adventureSettings', 'maxBet', parseInt(actionArg2));
                }

                /**
                 * @commandpath adventure set warningmessages [true / false] - Sets the per-user warning messages
                 */
                if (actionArg1.equalsIgnoreCase('warningmessages')) {
                    if (args[2].equalsIgnoreCase('true')) warningMessage = true, actionArg2 = $.lang.get('common.enabled');
                    if (args[2].equalsIgnoreCase('false')) warningMessage = false, actionArg2 = $.lang.get('common.disabled');
                    $.inidb.set('adventureSettings', 'warningMessage', warningMessage);
                }

                /**
                 * @commandpath adventure set entrymessages [true / false] - Sets the per-user entry messages
                 */
                if (actionArg1.equalsIgnoreCase('entrymessages')) {
                    if (args[2].equalsIgnoreCase('true')) enterMessage = true, actionArg2 = $.lang.get('common.enabled');
                    if (args[2].equalsIgnoreCase('false')) enterMessage = false, actionArg2 = $.lang.get('common.disabled');
                    $.inidb.set('adventureSettings', 'enterMessage', enterMessage);
                }
                
                /**
                 * @commandpath adventure set cooldownannounce [true / false] - Sets the cooldown announcement
                 */
                if (actionArg1.equalsIgnoreCase('cooldownannounce')) {
                    if (args[2].equalsIgnoreCase('true')) coolDownAnnounce = true, actionArg2 = $.lang.get('common.enabled');
                    if (args[2].equalsIgnoreCase('false')) coolDownAnnounce = false, actionArg2 = $.lang.get('common.disabled');
                    $.inidb.set('adventureSettings', 'coolDownAnnounce', coolDownAnnounce);
                }

                $.say($.whisperPrefix(sender) + $.lang.get('adventuresystem.set.success', actionArg1, actionArg2));
            }
        }
    });

    /**
     * @event initReady
     */
    $.bind('initReady', function() {
        $.registerChatCommand('./games/adventureSystem.js', 'quest', 7);
        $.registerChatSubcommand('quest', 'set', 1);
        $.registerChatSubcommand('quest', 'top5', 3);

        loadStories();
    });

    $.reloadAdventure = reloadAdventure;
})();