Trouble generating a random number between 0 and 10 - javascript

I'm working in a discord bot, specifically in a rate command, which is supposed to return:
"I would rate (thing to be rated) (random number)/10."
But it returns:
"I would rate (thing to be rated) [object Undefined]/10."
client.on('message', message => {
if(message.content.startsWith (prefix + "rate")) {
if(message.content.slice(prefix.length + 4) === ""){
message.channel.send("Give me something to rate");
}
else
message.channel.send("I would rate" + "**" +
message.content.slice(prefix.length + 4) + "**" + " " +
toString(Math.floor(Math.pow(Math.random, 10))) + "/10");
}
What can possibly be wrong?

You need to incorporate the following code (considering you want round integers returned):
Math.floor(Math.random()*11)
Ditch the Math.pow() method.
edit made from suggestion by #Geert-Jan

Related

Math.random returning same value when console logged javascript [duplicate]

This question already has answers here:
Why does generating a random number outside of a loop, causes it to be always the same?
(2 answers)
Closed 1 year ago.
here is my code
// import user input prompt
var inquirer = require('inquirer');
var emptyFamArray = [];
// ask the user how many relatives do they have
const getQuestions = () => {
inquirer.prompt([
{
name: "relatives_names",
type: 'input',
message: "Please input family first names seperated by a space. only 1-10 family members please!",
},
]).then((answers => {
// console.log(answers)
let test1 = JSON.stringify(answers.relatives_names).split(' ');
// console.log(test1);
let randomArrayName = test1[Math.floor(test1.length * Math.random())]
let randomArrayNameTwo = test1[Math.floor(test1.length * Math.random())]
console.log(randomArrayName)
if(test1.length > 10){
console.log('to many names please input 10 or less')
} else if (test1.length == 9){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
}else if (test1.length == 5){
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
console.log(randomArrayName + " Gets " + randomArrayNameTwo + " for christmas pickings!");
when it console logs it does randomise the names but it only returns the same value over and over
example
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
kylee Gets gerald for christmas pickings!
how would I fix this? im stuck and not entirly sure how to make the variables random everytime when logged
Thanks
When you are printing to the console the random selection have already happened and it happens only ones before you print out the names.
To make it select a random name each time , convert the selection to a function which you will call every time you want to print to console. For example:
var selectRandomName = function(names) {
return names[Math.floor(names.length * Math.random())]
}
console.log(selectRandomName(names) + " GETS " + selectRandomName(names) + " for Christmas pickings!");
Obviously this is oversimplified and you probably should also prevent selection of the same name twice and other similar cases, but this is out of the scope of current question. I assume this is some sort of exercise, as in real world application you should use some readily available matching libraries.

Discord bot send messages specific channel error

I want the message to be sent to a specific channel when I give the command. I want the user to encounter an error if the command was not run on a particular channel. I need your help.
if (msg.author.bot) return;
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 100;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
client.channels.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
}
Error: TypeError: client.channels.get is not a function
Since discord.js v12 you need to use the cache property to access channels collection, so you need to replace
client.channels.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
with
client.channels.cache.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})

Discord Random Image Bot spamming

I prepared an sending random images discord bot. bot works smoothly but instead of just sending an image, it randomly sends all images in the folder. I need your help.(12 images available, prefix: !! ) codes;
const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');
var prefix = settings.prefix;
client.on('ready', () => {
console.log(`${client.user.tag} ready!`);
});
client.on('message', msg => {
if (msg.content.toLowerCase() === prefix + 'xgif' )
number = 12;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
});
client.login(TOKEN HERE)
You have numerous problems leading to this. First, your if statement isn't scoped properly. Your code is the functional equivalent of:
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 12;
}
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
So what is happening is number is not always set to 12, and the last two lines execute with every single message, including messages that come from the bot itself. You need to:
1. scope your if statement correctly.
2. ignore all bot message.
client.on('message', msg => {
if(msg.author.bot) return; // Ignore bots!
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 12;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
} // End of if scope
}
Unlike Python, for one example, JavaScript and all other C-style syntax languages do not use white space to indicate scope. An if statement with no brackets only includes the next single statement in it's scope.

Random Count in a "return" without many code

I google for a solution that allows me to generate a random number between 1 and 6. i found this: http://www.w3schools.com/jsref/jsref_random.asp
Now i tryed to use it in my code:
$scope.getUserImage = function (user) {
if (user.avatar) {
return user.avatar;
} else {
return '/images/icons/user-' + user.gender((Math.random() * 6) + 1) + '.svg';
}
};
but with this i get a error, it means that the user.gender isnt any function. I know this is a realy very basic question. I started new with JavaScript. I am a Designer normaly.
Since you want to add the strings together (called 'concatenate' since we're talking about strings), separate each with a + symbol. But the 1-6 logic is also wrong, you'll need to round those numbers down.
$scope.getUserImage = function (user) {
if (user.avatar) {
return user.avatar;
} else {
var randomNumberOneToSix = Math.floor(Math.random() * 6 + 1);
return '/images/icons/user-' + user.gender + randomNumberOneToSix + '.svg';
}
};
Bonus tip: w3schools is not a great resource. Add 'mdn' to every search and use Mozilla's excellent documentation for learning about web technologies.
You miss a "+" to concat gender change this line
return '/images/icons/user-' + user.gender((Math.random() * 6) + 1) + '.svg';
to
return '/images/icons/user-' + user.gender + ((Math.random() * 6) + 1) + '.svg';

Javascript While Loop Returning Strange Results

I apologize in advance if there are several things wrong with my code; I'm still very new to this.
I made a simple little RNG betting game, which follows:
var funds = 100;
var betting = true;
function roll_dice() {
var player = Math.floor(Math.random() * 100);
var com = Math.floor(Math.random() * 100);
var bet = prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign.");
if (player === com) {
alert("tie.");
}
else if (bet > funds) {
alert("You don't have that much money. Please try again");
roll_dice();
}
else if (player > com) {
funds += bet;
alert("Your roll wins by " + (player - com) + " points. You get $" + bet + " and have a total of $" + funds + ".");
}
else {
funds -= bet;
alert("Computer's roll wins by " + (com - player) + " points. You lose $" + bet + " and have a total of $" + funds + ".");
}
}
while (betting) {
var play = prompt("Do you wish to bet? Yes or no?");
if (funds <= 0) {
alert("You have run out of money.");
betting = false;
}
else if (play === "yes") {
roll_dice();
}
else {
alert("Game over.");
betting = false;
}
}
The code deals with losing (i.e. subtraction) just fine, but can't seem to handle the addition part. If you bet, say, 50 and win, you'll wind up with 10050. Aside from never seeking out a job as a gambling software programmer, what should I do?
prompt returns a string. Adding a number to a string results in a string:
> "12" + 13
"1213"
While subtraction results in an integer, as only string concatenation is done with a plus sign:
> "12" - 13
-1
You need to convert your user's input into an integer:
var bet = parseInt(prompt("How much do you bet? Enter a number between 1 and " + funds + " without the $ sign."), 10);

Categories

Resources