Advertisement
here2share

# Tk_spiral_primes.py

Feb 21st, 2022 (edited)
754
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. # Tk_radial_prime_in_color.py
  2.  
  3. from Tkinter import *
  4. from math import sqrt
  5. from random import shuffle as rs
  6.  
  7. def oRGB(rgb): # pass
  8.     r,g,b = rgb
  9.     return "#%02x%02x%02x" % (r,g,b)
  10.    
  11. COLORS = 'red orange yellow green blue purple'.split()*5
  12. color = 0
  13. Lc = len(COLORS)
  14.  
  15. ww = 600
  16. hh = 600
  17. root = Tk()
  18. root.title("# Tk_radial_prime_in_color")
  19. root.geometry("%dx%d+0+0"%(ww,hh))
  20. canvas = Canvas(root, width=ww, height=hh)
  21. canvas.grid()
  22.  
  23. def isPrime(num):
  24.     a=2
  25.     while a <= sqrt(num):
  26.         if num%a < 1:
  27.             return a%Lc
  28.         a=a+1
  29.     return 0
  30.  
  31. def switch(state):
  32.     return {
  33.         0 : (x + stepSize, y),
  34.         1 : (x, y - stepSize),
  35.         2 : (x - stepSize, y),
  36.         3 : (x, y + stepSize),
  37.     }[state]
  38.  
  39. # to record spiral
  40. xy = []
  41.  
  42. # set up spiral
  43. step = 1
  44. state = 0
  45. numSteps = 1
  46. turnCounter = 1
  47. stepSize = 3
  48. cols = ww / stepSize
  49. rows = hh / stepSize
  50. totalSteps = cols * rows
  51. x = x0 = ww / 2
  52. y = y0 = hh / 2
  53.  
  54. while 1:
  55.     distance = int(sqrt((x0-x)**2+(y0-y)**2)) + (step*0.00001)
  56.     xy.append((distance,x,y))
  57.    
  58.     # Move according to state
  59.  
  60.     # Change state
  61.     if step % numSteps == 0:
  62.         state = (state + 1) % 4
  63.         turnCounter += 1
  64.         if turnCounter % 2 == 0:
  65.             numSteps += 1
  66.     step += 1
  67.     x, y = switch(state)
  68.  
  69.     # Are we done?
  70.     if step > totalSteps:
  71.         break
  72.        
  73. xy.sort()
  74. xy = [(x,y) for z,x,y in xy]
  75.  
  76. for x,y in xy:
  77.     color = isPrime(step)
  78.     t = stepSize
  79.     canvas.create_rectangle((x,y,x+t,y+t), fill=COLORS[color], outline='')
  80.     step += 1
  81.     canvas.update()
  82.     COLORS = COLORS + [COLORS.pop(0)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement