2017-04-17 22 views
0

在我之前的question上,我遇到了精灵的问题。所以我决定在绘制它们之前使用清晰的方法。它似乎有效,但当精灵到达屏幕底部时,即他们应该回到顶部时,他们消失了。只剩下9个中的2个。Pygame Sprites Dissapearing

在到达底部之前。

enter image description here

后,他们到达了底部,reseted顶部。


enter image description here

主文件

#!/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 


     screen.blit(background,(100,100)) 
     raindrops.clear(screen,background) 
     raindrops.update() 
     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

不包括所有的代码;改为创建[mcve]。它会让这个问题对其他人更有利,因为阅读,理解,测试/验证变得更容易,而且这也会让那些试图找出问题的人更容易。 –

+0

下次xD会考虑这个问题 –

回答

1
if self.rect.y == HEIGHT: 

问题是一些雨滴会超过HEIGHT,因为speedy是一个随机数在范围[1,8]中,因此为speedy mig的倍数不能被2*HEIGHT整除。例如speedy = 7,rect.y从-HEIGHT = -300到-293,-286,...,295,然后到302大于300,所以==检查永远不会是真的,并且雨滴将永远下降。

>=一个简单的改变就能解决问题:

if self.rect.y >= HEIGHT: