Character moves slowly when grid is displayed in pygame

Viewed 806

I am making a snake game in pygame and I noticed a wierd thing. Whenever I am displaying a grid my character runs slowly.
Here is the main function of my program.
I have just started learning pygame!

def main():
    global SCREEN, CLOCK
    pygame.init()
    CLOCK = pygame.time.Clock()
    SCREEN.fill(BLACK)

    x = 0
    y = 0
    velocity = 20
    x_change = 0
    y_change = 0

    while True:
        drawGrid()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    y_change = -velocity
                    x_change = 0
                if event.key == pygame.K_DOWN:
                    y_change = velocity
                    x_change = 0
                if event.key == pygame.K_LEFT:
                    x_change = -velocity
                    y_change = 0
                if event.key == pygame.K_RIGHT:
                    x_change = velocity
                    y_change = 0

        x += x_change
        y += y_change

        snake(x, y)
        pygame.display.update()
        SCREEN.fill(BLACK)
        CLOCK.tick(60)

def snake(x, y):
    head_rect = pygame.Rect(x, y, BLOCKSIZE, BLOCKSIZE)
    pygame.draw.rect(SCREEN, GREEN, head_rect)


def drawGrid():
    for x in range(WINDOW_WIDTH):
        for y in range(WINDOW_HEIGHT):
            rect = pygame.Rect(x*BLOCKSIZE, y*BLOCKSIZE,
                               BLOCKSIZE, BLOCKSIZE)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)

Here are images for sample Without grid

with grid

1 Answers

I don't think there is any issue with re-drawing. The number of items being re-drawn is less.

However, I can see that in the draw function you are drawing lines for each pixel in the row and column. It is very expensive if done in every frame and it is wasting CPU power unnecessarily as not all the lines will lie in the viewport. Try doing the following instead (divide the WINDOW_WIDTH with BLOCKSIZE in the range function). This way, you will just be drawing lines which lie in the view port.

def drawGrid():
    for x in range(WINDOW_WIDTH // BLOCKSIZE):
        for y in range(WINDOW_HEIGHT // BLOCKSIZE):
            rect = pygame.Rect(x*BLOCKSIZE, y*BLOCKSIZE,
                               BLOCKSIZE, BLOCKSIZE)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)
Related