CJMinecraft

Mandelbrot Pygame

Nov 9th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. import pygame
  2. from pygame.locals import *
  3. import math
  4. import os
  5. import colorsys
  6.  
  7. WIDTH = 900
  8. HEIGHT = 900
  9. CELL_SIZE = 1
  10. MAX_ITERATIONS = 100
  11.  
  12. def getScreenshotIndex():
  13. i = 0
  14. while os.path.isfile("screenshot_" + str(i) + ".jpg"):
  15. i = i + 1
  16. print("Screenshot index:", i)
  17. return i
  18.  
  19. SCREENSHOT_INDEX = getScreenshotIndex()
  20.  
  21. cells = []
  22.  
  23. def createMandlebrotSet():
  24. global cells
  25.  
  26. w = 2
  27. h = (w * HEIGHT) / WIDTH
  28.  
  29. xmin = -w / 2
  30. ymin = -h / 2
  31.  
  32. xmax = xmin + w
  33. ymax = ymin + h
  34.  
  35. dx = (xmax - xmin) / WIDTH * CELL_SIZE
  36. dy = (ymax - ymin) / HEIGHT * CELL_SIZE
  37.  
  38. y = ymin
  39.  
  40. for i in range(WIDTH // CELL_SIZE):
  41. cells.append([])
  42. x = xmin
  43. for j in range(HEIGHT // CELL_SIZE):
  44. a = x
  45. b = y
  46.  
  47. ca = a # Change these By default a
  48. cb = b # Change these By default b
  49.  
  50. n = 0
  51. while n < MAX_ITERATIONS:
  52. aa = a * a # Change these By default a * a
  53. bb = b * b # Change these By default b * b
  54. if aa + bb > 4:
  55. break
  56. twoab = 2.0 * a * b
  57. a = aa - bb + ca
  58. b = twoab + cb
  59.  
  60. n = n + 1
  61. if n == MAX_ITERATIONS:
  62. cells[i].append(0)
  63. else:
  64. n = math.sqrt(n / MAX_ITERATIONS) * 255
  65. cells[i].append(n)
  66. x = x + dx
  67. y = y + dy
  68. print("Created mandelbrot set!")
  69.  
  70. createMandlebrotSet()
  71.  
  72. pygame.init()
  73.  
  74. screen = pygame.display.set_mode((WIDTH, HEIGHT), HWSURFACE)
  75. pygame.display.set_caption("Mandlebrot Set")
  76.  
  77. # Change here to change how the colour is calculated from the number of iterationss
  78. def getColor(n):
  79. # rgb = colorsys.hsv_to_rgb(n / 255, 1, 150 / 255)
  80. # return (rgb[0] * 255, rgb[1] * 255, rgb[2] * 255)
  81. return (n, n, n)
  82.  
  83. def drawMandlebrotSet():
  84. global cells
  85. for x in range(WIDTH // CELL_SIZE):
  86. for y in range(HEIGHT // CELL_SIZE):
  87. if cells[x][y] != 0:
  88. pygame.draw.rect(screen, getColor(cells[x][y]), (x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE + 1, CELL_SIZE + 1))
  89.  
  90. running = True
  91. while running:
  92. drawMandlebrotSet()
  93. pygame.display.update()
  94.  
  95. for event in pygame.event.get():
  96. if event.type == QUIT:
  97. running = False
  98. if event.type == KEYDOWN:
  99. if event.key == K_s:
  100. pygame.image.save(screen, "screenshot_" + str(SCREENSHOT_INDEX) + ".jpg")
  101. SCREENSHOT_INDEX = SCREENSHOT_INDEX + 1
  102.  
  103. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment