# P-2 MCS 260 15 Feb 2010 : colordb.py # A color in a database is stored by two records. # For example, the color red corresponds to (255, 0, 0) and is stored # once as key "red" with value "16711680" (16711680 = 255*256**2) and # once as key "16711680" with value "red". Note that in both # cases the type of key and value are always strings. # The background window of turtle graphics displays the color # and the name of the color appears as the title of the window. import anydbm, turtle coldb = anydbm.open('colors.dbm','c') turtle.colormode(255) print "hit enter to give a color code" given = raw_input("or else type the name of a color : ") if given == "": # hitting enter leads to the empty string, case 1 code = input("-> give a triplet (*,*,*), * in 0..255 : ") numb = code[0]*256**2 + code[1]*256 + code[2] # number representation turtle.bgcolor(code) # show color in background if str(numb) in coldb.keys(): # code already in database, case 1.1 turtle.title(coldb[str(numb)]) # show the name of the color as title else: # code not in database, case 1.2 name = raw_input("-> give a name for the color %s : " % str(code)) turtle.title(name) # show the name of the color as title coldb[str(numb)] = name # store number as key, name as value coldb[name] = str(numb) # store name as key, number as value print "-> added (" + name + "," + str(numb) + ") to the color database" else: # user entered a name, case 2 if given in coldb.keys(): # name is in database, case 2.1 turtle.title(given) # show the name of the color as title numb = eval(coldb[given]) # convert string into a number (q1,r1) = divmod(numb,256) # first stage to tuple conversion (q2,r2) = divmod(q1,256) # second stage to tuple conversion code = (q2,r2,r1) # tuple code extracted from number turtle.bgcolor(code) # show color in background of turtle else: # name is not in database, case 2.2 print "-> \"" + given + "\" is not in the color database" prompt = "-> give a triplet (*,*,*), * in 0..255, for the color " code = raw_input(prompt + "\"%s\" : " % given) turtle.title(given) # show the name of color as title evco = eval(code) # convert tuple in string to tuple turtle.bgcolor(evco) # show the color in background numb = evco[0]*256**2 + evco[1]*256 + evco[2] # number representation coldb[str(numb)] = given # store number as key, name as value coldb[given] = str(numb) # store value as key, number as value print "-> added (" + given + "," + str(numb) + ") to the color database" ans = raw_input("hit enter to exit") # to prevent turtle window from closing