星空
2022-04-022.2万
AI 快速预览详细
这段代码是一个使用Python和Pygame库实现的星空模拟项目。通过创建Star类,设置星星的位置和速度,并使用Pygame绘制线条,实现了在屏幕上生成流动的星星效果。适合编程初学者和对编程感兴趣的青少年。
|
最近隔离在家好闲呐,随便整个代码 import pygame from pygame.locals import * from random import randint class Star(object): def __init__(self, x, y, speed): self.x = x self.y = y self.speed = speed def run(): pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) stars = [] for k in range(200): x = float(randint(0, 639)) y = float(randint(0, 479)) speed = float(randint(10, 300)) stars.append(Star(x, y, speed)) clock = pygame.time.Clock() white = (255, 255, 255) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return elif event.type == KEYDOWN: return y = float(randint(0, 479)) speed = float(randint(10, 300)) stars.append(Star(640., y, speed)) time_passed = clock.tick(60) time_passed_seconds = time_passed / 1000 screen.fill((0, 0, 0)) for star in stars: new_x = star.x - star.speed*time_passed_seconds pygame.draw.aaline(screen, white, (new_x, star.y), (star.x+1, star.y)) star.x = new_x def on_screen(star): return star.x > 0 stars = list(filter(on_screen, stars)) pygame.display.update() if __name__ == "__main__": run() |






