当我需要在while循环中合并两个数组时,如何避免递归添加数组?

时间:2022-07-03 12:16:14

Working with pygame, I am trying to create a larger list out of two smaller lists. This needs to be done during the game loop because those lists contain pygame.Rect objects which determine collision detection with the character.

使用pygame,我试图从两个较小的列表中创建一个更大的列表。这需要在游戏循环期间完成,因为这些列表包含pygame.Rect对象,这些对象确定与角色的碰撞检测。

charArray.append(guy.rect)
collideArray = newMap.rectArray + charArray

Of course, since this is in the game loop, guy.rect is recursively added to charArray, and collideArray is recursively adding newMap.rectArray to itself, creating a larger and larger list every frame, which eventually just destroys the framerate.

当然,由于这是在游戏循环中,guy.rect以递归方式添加到charArray中,而collideArray以递归方式将newMap.rectArray添加到自身,每帧创建一个越来越大的列表,最终只会破坏帧速率。

Is there a way I could empty the lists every frame so that they are simply being redefined every frame? Or is there some other approach I need to be taking?

有没有办法可以每帧清空列表,以便每帧都重新定义它们?或者我需要采取其他方法吗?

1 个解决方案

#1


2  

Easiest way to "empty" every array at the end of each frame is just to set them as empty at the end of each loop:

在每个帧结尾处“清空”每个数组的最简单方法是在每个循环结束时将它们设置为空:

while game==True:
    #your game code goes here
    charArray,collideArray = [],[]

#1


2  

Easiest way to "empty" every array at the end of each frame is just to set them as empty at the end of each loop:

在每个帧结尾处“清空”每个数组的最简单方法是在每个循环结束时将它们设置为空:

while game==True:
    #your game code goes here
    charArray,collideArray = [],[]