[英]Problem With Entites In A Dictionary in Ursina Python
我需要制作一个包含许多单独实体的网格,我正在使用字典自动创建它们,而不是使用 1521 行代码来创建每个单独的实体。
我正在使用 on_click function 来运行 function,“动作”,当实体被点击时,动作 function 需要知道点击了什么实体,所以我为 function 传递了一个参数,告诉它实体的键在存储所有实体的字典中单击。
我的问题是它只给我字典中最后一个键的键,(38,38)
我将如何解决这个问题?
这是我的代码:
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]))
尝试将 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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.