draw - arnthor89/pygame GitHub Wiki

draw

Description

This function belongs to a class that implements a group of dirty sprites (sprites with additional functionalities). The method performs the drawing of the group of sprites and can do it in two different rendering modes: dirty rectangle mode or full screen mode.

  • The dirty rectangle mode first looks for the rectangles where to draw and for eventual collisions (that are handled differently depending on the properties of the dirty sprite), then draws the sprites (again handling the different cases).
  • The full screen mode just draws the sprites without caring about collision with previous drawings.

Switching between modes depends on the time of execution of the function itself (wrt to a fixed threshold). More specifically, if the time exceeds the threshold than the _use_update attribute of the class is set to False so that full screen mode would be used for the next call to the function.
The functions parameters are the surface where to draw and optionally a background image (if none is passed the function uses the class attribute _bgd). It returns a list of rectangles that have been affected by any drawings/updates.

Complexity

The function has a very high CC equal to 23 and it's also very long (92 NLOC). Unfortunately I wasn't able to have a complete picture of how the function works in details because it involves a lot of different classes spread in different files of the Pygame library. However I think this is a bad written code, more than a super complex logics, for 2 reasons:

  • a simple refactor could be probably done in order to split the 2 rendering modes and keep the part involving the time as a different task outside the functions
  • the coder himself admits to not be happy with this function (line 1059 "still not happy with that part" and line 1088 "can it be done better? because that is an O(n**2) algorithm in worst case". The part he's referring to is actually the most difficult to my understanding.