Pygame:为什么我的圈子没被吸引到我的精灵表面?

时间:2015-11-09 11:33:31

标签: pygame

这可能很简单,但我看不到我的错误。为什么我的球没有被吸引到我的精灵表面而没有出现在屏幕上?当我改变'绘制椭圆'时它显示了在类中的行,以便它被绘制到屏幕上(而不是在表面上)。我做错了什么?

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

1 个答案:

答案 0 :(得分:3)

圆圈被绘制在精灵的表面上,但你永远不会将精灵画在屏幕上。

此外,您应该只创建一个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)
...