要编写代码来绘制星星,你可以选择不同的编程语言和绘图库。下面我将提供几种不同编程语言绘制星星的示例代码。
使用Python和Turtle库绘制星星
```python
import turtle
def draw_star():
turtle.penup()
turtle.goto(-50, 0)
turtle.pendown()
turtle.color("yellow")
turtle.begin_fill()
for _ in range(5):
turtle.forward(100)
turtle.right(144)
turtle.end_fill()
turtle.hideturtle()
调用函数绘制星星
draw_star()
关闭窗口的交互
turtle.done()
```
使用Python和Pygame库绘制星星
```python
import pygame
import numpy as np
设置窗口大小
WIDTH, HEIGHT = 800, 600
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
创建星星
num_stars = 200
stars = np.random.rand(num_stars, 3)
stars[:, 0] *= WIDTH
stars[:, 1] *= HEIGHT
stars[:, 2] *= 5
更新星星位置的函数
def move_stars():
stars[:, 2] -= 0.1
stars[stars[:, 2] < 0, 2] = 5
绘制星星的函数
def draw_stars():
for star in stars:
x, y, z = star
size = (5 - z) * 10 根据z坐标调整星星大小
color = (1, 1, 1, (1 - z / 5) * 255) 根据z坐标调整星星亮度
pygame.draw.circle(screen, color, (int(x), int(y)), size)
主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0)) 清空屏幕
move_stars()
draw_stars()
pygame.display.flip() 更新屏幕显示
clock.tick(60) 控制帧率
pygame.quit()
```
使用HTML5 Canvas和JavaScript绘制星星
```html