1

I need to make a grid of many individual entities and I am using a dictionary to create them automatically instead of having 1521 lines of code to create each individual entity.

I am using the on_click function to run a function, "action", when the entity is clicked, however, the action function needs to know what entity was clicked, so I pass a parameter for the function that tells it the key of the entity clicked in the dictionary that stores all of the entities made.

My problem is that it only gives me the key for the last key in the dictionary, (38,38)

How would I fix this?

Here is my code:

def action(button):
    print(button)  # finds what button was clicked


cell_dict = {}
cell_names = []


def create_dicts():
    # Create the keys for each entity. The keys are the entity's coordinates on the board.
    row_num = 0
    for row in board:
        column_num = 0
        for cell in row:
            cell_names.append((row_num, column_num))
            column_num += 1
        row_num += 1

    # Creates entities for each key in the list and adds them to the dictionary.
    for v in range(len(cell_names)):
        cell_dict[cell_names[v]] = Entity(model='quad', color=color.red, scale=0.125, collider='box', on_click=lambda: action(cell_names[v]))
Bluffyyy
  • 93
  • 5

1 Answers1

1

Try to change the lambda function:

def action(button):
    print(button)  # finds what button was clicked


cell_dict = {}
cell_names = []


def create_dicts():
    # Create the keys for each entity. The keys are the entity's coordinates on the board.
    row_num = 0
    for row in board:
        column_num = 0
        for cell in row:
            cell_names.append((row_num, column_num))
            column_num += 1
        row_num += 1

    # Creates entities for each key in the list and adds them to the dictionary.
    for v in range(len(cell_names)):
        cell_dict[cell_names[v]] = Entity(
            model="quad",
            color=color.red,
            scale=0.125,
            collider="box",
            on_click=lambda name=cell_names[v]: action(name),  # <-- create a parameter here
        )
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    Ohh okay, that woked thank you! I don't have much experience using lambda so they still sorta confuse me, but this makes sense. – Bluffyyy Jan 15 '23 at 23:05
  • @Bluffyyy You're creating a lambda function inside for-loop, which has it's own gotchas. More info for example here: https://stackoverflow.com/questions/7546285/creating-lambda-inside-a-loop – Andrej Kesely Jan 15 '23 at 23:07