python满天星代码
时间: 2023-11-20 22:51:31 浏览: 134
这里提供两个Python的满天星代码,一个使用turtle模块,另一个使用pygame模块。具体代码如下:
1. 使用turtle模块的满天星代码:
```
from turtle import *
import random
def cell(l1):
down()
for i in range(6):
forward(l1)
left(60)
forward(l1)
right(120)
up()
def lrk(l1,l2):
up()
width(random.randint(1,4))
colormode(255)
color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
goto(random.randint(0,300),random.randint(0,300))
cell(l1)
global t
t = not t
if l1/3 < l2:
return
elif t == 1:
l1 *= random.randint(1,2)
else:
l1 /= random.randint(1,4)
lrk(l1,l2)
def draw_star():
lrk(10,0.1)
speed(10)
bgcolor("black")
for i in range(50):
draw_star()
done()
```
2. 使用pygame模块的满天星代码:
```
import pygame
import random
pygame.init()
# 设置窗口大小
size = (800, 600)
screen = pygame.display.set_mode(size)
# 设置窗口标题
pygame.display.set_caption("Starry Sky")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义星星列表
stars = []
# 定义星星类
class Star(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([5, 5])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 随机生成星星
for i in range(100):
x = random.randint(0, 800)
y = random.randint(0, 600)
star = Star(x, y)
stars.append(star)
# 游戏循环
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 填充背景色
screen.fill(BLACK)
# 绘制星星
for star in stars:
screen.blit(star.image, star.rect)
# 刷新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
阅读全文