Pygame精灵消失了

2024-05-19 03:22:52 发布

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

在我之前的question中,我遇到了精灵的麻烦。所以我决定在画之前先用清晰的方法。它似乎起了作用,但当精灵到达屏幕的底部时,也就是他们应该回到顶部的时候,他们消失了。9人中只剩下2人

在到达底部之前。

enter image description here

到达底部并重置到顶部。


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)

Tags: pathfromrectimageimportselfmaindisplay
1条回答
网友
1楼 · 发布于 2024-05-19 03:22:52
if self.rect.y == HEIGHT:

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

>=的简单更改将解决问题:

if self.rect.y >= HEIGHT:

相关问题 更多 >

    热门问题