def test_color2(self): c1 = Color(0.9, 0.6, 0.75) c2 = Color(0.7, 0.1, 0.25) c3 = c1 + c2 self.assertTrue(equals(c3.x, 1.6)) self.assertTrue(equals(c3.y, 0.7)) self.assertTrue(equals(c3.z, 1))
def is_skin_hair_block(self, block, block_type): ''' Return true if the block (given by the argument 'block' which is the coordinate-tuple for the top-left corner) is a skin/hair-block - it is if a majority (as per the threshold attribute) of the pixels in the block are skin/hair colored. 'block_type' says whether we are testing for a skin block ('s') or a hair block ('h). ''' total_pixels = 0 if block_type == 's': num_pixels = 0 for width in range(block[0], block[0] + self.block_sz): for height in range(block[1], block[1] + self.block_sz): if 0 <= width < self.image.size( )[0] and 0 <= height < self.image.size()[1]: total_pixels += 1 pixel_cl = Color(self.image.get_rgba(width, height)) if self.is_skin(pixel_cl): num_pixels += 1 else: num_pixels = 0 for width in range(block[0], block[0] + self.block_sz): for height in range(block[1], block[1] + self.block_sz): if 0 <= width < self.image.size( )[0] and 0 <= height < self.image.size()[1]: total_pixels += 1 pixel_cl = Color(self.image.get_rgba(width, height)) if self.is_hair(pixel_cl): num_pixels += 1 if (float(num_pixels) / total_pixels >= self.fraction_pixel): return True
def test_a_stripe_pattern_is_constant_in_z(self): black = Color(0, 0, 0) white = Color(1, 1, 1) p = StripePattern(white, black) self.assertTrue(white.equals(p.pattern_at(Point(0, 0, 0)))) self.assertTrue(white.equals(p.pattern_at(Point(0, 0, 1)))) self.assertTrue(white.equals(p.pattern_at(Point(0, 0, 2))))
def render_moon(scene): light = Light(Color(1.0, 1.0, 1.0, 1.0), 1.0) light.transform.position = Vector3(0.0, 2.0, -2.0) scene.set_light(light) lambertianTintMaterial = Material() lambertianTintMaterial.albedo = Color(1.0, 1.0, 1.0, 1.0) lambertianTintMaterial.shader = LambertianTintShader() s1_earth = Sphere(0.6) s1_earth.transform.position = Vector3(0, 0, 1.5) s1_earth.material = lambertianTintMaterial.clone() scene.add_objects(s1_earth) s2_moon = Sphere(0.4) s2_moon.transform.position = Vector3(-0.2, -0.5, 1.2) s2_moon.material = lambertianTintMaterial.clone() s2_moon.material.set_texture(Texture("images/moon.jpg")) scene.add_objects(s2_moon) v1 = Vector3(0.0, 1.5, 0.5) v2 = Vector3(0.5, -1.0, 0.0) animation_velocity = 0.4 def update_method(t): p = Vector3(-0.2, -0.5, 1.2) p = p.add(v1.multiply(np.cos(animation_velocity * t * np.pi))) p = p.add(v2.multiply(np.sin(animation_velocity * t * np.pi))) s2_moon.transform.position = p s2_moon.transform.rotation = Vector3( 0.0, np.mod(0.5 * animation_velocity * t, 360), 0.0) return update_method
def __init__(self, filename, width, height): json = self.read_json(filename) self.preferred_team = json.get("preferred_team", "Cubs") self.preferred_division = json.get("preferred_division", "NL Central") self.rotate_games = json.get("rotate_games", False) self.rotate_rates = json.get("rotate_rates", DEFAULT_ROTATE_RATES) self.stay_on_live_preferred_team = json.get("stay_on_live_preferred_team", True) self.display_standings = json.get("display_standings", False) self.display_standings_on_offday = json.get("display_standings_on_offday", True) self.scroll_until_finished = json.get("scroll_until_finished", True) self.end_of_day = json.get("end_of_day", "00:00") self.display_full_team_names = json.get("display_full_team_names", True) self.slower_scrolling = json.get("slower_scrolling", False) self.debug_enabled = json.get("debug_enabled", False) # Get the layout info json = self.__get_layout(width, height) self.layout = Layout(json, width, height) # Store color information json = self.__get_colors("teams") self.team_colors = Color(json) json = self.__get_colors("scoreboard") self.scoreboard_colors = Color(json) #Check the rotate_rates to make sure it's valid and not silly self.check_rotate_rates() self.check_display_standings_on_offday()
def test_times(self): c1 = Color(0.1, 0.1, 0.1) c2 = Color(0.1, 0.1, 0.1) result = times(c1, c2) for n in result: self.assertAlmostEqual(n, 0.01)
def render_random_spheres(scene): total_sphere = random.randint(1, 15) light = Light(Color(1.0, 1.0, 1.0, 1.0), 1.0) light.transform.position = Vector3(0.0, 2.0, -2.0) scene.set_light(light) for i in range(0, total_sphere): s = Sphere(random.randint(10, 200) / 100.0) s.transform.position = Vector3(random.randint(-3, 3), random.randint(-3, 3), random.randint(2, 10)) s.albedo = Color( float(random.randint(20, 255)) * 1.0 / 255.0, float(random.randint(20, 255)) * 1.0 / 255.0, float(random.randint(20, 255)) * 1.0 / 255.0, 1.0) print("Sphere got color " + str(s.albedo)) scene.add_objects(s) v1 = Vector3(8.0, 0.0, -1.0) v2 = Vector3(0.0, 8.0, -3.0) animation_velocity = 0.5 def update_method(t): p = Vector3(0.0, 2.0, -2.0) p = p.add(v1.multiply(np.cos(animation_velocity * t * np.pi))) p = p.add(v2.multiply(np.sin(animation_velocity * t * np.pi))) light.transform.position = p return update_method
def testRaisesIfColorFormatIsUnexpected(self): with self.assertRaises(Exception): Color('fff') with self.assertRaises(Exception): Color('ffffff') with self.assertRaises(Exception): Color('1.0,1.0,1.0')
def interpolate_value(a,b): """ Returns an interpolator between the two arbitrary values *a* and *b*. The interpolator implementation is based on the type of the end value *b*, using the following algorithm: 1. If *b* is a color, [rgb](#rgb) is used. 2. If *b* is a string, [string](#string) is used. 3. If *b* is a list, [list](#list) is used. 4. If *b* is a dict, [dict](#dict) is used. 5. Otherwise, [number](#number) is used. Based on the chosen interpolator, *a* is coerced to a suitable corresponding type. The behavior of this method may be augmented to support additional types by pushing custom interpolator factories onto the values array. """ if isinstance(b, str): try: a, b = Color(a), Color(b) except ValueError: try: a, b = float(a), float(b) except ValueError: return interpolate_string(a,b) else: return interpolate_number(float(a),float(b)) else: return interpolate_rgb(Color(a),Color(b)) elif isinstance(b, (py_list,py_tuple)): return interpolate_list(a,b) elif isinstance(b, py_dict): return interpolate_dict(a,b) else: return interpolate_number(a,b)
def circle(self, surface, color, position, radius, width=0): """ Draw circular shape, and returns bounding Rect. Argument include surface to draw, color, position and radius. Optional width argument of outline, which defaults to 0 for filled shape. """ surface.beginPath() surface.arc(position[0], position[1], radius, 0, 2 * pi, False) if width: surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() else: if hasattr(color, 'a'): surface.setFillStyle(color) else: surface.setFillStyle(Color(color)) surface.fill() if surface._display: return surface._display._surface_rect.clip( Rect(position[0] - radius, position[1] - radius, 2 * radius, 2 * radius)) else: return surface.get_rect().clip( Rect(position[0] - radius, position[1] - radius, 2 * radius, 2 * radius))
def __init__(self, grid_h, grid_w): # set the dimensions of the game grid as the given arguments self.grid_height = grid_h self.grid_width = grid_w # create the tile matrix to store the tiles placed on the game grid self.tile_matrix = np.full((grid_h, grid_w), None) # the tetromino that is currently being moved on the game grid self.current_tetromino = None self.next_tetromino = None # game_over flag shows whether the game is over/completed or not self.game_over = False self.delta_time = 300 # set the color used for the empty grid cells #mouse position self.position = stddraw.getPosition() self.empty_cell_color = Color(205, 192, 180) #CHANGED Color(42, 69, 99) # set the colors used for the grid lines and the grid boundaries self.line_color = Color(147, 133, 120) self.boundary_color = Color(147, 133, 120) # thickness values used for the grid lines and the grid boundaries self.line_thickness = 0.002 self.box_thickness = 4 * self.line_thickness #sum score self.total_score = 0
def rect(self, surface, color, rect, width=0): """ Draw rectangle shape, and returns bounding Rect. Argument include surface to draw, color, Rect. Optional width argument of outline, which defaults to 0 for filled shape. """ if hasattr(rect, 'width'): _rect = rect else: _rect = Rect(rect) surface.beginPath() if width: surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.rect(_rect.x, _rect.y, _rect.width, _rect.height) surface.stroke() else: if hasattr(color, 'a'): surface.setFillStyle(color) else: surface.setFillStyle(Color(color)) surface.fillRect(_rect.x, _rect.y, _rect.width, _rect.height) if surface._display: return surface._display._surface_rect.clip(_rect) else: return surface.get_rect().clip(_rect)
def polygon(self, surface, color, pointlist, width=0): """ Draw polygon shape, and returns bounding Rect. Argument include surface to draw, color, and pointlist. Optional width argument of outline, which defaults to 0 for filled shape. """ surface.beginPath() surface.moveTo(*pointlist[0]) for point in pointlist[1:]: surface.lineTo(*point) surface.closePath() if width: surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() else: if hasattr(color, 'a'): surface.setFillStyle(color) else: surface.setFillStyle(Color(color)) surface.fill() xpts = [pt[0] for pt in pointlist] ypts = [pt[1] for pt in pointlist] xmin, xmax = min(xpts), max(xpts) ymin, ymax = min(ypts), max(ypts) if surface._display: return surface._display._surface_rect.clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)) else: return surface.get_rect().clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
def test_color3(self): c1 = Color(0.9, 0.6, 0.75) c2 = Color(0.7, 0.1, 0.25) c3 = c1 - c2 self.assertTrue(equals(c3.x, 0.2)) self.assertTrue(equals(c3.y, 0.5)) self.assertTrue(equals(c3.z, 0.5))
def draw_score(self, score): stddraw.setPenColor(self.boundary_color) # using boundary_color # set the pen radius stddraw.setPenRadius(self.box_thickness) # coordinates of the bottom left corner of the game grid pos_x, pos_y = self.grid_width - 0.5, -0.5 stddraw.rectangle(pos_x, pos_y, 3.5, self.grid_height) stddraw.setPenColor(Color(167, 160, 151)) stddraw.filledRectangle(pos_x + 0.03, pos_y + 0.09, 3.4, self.grid_height - 0.2) # set the text text_color = Color(0, 0, 0) stddraw.setFontFamily("Arial") stddraw.setFontSize(30) stddraw.setPenColor(text_color) text_to_display = "SCORE" text_to_display2 = "NEXT" stddraw.text(12 + 1.2, 5, text_to_display2) stddraw.text(self.grid_width + 1.2, 15, text_to_display) stddraw.text(self.grid_width + 1.2, 14, str(score)) # get the tetromino's type to create next tetromino to show in the next section tet_type = self.current_tetromino.get_type() if tet_type == 'I': width = 4 height = 11 elif tet_type == 'O': width = 2 height = 12 else: width = 3 height = 11 next_tetromino = Tetromino(tet_type, height, width) next_tetromino.draw_next_tet(self.current_tetromino) stddraw.setPenRadius() # reset the pen radius to its default value
def colorize_blue_gold(settings): """ Predefined blue and gold color palette """ gold = Color("gold") black = Color("black") palette = [] return_palette = [] palette += black_to_blue(floor(10 * (settings.MAX_ITER / 1024)) + 1) palette += blue_to_black(floor(30 * (settings.MAX_ITER / 1024))) palette += list(black.range_to(gold, floor(60 * settings.MAX_ITER / 1024))) palette += list(gold.range_to(black, floor(60 * settings.MAX_ITER / 1024))) palette += black_to_blue(floor(100 * (settings.MAX_ITER / 1024))) palette += blue_to_black(floor(100 * (settings.MAX_ITER / 1024))) palette += list(black.range_to(gold, floor(10 * settings.MAX_ITER / 1024))) palette += list(gold.range_to(black, floor(10 * settings.MAX_ITER / 1024))) palette += black_to_blue(floor(100 * (settings.MAX_ITER / 1024))) palette += blue_to_black(floor(100 * (settings.MAX_ITER / 1024))) palette += black_to_white(settings.MAX_ITER - len(palette)) for item in enumerate(palette): try: r = item[1].rgb[0] g = item[1].rgb[1] b = item[1].rgb[2] except AttributeError: # print(f"item:{item}") r = item[1][0] / 255 g = item[1][1] / 255 b = item[1][2] / 255 finally: return_palette.append([int(r * 255), int(g * 255), int(b * 255)]) return_palette[settings.MAX_ITER - 1] = (0, 0, 0) # print(f"palette:{return_palette}") return roll_rgb(return_palette, settings)
def draw(self): if (self.countdown > 30): return Color(0, 0, 0).toBytes() elif (self.countdown > 10): return Color(255, 0, 0).toBytes() else: return Color(255, 255, 255).toBytes()
def cornell_box(): '''Generate a scene with a Cornell box, using rectangles and boxes''' world = HittableList() red = Lambertian(Color(0.65, 0.05, 0.05)) white = Lambertian(Color(0.73, 0.73, 0.73)) green = Lambertian(Color(0.12, 0.45, 0.15)) light = DiffuseLight(Color(15, 15, 15)) aluminum = Metal(Color(0.8, 0.85, 0.88), 0.0) glass = Dielectric(1.5) box1 = Box(Point3(0, 0, 0), Point3(165, 330, 165), aluminum) box1 = RotateY(box1, 15) box1 = Translate(box1, Vec3(265, 0, 295)) box2 = Box(Point3(0, 0, 0), Point3(165, 165, 165), white) box2 = RotateY(box2, -18) box2 = Translate(box2, Vec3(130, 0, 65)) world.add(yzRect(0, 555, 0, 555, 555, green)) world.add(yzRect(0, 555, 0, 555, 0, red)) world.add(xzRect(0, 555, 0, 555, 555, white)) world.add(xzRect(0, 555, 0, 555, 0, white)) world.add(xyRect(0, 555, 0, 555, 555, white)) world.add(box1) world.add(box2) world.add(FlipFace(xzRect(213, 343, 227, 332, 554, light))) return world
def test_color(): Red, Orange, Yellow, Green, Blue, Indigo, Violet = range(7) foo = FooEnumInterface.create() get_set(foo, Red, "Red") get_set(foo, Green, "Green") get_set(foo, Violet, "Violet") # Test default enum __hash__ function works as expected color_set = set() color_green_1 = Color(Green) color_green_2 = Color(Green) color_set.add(color_green_1) color_set.add(color_green_2) assert len(color_set) == 1, "test_color failed" color_set.add(Color(Red)) assert len(color_set) == 2, "test_color failed" get_set_optional(foo, Red, "Red") get_set_optional(foo, Green, "Green") get_set_optional(foo, Violet, "Violet") foo.set_optional_enum(None) assert foo.get_optional_enum() is None
def replace_color(self, color, new_color=None): """ Replace color with with new_color or with alpha. """ pixels = self.impl.getImageData(0, 0, self.width, self.height) # pixels = self.getImageData(0, 0, self.width, self.height) if hasattr(color, 'a'): color1 = color else: color1 = Color(color) if new_color: if hasattr(new_color, 'a'): color2 = new_color else: color2 = Color(new_color) else: color2 = Color(color1.r, color1.g, color1.b, 0) col1 = (color1.r, color1.g, color1.b, color1.a) col2 = (color2.r, color2.g, color2.b, color2.a) for i in xrange(0, len(pixels.data), 4): if (self._getPixel(pixels, i), self._getPixel(pixels, i + 1), self._getPixel(pixels, i + 2), self._getPixel(pixels, i + 3)) == col1: for j in range(4): self._setPixel(pixels, i + j, col2[j]) self.impl.putImageData(pixels, 0, 0, 0, 0, self.width, self.height) # self.putImageData(pixels, 0, 0) return None
def __init__(self): #self.id = random.uniform(0, 999999999) Rectangle.__init__(self) self.handler = Handler() self.magnetos = Magnetos() self.offset = Point() self.pivot = Point() self.selected = False self.resizing = False self.direction = NONE self.control = AUTOMATIC self.z = 0 self.hints = False from ui.canvas import Canvas self.canvas = Canvas() self.handler.is_testing = self.canvas.is_testing self.dash = [] self.thickness = 1.0 self.fill_style = COLOR self.fill_color = Color(0.25, 0.25, 0.25, 0.25) self.stroke_color = Color(0.25, 0.25, 0.25, 1.0) self.gradient = Gradient()
class Instance: key = profile.get_pubkey() # joyride ... # keyHash = util.sha_data(key) # 8.2... # keyHash = util._sha_data(key) # keyHashPrintable = util.printable_hash(keyHash) nick_name = profile.get_nick_name() color_fill = Color() color_fill.init_hex(profile.get_color().get_fill_color()) color_stroke = Color() color_stroke.init_hex(profile.get_color().get_stroke_color()) instance_id = None instance_path = None data_path = None def __init__(self, ca): self.__class__.instance_id = ca._activity_id self.__class__.instance_path = os.path.join(ca.get_activity_root(), "instance") recreate_tmp() self.__class__.data_path = os.path.join(ca.get_activity_root(), "data") recreate_data()
def render(self, text, antialias, color, background=None): """ Render text onto surface. Arguments: text to render (string) antialias of text (bool) color of text (R,G,B) background color (R,G,B) """ w, h = self.size(text) surf = surface.Surface((w, h), BufferedImage.TYPE_INT_ARGB) g2d = surf.createGraphics() if background: g2d.setColor(Color(background)) #0.23 g2d.fillRect(0, 0, w, h) g2d.setFont(self.font) if antialias: g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON) g2d.setColor(Color(color)) #0.23 g2d.drawString(text, 0, (h // 2) + (self.fontMetrics.getAscent() // 2)) #0.22 if self.underline: g2d.setStroke(BasicStroke(1)) g2d.drawLine(0, h - 1, w - 1, h - 1) #0.22 g2d.dispose() return surf
def lighting(self, obj, light, point, eyev, normalv, in_shadow): if self.pattern is None: color = self.color else: color = self.pattern.pattern_at_shape(obj, point) effective_color = color * light.intensity ambient = effective_color * self.ambient if in_shadow: return ambient lightv = (light.position - point).normalize() light_dot_normal = lightv.dot(normalv) if light_dot_normal < 0: diffuse = Color(0, 0, 0) specular = Color(0, 0, 0) else: diffuse = effective_color * self.diffuse * light_dot_normal reflectv = (-lightv).reflect(normalv) reflect_dot_eye = reflectv.dot(eyev) if reflect_dot_eye <= 0: specular = Color(0, 0, 0) else: factor = reflect_dot_eye**self.shininess # print(factor) specular = light.intensity * self.specular * factor return ambient + diffuse + specular
def render(self, text, antialias=True, color=(0, 0, 0), background=None, surface=None): #optional surface for text rendering """ Render text onto surface. Arguments are text to render, and optional antialias, RGB color of text, RGB color of background, and surface for text rendering. """ if not surface: w, h = self.size(text) surf = Surface((w, h)) else: surf = surface w, h = surface.width, surface.height if background: surf.setFillStyle(Color(background)) surf.fillRect(0, 0, w, h) surf.setFont('%s %dpx %s' % (self.fontstyle, self.fontsize, self.fontname)) # if antialias: pass surf.setFillStyle(Color(color)) surf.fillText(text, 0, self.fontsize) if self.underline: surf.setLineWidth(1) surf.setStrokeStyle(Color(color)) surf.setStroke(BasicStroke(1)) surf.moveTo(0, h - 1) surf.lineTo(w - 1, h - 1) surf.stroke() return surf
def main(): image = Image.open('rainbow.png') pixels = image.load() width, height = image.size octree = OctreeQuantizer() # add colors to the octree for j in xrange(height): for i in xrange(width): octree.add_color(Color(*pixels[i, j])) # 256 colors for 8 bits per pixel output image palette = octree.make_palette(256) # create palette for 256 color max and save to file palette_image = Image.new('RGB', (16, 16)) palette_pixels = palette_image.load() for i, color in enumerate(palette): palette_pixels[i % 16, i / 16] = (color.red, color.green, color.blue) palette_image.save('rainbow_palette.png') # save output image out_image = Image.new('RGB', (width, height)) out_pixels = out_image.load() for j in xrange(height): for i in xrange(width): index = octree.get_palette_index(Color(*pixels[i, j])) color = palette[index] out_pixels[i, j] = (color.red, color.green, color.blue) out_image.save('rainbow_out.png')
def test_color_constructor(): """ Tests the creation of new colors """ col = Color(100, 200, 300) assert (col.data == None) col = Color(50, 100, 150) assert (col.data == (50, 100, 150))
def __init__(self, resolution, bg=Color()): self.resolution = resolution self.pixels = [] for i in xrange(self.resolution): lst = [] for j in xrange(self.resolution): lst.append(Color(rgb=bg.rgb, a=bg.a)) self.pixels.append(lst)
def test_light_behind_surface(self): m = Material() position = Point(0, 0, 0) eyev = Vector(0, 0, -1) normalv = Vector(0, 0, -1) light = PointLight(Point(0, 0, 10), Color(1, 1, 1)) result = PointLight.lighting(m, Sphere(), light, position, eyev, normalv, False) self.assertEqual(result, Color(0.1, 0.1, 0.1))
def test_light_eye_reflection(self): m = Material() position = Point(0, 0, 0) eyev = Vector(0, -math.sqrt(2) / 2, -math.sqrt(2) / 2) normalv = Vector(0, 0, -1) light = PointLight(Point(0, 10, -10), Color(1, 1, 1)) result = PointLight.lighting(m, Sphere(), light, position, eyev, normalv, False) self.assertEqual(result, Color(1.6364, 1.6364, 1.6364))