iT邦幫忙

2023 iThome 鐵人賽

DAY 28
0
自我挑戰組

Python Discord Bot(DC機器人)系列 第 28

Python Discord Bot#28 - 做中學 - 做個終極密碼(三)

  • 分享至 

  • xImage
  •  

這篇會補全功能上的限制或處理,
像是輸到誰就只能誰來回答,
與錯誤處理,
或是回答過的不可以再使用。

流程

https://ithelp.ithome.com.tw/upload/images/20230927/20106071bXlcLdZYQr.png

開局時限制

  1. 判斷發起者與按下的人是否一樣
if interaction.user.id != self.author.id:
    await interaction.response.send_message("你不是發起者喔w", ephemeral=True)
  1. 當確認為已開始模式: 開局按鈕 disable=True
for child in self.children:
    if type(child) == discord.ui.Button:
         child.disabled = True

await interaction.response.edit_message(view=self)

https://ithelp.ithome.com.tw/upload/images/20230927/201060713a70z0Yn7u.png

遊戲進行中

  1. 判斷此局與按下的人是否為本人
if interaction.user.id != setting.playerList[setting.round]:
     return await interaction.response.send_message(f"還沒輪到你喔w", ephemeral=True)
  1. 輸入不對的值
try: playerInput = int(playerInput)
except: return await interaction.response.send_message(f"請輸入 {setting.minVal + 1}~{setting.maxVal} 的整數", ephemeral=True)

if playerInput < setting.minVal or playerInput > setting.maxVal:
    return await interaction.response.send_message(f"請輸入 {setting.minVal + 1}~{setting.maxVal} 的整數", ephemeral=True)

https://ithelp.ithome.com.tw/upload/images/20230927/20106071WfqswXxEQ5.png
https://ithelp.ithome.com.tw/upload/images/20230927/20106071zhHsDbR4ng.png

Code

import random
import discord
from discord.commands import Option


def main(Bot):
    name = "終極密碼"
    print(f"{name} 註冊成功")


    class GameNumberView(discord.ui.View):
        def __init__(self, author, maxValue, client):
            super().__init__()
            self.client = client
            self.answer = random.randint(1, maxValue)
            self.author = author
            self.playerList = []
            self.round = 0
            self.minVal = 1
            self.maxVal = maxValue
            self.playerList.append(author.id)

      
        class PlayerStart(discord.ui.View):
            def __init__(playerSelf, setting):
                super().__init__()
                playerSelf.setting = setting

            @discord.ui.button(label="輸入猜測數字", style=discord.ButtonStyle.success)
            async def player_start_callback(playerSelf, button, interaction):
                setting = playerSelf.setting
                await interaction.response.send_modal(setting.NumberGuess(title=f"從 {setting.minVal}~{setting.maxVal} 選一個整數", setting=setting))
                

        class NumberGuess(discord.ui.Modal):
            def __init__(modalSelf, title, setting):
                super().__init__(title=title)
                modalSelf.setting = setting
                modalSelf.add_item(discord.ui.InputText(label="整數數字", required=True))
  
            async def callback(modalSelf, interaction):
                setting = modalSelf.setting
                playerInput = modalSelf.children[0].value
                  
                if interaction.user.id != setting.playerList[setting.round]:
                    return await interaction.response.send_message(f"還沒輪到你喔w", ephemeral=True)
                      
                try: playerInput = int(playerInput)
                except: return await interaction.response.send_message(f"請輸入 {setting.minVal + 1}~{setting.maxVal} 的整數", ephemeral=True)

                if playerInput < setting.minVal or playerInput > setting.maxVal:
                    return await interaction.response.send_message(f"請輸入 {setting.minVal + 1}~{setting.maxVal} 的整數", ephemeral=True)

                if playerInput != setting.answer:
                    if playerInput < setting.answer:
                        setting.minVal = playerInput + 1
                    elif playerInput > setting.answer:
                        setting.maxVal = playerInput - 1

                    if (setting.round + 1) >= len(setting.playerList): setting.round = 0
                    else: setting.round += 1

                    await interaction.response.edit_message(view=None)
                    channel = setting.client.get_channel(interaction.channel_id)
                    await channel.send(f"<@{setting.playerList[setting.round]}> 開始猜,從 {setting.minVal}~{setting.maxVal} 選一個整數", view=setting.PlayerStart(setting))
                else: 
                    await interaction.response.send_message(f"BOOM!!! <@{interaction.user.id}> 中獎囉WWW")
              
        @discord.ui.button(label="點擊參加", style=discord.ButtonStyle.primary)
        async def button_callback(self, button, interaction):
          
            try: self.playerList.index(interaction.user.id)
            except: self.playerList.append(interaction.user.id)

            message = f"<@{self.author.id}>已開啟了一場「終極密碼」\n 已參加 : "
            for data in self.playerList: message += f"<@{data}> "
            message += f"\n確認好人數後,發起者按下開始w"
            await interaction.response.edit_message(content=message)
          

        @discord.ui.button(label="開始", style=discord.ButtonStyle.success)
        async def button_start_callback(self, button, interaction):
          
          if interaction.user.id == self.author.id:
              for child in self.children:
                  if type(child) == discord.ui.Button:
                      child.disabled = True

              await interaction.response.edit_message(view=self)
              channel = Bot.get_channel(interaction.channel_id)
              await channel.send(f"<@{self.playerList[self.round]}> 開始猜,從 {self.minVal}~{self.maxVal} 選一個整數", view=self.PlayerStart(self))
          else:
              await interaction.response.send_message("你不是發起者喔w", ephemeral=True)

  

    @Bot.slash_command(name=name, description="建立一個猜數字遊戲")
    async def create_game(ctx, number: Option(int, "猜數字的最大範圍1~N", name="最大值", min_value=2, required=True)):
      msg = f"<@{ctx.author.id}>已開啟了一場「終極密碼」\n 已參加 : <@{ctx.author.id}> \n確認好人數後,發起者按下開始w"
      await ctx.send_response(msg, view=GameNumberView(ctx.author, number, Bot))


上一篇
Python Discord Bot#27 - 做中學 - 做個終極密碼(二)
下一篇
Python Discord Bot#29- 貼圖反應 (一)
系列文
Python Discord Bot(DC機器人)31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言