Advertisement
here2share

# Tk_spiral_primes_colors.py

Feb 21st, 2022
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. # Tk_spiral_primes_colors.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 grey'.split()*3
  12. color = 0
  13.  
  14. ww = 600
  15. hh = 600
  16. root = Tk()
  17. root.title("# Tk_spiral_primes")
  18. root.geometry("%dx%d+0+0"%(ww,hh))
  19. canvas = Canvas(root, width=ww, height=hh)
  20. canvas.grid()
  21.  
  22. def isPrime(num):
  23.     a=2
  24.     while a <= sqrt(num):
  25.         if num%a < 1:
  26.             return False
  27.         a=a+1
  28.     return num > 1
  29.    
  30. def switch(state):
  31.     return {
  32.         0 : (x + stepSize, y),
  33.         1 : (x, y - stepSize),
  34.         2 : (x - stepSize, y),
  35.         3 : (x, y + stepSize),
  36.     }[state]
  37.  
  38. while 1:
  39.     for L in range(2,len(COLORS)/3+1):
  40.         # set up spiral
  41.         step = 1
  42.         state = 0
  43.         numSteps = 1
  44.         turnCounter = 1
  45.         stepSize = 5
  46.         cols = ww / stepSize
  47.         rows = hh / stepSize
  48.         totalSteps = cols * rows
  49.         x = ww / 2
  50.         y = hh / 2
  51.        
  52.         canvas.delete('all')
  53.         while 1:
  54.             # If prime... draw
  55.             if isPrime(step):
  56.                 color = (color + 1) % L
  57.                 t = stepSize * 0.5
  58.                 canvas.create_rectangle((x,y,x+t,y+t), fill=COLORS[color], outline='')
  59.            
  60.             # Move according to state
  61.             x, y = switch(state)
  62.            
  63.             # Change state
  64.             if step % numSteps == 0:
  65.                 state = (state + 1) % 4
  66.                 turnCounter += 1
  67.                 if turnCounter % 2 == 0:
  68.                     numSteps += 1
  69.             step += 1  
  70.            
  71.             # Are we done?
  72.             if step > totalSteps:
  73.                 break
  74.         canvas.update()
  75.     rs(COLORS)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement