美文网首页
Python柏林噪声实例

Python柏林噪声实例

作者: 大龙10 | 来源:发表于2022-02-16 09:19 被阅读0次

       昨天围观简书线上元宵晚会,嘿嘿乐了一晚上,没写字。先水水一篇,近来在研究柏林噪声,看到的好例子(忘记地址了,稍后补上),先学习一下。

    运行效果

    一、分析

    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
    
    

    相关文章

      网友评论

          本文标题:Python柏林噪声实例

          本文链接:https://www.haomeiwen.com/subject/nbmrlrtx.html