python - 如何在python中使用pygame设置静态背景?

标签 python pygame pygame-clock

我正在用 python 编写一个 pygame 演示,想要在静态背景上绘制一个移动对象。但我不想更新静态背景。

首先我想画两层,一层用于静态背景,另一层用于移动物体。但是,我没有找到任何像图层这样的属性(就像Photoshop中的图层一样)。那我该怎么处理呢。

这是我的代码:

# -*- 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()

最佳答案

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

这是不可能的。当您在屏幕表面绘制某些内容时,它就在那里。要摆脱它,你必须画一些新的东西。

最简单的方法是在主循环的每次迭代中用纯色填充屏幕或将背景表面传输到屏幕。

有更先进的技术(例如仅重绘屏幕区域,其中背景被另一个表面覆盖),并且 pygames 以不同 Group 类的形式提供了一些抽象。例如,有一个 clear()函数将从 Group 的任何 Sprite 中“清除”屏幕(并通过使用提供的表面重新绘制这些区域来实现)。

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

您正在寻找LayeredUpdates类,它将按照 _layer 属性的顺序绘制 Sprite 。

如果您是 pygame 新手,您应该了解如何使用 pygame 的 SpriteGroup类,它们可以满足您的需要,并且在 99% 的情况下都足够好。

<小时/>

tl;博士:

您的选择是:

1) 游戏循环的每次迭代都填充屏幕表面
2) 在游戏循环的每次迭代中使用 Sprite 和Group及其clear函数
3) 使用 Sprite 和LayeredUpdates组并添加背景 Sprite

关于python - 如何在python中使用pygame设置静态背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50754859/

相关文章:

python - 从 Pandas dataFrame 中的列名称中删除 "\n"

python - win.blit()后台pygame时出现滞后

python - pygame clock.tick() vs 游戏主循环中的帧率

Python - 如何获取维基百科将我重定向到的页面?

python - 使用opencv在图像上编写表情符号

python - Python 是否禁止使用两个相似的 Unicode 标识符?

python - pygame.midi.Input.read 不能是字符串

python - 如何获得生命变化的数量(pygame)?

python - 如何在 Pygame 中获取 Sprite 的位置?

python - 为什么我的程序在我添加旋转后变得非常迟钝,我该如何解决这个问题?