Skip to content
Advertisement

Going through sprites in an array and redrawing them when it’s time to redraw causes some to blink

I’m working on a game that is like Cookie Clickers in Python. I’m trying to replicate the feature where when you get a cookie (1 cookie from CPS or from clicking the cookie) it makes a small cookie fall down the screen in the background with a random X position and a random Y position.

But the falling cookies start blinking if there is 5+ falling cookies in the array (that I store them in).

I know the reason why, it’s because when it’s calling the screen to redraw, I set the background to black and redraw everything BUT then it has to go through each falling cookie to redraw it which could take time if there was, say, 100 cookies in that array.

If there was 100 cookies in the array, the last cookie might disappear for ~1 second before it finally gets to the end of the array to that cookie.

Here is my code:

JavaScript

In the for loop, cookie is a Class (FallingCookie). Here is the code to that class:

JavaScript

So now, how do I make it so they all draw at once so there is no blinking and then make it move down.

Advertisement

Answer

You should avoid calling draw functions every frame, that’s too slow and I doubt your sprites need to be that dynamic. Instead you should draw onto a surface once and then blit that to your main window every frame. Even better, create a sprite that encapsulates much of the functionality you desire.

Here is an example of a FallingCookie class that inherits from pygame.sprite.Sprite:

JavaScript

You can then create a Group to manage the sprites:

JavaScript

To add some cookies to the group:

JavaScript

To move every cookie and have it check if it has dropped off the window:

JavaScript

To draw all the cookies:

JavaScript

Putting it all together, and adding some chocolate chips my ancient PC can easily maintain sixty frames per second with two thousand cookies: Choc Chip Cookies!

Full Code Listing:

JavaScript

Next you’d want to define some button sprites. See this answer for a good demonstration.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement