コード例 #1
0
class BlackLine(Task):
    """run at black line"""
    def __init__(self):
        self.passed = False
        self.last_rotation = False  # False - right, True - left
        self.color = Color()
        self.engine = Engine()

    def run(self):
        if self.color.is_path():
            self.engine.step()
        else:
            self.find_path()

    def find_path(self):
        if self.last_rotation:
            self.engine.step_left()
            # rewrite it after line-detectors adding
            if not self.color.is_path():
                self.engine.step_right()
                self.last_rotation = False
        else:
            self.engine.step_right()
            # rewrite it after line-detectors adding
            if not self.color.is_path():
                self.engine.step_left()
                self.last_rotation = True
コード例 #2
0
def show_map(dungeon, visited_squares=[], debug=False):
    d = ""
    wall = Color("#").cyan().render()
    door = Color("x").yellow().render()
    path = Color(".").dim().render()
    for y in range(len(dungeon)):
        for x in range(len(dungeon[y])):
            tile = dungeon[y][x]
            if debug:
                if tile is 1:
                    d += wall
                elif tile is 3:
                    d += door
                elif tile is 0:
                    d += path
            else:
                is_outer_wall = (y is 0 or x is 0 or y is len(dungeon) - 1
                                 or x is len(dungeon[y]) - 1)
                if is_outer_wall:
                    d += wall
                    continue

                if (x, y) in visited_squares:
                    if tile is 1:
                        d += wall
                    elif tile is 3:
                        d += door
                    elif tile is 0:
                        d += path
                else:
                    d += "#"

        d += "\n"
    return d
コード例 #3
0
ファイル: employee.py プロジェクト: ertolv/verklegtnamskeid
class Employee:
    """An employee has:
        title: str
        name: str
        user_id: str
        password: str
    """
    def __init__(self, title="", name="", user_id="", password=""):
        self.__title = title
        self.__name = name
        self.__id = user_id
        self.__password = password
        self.color = Color()

    def get_name(self):
        return self.__name

    def get_id(self):
        return self.__id

    def get_password(self):
        return self.__password

    def __str__(self):
        return "[{}] {}. {}".format(
            self.color.return_colored(self.__id, "yellow"),
            self.color.return_colored(self.__title, "bold"),
            self.color.return_colored(self.__name, "bold"))
コード例 #4
0
    def detect_first_task(self):
        measure_count = 0
        color = Color()
        for i in range(10):
            if color.is_path():
                measure_count++
            pyb.delay(100)

        if measure_count > 7:
            self.tasks = self.tasks[1:]
コード例 #5
0
def determineColor(outterBox, innerBox, grayscale, randomness, colors, tones):
    color = Color()

    randomness = int((randomness/100.0)*255);

    # color.r = max(0, min(255, int(outterBox.relativeX(innerBox.minX, 255)) + random.randint(-spread,spread)))
    # color.g = color.r if grayscale else max(0, min(255, int(outterBox.relativeY(innerBox.minY, 255)) + random.randint(-spread,spread)))
    # color.b = color.r if grayscale else  max(0, min(255, (color.r+color.g)/2 + random.randint(-spread,spread)))
    baseB = int((((outterBox.relativeX(innerBox.minX) - 50)/50)**2)*255)
    baseG = int((((outterBox.relativeY(innerBox.minY) - 50)/50)**2)*255)
    baseR = int((baseB+baseG)/2)

    if colors is not None:
        # sem by se hodilo něco komplexnějšího, ať je nějaký pattern...
        base = colors[random.randint(0, len(colors) - 1)]
        baseR = base.r
        baseG = base.g
        baseB = base.b

    if tones:
        negative = min(randomness, baseR if baseR else 255, baseG if baseG else 255, baseB if baseB else 255)
        positive = min(randomness, (255 - baseR) if baseR < 255 else 255, (255 - baseG) if baseG < 255 else 255, (255 - baseB) if baseB < 255 else 255)
        diff = random.randint(-negative, positive)
        color.r = max(0, min(255, baseR + diff))
        color.g = color.r if grayscale else max(0, min(255, baseG + diff))
        color.b = color.r if grayscale else max(0, min(255, baseB + diff))
    else:
        color.b = random.randint(min(255, max(0, baseB - randomness)), min(255, max(0, baseB + randomness)))
        color.g = color.b if grayscale else random.randint(min(255, max(0, baseG - randomness)), min(255, max(0, baseG + randomness)))
        color.r = color.b if grayscale else random.randint(min(255, max(0, baseR - randomness)), min(255, max(0, baseR + randomness)))

    return color
コード例 #6
0
    def effect(self):
        tree = None
        if self.options.input_filename:
            tree = etree.parse(open(self.options.input_filename))
        else:
            tree = self.document

        paths = findElements(tree, "path", self.selected)
        polygons = findElements(tree, "polygon", self.selected)
        colors = None if not self.options.colors else [Color.FromRGB(c) for c in re.findall("[a-z0-9]{6}", self.options.colors, re.IGNORECASE)]

        if self.options.change_fill:
            fill(tree, paths + polygons, self.options.color_space, self.options.grayscale, self.options.randomness, colors, self.options.tones)
        if self.options.change_lines:
            stroke(tree, paths + polygons, self.options.color_space, self.options.lines_width, Color.FromRGB(self.options.lines_color))
        if self.options.change_opacity:
            opacity(tree, paths + polygons, self.options.remove_opacity, float(self.options.opacity_start), float(self.options.opacity_end), self.options.opacity_formula)

        if self.options.input_filename:
            etree.register_namespace('namespace',"http://www.w3.org/2000/svg")
            xml = etree.tostring(tree.getroot())
            xml =  minidom.parseString(xml).toprettyxml(indent="  ")
            target_file = output_file(self.options.input_filename, self.options.color_space)
            if self.options.overwrite:
                target_file = self.options.input_filename
            with open(target_file, 'w') as file:
                file.write(re.sub("(\s*\n)+", "\n", xml, re.MULTILINE))
コード例 #7
0
def generatePalette(hex):
    color = Color.fromHex(hex)

    if not color:
        return None

    result = {}
    contrast = {}

    for i in [0.5, *range(1, 10)]:
        name = f"{int(i * 100)}"
        shade = color.clone()
        shade.scale((5 - i) / 5)
        result[name] = shade.hex

        againstBlack = (shade.luminance + 0.05) / 0.05
        againstWhite = 1.05 / (shade.luminance + 0.05)
        contrast[
            name] = white if shade.whiteContrast > shade.blackContrast else black

    color.saturate()
    for i in [1, 2, 4, 7]:
        name = f"A{i * 100}"
        shade = color.clone()
        shade.scale((5 - i) / 5)
        result[name] = shade.hex
        contrast[
            name] = white if shade.whiteContrast > shade.blackContrast else black

    result["contrast"] = contrast

    return result
コード例 #8
0
ファイル: board.py プロジェクト: braddotcoffee/AI-Project-2
 def __deepcopy__(self, memodict={}):
     copy_obj = Board(self.color)
     for coord in self.all_empty():
         copy_obj.add_empty_piece(coord)
     for coord in self.all_friendly():
         copy_obj.direct_add_piece(Piece(self.color, coord))
     for coord in self.all_enemy():
         copy_obj.direct_add_piece(Piece(Color.opposite(self.color), coord))
     return copy_obj
コード例 #9
0
ファイル: main.py プロジェクト: jake92918/Neopixel-Controller
    def index():
        if request.method == 'POST':
            data = request.form

            main.color = Color(int(data['red']), int(data['green']),
                               int(data['blue']))
            main.brightness = int(data['brightness'])

            controller.brightness(main.brightness)

            if data['submit'] == 'apply':
                main.state = True
                controller.clear()
                controller.color(main.color)
                controller.brightness(main.brightness)

            elif data['submit'] == 'effect':
                main.state = True
                controller.clear()
                controller.brightness(main.brightness)

                if data['effect'] in main.effects:
                    controller.start_effect(
                        data['effect'],
                        Color(int(data['red']), int(data['green']),
                              int(data['blue'])))
            elif data['submit'] == 'off':
                main.state = False
                controller.clear()

            if main.state:
                db.update({'color': main.color.__str__()}, query.color != '')
                db.update({'brightness': main.brightness},
                          query.brightness != '')

            db.update({'state': main.state}, query.state != '')

            return redirect(url_for('index'))

        return render_template('index.html',
                               effects=main.effects,
                               color=main.color,
                               brightness=main.brightness)
コード例 #10
0
ファイル: main.py プロジェクト: jake92918/Neopixel-Controller
    def color(red, green, blue):
        if not red or not green or not blue:
            abort(400)

        main.state = True
        main.color = Color(int(red), int(green), int(blue))
        controller.color(main.color)
        db.update({'color': main.color.__str__()}, query.color != '')

        return jsonify({'color': main.color.__str__()}), 201
コード例 #11
0
def get_gradients_from_schedule_file(schedule_file_name: str) -> List[Gradient]:
    sunrise_secs, sunset_secs = get_sunrise_and_sunset_seconds()

    gradients = []

    with open(schedule_file_name) as schedule_file:
        reader = csv.DictReader(schedule_file)

        for line in reader:
            time_string = line['timeslot']

            if time_string == 'SR':
                seconds = sunrise_secs
            elif time_string == 'SS':
                seconds = sunset_secs
            else:
                [hour, minute] = time_string.split(':')
                seconds = int(hour) * 3600 + int(minute) * 60

            color_1 = Color(
                red=int(line['red_1']),
                green=int(line['green_1']),
                blue=int(line['blue_1']),
            )

            color_2 = Color(
                red=int(line['red_2']),
                green=int(line['green_2']),
                blue=int(line['blue_2']),
            )

            gradients.append(
                Gradient(
                    seconds=seconds,
                    color_1=color_1,
                    color_2=color_2,
                    brightness=float(line['brightness']) / 100.0,
                    scroll_speed=float(line['scroll_speed']),
                )
            )
        return sorted(gradients, key=lambda gradient: gradient.seconds)
コード例 #12
0
class Start(Task):
    """get out from start place"""

    def __init__(self):
        self.passed = False
        self.color = Color()
        self.engine = Engine()

    def run(self):
        if self.color.is_path():
            self.passed = True
        else:
            self.engine.step()
コード例 #13
0
ファイル: main.py プロジェクト: jake92918/Neopixel-Controller
    def init():
        if db.search(query.color != ''):
            result = db.get(query.color != '')['color'].split(',')
            main.color = Color(int(result[0]), int(result[1]), int(result[2]))

        if db.search(query.brightness != ''):
            result = db.get(query.brightness != '')
            main.brightness = result['brightness']

        if db.search(query.state != ''):
            result = db.get(query.state != '')
            main.state = bool(result['state'])

        if main.state:
            controller.color(main.color)
            controller.brightness(main.brightness)

        main.effects = controller.effects()
コード例 #14
0
ファイル: tests.py プロジェクト: BaderSZ/pollenflug
    def test_colors(self):
        """Test the Color class. Specifically go for:

        - format_color() function
        - value to Enum conversion
        """
        # Test default = no coloring
        self.assertEqual(Color.format_color("Hello, World!"), "Hello, World!")

        # Test color<-> number conversion
        self.assertEqual(Color("0"), Color.GREEN)
        self.assertEqual(Color("1"), Color.ORANGE)
        self.assertEqual(Color("2"), Color.ORANGE_TOO)
        self.assertEqual(Color("3"), Color.RED)

        # Test some function colors
        self.assertEqual(Color.format_color("Hello, nothing!"),
                         "Hello, nothing!")
        self.assertEqual(Color.format_color("Hello, Red!", Color.RED),
                         "\033[91mHello, Red!\033[0m")
        self.assertEqual(Color.format_color("Hello, Green!", Color.GREEN),
                         "\033[92mHello, Green!\033[0m")
        self.assertEqual(Color.format_color("Hello, Orange!", Color.ORANGE),
                         "\033[93mHello, Orange!\033[0m")
コード例 #15
0
    def run(self):
        
        while(self.pollNextMove):
           
            #wait several ms,
            # then poll for move_file            
            time.sleep(0.5)
            #//TODO: Make the time delay lower
            
            if(os.path.isfile(self.groupname + ".go")):

                if(os.path.isfile("end_game")):
                   self.pollNextMove = False
                   break

                enemy_move = Hands.check_move_file()
                #//TODO: Start all the things
                if(self.first_move):
                    self.first_move = False
                    if enemy_move: 
                        self.color = Color.BLACK
                        self.body = Body(self.color)
                    else: # Executes one at most
                        self.color = Color.WHITE
                        self.body = Body(self.color)
                        self.write_move(self.mids[random.randint(0,3)])
                        continue

                # Normal Gameflow
                enemy_move = enemy_move.split()
                x = Hands.mapLetterToNumber(enemy_move[1])
                y = int(enemy_move[2])
                enemy_piece = Piece(Color.opposite(self.color), Coordinate(x,y))
                self.body.enemy_made_move(enemy_piece)
                our_move = self.body.make_move()
                self.write_move(our_move)
                time.sleep(3)
コード例 #16
0
def __render_player_name(player_name, player_title):
    return Color("{} the {}".format(player_name, player_title)).yellow().render()
コード例 #17
0
def __render_stat(stat_name, stat_value):
    stat_name_colored = Color(stat_name).yellow().render()
    stat_value_colored = Color(stat_value).white().render()
    return "{}: {}".format(stat_name_colored, stat_value_colored)
コード例 #18
0
def __render_weapon(weapon_name):
    label = Color("Weapon").yellow().render()
    weapon_colored = Color(weapon_name).green().render()
    return "{}: {}".format(label, weapon_colored)
コード例 #19
0
 def __init__(self):
     self.nocco_key = NoccoKey()
     self.color = Color()
     self.frame = Frame()
コード例 #20
0
def get_color_from_dict(color_dict: Dict[str, int]) -> Color:
    return Color(
        red=color_dict['r'],
        green=color_dict['g'],
        blue=color_dict['b'],
    )
コード例 #21
0
ファイル: lighthaus.py プロジェクト: ianrust/lighthouse
    def run(self) -> queue.Queue:
        assert not self.is_running
        self.is_running = True

        in_q = queue.Queue()

        graphics_thread = threading.Thread(target=self._run,
                                           kwargs=dict(in_q=in_q),
                                           daemon=True)
        graphics_thread.start()

        return in_q


if __name__ == '__main__':
    writer = create_neopixel_writer()

    controller = LighthausController(
        writer=writer,
        initial_color_1=Color(red=255, blue=0, green=0),
        initial_color_2=Color(red=0, blue=255, green=0),
        initial_scroll_speed=0.01,
    )

    controller_in_q = controller.run()
    update_from_schedule_async(controller_in_q)

    app = Flask(__name__)
    setup_endpoint(app, controller_in_q)
コード例 #22
0
class NoccoList:
    def __init__(self):
        self.nocco_key = NoccoKey()
        self.color = Color()
        self.frame = Frame()

    def print_alternatives(self, question, alternatives, alternative_index):
        print("[{}] {}: {}".format(
            self.color.return_colored("!", "yellow"), question,
            self.color.return_colored(alternatives[alternative_index],
                                      "bold")))
        for i, alternative in enumerate(alternatives):
            if i == alternative_index:
                if alternative == alternatives[-1]:
                    print()
                    print("   {}".format(
                        self.color.return_colored("> " + alternative, "red")))
                else:
                    print("   {}".format(
                        self.color.return_colored("> " + alternative, "cyan")))
            else:
                if alternative == alternatives[-1]:
                    print()
                print("     {}".format(alternative))

    def choose_one(self,
                   question,
                   alternatives,
                   answer_key,
                   get_chosen_index=False):
        """ from a list of alternatives, let user choose one of them """

        alternative_index = 0
        answer_from_user = ""
        #print the alternatives
        self.print_alternatives(question, alternatives, alternative_index)
        while not answer_from_user:  # run until the user chooses an alternative
            key = self.nocco_key.getKey()
            if key == "up":
                if alternative_index != 0:
                    alternative_index -= 1
            elif key == "down":
                if alternative_index != len(alternatives) - 1:
                    alternative_index += 1
            elif key == "right":
                if get_chosen_index:
                    answer_from_user = {
                        answer_key: alternatives[alternative_index],
                        "index": alternative_index
                    }
                else:
                    answer_from_user = {
                        answer_key: alternatives[alternative_index]
                    }
            elif key == "left":
                pass
            else:
                if os.name == "nt":  # for Windows
                    key = key.decode("utf-8")
                if key not in string.digits and key not in string.ascii_letters and key not in string.punctuation:
                    if get_chosen_index:
                        answer_from_user = {
                            answer_key: alternatives[alternative_index],
                            "index": alternative_index
                        }
                    else:
                        answer_from_user = {
                            answer_key: alternatives[alternative_index]
                        }
            self.frame.delete_last_lines(len(alternatives) + 2)
            self.print_alternatives(question, alternatives, alternative_index)

        # return answer
        return answer_from_user

    def single_list(self, alternative):
        """ 
            Only one alternative. Useful when for instance only giving 
            "Go back" alternative to the user 
        """
        print()
        print(" {}".format(self.color.return_colored("> " + alternative,
                                                     "red")))

        pressed = False

        while not pressed:
            key = self.nocco_key.getKey()  # get key_press from user
            enter_key = string.digits + string.ascii_letters + string.punctuation
            if key not in enter_key and key != "down" and key != "up":
                pressed = True
            self.frame.delete_last_lines(1)
            print(" {}".format(
                self.color.return_colored("> " + alternative, "red")))
コード例 #23
0
ファイル: board.py プロジェクト: braddotcoffee/AI-Project-2
 def all_enemy(self):
     return self._board[Color.opposite(self.color)]
コード例 #24
0
 def __init__(self):
     self.passed = False
     self.last_rotation = False  # False - right, True - left
     self.color = Color()
     self.engine = Engine()
コード例 #25
0
ファイル: board.py プロジェクト: braddotcoffee/AI-Project-2
 def is_enemy(self, coordinate):
     return coordinate in self._board[Color.opposite(self.color)]
コード例 #26
0
 def color(self):
     return Color(self.spectrum, 1, self.name)
コード例 #27
0
 def __init__(self):
     self.passed = False
     self.color = Color()
     self.engine = Engine()
コード例 #28
0
ファイル: employee.py プロジェクト: ertolv/verklegtnamskeid
 def __init__(self, title="", name="", user_id="", password=""):
     self.__title = title
     self.__name = name
     self.__id = user_id
     self.__password = password
     self.color = Color()
コード例 #29
0
ファイル: main.py プロジェクト: jake92918/Neopixel-Controller
def main():
    app = Flask(__name__)
    controller = Controller(config.controller['leds'],
                            config.controller['neopixel_gpio_pin'],
                            config.controller['neopixel_frequency'],
                            config.controller['neopixel_dma'],
                            config.controller['neopixel_invert'],
                            config.controller['neopixel_brightness'],
                            config.controller['neopixel_channel'],
                            config.controller['neopixel_strip'])
    db = TinyDB('data/database.json')
    query = Query()

    app.config['SECRET_KEY'] = os.urandom(24)

    CSRFProtect(app)

    main.color = Color(0, 0, 0)
    main.brightness = 255
    main.state = False
    main.effects = []

    @app.before_first_request
    def init():
        if db.search(query.color != ''):
            result = db.get(query.color != '')['color'].split(',')
            main.color = Color(int(result[0]), int(result[1]), int(result[2]))

        if db.search(query.brightness != ''):
            result = db.get(query.brightness != '')
            main.brightness = result['brightness']

        if db.search(query.state != ''):
            result = db.get(query.state != '')
            main.state = bool(result['state'])

        if main.state:
            controller.color(main.color)
            controller.brightness(main.brightness)

        main.effects = controller.effects()

    @app.route('/', methods=['GET', 'POST'])
    def index():
        if request.method == 'POST':
            data = request.form

            main.color = Color(int(data['red']), int(data['green']),
                               int(data['blue']))
            main.brightness = int(data['brightness'])

            controller.brightness(main.brightness)

            if data['submit'] == 'apply':
                main.state = True
                controller.clear()
                controller.color(main.color)
                controller.brightness(main.brightness)

            elif data['submit'] == 'effect':
                main.state = True
                controller.clear()
                controller.brightness(main.brightness)

                if data['effect'] in main.effects:
                    controller.start_effect(
                        data['effect'],
                        Color(int(data['red']), int(data['green']),
                              int(data['blue'])))
            elif data['submit'] == 'off':
                main.state = False
                controller.clear()

            if main.state:
                db.update({'color': main.color.__str__()}, query.color != '')
                db.update({'brightness': main.brightness},
                          query.brightness != '')

            db.update({'state': main.state}, query.state != '')

            return redirect(url_for('index'))

        return render_template('index.html',
                               effects=main.effects,
                               color=main.color,
                               brightness=main.brightness)

    @app.route('/api/v1.0/state/<string:state>', methods=['GET'])
    def state(state):
        if not state:
            abort(400)

        main.state = True if state == 'true' else False
        db.update({'state': main.state}, query.state != '')
        controller.clear()

        if main.state:
            controller.color(main.color)
            controller.brightness(main.brightness)

        return jsonify({'state': main.state}), 201

    @app.route('/api/v1.0/color/<int:red>/<int:green>/<int:blue>',
               methods=['GET'])
    def color(red, green, blue):
        if not red or not green or not blue:
            abort(400)

        main.state = True
        main.color = Color(int(red), int(green), int(blue))
        controller.color(main.color)
        db.update({'color': main.color.__str__()}, query.color != '')

        return jsonify({'color': main.color.__str__()}), 201

    @app.route('/api/v1.0/brightness/<int:brightness>', methods=['GET'])
    def brightness(brightness):
        if not brightness:
            abort(400)

        main.state = True
        main.brightness = int(brightness)
        controller.brightness(main.brightness)
        db.update({'brightness': main.brightness}, query.brightness != '')

        return jsonify({'brightness': main.brightness}), 201

    app.run(host='0.0.0.0', port=5000)
    db.close()
    atexit.register(controller.__exit__)