硬币翻转命令只提供'tails'和'you loose'



我试图制作一个硬币翻转命令,用户输入.cf heads,机器人向他显示他的答案,结果以及他们是赢还是输。

我尝试使用args但没有它,但它不起作用;我的代码中有一个错误:

bot.on('message', message => {
const prefix = '.';
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/  +/g)
const cmd = args.shift().toLowerCase();
var choice = 'h';
if (args[1] != undefined)
args[1] = args[1].toLowerCase();
if (args[1] == 'heads' || args[1] == 'h' || args[1] == 'head')
choice = 'h';
else if (args[1] == 'tails' || args[1] == 't' || args[1] == 'tail')
choice = 't';
if (cmd === 'cf' || cmd === 'coin' || cmd === 'flip' || cmd ===
'coinflip') {
var coins = [
"heads",
"tails"
];
coinz = coins[Math.floor(Math.random() * coins.length)];
if (choice != coinz) {
message.channel.send(`Your bet: `${args[1]}`, 
outcome: `${coinz}` you lose`);
} else {
message.channel.send(`Your bet: `${args[1]}`, 
outcome: `${coinz}` you win`);
};
};
});

代码有效,但它给了我 100% 的损失,有时${args[1]}是未定义的,尽管我输入了headshhead;${coinz}每次都是尾巴。

回答收集我的原始评论。

关于 100% 的损失率:要决定是赢还是输,您可以将您的选择变量与 coinz 进行比较。但是,在您的代码中,">选择"只能是">h"或"t",而"coinz"将是">heads">"tails"。这种比较总是会返回 false,告诉你这是一种损失。

关于未定义的$args[1]: args[1] undefined来自您的args.shift()调用。移动数组会从该数组中删除第一个元素,因此一旦提取了"cmd"变量,您的参数现在就存储在 args[0] 中。 我在这里解决这个问题的方法是将一个cmdvar 存储为args[0],将一个choicevar 存储为args[1],没有移位。 另请注意,您仍然可能会遇到错误,因为您的测试:

if (args[1] != undefined)
args[1] = args[1].toLowerCase();

没有括号,这意味着无论条件是否通过,以下行都将运行,这意味着即使它不存在,您也会尝试访问 args[1]。您应该将以下所有代码包装在{ }中,因为它取决于args[1]变量:

client.on('message', message => {
const prefix = '.';
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const cmd = args[0].toLowerCase();
console.log(`CMD : ${cmd}`);
// Little optimization here, check for the command before doing anything else.
if (cmd === 'cf' || cmd === 'coin' || cmd === 'flip' || cmd === 'coinflip') {
if (args[1] != undefined) {
let choice = args[1].toLowerCase();
console.log(`choice : ${choice}`);
if (choice == 'heads' || choice == 'h' || choice == 'head') {
choice = 'heads';
}
else if (choice == 'tails' || choice == 't' || choice == 'tail') {
choice = 'tails';
}

var coins = [
"heads",
"tails"
];
coinz = coins[Math.floor(Math.random() * coins.length)];
if (choice != coinz) {
message.channel.send(`Your bet: `${choice}`,
outcome: `${coinz}` you lose`);
} else {
message.channel.send(`Your bet: `${choice}`,
outcome: `${coinz}` you win`);
};
}
else {
message.reply("please choose *heads* or *tails* before the coin flip.");
}
}

});

似乎要决定以太币是赢还是输,您将您的选择变量与coinz进行比较。但是,在您的代码中,"选择"只能是"h"或"t",而"coinz"将是"heads"或"tails"。这种比较总是会返回 false,告诉你这是一个损失@Gruntzy

相关内容

最新更新