Multiple “inline” rolls

问题: I'm trying to build a randomizer that will replace a typical #d# (for those of you familiar with D&D) with an actual numerical output. I've got most of it figured out,...

问题:

I'm trying to build a randomizer that will replace a typical #d# (for those of you familiar with D&D) with an actual numerical output. I've got most of it figured out, but can't for the life of me, figure out how to get this to output when there are multiple #d# items in the array. Below is a snippet of the code I'm using. You'll notice that for the #d# sections I'm using RegEx to replace the items, for example:

Original string - "bland. Hunger mushroom, makes you hunger for more mushrooms for the next <roll-1d4> hours"

Output after RegEx - "The mushroom tastes bland. Hunger Mushroom, makes you hunger for more mushrooms for the next 3 hours."

That works perfectly fine, my problem lies in this part:

Original string - "like shiitake. <roll-1d4> mushrooms sprout from your body. The grant <roll-1d4> temporary HP if eaten by anyone other than you for the next <roll-1d4> hours."

Output after RegEx - "The mushroom tastes like shiitake. 2 mushrooms sprout from your body. They grant temporary HP if eaten by anyone other than you for the next hours." - Notice the blank spaces in front of the "temporary HP" and "next hours" parts.

Any ideas on how I can correct this?

Code Snippet here

<!DOCTYPE html>
<html>
<head>

    <title>
        Random Table Generators
        </title>
</head>
<body>

    <h1>Clear Screen</h1>

<p>This is so you can clear the screen from all the random tables you rolled. This will make room for more table rolls.</p>

    <div>
        <input type="button" id="btnSearch" value="Clear Screen" onClick="clearMe();" /> 
    </div>

<h1>Utility</h1>

<p>This is where most of the randomness comes out. You can find books, trinkets, food menues, junk, even random races, classes, or monsters for an Arrow of Slaying that someone finds...</p>

    <div>
        <input type="button" value="Mushrooms" onClick="getMushrooms();" />
</div>



    <p class="clear" id="mushroom"></p>

<!---Begin JavaScript here--->

<script type="text/javascript">

    //Mushroom Randomizer

function chooseMushroom()
{
    var mushroom = ["bland. Hunger mushroom, makes you hunger for more mushrooms for the next <roll-1d4> hours", "like gold", "like grapes. You can see in total darkness, but bright light blinds you for the next <roll-1d4> hours", "like milk", "like gum. You laugh long and loudly at the next sentence you hear, regardless of the content", "like mushrooms. Your size increases by one category until you take any damage", "like chicken. Add Chaotic to your alignment, even if it's already present for the next <roll-1d4> hours", "like tapioca. You can speak with oozes & puddings, but not with elves for the next <roll-1d4> hours", "bitter. Everything you intend to convey is tinged with sarcasm for the next <roll-1d4> hours", "like rancid celery", "like cheap gin. You take <roll-1d6> points of damage and gain <roll-1d12> temporary HP", "like nothing. It has no taste", "like chalk. You've forgotten everyone's name in your party for the next <roll-1d4> hours", "like copper coins", "like magic", "like chai. You can't sleep today or tomorrow. (this  will cause you to gain 2 levels of exhaustion. This effect stacks if you eat more than one of these mushrooms at a time)", "like sulfur, or maybe eggs.", "like tears. You receive a vision from <roll-1d10> minutes in the future", "like tree bark", "like your own tongue", "minty. Any flame you see appears green", "like raw lobster", "like gin. You can see invisible objects and entities for the next <roll-1d4> hours", "like a sweet cake", "like medicine. You gain a form of limited telepathy, which only allows you to know another creatures' opinion of you for the next <roll-1d4> hours", "like the far realm. INDESCRIBABLE", "like oatmeal. You become incredibly sentimental for the next <roll-1d4> hours", "like chamomile. You have the effects of the Sleep spell cast on you", "like your first kiss. You sweat uncontrollably until you ingest another mushroom", "like cotton. You're convinced you have a fly speed of 30 for the next <roll-1d4> hours", "like water. You  can't experience intense emotions for the next <roll-1d4> hours", "like bones. You attract undead in a 100 mile radius for the next <roll-1d4> hours", "like vegemite. You are quite unpalatable to purple worms for the next <roll-1d4> hours", "like dirt", "like plastic. For the next 5 minutes you are clearly aware of your true nature as a D&D player character", "like Dwarf", "like shiitake. <roll-1d4> mushrooms sprout from your body. They grant <roll-1d4> temporary HP if eaten by anyone other than you for the next <roll-1d4> hours", "like apple pie. You smell and taste delicious to everything for the next <roll-1d4> hours", "like Dragon Turtle", "like coffee. For 10 minutes, you share all your senses with the last creature to have eaten this type of mushroom", "like ash", "like paper. You suffer a terrible thirst that can only be quenched with magically created water", "like blubber. The hair on your head turns white and starts to grow 1 inch per minute, even if you don't normally have hair for the next <roll-1d4> hours", "like ozone. Your voice takes on a deep an terrifying tone for the next <roll-1d4> hours", "like citrus", "like cilantro. You hear music that portends unfolding events for the next <roll-1d4> hours", "like fertilizer", "like beets. You regain <roll-1d8> HP per hour that you are buried in soil for the next <roll-1d4> hours", "like old leather", "like fabric. If you stare into someone else's eyes for 1 solid hour you can see the nature of their death", "like seaweed", "like soybeans. None of your attacks, magical or otherwise, can be executed unless you state their name first for the next <roll-1d4> hours", "like tree sap", "smoky. You can squeeze through any opening without penalty for the next <roll-1d4> hours", "like cold honey", "like soap. You become increasingly buoyant for the next <roll-1d4> hours", "like beef jerky", "like marshmallow. A large, soft fungal growth sprouts from your body. You may change its shape at-will for the next <roll-1d4> hours", "like green onions. You can hear the song of all mushrooms. A Constitution saving throw is required every 10 minutes not to sing along for the next <roll-1d4> hours", "like watermelon. The next time you take a long rest, you will awaken to find an inanimate fungal clone of your body lying beside you for the next <roll-1d4> hours", "like tobacco", "sour. You can tell the emotional residue on an object by licking it for the next <roll-1d4> hours", "like crickets", "like strawberry. You enter a deathlike state for <roll-1d6> minutes", "like grass", "like sugar. <roll-1d12> of your teeth fall out and are replaced by fangs for the next <roll-1d4> hours", "like mold. You become encased in a fungal layer, improving your AC by 1 and reducing your speed by 10 for the next <roll-1d4> hours", "like poison, but is perfectly safe to eat", "like butter", "like charcoal. You spiders of all kinds are very attracted to you for the next <roll-1d4> hours", "like gingerbread", "like blood. You regain <roll-1d10> HP for every hour you spend in total darkness, but exposure to sunlight causes you to suffer <roll-1d6> damage per minute exposed for the next <roll-1d4> hours", "like popcorn", "zesty. Your speed doubles, but you must move the entire distance when you take your move action for the next <roll-1d4> hours", "like baked beans", "like a fruit gummy. You can be knocked unconscious, but can't be killed by any damage other than fire or acid for the next <roll-1d4> hours", "like apples. You cannot tell a lie for the next <roll-1d4> hours", "like Kobold pie", "like escargot. You walk at half speed, but can crawl at full speed for the next <roll-1d4> hours", "like BBQ. Eating this mushroom will kill you in <roll-3d20> years"];

    var randomMushroom0 = pickRandomMessage(mushroom);

    return randomMushroom0;
}

function getMushrooms()
{
    var randMushroom = "The mushroom tastes " + chooseMushroom() + "." + "<br>";

    document.getElementById("mushroom").innerHTML += randMushroom;

    return randMushroom;
}

function pickRandomMessage(messagePool){
    var messageIndex = rand(0, messagePool.length-1);
    var message = messagePool[messageIndex];
    var rollPlaceholder = message.match(/<roll-([1-9][0-9]*)d([1-9][0-9]*)>/);
    if (rollPlaceholder !== null) {
        var die = parseInt(rollPlaceholder[1], 10);
        var sides = parseInt(rollPlaceholder[2], 10);
        var rollTotal = 0;
        for (var i = 0; i < die; i++) {
            rollTotal += rand(1, sides);
        }
        message = message.replace(rollPlaceholder[0], rollTotal);
    }
    return message;
}

function rand(min, max) {
    min = parseInt(min, 10);
    max = parseInt(max, 10);
    if (max < min) {
        var temp = max;
        max = min;
        min = temp;
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


function clearMe()
{
    var cleared = document.getElementsByClassName("clear");
    var i;
    for (i = 0; i <= cleared.length-1; i++) {
        cleared[i].innerHTML = " ";
    }
} 

</script>i

</body>
</html>

EDIT: - Added actual code instead of external link. I also tried the g flag, but all that does is make the first roll have a 0 for the output and still blanks for the rest.


回答1:

You could use the g flag with your regex, which will make it match all occurrences in the string (not only the first one). Then, as a second argument, give it a function that will return a random number each time. Something like (simplified) :

let message = "like shiitake. <roll-1d4> mushrooms sprout from your body. The grant <roll-1d4> temporary HP if eaten by anyone other than you for the next <roll-1d4> hours."

const regex = /<roll-([1-9][0-9]*)d([1-9][0-9]*)>/g

message = message.replace(regex, () => Math.floor(1 + Math.random() * 20))

console.log(message)

  • 发表于 2019-03-17 06:53
  • 阅读 ( 101 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除