コード例 #1
0
    def apply(self):
        shared.level['objects'] += self.adjusted

        if self.adjusted_constraints is None:
            adjusted_constraints = copy.deepcopy(
                self.constraints,
                dict((id(obj), adjusted)
                     for obj, adjusted in zip(self.objects, self.adjusted)))
        else:
            adjusted_constraints = self.adjusted_constraints
        shared.level['constraints'] += adjusted_constraints

        set_error('Finished')
        shared.selection = list(
            reversed(
                range(
                    len(get_objects()) - len(self.adjusted),
                    len(get_objects()))))

        shared.joint_selection = list(
            reversed(
                range(
                    len(shared.level['constraints']) -
                    len(adjusted_constraints),
                    len(shared.level['constraints']))))

        insert()
        shared.level_modified = True
コード例 #2
0
def save_to_string(pretty):
    level_copy = copy.deepcopy(shared.level)

    for nConstraint, constraint in zip(level_copy['constraints'],
                                       shared.level['constraints']):
        a, b = constraint['objects']
        try:
            nConstraint['objects'] = [
                shared.get_objects().index(a),
                shared.get_objects().index(b)
            ]
        except ValueError:
            nConstraint['objects'] = None

    level_copy['constraints'] = list(
        filter(lambda constraint: constraint['objects'] is not None,
               level_copy['constraints']))

    if pretty:  # calling it pretty is a bit of a stretch
        data = '{\n'
        if len(level_copy) > 1:
            data += '  ' + ',\n  '.join(
                '"{}": '.format(key) + json.dumps(level_copy[key])
                for key in filter(lambda key: key != 'objects',
                                  level_copy)) + ',\n'
        data += '  "objects": [\n    ' + ',\n    '.join(
            '{\n      ' +
            ',\n      '.join('"' + name + '": ' + json.dumps(obj[name])
                             for name in obj) + '\n    }'
            for obj in level_copy['objects']) + '\n  ]'
        data += '\n}'
    else:
        data = json.dumps(level_copy)
    return data
コード例 #3
0
    def click(self, pos, button):
        if button == pg_locals.BUTTON_RIGHT:
            self.cancel()
            raise StopAction()

        obj = get_object_at(pos)
        if obj is None:
            return

        #n = get_objects().index(obj)
        n = -1
        for i, other in enumerate(get_objects()):
            if other is obj:
                n = i
                break

        if n in shared.selection:
            shared.selection.remove(n)
            for i in shared.joint_selection.copy():
                obj_a, obj_b = shared.level['constraints'][i]['objects']
                if obj is obj_a or obj is obj_b:
                    shared.joint_selection.remove(i)
        else:
            for i, constraint in enumerate(shared.level['constraints']):
                obj_a, obj_b = constraint['objects']
                if (obj is obj_a and any(get_objects()[n] is obj_b for n in shared.selection))\
                or (obj is obj_b and any(get_objects()[n] is obj_a for n in shared.selection)):
                    shared.joint_selection.append(i)
            shared.joint_selection.sort(reverse=True)

            shared.selection.append(n)
            shared.selection.sort(reverse=True)

        set_error('Selecting {} objects'.format(len(shared.selection)))
コード例 #4
0
    def apply(self):
        groups = [[] for _ in range(len(shared.get_objects()))]
        for element in self.list.get_children():
            for member in element.members:
                groups[member].append(element.name)

        for new_groups, obj in zip(groups, shared.get_objects()):
            obj['groups'] = new_groups
        insert()
コード例 #5
0
 def cancel(self):
     if self.objects is not None:
         for i, obj in zip(reversed(self.selection_snapshot),
                           reversed(self.objects)):
             get_objects().insert(i, obj)
         for i, constraint in zip(reversed(self.joint_selection_snapshot),
                                  reversed(self.constraints)):
             shared.level['constraints'].insert(i, constraint)
         insert()
         shared.selection = self.selection_snapshot
         shared.joint_selection = self.joint_selection_snapshot
     set_error('Cancelled')
コード例 #6
0
    def undo(self):
        shared.level['objects'] = shared.level['objects'][:-len(self.objects) *
                                                          2]
        shared.level['constraints'] = shared.level[
            'constraints'][:-len(self.adjusted_constraints) * 2]

        for i, obj in zip(self.selection_snapshot, self.objects):
            get_objects().insert(i, obj)
        for i, constraint in zip(self.joint_selection_snapshot,
                                 self.constraints):
            shared.level['constraints'].insert(i, constraint)

        shared.selection = self.selection_snapshot
        shared.joint_selection = self.joint_selection_snapshot
コード例 #7
0
    def undo(self):
        shared.level['objects'] = get_objects()[:-len(self.adjusted)]
        for i, obj in zip(self.selection_snapshot, self.objects):
            get_objects().insert(i, obj)

        if self.adjusted_constraints is None:
            shared.level['constraints'] = shared.level[
                'constraints'][:-len(self.constraints)]
        else:
            shared.level['constraints'] = shared.level[
                'constraints'][:-len(self.adjusted_constraints)]

        for i, constraint in zip(self.joint_selection_snapshot,
                                 self.constraints):
            shared.level['constraints'].insert(i, constraint)
コード例 #8
0
 def apply(self):
     shared.level['objects'] += self.objects + self.adjusted
     shared.level[
         'constraints'] += self.constraints + self.adjusted_constraints
     shared.selection = list(
         reversed(
             range(
                 len(get_objects()) - len(self.adjusted),
                 len(get_objects()))))
     shared.joint_selection = list(
         reversed(
             range(
                 len(shared.level['constraints']) -
                 len(self.adjusted_constraints),
                 len(shared.level['constraints']))))
コード例 #9
0
 def apply(self):
     assert self.obj is not None
     self.obj = add_default_properties(self.obj)
     add_object(self.obj)
     shared.selection = [len(get_objects()) - 1]
     shared.joint_selection = []
     shared.level_modified = True
コード例 #10
0
    def __init__(self):
        self.selected = None

        frame = tk.Frame(get_inner())
        insert(frame)

        self.list = widgets.ScrolledList(frame, 150, 200)
        self.list.pack()

        tk.Button(frame, text='Apply',
                  command=apply_wrapper(self.apply)).pack(side='left')
        tk.Button(frame, text='Cancel',
                  command=cancel_action).pack(side='left')
        tk.Button(frame, text='Add',
                  command=self.make_group).pack(side='right')

        groups = {}
        for i, obj in enumerate(shared.get_objects()):
            for group in obj['groups']:
                if group not in groups:
                    groups[group] = []
                groups[group].append(i)

        for key, val in groups.items():
            element = Group.GroupElement(self.list, key, self)
            element.members = sorted(val, reverse=True)
            self.list.insert(element)

        self.list.update_scrollbar()
コード例 #11
0
    def __init__(self, ignore_constraints=False):
        if len(shared.selection) == 0:
            set_error('Select some objects to start')
            raise StopAction

        # selection must always be sorted (highest to lowest)
        self.objects = [get_objects()[i] for i in shared.selection][::-1]
        self.adjusted = [copy.deepcopy(obj) for obj in self.objects]

        self.constraints = [
            shared.level['constraints'][i] for i in shared.joint_selection
        ][::-1]

        if ignore_constraints:
            self.adjusted_constraints = None
        else:
            for constraint in shared.level['constraints']:
                obj_a, obj_b = constraint['objects']
                if (obj_a in self.objects) != (obj_b in self.objects):
                    set_error(
                        'Cannot start action: hanging constraints exist in current selection'
                    )
                    raise StopAction

            self.adjusted_constraints = []
            for constraint in self.constraints:
                new_constraint = constraint.copy()
                del new_constraint['objects']
                new_constraint = copy.deepcopy(new_constraint)
                new_constraint['objects'] = [
                    self.adjusted[self.objects.index(obj)]
                    for obj in constraint['objects']
                ]
                self.adjusted_constraints.append(new_constraint)

        for i in shared.selection:
            get_objects().pop(i)
        for i in shared.joint_selection:
            shared.level['constraints'].pop(i)

        self.selection_snapshot = shared.selection.copy()
        self.joint_selection_snapshot = shared.joint_selection.copy()
        shared.selection = []
        shared.joint_selection = []

        set_error('Action started')
コード例 #12
0
    def redo(self):
        for i in self.selection_snapshot:
            get_objects().pop(i)
        shared.level['objects'] += self.adjusted

        for i in self.joint_selection_snapshot:
            shared.level['constraints'].pop(i)

        if self.adjusted_constraints is None:
            adjusted_constraints = copy.deepcopy(
                self.constraints,
                dict((id(obj), adjusted)
                     for obj, adjusted in zip(self.objects, self.adjusted)))
        else:
            adjusted_constraints = self.adjusted_constraints

        shared.level['constraints'] += adjusted_constraints
コード例 #13
0
def load_pressed():
    global current_file
    filename = filedialog.askopenfilename(title='Load Level',
                                          filetypes=(('JSON files', '*.json'),
                                                     ('all files', '*.*')))
    if filename != '':
        shared.level = load_file(filename)
        actions.set_error('Level with ' + str(len(shared.get_objects())) +
                          ' Objects Loaded')
コード例 #14
0
def select(pos):
    global selection
    # Top polygon checked first
    for i, obj in enumerate(shared.get_objects()[::-1]):
        crossings = 0
        for p1, p2 in zip(obj['points'], np.roll(obj['points'], -1, 0)):
            if pos[1] < min(p1[1], p2[1]):
                continue
            if pos[1] > max(p1[1], p2[1]):
                continue
            if p1[1] == p2[1]:
                if pos[1] == p1[1] and pos[0] > min(p1[0], p2[0]):
                    crossings += 1
            elif pos[0] > p1[0] + (pos[1] - p1[1]) * (p2[0] - p1[0]) / (p2[1] -
                                                                        p1[1]):
                crossings += 1
        if crossings % 2 == 1:
            selection = len(shared.get_objects()) - i - 1
            return
コード例 #15
0
    def click(self, pos, button):
        obj = get_object_at(pos)

        if obj is None:
            return

        i = get_objects().index(obj)
        try:
            shared.selection.remove(i)
        except ValueError:
            shared.selection.append(i)
            shared.selection.sort(reverse=True)
コード例 #16
0
    def __init__(self):
        if len(shared.selection) != 2:
            set_error('Select two objects')
            raise StopAction()
        self.objects = [get_objects()[i] for i in shared.selection]
        if all('physics' not in obj for obj in self.objects):
            set_error('At least one object must have physics enabled')
            raise StopAction()

        self.snapPoints = [
            np.array(obj['pos'], dtype=int) for obj in self.objects
            if obj['type'] == 'circle'
        ]
コード例 #17
0
    def apply(self):
        try:
            if int(self.size.get()) < 10:
                set_error('Size too small')
                return
        except ValueError:
            set_error('Invalid size')
            return

        if len(self.content.get()) != 1:
            set_error('Invalid content length')
            return

        super().apply()
        set_error('Text Created')
        shared.selection = [len(get_objects()) - 1]
        insert()
コード例 #18
0
def get_object_at(pos):
    pos = np.array(pos)
    for obj in reversed(get_objects()):  # Top polygon checked first
        if obj['type'] == 'polygon':
            intersects = False
            for p1, p2 in zip(np.array(obj['points']),
                              np.roll(obj['points'], -1, 0)):
                if not (min(p1[1], p2[1]) < pos[1] < max(p1[1], p2[1])):
                    continue

                t = (pos[1] - p1[1]) / (p2[1] - p1[1])
                proj_x = p2[0] * t + p1[0] * (1 - t)

                if proj_x < pos[0]:
                    intersects = not intersects
            if intersects:
                return obj
        elif obj['type'] == 'circle':
            if length2(obj['pos'] - pos) <= obj['radius']**2:
                return obj
        elif obj['type'] == 'text':
            if font.point_in_char(obj['char'], obj['size'], pos - obj['pos']):
                return obj
    return None
コード例 #19
0
 def redo(self):
     for i in self.selection_snapshot:
         del get_objects()[i]
     for i in self.joint_selection_snapshot:
         del shared.level['constraints'][i]
     self.apply()