Pygame - sprite movement causes layers

2019-09-14 23:36发布

问题:

Im trying to make a rain effect with pygame but it seems as if the background is not cleaning up before updating the sprites. this is what it looks like when i execute the code..

I wonder if there's a way to fix this problem.

rain.py (main file)

#!/usr/bin/python
VERSION = "0.1"
import os, sys, raindrop
from os import path

try:
    import pygame
    from pygame.locals import *
except ImportError, err:
    print 'Could not load module %s' % (err)
    sys.exit(2)

# main variables
WIDTH, HEIGHT, FPS = 300, 300, 30


# initialize game
pygame.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Rain and Rain")

# background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((40,44,52))

# blitting
screen.blit(background,(0,0))
pygame.display.flip()

# clock for FPS settings
clock = pygame.time.Clock()


def main():
    raindrops = pygame.sprite.Group()

    # a function to create new drops
    def newDrop():
        nd = raindrop.Raindrop()
        raindrops.add(nd)

    # creating 10 rain drops
    for x in range(0,9): newDrop()

    # variable for main loop
    running = True

    # event loop
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        raindrops.update()
        screen.blit(background,(100,100))
        raindrops.draw(screen)
        pygame.display.flip()
    pygame.quit()

if __name__ == '__main__': main()

raindrop.py ( class for raindrops )

import pygame
from pygame.locals import *
from os import path
from random import randint
from rain import HEIGHT

img_dir = path.join(path.dirname(__file__), 'img')

class Raindrop(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.width = randint(32, 64)
        self.height = self.width + 33
        self.image = pygame.image.load(path.join(img_dir, "raindrop.png")).convert_alpha()
        self.image = pygame.transform.scale(self.image, (self.width, self.height))
        self.speedy = 5 #randint(1, 8)
        self.rect = self.image.get_rect()
        self.rect.x = randint(0, 290)
        self.rect.y = -self.height

    def update(self):
        self.rect.y += self.speedy
        if self.rect.y == HEIGHT:
            self.rect.y = -self.height
            self.rect.x = randint(0, 290)

回答1:

This is the line you use to clear the screen:

screen.blit(background, (100, 100))

In other words; you're clearing the screen starting at x=100, y=100. Since pygame coordinates starts from topleft and extends to the right and downwards, you're not clearing the screen left of x=100 and above y=100.

Simple fix is blitting at 0, 0 as you did at the start of the program.

screen.blit(background, (0, 0))