Exemple #1
0
 def draw_map_fog(self):
     """Рисуем вокруг игрока все на одну ячейку, учитывая границу лабиринта"""
     x_player = self.get_x_player()
     with hold_canvas(self.canvas):
         self.canvas.clear()
         for row in range(max(x_player[0] - 1, 0),
                          min(x_player[0] + 1, self.map_size - 1) + 1):
             for col in range(max(x_player[1] - 1, 0),
                              min(x_player[1] + 1, self.map_size - 1) + 1):
                 value = self.lab_map[row, col]
                 """
                 if value == obj.player:
                     self.canvas.fill_style = self.colordict[(value, self.state)]
                 else:
                     self.canvas.fill_style = self.colordict[value]
                 self.canvas.fill_rect(col * self.n_pixels, row * self.n_pixels, self.n_pixels, self.n_pixels)
                 """
                 if value == obj.player:
                     self.canvas.draw_image(
                         self.imagedict[(value, self.state)],
                         col * self.n_pixels, row * self.n_pixels)
                 elif value == obj.guard:
                     for i_guard in range(0, len(self.guard_objects)):
                         if np.array_equal(
                                 self.guard_objects[i_guard].x_guard,
                                 np.array([row, col])):
                             self.canvas.draw_image(
                                 self.imagedict[value][i_guard],
                                 col * self.n_pixels, row * self.n_pixels)
                             break
                 else:
                     self.canvas.draw_image(self.imagedict[value],
                                            col * self.n_pixels,
                                            row * self.n_pixels)
    def draw_stage(self):
        with hold_canvas(self.canvas):
            # draw live cells
            cells_index = np.where(self.stage)
            cells_x = cells_index[0] * self.cell_size
            cells_y = cells_index[1] * self.cell_size
            size_array = np.full(cells_x.shape, self.cell_size)
            self.canvas.fill_style = self.live_color
            self.canvas.fill_rects(cells_x, cells_y, size_array)
            # draw "border" of live cells
            if self.border_width != 0.0:
                self.canvas.line_width = self.border_width
                self.canvas.stroke_style = self.background_color
                self.canvas.stroke_rects(cells_x, cells_y, size_array)

            # draw dead cells
            cells_index = np.where(self.stage == False)
            cells_x = cells_index[0] * self.cell_size
            cells_y = cells_index[1] * self.cell_size
            size_array = np.full(cells_x.shape, self.cell_size)
            self.canvas.fill_style = self.dead_color
            self.canvas.fill_rects(cells_x, cells_y, size_array)
            # draw "border" of dead cells
            if self.border_width != 0.0:
                self.canvas.line_width = self.border_width
                self.canvas.stroke_style = self.background_color
                self.canvas.stroke_rects(cells_x, cells_y, size_array)
Exemple #3
0
    def loop(self):
        global _sparkplug_active_thread_id, _sparkplug_running

        # Set active thread to this thread. This will stop any other active thread.
        current_thread_id = threading.current_thread().native_id
        _sparkplug_active_thread_id = current_thread_id
        _sparkplug_running = True
        self.refresh_last_activity()

        draw = self._methods.get("draw", None)
        setup = self._methods.get("setup", None)

        if setup:
            try:
                setup()
            except Exception as e:
                self.print_status("Error in setup() function: " + str(e))
                return

        while _sparkplug_running:
            if _sparkplug_active_thread_id != current_thread_id or time.time() - _sparkplug_last_activity > NO_ACTIVITY_THRESHOLD:
                self.stop("Stopped due to inactivity")
                return

            if not draw:
                return

            with hold_canvas(self.canvas):
                try:
                    draw()
                except Exception as e:
                    self.print_status("Error in draw() function: " + str(e))
                    return

            time.sleep(1 / FRAME_RATE)
Exemple #4
0
def draw_img(canvas, file, clear=False):
    # draws resized image on canvas and returns scale used
    with hold_canvas(canvas):
        if clear:
            canvas.clear()

        sprite1 = Image.from_file(file)

        width_canvas, height_canvas = canvas.width, canvas.height
        width_img, height_img = get_image_size(file)

        ratio_canvas = float(width_canvas) / height_canvas
        ratio_img = float(width_img) / height_img

        if ratio_img > ratio_canvas:
            # wider then canvas, scale to canvas width
            scale = width_canvas / width_img
        else:
            # taller then canvas, scale to canvas hight
            scale = height_canvas / height_img

        canvas.draw_image(sprite1,
                          0,
                          0,
                          width=width_img * min(1, scale),
                          height=height_img * min(1, scale))
        return scale
Exemple #5
0
    def draw_splash(self, canvas, x, y, scale):

        if scale > 0.:
            splash_canvas = Canvas(width=self.cell_pixels,
                                   height=self.cell_pixels)
            sprite = Image.from_file('images/splash_2.png')

            with hold_canvas(splash_canvas):

                pos_x = self.cell_pixels // 2
                pos_y = self.cell_pixels // 2

                # Choose a random rotation angle
                # (but first set the rotation center with `translate`)
                splash_canvas.translate(pos_x, pos_y)
                splash_canvas.rotate(uniform(0., pi))

                # scale the image
                splash_canvas.scale(scale)

                # Restore the canvas center
                splash_canvas.translate(-pos_x, -pos_y)

                # Draw the sprite
                splash_canvas.draw_image(sprite, 0, 0)

            x_px = x * self.cell_pixels + self.padding
            y_px = y * self.cell_pixels + self.padding
            canvas.draw_image(splash_canvas,
                              x_px,
                              y_px,
                              width=self.cell_pixels,
                              height=self.cell_pixels)
Exemple #6
0
 def draw_topography(self):
     with hold_canvas(self.canvas[0]):
         self.canvas[0].save()
         self.canvas[0].scale(self.scale)
         self.canvas[0].clear()
         self.canvas[0].put_image_data(self.toposim.shaded_topography, 0, 0)
         self.canvas[0].restore()
    def side_panel_text(self,
                        x,
                        y,
                        text,
                        canvas_id=0,
                        font='bold 14px sans-serif',
                        color='#000',
                        text_align='left',
                        text_baseline='top'):
        ''' add information text in the side panel '''

        canvas = self.canvases[canvas_id]
        with hold_canvas(canvas):

            # if a central area is being used to display messages clear this
            if self.fill_center == True:
                canvas.clear_rect(70, 70, 190, 56)
            else:
                canvas.clear_rect(x, y - 5, 190, 20)
                canvas.fill_style = 'white'
                canvas.fill_rect(x, y - 5, 190, 20)

            canvas.fill_style = color
            canvas.text_align = text_align
            canvas.text_baseline = text_baseline
            canvas.font = font
            canvas.fill_text(text, x, y)
Exemple #8
0
    def draw_buckets(self):
        xsize, ysize = self.canvas[2].size

        with hold_canvas(self.canvas[2]):
            self.canvas[2].clear()

            self.canvas[2].font = '20px serif'
            self.canvas[2].fill_style = 'black'

            for i, x in enumerate(self.buckets.x_separators[0:-1]):
                self.canvas[2].fill_text(f"{i+1:02d}", x + 15, ysize - 120)

            self.canvas[2].fill_rects(self.buckets.x_separators,
                                      self.toposim.shape[0] * self.scale, 1,
                                      self.buckets_height)

            self.canvas[2].fill_style = '#3378b8'
            self.canvas[2].fill_rects(self.buckets.x_separators + 5,
                                      ysize - self.buckets.bar_heights,
                                      self.buckets.bar_width - 10,
                                      self.buckets.bar_heights)

            self.canvas[2].fill_style = 'black'
            self.canvas[2].fill_rect(0, ysize - 3, xsize, 3)
            self.canvas[2].fill_rect(0, ysize - 155, xsize, 10)
Exemple #9
0
 def draw_sprite(self, index):
     ' remove the last sprite and add the new one at the current position '
     if self.sprite_index < self.get_number_of_sprites():
         with hold_canvas(self.canvas):
             self.canvas.clear_rect(self.x, self.y, self.robot_size)
             self.canvas.draw_image(self.canvas_sprites[index], self.x,
                                    self.y)
Exemple #10
0
    def drawArrow(self, layer, x_start, y_start, x_end, y_end, savePath):

        currentCanvas = self.cdict[layer]
        with hold_canvas(currentCanvas):
            if not savePath:
                currentCanvas.clear()
            currentCanvas.stroke_line(x_start, y_start, x_end, y_end)
Exemple #11
0
def draw_bounding_box(canvas,
                      coords: list,
                      color='white',
                      line_width=None,
                      border_ratio=2,
                      clear=False,
                      stroke_color='black'):
    with hold_canvas(canvas):
        if clear:
            canvas.clear()

        pos_x, pos_y, rect_x, rect_y = coords

        canvas.line_width = line_width or log(canvas.height) / 5
        gap = canvas.line_width * border_ratio

        canvas.stroke_color = stroke_color
        canvas.fill_style = color

        canvas.stroke_rect(pos_x, pos_y, rect_x, rect_y)
        canvas.fill_rect(pos_x, pos_y, rect_x, rect_y)
        canvas.stroke_rect(pos_x, pos_y, rect_x, rect_y)
        canvas.clear_rect(pos_x + gap, pos_y + gap, rect_x - 2 * gap,
                          rect_y - 2 * gap)
        canvas.stroke_rect(pos_x + gap, pos_y + gap, rect_x - 2 * gap,
                           rect_y - 2 * gap)
Exemple #12
0
    def drawCircle(self, layer, x, y, radius, savePath):

        currentCanvas = self.cdict[layer]
        with hold_canvas(currentCanvas):
            if not savePath:
                currentCanvas.clear()
            currentCanvas.fill_circle(x, y, radius)
            currentCanvas.stroke_circle(x, y, radius)
Exemple #13
0
    def drawRectangle(self, layer, x, y, width, height, savePath):

        currentCanvas = self.cdict[layer]
        with hold_canvas(currentCanvas):
            if not savePath:
                currentCanvas.clear()
            currentCanvas.fill_rect(x, y, width, height)
            currentCanvas.stroke_rect(x, y, width, height)
Exemple #14
0
 def draw_map(self):
     with hold_canvas(self.canvas):
         self.canvas.clear()
         for row in range(len(self.map)):
             for col in range(len(self.map[0])):
                 value = self.map[row][col]
                 self.buttons[row][col].icon = self.icons[value]
                 self.buttons[row][col].disabled = value != obj.space
Exemple #15
0
    def draw_particles(self):
        x, y = self.particles.positions

        with hold_canvas(self.canvas[1]):
            self.canvas[1].clear()
            self.canvas[1].global_alpha = 0.4
            self.canvas[1].fill_style = '#3378b8'
            self.canvas[1].fill_rects(x, y, self.particles.sizes)
Exemple #16
0
    def update(self, img, out):

        resized = cv2.resize(img, (self.width, self.height),
                             interpolation=cv2.INTER_AREA)

        with hold_canvas(self.canvas):
            self.canvas.clear()
            self.canvas.put_image_data(resized, 0, 0)
Exemple #17
0
    def re_draw(self):

        with hold_canvas(self):
            canvas = self[1]
            canvas.clear()
            # draw all existing polygons:
            for point in self.points:
                self.draw_point(point)
Exemple #18
0
def stroke_lines(canvas, mvp, lines, scale=None, translation=None):
    """Lines is a 2n x 3 matrix with start and end points interleaved"""
    # project with camera
    transformed_lines = scale * dehomogenize(
        mvp @ homogenize(lines.T)).T + translation

    with hold_canvas(canvas):
        for p1, p2 in pairwise(transformed_lines):
            stroke_line(canvas, p1, p2)
Exemple #19
0
    def re_draw(self, change=None):

        with hold_canvas(self):
            self[1].clear()
            # draw all existing polygons:
            for polygon in self.polygons:
                self.draw_polygon(polygon)
            # draw the current polygon:
            self.draw_polygon(self.current_polygon, tentative=True)
Exemple #20
0
    def re_draw(self):
        """Re-draw the data onto the canvas."""

        with hold_canvas(self):
            canvas = self[1]
            canvas.clear()
            # draw all existing polygons:
            for point in self.points:
                self.draw_point(point)
Exemple #21
0
        def on_mouse_move(x, y):
            global drawing

            if not drawing:
                return

            with hold_canvas(canvas):
                canvas.fill_style = 'black'
                canvas.fill_circle(x, y, 8)
Exemple #22
0
 def _draw_turtle(self):
     """Update the position of the turtle."""
     with hold_canvas(self._canvas[2]):
         self._canvas[2].clear()
         self._canvas[2].reset_transform()
         if self._show:
             self._canvas[2].translate(self._current[0], self._current[1])
             self._canvas[2].rotate(self._cur_heading - (3 * math.pi) / 2)
             self._canvas[2].draw_image(self._turtle, x=-15, y=-15, \
                 width=30, height=30)
Exemple #23
0
    def re_draw(self, change=None):

        with hold_canvas(self):
            self.annotation_canvas.clear()
            # draw all existing polygons:
            for annotation in self.annotations:
                self.draw_box(annotation)
            # draw the current box:
            if self._proposed_annotation is not None:
                self.draw_box(self._proposed_annotation, proposed=True)
Exemple #24
0
 def animate(self, x, y, room, t):
     canvas = self.full_render(x[0], y[0], room[0])
     for i in range(1,len(t)):
         with hold_canvas(canvas):
             # Clear the old animation step
             canvas.clear()
             canvas = self.full_render(x[i], y[i], room[i], canvas=canvas)
         # Animation frequency ~50Hz = 1./50. seconds
         sleep(0.02)
         canvas
Exemple #25
0
 def animate(self, coord, Zone, t):
     canvas = self.full_render(coord[0], Zone[0])
     for i in range(1, len(t)):
         with hold_canvas(canvas):
             # Clear the old animation step
             canvas.clear()
             canvas = self.full_render(coord[i], Zone[i], canvas=canvas)
         # Animation frequency ~50Hz = 1./50. seconds
         sleep(0.02)
         canvas
Exemple #26
0
    def _display_image(self, *change):
        image = self.image_crop
        if self.image_brightness != 1 or self.image_contrast != 1:
            image = adjust(
                image,
                contrast_factor=self.image_contrast,
                brightness_factor=self.image_brightness,
            )

        with hold_canvas(self.image_canvas):
            self.image_canvas.draw_image(pil_to_widget(image))
            self.image_canvas.stroke_rect(0, 0, self.width, self.height)
Exemple #27
0
 def _do_draw(self):
     """Context manager that combines all drawing operations and re-renders the turtle."""
     with hold_canvas(self._canvas):
         yield 
         self._canvas[2].clear()
         if self._show:
             self._canvas[2].save()
             self._canvas[2].translate(self._current.x, self._current.y)
             self._canvas[2].rotate(self._cur_heading + math.pi / 2)
             self._canvas[2].draw_image(self._turtle, 
                 x=-15, y=-15, 
                 width=30, height=30)
             self._canvas[2].restore()
Exemple #28
0
 def redraw(self):
     if self.update_map():
         with hold_canvas(self.canvas):
             for row in range(len(self.map)):
                 for col in range(len(self.map[row])):
                     cell = self.map[row][col]
                     if cell['obj'] == obj.player:
                         for user_i in self.users:
                             if user_i['id'] == cell['userid']:
                                 if user_i['state'] == player_state.hide:
                                     self.canvas.clear_rect(
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS, CELL_PIXELS,
                                         CELL_PIXELS)
                                     self.canvas.draw_image(
                                         self.images_ava_hide[
                                             cell['image']],
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS)
                                 elif user_i[
                                         'state'] == player_state.active:
                                     self.canvas.clear_rect(
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS, CELL_PIXELS,
                                         CELL_PIXELS)
                                     self.canvas.draw_image(
                                         self.images_ava[(cell['obj'],
                                                          cell['image'])],
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS)
                                 elif user_i[
                                         'state'] == player_state.killed:
                                     self.canvas.draw_image(
                                         self.image_killed,
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS)
                                 elif user_i[
                                         'state'] == player_state.inactive:
                                     self.canvas.clear_rect(
                                         col * CELL_PIXELS,
                                         row * CELL_PIXELS, CELL_PIXELS,
                                         CELL_PIXELS)
                     elif cell['obj'] in [obj.chest, obj.guard, obj.ball]:
                         self.canvas.draw_image(
                             self.images_ava[(cell['obj'], cell['image'])],
                             col * CELL_PIXELS, row * CELL_PIXELS)
                     elif cell['obj'] == obj.space:
                         self.canvas.clear_rect(col * CELL_PIXELS,
                                                row * CELL_PIXELS,
                                                CELL_PIXELS, CELL_PIXELS)
         self.update_panel()
Exemple #29
0
        def on_predict(*args, **kwargs):
            with hold_canvas(canvas):
                img_array = canvas.get_image_data()
                img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY)
                img_array = cv2.bitwise_not(img_array)
                img_array = cv2.resize(img_array, (28, 28))

                img_array = img_array / 255.0
                img_array = np.reshape(img_array, 784)
                img_array = np.array(img_array, ndmin=2).T
                result = self.predict(img_array)[1]
                label = np.argmax(result)
                canvas.font = '32px serif'
                canvas.fill_text(label, 10, 32)
Exemple #30
0
 def draw_base(self, color='black'):
     self.update_map()
     with hold_canvas(self.canvas_base):
         self.canvas_base.clear()
         self.canvas_base.fill_style = color
         self.canvas_base.fill_rect(0, 0, self.canvas_base.size[0],
                                    self.canvas_base.size[1])
         for row in range(len(self.map)):
             for col in range(len(self.map[row])):
                 cell = self.map[row][col]
                 if cell['obj'] == obj.wall:
                     self.canvas_base.draw_image(
                         self.images_ava[(obj.wall, '')], col * CELL_PIXELS,
                         row * CELL_PIXELS)