示例#1
0
    def pattern(self):

        bottle_states = []
        for r in range(NUM_NODES + 1):
            bottle_states.append(r % 2 == 0)

        stop = False
        while not stop:
            hue = random()
            c1 = hue_to_color(hue)
            c1 = Colour(rgb=(c1[0] / 255.0, c1[1] / 255.0, c1[2] / 255.0))
            c2 = hue_to_color(hue + .5)
            c2 = Colour(rgb=(c2[0] / 255.0, c2[1] / 255.0, c2[2] / 255.0))

            gradient = []
            for c in c1.range_to(c2, 181):
                gradient.append(
                    (int(c.red * 255), int(c.green * 255), int(c.blue * 255)))

            for angle in range(181, 0, -1):
                for bottle, bottle_angle in self.geo.get_near_bottles(
                        angle, 1):
                    if bottle_angle < angle:
                        if bottle_states[bottle]:
                            self.trap.set_color(bottle,
                                                gradient[int(bottle_angle)])
                        else:
                            self.trap.set_color(
                                bottle, gradient[int(180 - bottle_angle)])
                        bottle_states[bottle] = not bottle_states[bottle]
                        sleep(.03)

            if self.stop_thread:
                stop = True
                break
示例#2
0
class Config:
    board_size = BOARD_SIZE
    board_colour = Colour(WHITE)
    vehicles = VEHICLE_SETS
    width = WIDTH
    height = HEIGHT
    escape_car_colour = Colour(RED)
示例#3
0
 def __init__(self):
     self.coloursDict = {
         1: Colour(135, 206, 235, convertToDecimal=True),
         2: Colour(82, 105, 53, convertToDecimal=True),
         3: Colour(146, 108, 77, convertToDecimal=True),
         4: Colour(169, 163, 163, convertToDecimal=True),
         5: Colour(135, 206, 235, convertToDecimal=True),
     }
示例#4
0
def get_vehicle_from_config(vehicle_type, x, y, orientation, rgb,
                            escape_car_colour):
    if vehicle_type == 'car':
        vehicle = Car(Position(x, y), orientation, Colour(rgb))
    elif vehicle_type == 'lorry':
        vehicle = Lorry(Position(x, y), orientation, Colour(rgb))
    else:
        raise Exception('Unknown vehicle_type! {}'.format(vehicle_type))

    if vehicle.colour == escape_car_colour:
        vehicle.is_escape_vehicle = True
    return vehicle
示例#5
0
def __get_ranged_color(critical, current, high, temp_color):
    if current >= critical:
        return temp_color['critical']
    elif current >= high:
        return temp_color['high']
    else:
        start_color = Colour('#' + temp_color['start'])
        end_color = Colour('#' + temp_color['end'])
        color_list = list(start_color.range_to(end_color, high))

        value = int(current)

        return color_list[value]
示例#6
0
def main():

    import warnings
    warnings.filterwarnings("ignore")

    # create halo catalogue
    halo_cat = MXXLCatalogue()

    # empty galaxy catalogue
    gal_cat = BGSGalaxyCatalogue(halo_cat)

    # use hods to populate galaxy catalogue
    hod = HOD_BGS()
    gal_cat.add_galaxies(hod)

    # position galaxies around their haloes
    gal_cat.position_galaxies()

    # add g-r colours
    col = Colour()
    gal_cat.add_colours(col)

    # use colour-dependent k-correction to get apparent magnitude
    kcorr = GAMA_KCorrection()
    gal_cat.add_apparent_magnitude(kcorr)

    # cut to galaxies brighter than apparent magnitude threshold
    gal_cat.cut(gal_cat.get("app_mag") <= par.mag_faint)

    # save catalogue to file
    gal_cat.save_to_file(par.output_dir + "cat.hdf5", format="hdf5")
示例#7
0
 def make_embed(self, test_index) -> discord.Embed:
     c = Colour(self.colour).rgb
     new_c = discord.Colour.from_rgb(int(c[0] * 255), int(c[1] * 255),
                                     int(c[2] * 255))
     test = self.tests[test_index]
     embed = discord.Embed(
         title=f'{self.registration_date.year} {self.make} {self.model}',
         colour=new_c)
     embed.add_field(name='MOT Result', value=test.result, inline=True)
     embed.add_field(name='MOT Date',
                     value=test.completed_date.strftime("%d/%m/%Y"),
                     inline=True)
     if test.result != 'FAILED':
         embed.add_field(name='MOT Expiry',
                         value=test.expiry_date.strftime("%d/%m/%Y"),
                         inline=True)
     else:
         embed.add_field(name='MOT Expiry', value='N/A', inline=True)
     embed.add_field(
         name='MOT Mileage',
         value=
         f'{"{:,}".format(test.odometer_reading.value)}{test.odometer_reading.unit}',
         inline=True)
     embed.add_field(name='MOT Number', value=test.id, inline=True)
     embed.add_field(name='Car Colour', value=self.colour, inline=True)
     return embed
示例#8
0
    def sendled():
        timestamp = get_timestamp()
        # make the socket blocking
        # (waits for the data to be sent and for the 2 receive windows to expire)
        s.setblocking(True)
        Colour.blink_green()
        ######################
        #  Data
        #######################
        s.bind(6)
        s.send(timestamp)
        time.sleep(5)

        # make the socket non-blocking
        # (because if there's no data received it will block forever...)
        s.setblocking(False)
示例#9
0
    def __init__(self, pin, length):
        self._effect = Effects.RGB
        self._thread = None
        self._thread_terminate = False
        self._thread_running = False
        self.pixels = neopixel.NeoPixel(pin, length)
        self._length = length
        self.pixels[0] = (0, 255, 0)
        self.colour = Colour(0, 0, 20)
        self.paused = False
        self._brightness = 1.0

        for i in range(1, length):
            self.pixels[i] = (0, 0, 20)

        self._backup = []
        self._temperature_pixels = []

        self.save_period = Config.TIME_TO_SAVE
        self.restore_timer = MyTimer(self.save_period, self.restore)
        self.dim_timer = MyTimer(self.save_period, self._dim)

        for i in range(0, self._length):
            self._backup.append(self.pixels[i])

        self._prepare_temperature_pixels()

        self.saved = False
示例#10
0
文件: menu.py 项目: marax27/pyNoid
    def __init__(self, renderer, highscores=None):
        # Background stuff.
        Menu.bg_offset_at_start = 250
        Menu.bg_offset = Menu.bg_offset_at_start
        Menu.bg_dimness_peak = 0x88
        Menu.bg_dimness_current = 0xff
        Menu.bg_diminish_rate = 0.33

        self.choice = None
        self.is_open = True

        self.title = hud.Text('pyNoid', renderer, Constants.TITLE_FONT_SIZE)
        self.title.position = vec2(50, 50)

        self.credits = hud.Text('Kacper Tonia 2017/18', renderer,
                                Constants.TINY_FONT_SIZE)
        self.credits.position = self.title.position + vec2(
            self.title.size[0] // 2, self.title.size[1])

        grey = Colour.greyscale(0.75)

        sub1 = hud.Button.buildClickableText('New Game', renderer,
                                             Colour.White, grey, grey,
                                             Constants.MENU_FONT_SIZE)
        sub2 = hud.Button.buildClickableText('Exit', renderer, Colour.White,
                                             grey, grey,
                                             Constants.MENU_FONT_SIZE)
        self.menu = hud.VerticalContainer([sub1, sub2],
                                          Constants.WINDOW_SIZE.y // 2)

        if highscores:
            leaderboard = []
            player_name_length = max([len(x[0]) for x in highscores])
            score_length = max([len(str(x[1])) for x in highscores])
            s_format = '{:>%d} {}{}' % player_name_length
            for idx, item in enumerate(highscores):
                leaderboard.append(
                    hud.Text(
                        s_format.format(
                            item[0], item[1],
                            ' ' * (score_length - len(str(item[1])))),
                        renderer, Constants.FONT_SIZE_1,
                        Colour.greyscale((5 - idx) / 5.0)))
            self.render_content = hud.VerticalContainer(
                leaderboard, Constants.WINDOW_SIZE.y * 3 // 4)
        else:
            self.render_content = []
    def __init__(self, sprite):
        super().__init__('rect renderer')
        self.sprite = sprite
        self.body = None

        self.offset = (0, 0)
        self.size = (10, 10)
        self.colour = Colour((255, 10, 10))
示例#12
0
    def getColours(self, venues, dates):
        colours = []
        for ven in venues:
            for date in dates:
                c = Colour(ven, date)
                colours.append(c)

        return colours
 def getPixel(self, pixelBox):
     (x, y, x2, y2) = pixelBox
     pixSize = x2 - x
     colour = Colour(0, 0, 0)
     for i in range(self.subPixels):
         colour += self.rayfunc(
             Ray3(self.eye,
                  (Point3(random.uniform(x, x2), random.uniform(y, y2), 1) -
                   self.eye)))
     return old_div(colour, self.subPixels)
示例#14
0
 def colour(self):
     if self.entry < 0:
         return Colour(0, 0, 0)
     colour = self.mat.litColour(self.normal, self.ambient, self.lights,
                                 -self.ray.dir, self.texCords)
     if self.reflection:
         colour += self.mat.reflectivity * self.reflection.colour()
     elif self.bgcolour:
         colour += self.mat.reflectivity * self.bgcolour
     return colour
示例#15
0
文件: engine.py 项目: bigOwlTr/puray
 def ray_trace(self, ray, scene):
     colour = Colour(0, 0, 0)
     # Find the nearest object hit by the ray in the scene
     dist_hit, obj_hit = self.find_nearest(ray, scene)
     if obj_hit is None:
         return colour
     hit_pos = ray.origin + ray.direction * dist_hit
     hit_normal = obj_hit.normal(hit_pos)
     colour += self.colour_at(obj_hit, hit_pos, hit_normal, scene)
     return colour
示例#16
0
 def make_basic_embed(self):
     c = Colour(self.colour).rgb
     new_c = discord.Colour.from_rgb(int(c[0] * 255), int(c[1] * 255),
                                     int(c[2] * 255))
     embed = discord.Embed(
         title=f'{self.registration_date.year} {self.make} {self.model}',
         colour=new_c)
     embed.add_field(name='MOT Expiry',
                     value=self.mot_expiry_date.strftime("%d/%m/%Y"),
                     inline=True)
     embed.add_field(name='Colour', value=self.colour, inline=True)
     return embed
示例#17
0
    def new_colour(_colour):
        new_colour = utilities.check_vector(_colour, int)

        if len(new_colour) == 3:
            good = True
            for i in range(3):
                if 0 > new_colour[i] > 255:
                    good = False

            if good:
                return Colour(new_colour)

        raise Exception(f'Cannot create colour {new_colour}. Make sure there are three elements between 0 and 255.')
示例#18
0
    def draw_box(self, start_x: int, start_y: int, end_x: int, end_y: int,
                 colour: Colour):
        """Draw a box

        Args:
            start_x (int): The x position of the left side of the box
            start_y (int): The y position of the bottom
            end_x (int): The x position of the right side
            end_y (int): The y position of the top
            colour (Colour): The colour of the background of the box
        Return: None
        """
        red, blue, green = colour.rgb()
        self.buffer += f"""
示例#19
0
    def pattern(self):
        stop = False
        while not stop:
            c1 = random_color()
            c1 = Colour(rgb=(c1[0] / 255.0, c1[1] / 255.0, c1[2] / 255.0))
            c2 = random_color()
            c2 = Colour(rgb=(c2[0] / 255.0, c2[1] / 255.0, c2[2] / 255.0))

            gradient = []
            for c in c1.range_to(c2, 181):
                gradient.append(
                    (int(c.red * 255), int(c.green * 255), int(c.blue * 255)))

            for angle in range(181, 0, -1):
                for bottle, bottle_angle in self.geo.get_near_bottles(
                        angle, 1):
                    if bottle_angle < angle:
                        self.trap.set_color(bottle,
                                            gradient[int(bottle_angle)])
                        sleep(.01)

            if self.stop_thread:
                stop = True
                break
示例#20
0
    def get_card(self, card_key):
        if card_key in self._card_dict:
            return self._card_dict[card_key]

        colour_val = int(card_key[0:1])
        number = int(card_key[1:])

        if colour_val < 1 or colour_val > 6:
            raise ValueError("Invalid colour val", colour_val)

        if number < 1 or number > 10:
            raise ValueError("Invalid card number", number)

        new_card = Card(Colour(colour_val), number)
        self._card_dict[card_key] = new_card
        return new_card
    def __init__(self, sprite):
        super().__init__('particle emitter')
        self.sprite = sprite

        self.rate = 1
        self.size = 3
        self.life_time = 10
        self.speed = 1
        self.angle_range = (0, 360)

        self.go = True
        self.colour = Colour((0, 0, 0))

        self.particles = []

        self.count = 0
示例#22
0
    def pixelColour(self, x, y, samples=1):
        pitch = .5 / samples
        colour = Colour(0, 0, 0)
        count = 0
        for subX in range(samples):
            for subY in range(samples):
                count += 1
                ray = self.getRay(x - .5 + (subX + 1) * pitch + subX * pitch,
                                  y - .5 + (subY + 1) * pitch + subY * pitch)
                hit = self.processRay(ray)
                colour = colour + hit.colour()
                #depth = math.log((hit.length() + 0.1), 10)
                #colour = colour + Colour(depth, depth, depth)

        self.pixels[samples] += 1
        return colour / count
 def getPixel(self, pixelBox):
     (x, y, x2, y2) = pixelBox
     pitch = old_div((x2 - x), (self.subPixels * 2))
     xx = x
     yy = y
     count = 0
     colour = Colour(0, 0, 0)
     for col in range(self.subPixels):
         for row in range(self.subPixels):
             colour += self.rayfunc(
                 Ray3(self.eye,
                      (Point3(xx + pitch, yy + pitch, 1) - self.eye)))
             count += 1
             yy += pitch * 2
         yy = y
         xx += pitch * 2
     assert count == self.subPixels * self.subPixels
     return old_div(colour, count)
示例#24
0
def create_color_stops(breaks, colors='RdYlGn', color_ramps=color_ramps):
    """Convert a list of breaks into color stops using colors from colorBrewer
    or a custom list of color values in RGB, RGBA, HSL, CSS text, or HEX format.
    See www.colorbrewer2.org for a list of color options to pass
    """

    num_breaks = len(breaks)
    stops = []

    if isinstance(colors, list):
        # Check if colors contain a list of color values
        if len(colors) == 0 or len(colors) != num_breaks:
            raise ValueError(
                'custom color list must be of same length as breaks list')

        for color in colors:
            # Check if color is valid string
            try:
                Colour(color)
            except:
                raise ValueError(
                    'The color code {color} is in the wrong format'.format(
                        color=color))

        for i, b in enumerate(breaks):
            stops.append([b, colors[i]])

    else:
        if colors not in color_ramps.keys():
            raise ValueError('color does not exist in colorBrewer!')
        else:

            try:
                ramp = color_ramps[colors][num_breaks]
            except KeyError:
                raise ValueError(
                    "Color ramp {} does not have a {} breaks".format(
                        colors, num_breaks))

            for i, b in enumerate(breaks):
                stops.append([b, ramp[i]])

    return stops
示例#25
0
    def _fade(self, colour1, colour2, steps, interval):
        self._thread_running = True
        lastUpdate = time.time() - interval
        interval = interval / steps

        for i in range(1, steps + 1):
            r = round(((colour1.r * (steps - i)) + (colour2.r * i)) / steps)
            g = round(((colour1.g * (steps - i)) + (colour2.g * i)) / steps)
            b = round(((colour1.b * (steps - i)) + (colour2.b * i)) / steps)

            while ((time.time() - lastUpdate) < interval):
                pass

            colour = Colour(r, g, b)
            for j in range(0, self._length):
                if not self.paused:
                    self._set_pixel(j, colour.r, colour.g, colour.b)

            lastUpdate = time.time()
        self._thread_running = False
        self.colour = colour2
示例#26
0
    def match_color(self, color, convert2discord=True):
        color = color.lower()
        if color in self._color_names:
            rgb = self._color_names[color]

            if not convert2discord:
                return rgb['hex']

            rgb = rgb['rgb']
            rgb = tuple(map(lambda c: c / 255.0, rgb))
        else:
            try:
                rgb = Colour(color)

                if not convert2discord:
                    return rgb.get_hex_l()

                rgb = rgb.rgb
            except:
                return

        return self.check_rgb(rgb)
示例#27
0
文件: engine.py 项目: bigOwlTr/puray
 def colour_at(self, obj_hit, hit_pos, normal, scene):
     material = obj_hit.material
     obj_colour = material.colour_at(hit_pos)
     to_cam = scene.camera - hit_pos
     specular_k = 50
     colour = material.ambient * Colour.from_hex("#000000")
     # Light calculations
     for light in scene.lights:
         to_light = Ray(hit_pos, light.position - hit_pos)
         # Diffuse shading (Lambert)
         colour += (
                 obj_colour
                 * material.diffuse
                 * max(normal.dot_product(to_light.direction), 0)
         )
         # Specular shading
         half_vector = (to_light.direction + to_cam).normalise()
         colour += (
                 light.colour
                 * material.specular
                 * max(normal.dot_product(half_vector), 0) ** specular_k
         )
     return colour
示例#28
0
    def __init__(self,
                 obj,
                 ray,
                 entry,
                 exit,
                 normal=None,
                 material=None,
                 TexCords=None):
        self.obj = obj
        self.entry = entry
        self.exit = exit
        self.normal = normal
        self.normal2 = None
        self.mat = material
        self.texCords = TexCords
        self.ray = ray

        # Undefined variables
        self.reflection = None
        self.bgcolour = None
        self.lights = [None]

        # temp ambiant for when colour is called before calcLights
        self.ambient = Colour(0.8, 0.8, 0.8)
示例#29
0
    def __init__(
        self,
        x_pos: int,
        y_pos: int,
        text: str = "",
        min_width: int = 10,
        min_height: int = 10,
    ):
        """
        Create a Box

        Args:
          x_pos: The x position of the box
          y_pos: The y position of the box
          text: The text to show in the box
          min_width: The minimum width for the box
          min_height: The minimum height for the box
        """
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.colour = Colour("black")

        # These settings are ratios of how far up/across our anchor point
        # is (0 => left, 0.5 => middle, 1 => right for x)
        self.x_anchor = 0.5
        self.y_anchor = 0.5

        self._min_width = min_width
        self._min_height = min_height

        # Option to put text at the top of the box
        self.text_top = False

        # Setting the text will actually try to resize the box so we need to
        # do this last to make sure the min and max have already been set
        self.text = text
示例#30
0
文件: main.py 项目: bigOwlTr/puray
def main():
    width = 3200
    height = 2000
    camera = Vector(0, 0, -0.5)
    lights = [
        Light(Point(0, -0.6, -6), Colour.from_hex("#FFFFFF")),
        Light(Point(5, -0.9, 10), Colour.from_hex("#FFFFFF")),
        Light(Point(-1, -0.9, 10), Colour.from_hex("#FFFFFF"))
    ]
    objects = [
        Sphere(Point(-0.53, 0, 1), 0.5, Material(Colour.from_hex("#FF0000"))),
        Sphere(Point(0.53, 0, 1), 0.5, Material(Colour.from_hex("#F80000"))),
        Sphere(Point(0, 1000000.5, 1), 1000000,
               Material(Colour.from_hex("#FFFFFF")))
    ]
    scene = Scene(camera, objects, lights, width, height)
    engine = RenderEngine()
    image = engine.render(scene)

    with open("render.ppm", "w") as img_file:
        image.write_ppm(img_file)
示例#31
0
class Shape:
	def __init__(self):
		self.poly = self.__randPoly(randint(config.POLY_MIN_SIDES, config.POLY_MAX_SIDES), 0, 0, config.PIC_W, config.PIC_H)
		self.colour = Colour() 
		self.image = self.buildImage()

	class ShapeCommand(object):
		def __init__(self, shape):
			self.shape = shape;
			self.didExecute = False

	class InsertPointCommand(ShapeCommand):
		def execute(self):
			if len(self.shape.poly) < config.POLY_MAX_SIDES:
				index = randint(1, len(self.shape.poly)-2)
				prevPoint = self.shape.poly[index-1]
				nextPoint = self.shape.poly[index+1]
				newPoint = (((prevPoint[0] + nextPoint[0]) / 2), ((prevPoint[1] + nextPoint[1]) / 2))
				self.shape.poly.insert(index, newPoint)
				self.insertedPoint = newPoint
				self.didExecute = True
		def undo(self):
			if self.didExecute:
				self.shape.poly.remove(self.insertedPoint)
	
	class RemovePointCommand(ShapeCommand):
		def execute(self):
			if len(self.shape.poly) > config.POLY_MIN_SIDES:
				self.poppedIndex = randint(0, len(self.shape.poly)-1)
				self.poppedPoint = self.shape.poly.pop(self.poppedIndex)
				self.didExecute = True
		def undo(self):
			if self.didExecute:
				self.shape.poly.insert(self.poppedIndex, self.poppedPoint) 

	class MovePointCommand(ShapeCommand):
		def __init__(self, shape, isMajor):
			super(Shape.MovePointCommand, self).__init__(shape)
			self.isMajor = isMajor
		def execute(self):
			if self.isMajor:
				move = config.PIC_W / 3
			else:
				move = 3
			self.index = randint(0, len(self.shape.poly)-1)
			point = self.shape.poly[self.index]
			x, y = point[0], point[1]
			self.oldPoint = point 
			x += randint(-move, move)
			x = min(config.PIC_W, max(0, x))
			y += randint(-move, move)
			y = min(config.PIC_H, max(0, y))
			self.shape.poly[self.index] = (x, y) 
		def undo(self):
			self.shape.poly[self.index] = self.oldPoint

	class RebuildCommand(ShapeCommand):
		def execute(self):
			self.oldImage = self.shape.image
			self.shape.image = self.shape.buildImage()
		def undo(self):
			self.shape.image = self.oldImage
	
	def mutate(self, major=False):
		commands = []
		if chance(10):
			if chance(1):
				commands.append(Shape.RemovePointCommand(self))
			else:
				commands.append(Shape.InsertPointCommand(self))
		else:
			commands.append(Shape.MovePointCommand(self, isMajor=major))
		commands.append(Shape.RebuildCommand(self))
		return commands

	def buildImage(self):
		image = Image.new('RGBA', (config.PIC_W, config.PIC_H))
		ImageDraw.Draw(image).polygon(self.poly, fill=self.colour.getTuple())
		return image

	def __randPoly(self, sides, minX, minY, maxX, maxY):
		zoneDivisor = randint(1, 4)
		zone = (randint(0, zoneDivisor-1), randint(0, zoneDivisor-1))
		size = ((maxX - minX) / zoneDivisor, (maxY - minY) / zoneDivisor)
		points = []
		start = (zone[0] * size[0], zone[1] * size[1])
		for i in xrange(sides):
			points.append((randint(start[0], start[0] + size[0]), randint(start[1], start[1] + size[1])))
		return points
示例#32
0
	def __init__(self):
		self.poly = self.__randPoly(randint(config.POLY_MIN_SIDES, config.POLY_MAX_SIDES), 0, 0, config.PIC_W, config.PIC_H)
		self.colour = Colour() 
		self.image = self.buildImage()