0

I have a pretty simple array like this:

players = []

I want to check if username is exists in the array, if so, then the user shouldn't be added. I don't think iterating through the array would be the smartest approach, because it might be to big to run this everytime.

I also thought it might be an idea to use a dict, but never did that before so I don't know if that would solve my problem.

My Player-Class looks like this:

class Player:

    def __eq__(self, other):
        return self._username == other._username

    def __init__(self, x, y, name, sprite):
        # more stuff

The main problem is, that I need to access this array from two different function, which is why I probably can't check with if character in players

Have a look at the full code:

This is where I add the character to my array:

@commands.command(name='join')
async def join(self, ctx: commands.Context):
    character = Player(random.randint(100, 400), 210, ctx.author.display_name, random.choice(["blue", "red"]))
    if character not in players:
        await ctx.send(f'You are in, {ctx.author.name}!')
        players.append(character)
    else:
        await ctx.send(f'You are already in, {ctx.author.name}!')

Here where I want to check if the name already exists in the array, so it will either print "can quest" or "can't quest, not ingame yet"

@commands.command(name='quest')
async def quest(self, ctx: commands.Context):
    #check if player joined the game
    print(players)
    await ctx.send(f'{ctx.author.name} joined the quest!')

or similar?

DasSaffe
  • 2,080
  • 1
  • 28
  • 67
  • 2
    you can use `if character in players:` or use a set instead of list. set will only have unique values. – Nesi Jun 25 '23 at 16:17
  • Please share the definition of `Player` class – Zero Jun 25 '23 at 16:18
  • You should really learn how to use dicts. A dict keyed by username seems like the obvious choice here. The thing is, this site isn't built to teach the basics of a programming language, so I'd recommend doing a tutorial instead. – wjandrea Jun 25 '23 at 16:27
  • @DasSaffe Please post the whole definition of `Player`. We need to see if the username is accessible. Ideally, make a [mre]. – wjandrea Jun 25 '23 at 16:29
  • Possible duplicate: [Check if list of objects contain an object with a certain attribute value](/q/9371114/4518341) – wjandrea Jun 25 '23 at 16:32
  • How many players are on the list? – Kelly Bundy Jun 25 '23 at 18:18

3 Answers3

2

You can use any() and a comprehension expression:

if any(player.username == "Fred" for player in players)

This code will iterate over each item in the players list, checking if that player has a name of "Fred".

If it finds a match, it will stop iterating and return True.

If it does not find a match, it will return False.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • If you check out OP's code snippet, it is `_username`, not `username` which makes the attribute private. – Zero Jun 25 '23 at 17:08
  • 1
    @MohitGoyal At the time I posted this answer, OP had not yet provided the class definition. I assume they can adapt my code to their specific needs. – John Gordon Jun 25 '23 at 17:16
  • @MohitGoyal There is not really any such thing as "private" in python code. At best, it is a _suggestion_ on how to use the attribute. – John Gordon Jun 25 '23 at 17:17
0

You suggested using a dictionary. Here is how you would do it:

players = {}
# This is how you add a player
if user_name not in players:
    players[user_name] = Player(user_name)
else:
    print(f"{user_name} already exists")

The code below shows what the dictionary would look like

{'Michelle': Player('Michelle'), 'Raul': Player('Raul')}
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

You can use a dictionary instead of a list to check if a username exists in the players' array. Dictionaries provide faster lookup times compared to iterating through an array.

Example:

players = {}

# Adding players
username = "example"
if username not in players:
    character = Player(username)
    players[username] = character
    print("Player added successfully.")
else:
    print("Username already exists.")

# Checking if the username exists
username = "example"
if username in players:
    print("Username exists.")
else:
    print("Username does not exist.")

In this code, the players' dictionary uses the username as the key and the corresponding Player object as the value. When adding a player, it checks if the username already exists in the dictionary. A new player is created and added to the dictionary if it doesn't exist. If it does exist, the username is already taken, and the player is not counted.

When checking if a username exists, you can use the in operator to check if the username is a key in the dictionary.

wjandrea
  • 28,235
  • 9
  • 60
  • 81