Pygame - 精灵运动导致层次

时间:2017-04-17 15:42:30

标签: python python-2.7 pygame sprite

我试图用pygame制作一个降雨效果,但似乎在更新精灵之前背景没有清理。 这是我执行代码时的样子.. enter image description here

我想知道是否有办法解决这个问题。

rain.py(主文件)

#!/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(雨滴类)

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 个答案:

答案 0 :(得分:1)

这是您用来清除屏幕的行:

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

换句话说;你从x = 100开始清除屏幕,y = 100。由于pygame坐标从topleft开始并向右和向下延伸,因此您不会清除x = 100左侧和y = 100左侧的屏幕。

简单修复就像在程序开始时那样在0,0处进行blitting。

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