选取一个示例,例如,绘制线条示例,修改它以便使用随机的值绘制1000个线条。了解一下random库和random.randint()函数
首先记得引入random库
import random
同时由于绘制完线条后会自动关闭,需要引入time库
import time
import math
import sys
import pygame
import random
import time
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,500))
pygame.display.set_caption(("随机画1000条直线"))
color = 255,255,255
width=3
#lean the screen
count=0
screen.fill((0,0,200))
while count<1000:
for event in pygame.event.get():
if event.type in (QUIT,KEYDOWN):
sys.exit()
pos_x1=random.randint(0,600)
pos_y1=random.randint(0,500)
pos_x2=random.randint(0,600)
pos_y2=random.randint(0,500)
#draw the line
pygame.draw.line(screen,color,(pos_x1,pos_y1),(pos_x2,pos_y2),width)
count+=1
#pygame.display.update()
pygame.display.update()
time.sleep(0.5) # 做完一次,延迟0.05秒
下面是另外一种做法
引自https://blog.csdn.net/weixin_41131904/article/details/85320197
import sys
import random
import time
import pygame
from pygame.locals import *
# 初始化
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Random Lines")
# 帧率
FPS = 60
fps_clock = pygame.time.Clock()
# 绘制屏幕颜色
# 放主循环外,否则会覆盖掉上次绘制的线条
screen.fill((0, 80, 0))
# 主循环(绘制随机线条)
n = 1
while n < 1000:
# 键鼠事件
for event in pygame.event.get():
if event.type in (QUIT, KEYDOWN):
sys.exit()
# 绘制线条
# 起始点,和结束点必须在主循环内,否则只会绘制一条线条,下方的颜色同理
width = 2
x_start_random = random.randint(0, 600)
y_start_random = random.randint(0, 500)
x_end_random = random.randint(0, 600)
y_end_random = random.randint(0, 500)
start_point = (x_start_random, y_start_random)
end_point = (x_end_random, y_end_random)
# 添加颜色的变化(题目未作要求233)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
color = r, g, b
pygame.draw.line(screen, color, start_point, end_point, width)
# 更新屏幕显示
pygame.display.update()
fps_clock.tick(FPS)
time.sleep(0.05) # 做完一次,延迟0.05秒
n += 1