Subdomain Posts
Recent Posts
PAWN | 0 sec ago
Java | 3 sec ago
None | 14 sec ago
JavaScript | 20 sec ago
PHP | 41 sec ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
Sitereport
Find cool info about any domain on the internet?
visit sitereport
Free Subdomains
Want a pastebin.com sub-domain for your community?
learn more...
What is pastebin?
Pastebin is a website that hosts all your text & code on dedicated servers for easy sharing.
learn more...
Learn a little bit about the new Pastebin.com on our help page. hide message
By Dick Moores on the 12th of Aug 2008 02:35:08 AM Download | Raw | Embed | Report
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. # random_rectanglesV20_web.py
  4.  
  5. """
  6. ATTENTION: The turtle module imported here is the turtle.py that is part of Python2.6 beta2.
  7. See http://article.gmane.org/gmane.comp.python.tutor/49765 for more information.
  8. """
  9.  
  10. from turtle26 import *
  11. from random import randint, choice, randrange
  12. from math import ceil
  13. import time
  14.  
  15. COLOR_NAMES_NO_GREYS = ['yellow', 'darkseagreen', 'aquamarine4', 'aquamarine1', 'aquamarine3', 'aquamarine2', 'brown', 'indianred4', 'skyblue', 'rosybrown4', 'cornsilk', 'lightpink', 'indianred2', 'chocolate1', 'lemonchiffon3', 'lemonchiffon2', 'lemonchiffon1', 'bisque', 'violetred1', 'chocolate2', 'lemonchiffon4', 'chocolate3', 'chocolate4', 'lightgoldenrodyellow', 'lavender', 'chartreuse3', 'chartreuse2', 'chartreuse1', 'darkslateblue', 'chartreuse4', 'lightskyblue', 'blue', 'rosybrown2', 'maroon4', 'maroon3', 'maroon2', 'maroon1', 'gold3', 'gold2', 'gold1', 'gold4', 'wheat4', 'rosybrown1', 'skyblue4', 'skyblue1', 'skyblue3', 'skyblue2', 'indianred1', 'floralwhite', 'turquoise1', 'firebrick3', 'firebrick2', 'firebrick1', 'steelblue2', 'steelblue4', 'firebrick4', 'lightskyblue1', 'greenyellow', 'lightseagreen', 'sienna', 'tomato', 'indianred3', 'royalblue', 'gainsboro', 'peru', 'red3', 'red2', 'red1', 'springgreen3', 'violetred4', 'lightyellow', 'lemonchiffon', 'chocolate', 'antiquewhite', 'moccasin', 'deeppink', 'springgreen1', 'springgreen2', 'dodgerblue', 'springgreen4', 'seashell2', 'seashell3', 'magenta', 'seashell1', 'tan', 'seashell4', 'pink', 'palevioletred', 'powderblue', 'mediumblue', 'honeydew1', 'mediumpurple1', 'mediumpurple2', 'mediumpurple3', 'mediumpurple4', 'honeydew2', 'khaki4', 'honeydew3', 'paleturquoise3', 'khaki1', 'cadetblue', 'khaki3', 'salmon1', 'honeydew4', 'salmon3', 'salmon2', 'salmon4', 'linen', 'green', 'blueviolet', 'brown2', 'brown3', 'brown1', 'brown4', 'orange4', 'orange1', 'orange3', 'orange2', 'cyan', 'yellow4', 'yellow3', 'yellow2', 'yellow1', 'orange', 'lightsteelblue', 'goldenrod', 'cyan4', 'darkviolet', 'darkmagenta', 'navy', 'ghostwhite', 'plum', 'khaki2', 'darkkhaki', 'violetred', 'red', 'peachpuff', 'lightslateblue', 'lightskyblue4', 'aliceblue', 'lightskyblue2', 'lightskyblue3', 'blue1', 'blue3', 'blue2', 'blue4', 'purple3', 'lightcyan', 'darksalmon', 'mediumspringgreen', 'tomato4', 'tomato1', 'tomato3', 'tomato2', 'mistyrose', 'blanchedalmond', 'orangered', 'navajowhite', 'pink3', 'pink2', 'burlywood', 'pink4', 'mistyrose1', 'white', 'darkolivegreen4', 'lightyellow3', 'paleturquoise4', 'darkolivegreen1', 'seagreen4', 'seagreen3', 'seagreen2', 'seagreen1', 'paleturquoise2', 'limegreen', 'mistyrose3', 'palegreen1', 'palegreen3', 'palegreen2', 'palegreen4', 'mistyrose2', 'burlywood1', 'turquoise2', 'burlywood3', 'burlywood2', 'burlywood4', 'rosybrown', 'turquoise4', 'whitesmoke', 'lightblue', 'snow', 'orangered3', 'orangered2', 'orangered1', 'orangered4', 'mistyrose4', 'thistle2', 'thistle1', 'salmon', 'thistle4', 'oldlace', 'darkseagreen4', 'darkseagreen3', 'darkseagreen2', 'darkseagreen1', 'darkblue', 'lightpink1', 'gold', 'lightsalmon4', 'lightsalmon2', 'lightsalmon3', 'lightsalmon1', 'green4', 'green1', 'green3', 'green2', 'steelblue1', 'papayawhip', 'black', 'orchid4', 'orchid1', 'orchid2', 'orchid3', 'purple2', 'antiquewhite3', 'antiquewhite2', 'antiquewhite1', 'antiquewhite4', 'bisque4', 'bisque1', 'bisque2', 'bisque3', 'darkturquoise', 'turquoise3', 'plum4', 'plum3', 'plum2', 'plum1', 'lightblue3', 'thistle', 'violet', 'darkorchid4', 'darkorchid1', 'darkorchid2', 'darkorchid3', 'rosybrown3', 'honeydew', 'cornflowerblue', 'palevioletred4', 'palevioletred1', 'palevioletred2', 'palevioletred3', 'mediumpurple', 'lightblue2', 'darkcyan', 'lightblue1', 'lightblue4', 'darkred', 'lavenderblush1', 'lavenderblush3', 'lavenderblush2', 'lavenderblush4', 'mediumturquoise', 'lightyellow1', 'lightyellow4', 'lightgoldenrod', 'navajowhite4', 'hotpink', 'olivedrab', 'navajowhite1', 'navajowhite2', 'magenta2', 'magenta1', 'palegreen', 'seashell', 'aquamarine', 'tan4', 'tan3', 'tan2', 'tan1', 'paleturquoise1', 'lawngreen', 'slateblue', 'darkorange4', 'mintcream', 'darkorange1', 'darkorange3', 'darkorange2', 'saddlebrown', 'goldenrod4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'darkgoldenrod', 'lightcyan1', 'sandybrown', 'lightcyan3', 'ivory3', 'ivory2', 'ivory1', 'lightcyan2', 'mediumseagreen', 'ivory4', 'darkorange', 'violetred2', 'steelblue3', 'lightcyan4', 'sienna1', 'palegoldenrod', 'sienna3', 'violetred3', 'sienna2', 'pink1', 'lightyellow2', 'darkolivegreen3', 'darkolivegreen2', 'lavenderblush', 'azure1', 'azure3', 'azure2', 'azure4', 'firebrick', 'indianred', 'sienna4', 'darkolivegreen', 'mediumorchid4', 'lightsteelblue1', 'lightsteelblue2', 'lightsteelblue3', 'lightsteelblue4', 'darkgoldenrod4', 'mediumorchid1', 'magenta4', 'magenta3', 'darkgoldenrod1', 'darkgoldenrod2', 'darkgoldenrod3', 'chartreuse', 'mediumslateblue', 'mediumorchid3', 'springgreen', 'mediumorchid2', 'lightsalmon', 'cyan2', 'turquoise', 'cyan3', 'olivedrab4', 'royalblue4', 'cyan1', 'purple4', 'navajowhite3', 'darkgreen', 'peachpuff4', 'purple1', 'slateblue3', 'peachpuff1', 'peachpuff2', 'olivedrab1', 'olivedrab2', 'olivedrab3', 'slateblue4', 'slateblue2', 'lightgoldenrod4', 'yellowgreen', 'lightgoldenrod1', 'slateblue1', 'lightgoldenrod3', 'lightgoldenrod2', 'peachpuff3', 'orchid', 'purple', 'darkorchid', 'royalblue1', 'thistle3', 'wheat1', 'wheat3', 'wheat2', 'coral3', 'coral2', 'coral1', 'deepskyblue4', 'deepskyblue3', 'deepskyblue2', 'deepskyblue1', 'coral4', 'khaki', 'wheat', 'deepskyblue', 'coral', 'beige', 'azure', 'dodgerblue1', 'dodgerblue2', 'dodgerblue3', 'dodgerblue4', 'mediumvioletred', 'snow4', 'snow2', 'snow3', 'snow1', 'lightcoral', 'ivory', 'lightpink2', 'lightpink3', 'forestgreen', 'lightpink4', 'midnightblue', 'mediumorchid', 'cornsilk4', 'cornsilk2', 'cornsilk3', 'cornsilk1', 'royalblue3', 'royalblue2', 'maroon', 'seagreen', 'red4', 'cadetblue4', 'cadetblue3', 'cadetblue2', 'cadetblue1', 'paleturquoise', 'deeppink3', 'deeppink2', 'deeppink1', 'deeppink4', 'hotpink3', 'hotpink2', 'hotpink1', 'lightgreen', 'hotpink4', 'navyblue', 'mediumaquamarine', 'steelblue']
  16.  
  17. BACKGROUND_COLORS = ['aquamarine4', 'blue', 'blueviolet', 'cadetblue1',
  18.                 'cadetblue3', 'chartreuse2', 'chartreuse4',
  19.                 'coral', 'cyan', 'cyan3', 'darkgoldenrod1', 'darkgreen',
  20.                 'darkolivegreen1', 'darkorange2', 'darksalmon', 'darkseagreen',
  21.                 'darkseagreen2', 'darkviolet', 'deeppink', 'firebrick',
  22.                 'forestgreen', 'gold', 'green', 'hotpink', 'lightcoral',
  23.                 'lightcyan', 'lightgoldenrod1', 'lightgoldenrodyellow',
  24.                 'lightsalmon2', 'lightskyblue',
  25.                 'lightslateblue', 'lightsteelblue1', 'lightsteelblue3',
  26.                 'magenta', 'magenta1', 'magenta2', 'magenta3', 'mediumorchid1',
  27.                 'mediumvioletred', 'navy', 'orangered', 'orangered4', 'orchid1',
  28.                 'palegreen', 'paleturquoise1', 'palevioletred1', 'papayawhip',
  29.                 'pink', 'plum1', 'purple','purple4', 'red4', 'skyblue', 'skyblue2',
  30.                 'skyblue3', 'springgreen',
  31.                 'springgreen4', 'turquoise1', 'turquoise3', 'violetred', 'yellow']
  32.  
  33. DUPE_COLORS_NO_GREYS = [['tomato', 'tomato1'], ['blue4', 'darkblue'], ['cyan4', 'darkcyan'],
  34.                         ['aquamarine3', 'mediumaquamarine'], ['yellow', 'yellow1'],
  35.                         ['darkmagenta', 'magenta4'], ['red1', 'red'], ['honeydew1', 'honeydew'],
  36.                         ['lightyellow', 'lightyellow1'], ['darkred', 'red4'],
  37.                         ['chocolate4', 'saddlebrown'], ['springgreen1', 'springgreen'],
  38.                         ['lavenderblush1', 'lavenderblush'], ['blue', 'blue1'],
  39.                         ['ivory1', 'ivory'], ['deeppink', 'deeppink1'],
  40.                         ['lemonchiffon1', 'lemonchiffon'], ['lightsalmon1', 'lightsalmon'],
  41.                         ['dodgerblue', 'dodgerblue1'], ['seashell1', 'seashell'],
  42.                         ['peachpuff', 'peachpuff1'], ['palegreen2', 'lightgreen'],
  43.                         ['navy', 'navyblue'], ['deepskyblue1', 'deepskyblue'],
  44.                         ['orangered', 'orangered1'], ['olivedrab3', 'yellowgreen'],
  45.                         ['magenta', 'magenta1'], ['mistyrose', 'mistyrose1'],
  46.                         ['mediumblue', 'blue3'], ['seagreen4', 'seagreen'], ['azure1', 'azure'],
  47.                         ['cornsilk', 'cornsilk1'], ['navajowhite', 'navajowhite1'],
  48.                         ['cyan', 'cyan1'], ['peru', 'tan3'], ['snow', 'snow1'],
  49.                         ['lightcyan', 'lightcyan1'], ['green', 'green1'], ['orange1', 'orange'],
  50.                         ['aquamarine1', 'aquamarine'], ['gold1', 'gold'], ['bisque', 'bisque1'],
  51.                         ['chartreuse1', 'chartreuse']]
  52.  
  53. def floatToNearestInt(x):
  54.     """
  55.    convert float x to the nearest integer n
  56.    e.g., 3.4 --> 3;  45.5 --> 46; -2.1 --> -2; -0.8 --> -1
  57.    """
  58.     return int(round(x))
  59.  
  60. def intCommas(n):
  61.     """
  62.    inserts commas into integers. E.g. -12345678 -> -12,345,789
  63.    """
  64.     s = str(n)
  65.     sign = ''
  66.     if s[0] == '-':
  67.         sign = '-'
  68.         s = s[1:]
  69.     slen = len(s)
  70.     a = ''
  71.     for index in range(slen):
  72.         if index > 0 and index % 3 == slen % 3:
  73.             a = a + ','
  74.         a = a + s[index]
  75.     return sign + a
  76.  
  77. def int_to_ordinal(n):
  78.     """
  79.    Takes an int and returns the string ordinal integer, with commas as appropriate
  80.    plus the appropriate suffix; e.g. 1237 -> 1,237th
  81.    """
  82.     n = str(n)
  83.     if n[-1] in "0456789":
  84.         suff = "th"
  85.     elif n[-2:] in ['11', '12', '13']:
  86.         suff = "th"
  87.     elif n[-1] == "1":
  88.         suff = "st"
  89.     elif n [-1] == "2":
  90.         suff = "nd"
  91.     else:
  92.         suff = "rd"
  93.     return intCommas(n) + suff
  94.  
  95. def hmsToText(seconds):
  96.     """
  97.    Convert seconds to hours, minutes, seconds and return result
  98.    """
  99.     seconds = floatToNearestInt(seconds)
  100.     hours, minutes = 0, 0
  101.  
  102.     if seconds >= 60 and seconds < 3600:
  103.         minutes, seconds = divmod(seconds, 60)
  104.     elif seconds >= 3600:
  105.         hours, seconds = divmod(seconds, 3600)
  106.         minutes, seconds = divmod(seconds, 60)
  107.  
  108.     hp, mp, sp = "s", "s", "s" ## add "s" to make "hour", "minute", "second" plural
  109.     if hours == 1:
  110.         hp = "" ## no "s" on "hour"
  111.     if minutes == 1:
  112.         mp = ""
  113.     if seconds >= 1 and seconds < 2:
  114.         sp = ""
  115.  
  116.     if hours == 0 and minutes == 0:
  117.         result = "%d second%s" % (seconds, sp)
  118.     elif hours == 0:
  119.         if seconds == 0:
  120.             result = "%d minute%s exactly" % (minutes, mp)
  121.         else:
  122.             result = "%d minute%s, %d second%s" % (minutes, mp, seconds, sp)
  123.     elif minutes == 0:
  124.         if seconds == 0:
  125.             result = "%d hour%s exactly" % (hours, hp)
  126.         else:
  127.             result = "%d hour%s, %d second%s" % (hours, hp, seconds, sp)
  128.     else:
  129.         result = "%d hour%s, %d minute%s, %d second%s" % (hours, hp, minutes, mp, seconds, sp)
  130.     return result
  131.  
  132. def defaults():
  133.     global default_min
  134.     global default_max
  135.     global default_begin_range
  136.     global default_end_range
  137.     global default_pause
  138.     global default_speed
  139.     global default_delay
  140.     default_min, default_max = 5, 20
  141.     default_begin_range, default_end_range = default_min, default_max
  142.     default_pause = 1
  143.     default_speed = 4
  144.     default_delay = 15
  145.  
  146. def print_defaults_before_acceptance():
  147.     print "The defaults are:"
  148.     print "default min, default max: %d, %d" % (default_min, default_max)
  149.     print "default pause:", default_pause
  150.     print "default speed:", default_speed
  151.     print "default delay:", default_delay
  152.     print "default number of cycles:", default_max_num_cycles
  153.  
  154. def initialize_variables():
  155.     global used_colors
  156.     global multiple_of_num_avail_colors
  157.     global num_cycles
  158.     global total_rects
  159.     global black_or_colored_list
  160.     global unused_background_colors
  161.     mode("standard")
  162.     setup(width=.735, height= 1.0, startx=-1, starty=0)
  163.     unused_background_colors = BACKGROUND_COLORS[:]
  164.     num_cycles = 0
  165.     used_colors = []
  166.     total_rects = 0
  167.     multiple_of_num_avail_colors = 0
  168.     black_or_colored_list = [10, 10, 10, 0] ## so that first sum of list cannot be 0 or 4
  169.     title_string = "Random Rectangles with %d Colors" % num_avail_colors
  170.     title(title_string)
  171.  
  172. def getMinAndMaxIntegersFromUser(default_min, default_max):
  173.     print "Enter 2 integers > 1 for min and max, with max >= min"
  174.     print "Put a comma between the numbers. E.g., '8, 20'"
  175.     print "Press Enter to set default of  %d, %d" % (default_min, default_max)
  176.  
  177.     while True:
  178.         ans = raw_input("min, max: ")
  179.         if ans == '':
  180.             print "The default min, max have been set to %d, %d" % (default_min, default_max)
  181.             return (default_min, default_max)
  182.         try:
  183.             min, max = ans.split(',')
  184.         except ValueError:
  185.             print "\nPlease start over and enter correct min and max."
  186.             print "Enter 2 integers > 1 for min and max, with max >= min"
  187.             print "Press Enter to set default of  5, 20\n"
  188.             continue
  189.         try:
  190.             min = int(min)
  191.         except ValueError:
  192.             print "\nPlease start over and enter correct min and max."
  193.             print "Enter 2 INTEGERS > 1 for min and max, with max >= min"
  194.             print "Press Enter to set default of  5, 20\n"
  195.             continue
  196.         try:
  197.             max = int(max)
  198.         except ValueError:
  199.             print "\nPlease start over and enter correct min and max."
  200.             print "Enter 2 INTEGERS > 1 for min and max, with max >= min"
  201.             print "Press Enter to set default of  5, 20"
  202.             continue
  203.         if min > max or min < 2:
  204.             print "\nPlease start over and enter correct min and max."
  205.             print "min must be <= max and min must be > 1"
  206.             print "Enter 2 integers > 1 for min and max, with max >= min"
  207.             print "Press Enter to set default of  5, 20"
  208.             continue
  209.         else:
  210.             break
  211.     return (min, max)
  212.  
  213. def get_pause_from_user(default_pause):
  214.     print """
  215. You can set the pause between the filling of a rectangle and the start of the
  216. next. Enter any non-negative number for the number of seconds to pause.
  217. E.g., 0, 2, or 2.4
  218. To set the default pause of %s, just press Enter
  219. """ % singular_to_plural(default_pause, 'second')
  220.  
  221.     while True:
  222.         ans = raw_input("Enter pause in seconds: ")
  223.         if ans == '':
  224.             print "a pause of %s has been set" % singular_to_plural(default_pause, 'second')
  225.             return default_pause
  226.         try:
  227.             pause = float(ans)
  228.         except ValueError:
  229.             print "\nPlease start over and enter a number of seconds >= 0."
  230.             print "Just press Enter to set default pause of %s" % singular_to_plural(default_pause, 'second')
  231.             continue
  232.         if pause < 0:
  233.             print "\nPlease start over and enter a NONNEGATIVE number."
  234.             print "Press Enter to set default of  5, 20"
  235.             continue
  236.  
  237.         print "a pause of %.3g second%s has been set" % (float(ans), s_or_none(float(ans)))
  238.         return float(ans)
  239.  
  240. def get_speed_and_delay_from_user(default_speed, default_delay):
  241.     print """
  242. Enter the speed and delay you want in the drawing of rectangles as
  243. two integers separated by a comma; e.g.,  2, 20.
  244.    """
  245.     print "Enter 2 integers >= 0 for speed and delay"
  246.     print "Put a comma between the numbers. E.g., '2, 20'"
  247.     print "Just press Enter to set defaults of  %d, %d" % (default_speed, default_delay)
  248.  
  249.     while True:
  250.         ans = raw_input("speed, delay: ")
  251.         if ans == '':
  252.             print "The defaults of speed %d, delay %d have been set" % (default_speed, default_delay)
  253.             return (default_speed, default_delay)
  254.         try:
  255.             spd, dly = ans.split(',')
  256.         except ValueError:
  257.             print "\nPlease start over and enter correct speed and delay."
  258.             print "Enter 2 integers >= 0 for speed and delay"
  259.             print "Just press Enter to set defaults of  %d, %d" % (default_speed, default_delay)
  260.             continue
  261.         try:
  262.             spd = int(spd)
  263.         except ValueError:
  264.             print "\nPlease start over and enter correct min and max."
  265.             print "Enter 2 INTEGERS > 1 for min and max, with max >= min"
  266.             print "Just press Enter to set defaults of  %d, %d" % (default_speed, default_delay)
  267.             continue
  268.         try:
  269.             dly = int(dly)
  270.         except ValueError:
  271.             print "\nPlease start over and enter correct min and max."
  272.             print "Enter 2 INTEGERS > 1 for min and max, with max >= min"
  273.             print "Just press Enter to set defaults of  %d, %d" % (default_speed, default_delay)
  274.             continue
  275.         if spd < 0 or dly < 0:
  276.             print "\nPlease start over and enter correct min and max."
  277.             print "Both speed and delay must be NONNEGATIVE, i.e., >= 0"
  278.             print "Enter 2 integers >= 0 for speed and delay"
  279.             print "Just press Enter to set defaults of  %d, %d" % (default_speed, default_delay)
  280.             continue
  281.         else:
  282.             break
  283.     print "speed has been set to %d; delay to %d" % (spd, dly)
  284.     return (spd, dly)
  285. def calculate_num_avail_colors():
  286.     num_avail_colors = len(COLOR_NAMES_NO_GREYS) - len(DUPE_COLORS_NO_GREYS) ## dupe colors are all in pairs
  287.     return num_avail_colors
  288.  
  289. def calculate_num_cycles_to_show_all_colors(begin_range, end_range):
  290.     avg = (begin_range + end_range)*1.0/2
  291.     num_cycles_to_show_all_colors = int(ceil(num_avail_colors/avg))
  292.     print "num_cycles_to_show_all_colors:", num_cycles_to_show_all_colors
  293.     return num_cycles_to_show_all_colors
  294.  
  295. def get_max_num_cycles_from_user():
  296.     num_cycles_to_show_all_colors = calculate_num_cycles_to_show_all_colors(begin_range, end_range)
  297.     longstr = """\nEnter the number of cycles; %d cycles will show approximately %d rectangles using all %d colors"""
  298.     print longstr % (num_cycles_to_show_all_colors, num_avail_colors, num_avail_colors)
  299.     print "Press Enter to set the default of %d" % num_cycles_to_show_all_colors
  300.     while True:
  301.         ans = raw_input("Number of cycles: ")
  302.         if ans == '':
  303.             ans = num_cycles_to_show_all_colors
  304.             print "The number of cycle%s has been set to %d." % (s_or_none(num_cycles_to_show_all_colors), num_cycles_to_show_all_colors)
  305.         try:
  306.             ans = int(ans)
  307.         except ValueError:
  308.             print "\nPlease start over and enter a number of cycles >= 1."
  309.             print "Just press Enter to set default number of cycles of %s" % num_cycles_to_show_all_colors
  310.             continue
  311.         if ans < 1:
  312.             print "\nPlease start over and enter a positive integer."
  313.             print "Press Enter to set default of %d" % num_cycles_to_show_all_colors
  314.             continue
  315.         else:
  316.             ans = int(ans)
  317.         return ans
  318.  
  319. def adjust_for_monitor_resolution():
  320.     wd = window_width()
  321.     width_adjustment = wd*1.0/999
  322.     ht = window_height()
  323.     height_adjustment = ht*1.0/702
  324.     return width_adjustment, height_adjustment
  325.  
  326. def get_next_rect_params():
  327.     color_name = get_next_rect_color()
  328.     x = randrange(15, 451, 2)
  329.     y = randrange(15, 251, 2)
  330.     width_adjustment, height_adjustment = adjust_for_monitor_resolution()
  331.     x = x * width_adjustment
  332.     y = y * height_adjustment
  333.     pen_size = get_pen_size(x, y)
  334.     flag = randint(1, 8)
  335.     return pen_size, color_name, x, y, flag
  336.  
  337. def get_pen_size(x, y):
  338.     """
  339.    Return a pen size proportional to the area of the rectangle
  340.    """
  341.     pen_size = (x * y)//11320 + 1
  342.     return pen_size
  343.  
  344. def get_next_rect_color():
  345.     global used_colors
  346.     global multiple_of_num_avail_colors
  347.     while True:
  348.         color_name = choice(COLOR_NAMES_NO_GREYS)
  349.         ## when have exhausted colors
  350.         if len(used_colors) >= num_avail_colors:
  351.             used_colors = []
  352.             multiple_of_num_avail_colors += num_avail_colors
  353.         color_names = dupe_color_names(color_name)
  354.         if isinstance(color_names, tuple):
  355.             name0 = color_names[0]
  356.             name1 = color_names[1]
  357.             if name0 not in used_colors and name1 not in used_colors:
  358.                 used_colors.append(name0)
  359.                 used_colors.append(name1)
  360.                 return name0
  361.             for col_name in color_names:
  362.                 if col_name not in used_colors:
  363.                     used_colors.append(col_name)
  364.                     return col_name
  365.         else:
  366.             col_name = color_names ## only one name in this case
  367.             if col_name not in used_colors:
  368.                 used_colors.append(col_name)
  369.                 return col_name
  370.  
  371.  
  372. def dupe_color_names(color_name):
  373.     """
  374.    Check if color_name is a dupe.
  375.    Return a tuple of it and its fellow dupes.
  376.    If not a dupe, return color_name.
  377.    (a dupe color_name is a color name that has the same color value as at
  378.    least one other color name in COLOR_NAMES_NO_GREYS)
  379.    """
  380.     for x in DUPE_COLORS_NO_GREYS:
  381.         if color_name in x:
  382.             return x[0], x[1]
  383.     return color_name
  384.  
  385. def print_color_names(color_names):
  386.     if isinstance(color_names, tuple):
  387.         for col_name in color_names:
  388.             print col_name,
  389.         print
  390.     else:
  391.         print color_names # a single color
  392.  
  393. def draw_rect():
  394.     speed(spd)
  395.     pensize(pen_size)
  396.     color(color_name)
  397.     color_names = dupe_color_names(color_name)
  398.     print_color_names(color_names)
  399.     begin_fill()
  400.     ## NE, CW (northeast, clockwise)
  401.     if flag == 1:
  402.         up()
  403.         goto(x, y)
  404.         down()
  405.         ## up to here tracer(False) is in effect from the last time draw_rect()
  406.         ## was called (see bottom line)
  407.         tracer(True, dly)
  408.         goto(x, -y)
  409.         goto(-x, -y)
  410.         goto(-x, y)
  411.         goto(x, y)
  412.     ## NE, CCW (northeast, counterclockwise)
  413.     elif flag == 2:
  414.         up()
  415.         goto(x, y)
  416.         down()
  417.         tracer(True, dly)
  418.         goto(-x, y)
  419.         goto(-x, -y)
  420.         goto(x, -y)
  421.         goto(x, y)
  422.     ## SE, CW
  423.     elif flag == 3:
  424.         up()
  425.         goto(x, -y)
  426.         down()
  427.         tracer(True, dly)
  428.         goto(-x, -y)
  429.         goto(-x, y)
  430.         goto(x, y)
  431.         goto(x, -y)
  432.     ## SE, CCW
  433.     elif flag == 4:
  434.         up()
  435.         goto(x, -y)
  436.         down()
  437.         tracer(True, dly)
  438.         goto(x, y)
  439.         goto(-x, y)
  440.         goto(-x, -y)
  441.         goto(x, -y)
  442.     ## SW, CW
  443.     elif flag == 5:
  444.         up()
  445.         goto(-x, -y)
  446.         down()
  447.         tracer(True, dly)
  448.         goto(-x, y)
  449.         goto(x, y)
  450.         goto(x, -y)
  451.         goto(-x, -y)
  452.     ## SW, CCW
  453.     elif flag == 6:
  454.         up()
  455.         goto(-x, -y)
  456.         down()
  457.         tracer(True, dly)
  458.         goto(x, -y)
  459.         goto(x, y)
  460.         goto(-x, y)
  461.         goto(-x, -y)
  462.     ## NW, CW
  463.     elif flag == 7:
  464.         up()
  465.         goto(-x, y)
  466.         down()
  467.         tracer(True, dly)
  468.         goto(x, y)
  469.         goto(x, -y)
  470.         goto(-x, -y)
  471.         goto(-x, y)
  472.     ## NW, CCW
  473.     elif flag == 8:
  474.         up()
  475.         goto(-x, y)
  476.         down()
  477.         tracer(True, dly)
  478.         goto(-x, -y)
  479.         goto(x, -y)
  480.         goto(x, y)
  481.         goto(-x, y)
  482.     end_fill()
  483.     tracer(False)
  484.  
  485. def get_black_or_colored():
  486.     """
  487.    For the next background color, return 0 if it will
  488.    be "black"; 1 if it will be colored, i.e., a color
  489.    to be chosen from the list of unused background colors.
  490.    This function serves the purpose of preventing "black"
  491.    from being used more than once in a row, and a non-black
  492.    color from being used more than four times in a row.
  493.    """
  494.     global black_or_colored_list
  495.     if sum(black_or_colored_list[-1:]) == 0:
  496.         black_or_colored = 1
  497.     elif sum(black_or_colored_list[-4:]) == 4:
  498.         black_or_colored = 0
  499.     else:
  500.         black_or_colored = choice((0, 1))
  501.     black_or_colored_list.append(black_or_colored)
  502.     return black_or_colored
  503.  
  504. def get_next_background_color():
  505.     """
  506.    Return random hue from an updating list of unused background colors.
  507.    """
  508.     global BACKGROUND_COLORS
  509.     global unused_background_colors
  510.     while True:
  511.         if len(unused_background_colors) > 0:
  512.             hue = choice(unused_background_colors)
  513.             unused_background_colors.remove(hue)
  514.             return hue
  515.         else:
  516.             unused_background_colors = BACKGROUND_COLORS[:]
  517.  
  518. def get_background():
  519.     black_or_colored = get_black_or_colored() # 0 for black; 1 for colored
  520.     clearscreen()
  521.     if black_or_colored == 0:
  522.         hue = 'black'
  523.     else:
  524.         hue = get_next_background_color()
  525.     if num_cycles < max_num_cycles:
  526.         print
  527.         print '%s is the new background color' % hue
  528.     return hue
  529.  
  530. def print_so_far_report():
  531.     """
  532.    Print at end of each cycle except for the last, when
  533.    print_program_end_report() will by called.
  534.    """
  535.     if 0 < num_used_colors_to_report < num_avail_colors:
  536.         astr = "%d rects drawn, %d colors used so far, of %d colors"
  537.         print astr % (total_rects, total_rects, num_avail_colors)
  538.     elif total_rects >= num_avail_colors:
  539.         longstr = "%d rects drawn so far; all %d colors have been used"
  540.         print longstr % (total_rects, num_avail_colors)
  541.  
  542. def s_or_none(n):
  543.     """
  544.    Returns 's' to pluralize regular nouns.
  545.    n can be an int, long, float, or str
  546.    """
  547.     e = .0000000000001
  548.     if isinstance(n, (int, long)):
  549.         if n == 1:
  550.             return ''
  551.     elif isinstance(n, float):
  552.         if n - e < 1 < n + e:
  553.             print n
  554.             return ''
  555.     elif isinstance(n, str):
  556.         if '.' not in n:
  557.             if n == '1':
  558.                 return ''
  559.         else:
  560.             n = float(n)
  561.             if n - e < 1 < n + e:
  562.                 return ''
  563.     return 's'
  564.  
  565. def singular_to_plural(n, noun):
  566.     """
  567.    Depending on n, return plural of regular noun in phrase such as
  568.    "3 goats", "1 goat", "1.0 goat", "1.3 goats", "0 goats"
  569.    n may be an int, long, float, or str
  570.    """
  571.     e = .0000000000001
  572.     if isinstance(n, (int, long)):
  573.         if n == 1:
  574.             return str(n) + ' ' + noun
  575.     elif isinstance(n, float):
  576.         if n - e < 1 < n + e:
  577.             return str(n) + ' ' + noun
  578.     elif isinstance(n, str):
  579.         if '.' not in n:
  580.             if n == '1':
  581.                 return n + ' ' + noun
  582.         else:
  583.             n = float(n)
  584.             if n - e < 1 < n + e:
  585.                 return str(n) + ' ' + noun
  586.     return str(n) + ' ' + noun + 's'
  587.  
  588. def print_program_end_report():
  589.     if 0 < total_rects < num_avail_colors:
  590.         astr = "%d colors of %d were used for %d rectangles"
  591.         print astr % (total_rects, num_avail_colors,
  592.         total_rects)
  593.     elif num_avail_colors <= total_rects:
  594.         print "all %d colors were used for %d rectangles" % (num_avail_colors,
  595.         total_rects)
  596.  
  597. def beepN(times,interval):
  598.     """Calls beep() n times at interval of x seconds."""
  599.     import time
  600.     for k in range(times-1):
  601.         beep()
  602.         time.sleep(interval)
  603.     beep()
  604.  
  605. def beep():
  606.     """
  607.    A very short Beep. Useful at end of program to remind user of the .exe
  608.    to check final report in the 10 seconds before the console window closes
  609.    """
  610.     import winsound
  611.     pitch = 500
  612.     length = 30
  613.     winsound.Beep(pitch,length)
  614.  
  615. print \
  616. """
  617. This program creates sets (cycles) of concentric randomly sized and
  618. randomly colored rectangles against background colors randomly chosen from a
  619. special list of %d colors. After the initial background of white, a black
  620. background will be chosen at least once in five times, but never twice in a row.
  621. No rectangle color will repeat until all %d colors have been chosen.
  622. """ % (len(BACKGROUND_COLORS), len(COLOR_NAMES_NO_GREYS))
  623. ## defaults() has all the defaults except max_num_cycles, which depends on
  624. ## num_cycles_to_show_all_colors, which in turn depends on num_avail_colors,
  625. ## which depends on end_range, begin_range, which depend on the defaults
  626. ## default_min, default_max .
  627. defaults()
  628.  
  629. num_avail_colors = calculate_num_avail_colors()
  630. default_max_num_cycles = calculate_num_cycles_to_show_all_colors(default_begin_range, default_end_range)
  631. print_defaults_before_acceptance()
  632. print """
  633. You can accept all defaults by pressing Enter at the prompt
  634. Enter 'n' to decline to accept all defaults
  635. """
  636. ans = raw_input("Your choice: ")
  637. if ans == '':
  638.     print "All defaults have been set."
  639.     accept_all_defaults = True
  640.     begin_range, end_range = default_min, default_max
  641.     pause = default_pause
  642.     max_num_cycles = default_max_num_cycles
  643.     spd, dly = default_speed, default_delay
  644.     speed(spd)
  645. else:
  646.     accept_all_defaults = False
  647.  
  648. if not accept_all_defaults:
  649.     print \
  650.     """You can configure the number of rectangles per cycle by setting the minimum
  651.    and maximum numbers. This will be the range from which the actual number will
  652.    be chosen by a random process for each cycle. E.g., enter  10, 15 for a range of
  653.    10 to 15."""
  654.  
  655.     print "For the default of %d, %d just press Enter." % (default_min, default_max)
  656.     begin_range, end_range = getMinAndMaxIntegersFromUser(default_min, default_max)
  657.     print
  658.     pause = get_pause_from_user(default_pause)
  659.  
  660. if not accept_all_defaults:
  661.     max_num_cycles = get_max_num_cycles_from_user()
  662.  
  663. print """
  664. The program will stop after %s.
  665. To stop it sooner, click in the console window to
  666. make it the active window; then press Ctrl+Q.
  667. """ % singular_to_plural(max_num_cycles, 'cycle')
  668.  
  669. if not accept_all_defaults:
  670.     spd, dly = get_speed_and_delay_from_user(default_speed, default_delay)
  671.  
  672. ## spd is used in line below; dly is used in tracer() in function draw_rect()
  673. speed(spd)
  674. initialize_variables()
  675. print "\nThe program has started\n"
  676. timeStart = time.time()
  677.  
  678. for x in range(1, max_num_cycles+1):
  679.     if x == 1:
  680.         bgcolor("white")
  681.         print "white is the background color"
  682.         ## do setup() again (only once again), in order to set the window
  683.         ## height so that the bottom will be just at the top of task bar.
  684.         setup(width=.735, height=(window_height()- 40), startx=-1, starty=0)
  685.     final_rect_num = randint(begin_range, end_range)
  686.     count = 0
  687.     num_used_colors = len(used_colors)
  688.     num_used_colors_to_report = num_used_colors + multiple_of_num_avail_colors
  689.     print_so_far_report()
  690.     print "%d rects in new %s cycle are coming up" % (final_rect_num,
  691.                                             int_to_ordinal(num_cycles+1))
  692.  
  693.     for x in range(0, final_rect_num):
  694.         pen_size, color_name, x, y, flag = get_next_rect_params()
  695.         hideturtle()
  696.         draw_rect()
  697.         total_rects += 1
  698.         count += 1
  699.         if count == final_rect_num:
  700.             num_cycles += 1
  701.             print "That ends the %s cycle of %d cycles" % (int_to_ordinal(num_cycles), max_num_cycles)
  702.             time.sleep(1.5)
  703.             if num_cycles < max_num_cycles:
  704.                 hue = get_background()
  705.                 bgcolor(hue)
  706.             else:
  707.                 beepN(3, 0.2)
  708.                 print "The program will close in 10 seconds"
  709.         else:
  710.             time.sleep(pause)
  711.  
  712. ## report at end of program
  713. print
  714. print_program_end_report()
  715. timeEnd = time.time()
  716. print "Time was %s" % (hmsToText(timeEnd - timeStart))
  717. time.sleep(8.5)
Submit a correction or amendment below. [ previous version ] | [ difference ] | Make A New Post
To highlight particular lines, prefix each line with @h@
Syntax highlighting:
Post expiration:
Post exposure:
Name / Title:
Email: