Quick answer: Plain pygame.sprite.Group has no draw order guarantees. Use pygame.sprite.LayeredUpdates instead, set each sprite’s _layer attribute, and call group.change_layer when sprites move. For Y-sort top-down games, set _layer = rect.bottom each frame.
Here is how to fix Pygame sprite groups whose draw order seems random. Your player walks behind a tree on one frame and in front of it the next. Or the HUD bar draws below the world. The default Group class makes no guarantees about draw order, and the workaround is to use LayeredUpdates with explicit per-sprite layer values.
The Symptom
You add sprites to a pygame.sprite.Group and call group.draw(screen). The player draws above some tiles but below others. The order changes when sprites are added or removed. You try sorting the group with sorted(group.sprites(), ...) but the next call to draw ignores the sort.
What Causes This
Group does not preserve insertion order across versions. The implementation uses a dict internally, and while modern Python preserves dict insertion order, the practical iteration during draw was never specified to be stable across pygame versions.
No layer concept in Group. A plain Group has no per-sprite priority. There is no way to say “always draw the player last.”
Sorting the sprite list does not persist. Methods like group.sprites() return a list copy. Sorting it does not change the underlying group iteration order.
Y-sort needs frame updates. Even with a layered group, Y-sorting requires updating each sprite’s layer every frame to reflect its current Y position.
The Fix
Step 1: Use LayeredUpdates for ordered groups.
import pygame
class Tile(pygame.sprite.Sprite):
def __init__(self, image, pos):
super().__init__()
self.image = image
self.rect = image.get_rect(topleft=pos)
self._layer = 0 # background
class Player(pygame.sprite.Sprite):
def __init__(self, image, pos):
super().__init__()
self.image = image
self.rect = image.get_rect(center=pos)
self._layer = 10 # draws on top
world = pygame.sprite.LayeredUpdates()
world.add(tile1, tile2, player)
world.draw(screen)
Step 2: Y-sort for pseudo-depth in top-down games.
def update_y_sort(group):
for sprite in group:
# Use rect.bottom so feet line up with depth
new_layer = sprite.rect.bottom
if sprite._layer != new_layer:
group.change_layer(sprite, new_layer)
# Each frame
update_y_sort(world)
world.draw(screen)
Step 3: Reserve high layer numbers for HUD. If you draw the HUD through the same group, give HUD sprites a layer like 1000 so they always draw above any Y-sorted world content.
health_bar._layer = 1000
world.add(health_bar)
Step 4: Avoid mutating layers mid-iteration. Update layers before calling draw, never inside a draw loop. Modifying a LayeredUpdates group during iteration can produce inconsistent results.
Step 5: Use multiple groups for clarity. Separate groups for background tiles, world entities, and HUD. Draw each in turn:
background_group.draw(screen)
entity_group.draw(screen) # LayeredUpdates with Y-sort
foreground_group.draw(screen)
hud_group.draw(screen)
Performance Note
LayeredUpdates is slightly slower than plain Group because it sorts on every layer change. For Y-sort with hundreds of sprites, set the layer only when the sprite’s Y actually changes:
def update(self, dt):
old_y = self.rect.bottom
# ... move sprite ...
if self.rect.bottom != old_y:
self.groups()[0].change_layer(self, self.rect.bottom)
Understanding the issue
This bug class falls into a pattern that's worth understanding beyond the specific case. In Pygame, the underlying behavior is shaped by how the engine layers its abstractions - the public API you call, the runtime systems that respond, and the platform-specific implementations underneath. A bug at any layer can produce symptoms that look like they originate at a different layer. Triaging effectively means recognizing which layer the symptom belongs to, even when the gameplay code is what's visible.
The specific bug described above is the kind that surfaces during integration rather than unit testing. It depends on a combination of factors: the asset configuration, the runtime state, the platform's specific behavior. In isolation, each piece looks correct; in combination, the bug emerges. This is why thorough integration testing - playing the actual game in realistic conditions - catches things that automated tests miss.
Why this happens
This bug class disproportionately affects late-stage development. The work to surface it is interactive testing in realistic conditions, which only really happens after the gameplay is in place and assets are populated. Catching it early requires deliberate testing of conditions that look unimportant.
At the engine level, the behavior comes from a deliberate design decision in Pygame. The engine team chose a particular trade-off - usually performance versus convenience, or generality versus specificity - and that trade-off has consequences when you push against it. Understanding the trade-off is what turns 'this bug is mysterious' into 'this bug is the expected consequence of this design'.
Verifying the fix
Verifying this fix in isolation is straightforward: reproduce the bug, apply the change, confirm the bug no longer reproduces. The harder verification is regression - did this fix introduce a new bug elsewhere? Run your standard regression suite, plus any tests that exercise the same code path with different inputs.
Reproducibility is the prerequisite for verification. If you can't reliably reproduce the bug pre-fix, you can't reliably verify it post-fix. Spend time getting a clean reproduction before you write any fix code. The fix is fast once you understand the reproduction; the reproduction is the slow part.
Variations to watch for
There's almost always a less obvious case where the same problem applies. The reported case is the one a player hit; the related cases hide because they're rarer or affect fewer players. After fixing the reported case, search the codebase for the pattern - one fix often unlocks several.
Adjacent bugs often share a root cause. After fixing the case you've found, spend an hour searching the codebase for similar patterns. What's the same call with different arguments? The same data flow with a different entity type? The same lifecycle issue in a sibling system? Each match is a candidate for the same fix, or a related fix that prevents future bugs of the same class.
In production
In shipping builds, this issue may interact with other production-only behavior. Stripping, encryption, asset bundling, and platform-specific code paths can each modify the symptoms. When players report a related issue, capture build SHA, platform, and any feature flags - those three fields cover most of the production-only variations.
When triaging a similar issue in production, prioritize gathering data over hypothesizing causes. A player report describes a symptom; what you need is a build SHA, a session timestamp, and ideally a screen recording or session replay. With those, the bug becomes tractable. Without them, you're guessing at hypothetical reproductions that may not match what the player actually hit.
Performance considerations
If this issue manifests under high load (many actors, many particles, many network connections), profile the post-fix code path with realistic counts. The original cost was a bug; the new cost is real work, and real work has a budget.
Diagnostic approach
The diagnostic tools available depend on your engine and platform. Use the engine's native profilers and debug overlays before reaching for external tools. The native tools have context that external tools lack - they know which subsystem owns the code, which assets are loaded, and what state the engine is in.
For Pygame-specific diagnostics, the editor's profiler is the canonical starting point. Capture a representative frame with the symptom present; compare against a frame without the symptom; the diff often points directly at the cause. If the symptom is non-deterministic, capture multiple frames and look for the pattern - the cause is usually a state transition or a specific input value rather than a continuous effect.
Tooling and ecosystem
Modern engine versions ship better tooling for this kind of issue than older versions. If you're on an older release, the diagnostic step may take significantly longer because the tools you'd want don't exist yet. Sometimes the right answer is upgrading rather than fighting through limited tooling.
Within Pygame, the relevant diagnostic surfaces include the standard frame debugger, memory profiler, and engine-specific debug overlays. Each one shows a different facet of what's happening. The frame debugger reveals draw call ordering and state transitions; the memory profiler shows allocation patterns; the debug overlay reveals per-system state. Bugs that resist one tool usually surrender to another - the trick is knowing which tool to reach for first.
Edge cases and pitfalls
Platform-specific edge cases are worth enumerating explicitly. iOS handles backgrounding differently than Android; Windows handles focus changes differently than macOS. A fix that works on the development platform may not work on every target. Test on each shipping platform deliberately.
When writing a regression test for this fix, focus on the boundary conditions that surfaced the original bug. Tests that exercise the happy path catch obvious regressions; tests that exercise the boundary catch the subtler regressions that look like new bugs but are really the original returning. The latter are the tests that earn their keep over the long life of the project.
Team communication
When this bug class affects multiple teams (often the case for cross-system issues), early communication prevents duplicate work. The team that owns the symptom may not own the cause. A 15-minute conversation at the start of triage often saves hours of independent investigation.
If this fix touches a system several engineers work in, a short writeup in the team's engineering channel helps. Not a full design doc - a paragraph explaining what was wrong, what's fixed, and what to watch for. Future engineers encountering similar symptoms will search for the fix; making it findable is a small investment that pays back later.
“Group has no opinion about order. LayeredUpdates does. The _layer attribute is the contract between you and pygame.”
Related Issues
For other Pygame issues, see Pygame Joystick Not Detected.
LayeredUpdates. _layer attribute. change_layer when it moves. Y-sort comes for free.