Reputation: 2467
I'm writing a game and in while True: loop I have a code repainting game state.
I have few lists of objects of different kinds (spaceships, beams, stars) - all to improve performance.
And I need to paint them all. I could do:
for spaceship in spaceships:
screen.blit(spaceship.image, (spaceship.x, spaceship.y))
for beam in beams:
screen.blit(beam.image, (beam.x, beam.y))
...
but I feel it's somehow against the DRY principle. And I just feel it can be done better.
What I need is a construction like this:
for actor in spaceships + beams + stars:
actor.move()
screen.blit(actor.image, (actor.x, actor.y))
but a one, which wouldn't join them all (nor do anything which would decrease the performance). Your ideas?
Upvotes: 0
Views: 42
Reputation: 7821
Use chain
from the itertools
module:
from itertools import chain
for actor in chain(spaceships, beams, stars):
actor.move()
screen.blit(actor.image, (actor.x, actor.y))
From the docs:
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
chain
uses lazy evaluation (e.g. no intermediate lists are created), so there will not be any performance drop.
Upvotes: 6