pygame中的所有精灵不会在屏幕上绘制

2024-04-27 04:34:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望所有的sprite行都从屏幕上掉下来,但是当我运行update方法时,只有一行raindrops被绘制下来并移到屏幕上。然而,当我注释掉update方法时,所有的雨滴行都被绘制出来了。我在谷歌上搜索这个问题,但找不到解决办法。所以请任何人帮我。

import pygame
import sys

from pygame.sprite import Sprite
from pygame.sprite import Group

class Raindrops(Sprite):

    def __init__(self, screen, x=0, y=0):
        super().__init__()

        self.image = pygame.image.load('images/rain1.bmp')
        self.screen = screen
        self.rect = self.image.get_rect()
        self.screen_rect = self.screen.get_rect()
        self.rect.x = x
        self.rect.y = y

        self.center = float(self.rect.centery) # It is saved as float so that the location can be saved accurately.

    # This method moves the raindrops to the bottom of the screen.
    def update(self):
        if self.rect.top <= self.screen_rect.bottom:
            self.center += 1.4
            self.rect.center = self.center

def run_game():
    pygame.init()

    screen = pygame.display.set_mode((1000, 600))
    screen.convert()

    screen_rect = screen.get_rect()

    pygame.display.set_caption("Rain")

    rain_drop = Raindrops(screen)

    rain_drops = Group()

    number_drops_x = int(screen_rect.width / (1.5 * rain_drop.rect.width))

    number_rows = 5

    for row in range(number_rows):
        for drop in range(number_drops_x):
            rain_drop.rect.x = drop * (1.5 * rain_drop.rect.width)
            rain_drop.rect.y = row * (2 * rain_drop.rect.height)   
            rain_drop.add(rain_drops)
            rain_drop = Raindrops(screen)

    # Loop for the game
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill((135, 206, 235))

        rain_drops.draw(screen)

        # When the update method is added the rows of raindrops disappear
        for drop in rain_drops:
            drop.update()

        for drop in rain_drops:
            if drop.rect.top == 601:
                sys.exit()

        pygame.display.flip()

run_game()

Tags: theinrectimportselfnumberforget