pythondictionaryentityursina

Problem With Entites In A Dictionary in Ursina Python


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]))

Solution

  • 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
            )