昨天围观简书线上元宵晚会,嘿嘿乐了一晚上,没写字。先水水一篇,近来在研究柏林噪声,看到的好例子(忘记地址了,稍后补上),先学习一下。
运行效果一、分析
1、框架
采用的pygame游戏框架,循环执行画图,按ESC推出
2、柏林噪声
模块random_pos,调用柏林噪声函数,随机生成平滑的位置点(x,y)。
3、画方框
模块draw_rec,有透明度。
4、填充方框
模块fill_rect,填充方框,渐变,alpha值减少,透明度由低到高。
5、动态
随机生成点画方框,下一个点是由柏林噪声函数生成,画面显示出方框平滑移动的动态效果。
二、代码
import pygame
from pygame.locals import *
import random
from noise import snoise2
pygame.init()
screen = pygame.display.set_mode((0,0),FULLSCREEN) # Surface
W,H = screen.get_size()
canvas = screen.convert_alpha()
pygame.display.set_caption('my game')
x_scale,y_scale,scale = W/2,H/2,512
seed_x,seed_y = random.random(),random.random()
px,py = random.randint(0,100),random.randint(0,100)
def random_pos():
global px,py
px += 1
py += 1
x = int(W/2 - snoise2(px/scale,seed_y)*x_scale)
y = int(H/2 - snoise2(seed_x,py/scale)*y_scale)
return x,y
def draw_rect(x,y,width,height,alpha):
pygame.draw.rect(canvas,(0,255,0,alpha),(x,y,width,height),3)
def fill_rect(x,y,n):
wstep = W/n
hstep = H/n
sw = x / n
sh = y / n
sa = 200/n
for i in range(n+1,0,-1):
alpha = sa * i
draw_rect(x-i*sw,y-i*sh,i*wstep,i*hstep,alpha)
x0,y0 = W/2,H/2
n = 30
bright = n
time_count = 0
pygame.mouse.set_visible(False)
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
screen.fill(0)
canvas.fill((0,0,0,0))
# x0,y0 = pygame.mouse.get_pos()
x0,y0 = random_pos()
fill_rect(x0,y0,n)
screen.blit(canvas,(0,0))
pygame.display.update()
clock.tick(60)
pygame.quit()
三、参考资料:
1、WilenWu-CSDN博客_python 柏林噪声:https://blog.csdn.net/qq_41518277/article/details/82779516
2、http://libnoise.sourceforge.net/index.html
3、https://www.cnblogs.com/leoin2012/p/7218033.html
4、Sengo的CSDN博客:https://blog.csdn.net/Sengo_GWU/article/details/80153638
5、《不只是噪声,更是数学美》:https://blog.csdn.net/qq_34302921/article/details/80849139
网友评论