Example #1
0
    def __init__(self):
        self.start_game_button = MainMenuState.main_menu_button(
            'start game',
            lambda: pygame.event.post(make_event(
                GameEvent.CHANGE_STATE,
                state=LevelState()
            ))
        )

        self.ai_button = MainMenuState.main_menu_button(
            'ai',
            lambda: print('click ai'),
        )

        self.quit_game_button = MainMenuState.main_menu_button(
            'quit game',
            lambda: pygame.event.post(pygame.event.Event(QUIT))
        )

        self.button_sprites: Union[pygame.sprite.Group, Iterable[Button]] = pygame.sprite.Group()
        self.button_sprites.add(self.start_game_button)
        self.button_sprites.add(self.ai_button)
        self.button_sprites.add(self.quit_game_button)

        self.button_layout = Layout(vpadding_inner=20)
        self.button_layout.add_all(self.button_sprites)
Example #2
0
 def __init__(self, rows=2, cols=2):
     Element.__init__(self, gtk.Table(rows, cols))
     self.layout = Layout(0, 0)
     self.entry_rows = None
     self.entry_cols = None
     self.targets = {}
     self.child.set_row_spacings(3)
     self.child.set_col_spacings(3)
     self._resize_table(rows, cols)
Example #3
0
 def __init__(self, app):
     
     self.__organisms = []
     self.__born = []
     self.__dead = []
     self.__sheeps = []
     self.__heracleums = []
     self.__organismsC = 0
     self.__start = False
     self.__changed = False
     self.__layout = Layout(self, app)
Example #4
0
 def __init__(self, genome=Genome(), flc=FeatureListContainer(), initial_position=3520, initial_startRange=0, initial_endRange=5000):
     self.genome=genome
     self.featureListContainer=flc
     self.position=initial_position
     self.startRange=initial_startRange
     self.endRange=initial_endRange
     self.layout=Layout()
Example #5
0
 def __init__(self, parent=None, rect=sf.Rectangle(),\
         alignment = Position.Center, spacing=sf.Vector2(0, 0), \
         autoDefineSize = True, select=False, active=False, \
         alwaysUpdateSelection=True, alwaysUpdateActivation=True, \
         permanentSelection=False, permanentActivation=False, \
         changeRight = sf.Keyboard.RIGHT, changeLeft = sf.Keyboard.LEFT,\
         changeTop = sf.Keyboard.UP, changeBottom = sf.Keyboard.DOWN):
     Layout.__init__(self, parent, rect, alignment, spacing, autoDefineSize)
     Active.__init__(self, select, active, alwaysUpdateSelection,\
             alwaysUpdateActivation, permanentSelection, permanentActivation)
     self.canFocus=False
     self.changeLeft = changeLeft
     self.changeRight = changeRight
     self.changeTop = changeTop
     self.changeBottom = changeBottom
     self._howActiveKeyboard = [self.changeLeft, self.changeRight, self.changeTop, self.changeBottom]
     self._currentSelect = None
Example #6
0
 def __init__(self, genome=Genome(), flc=FeatureListContainer(), initial_upperCase=True, initial_charsPerLine=50, initial_position=3520, initial_startRange=0, initial_endRange=5000):
     self.genome=genome
     self.featureListContainer=flc
     self.upperCase=initial_upperCase
     self.charsPerLine=initial_charsPerLine
     self.position=initial_position
     self.startRange=initial_startRange
     self.endRange=initial_endRange
     self.layout=Layout()
Example #7
0
 def __init__(self, rows = 2, cols = 2):
     Element.__init__(self, gtk.Table(rows, cols))
     self.layout     = Layout(0, 0)
     self.entry_rows = None
     self.entry_cols = None
     self.targets    = {}
     self.child.set_row_spacings(3)
     self.child.set_col_spacings(3)
     self._resize_table(rows, cols)
Example #8
0
 def __init__(self, textbuffer=None, *args, **kwargs):
     if textbuffer is None:
         textbuffer = TextBuffer()
     gtk.TextView.__init__(self, textbuffer, *args, **kwargs)
     self.buffer = textbuffer
     self.anno_width = 200
     self.anno_padding = 10
     self.anno_layout = Layout(self)
     self.anno_views = {}
     self.show_annotations = True
     self.handle_links = True
     self.set_right_margin(50 + self.anno_padding)
     self.connect('map-event', self._on_map_event)
     self.connect('expose-event', self._on_expose_event)
     self.connect('motion-notify-event', self._on_motion_notify_event)
     self.connect('event-after', self._on_event_after)
     self.buffer.connect('mark-set', self._on_buffer_mark_set)
     self.buffer.connect('annotation-added', self._on_annotation_added)
     self.buffer.connect('annotation-removed', self._on_annotation_removed)
     self.set_wrap_mode(gtk.WRAP_WORD)
Example #9
0
    def __init__(self, name, facility):
        Layout.__init__(self, name, facility)

        # containing communicator
        self.ccomm = None

        # embedded comminicator1
        self.ecomm1 = None

        # embedded comminicator2
        self.ecomm2 = None

        # list of communicators created to pass imformation
        # between different solvers
        self.ccommPlus1 = []
        self.ccommPlus2 = []
        self.ecommPlus1 = []
        self.ecommPlus2 = []

        self.comm = None
        self.rank = 0
        self.nodes = 0
        return
Example #10
0
    def __init__(self, name, facility):
        Layout.__init__(self, name, facility)

        # containing communicator
        self.ccomm = None

        # embedded comminicator1
        self.ecomm1 = None

        # embedded comminicator2
        self.ecomm2 = None

        # list of communicators created to pass imformation
        # between different solvers
        self.ccommPlus1 = []
        self.ccommPlus2 = []
        self.ecommPlus1 = []
        self.ecommPlus2 = []

        self.comm = None
        self.rank = 0
        self.nodes = 0
        return
Example #11
0
 def __init__(self, textbuffer = None, *args, **kwargs):
     if textbuffer is None:
         textbuffer = TextBuffer()
     gtk.TextView.__init__(self, textbuffer, *args, **kwargs)
     self.buffer           = textbuffer
     self.anno_width       = 200
     self.anno_padding     = 10
     self.anno_layout      = Layout(self)
     self.anno_views       = {}
     self.show_annotations = True
     self.handle_links     = True
     self.set_right_margin(50 + self.anno_padding)
     self.connect('map-event',           self._on_map_event)
     self.connect('expose-event',        self._on_expose_event)
     self.connect('motion-notify-event', self._on_motion_notify_event)
     self.connect('event-after',         self._on_event_after)
     self.buffer.connect('mark-set',           self._on_buffer_mark_set)
     self.buffer.connect('annotation-added',   self._on_annotation_added)
     self.buffer.connect('annotation-removed', self._on_annotation_removed)
     self.set_wrap_mode(gtk.WRAP_WORD)
Example #12
0
class Table(Element):
    name = 'table'
    caption = 'Table'
    xoptions = gtk.EXPAND | gtk.FILL
    yoptions = gtk.FILL

    def __init__(self, rows=2, cols=2):
        Element.__init__(self, gtk.Table(rows, cols))
        self.layout = Layout(0, 0)
        self.entry_rows = None
        self.entry_cols = None
        self.targets = {}
        self.child.set_row_spacings(3)
        self.child.set_col_spacings(3)
        self._resize_table(rows, cols)

    def has_layout(self):
        return True

    def copy(self):
        widget = Table(self.layout.n_rows, self.layout.n_cols)
        for child in self.child.get_children():
            top = self.child.child_get_property(child, 'top-attach')
            bot = self.child.child_get_property(child, 'bottom-attach')
            lft = self.child.child_get_property(child, 'left-attach')
            rgt = self.child.child_get_property(child, 'right-attach')
            child = child.copy()
            widget.child.attach(child, lft, rgt, top, bot)
            widget.layout.add(child, lft, rgt, top, bot)
        return widget

    def reassign(self, widget, upper_left, lower_right):
        top = self.child.child_get_property(upper_left, 'top-attach')
        bot = self.child.child_get_property(lower_right, 'bottom-attach')
        lft = self.child.child_get_property(upper_left, 'left-attach')
        rgt = self.child.child_get_property(lower_right, 'right-attach')

        if top >= bot or lft >= rgt:
            return

        # Remove the old target.
        target = widget.get_parent_target()
        widget.unparent()
        self._remove_target(target)

        # Re-add it into the new cells.
        target = self._add_target(top, bot, lft, rgt)
        target.attach(widget)

    def _remove_target(self, target):
        self.layout.remove(target)
        self.child.remove(target)

    def _remove_targets_at(self, top, bot, lft, rgt):
        for row in range(top, bot):
            for col in range(lft, rgt):
                target = self.layout.get_widget_at(row, col)
                self.layout.remove(target)
                if target and target.parent:
                    self.child.remove(target)

    def _add_target(self, top, bot, lft, rgt):
        # Remove the old target, if any.
        self._remove_targets_at(top, bot, lft, rgt)

        # Create a new target.
        target = Target()
        target.connect('child-attached', self._on_target_child_attached)
        target.connect('child-dropped', self._on_target_child_removed)
        target.connect('child-replaced', self._on_target_child_replaced)
        target.set_data('row', top)
        target.set_data('col', lft)
        self.layout.add(target, lft, rgt, top, bot)
        self.child.attach(target, lft, rgt, top, bot)
        target.show_all()
        return target

    def _position_of(self, child):
        top = self.child.child_get_property(child, 'top-attach')
        bot = self.child.child_get_property(child, 'bottom-attach')
        lft = self.child.child_get_property(child, 'left-attach')
        rgt = self.child.child_get_property(child, 'right-attach')
        return lft, rgt, top, bot

    def _resize_table(self, rows, cols):
        old_rows, old_cols = self.layout.n_rows, self.layout.n_cols
        self.layout.resize(rows, cols)

        # Remove useless targets.
        for child in self.child.get_children():
            if child.get_data('row') >= rows or child.get_data('col') >= cols:
                self.child.remove(child)

        # Add new targets.
        self.child.resize(rows, cols)
        for row in range(old_rows, rows):
            for col in range(0, old_cols):
                self._add_target(row, row + 1, col, col + 1)
        for col in range(old_cols, cols):
            for row in range(0, rows):
                self._add_target(row, row + 1, col, col + 1)

    def _child_at(self, x, y):
        for child in self.child.get_children():
            child_x, child_y = self.translate_coordinates(child, x, y)
            if child_x < 0 or child_y < 0:
                continue
            alloc = child.get_allocation()
            if child_x > alloc.width or child_y > alloc.height:
                continue
            return child
        return None

    def target_at(self, x, y):
        child = self._child_at(x, y)
        if child is None:
            return None
        child_x, child_y = self.translate_coordinates(child, x, y)
        target = child.target_at(child_x, child_y)
        if target is not None:
            return target
        return child

    def _on_target_child_attached(self, target, child):
        self.child.child_set_property(target, 'x-options', child.xoptions)
        self.child.child_set_property(target, 'y-options', child.yoptions)

    def _on_target_child_removed(self, target, child):
        lft, rgt, top, bot = self._position_of(target)

        # Remove the target, as it may have a cellspan.
        self.child.remove(target)

        # Add new targets into each cell.
        for row in range(top, bot):
            for col in range(lft, rgt):
                self._add_target(row, row + 1, col, col + 1)

    def _on_target_child_replaced(self, target, child):
        self._on_target_child_attached(target, child)
Example #13
0
        self.step = self.step + 1

    def decStep(self):
        """
            Decrease current step by one.
        """
        if self.step <= 0:
            raise RuntimeError("Step number has already been zero")
        self.step = self.step - 1

    def setStep(self, num):
        """
            Step step number.
        """
        if num < 0:
            raise ValueError("Step number less than zero")
        self.step = num


if __name__ == '__main__':
    from Layout import Layout
    chessBoard = ChessBoard()
    l = Layout(0)
    l.setToDefault()
    chessBoard.copyFromLayout(0, l)
    mv0 = Movement(0, 29, 23, Result.RES_WIN)
    mv1 = Movement(1, 23, 17, Result.RES_WIN)
    print(chessBoard.move(mv0))
    print(chessBoard.move(mv1))
    print(chessBoard)
Example #14
0
class Table(Element):
    name     = 'table'
    caption  = 'Table'
    xoptions = gtk.EXPAND|gtk.FILL
    yoptions = gtk.FILL

    def __init__(self, rows = 2, cols = 2):
        Element.__init__(self, gtk.Table(rows, cols))
        self.layout     = Layout(0, 0)
        self.entry_rows = None
        self.entry_cols = None
        self.targets    = {}
        self.child.set_row_spacings(3)
        self.child.set_col_spacings(3)
        self._resize_table(rows, cols)


    def has_layout(self):
        return True


    def copy(self):
        widget = Table(self.layout.n_rows, self.layout.n_cols)
        for child in self.child.get_children():
            top   = self.child.child_get_property(child, 'top-attach')
            bot   = self.child.child_get_property(child, 'bottom-attach')
            lft   = self.child.child_get_property(child, 'left-attach')
            rgt   = self.child.child_get_property(child, 'right-attach')
            child = child.copy()
            widget.child.attach(child, lft, rgt, top, bot)
            widget.layout.add(child, lft, rgt, top, bot)
        return widget


    def reassign(self, widget, upper_left, lower_right):
        top = self.child.child_get_property(upper_left,  'top-attach')
        bot = self.child.child_get_property(lower_right, 'bottom-attach')
        lft = self.child.child_get_property(upper_left,  'left-attach')
        rgt = self.child.child_get_property(lower_right, 'right-attach')

        if top >= bot or lft >= rgt:
            return

        # Remove the old target.
        target = widget.get_parent_target()
        widget.unparent()
        self._remove_target(target)

        # Re-add it into the new cells.
        target = self._add_target(top, bot, lft, rgt)
        target.attach(widget)


    def _remove_target(self, target):
        self.layout.remove(target)
        self.child.remove(target)


    def _remove_targets_at(self, top, bot, lft, rgt):
        for row in range(top, bot):
            for col in range(lft, rgt):
                target = self.layout.get_widget_at(row, col)
                self.layout.remove(target)
                if target and target.parent:
                    self.child.remove(target)


    def _add_target(self, top, bot, lft, rgt):
        # Remove the old target, if any.
        self._remove_targets_at(top, bot, lft, rgt)

        # Create a new target.
        target = Target()
        target.connect('child-attached', self._on_target_child_attached)
        target.connect('child-removed',  self._on_target_child_removed)
        target.connect('child-replaced', self._on_target_child_replaced)
        target.set_data('row', top)
        target.set_data('col', lft)
        self.layout.add(target, lft, rgt, top, bot)
        self.child.attach(target, lft, rgt, top, bot)
        target.show_all()
        return target


    def _position_of(self, child):
        top = self.child.child_get_property(child, 'top-attach')
        bot = self.child.child_get_property(child, 'bottom-attach')
        lft = self.child.child_get_property(child, 'left-attach')
        rgt = self.child.child_get_property(child, 'right-attach')
        return lft, rgt, top, bot


    def _resize_table(self, rows, cols):
        old_rows, old_cols = self.layout.n_rows, self.layout.n_cols
        self.layout.resize(rows, cols)

        # Remove useless targets.
        for child in self.child.get_children():
            if child.get_data('row') >= rows or child.get_data('col') >= cols:
                self.child.remove(child)

        # Add new targets.
        self.child.resize(rows, cols)
        for row in range(old_rows, rows):
            for col in range(0, old_cols):
                self._add_target(row, row + 1, col, col + 1)
        for col in range(old_cols, cols):
            for row in range(0, rows):
                self._add_target(row, row + 1, col, col + 1)


    def _child_at(self, x, y):
        for child in self.child.get_children():
            child_x, child_y = self.translate_coordinates(child, x, y)
            if child_x < 0 or child_y < 0:
                continue
            alloc = child.get_allocation()
            if child_x > alloc.width or child_y > alloc.height:
                continue
            return child
        return None


    def target_at(self, x, y):
        child = self._child_at(x, y)
        if child is None:
            return None
        child_x, child_y = self.translate_coordinates(child, x, y)
        target           = child.target_at(child_x, child_y)
        if target is not None:
            return target
        return child


    def _on_target_child_attached(self, target, child):
        self.child.child_set_property(target, 'x-options', child.xoptions)
        self.child.child_set_property(target, 'y-options', child.yoptions)


    def _on_target_child_removed(self, target, child):
        lft, rgt, top, bot = self._position_of(target)

        # Remove the target, as it may have a cellspan.
        self.child.remove(target)

        # Add new targets into each cell.
        for row in range(top, bot):
            for col in range(lft, rgt):
                self._add_target(row, row + 1, col, col + 1)


    def _on_target_child_replaced(self, target, child):
        self._on_target_child_attached(target, child)
Example #15
0
class TextEditor(gtk.TextView):
    def __init__(self, textbuffer=None, *args, **kwargs):
        if textbuffer is None:
            textbuffer = TextBuffer()
        gtk.TextView.__init__(self, textbuffer, *args, **kwargs)
        self.buffer = textbuffer
        self.anno_width = 200
        self.anno_padding = 10
        self.anno_layout = Layout(self)
        self.anno_views = {}
        self.show_annotations = True
        self.handle_links = True
        self.set_right_margin(50 + self.anno_padding)
        self.connect('map-event', self._on_map_event)
        self.connect('expose-event', self._on_expose_event)
        self.connect('motion-notify-event', self._on_motion_notify_event)
        self.connect('event-after', self._on_event_after)
        self.buffer.connect('mark-set', self._on_buffer_mark_set)
        self.buffer.connect('annotation-added', self._on_annotation_added)
        self.buffer.connect('annotation-removed', self._on_annotation_removed)
        self.set_wrap_mode(gtk.WRAP_WORD)

    def _on_motion_notify_event(self, editor, event):
        if not self.handle_links:
            return
        x, y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET,
                                            int(event.x), int(event.y))
        tags = self.get_iter_at_location(x, y).get_tags()

        # Without this call, further motion notify events don't get
        # triggered.
        self.window.get_pointer()

        # If any of the tags are links, show a hand.
        cursor = gtk.gdk.Cursor(gtk.gdk.XTERM)
        for tag in tags:
            if tag.get_data('link'):
                cursor = gtk.gdk.Cursor(gtk.gdk.HAND2)
                break

        self.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(cursor)
        return False

    def _on_event_after(self, textview, event):
        # Handle links here. Only when a button was released.
        if event.type != gtk.gdk.BUTTON_RELEASE:
            return False
        if event.button != 1:
            return False
        if not self.handle_links:
            return

        # Don't follow a link if the user has selected something.
        bounds = self.buffer.get_selection_bounds()
        if bounds:
            start, end = bounds
            if start.get_offset() != end.get_offset():
                return False

        # Check whether the cursor is pointing at a link.
        x, y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET,
                                            int(event.x), int(event.y))
        iter = textview.get_iter_at_location(x, y)

        for tag in iter.get_tags():
            link = tag.get_data('link')
            if not link:
                continue
            self.emit('link-clicked', link)
            break
        return False

    def _on_buffer_mark_set(self, buffer, iter, mark):
        self._update_annotations()

    def _on_map_event(self, widget, event):
        self._update_annotation_area()
        self._update_annotations()

    def _on_expose_event(self, widget, event):
        text_window = widget.get_window(gtk.TEXT_WINDOW_TEXT)
        if event.window != text_window:
            return

        # Create the cairo context.
        ctx = event.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        ctx.rectangle(event.area.x, event.area.y, event.area.width,
                      event.area.height)
        ctx.clip()

        self.draw(ctx, *event.window.get_size())

    def draw(self, ctx, w, h):
        if ctx is None:
            return
        if not self.show_annotations:
            return

        # Draw the dashes that connect annotations to their marker.
        ctx.set_line_width(1)
        ctx.set_dash((3, 2))
        right_margin = self.get_right_margin()
        for annotation in self.anno_layout.get_children():
            mark_x, mark_y = self._get_annotation_mark_position(annotation)
            anno_x, anno_y, anno_w, anno_h, d = annotation.window.get_geometry(
            )
            path = [(mark_x, mark_y - 5), (mark_x, mark_y),
                    (w - right_margin, mark_y), (w, anno_y + anno_h / 2)]

            stroke_color = annotation.get_border_color()
            ctx.set_source_rgba(*color.to_rgba(stroke_color))
            ctx.move_to(*path[0])
            for x, y in path[1:]:
                ctx.line_to(x, y)
            ctx.stroke()

    def _get_annotation_mark_offset(self, view1, view2):
        mark1 = view1.annotation.start_mark
        mark2 = view2.annotation.start_mark
        iter1 = self.get_buffer().get_iter_at_mark(mark1)
        iter2 = self.get_buffer().get_iter_at_mark(mark2)
        rect1 = self.get_iter_location(iter1)
        rect2 = self.get_iter_location(iter2)
        if rect1.y != rect2.y:
            return rect1.y - rect2.y
        return rect2.x - rect1.x

    def _get_annotation_mark_position(self, view):
        start_mark = view.annotation.start_mark
        iter = self.get_buffer().get_iter_at_mark(start_mark)
        rect = self.get_iter_location(iter)
        mark_x, mark_y = rect.x, rect.y + rect.height
        return self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT, mark_x,
                                            mark_y)

    def _update_annotation(self, annotation):
        # Resize the annotation.
        item_width = self.anno_width - 2 * self.anno_padding
        annotation.set_size_request(item_width, -1)

        # Find the x, y of the annotation's mark.
        mark_x, mark_y = self._get_annotation_mark_position(annotation)
        self.anno_layout.pull(annotation, mark_y)

    def _update_annotation_area(self):
        # Update the width and color of the annotation area.
        self.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, self.anno_width)
        bg_color = self.get_style().base[gtk.STATE_NORMAL]
        window = self.get_window(gtk.TEXT_WINDOW_RIGHT)
        if window:
            window.set_background(bg_color)

    def _update_annotations(self):
        if not self.show_annotations:
            return

        # Sort the annotations by line/char number and update them.
        iter = self.get_buffer().get_end_iter()
        rect = self.get_iter_location(iter)
        height = rect.y + rect.height
        self.anno_layout.sort(self._get_annotation_mark_offset)
        for annotation in self.anno_layout.get_children():
            self._update_annotation(annotation)
        self.anno_layout.update(self.anno_width, height)

        # Update lines.
        self.queue_draw()

    def set_annotation_area_width(self, width, padding=10):
        self.anno_width = width
        self.anno_padding = padding
        self._update_annotations()

    def _on_annotation_added(self, buffer, annotation):
        if self.show_annotations == False:
            return
        annotation.set_display_buffer(self.buffer)
        view = AnnotationView(annotation)
        self.anno_views[annotation] = view
        for event in ('focus-in-event', 'focus-out-event'):
            view.connect(event, self._on_annotation_event, annotation, event)
        view.show_all()
        self._update_annotation_area()
        self.anno_layout.add(view)
        self.add_child_in_window(view, gtk.TEXT_WINDOW_RIGHT,
                                 self.anno_padding, 0)
        self._update_annotations()

    def _on_annotation_removed(self, buffer, annotation):
        view = self.anno_views[annotation]
        self.anno_layout.remove(view)
        self.remove(view)

    def _on_annotation_event(self, buffer, *args):
        annotation = args[-2]
        event_name = args[-1]
        self.emit('annotation-' + event_name, annotation)

    def set_show_annotations(self, active=True):
        if self.show_annotations == active:
            return

        # Unfortunately gtk.TextView deletes all children from the
        # border window if its size is 0. So we must re-add them when the
        # window reappears.
        self.show_annotations = active
        if active:
            for annotation in self.buffer.get_annotations():
                self._on_annotation_added(self.buffer, annotation)
        else:
            for annotation in self.buffer.get_annotations():
                self._on_annotation_removed(self.buffer, annotation)
            self.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 0)

    def set_handle_links(self, handle):
        """
        Defines whether the cursor is changed and whether clicks are accepted
        when hovering over text with tags that have data named "link"
        attached.
        """
        self.handle_links = handle
Example #16
0
class MainMenuState(GameState):

    @staticmethod
    def main_menu_button(text: str, on_click: Callable[[], None]):
        return Button(
            x=0, y=0, width=100, height=50,
            surface=filled_rect((200, 100), hex_to_rgb('B7CBFF')),
            surface_hover=filled_rect((200, 100), hex_to_rgb('85A7FF')),
            surface_click=filled_rect((200, 100), hex_to_rgb('6B95FF')),
            text=text,
            text_color=hex_to_rgb('FFFFFF'),
            font=FONT,
            on_click=on_click,
        )

    def __init__(self):
        self.start_game_button = MainMenuState.main_menu_button(
            'start game',
            lambda: pygame.event.post(make_event(
                GameEvent.CHANGE_STATE,
                state=LevelState()
            ))
        )

        self.ai_button = MainMenuState.main_menu_button(
            'ai',
            lambda: print('click ai'),
        )

        self.quit_game_button = MainMenuState.main_menu_button(
            'quit game',
            lambda: pygame.event.post(pygame.event.Event(QUIT))
        )

        self.button_sprites: Union[pygame.sprite.Group, Iterable[Button]] = pygame.sprite.Group()
        self.button_sprites.add(self.start_game_button)
        self.button_sprites.add(self.ai_button)
        self.button_sprites.add(self.quit_game_button)

        self.button_layout = Layout(vpadding_inner=20)
        self.button_layout.add_all(self.button_sprites)

    def handle_events(self, game: 'Game'):
        for event in pygame.event.get():
            if event.type == QUIT:
                return game.quit()

            if event.type == DispatchableEvent.EVENT.value:
                if event.event == GameEvent.CHANGE_STATE:
                    game.set_state(event.state)

            for button in self.button_sprites:
                button.handle_event(event)

    def update(self, game: 'Game'):
        self.button_layout.update(
            game.screen.get_rect(),
            (LayoutLocation.CENTER, LayoutLocation.CENTER)
        )

    def draw(self, game: 'Game'):
        game.screen.fill((0, 0, 0))
        game.grid.draw_background(game.screen)
        self.button_sprites.draw(game.screen)
Example #17
0
    def update(self, render=None):
        Active.update(self)
        currentHowActiveMouse = None
        if self.isActive and self.isSelect:

            done = False
            for widgetList in self._widget:
                for child in widgetList:
                    if isinstance(child, Active) and child.isSelect and child is not self._currentSelect:
                        self._currentSelect = child
                        done = True
                        break
                if done:
                    break

            if not self._currentSelect:
                done = False
                for widgetList in self._widget:
                    for child in widgetList:
                        if isinstance(child, Active):
                            self._currentSelect = child
                            done = True
                            break
                    if done:
                        break
            self._deselectOtherWidget()

            if self.event and self._currentSelect:
                currentHowActiveMouse = self._currentSelect.howActiveMouse
                if not self._currentSelect.howSelect():
                    self._currentSelect.howActiveMouse=[None]
                posCurrentSelect = self.getWidgetPosition(self._currentSelect)
                caseCurrentSelect = self.getWidgetCase(self._currentSelect)

                if not self.changeLeft in self._currentSelect.howActiveKeyboard and\
                        self.event.getOnePressedKeys(self.changeLeft):
                    done = False
                    for x in range(posCurrentSelect.x-1, -1, -1):
                        for y in range(posCurrentSelect.y, len(self._widget[x])):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break

                        if done:
                            break

                        for y in range(0, posCurrentSelect.y):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break
                        if done:
                            break

                    if not done:
                        for x in range(len(self._widget)-1, posCurrentSelect.x, -1):
                            for y in range(posCurrentSelect.y, len(self._widget[x])):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break

                            if done:
                                break

                            for y in range(0, posCurrentSelect.y):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break

                elif not self.changeRight in self._currentSelect.howActiveKeyboard and\
                        self.event.getOnePressedKeys(self.changeRight):
                    done = False
                    y = posCurrentSelect.y
                    for x in range(posCurrentSelect.x + caseCurrentSelect.x, \
                            len(self._widget)):
                        for y in range(posCurrentSelect.y, len(self._widget[x])):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break

                        if done:
                            break

                        for y in range(0, posCurrentSelect.y):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break

                        if done:
                            break

                    if not done:
                        for x in range(0, posCurrentSelect.x):
                            for y in range(posCurrentSelect.y, len(self._widget[x])):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break

                            for y in range(0, posCurrentSelect.y):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break

                elif not self.changeTop in self._currentSelect.howActiveKeyboard and \
                        self.event.getOnePressedKeys(self.changeTop):
                    done = False
                    for y in range(posCurrentSelect.y-1, -1, -1):
                        for x in range(posCurrentSelect.x, len(self._widget)):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break
                        if done:
                            break

                        for x in range(0, posCurrentSelect.x):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break
                        if done:
                            break


                    if not done:
                        for y in range(len(self._widget[0])-1, posCurrentSelect.y, -1):
                            for x in range(posCurrentSelect.x, len(self._widget)):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break
                            for x in range(0, posCurrentSelect.x):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break
                elif not self.changeBottom in self._currentSelect.howActiveKeyboard and\
                        self.event.getOnePressedKeys(self.changeBottom):
                    done = False
                    x = posCurrentSelect.x
                    for y in range(posCurrentSelect.y + caseCurrentSelect.y, \
                            len(self._widget[0])):
                        for x in range(posCurrentSelect.x, len(self._widget)):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break
                        if done:
                            break

                        for x in range(0, posCurrentSelect.x):
                            child = self.__getitem__(sf.Vector2(x, y))
                            if isinstance(child, Active) and child is not self._currentSelect:
                                done = True
                                self._currentSelect = child
                                break
                        if done:
                            break

                    if not done:
                        for y in range(0, posCurrentSelect.y):
                            for x in range(posCurrentSelect.x, len(self._widget)):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break
                            for x in range(0, posCurrentSelect.x):
                                child = self.__getitem__(sf.Vector2(x, y))
                                if isinstance(child, Active) and child is not self._currentSelect:
                                    done = True
                                    self._currentSelect = child
                                    break
                            if done:
                                break
            self._deselectOtherWidget()
        else:
            if self._currentSelect:
                self._currentSelect.permanentSelection=False
                self._currentSelect.deselectIt()

        Layout.update(self, render)
        if self._currentSelect:
            self._currentSelect.howActiveMouse = currentHowActiveMouse
Example #18
0
	def __getattr__(self, name):
		return getattr(self._args, name)

parser = FriendlyArgumentParser()
parser.add_argument("--datadir", metavar = "path", type = str, default = None, help = "Specifies directory in which the data files are located. Defaults to data/ relative to executable.")
parser.add_argument("-g", "--game", choices = [ "mahjong", "shisen" ], default = "mahjong", help = "Specifies which game to play")
parser.add_argument("-t", "--tileset", metavar = "name", default = "default", help = "Name of the tileset to use. Defaults to %(default)s")
parser.add_argument("-l", "--layout", metavar = "name", help = "Name of the board layout to use.")
parser.add_argument("-s", "--seed", metavar = "seed", type = int, help = "Seed of the game to use. Randomly chosen if omitted.")
parser.add_argument("--texresolution", metavar = "res", type = int, default = 512, help = "Specify texture resolution that should be used. Default is %(default)s.")
parser.add_argument("--allow-unsolvable", action = "store_true", default = False, help = "Allow non-solvable board layouts.")
args = parser.parse_args(sys.argv[1:])

config = Configuration(args)
layout = Layout(config.layoutfile)
tileset = TileSet(config.tilesetfile)
if args.game == "mahjong":
	board = MahjongBoard(layout.gridlen)
elif args.game == "shisen":
	board = ShisenBoard()
else:
	raise Exception(NotImplemented)
game = Game(config, layout, tileset, board)
game.new()

display = OpenGLDisplay()

gamecontroller = GameController(args, game, display)

Example #19
0
class GenomeModel(Observable):
    genome = Genome()
    featureListContainer = FeatureListContainer()
    upperCase = True
    charsPerLine = 0
    position = 0
    startRange = 0
    endRange = 0
    layout = Layout()
    def __init__(self, genome=Genome(), flc=FeatureListContainer(), initial_upperCase=True, initial_charsPerLine=50, initial_position=3520, initial_startRange=0, initial_endRange=5000):
        self.genome=genome
        self.featureListContainer=flc
        self.upperCase=initial_upperCase
        self.charsPerLine=initial_charsPerLine
        self.position=initial_position
        self.startRange=initial_startRange
        self.endRange=initial_endRange
        self.layout=Layout()
    def getGenome(self):
        return self.genome
    def setGenome(self, genome):
        self.genome=genome
        self.setChanged()
    def getFeatureListContainer(self):
        return self.featureListContainer
    def setFeatureListContainer(self, flc):
        self.featureListContainer=flc
        self.setChanged()
    def getUpperCase(self):
        return self.upperCase
    def setUpperCase(self, bool):
        self.upperCase=bool
        self.setChanged()
    def getCharsPerLine(self):
        return self.charsPerLine
    def setCharsPerLine(self, n):
        self.charsPerLine=n
        self.setChanged()
    def getPosition(self):
        return self.position
    def setPosition(self, n):
        self.position=n
        self.setChanged()
    def getStartRange(self):
        return self.startRange
    def setStartRange(self, n):
        self.startRange=n
        self.setChanged()
    def getEndRange(self):
        return self.endRange
    def setEndRange(self, n):
        self.endRange=n
        self.setChanged()
    def setRanges(self, start ,end):
        self.startRange = start
        self.endRange = end
        self.setChanged()
    def writeSequence(self, txtctrl):
        #print self.genome.getSequence()[0:50]
        if self.upperCase:
            sequence=self.genome.getSequence()[self.startRange:self.endRange].upper()
        else:
            sequence=self.genome.getSequence()[self.startRange:self.endRange]
        seqLen=len(sequence)
        numeration=self.startRange
	print "PENIS", self.endRange
        i=0
        while i+self.charsPerLine <= seqLen:
            txtctrl.BeginStyle(self.layout.getSeqTextAttrEx())
            # print str(len(sequence[i:i+self.charsPerLine]))
            txtctrl.WriteText(sequence[i:i+self.charsPerLine])
            txtctrl.Newline()
            txtctrl.EndStyle()
            txtctrl.BeginStyle(self.layout.getNumTextAttrEx())
            txtctrl.WriteText(self.writeNum(len(str(self.endRange-1)), str(numeration), str(numeration+txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-2)-1)))
            # letzte Zeile ohne Newline()
            if i+self.charsPerLine < seqLen:
                # print "charsPerLine" + str(i+self.charsPerLine) + "=" + str(seqLen)
                txtctrl.Newline()
            txtctrl.EndStyle()
            i+=self.charsPerLine
            numeration+=txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-3)
        if seqLen-i>0:
            txtctrl.BeginStyle(self.layout.getSeqTextAttrEx())
            txtctrl.WriteText(sequence[i:])
            txtctrl.Newline()
            txtctrl.EndStyle()
            txtctrl.BeginStyle(self.layout.getNumTextAttrEx())
            txtctrl.WriteText(self.writeNum(len(str(self.endRange)), str(numeration), str(numeration+txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-2))))
            txtctrl.EndStyle()
    # gibt Nummerierung als gleichlange Strings zurueck
    def writeNum(self, strLen, str1, str2):
        while len(str1) < strLen:
            str1= "0" + str1
        while len(str2) < strLen:
            str2= "0" + str2
        return str1 + "-" + str2
    # durchsucht den Container nach allen aktiven Features und uebergibt deren Parameter an writeFeaturesHelper
    def writeFeatures(self, txtctrl):
        for iFlist in range(self.featureListContainer.getContainerLength()):
            # print iFlist
            # print self.featureListContainer.getContainerLength()
            if self.featureListContainer.getFlistActive(iFlist):
                for iFeature in range(self.featureListContainer.getFlistLength(iFlist)):
                    # print iFeature
                    # print self.featureListContainer.getFlistLength(iFlist)
                    if self.featureListContainer.getFeatureActive(iFlist, iFeature):
                        start=self.featureListContainer.getStartPos(iFlist, iFeature)
                        end=self.featureListContainer.getEndPos(iFlist, iFeature)
                        if start >= self.startRange and end <= self.endRange:
                            type=self.featureListContainer.getType(iFlist, iFeature)
                            description=self.featureListContainer.getDescription(iFlist, iFeature)
                            self.writeFeaturesHelper(txtctrl, start, end, type, description)
    # faerbt Bereiche und ueberspringt Nummerierung
    def writeFeaturesHelper(self, txtctrl, start, end, type, description):
        #print "start1: " + str(start)
        #print "end1: " + str(end)
        rta = rt.RichTextAttr()
        #Farbgebung
        self.layout.addTypeColDict(type)
        rta.SetTextColour(self.layout.getTypeColDict(type))
        rta.SetURL(description)
        txtctrl.Bind(wx.EVT_TEXT_URL, self.onUrl)
        #txtctrl.SetStyle((246, 306), rta)
        calc1=start%self.charsPerLine
        calc2=self.charsPerLine-calc1
        calc3=self.startRange%self.charsPerLine
        calc4=(calc2+calc3)%self.charsPerLine
        modStart=self.modifyStartPos(start,txtctrl)
        modEnd=self.modifyEndPos(end, txtctrl)
        #print "calc1: " + str(calc1)
        #print "calc2: " + str(calc2)
        #print "calc3: " + str(calc3)
        #print "calc4: " + str(calc4)
        #print "start2: " + str(modStart)
        #print "end2: " + str(modEnd)
        # Anfang: wenn Einfaerbung nicht am Zeilenanfang beginnt
        if calc4!=0:
            if end-start<=calc4:
                txtctrl.SetStyle((modStart,modEnd), rta)
                modStart+=modEnd
                #print "if"
            else:
                txtctrl.SetStyle((modStart,modStart+calc4), rta)
                modStart+=calc4+txtctrl.GetLineLength(1)+2
                #print "else"
        # Mitte: faerbt ganze Zeilen
        while modStart+self.charsPerLine<=modEnd:
            txtctrl.SetStyle((modStart,modStart+self.charsPerLine), rta)
            #print str(modStart+self.charsPerLine+txtctrl.GetLineLength(1)+1)
            modStart+=self.charsPerLine+txtctrl.GetLineLength(1)+2
            #print "middle"
        # Ende: faerbt letzte Zeile nicht ganz
        if modEnd-modStart>0:
            txtctrl.SetStyle((modStart,modEnd), rta)
            #print "end"
    # wandelt Positionen auf dem Genom in Positionen im Genomtextfeld um
    def modifyStartPos(self, n, txtctrl):
        newN=n-self.startRange
        quot=newN/self.charsPerLine*2
        numCount=0
        i=1
        while i <= quot:
            numCount+=txtctrl.GetLineLength(i)
            i+=2
        #print newN+quot+numCount
        return newN+quot+numCount
    def modifyEndPos(self, n, txtctrl):
        newN=n-self.startRange
        quot=newN/self.charsPerLine*2
        numCount=0
        i=1
        while i < quot:
            numCount+=txtctrl.GetLineLength(i)
            i+=2
        #print str(newN+quot+numCount+1)
        return newN+quot+numCount+1
    def onUrl(self, evt):
        wx.MessageBox(evt.GetString(), "Description")
    # rechnet Position im Genom in Position im Textfeld um und scrollt im Textfeld an richtige Stelle
    def showPos(self, txtctrl):
        if self.position>=self.startRange and self.position<=self.endRange:
            realPos=self.modifyStartPos(self.position, txtctrl)
            txtctrl.ShowPosition(realPos)
            txtctrl.SelectWord(realPos)
    # rechnet Position des Features in Position im Textfeld um und scrollt im Textfeld an richtige Stelle
    def showFeature(self, start, end, txtctrl):
        realStart=self.modifyStartPos(start, txtctrl)
        realEnd=self.modifyEndPos(end, txtctrl)
        txtctrl.ShowPosition(realStart)
        txtctrl.SetSelection(realStart, realEnd)
Example #20
0
class GenomeModel(Observable):
    """contains data of genome-view"""
    genome = Genome()
    featureListContainer = FeatureListContainer()
    position = 0
    startRange = 0
    endRange = 0
    layout = Layout()
    def __init__(self, genome=Genome(), flc=FeatureListContainer(), initial_position=3520, initial_startRange=0, initial_endRange=5000):
        self.genome=genome
        self.featureListContainer=flc
        self.position=initial_position
        self.startRange=initial_startRange
        self.endRange=initial_endRange
        self.layout=Layout()
    def getGenome(self):
        return self.genome
    def setGenome(self, genome):
        self.genome=genome
        self.setChanged()
    def getFeatureListContainer(self):
        return self.featureListContainer
    def setFeatureListContainer(self, flc):
        self.featureListContainer=flc
        self.setChanged()
    def getCharsPerLine(self):
        return self.layout.getCharsPerLine()
    def setCharsPerLine(self, n):
        self.layout.setCharsPerLine(n)
    def getPosition(self):
        return self.position
    def setPosition(self, n):
        self.position=n
        self.setChanged()
    def getStartRange(self):
        return self.startRange
    def setStartRange(self, n):
        self.startRange=n
        self.setChanged()
    def getEndRange(self):
        return self.endRange
    def setEndRange(self, n):
        self.endRange=n
        self.setChanged()
    def setRanges(self, start ,end):
        self.startRange = start
        self.endRange = end
        self.setChanged()
    def resetLayout(self):
        new = Layout()
        self.layout = Layout()
        self.setChanged()
    def getTypeDict(self):
        return self.layout.getTypeDict()
    def getNumSize(self):
        return self.layout.getNumSize()
    def incNumSize(self, int):
        numsize=self.layout.getNumSize()
        self.layout.setNumSize(numsize+int)
    def decNumSize(self, int):
        numsize=self.layout.getNumSize()
        if (numsize-int >=0):
            self.layout.setNumSize(numsize-int)
        else:
            self.layout.setNumSize(0)
    def getSeqSize(self):
        return self.layout.getSeqSize();
    def incSeqSize(self, int):
        seqsize=self.layout.getSeqSize()
        self.layout.setSeqSize(seqsize+int)
    def decSeqSize(self, int):
        seqsize=self.layout.getSeqSize()
        if (seqsize-int >=0):
            self.layout.setSeqSize(seqsize-int)
        else:
            self.layout.setSeqSize(0)
    def isItalic(self):
        return self.layout.getSeqStyle() == wx.ITALIC
    def isBold(self):
        return self.layout.getSeqWeight() == wx.BOLD
    def changeSeqWeight(self):
        if self.layout.getSeqWeight()== wx.NORMAL:
            self.layout.setSeqWeight(wx.BOLD)
        else:
            self.layout.setSeqWeight(wx.NORMAL)
    def changeSeqStyle(self):
        if self.layout.getSeqStyle()== wx.NORMAL:
            self.layout.setSeqStyle(wx.ITALIC)
        else:
            self.layout.setSeqStyle(wx.NORMAL)
    def increaseLineSp(self, int):
        lp=self.layout.getLineSpacing()
        self.layout.setLineSpacing(lp+int)
    def decreaseLineSp(self, int):
        lp=self.layout.getLineSpacing()
        if lp-int >= 0:
            self.layout.setLineSpacing(lp-int)
        else:
            self.layout.setLineSpacing(0)
    def indentMore(self, int):
        indent=self.layout.getLeftIndent()
        self.layout.setLeftIndent(indent+int)
    def indentLess(self, int):
        indent=self.layout.getLeftIndent()
        if indent-int>=0:
            self.layout.setLeftIndent(indent-int)
        else:
            self.layout.setLeftIndent(0)
    def setSeqColor(self, color):
        self.layout.setSeqColor(color)
    def getSeqColor(self):
        return self.layout.getSeqColor()
    def setNumColor(self, color):
        self.layout.setNumColor(color)
    def getNumColor(self):
        return self.layout.getNumColor()
    def isUpperCase(self):
        return self.layout.getUpperCase()
    def changeUpperCase(self):
        if self.layout.getUpperCase():
            self.layout.setUpperCase(False)
        else:
            self.layout.setUpperCase(True)
    def getCharWidth(self):
        self.layout.getCharWidth()
    def writeSequence(self, txtctrl):
        #print self.genome.getSequence()[0:50]
        #print "UpperCase: " + str(self.layout.getUpperCase())
        if self.layout.getUpperCase():
            sequence=self.genome.getSequence()[self.startRange:self.endRange].upper()
        else:
            sequence=self.genome.getSequence()[self.startRange:self.endRange].lower()
        seqLen=len(sequence)
        numeration=self.startRange
        i=0
        while i+self.layout.getCharsPerLine() <= seqLen:
            txtctrl.BeginStyle(self.layout.getSeqTextAttrEx())
            # print str(len(sequence[i:i+self.charsPerLine]))
            txtctrl.WriteText(sequence[i:i+self.layout.getCharsPerLine()])
            txtctrl.Newline()
            txtctrl.EndStyle()
            txtctrl.BeginStyle(self.layout.getNumTextAttrEx())
            txtctrl.WriteText(self.writeNum(len(str(self.endRange-1)), str(numeration), str(numeration+txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-2)-1)))
            # letzte Zeile ohne Newline()
            if i+self.layout.getCharsPerLine() < seqLen:
                # print "charsPerLine" + str(i+self.charsPerLine) + "=" + str(seqLen)
                txtctrl.Newline()
            txtctrl.EndStyle()
            i+=self.layout.getCharsPerLine()
            numeration+=txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-3)
        if seqLen-i>0:
            txtctrl.BeginStyle(self.layout.getSeqTextAttrEx())
            txtctrl.WriteText(sequence[i:])
            txtctrl.Newline()
            txtctrl.EndStyle()
            txtctrl.BeginStyle(self.layout.getNumTextAttrEx())
            txtctrl.WriteText(self.writeNum(len(str(self.endRange)), str(numeration), str(numeration+txtctrl.GetLineLength(txtctrl.GetNumberOfLines()-2))))
            txtctrl.EndStyle()
    # gibt Nummerierung als gleichlange Strings zurueck
    def writeNum(self, strLen, str1, str2):
        while len(str1) < strLen:
            str1= "0" + str1
        while len(str2) < strLen:
            str2= "0" + str2
        return str1 + "-" + str2
    # durchsucht den Container nach allen aktiven Features und uebergibt deren Parameter an writeFeaturesHelper
    def writeFeatures(self, txtctrl):
        for iFlist in range(self.featureListContainer.getContainerLength()):
            # print iFlist
            # print self.featureListContainer.getContainerLength()
            if self.featureListContainer.getFlistActive(iFlist):
                for iFeature in range(self.featureListContainer.getFlistLength(iFlist)):
                    # print iFeature
                    # print self.featureListContainer.getFlistLength(iFlist)
                    if self.featureListContainer.getFeatureActive(iFlist, iFeature):
                        start=self.featureListContainer.getStartPos(iFlist, iFeature)
                        end=self.featureListContainer.getEndPos(iFlist, iFeature)
                        if start >= self.startRange and end <= self.endRange:
                            type=self.featureListContainer.getType(iFlist, iFeature)
                            description=self.featureListContainer.getDescription(iFlist, iFeature)
                            self.writeFeaturesHelper(txtctrl, start, end, type, description)
    # faerbt Bereiche und ueberspringt Nummerierung
    def writeFeaturesHelper(self, txtctrl, start, end, type, description):
        #print "start1: " + str(start)
        #print "end1: " + str(end)
        rta = rt.RichTextAttr()
        #Farbgebung
        self.layout.addTypeColDict(type)
        rta.SetTextColour(self.layout.getTypeColDict(type))
        description=description+";"+str(start)+";"+str(end)+";"+type
        rta.SetURL(description)
        txtctrl.Bind(wx.EVT_TEXT_URL, self.onUrl)
        #txtctrl.SetStyle((246, 306), rta)
        calc1=start%self.layout.getCharsPerLine()
        calc2=self.layout.getCharsPerLine()-calc1
        calc3=self.startRange%self.layout.getCharsPerLine()
        calc4=(calc2+calc3)%self.layout.getCharsPerLine()
        modStart=self.modifyStartPos(start,txtctrl)
        modEnd=self.modifyEndPos(end, txtctrl)
        #print "calc1: " + str(calc1)
        #print "calc2: " + str(calc2)
        #print "calc3: " + str(calc3)
        #print "calc4: " + str(calc4)
        #print "start2: " + str(modStart)
        #print "end2: " + str(modEnd)
        # Anfang: wenn Einfaerbung nicht am Zeilenanfang beginnt
        if calc4!=0:
            if end-start<=calc4:
                txtctrl.SetStyle((modStart,modEnd), rta)
                modStart+=modEnd
                #print "if"
            else:
                txtctrl.SetStyle((modStart,modStart+calc4), rta)
                modStart+=calc4+txtctrl.GetLineLength(1)+2
                #print "else"
        # Mitte: faerbt ganze Zeilen
        while modStart+self.layout.getCharsPerLine()<=modEnd:
            txtctrl.SetStyle((modStart,modStart+self.layout.getCharsPerLine()), rta)
            #print str(modStart+self.charsPerLine+txtctrl.GetLineLength(1)+1)
            modStart+=self.layout.getCharsPerLine()+txtctrl.GetLineLength(1)+2
            #print "middle"
        # Ende: faerbt letzte Zeile nicht ganz
        if modEnd-modStart>0:
            txtctrl.SetStyle((modStart,modEnd), rta)
            #print "end"
    # wandelt Positionen auf dem Genom in Positionen im Genomtextfeld um
    def modifyStartPos(self, n, txtctrl):
        newN=n-self.startRange
        quot=newN/self.layout.getCharsPerLine()*2
        numCount=0
        i=1
        while i <= quot:
            numCount+=txtctrl.GetLineLength(i)
            i+=2
        #print newN+quot+numCount
        return newN+quot+numCount
    def modifyEndPos(self, n, txtctrl):
        newN=n-self.startRange
        quot=newN/self.layout.getCharsPerLine()*2
        numCount=0
        i=1
        while i < quot:
            numCount+=txtctrl.GetLineLength(i)
            i+=2
        #print str(newN+quot+numCount+1)
        return newN+quot+numCount+1

    def onUrl(self, evt):
        info = Information(None, -1, evt.GetString(), 'Information')
        info.ShowModal()
        info.Destroy()
        #wx.MessageBox(evt.GetString(), "Description")

    # rechnet Position im Genom in Position im Textfeld um und scrollt im Textfeld an richtige Stelle
    def showPos(self, txtctrl):
        if self.position>=self.startRange and self.position<=self.endRange:
            realPos=self.modifyStartPos(self.position, txtctrl)
            txtctrl.ShowPosition(realPos)
            txtctrl.SelectWord(realPos)
    # rechnet Position des Features in Position im Textfeld um und scrollt im Textfeld an richtige Stelle
    def showFeature(self, start, end, txtctrl):
        realStart=self.modifyStartPos(start, txtctrl)
        realEnd=self.modifyEndPos(end, txtctrl)
        txtctrl.ShowPosition(realStart)
        txtctrl.SetSelection(realStart, realEnd)
Example #21
0
zM = 55  # Altitude du mât
zL = 0  # Altitude du Lidar

# Initialisation RWS_Sonic

R8, U8, V8, VL8 = [], [], [], []
tmptime = []
tmplidar = []
fig, axes = plt.subplots(1, 1, num="RWS_Sonic", figsize=(14, 14))
axes.set_xlabel("t (s)", fontsize=25)
axes.set_ylabel("RWS (m/s)", fontsize=20)
axes.set_title("Evolution de la vitesse radiale mesurée par l'anémomètre",
               fontsize=20)

xM, yM, xL, yL = Layout(path + "Work/",
                        False)  # Coordonnées du mât et du Lidar
plt.close("Layout")

for hour in range(1, n + 1):  # On parcourt les différents fichiers

    path1 = path0 + "151030" + str(hour) + ".I55"
    path2 = path0 + "WLS200s-15_radial_wind_data_2015-04-13_0" + str(
        hour) + "-00-00.csv"

    # Champs des vitesses

    try:
        U, V, W = ParseurSonique(path1)
        L = ParseurLidar(path2)
        L[0] %= 36000
    except FileNotFoundError:
Example #22
0
    def loadDialog(self):
        home_folder = os.listdir('D:/')
        if not 'LayOutQC' in home_folder:
            os.mkdir('D:/LayOutQC/')
        if not '--INCOMING--' in home_folder:
            os.mkdir('D:/--INCOMING--/')
        self.load_name = QFileDialog.getOpenFileName(self, 'Open file', 'D:/LayOutQC/', "TIF files (*.tif)")[0]
        self.FileName = self.load_name.split("/")[-1]
        self.PathName = self.load_name[:len(self.load_name) - len(self.FileName)]
        if self.FileName:
            self.im = ImagePil.open(self.load_name)
            self.LayOutLoaded = True
            self.prw_name = 'temp/input_temp.png'
            self.comboTT_tables.setCurrentText(' ')
            self.comboTT_location.clear()
            self.comboTT_location.addItems([' '])
            self.comboTT_name.clear()
            self.comboTT_name.addItems([' '])
            self.comboTT_code.clear()
            self.comboTT_code.addItems([' '])
            self.TT_dismentions.setText('')
            self.CheckTT_act.setEnabled(False)
            self.Show_input_act.setIcon(self.icon4)
            self.Show_input_act.setEnabled(False)
            self.TopZone_act.setEnabled(False)
            files = glob.glob('temp/*')
            for f in files:
                os.remove(f)

            # Runing Layout Module
            self.layout = Layout(self.im)
            self.layout._DEBAG(LayoutQC_DEBAG)

            #  set Layout info into Toolbar
            self.modeToolbar.setStyleSheet(self.layout.layout_mode_status())
            self.iccToolbar.setStyleSheet(self.layout.layout_profile_status())

            self.modeToolbar.setText(self.layout.image.mode)
            self.resToolbar.setText(str(self.layout.resolution))
            self.dismX.setText(str(self.layout.width_layout) + 'mm')
            self.dismY.setText(str(self.layout.height_layout) + 'mm')
            self.iccToolbar.setText(self.layout.layout_profile_name())

            # make $ showing preview
            self.layout.make_prw(self.prw_name, LayoutQC_DEBAG=LayoutQC_DEBAG)


            # self.im222=QPixmap(self.prw_name)


            # self.scaleFactor = 1.0
            # show_x = self.desktop.width() - 270
            # show_y = show_x / self.im.size[0] * self.im.size[1]
            # if show_y > self.desktop.height() - 200:
            #     show_y = self.desktop.height() - 200
            #     show_x = show_y / self.im.size[1] * self.im.size[0]

            width_central_widget = self.desktop.width() - 222
            height_central_widget = self.desktop.width() - 178
            if self.im.size[0] > self.im.size[1]:
                self.zoom = width_central_widget / self.im.size[0]
            else:
                self.zoom = height_central_widget / self.im.size[1]

            self.scene.clear()
            self.scene.addPixmap(QPixmap(self.prw_name))
            self.updateView()

            print(self.desktop.width())
            print(self.desktop.height())


            self.AutoSelectTT_act.setEnabled(True)
            self.tables = self.layout.layout_db_tabeles
            self.comboTT_tables.addItems(self.tables)
            self.name_Layout()
Example #23
0
class LayOutQC(QMainWindow):

    def __init__(self):
        super().__init__()

        self.tables = [' ']
        self.pr = ''

        # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\STYLES IN CSS////////////////////////////////
        self.style_norm = "color: #cdd6e6;  font-size: 20px; font-family: Arial; background-color: rgba(55, 55, 68, " \
                          "0.4); margin-bottom: 13px; margin-top: 13px; border: 1px solid; border-color: #516588; "
        self.style_warning = "color: #cdd6e6;  font-size: 20px; font-family: Arial; background-color: rgba(55, 55, " \
                             "68, 0.4); margin-bottom: 13px; margin-top: 13px; border: 4px solid; border-color: " \
                             "#ff0000; "
        self.style_appFont_title = "color: #8fa3c4;  font-size: 18px; font-family: Arial;  margin-left: 20px; " \
                                   "margin-right: 20px; margin-bottom: 5px; margin-top: 5px;background-color: rgba(" \
                                   "55, 55, 68, 0.4); "
        self.style_appFont = "color: #8fa3c4;  font-size: 16px; font-family: Arial;  margin-bottom: 5px; margin-top: " \
                             "5px; text-align: center; "
        self.style_OK = "color: #cdd6e6;  font-size: 22px; font-family: Arial;"
        self.style_not_OK = "color: #ff0000;  font-size: 22px; font-family: Arial;"
        self.style_header = "color: #ffff00;  font-size: 16px; font-family: Arial;"

        self.initUI()

    def initUI(self):
        self.scene = QGraphicsScene()
        self.zoom = 0.1
        self.view = Preview(self.scene, self)
        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setTransform(QTransform().scale(self.zoom, self.zoom))
        self.view.setBackgroundBrush(QBrush(QColor(40, 40, 50)))
        self.setCentralWidget(self.view)
        self.LayOutLoaded = False
        # self.TT()

        openAction = QAction(QIcon('icons/open.png'), 'Открыть', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Открыть макет для проверки')
        openAction.triggered.connect(self.loadDialog)

        saveAction = QAction(QIcon('icons/save.png'), 'Сохранить', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Сохранить макет')
        saveAction.triggered.connect(self.saveDialog)

        closeAction = QAction(QIcon('icons/close.png'), 'Закрыть', self)
        closeAction.setShortcut('Ctrl+C')
        closeAction.setStatusTip('Закрыть макет')

        editAction = QAction(QIcon('icons/edit.png'), 'Редактировать', self)
        editAction.setShortcut('Ctrl+C')
        editAction.setStatusTip('Закрыть макет')

        mailAction = QAction(QIcon('icons/mail.png'), 'Почта', self)
        mailAction.setShortcut('Ctrl+C')
        mailAction.setStatusTip('Перейти к почте')

        exitAction = QAction(QIcon('icons/exit.png'), 'Выйти', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Закрыть приложение')
        exitAction.triggered.connect(self.close)

        self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl+Z", enabled=True)
        self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+X", enabled=True)
        self.normalSizeAct = QAction("&Normal Size", self, shortcut="A")

        icon1 = QIcon()
        icon1.addPixmap(QPixmap('icons/auto_TT.png'))
        icon1.addPixmap(QPixmap('icons/auto_TT_dis.png'), QIcon.Disabled)
        icon1.addPixmap(QPixmap('icons/auto_TT_cl.png'), QIcon.Active)
        self.AutoSelectTT_act = QAction(icon1, 'Автоподбор ТТ', self, shortcut="Ctrl+T", enabled=False,
                                        triggered=self.Auto_SelectTT)

        icon2 = QIcon()
        icon2.addPixmap(QPixmap('icons/check.png'))
        icon2.addPixmap(QPixmap('icons/check_dis.png'), QIcon.Disabled)
        icon2.addPixmap(QPixmap('icons/check_cl.png'), QIcon.Active)
        self.CheckTT_act = QAction(icon2, 'Автоподбор ТТ', self, shortcut="Ctrl+R", enabled=False,
                                   triggered=self.CheckLayOut)

        icon3 = QIcon()
        icon3.addPixmap(QPixmap('icons/top.png'))
        icon3.addPixmap(QPixmap('icons/top_dis.png'), QIcon.Disabled)
        icon3.addPixmap(QPixmap('icons/top_cl.png'), QIcon.Active)
        self.TopZone_act = QAction(icon3, 'Автоподбор ТТ', self, shortcut="Ctrl+Y", enabled=False,
                                   triggered=self.ShowVipZone)

        self.icon4 = QIcon()
        self.icon4.addPixmap(QPixmap('icons/show_input.png'))
        self.icon4.addPixmap(QPixmap('icons/show_input_dis.png'), QIcon.Disabled)
        self.icon4.addPixmap(QPixmap('icons/show_input_cl.png'), QIcon.Active)
        self.Show_input_act = QAction(self.icon4, 'Автоподбор ТТ', self, shortcut="Ctrl+I", enabled=False,
                                      triggered=self.ShowInputPrw)

        self.statusBar()

        but_tool = QPushButton()
        but_tool.setIcon(QIcon('icons/close.png'))
        but_tool.setIconSize(QSize(40, 40))

        self.dism_iconX = QLabel()
        self.dism_iconX.setPixmap(QPixmap('icons/dism_x.png'))
        self.dism_iconX.setToolTip('Ширина макета в мм')
        self.dismX = QLabel()
        self.dismX.setText('      ')
        self.dismX.setStyleSheet(self.style_norm)

        self.dism_iconY = QLabel()
        self.dism_iconY.setPixmap(QPixmap('icons/dism_y.png'))
        self.dism_iconY.setToolTip('Высота макета в мм')
        self.dismY = QLabel()
        self.dismY.setText('      ')
        self.dismY.setStyleSheet(self.style_norm)

        self.res_icon = QLabel()
        self.res_icon.setPixmap(QPixmap('icons/dpi.png'))
        self.res_icon.setToolTip(
            'Разрешение макета в dpi.\n Если исходник макета в ppcm, макет будет отконвертирован в dpi автоматически')
        self.resToolbar = QLabel()
        self.resToolbar.setText('      ')
        self.resToolbar.setStyleSheet(self.style_norm)

        self.mode_icon = QLabel()
        self.mode_icon.setPixmap(QPixmap('icons/mode.png'))
        self.mode_icon.setToolTip('Цветовой режим макета')
        self.modeToolbar = QLabel()
        self.modeToolbar.setText('      ')
        self.modeToolbar.setStyleSheet(self.style_norm)

        self.icc_icon = QLabel()
        self.icc_icon.setPixmap(QPixmap('icons/icc.png'))
        self.icc_icon.setToolTip('Цветовой профиль макета')
        self.iccToolbar = QLabel()
        self.iccToolbar.setText('      ')
        self.iccToolbar.setStyleSheet(self.style_norm)

        self.comboLabel_title = QLabel('ТЕХ ТРЕБОВАНИЯ')
        self.comboLabel_title.setStyleSheet(self.style_appFont_title)
        self.comboLabel_tables = QLabel('Раздел')
        self.comboLabel_tables.setStyleSheet(self.style_appFont)
        self.comboTT_tables = QComboBox()
        self.comboTT_tables.addItems(self.tables)
        self.comboTT_tables.activated[str].connect(self.tables_Activated)
        self.comboLabel2 = QLabel('Локация')
        self.comboLabel2.setStyleSheet(self.style_appFont)
        self.comboTT_location = QComboBox()
        self.comboTT_location.addItems([' '])
        self.comboTT_location.activated[str].connect(self.location_Activated)
        self.comboLabel3 = QLabel('Название ТТ')
        self.comboLabel3.setStyleSheet(self.style_appFont)
        self.comboTT_name = QComboBox()
        self.comboTT_name.addItems([' '])
        self.comboTT_name.activated[str].connect(self.name_Activated)
        self.comboLabelCode = QLabel('Код ТТ')
        self.comboLabelCode.setStyleSheet(self.style_appFont)
        self.comboTT_code = QComboBox()
        self.comboTT_code.addItems([' '])
        self.comboTT_code.activated[str].connect(self.code_Activated)
        self.TT_dismentions = QLabel('')
        self.TT_dismentions.setStyleSheet(self.style_appFont)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('Файл')
        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(editAction)
        fileMenu.addAction(closeAction)
        fileMenu.addAction(exitAction)

        checkMenu = menubar.addMenu('Проверить')
        editMenu = menubar.addMenu('Редактировать')
        mailMenu = menubar.addMenu('Почта')
        mailMenu.addAction(mailAction)
        viewMenu = menubar.addMenu('Вид')
        viewMenu.addAction(self.zoomInAct)
        viewMenu.addAction(self.zoomOutAct)

        toolbar = self.addToolBar('TopToolbar')
        toolbar.setIconSize(QSize(40, 40))
        toolbar.addAction(openAction)
        toolbar.addAction(saveAction)
        toolbar.addAction(closeAction)
        toolbar.addAction(editAction)
        toolbar.addAction(mailAction)
        toolbar.addAction(exitAction)
        toolbar.addSeparator()
        toolbar.addWidget(self.dism_iconX)
        toolbar.addWidget(self.dismX)
        toolbar.addWidget(self.dism_iconY)
        toolbar.addWidget(self.dismY)
        toolbar.addWidget(self.res_icon)
        toolbar.addWidget(self.resToolbar)
        toolbar.addWidget(self.mode_icon)
        toolbar.addWidget(self.modeToolbar)
        toolbar.addWidget(self.icc_icon)
        toolbar.addWidget(self.iccToolbar)

        self.toolbarTT = self.addToolBar('TT_Toolbar')
        self.addToolBar(Qt.RightToolBarArea, self.toolbarTT)
        # self.toolbarTT.setStyleSheet(self.style_appFont)
        self.toolbarTT.setIconSize(QSize(200, 40))
        self.toolbarTT.addWidget(self.comboLabel_title)
        self.toolbarTT.addWidget(self.comboLabel_tables)
        self.toolbarTT.addWidget(self.comboTT_tables)
        self.toolbarTT.addWidget(self.comboLabel2)
        self.toolbarTT.addWidget(self.comboTT_location)
        self.toolbarTT.addWidget(self.comboLabel3)
        self.toolbarTT.addWidget(self.comboTT_name)
        self.toolbarTT.addWidget(self.comboLabelCode)
        self.toolbarTT.addWidget(self.comboTT_code)
        self.toolbarTT.addWidget(self.TT_dismentions)
        self.toolbarTT.addAction(self.AutoSelectTT_act)
        self.toolbarTT.addAction(self.CheckTT_act)
        self.toolbarTT.addAction(self.TopZone_act)
        self.toolbarTT.addAction(self.Show_input_act)

        self.desktop = QApplication.desktop()
        self.setGeometry(0, 0, self.desktop.width() - 5, self.desktop.height() - 80)
        self.setWindowIcon(QIcon("icons/icon.png"))
        self.setWindowTitle('LayOutQC')
        self.show()

    def zoomIn(self):
        if self.zoom <=30:
            self.zoom *= 1.05
            self.updateView()

    def zoomOut(self):
        if self.zoom >= 0.05:
            self.zoom /= 1.05
            self.updateView()

    def updateView(self):
        self.view.setTransform(QTransform().scale(self.zoom, self.zoom))
    # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\END UI\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

    def loadDialog(self):
        home_folder = os.listdir('D:/')
        if not 'LayOutQC' in home_folder:
            os.mkdir('D:/LayOutQC/')
        if not '--INCOMING--' in home_folder:
            os.mkdir('D:/--INCOMING--/')
        self.load_name = QFileDialog.getOpenFileName(self, 'Open file', 'D:/LayOutQC/', "TIF files (*.tif)")[0]
        self.FileName = self.load_name.split("/")[-1]
        self.PathName = self.load_name[:len(self.load_name) - len(self.FileName)]
        if self.FileName:
            self.im = ImagePil.open(self.load_name)
            self.LayOutLoaded = True
            self.prw_name = 'temp/input_temp.png'
            self.comboTT_tables.setCurrentText(' ')
            self.comboTT_location.clear()
            self.comboTT_location.addItems([' '])
            self.comboTT_name.clear()
            self.comboTT_name.addItems([' '])
            self.comboTT_code.clear()
            self.comboTT_code.addItems([' '])
            self.TT_dismentions.setText('')
            self.CheckTT_act.setEnabled(False)
            self.Show_input_act.setIcon(self.icon4)
            self.Show_input_act.setEnabled(False)
            self.TopZone_act.setEnabled(False)
            files = glob.glob('temp/*')
            for f in files:
                os.remove(f)

            # Runing Layout Module
            self.layout = Layout(self.im)
            self.layout._DEBAG(LayoutQC_DEBAG)

            #  set Layout info into Toolbar
            self.modeToolbar.setStyleSheet(self.layout.layout_mode_status())
            self.iccToolbar.setStyleSheet(self.layout.layout_profile_status())

            self.modeToolbar.setText(self.layout.image.mode)
            self.resToolbar.setText(str(self.layout.resolution))
            self.dismX.setText(str(self.layout.width_layout) + 'mm')
            self.dismY.setText(str(self.layout.height_layout) + 'mm')
            self.iccToolbar.setText(self.layout.layout_profile_name())

            # make $ showing preview
            self.layout.make_prw(self.prw_name, LayoutQC_DEBAG=LayoutQC_DEBAG)


            # self.im222=QPixmap(self.prw_name)


            # self.scaleFactor = 1.0
            # show_x = self.desktop.width() - 270
            # show_y = show_x / self.im.size[0] * self.im.size[1]
            # if show_y > self.desktop.height() - 200:
            #     show_y = self.desktop.height() - 200
            #     show_x = show_y / self.im.size[1] * self.im.size[0]

            width_central_widget = self.desktop.width() - 222
            height_central_widget = self.desktop.width() - 178
            if self.im.size[0] > self.im.size[1]:
                self.zoom = width_central_widget / self.im.size[0]
            else:
                self.zoom = height_central_widget / self.im.size[1]

            self.scene.clear()
            self.scene.addPixmap(QPixmap(self.prw_name))
            self.updateView()

            print(self.desktop.width())
            print(self.desktop.height())


            self.AutoSelectTT_act.setEnabled(True)
            self.tables = self.layout.layout_db_tabeles
            self.comboTT_tables.addItems(self.tables)
            self.name_Layout()

    def name_Layout(self):
        self.completer_list = []
        self.name_and_folder = self.FileName.split('.')[0]
        self.suget = ''
        for n in os.listdir('D:/LayOutQC/'):
            if not os.path.isfile('D:/LayOutQC/' + n):
                self.completer_list.append(n)
        self.popup(700, 50, 'Название макета')
        grid = QGridLayout()
        klientTitle = QLabel('Клиент')
        klientTitle.setStyleSheet(style_title)
        sugetTitle = QLabel('Сюжет')
        sugetTitle.setStyleSheet(style_title)
        klientInput = QLineEdit(self.name_and_folder)
        completer = QCompleter(self.completer_list)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        klientInput.setCompleter(completer)
        klientInput.textChanged[str].connect(self.klient_name)
        klientInput.setStyleSheet(style_OK)
        sugetInput = QLineEdit()
        sugetInput.textChanged[str].connect(self.suget_name)
        sugetInput.setStyleSheet(style_OK)
        grid.addWidget(klientTitle, 0, 0)
        grid.addWidget(sugetTitle, 1, 0)
        grid.addWidget(klientInput, 0, 1)
        grid.addWidget(sugetInput, 1, 1)
        self.layoutPop_old.insertLayout(0, grid)
        self.add_butOK(connect=self.make_Folder, text='Закрыть')
        self.add_butClose()
        self.path = self.PathName
        self.popUpModal.show()

    def klient_name(self, name_):
        self.name_and_folder = name_

    def suget_name(self, name_):
        self.suget = name_



    def make_Folder(self):
        # if self.name_and_folder != None or ' ':
        #     self.name_Layout()
        self.layout.makeFolder(self.name_and_folder, self.suget)




    def saveDialog(self):
        self.klient_suget = self.name_and_folder + '_' + self.suget
        self.signature = self.layout.makeSignature()
        self.comment = self.layout.makeComment()
        self.popup(900, 50, "Код ТТ")
        grid = QGridLayout()
        klientTitle = QLabel('Название')
        klientTitle.setStyleSheet(style_title)
        sugetTitle = QLabel('Подпись')
        sugetTitle.setStyleSheet(style_title)
        comentTitle = QLabel('Коментарий')
        comentTitle.setStyleSheet(style_title)
        nameInput = QLineEdit(self.klient_suget)
        nameInput.setStyleSheet(style_OK)
        nameInput.textChanged[str].connect(self.ks)

        signatureInput = QLineEdit(self.signature)
        signatureInput.setStyleSheet(style_OK)
        signatureInput.textChanged[str].connect(self.sig)

        commentInput = QLineEdit( self.comment)
        commentInput.setStyleSheet(style_OK)
        commentInput.textChanged[str].connect(self.com)

        person = QLabel('FRA')
        person.setStyleSheet(style_title)
        grid.addWidget(klientTitle, 0, 0)
        grid.addWidget(sugetTitle, 0, 1)
        grid.addWidget(comentTitle, 0, 2)
        grid.addWidget(nameInput, 1, 0)
        grid.addWidget(signatureInput, 1, 1)
        grid.addWidget(commentInput, 1, 2)
        grid.addWidget(person, 1, 3)
        self.layoutPop_old.insertLayout(0, grid)

        self.add_butOK(connect=self.save_)
        self.add_butClose()
        self.popUpModal.show()

    def ks(self, name_):
        self.klient_suget = name_

    def sig(self, name_):
        self.signature = name_

    def com(self, name_):
        self.comment = name_
    def save_(self):
        self.layout.saveLayout(self.klient_suget + self.signature + self.comment,  self.load_name, self.PathName)

    # ====================================================================================


        # ======================================  TT DATABASE  ==============================================

        # |||||||||||||||||||||||||||||||||||||||||||||||QUERY FOR A LOCATION||||||||||||||||||||||||||||||||||

    def tables_Activated(self, text_tables):
        self.comboTT_location.clear()
        self.comboTT_location.addItems([' '])
        self.comboTT_name.clear()
        self.comboTT_name.addItems([' '])
        self.comboTT_code.clear()
        self.comboTT_code.addItems([' '])
        self.TT_dismentions.setText('')
        locations = self.layout.table_Activated(text_tables)
        self.comboTT_location.addItems(locations)
        self.Show_input_act.setEnabled(False)

    # ||||||||||||||||||||||||||||||||||||||||||||||||||QUERY FOR A NAME TT|||||||||||||||||||||||||||||||||||||||

    def location_Activated(self, text_location):
        self.comboTT_name.clear()
        self.comboTT_name.addItems([' '])
        self.comboTT_code.clear()
        self.comboTT_code.addItems([' '])
        self.TT_dismentions.setText('')
        name = self.layout.location_Activated(text_location)
        self.comboTT_name.addItems(name)
        self.Show_input_act.setEnabled(False)

    # |||||||||||||||||||||||||||||||||||||QUERY FOR A CODE TT|||||||||||||||||||||||||||||||||||||||||||||
    def name_Activated(self, text_name):
        self.comboTT_code.clear()
        self.comboTT_code.addItems([' '])
        self.TT_dismentions.setText('')
        self.codes = self.layout.name_Activated(text_name)
        self.comboTT_code.addItems(self.codes)
        if text_name != ' ':
            if self.LayOutLoaded:
                self.TT_dismentions.setText(self.layout.layout_db.tt_value())
                self.CheckTT_act.setEnabled(True)
                # self.TopZone_act.setEnabled(True)
        self.Show_input_act.setEnabled(False)
        if LayoutQC_DEBAG:
            print('Name ', text_name, ' activated')

    def code_Activated(self, text_code):
        if text_code == 'выбрать несколько конструкций':
            self.PopUpCode()
        if LayoutQC_DEBAG:
            print('Code ', text_code, ' activated')
        self.Show_input_act.setEnabled(False)

    def ButtonClicked(self):
        checked_list = []
        for i in range(self.table_autoselectedTT.rowCount()):
            if self.table_autoselectedTT.cellWidget(i, 0).findChild(type(QCheckBox())).isChecked():
                checked_list.append(self.table_autoselectedTT.item(i, 1).text())
        ch = [str(checked_list).replace("', '", ",")[2:-2]]
        self.comboTT_code.clear()
        self.comboTT_code.addItems(ch + ['выбрать несколько конструкций'] + self.codes[:-1])
        self.code_Activated(ch[0])

    # ||||||||||||||||||||||||||||||||||||||||||||||||||||FUNC TO SHOW POPUP CODE|||||||||||||||||||||||||||||||
    def PopUpCode(self):
        self.popup(200, 400, "Код ТТ")
        self.table_autoselectedTT = QTableWidget(len(self.codes[:-1]), 2, self)
        self.table_autoselectedTT.setSelectionMode(QAbstractItemView.NoSelection)
        self.table_autoselectedTT.setStyleSheet(
            "background-color: rgba(55, 55, 68, 0.1); color: #8fa3c4;  font-size: 16px; font-family: Arial;  "
            "margin-bottom: 5px; margin-top: 5px; text-align: center;")
        self.table_autoselectedTT.horizontalHeader().hide()
        self.table_autoselectedTT.verticalHeader().hide()
        self.table_autoselectedTT.setShowGrid(False)
        row = 0
        for name_row in self.codes[:-1]:
            widget = QWidget()
            checkbox = QCheckBox()
            checkbox.setCheckState(Qt.Unchecked)
            layoutH = QHBoxLayout(widget)
            layoutH.addWidget(checkbox)
            layoutH.setAlignment(Qt.AlignCenter)
            layoutH.setContentsMargins(0, 0, 0, 0)
            self.table_autoselectedTT.setCellWidget(row, 0, widget)
            self.table_autoselectedTT.setItem(row, 1, QTableWidgetItem(name_row))
            row += 1
        self.layoutPop_old.insertWidget(0, self.table_autoselectedTT)
        self.add_butOK(connect=self.ButtonClicked)
        self.add_butClose()
        self.popUpModal.show()

    def popup(self, x_w, y_h, name_pop):
        self.popUpModal = QWidget(ex, Qt.Tool)
        self.popUpModal.setWindowTitle(name_pop)
        self.popUpModal.setGeometry(self.desktop.width() / 2 - x_w / 2, self.desktop.height() / 2 - y_h / 2, x_w, y_h)
        self.popUpModal.setWindowModality(Qt.WindowModal)
        self.popUpModal.setAttribute(Qt.WA_DeleteOnClose, True)
        palle = self.popUpModal.palette()
        palle.setBrush(QPalette.Window, QBrush(QPixmap("bg_workspace_tools.png")))
        self.popUpModal.setPalette(palle)
        self.layoutPop_old = QVBoxLayout(self)
        self.layout_but = QHBoxLayout()
        self.layoutPop_old.addLayout(self.layout_but)
        self.popUpModal.setLayout(self.layoutPop_old)

    def Auto_SelectTT(self):
        self.autoselect_result = self.layout.Auto_SelectTT() \
                                 + [
                                     '---------------------------------------Похожие ТТ---------------------------------------'] \
                                 + self.layout.Auto_SelectTT_warning()

        self.popup(800, 400, "Выберите ТТ")
        self.table_autoselectedTT = QTableWidget(len(self.autoselect_result), 1, self)
        self.table_autoselectedTT.setStyleSheet(
            "background-color: rgba(55, 55, 68, 0.1); color: #8fa3c4;  font-size: 16px; "
            "font-family: Arial;  text-align: center;")
        self.table_autoselectedTT.setShowGrid(False)
        self.table_autoselectedTT.verticalHeader().hide()
        self.table_autoselectedTT.horizontalHeader().hide()
        self.table_autoselectedTT.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        row = 0
        for name_row in self.autoselect_result:
            if name_row == '---------------------------------------Похожие ТТ---------------------------------------':
                m = str(name_row)
            else:
                m = str(name_row).replace("', '", ", ")[2:-2]
            self.table_autoselectedTT.setItem(row, 0, QTableWidgetItem(m))
            row += 1
        header_no_TT = QLabel('Нет подходящих ТТ').setStyleSheet(self.style_not_OK)
        if self.autoselect_result:
            self.layoutPop_old.insertWidget(0, self.table_autoselectedTT)
        else:
            self.layoutPop_old.insertWidget(0, header_no_TT, alignment=Qt.AlignCenter)
        self.table_autoselectedTT.clicked.connect(self.AutoSelectChecked)
        self.add_butClose()
        self.popUpModal.show()

    def AutoSelectChecked(self):
        choosed_TT = []
        for n in self.table_autoselectedTT.selectedItems():
            choosed_TT = self.autoselect_result[n.row()]
        if choosed_TT != '---------------------------------------Похожие ТТ---------------------------------------':
            text_tables = choosed_TT[0]
            self.comboTT_tables.setCurrentText(text_tables)
            self.tables_Activated(text_tables)
            text_location = choosed_TT[1]
            self.comboTT_location.setCurrentText(text_location)
            self.location_Activated(text_location)
            text_name = choosed_TT[2]
            self.comboTT_name.setCurrentText(text_name)
            self.name_Activated(text_name)
            self.comboTT_code.setCurrentText(choosed_TT[3])
            self.popUpModal.close()
            self.CheckTT_act.setEnabled(True)
            self.Show_input_act.setEnabled(False)

    # ----------------------------------------------CHECKING!!!!!!!!!!!! _______
    def CheckLayOut(self):
        self.fin_temp = 'temp/out.tif'
        self.layout.CheckLayOut_func()

        checkpop = []
        CheckResult = QLabel(self.layout.CheckResult)
        CheckResult.setStyleSheet(self.style_OK)
        self.dismX.setStyleSheet(self.style_norm)
        self.dismY.setStyleSheet(self.style_norm)
        self.dismX.setText(str(self.layout.width_layout) + 'mm')
        self.dismY.setText(str(self.layout.height_layout) + 'mm')
        checkpop.append(CheckResult)
        if self.layout.CheckResult != 'Ширина и высота по ТТ ОК':
            CheckResult.setStyleSheet(self.style_not_OK)
            Check_edit_dimentions = QPushButton('Подогнать под размеры в ТТ')
            Check_edit_dimentions.clicked.connect(self.fit_dimensions)
            checkpop.append(Check_edit_dimentions)
            if self.layout.CheckResult == 'Ширина не по ТТ, а высота по ТТ ОК':
                self.dismX.setStyleSheet(self.style_warning)
            elif self.layout.CheckResult == 'Ширина по ТТ ОК, а высота не по ТТ':
                self.dismY.setStyleSheet(self.style_warning)
            else:
                self.dismX.setStyleSheet(self.style_warning)
                self.dismY.setStyleSheet(self.style_warning)

        CheckResult_DPI = QLabel(self.layout.CheckResult_DPI)
        CheckResult_DPI.setStyleSheet(self.style_OK)
        checkpop.append(CheckResult_DPI)
        if self.layout.CheckResult_DPI != 'Разрешение по ТТ ОК':
            CheckResult_DPI.setStyleSheet(self.style_not_OK)
            self.resToolbar.setStyleSheet(self.style_warning)

        CheckResult_mode = QLabel(self.layout.CheckResult_mode)
        CheckResult_mode.setStyleSheet(self.style_OK)
        checkpop.append(CheckResult_mode)
        self.modeToolbar.setText(self.layout.image.mode)
        self.modeToolbar.setStyleSheet(self.style_norm)
        if self.layout.CheckResult_mode != 'Цветовой режим CMYK OK':
            CheckResult_mode.setStyleSheet(self.style_not_OK)
            Check_edit_mode = QPushButton('Конвертировать в CMYK')
            Check_edit_mode.clicked.connect(self.convert_Mode)
            checkpop.append(Check_edit_mode)
            self.modeToolbar.setStyleSheet(self.style_warning)

        CheckResult_ICC = QLabel(self.layout.CheckResult_ICC)
        CheckResult_ICC.setStyleSheet(self.style_OK)
        checkpop.append(CheckResult_ICC)
        self.iccToolbar.setText(self.layout.layout_profile_name())
        self.iccToolbar.setStyleSheet(self.layout.layout_profile_status())

        if self.layout.CheckResult_ICC != 'Цветовой профиль Euroscale Coated v2 ОК':
            CheckResult_ICC.setStyleSheet(self.style_not_OK)
            if self.layout.CheckResult_mode == 'Цветовой режим CMYK OK' \
                    and CheckResult_ICC != 'Цветовой профиль Euroscale Coated v2 ОК':
                Check_edit_ICC_Euro = QPushButton('Изменить цветовой профиль на Euroscale Coated v2')
                Check_edit_ICC_Euro.clicked.connect(self.assign_Icc)
                checkpop.append(Check_edit_ICC_Euro)

            self.iccToolbar.setStyleSheet(self.style_warning)
        Check_edit_ICC = QPushButton('Выбрать другой цветовой профиль')
        Check_edit_ICC.clicked.connect(self.assign_AnotherICC)
        checkpop.append(Check_edit_ICC)

        self.popup(500, 230, "Результат проверки")
        n = 0
        for v in checkpop:
            self.layoutPop_old.insertWidget(n, v)
            n += 1
        if self.layout.CheckResult == 'Ширина и высота по ТТ ОК' and self.layout.image.mode == 'CMYK':
            self.add_butOK(self.ShowVipZone, 'Показать зону значимых элементов')
            self.TopZone_act.setEnabled(True)
        self.add_butClose()
        self.popUpModal.show()
        self.prw_name = self.layout.prw_name
        self.scene.clear()
        self.scene.addPixmap(QPixmap(self.prw_name))
        self.Show_input_act.setEnabled(True)

    def fit_dimensions(self):
        self.popUpModal.close()
        self.layout.FitDimensions()
        self.CheckLayOut()

    def convert_Mode(self):
        self.popUpModal.close()
        self.layout.ConvertMode_and_Icc()
        self.CheckLayOut()

    def assign_Icc(self):
        self.popUpModal.close()
        self.layout.Assign_Icc()
        self.CheckLayOut()

    def assign_AnotherICC(self):
        self.popUpModal.close()
        self.popup(500, 230, "Результат проверки")
        listdir = [f for f in os.listdir('icc/CMYK/')]
        n = 0
        for v in listdir:
            icc_but = QPushButton(v.split('.')[0])
            icc_but.setStyleSheet(style_OK)
            icc_but.clicked.connect(partial(self.Selected_ICC, v))
            self.layoutPop_old.insertWidget(n, icc_but)
            n += 1
        self.add_butClose()
        self.popUpModal.show()

    def Selected_ICC(self, icc):
        self.popUpModal.close()
        profile = ImageCms.getOpenProfile('icc/CMYK/' + icc)
        self.layout.Assign_Icc(profile)
        self.CheckLayOut()

    def ShowInputPrw(self):
        if self.prw_name == 'temp/convert_ICC_temp.png':
            self.prw_name = 'temp/input_temp.png'
            self.Show_input_act.setIcon(QIcon('icons/show_input_cl.png'))
            self.TopZone_act.setEnabled(False)
            self.CheckTT_act.setEnabled(False)
            self.AutoSelectTT_act.setEnabled(False)
        else:
            self.prw_name = 'temp/convert_ICC_temp.png'
            self.Show_input_act.setIcon(QIcon('icons/show_input.png'))
            self.TopZone_act.setEnabled(True)
            self.CheckTT_act.setEnabled(True)
            self.AutoSelectTT_act.setEnabled(True)
        self.scene.clear()
        self.scene.addPixmap(QPixmap(self.prw_name))

    def ShowVipZone(self):
        if not os.path.exists('temp/vip_temp.png'):
            self.layout.make_VIP_zone()
        if self.prw_name == 'temp/convert_ICC_temp.png' or self.prw_name == 'temp/input_temp.png':
            self.pr = self.prw_name
            self.prw_name = 'temp/vip_temp.png'
            self.CheckTT_act.setEnabled(False)
            self.AutoSelectTT_act.setEnabled(False)
            self.Show_input_act.setEnabled(False)
        elif self.prw_name == 'temp/vip_temp.png':
            self.prw_name = self.pr
            self.CheckTT_act.setEnabled(True)
            self.AutoSelectTT_act.setEnabled(True)
            self.Show_input_act.setEnabled(True)
        self.scene.clear()
        self.scene.addPixmap(QPixmap(self.prw_name))

    def add_butClose(self):
        self.butClose = QPushButton('Отмена')
        self.butClose.clicked.connect(self.popUpModal.close)
        self.layout_but.addWidget(self.butClose)

    def add_butOK(self, connect=None, text='OK'):
        self.butOK = QPushButton(text)
        if connect:
            self.butOK.clicked.connect(connect)
        self.butOK.clicked.connect(self.popUpModal.close)
        self.layout_but.addWidget(self.butOK)

    def CheckResult(self):
        print('checked')
Example #24
0
 def resetLayout(self):
     new = Layout()
     self.layout = Layout()
     self.setChanged()
Example #25
0
class TextEditor(gtk.TextView):
    def __init__(self, textbuffer = None, *args, **kwargs):
        if textbuffer is None:
            textbuffer = TextBuffer()
        gtk.TextView.__init__(self, textbuffer, *args, **kwargs)
        self.buffer           = textbuffer
        self.anno_width       = 200
        self.anno_padding     = 10
        self.anno_layout      = Layout(self)
        self.anno_views       = {}
        self.show_annotations = True
        self.handle_links     = True
        self.set_right_margin(50 + self.anno_padding)
        self.connect('map-event',           self._on_map_event)
        self.connect('expose-event',        self._on_expose_event)
        self.connect('motion-notify-event', self._on_motion_notify_event)
        self.connect('event-after',         self._on_event_after)
        self.buffer.connect('mark-set',           self._on_buffer_mark_set)
        self.buffer.connect('annotation-added',   self._on_annotation_added)
        self.buffer.connect('annotation-removed', self._on_annotation_removed)
        self.set_wrap_mode(gtk.WRAP_WORD)


    def _on_motion_notify_event(self, editor, event):
        if not self.handle_links:
            return
        x, y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET,
                                            int(event.x),
                                            int(event.y))
        tags = self.get_iter_at_location(x, y).get_tags()

        # Without this call, further motion notify events don't get
        # triggered.
        self.window.get_pointer()

        # If any of the tags are links, show a hand.
        cursor = gtk.gdk.Cursor(gtk.gdk.XTERM)
        for tag in tags:
            if tag.get_data('link'):
                cursor = gtk.gdk.Cursor(gtk.gdk.HAND2)
                break

        self.get_window(gtk.TEXT_WINDOW_TEXT).set_cursor(cursor)
        return False


    def _on_event_after(self, textview, event):
        # Handle links here. Only when a button was released.
        if event.type != gtk.gdk.BUTTON_RELEASE:
            return False
        if event.button != 1:
            return False
        if not self.handle_links:
            return

        # Don't follow a link if the user has selected something.
        bounds = self.buffer.get_selection_bounds()
        if bounds:
            start, end = bounds
            if start.get_offset() != end.get_offset():
                return False

        # Check whether the cursor is pointing at a link.
        x, y = self.window_to_buffer_coords(gtk.TEXT_WINDOW_WIDGET,
                                            int(event.x),
                                            int(event.y))
        iter = textview.get_iter_at_location(x, y)

        for tag in iter.get_tags():
            link = tag.get_data('link')
            if not link:
                continue
            self.emit('link-clicked', link)
            break
        return False


    def _on_buffer_mark_set(self, buffer, iter, mark):
        self._update_annotations()


    def _on_map_event(self, widget, event):
        self._update_annotation_area()
        self._update_annotations()


    def _on_expose_event(self, widget, event):
        text_window = widget.get_window(gtk.TEXT_WINDOW_TEXT)
        if event.window != text_window:
            return

        # Create the cairo context.
        ctx = event.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        ctx.rectangle(event.area.x,
                      event.area.y,
                      event.area.width,
                      event.area.height)
        ctx.clip()

        self.draw(ctx, *event.window.get_size())


    def draw(self, ctx, w, h):
        if ctx is None:
            return
        if not self.show_annotations:
            return

        # Draw the dashes that connect annotations to their marker.
        ctx.set_line_width(1)
        ctx.set_dash((3, 2))
        right_margin = self.get_right_margin()
        for annotation in self.anno_layout.get_children():
            mark_x, mark_y = self._get_annotation_mark_position(annotation)
            anno_x, anno_y, anno_w, anno_h, d = annotation.window.get_geometry()
            path = [(mark_x,           mark_y - 5),
                    (mark_x,           mark_y),
                    (w - right_margin, mark_y),
                    (w,                anno_y + anno_h / 2)]

            stroke_color = annotation.get_border_color()
            ctx.set_source_rgba(*color.to_rgba(stroke_color))
            ctx.move_to(*path[0])
            for x, y in path[1:]:
                ctx.line_to(x, y)
            ctx.stroke()


    def _get_annotation_mark_offset(self, view1, view2):
        mark1 = view1.annotation.start_mark
        mark2 = view2.annotation.start_mark
        iter1 = self.get_buffer().get_iter_at_mark(mark1)
        iter2 = self.get_buffer().get_iter_at_mark(mark2)
        rect1 = self.get_iter_location(iter1)
        rect2 = self.get_iter_location(iter2)
        if rect1.y != rect2.y:
            return rect1.y - rect2.y
        return rect2.x - rect1.x


    def _get_annotation_mark_position(self, view):
        start_mark     = view.annotation.start_mark
        iter           = self.get_buffer().get_iter_at_mark(start_mark)
        rect           = self.get_iter_location(iter)
        mark_x, mark_y = rect.x, rect.y + rect.height
        return self.buffer_to_window_coords(gtk.TEXT_WINDOW_TEXT,
                                            mark_x, mark_y)


    def _update_annotation(self, annotation):
        # Resize the annotation.
        item_width = self.anno_width - 2 * self.anno_padding
        annotation.set_size_request(item_width, -1)

        # Find the x, y of the annotation's mark.
        mark_x, mark_y = self._get_annotation_mark_position(annotation)
        self.anno_layout.pull(annotation, mark_y)


    def _update_annotation_area(self):
        # Update the width and color of the annotation area.
        self.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, self.anno_width)
        bg_color = self.get_style().base[gtk.STATE_NORMAL]
        window   = self.get_window(gtk.TEXT_WINDOW_RIGHT)
        if window:
            window.set_background(bg_color)


    def _update_annotations(self):
        if not self.show_annotations:
            return

        # Sort the annotations by line/char number and update them.
        iter   = self.get_buffer().get_end_iter()
        rect   = self.get_iter_location(iter)
        height = rect.y + rect.height
        self.anno_layout.sort(self._get_annotation_mark_offset)
        for annotation in self.anno_layout.get_children():
            self._update_annotation(annotation)
        self.anno_layout.update(self.anno_width, height)

        # Update lines.
        self.queue_draw()


    def set_annotation_area_width(self, width, padding = 10):
        self.anno_width   = width
        self.anno_padding = padding
        self._update_annotations()


    def _on_annotation_added(self, buffer, annotation):
        if self.show_annotations == False:
            return
        annotation.set_display_buffer(self.buffer)
        view = AnnotationView(annotation)
        self.anno_views[annotation] = view
        for event in ('focus-in-event', 'focus-out-event'):
            view.connect(event, self._on_annotation_event, annotation, event)
        view.show_all()
        self._update_annotation_area()
        self.anno_layout.add(view)
        self.add_child_in_window(view,
                                 gtk.TEXT_WINDOW_RIGHT,
                                 self.anno_padding,
                                 0)
        self._update_annotations()


    def _on_annotation_removed(self, buffer, annotation):
        view = self.anno_views[annotation]
        self.anno_layout.remove(view)
        self.remove(view)


    def _on_annotation_event(self, buffer, *args):
        annotation = args[-2]
        event_name = args[-1]
        self.emit('annotation-' + event_name, annotation)


    def set_show_annotations(self, active = True):
        if self.show_annotations == active:
            return

        # Unfortunately gtk.TextView deletes all children from the
        # border window if its size is 0. So we must re-add them when the
        # window reappears.
        self.show_annotations = active
        if active:
            for annotation in self.buffer.get_annotations():
                self._on_annotation_added(self.buffer, annotation)
        else:
            for annotation in self.buffer.get_annotations():
                self._on_annotation_removed(self.buffer, annotation)
            self.set_border_window_size(gtk.TEXT_WINDOW_RIGHT, 0)


    def set_handle_links(self, handle):
        """
        Defines whether the cursor is changed and whether clicks are accepted
        when hovering over text with tags that have data named "link"
        attached.
        """
        self.handle_links = handle
Example #26
0
zM = 75  # Altitude du mât
zL = 0  # Altitude du Lidar

# ---------- Représentations ----------

plt.close('all')

# Disposition du parc éolien

rep = builtins.input(
    "Do you wish to display the layout of the windfarm (Y/N) ? ")

if rep.upper() == "Y" or rep.upper(
) == "O":  # O pour ceux qui voudraient dire oui
    xM, yM, xL, yL = Layout(path + "Work/", True)
else:
    xM, yM, xL, yL = Layout(path + "Work/", False)
    plt.close("Layout")

# Maillage

rep = builtins.input(
    "Do you wish to display the grid of the points measured by the Lidar (Y/N) ? "
)

if rep.upper() == "Y" or rep.upper() == "O":
    sav = builtins.input("Do you wish to save it (Y/N) ? ")
    n = builtins.input(
        "Number of points (Recommended : 800) : ")  # 800 c'est pas mal
    t = builtins.input(
Example #27
0
class World(object):
    """description of class"""

    def __init__(self, app):
        
        self.__organisms = []
        self.__born = []
        self.__dead = []
        self.__sheeps = []
        self.__heracleums = []
        self.__organismsC = 0
        self.__start = False
        self.__changed = False
        self.__layout = Layout(self, app)

    @property
    def age(self):
        self.__organismsC += 1
        return self.__organismsC

    @age.setter
    def age(self, value):
        self.__organismsC = value

    @property
    def start(self):
        return self.__start

    @start.setter
    def start(self, value):
        self.__start = value

    @property
    def layout(self):
        return self.__layout
    
    @property
    def finish(self):
        return self.__player.isAlive

    @property
    def input(self):
        pass

    @input.setter
    def input(self, code):
        self.__player.input = code

    def __Populate(self, n):
        for i in range(n):
            for entity in Entities:
                o = entity.Create()
                #o = Entities.CreateString("Fox")
                o.age = self.age
                o.world = self
                self.AddToWorld(o, Navigation.NULL_POINT)

    def __ClearLegend(self):
        legend = self.layout.legend
        legend.Clear()

    def NextTurn(self):
        self.Notify("New turn!")

        if len(self.__born) != 0:
            for o in self.__born:
                self.__organisms.append(o)

            self.__born.clear()
            self.__born.sort(key = Organism.compareTo)

        for o in self.__organisms:
            if o.isAlive == True:
                o.Action()
        
        if len(self.__dead) != 0:
            for o in self.__dead:
                self.__organisms.remove(o)

            self.__dead.clear()

        if self.__changed == True:
            for sheep in self.__sheeps:
                p = self.__SeekClosest(sheep)
                sheep.target = p
            self.__change = False

    def __SeekClosest(self, sheep):
        if len(self.__heracleums) == 0:
            return None

        max = -1
        seek = None

        for heracleum in self.__heracleums:
            result = 0
            result += abs(sheep.location.x - heracleum.location.x)
            result += abs(sheep.location.y - heracleum.location.y)

            if (max == -1) or result < max:
                max = result
                seek = heracleum.location

        return seek

    def WorldInit(self, oc):

        rows = self.layout.height
        cols = self.layout.width

        self.__board = Board(cols, rows)

        self.__player = Human(self.age, self)
        self.AddToWorld(self.__player, Navigation.NULL_POINT)

        self.__Populate(oc)

    def Notify(self, s):
        self.__layout.Print(s)

    def AddToWorld(self, o, p):
        self.__born.append(o)

        if p == Navigation.NULL_POINT:
            self.__board.SetAt(o)
        else:
            self.__board.SetAtPoint(p, o)

        self.__layout.Update(o)

        if isinstance(o, CyberSheep.CyberSheep):
            self.__sheeps.append(o)
        if isinstance(o, HeracleumSosnowskyi.HeracleumSosnowskyi):
            self.__heracleums.append(o)
            self.__changed = True

    def RemoveFromWorld(self, o):
        self.__layout.Clear(o.location)
        self.__board.KillAt(o.location)
        self.__dead.append(o)

        if isinstance(o, CyberSheep.CyberSheep):
            self.__sheeps.remove(o)
        if isinstance(o, HeracleumSosnowskyi.HeracleumSosnowskyi):
            self.__heracleums.remove(o)
            self.__changed = True

    def MassRemoveFromWorld(self, s, p, foo):

        x = 0 if p.x - 1 < 0 else p.x - 1
        y = 0 if p.y - 1 < 0 else p.y - 1

        yMax = p.x if p.x + 1 == self.__board.row else p.x + 1
        xMax = p.y if p.y + 1 == self.__board.col else p.y + 1

        temp = Point(0, 0)

        for i in range(x, xMax + 1):
            for j in range(y, yMax + 1):
                if (i == p.x) and (y == p.y):
                    continue

                temp.set(i, j)

                o = self.__board.GetAt(temp)
                if o == None:
                    continue

                if foo(o) == False:
                    continue
                else:
                    o.Kill(s)

    def PointValidate(self, p):
        return self.__board.Validate(p)

    def SeekForFree(self, p):
        return self.__board.SeekForFree(p)

    def GetAt(self, p):
        return self.__board.GetAt(p)

    def MoveTo(self, p, o):
        self.__layout.Clear(o.location)
        self.__board.SetAtPoint(p, o)
        self.__layout.Update(o)

    def LegendUpdate(self, dir):
        self.__ClearLegend()
        
        legend = self.layout.legend

        legend.AppendText("STATISTICS:\n")
        legend.AppendText("Strength: " + str(self.__player.strength) + "\n")
        legend.AppendText("Position: " + self.__player.location.string + "\n")
        
        legend.AppendText("\n")
        
        if dir != WorldDirections.DIR_NULL:
            legend.AppendText("Current direction: " + Navigation.string(dir) + "\n")

        legend.AppendText("\n")

        legend.AppendText("Cooldown: " + str(self.__player.cooldown) + "\n")
        legend.AppendText("Duration: " + str(self.__player.duration) + "\n")

        if self.__player.duration > 0:
            legend.AppendText("\n")
            legend.AppendText("Player empowered.\n")

    def ClearInput(self):
        self.__direction = WorldDirections.DIR_NULL

    def Save(self, e):

        f = open("C:/Users/abc/source/repos/PythonApplication1/PythonApplication1/General/Resources/save.txt", "w")

        #saving
        self.Notify("Saving...")

        #world
        f.write("%d\n" %self.__organismsC)

        #board
        f.write("%d\n%d\n" %(self.__board.row, self.__board.col))

        p = Point(0, 0)

		#organisms
        for y in range(self.__board.row):
            for x in range(self.__board.col):
                p.set(x, y)
                o = self.GetAt(p)

                if o == None:
                     f.write("%d\n" %0)
                else:
                    f.write("%d\n%c\n%d\n%d\n" %(1, o.token, o.age, o.strength))

        #born
        f.write("%d\n" %len(self.__born))
        for o in self.__born:
            if o == None:
                f.write("%d\n" %0)
            else:
                f.write("%d\n%d\n%d\n" %(1, o.location.x, o.location.y))

        #dead
        f.write("%d\n" %len(self.__dead))
        for o in self.__dead:
            if o == None:
                f.write("%d\n" %0)
            else:
                f.write("%d\n%d\n%d\n" %(1, o.location.x, o.location.y))

        f.write("%d\n%d" %(self.__player.cooldown, self.__player.duration))

        f.close()
        self.Notify("Saving complete!")

    def Load(self, e):

        f = open("C:/Users/abc/source/repos/PythonApplication1/PythonApplication1/General/Resources/save.txt", "r")

        #loading
        self.Notify("Loading...")

        i1 = int(f.readline())
        self.age = i1

        #board
        i1 = int(f.readline())
        i2 = int(f.readline())

        self.layout.Build(i1, i2)

        self.__born.clear()
        self.__dead.clear()

        #organisms
        for y in range(self.__board.row):
            for x in range(self.__board.col):
                p = Point(x, y)

                i1 = int(f.readline())

                if i1 == 0:
                    continue
                else:
                    t = f.readline()[0]
                    i2 = int(f.readline())
                    i3 = int(f.readline())

                    o = Entities.CreateChar(t)
                    o.world = self
                    o.age = i2
                    o.strength = i3
                    o.location = p

                    self.AddToWorld(o, p)

        self.__board.Print()

        #born
        i1 = int(f.readline())
        for i in range(i1):
            i2 = int(f.readline())
            if i2 == 0:
                continue
            else:
                i3 = int(f.readline())
                i4 = int(f.readline())

                p = Point(i3, i4)

                self.__born.append(self.GetAt(p))

        #dead
        i1 = int(f.readline())
        for i in range(i1):
            i2 = int(f.readline())
            if i2 == 0:
                continue
            else:
                i3 = int(f.readline())
                i4 = int(f.readline())

                p = Point(i3, i4)

                self.__dead.append(self.GetAt(p))

        i1 = int(f.readline())
        i2 = int(f.readline())

        self.__player.SetActive(i1, i2)

        f.close()
        self.__ClearLegend()
        self.Notify("Loading complete!")
Example #28
0
            Increase current step by one.
        """
        self.step = self.step + 1
        
    def decStep(self):
        """
            Decrease current step by one.
        """
        if self.step <= 0:
            raise RuntimeError("Step number has already been zero")
        self.step = self.step - 1

    def setStep(self, num):
        """
            Step step number.
        """
        if num < 0:
            raise ValueError("Step number less than zero")
        self.step = num
if __name__ == '__main__':
    from Layout import Layout
    chessBoard = ChessBoard()
    l = Layout( 0 )
    l.setToDefault()
    chessBoard.copyFromLayout( 0, l )
    mv0 = Movement(0, 29, 23, Result.RES_WIN)
    mv1 = Movement(1, 23, 17, Result.RES_WIN)
    print( chessBoard.move(mv0) )
    print( chessBoard.move(mv1) )
    print( chessBoard )