Pygame: 为什么我的圆圈没有被绘制到精灵的表面上?

Pygame: Why is my circle not being drawn onto my sprite's surface?

这可能很简单,但我看不出我的错误。为什么我的球没有被绘制到精灵的表面上,因此没有出现在屏幕上?当我更改 class 中的 'draw ellipse' 行以便将其绘制到屏幕上(而不是绘制到表面上)时,它会显示。我做错了什么?

import pygame

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)

class Ball(pygame.sprite.Sprite):
    """This class represents the ball."""
    def __init__(self, width, height):
        """ Constructor. Pass in the balls x and y position. """
        # Call the parent class (Sprite) constructor
        super().__init__()
        # Create the surface, give dimensions and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        # Draw the ellipse onto the surface
        pygame.draw.ellipse(self.image, (255,0,0), [0,0,width,height], 10)

# Initialize Pygame
pygame.init()

# Set the height and width of the screen
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Loop until the user clicks the close button.
done = False

# -------- Main Program Loop -----------
while not done:
    # --- Events code goes here (mouse clicks, key hits etc)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Clear the screen
    screen.fill((255,255,255))

    # --- Draw all the objects
    ball = Ball(100,100)

    # --- Update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

pygame.quit()

圆被绘制到精灵的表面上,但您从未将精灵绘制到屏幕上。

此外,您应该只创建一个 Ball 实例,而不是在主循环的每次迭代中都创建一个。

您通常将精灵分组并调用 draw 来实际绘制精灵,例如

...
# Loop until the user clicks the close button.
done = False

# --- Create sprites and groups
ball = Ball(100,100)
g = pygame.sprite.Group(ball)

# -------- Main Program Loop -----------
while not done:
    # --- Events code goes here (mouse clicks, key hits etc)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    # --- Clear the screen
    screen.fill((255,255,255))

    # --- Draw all the objects
    g.draw(screen)

    # --- Update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

pygame.quit()

请注意,您的精灵还需要一个 rect 属性才能正常工作:

...
# Create the surface, give dimensions and set it to be transparent
self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
# this rect determinies the position the ball is drawn
self.rect = self.image.get_rect()
# Draw the ellipse onto the surface
pygame.draw.ellipse(self.image, (255,0,0), [0,0,width,height], 10)
...