Help with a custom command for a random outcome with random strings

I wanted to make a DnD style attack command, where one user can attack another user with a d20 die roll.
Example

$(user) `is a formidable` $(z) `whos rolling` $(y) `to hit` $(touser) `armor class of` $(x) `with a` $(a) , $(touser)
if y > x user has died dead
else if y < x user is still alive

This code works but i am wondering if theres more cleaner way to write it and compare z to y, depending on the number if higher or lower to have different string output?

$(user) is a formidable $(eval z=["warrior", "evil mage", "new challenger", "poor pleb"];z[Math.floor(Math.random()*z.length)]) whos rolling $(eval y=Math.floor((Math.random() * 20) + 1)) to hit $(touser) armor class of $(eval x=Math.floor((Math.random() * 20) + 1)) with $(eval a=["a sword", "an axe", "a staff", "a rock", "a bow", "a pin", "a puppy", "a hug", "a gentle touch", "a burp", "a spit", "a catapulted animal"];a[Math.floor(Math.random()*a.length)])

Hey @rongyao!

Yes, there’s a cleaner way to write your code: you can combine everything into one $(eval), although I don’t understand what you mean by

since z here is a string, and y is an integer, so I assume you’re talking about x and y.

Anyway, here’s a way to write a cleaner code, and include your if statement:

$(eval c=['warrior','evil mage','new challenger','poor pleb'];w=['a sword','an axe','a staff','a rock','a bow','a pin','a puppy','a hug','a gentle touch','a burp','a spit','a catapulted animal'];r=()=>Math.floor(Math.random()*20)+1;s=a=>a[Math.floor(Math.random()*a.length)];x=r();y=r();`$(user) is a formidable ${s(c)} whos rolling ${x} to hit $(touser) armor class of ${y} with ${s(w)}. ${x>y?'$(user) is still alive':y>x?'$(user) has died dead':'It\'s a tie'}!`)

I had to remove the spaces for the code to fit under 500 characters, but here’s an easier to read version:

const classes = ['warrior', 'evil mage', 'new challenger', 'poor pleb'];
const weapons = ['a sword', 'an axe', 'a staff', 'a rock', 'a bow', 'a pin', 'a puppy', 'a hug', 'a gentle touch', 'a burp', 'a spit', 'a catapulted animal'];

const randomNumber = () => Math.floor(Math.random() * 20) + 1;
const randomItemArray = array => array[Math.floor(Math.random() * array.length)];

const roll = randomNumber();
const armorClass = randomNumber();

return `$(user) is a formidable ${randomItemArray(classes)} whos rolling ${roll} to hit $(touser) armor class of ${armorClass} with ${randomItemArray(weapons)}. ${roll > armorClass ? '$(user) is still alive' : armorClass > roll ? '$(user) has died dead' : 'It\'s a tie'}!`;

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.