编程怎么画月亮星星图解

时间:2025-01-24 23:02:55 游戏攻略

画星星

导入库

```python

import turtle

import random

```

定义画星星的函数

```python

def draw_star(x, y, size):

turtle.penup()

turtle.goto(x, y)

turtle.pendown()

angle = 120

for _ in range(5):

turtle.forward(size)

turtle.right(angle)

turtle.forward(size)

turtle.right(72 - angle)

```

让星星布满天空

```python

screen = turtle.Screen()

screen.bgcolor("black")

turtle.speed(1)

turtle.color("white")

for _ in range(100):

size = random.randint(20, 50)

x = random.randint(-200, 200)

y = random.randint(-200, 200)

draw_star(x, y, size)

turtle.done()

```

画月亮

定义画月亮的函数

```python

def draw_moon(x, y, size):

turtle.penup()

turtle.goto(x, y)

turtle.pendown()

turtle.color("gray")

turtle.begin_fill()

turtle.circle(size)

turtle.left(90)

turtle.circle(size / 2)

turtle.end_fill()

```

在画布上绘制月亮

```python

screen = turtle.Screen()

screen.bgcolor("black")

turtle.speed(1)

turtle.color("white")

for _ in range(100):

size = random.randint(20, 50)

x = random.randint(-200, 200)

y = random.randint(-200, 200)

draw_star(x, y, size)

draw_moon(0, 0, 100)

turtle.done()

```

综合示例

将上述代码整合在一起,可以绘制出满天繁星和月亮的效果:

```python

import turtle

import random

画星星的函数

def draw_star(x, y, size):

turtle.penup()

turtle.goto(x, y)

turtle.pendown()

angle = 120

for _ in range(5):

turtle.forward(size)

turtle.right(angle)

turtle.forward(size)

turtle.right(72 - angle)

画月亮的函数

def draw_moon(x, y, size):

turtle.penup()

turtle.goto(x, y)

turtle.pendown()

turtle.color("gray")

turtle.begin_fill()

turtle.circle(size)

turtle.left(90)

turtle.circle(size / 2)

turtle.end_fill()

让星星布满天空

screen = turtle.Screen()

screen.bgcolor("black")

turtle.speed(1)

turtle.color("white")

for _ in range(100):

size = random.randint(20, 50)

x = random.randint(-200, 200)

y = random.randint(-200, 200)

draw_star(x, y, size)

在画布上绘制月亮

draw_moon(0, 0, 100)

turtle.done()

```

运行上述代码,将会弹出一个窗口,窗口中绘制了一个黑色背景,中间有一个白色月亮和满天的白色星星。你可以根据需要调整代码中的参数,如画笔的颜色、大小、位置等,来绘制不同样式的星星和月亮。