Home > OS >  Using fewer if statements
Using fewer if statements

Time:02-11

I am trying to code the game One Night Ultimate Werewolf for Discord. I already figured out the first steps, of choosing cards, and sending roles through direct messages. The next step, is to create commands through DM, such as "!seer " for the seer to do her action. The problem is: I don't know how to make the bot check if the message author is actually a seer. I was thinking on doing the following: the variables dargon, ven, rocky, etc. are player names, where they have their player IDs stored. The variables dargon_c, ven_c, rocky_c, etc. have the players' Werewolf cards assigned to them.

  try:
    global dargon_c, ven_c, nastith_c, rocky_c, petra_c, center_c, left_center_c, right_center_c
    target = await bot.fetch_user(dargon)
    await target.send('Your card is: '   cards[0])
    dargon_c = cards[0]

    target = await bot.fetch_user(ven)
    await target.send('Your card is: '   cards[1])
    ven_c = cards[1]

    target = await bot.fetch_user(nastith)
    await target.send('Your card is: '   cards[2])
    nastith_c = cards[2]

    target = await bot.fetch_user(rocky)
    await target.send('Your card is: '   cards[3])
    rocky_c = cards[3]

    target = await bot.fetch_user(petra)
    await target.send('Your card is: '   cards[4])
    petra_c = cards[4]

    center_c = cards[5]
    left_center_c = cards[6]
    right_center_c = cards[7]

  except:
    ctx.channel.send("Some users didn't recieve their cards")

dargon_c = 'Seer'

@bot.command()
async def seer(ctx):
  global see
  if ctx.author.id == dargon and dargon_c == 'Seer':
    ctx.channel.send('Card')
  if ctx.author.id == ven and ven_c == 'Seer':
    see = ctx.content[3:]
    ctx.channel.send('Card')

Is there any way I could do this without needing to do 100 if blocks for every single command?

CodePudding user response:

Try using a list. The format looks like this:

Remember that list indexes start with 0, and go up.

So if the list is ["hello", "world] then [0] is hello and [1] is world.

myCards = [
    ["dargon", 0],
    ["ven",1]
]

for i in myCards:
    target = await bot.fetch_user(i[0])
    await target.send('Your card is: '   cards[1])

Alternatively and even better, put all this content in a json file and have the bot read from that.

{
    "dargon_c": { "name": "dargon", "index": 0},
    "ven_c": { "name": "ven", "index": 1},
}

json.load(open('path/to/file.json', 'r'))["dargon_c"]["name"] # "dargon"
  • Related