我试图做出一个硬币翻转命令,其中用户键入.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]}
,heads
或h
,但有时head
是不确定的; ${coinz}
每次都是尾巴。
答案 0 :(得分:1)
回答我的原始评论。
关于100%的丢失率: 要确定是赢还是输,您可以将选择变量与coinz进行比较。但是,使用您的代码,“选择” 只能是“ h” 或“ t” ,而“ coinz”将是 “头部” 或“尾巴” 。此比较将始终返回false,告诉您这是损失。
关于未定义的$ args [1]:
args [1]未定义来自您的args.shift()
调用。移位数组会从该数组中删除第一个元素,因此,一旦提取了“ cmd”变量,您的参数现在将存储在args [0]中。
我在这里解决此问题的方法是将一个cmd
变量存储为args[0]
,将一个choice
变量存储为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.");
}
}
});
答案 1 :(得分:0)
您似乎想决定以太坊是赢还是输,您将选择变量与coinz进行比较。但是,对于您的代码,“选择”只能是“ h”或“ t”,而“ coinz”将是“头”或“尾”。此比较将始终返回false,告诉您@Gruntzy造成的损失