Pygame basic tutorial 02: display window (display) and image (Surface)

Original link:https://xiets.blog.csdn.net/article/details/131382728

Copyright Statement: Reprinting of original articles is prohibited

Column directory:Pygame column (general directory)

1. Display window: display

pygame.displayThe module provides control over pygame display. You can think of pygame.display as a monitor screen containing a system window.

pygame.displayModule main functions:

# 设置显示窗口的标题
pygame.display.set_caption(title, icontitle=None)

# 设置显示窗口的图标
pygame.display.set_icon(Surface)

# 初始化用于显示的窗口或屏幕, 该函数将创建一个用于映射到系统窗口显示的 Surface 图像。
#
# size      显示窗口的大小 (内容窗口, 不包括标题栏和边框)
#
# flags     控制显示类型, 可以用 位或|运算 组合多种类型, 
#           flags 可取值:
#               pygame.FULLSCREEN       创建全屏显示 create a fullscreen display
#               pygame.DOUBLEBUF        仅适用于OPENGL
#               pygame.HWSURFACE        在 pygame 2 已过时
#               pygame.OPENGL           创建 OpenGL 可渲染显示
#               pygame.RESIZABLE        显示窗口大小可变
#               pygame.NOFRAME          显示窗口将没有边框或控件
#               pygame.SCALED           分辨率取决于桌面大小和图形缩放
#               pygame.SHOWN            窗口以可见模式打开 (默认)
#               pygame.HIDDEN           窗口以隐藏模式打开
#
# display   窗口在哪个显示器上显示, 用于连接了多个显示器的情况, 如果 get_num_displays() == 2, 则 display=1 表示窗口显示在第2个显示器上
#
# depth     颜色深度, 通常最好不要传递 depth 参数, 它将默认为系统的最佳和最快颜色深度
#
# vsync     通过将 vsync 参数设置为 1, 可以获得具有垂直同步的显示器, 但不能保证获得
#
# 返回一个与窗口内容区域绑定的 Surface 图像对象, 之后在此图像上的绘制, 在调用 update() 或 flip() 函数后, 将同步显示在屏幕窗口上
#
pygame.display.set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface

# 更新屏幕显示, 将 set_mode() 返回的 Surface图像 中的内容全部更新到显示屏幕上
pygame.display.flip()

# 更新屏幕显示, 只更新特定区域。如果没有传递任何参数, 则相当于 flip(), 即 update() 相当于 flip()。
pygame.display.update(rectangle=None)

pygame.displayOther functions of the module:

pygame.display.init()                                   # 初始化显示模块, 当调用 pygame.init() 时会自动调用
pygame.display.quit()                                   # 关闭显示模块, 程序退出时自动处理
pygame.display.get_init() -> bool                       # 如果显示模块已初始化, 则返回 True
pygame.display.get_active() -> bool                     # 当前窗口的 Surface 在屏幕上处于活动状态时返回 True
pygame.display.get_caption() -> (title, icontitle)      # 获取显示窗口的标题
pygame.display.get_surface() -> Surface                 # 获取当前窗口的 Surface, 即 set_mode() 返回的对象
pygame.display.get_num_displays() -> int                # 返回显示器的数量
pygame.display.get_window_size() -> tuple               # 返回窗口或屏幕的大小, 即 set_mode() 返回的 Surface 大小, 如果使用了 pygame.SCALED, 可能和 set_mode() 返回的 Surface 大小不一样
pygame.display.get_wm_info() -> dict                    # 获取有关当前窗口系统的信息

pygame.display.get_desktop_sizes() -> list                                      # 获取激活状态的显示器分辨率大小
pygame.display.list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list  # 获取可用的全屏模式列表

pygame.display.toggle_fullscreen() -> int                           # 在 窗口模式 和 全屏模式之 间切换显示窗口

pygame.display.mode_ok(size, flags=0, depth=0, display=0) -> depth  # 为显示模式选择最佳颜色深度
pygame.display.iconify() -> bool                                    # 图标化显示Surface
pygame.display.set_gamma(red, green=None, blue=None) -> bool        # 更改硬件伽马斜坡
pygame.display.set_gamma_ramp(red, green, blue) -> bool             # 使用自定义查找更改硬件伽玛斜坡

pygame.display.set_palette(palette=None)            # 设置显示调色板

pygame.display.get_driver() -> str                  # 获取 pygame 显示后端的名称
pygame.display.Info() -> VideoInfo                  # 创建视频显示信息对象

pygame.display.get_allow_screensaver() -> bool      # 返回是否允许运行屏保
pygame.display.set_allow_screensaver(bool)          # 设置屏保是否可以运行

pygame.display.gl_get_attribute(flag) -> value      # 获取当前显示的 OpenGL 标志的值
pygame.display.gl_set_attribute(flag, value)        # 请求显示模式的 OpenGL 显示属性

2. Image: Surface

pygame.surfaceSurfaceThere is mainly one type in the . pygame module and can be used directly module, and it is exported to the pygame.Surface

In Pygame Surface is used to represent an image in memory with a fixed resolution and pixel format. For example, after a local image is loaded into memory, a Surface object is obtained.

Callpygame.display.set_mode() function to initialize the display window, and what is returned is a Surface object, called "display image< /span> or function updates the content in the displayed image to the screen. ) corresponds to the content area of ​​the system window on the screen. Game content can be drawn into the display image, and then by calling Surface, which is contained in the system window and runs full screen if it is in full screen mode. The display image (” (display Surface). The display image is a separate one in Pygame Surfacepygame.display.update()pygame.display.flip()

The relationship between system window and display image:

pygame_display_surface.png

A system window in the screen, including window icon, window title, minimize/maximize and close buttons, window border, window content (can also have menu bar, toolbar, status bar, etc.). The red part in the above picture is the content area of ​​the window, which is the area corresponding to the display image () returned by the pygame.display.set_mode() function. Except for the window content, everything else is part of the operating system. Different operating systems and different system themes may display different effects. Surface

In addition to the Surface returned by set_mode(), the program can call its constructor to create any Surface object. You can also load local images as Surface, and render any text as Surface through the font module. Then draw the Surface you created into the display image () returned by set_mode() through the blit() method, and then call update() or flip(). displayed on the screen simultaneously. Surface

SurfaceThe origin of the image coordinate system is at the upper left corner, the X-axis direction is horizontally to the right, and the Y-axis direction is vertically downward:

surface_coord.png

pygame.SurfaceThe main method of the class:

# Surface 的构造方法, 创建具有指定宽高的图像, 默认使用纯黑色填充
# flags 附加标志, 典型的标志是: pygame.RLEACCEL, pygame.SRCALPHA (像素点包含alpha通道), pygame.SRCCOLORKEY
# depth 像素的颜色深度, 默认 Pygame 会使用最适合当前系统的颜色深度。
pygame.Surface((width, height), flags=0, depth=0, masks=None) -> Surface
pygame.Surface((width, height), flags=0, Surface) -> Surface

# 获取 Surface 的宽高尺寸
pygame.Surface.get_size() -> (width, height)
pygame.Surface.get_width() -> int
pygame.Surface.get_height() -> int

# 将 一个图像(source) 绘制到 当前图像(self) 上, 绘制后超出当前图像部分将被忽略。
# dest 是一个坐标二元组, 表示绘制的位置 (绘制后 source 的左上角在 self 上的坐标位置)。
# dest 也可以是一个 四元祖(x, y, width, height) 或 Rect矩形区域, 如果是则只取 Rect.x 和 Rect.y 属性作为绘制坐标。
# 返回 绘制后 source 在 self 上的位置区域。
pygame.Surface.blit(source, dest, area=None, special_flags=0) -> Rect

# 将 多个图像 绘制到 当前图像 上
pygame.Surface.blits(blit_sequence=((source, dest), ...), doreturn=1) -> [Rect, ...]
pygame.Surface.blits(((source, dest, area), ...)) -> [Rect, ...]
pygame.Surface.blits(((source, dest, area, special_flags), ...)) -> [Rect, ...]

# 用纯色填充 Surface
pygame.Surface.fill(color, rect=None, special_flags=0) -> Rect

# 创建 Surface 的新副本
pygame.Surface.copy() -> Surface

# 更改图像的像素格式(增加 alpha 通道), 包括每个像素的 alpha, 创建新副本
pygame.Surface.convert_alpha(Surface) -> Surface
pygame.Surface.convert_alpha() -> Surface

# 设置 Surface 图像的整体 alpha 值。这里设置的 alpha 是与像素值无关的外置属性, 不针对某个像素点, 而是针对整体, 
# 最终显示为具体像素点的 alpha 值和整体 alpha 值的组合效果。就算没有通过 convert_alpha() 转换为带 alpha 通道的图像, 也可以设置整体 alpha 值。 
pygame.Surface.set_alpha(value, flags=0)
pygame.Surface.set_alpha(None)
# 获取当前 Surface 图像的整体 alpha 值
pygame.Surface.get_alpha() -> int

# 获取单个像素的颜色值, 像素值无论是否有 alpha 通道, 均返回 (R, G, B, A)。如果没有 alpha 通道, 则 A 固定为 255。
pygame.Surface.get_at((x, y)) -> Color
# 设置单个像素的颜色值, 可以以 "#RGBA" 或 (R, G, B, A) 的形式设置。如果参数格式中没有 A, 则 A 默认为 255。如果没有 alpha 通道, 则 A 将被忽略。
pygame.Surface.set_at((x, y), Color)

# 创建一个引用其父级的新 Surface (获取 Surface 的某个区域, 相当于图像裁剪)
# 返回的是原 Surface 的一个区域视图, 不是副本 (如果需要副本, 可以再调用 copy() 方法), 因此在原图像上的改变会反应在返回的视图上。
pygame.Surface.subsurface(Rect) -> Surface

pygame.SurfaceOther methods of the class:

pygame.Surface.convert(Surface=None) -> Surface         # 更改图像的像素格式, 创建新副本
pygame.Surface.convert(depth, flags=0) -> Surface
pygame.Surface.convert(masks, flags=0) -> Surface

pygame.Surface.lock()                                   # 锁定 Surface 内存以进行像素访问
pygame.Surface.unlock()                                 # 通过像素访问解锁 Surface 内存
pygame.Surface.mustlock() -> bool                       # 判断 Surface 是否需要锁定
pygame.Surface.get_locked() -> bool                     # 判断 Surface 当前是否锁定
pygame.Surface.get_locks() -> tuple                     # 获取 Surface 的锁

pygame.Surface.set_colorkey(Color, flags=0)             # 设置透明色键
pygame.Surface.get_colorkey() -> RGB | None             # 获取当前透明色键
pygame.Surface.get_at_mapped((x, y)) -> Color           # 获取单个像素的映射颜色值
pygame.Surface.get_palette() -> [RGB, RGB, RGB, ...]    # 获取 8 位 Surface 的颜色索引调色板
pygame.Surface.get_palette_at(index) -> RGB             # 获取调色板中单个条目的颜色
pygame.Surface.set_palette([RGB, RGB, RGB, ...])        # 为 8 位 Surface 设置调色板
pygame.Surface.set_palette_at(index, RGB)               # 在 8 位 Surface 调色板中设置单个索引的颜色
pygame.Surface.map_rgb(Color) -> mapped_int             # 将颜色转换为映射颜色值
pygame.Surface.unmap_rgb(mapped_int) -> Color           # 将映射的整数颜色值转换为 Color
pygame.Surface.set_clip(rect|None)                      # 设置 Surface 的当前裁剪区域
pygame.Surface.get_clip() -> Rect                       # 获取 Surface 当前的裁剪区域
pygame.Surface.scroll((dx=0, dy=0))                     # 将图像向右移动 dx 像素, 向下移动 dy 像素 (dx 和 dy 可以是负值)

pygame.Surface.get_parent() -> Surface                  # 找到子 Surface 的父级
pygame.Surface.get_abs_parent() -> Surface              # 找到子 Surface 的顶级父级
pygame.Surface.get_offset() -> (x, y)                   # 找到父子 Surface 下子 Surface 的位置
pygame.Surface.get_abs_offset() -> (x, y)               # 找到子 Surface 在其顶级父 Surface 内的绝对位置

pygame.Surface.get_rect() -> Rect                       # 获取 Surface 的矩形区域, 返回 Rect(0, 0, width, height)
pygame.Surface.get_bitsize() -> int                     # 获取 Surface 像素格式的位深度
pygame.Surface.get_bytesize() -> int                    # 获取 Surface 每个像素点使用的字节数, RGB 格式的图像为 3, RGBA 格式的图像为 4
pygame.Surface.get_flags() -> int                       # 获取用于 Surface 的附加标志
pygame.Surface.get_pitch() -> int                       # 获取每个 Surface 行使用的字节数, 等价于 width * get_bytesize()
pygame.Surface.get_masks() -> (R, G, B, A)              # 在颜色和映射整数之间转换所需的位掩码
pygame.Surface.set_masks((R, G, B, A))                  # 设置在颜色和映射整数之间转换所需的位掩码
pygame.Surface.get_shifts() -> (R, G, B, A)             # 在颜色和映射整数之间转换所需的位移位
pygame.Surface.set_shifts((R, G, B, A))                 # 设置在颜色和映射整数之间转换所需的位移位
pygame.Surface.get_losses() -> (R, G, B, A)             # 用于在颜色和映射整数之间转换的有效位
pygame.Surface.get_bounding_rect(min_alpha=1) -> Rect   # 找到包含数据的最小矩形
pygame.Surface.get_view(<kind>="2") -> BufferProxy      # 返回 Surface 像素的缓冲区视图
pygame.Surface.get_buffer() -> BufferProxy              # 为 Surface 的像素获取缓冲区对象
pygame.Surface._pixels_address: int                     # (属性) 像素缓冲区地址
pygame.Surface.premul_alpha() -> Surface                # 返回 Surface 的副本, 其中 RGB 通道预乘以 alpha 通道

3. Display and Surface code examples

Here are two example images for demonstration:

duck.png floor.png

Save the above two pictures locally, put them in the same directory as the py source code file, and name them duck.png and floor.png.

display and surface code examples:

import pygame


def main():
    # 初始化 pygame
    pygame.init()

    # 设置系统窗口标题
    pygame.display.set_caption("display 与 Surface")

    # 加载本地图片 (图片文件 与 当前py文件 在相同路径), 返回的是 Surface 对象
    duck_img = pygame.image.load("duck.png")
    print(type(duck_img), duck_img)
    # Output: <class 'pygame.surface.Surface'> <Surface(80x80x32 SW)>
    # 其中 80x80x32 表示 duck_img 的宽高为 80x80, 颜色模式为 32 位颜色

    # 设置系统窗口图标, 把一个 Surface 图像设置为系统窗口图标
    pygame.display.set_icon(duck_img)

    # 初始化显示窗口, 返回一个与窗口内容区域绑定的 Surface 对象 (显示图像)
    # 因为此 Surface 与屏幕窗口关联, 所以一般命名为 screen 或 display_surface
    screen = pygame.display.set_mode((400, 300))
    print(type(screen), screen)                 # Output: <class 'pygame.surface.Surface'> <Surface(400x300x32 SW)>

    # 加载本地图片
    floor_img = pygame.image.load("floor.png")

    # 裁剪图像, 创建 floor_img 左上角 100x100 的矩形视图区域, 返回的是 Surface 对象
    sub_img = floor_img.subsurface((0, 0, 100, 100))
    print(type(sub_img), sub_img)               # Output: <class 'pygame.surface.Surface'> <Surface(100x100x32 SW)>

    # 游戏主循环
    while True:
        # QUIT 退出事件判断
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出 pygame
                pygame.quit()
                return

        # 先填充背景颜色
        screen.fill("#CCCCCC")

        # 把 duck_img 绘制到 screen 图像中, 绘制后 duck_img 的左上角在 screen 的 (50, 50) 坐标位置
        screen.blit(duck_img, (50, 50))

        # 把 floor_img 绘制到 screen 图像的底部中间
        screen.blit(floor_img, (screen.get_width() / 2 - floor_img.get_width() / 2, screen.get_height() - floor_img.get_height()))

        # 把 sub_img 绘制到 screen 的 (230, 30) 位置
        screen.blit(sub_img, (230, 30))

        # 把 screen 图形中的内容更新到屏幕窗口
        pygame.display.flip()


if __name__ == "__main__":
    main()

pygame.image.load() The function loads the image, and the parameter passed is the local path of the image file. In any programming language, the path can be relative path or absolute path Indicates that, for example, duck.png and image/duck.png are both relative paths, and D:\image\duck.png or /image/duck.png is an absolute path. path. The relative path is relative to the current working directory of the program. In Python, you can call os.getcwd() to get the current working path. If beginners are confused about the relative path or the prompt file cannot be found, they can directly use the absolute path first, for example: r"D:\image\duck.png" or "D:/image/duck.png".

Run the code in the path where the source code file is located:

pygame_demo.png

Guess you like

Origin blog.csdn.net/xietansheng/article/details/131382728