微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Pygame 移动星星

如何解决Pygame 移动星星

我正在尝试编写一个移动的星空背景,其中随机数量的白色星星(点)被绘制到黑色背景上,然后慢慢落到底部,一旦落下,就会重新出现在顶部。

到目前为止,我得到了我的星空背景,虽然是静态的并且带有奇怪的图案..

在屏幕顶部出现新星星的奖励积分:)

谢谢!

import pygame
import random

pygame.init()

WIDTH = 480
HEIGHT = 600

WHITE = (255,255,255)
BLACK = (0,0)

FPS = 60
clock = pygame.time.Clock()

screen = pygame.display
screen.set_caption("Starry Night")
screen = screen.set_mode((WIDTH,HEIGHT))
screen.fill(BLACK)

yspeed = 5

x = 1
y = 1

class Star(object):
    def __init__(self,x,y,yspeed):
        self.colour = WHITE
        self.radius = 1
        self.x = x
        self.y = y
        self.yspeed = yspeed

    def draw(self):
        pygame.draw.circle(screen,self.colour,(self.x,self.y),self.radius)

    def fall(self):
        self.y += self.yspeed

    def check_if_i_should_reappear_on_top(self):
        if self.y >= HEIGHT:
            self.y = 0


stars = []

for i in range(100):
    x = random.randint(1,WIDTH - 1)
    y = random.randint(1,HEIGHT - 1)
    stars.append(Star(x,yspeed))

GameOn = True

while GameOn:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            GameOn = False

    for star in stars:
        star.draw()
        star.fall()
        star.check_if_i_should_reappear_on_top()

    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()

解决方法

您必须在每一帧中重新绘制整个场景。因此,您必须清除每一帧中的显示:

while GameOn:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            GameOn = False

    screen.fill(BLACK)                            # <--- CLAER DISPLAY

    for star in stars:
        star.draw()
        star.fall()
        star.check_if_i_should_reappear_on_top()

    pygame.display.flip()
    clock.tick(FPS)

典型的 PyGame 应用程序循环必须:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。