[英]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.