Search code examples
pythonpygamepygame-clock

How to set a static background with pygame in python?


I am writing a demo with pygame in python, and want to draw a moving object on a static background. But I do not want to update the static background.

At first I want to draw two layers, one for the static background and the other for the moving object. However, I do not find any attribute like layers (just like layers in photoshop). So how can I deal with it.

here is my code:

# -*- coding: utf-8 -*-
import sys
from settings import Settings
import pygame
import math


def run_game():
    # 
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Catch Me If You CAN")

    radius = 10

    # 
    while True:

        # 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        # 
        screen.fill(ai_settings.bg_color)

        pygame.draw.rect(screen, [0, 0, 0], [math.cos(radius)*100+300, math.sin(radius)*50+200, 10, 10], 4)

        radius = radius + 0.1

        # 
        pygame.display.flip()


run_game()

Solution

  • what I want to achieve is to draw the background at the beginning and need not to reset the background

    That's not possible. When you draw something to the screen surface, it's just there. To get rid of it, you have to draw something new.

    The easiest way is to just fill the screen with a solid color or blit your background surface to the screen once every iteration of the main loop.

    There a more advanced techniques (like only redraw the areas of the screen with the background that where overwritten by another surface), and pygames offers some abstractions in the form of the different Group classes. E.g, there's a clear() function that will "clear" the screen from any sprites of the Group (and does so by redrawing those areas with the surface provided).

    At first I want to draw two layers, one for the static background and the other for the moving object. However, I do not find any attribute like layers

    You're looking for the LayeredUpdates class, which will draw its sprites in the order of their _layer-attribute.

    If you're new to pygame, you should look into how to use pygame's Sprite and Group classes, which will do what you need and are good enough in like 99% of all cases.


    tl;dr:

    Your options are:

    1) fill the screen surface every iteration of the game loop
    2) use sprites and a Group and its clear function every iteration of the game loop
    3) use sprites and a LayeredUpdates-group and add background sprite