I'm working on a game that shows Python drawn images on the screen and occasionally the user needs to click and drag an item from an inventory to have some collision on the screen.
The main function of the game has: clock.tick(60)
. I created a function that shows noise (like when a TV doesn't have reception) and at 60 FPS, it runs way too fast. If I add a sleep, wait, delay, etc., it looks great, but, then dragging an item on the screen has a lot of lag. I would prefer to not have the items lag at all, so I need to know how to slow down the noise function.
def whitespace(surface, rect):
pixel_size = 4
pixel_length = rect.h / pixel_size
pixel_height = rect.w / pixel_size
start = rect.x
pixel_grid = [[1]*int(pixel_height) for n in range(int(pixel_length))]
colors = [(255, 255, 255), (205, 205, 205), (155, 155, 155), (100, 100, 100)]
for row in pixel_grid:
for col in row:
color = random.randint(0, 3)
surface.fill(colors[color], ((rect.x, rect.y), (pixel_size, pixel_size)))
rect.x += pixel_size
rect.y += pixel_size
rect.x = start
Create a function that can generate the a "whitespace" surface. The generated surface is returned from the function:
def create_whitespace(rect):
surface = pygame.Surface(rect.size)
pixel_size = 4
pixel_length = rect.h / pixel_size
pixel_height = rect.w / pixel_size
start = rect.x
pixel_grid = [[1]*int(pixel_height) for n in range(int(pixel_length))]
colors = [(255, 255, 255), (205, 205, 205), (155, 155, 155), (100, 100, 100)]
for row in pixel_grid:
for col in row:
color = random.randint(0, 3)
surface.fill(colors[color], (0, 0, pixel_size, pixel_size))
rect.x += pixel_size
rect.y += pixel_size
rect.x = start
return surface
Create another function which blit
s the surface the the window:
def draw_whitespace(surface, ws_surf, rect):
surface.blit(ws_surf, rect)
Blit the surface to the window in every frame, but generate a new random "whitespace" surface less often. That causes that the same "whitespace" is draw for multiple frames:
ws_cnt = 0
while True:
# [...]
if ws_cnt == 0:
ws_surf = create_whitespace(rect)
ws_cnt += 1
if ws_cnt == 5: # 5 is just an example
ws_cnt = 0
draw_whitespace(screen, ws_surf, rect)
# [...]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.