I made a dice roll command with different outcomes, each outcome depending of the dice result obtained. This was all done for twitch bot for fun
Below the code used:
if (message == '!roll') {
client.say(channel, `@${userstate.username} A goblin appears before you, ready to attack. Roll a d20.`);
const num = rollDice();
client.say(channel, `You rolled ${num}`);
//console.log(`* Executed ${commandName} command`);
if (num == 1){
client.say(channel,`@${userstate.username} You shit yourself and die of dehydration... Wow.`);
}
if (1<num && num<11){
client.say(channel, `@${userstate.username} The Goblin destroys you. You died.`);
}
if (10<num && num<20){
client.say(channel, `@${userstate.username} You fought the goblin bravely and are victorious. You Win!`);
}
if (num == 20){
client.say(channel, `@${userstate.username} The goblin immediatly falls in love with your beauty and you get married! Good Ending! Pog `);
}
}
});
// Function called when the "dice" command is issued
function rollDice() {
const sides = 20;
return Math.floor(Math.random() * sides) + 1;
}
As you can see, I want the bot to output the starting story,the dice output the user rolled and then the outcome of that dice roll. But currently all these things are printed seperately.
I want to make all these things output in a single line, just don’t know how.
I tried modifiying the code, putting all the conditions under a single function and print the output of that single function, but didn’t work.
>Solution :
All you have to do is create an empty string and append the texts that you want to output. Once all the text has been appended to the variable, you can send it to the channel.
Thus the modified code becomes
let output = '';
if (message == '!roll') {
output += `@${userstate.username} A goblin appears before you, ready to attack. Roll a d20.`;
const num = rollDice();
output += '\n';
output += `You rolled ${num}`;
if (num == 1){
output += `@${userstate.username} You shit yourself and die of dehydration... Wow.`;
}
if (1<num && num<11){
output += `@${userstate.username} The Goblin destroys you. You died.`;
}
if (10<num && num<20){
output += `@${userstate.username} You fought the goblin bravely and are victorious. You Win!`;
}
if (num == 20){
output += `@${userstate.username} The goblin immediatly falls in love with your beauty and you get married! Good Ending! Pog `
}
}
client.say(channel, output);
});
// Function called when the "dice" command is issued
function rollDice() {
const sides = 20;
return Math.floor(Math.random() * sides) + 1;
}