You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord.js小游戏中根据胜负修改点击按钮的颜色

解决按钮颜色切换问题

要让用户点击的按钮根据小游戏胜负结果切换为绿色(成功)或红色(失败),你可以利用Discord.js提供的ButtonStyle枚举:

  • 绿色对应ButtonStyle.Success
  • 红色对应ButtonStyle.Danger
  • 其余按钮保持灰色(ButtonStyle.Secondary)并禁用,这样用户能清晰区分自己点击的选项。

修改后的完整代码如下:

const { ActionRowBuilder, ButtonBuilder, ButtonStyle, ComponentType, EmbedBuilder } = require('discord.js');

module.exports = {
    name: 'basketball',
    aliases: ['bball'],
    description: 'Starts the basketball minigame.',
    run: async (client, message, args) => {
        const winArray = ['Nice shot, mate!', 'Deep three, swish!', 'Look at you go, Stephen Curry up in here.', 'Great shot!', 'At the buzzer... GOOOOOOD!', 'You\'re going places, what a shot!', 'Golden, Well done.'];
        const loseArray = ['So close, but so far away', 'Close, but no cigar..', 'Nearly made it', 'Keep trying, you\'ll make it eventually', 'Wow, you got denied', 'Durant could have made that shot...', 'Don\'t give up, mate :/', 'Maybe try a different time?'];
        
        const positions = {
            left: '_ _🗑️🗑️🗑️\n_ _🕴️\n      \n_ _      🏀',
            middle: '_ _🗑️🗑️🗑️\n_ _     🕴️\n      \n_ _      🏀',
            right: '_ _🗑️🗑️🗑️\n_ _           🕴️\n      \n_ _      🏀',
        };
        
        let randomized = Math.floor(Math.random() * Object.keys(positions).length);
        let gameEnded = false;
        let randomPos = positions[Object.keys(positions)[randomized]];
    
        let leftButton = new ButtonBuilder()
            .setLabel("Left")
            .setCustomId('left')
            .setStyle(ButtonStyle.Secondary);
        
        let middleButton = new ButtonBuilder()
            .setLabel("Middle")
            .setCustomId('middle')
            .setStyle(ButtonStyle.Secondary);
        
        let rightButton = new ButtonBuilder()
            .setLabel("Right")
            .setCustomId('right')
            .setStyle(ButtonStyle.Secondary);
        
        const msg = await message.reply({ content: randomPos, components: [new ActionRowBuilder().addComponents(leftButton, middleButton, rightButton)] });
        
        function update() {
            randomized = Math.floor(Math.random() * Object.keys(positions).length);
            randomPos = positions[Object.keys(positions)[randomized]];
            msg.edit({ content: randomPos, components: [new ActionRowBuilder().addComponents(leftButton, middleButton, rightButton)] });
        }
        
        setInterval(() => {
            if(!gameEnded) update();
        }, 2000);
    
        const filter = button => button.user.id === message.author.id;
        
        const button = await msg.awaitMessageComponent({ filter, componentType: ComponentType.Button, max: 1 });

        gameEnded = true;
        // 先禁用所有按钮,防止重复操作
        leftButton.setDisabled(true);
        middleButton.setDisabled(true);
        rightButton.setDisabled(true);

        // 根据胜负设置点击按钮的颜色
        const correctId = Object.keys(positions)[randomized];
        let feedbackMsg = '';
        if (button.customId === correctId) {
            // 猜对,按钮设为绿色
            switch(button.customId) {
                case 'left': leftButton.setStyle(ButtonStyle.Success); break;
                case 'middle': middleButton.setStyle(ButtonStyle.Success); break;
                case 'right': rightButton.setStyle(ButtonStyle.Success); break;
            }
            feedbackMsg = winArray[Math.floor(Math.random() * winArray.length)];
        } else {
            // 猜错,按钮设为红色
            switch(button.customId) {
                case 'left': leftButton.setStyle(ButtonStyle.Danger); break;
                case 'middle': middleButton.setStyle(ButtonStyle.Danger); break;
                case 'right': rightButton.setStyle(ButtonStyle.Danger); break;
            }
            feedbackMsg = loseArray[Math.floor(Math.random() * loseArray.length)];
        }

        await button.deferUpdate();
        await button.editReply({ content: randomPos, components: [new ActionRowBuilder().addComponents(leftButton, middleButton, rightButton)] });
        await message.reply({ content: feedbackMsg, allowedMentions: { repliedUser: true } });
    },
};

关键修改说明:

  1. 修正胜负判断逻辑:原代码中胜负判断颠倒,现在改为点击的ID匹配正确位置时显示胜利消息,符合常规游戏逻辑
  2. 按钮颜色动态设置:通过switch语句匹配用户点击的按钮ID,将对应按钮样式切换为绿色或红色
  3. 统一禁用逻辑:先禁用所有按钮,再单独修改点击按钮的颜色,既阻止重复操作,又清晰标记用户的选择

内容的提问来源于stack exchange,提问作者Roman Beard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:36:17