Advertisement
cookertron

Worley Noise - Python Pygame

May 11th, 2020
2,111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. import pygame
  2. import math
  3. from random import randint
  4.  
  5. DW = DH = 400 # DisplayWidth, DisplayHeight
  6. HDW = int(DW / 2) # HalfDisplayWidth
  7. HDH = int(DH / 2) # HalfDisplayHeight
  8. #FPS = 60
  9.  
  10. # colors
  11. RED = [255, 0, 0]
  12.  
  13. class point:
  14.     def __init__(s, x, y):
  15.         s.x = x
  16.         s.y = y
  17.  
  18.     def pos(s):
  19.         return [s.x, s.y]
  20.  
  21. pygame.init()
  22. PD = pygame.display.set_mode((DW, DH)) # PD = Primary Display
  23. pygame.display.set_caption("Worley Noise")
  24.  
  25. # generate points
  26. NUMBER_OF_POINTS = 25
  27. points = [point(randint(0, DW), randint(0, DH)) for count in range(NUMBER_OF_POINTS)]
  28.  
  29. # draw
  30. PA = pygame.PixelArray(PD) # get a pixel array of the primary display
  31. for x in range(DW):
  32.     for y in range(DH): # go through the all the pixels starting at 0, 0 and ending at DW, DH
  33.         distances = [] # this will store the distances between the points and x, y from the loops above
  34.         for index in range(NUMBER_OF_POINTS): # index will reference the points in the points list
  35.             p = points[index]
  36.             distance = math.hypot(x - p.x, y - p.y) # get the distance
  37.             distances.append(distance) # add the distance to the list
  38.         n = 0 # this value selects which distance to use to render the noise value. Remember index 0 in the distances list is the closet point to x, y
  39.         distances.sort() # sort the distances so the closest is at index 0
  40.         noise = int((distances[n] / (HDW / 2)) * 255) # hard to explain this but it's trying to keep the value noise less than 255
  41.         if noise > 255: noise = 255 # if the noise value is greater than 255 then limit it to 255
  42.         PA[x][y] = PD.map_rgb(noise, noise, noise) # apply the noise value to the pixel at x, y
  43. PA.close() # close the pixel array
  44. del PA # and delete (something about memory bleed)
  45.  
  46. # display the points
  47. for p in points:
  48.     pygame.draw.circle(PD, RED, p.pos(), 2) # 2 is the radius
  49.  
  50. pygame.display.update()
  51.  
  52. # press escape to get out!
  53. while True:
  54.     e = pygame.event.get()
  55.     if pygame.key.get_pressed()[pygame.K_ESCAPE]: break
  56.  
  57. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement