首页 > 解决方案 > discord.py (rewrite) 如何为 rps(rock, paper, scissors) 游戏创建获胜条件?

问题描述

我正在尝试为石头剪刀布游戏制定获胜条件。我试过这样做,但它只是坏了,完全不起作用。这里有一些代码可以解决:

import discord
from discord.ext import commands, tasks
import os
import random
import asyncio
from asyncio import gather

@client.command()
async def rps(ctx, user_choice):
    rpsGame = ['rock', 'paper', 'scissors']
    if user_choice == 'rock' or user_choice == 'paper' or user_choice == 'scissors':
        await ctx.send(f'Choice: `{user_choice}`\nBot Choice: `{random.choice(rpsGame)}`')
        bot_choice = f'{random.choice(rpsGame)}'
    else:
        await ctx.send('**Error** This command only works with rock, paper, or scissors.')

    # Rock Win Conditions #
    if user_choice == 'rock' and bot_choice == 'paper':
        await ctx.send('I won!')
    if user_choice == 'rock' and bot_choice == 'scissors':
        await ctx.send('You won!')
    # Paper Win Conditions #
    if user_choice == 'paper' and bot_choice == 'rock':
        await ctx.send('You won!')
    if user_choice == 'paper' and bot_choice == 'scissors':
        await ctx.send('I won!')
    # Scissor Win Conditions #
    if user_choice == 'scissors' and bot_choice == 'paper':
        await ctx.send('You won!')
    if user_choice == 'scissors' and bot_choice == 'rock':
        await ctx.send('I won!')


client.run('token')

标签: pythondiscorddiscord.py-rewrite

解决方案


这是您的代码的重写,我修复了一些无用的 f 字符串,并在 rpsGame 中的 if 中移动了赢/输条件的user_choice缩进以防止variable referenced before assignment

@client.command()
async def rps(ctx, user_choice):
    rpsGame = ['rock', 'paper', 'scissors']
    if user_choice.lower() in rpsGame: # Better use this, its easier. [lower to prevent the bot from checking a word like this "rOcK or pApeR"
        bot_choice = random.choice(rpsGame)
        await ctx.send(f'Choice: `{user_choice}`\nBot Choice: `{bot_choice}`')
        user_choice = user_choice.lower() # Also prevent a random word such as "rOcK"
        if user_choice == bot_choice:
            await ctx.send('We tied')
        # Rock Win Conditions #
        if user_choice == 'rock' and bot_choice == 'paper':
            await ctx.send('I won!')
        if user_choice == 'rock' and bot_choice == 'scissors':
            await ctx.send('You won!')
        # Paper Win Conditions #
        if user_choice == 'paper' and bot_choice == 'rock':
            await ctx.send('You won!')
        if user_choice == 'paper' and bot_choice == 'scissors':
            await ctx.send('I won!')
        # Scissor Win Conditions #
        if user_choice == 'scissors' and bot_choice == 'paper':
            await ctx.send('You won!')
        if user_choice == 'scissors' and bot_choice == 'rock':
            await ctx.send('I won!')
    else:
        await ctx.send('**Error** This command only works with rock, paper, or scissors.')

您应该将 bot_choice 设置为 1 变量,这是唯一导致其损坏的因素,因为机器人发送的选项与ctx.sendI also added tie 选项下的 bot_choice 不同。


推荐阅读