Python繁星宇宙
时间: 2023-12-25 11:28:51 浏览: 148
以下是使用Python绘制繁星宇宙的代码和步骤:
1. 导入必要的库
```python
import pygame
import random
```
2. 初始化pygame
```python
pygame.init()
```
3. 设置画布大小和标题
```python
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Starry Sky")
```
4. 定义星星类
```python
class Star:
def __init__(self, x, y, size, color):
self.x = x
self.y = y
self.size = size
self.color = color
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.size)
```
5. 定义生成随机星星的函数
```python
def create_star():
x = random.randint(0, width)
y = random.randint(0, height)
size = random.randint(1, 3)
color = (255, 255, 255)
return Star(x, y, size, color)
```
6. 生成一定数量的星星
```python
stars = []
for i in range(100):
stars.append(create_star())
```
7. 游戏主循环
```python
while True:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 绘制背景
screen.fill((0, 0, 0))
# 绘制星星
for star in stars:
star.draw(screen)
# 更新屏幕
pygame.display.update()
```
阅读全文