python - PyGame:使用SDL2渲染像素

标签 python pygame

我想使用 SDL2 在 PyGame 中渲染单个绿色像素。这是我当前的代码:

import pygame
import pygame._sdl2

SCREEN_W = 800
SCREEN_H = 800

pygame.init()

pygame_screen = pygame.display.set_mode((SCREEN_W, SCREEN_H), vsync=0, flags=pygame.SCALED)
window = pygame._sdl2.Window.from_display_module()

renderer = pygame._sdl2.Renderer.from_window(window)
renderer.draw_color = (0, 255, 0, 255)  # Set the draw color to green

clock = pygame.time.Clock()

scale_factor = 1

# Create a green surface
green_pixel = pygame.Surface((scale_factor, scale_factor))
green_pixel.fill((0, 255, 0, 255))

use_sdl2 = True

while True:
    msec = clock.tick(60)
    pygame_screen.fill((0, 0, 0))

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

    if use_sdl2:
        renderer.clear()
        dest_rect = pygame.rect.Rect(100, 100, scale_factor, scale_factor)
        renderer.blit(green_pixel, dest_rect)
        renderer.present()
    else:
        dest_rect = pygame.rect.Rect(100, 100, scale_factor, scale_factor)
        pygame_screen.blit(green_pixel, dest_rect)
        pygame.display.flip()

这会产生以下错误:

Traceback (most recent call last):
  File "/home/harald-yoga/Documents/Projects/Python/game-engine/src/game_engine/main.py", line 37, in <module>
    renderer.blit(green_pixel, dest_rect)
  File "src_c/cython/pygame/_sdl2/video.pyx", line 1166, in pygame._sdl2.video.Renderer.blit
  File "src_c/cython/pygame/_sdl2/video.pyx", line 1179, in pygame._sdl2.video.Renderer.blit
TypeError: source must be drawable

非 SDL2 版本 (use_sdl2 = False) 工作正常,并在 x: 100、y: 100 处渲染绿色像素。我在 SDL 版本上做错了什么?

最佳答案

SDL2 blit 方法通常需要纹理而不是表面。 pygame.Surface 不适用于 SDL2 的渲染函数。通过将 pygame.Surface 转换为纹理来修复它。这是新代码:

# ... [previous code] ...

# Create a green surface
green_pixel = pygame.Surface((scale_factor, scale_factor))
green_pixel.fill((0, 255, 0, 255))

# Convert the surface to a texture
green_pixel_texture = renderer.create_texture_from_surface(green_pixel)

use_sdl2 = True

while True:
    # Previous code in the loop here

    if use_sdl2:
        renderer.clear()
        dest_rect = pygame.rect.Rect(100, 100, scale_factor, scale_factor)
        renderer.copy(green_pixel_texture, dstrect=dest_rect)  # Use copy instead of blit
        renderer.present()
    else:
        # Not SDL2 rendering code

关于python - PyGame:使用SDL2渲染像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77682444/

相关文章:

python - 在 pygame 中通过 colliderect 检查非常相似的障碍物的碰撞时,如何提高性能?

python - 在蒙版图像pygame上检测鼠标事件

python - 为什么当我使用 pygame.key.get_pressed() 时我的角色只向左移动?

Python打印函数

python - While 循环在语音转文本聊天机器人中未按预期工作

等待用户 IO ('getchar()' 的 c++ 线程在主进程中挂起 'Py_Initialize()'

python - Tensorflow的占位符初始化与tensorflow的常量初始化不同。为什么?

python - 在while循环中从服务器接收数据显示窗口没有响应

python - 我正在尝试代码,但不知道我在某个页面上遇到错误,例如没有对象属性

python - 如何旋转数据框