python - 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')
解决方案
这是您的代码的重写,我修复了一些无用的 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.send
I also added tie 选项下的 bot_choice 不同。
推荐阅读
- c++ - 在第二个构造函数 Matrix3D 中切换索引。例如,为什么 n[0][1] = n10?
- ruby - 如何在 Ruby 中测试自定义 Bugsnag meta_data?
- prolog - 你会如何在 Prolog 中表达事实的互斥?
- java - 如何在数据库中插入一行?
- pipenv - 为什么 pipenv 在名称末尾添加扩展名?
- javascript - 在页面直接到另一个页面后将类添加到 div
- javascript - 以分层/树格式打印 JSON 对象
- javascript - React 服务器组件在 SEO 上的性能
- javascript - 登录后单击硬件后退按钮导航到登录页面如何在离子4中防止它
- python - Python中矩阵铅笔的主要广义特征向量