以下是使用Python实现动态星空的示例代码:

import pygame
import random

# 初始化pygame库
pygame.init()

# 设置窗口大小
width = 800
height = 600
screen = pygame.display.set_mode((width, height))

# 设置窗口标题
pygame.display.set_caption('动态星空')

# 定义星星的数量
num_stars = 200

# 定义星星的最大大小和最大速度
max_star_size = 3
max_star_speed = 5

# 定义星星列表
stars = []

# 生成星星
for i in range(num_stars):
    # 随机生成星星的位置、大小和速度
    x = random.randint(0, width)
    y = random.randint(0, height)
    size = random.randint(1, max_star_size)
    speed = random.randint(1, max_star_speed)
    stars.append((x, y, size, speed))

# 定义背景颜色
bg_color = (0, 0, 0)

# 游戏循环
while True:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            # 退出游戏
            pygame.quit()
            exit()

    # 绘制背景
    screen.fill(bg_color)

    # 更新星星的位置
    for i in range(num_stars):
        x, y, size, speed = stars[i]
        x += speed

        # 如果星星已经移出屏幕,则重新生成一个新的星星
        if x > width:
            x = 0
            y = random.randint(0, height)
            size = random.randint(1, max_star_size)
            speed = random.randint(1, max_star_speed)

        stars[i] = (x, y, size, speed)

        # 绘制星星
        pygame.draw.circle(screen, (255, 255, 255), (x, y), size)

    # 更新屏幕
    pygame.display.update()

以上代码中,我们使用pygame库创建了一个窗口,并在窗口中绘制了动态星空。在游戏循环中,我们不断地更新星星的位置,并在屏幕上绘制它们,从而实现了动态星空的效果。


原文地址: https://www.cveoy.top/t/topic/m0tU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录