Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

python - Pygame lags after drawing full window grid

I was coded a simple pygame grid window. but pygame window start lag after that.

Here is that simple code??

import pygame
import random

pygame.init()
pygame.font.init()

screen_width = 500
screen_height = screen_width

screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")

def drawGrid():
    grid_list = []
    blockSize = 25
    for x in range(screen_width):
        for y in range(screen_height):
            rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
            pygame.draw.rect(screen, (255,255,255), rect, 1)

running = True
while running:
    screen.fill((0,0,0))
    drawGrid()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.update()

I was tried changing the call snippet of drawGrid() function position.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To improve the performance, do not construct the grind in every frame.

Create a pygame.Surface with the size of the window and draw the grid on this surface:

grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)

This surface is the back ground for your scene. blit it at the begin of every frame:

screen.blit(grid_surf, (0, 0))

Example code:

import pygame
import random

pygame.init()
pygame.font.init()

screen_width = 500
screen_height = screen_width

screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Snake GaMe By Akila")

def drawGrid(surf):
    grid_list = []
    blockSize = 25
    for x in range(screen_width):
        for y in range(screen_height):
            rect = pygame.Rect(x*blockSize, y*blockSize, blockSize, blockSize)
            pygame.draw.rect(surf, (255,255,255), rect, 1)

grid_surf = pygame.Surface((screen_width,screen_height))
drawGrid(grid_surf)

running = True
while running:
    screen.blit(grid_surf, (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.update()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...