我想在屏幕上用新的数据创建新的对象是这样的:Python的字典项没有被引用正确
spawnedObjectDict = dict()
while True: # main loop
if mouseClicked == True:
RectangleName = "Rectangle" + str((len(spawnedObjectDict)))
spawnedObjectDict[RectangleName] = SpawnedRectangle
spawnedObjectDict[RectangleName].positionX = mouseX
spawnedObjectDict[RectangleName].positionY = mouseY
这应该是创建新的对象并赋予它们的坐标等于鼠标。但是,它始终将所有的鼠标指定为新的鼠标坐标,因此它们只是堆叠在一起。起初我以为这只是画一个,或者只有一个对象是在字典出于某种原因,但我加入这个以确保:
def drawRectCoords(RectName, theDict, x, y, size_x, size_y):
for i in iter(theDict):
BASICFONT = pygame.font.Font('freesansbold.ttf', 20)
textSurf = BASICFONT.render(str(theDict['Rectangle0'].positionX) + ", " + \
str(theDict['Rectangle0'].positionY), True, (255, 255, 255), (0, 0, 0))
textRect = textSurf.get_rect()
textRect.topleft = (x, y)
textSurf2 = BASICFONT.render(str(len(theDict)) + ", " + RectName, True, (255, 255, 255), (0, 0, 0))
textRect2 = textSurf2.get_rect()
textRect2.topleft = (150, (20*len(theDict)))
DISPLAYSURF.blit(textSurf, textRect)
DISPLAYSURF.blit(textSurf2, textRect2)
果然,Rectangle0的坐标每次变化,但每次更新textSurf2以显示RectangleName正在改变并且spawnedObjectDict的长度正在增加。
为什么你使用字典而不是列表呢? – ThiefMaster