Ejemplo n.º 1
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=Tkinter.VERTICAL)
        vscrollbar.pack(fill=Tkinter.Y,
                        side=Tkinter.RIGHT,
                        expand=Tkinter.FALSE)

        hscrollbar = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        hscrollbar.pack(fill=Tkinter.X,
                        side=Tkinter.BOTTOM,
                        expand=Tkinter.FALSE)

        canvas = Canvas(self,
                        bd=0,
                        highlightthickness=0,
                        yscrollcommand=vscrollbar.set,
                        xscrollcommand=hscrollbar.set)
        canvas.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=Tkinter.TRUE)
        vscrollbar.config(command=canvas.yview)
        hscrollbar.config(command=canvas.xview)

        # reset the view

        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it

        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0,
                                           0,
                                           window=interior,
                                           anchor=Tkinter.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar

        def _configure_interior(event):
            '''
            update the scrollbars to match the size of the inner frame
            '''
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion='0 0 %s %s' % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            '''
            _configure_canvas is used to resize the window size to fit content.
            Can be used when changing window.
            '''

            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
Ejemplo n.º 2
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self,
                        bd=0,
                        highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)
        self.canv = canvas  # @UndefinedVariable
        self.scroller = vscrollbar

        def _configure_interior(event):
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.config(width=interior.winfo_reqwidth())

        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())

        canvas.bind('<Configure>', _configure_canvas)
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(
            self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)
        self.canv = canvas  # @UndefinedVariable
        self.scroller = vscrollbar

        def _configure_interior(event):
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)
Ejemplo n.º 4
0
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
Ejemplo n.º 6
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event=None):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event=None):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)
Ejemplo n.º 7
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=Tkinter.VERTICAL)
        vscrollbar.pack(fill=Tkinter.Y, side=Tkinter.RIGHT, expand=Tkinter.FALSE)

        hscrollbar = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        hscrollbar.pack(fill=Tkinter.X, side=Tkinter.BOTTOM, expand=Tkinter.FALSE)

        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
        canvas.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=Tkinter.TRUE)
        vscrollbar.config(command=canvas.yview)
        hscrollbar.config(command=canvas.xview)


        # reset the view

        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it

        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=Tkinter.NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar

        def _configure_interior(event):

            '''
            update the scrollbars to match the size of the inner frame
            '''
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion='0 0 %s %s' % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):

            '''
            _configure_canvas is used to resize the window size to fit content.
            Can be used when changing window.
            '''

            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
Ejemplo n.º 8
0
class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    
    """
    def _configure_interior(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.interior.winfo_reqwidth(),
                self.interior.winfo_reqheight())
        self.canvas.config(scrollregion="0 0 %s %s" % size)
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canvas.config(width=self.interior.winfo_reqwidth())
        self.interior.bind('<Configure>', _configure_interior)

    def _configure_canvas(self, event):
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.canvas.itemconfigure(self.interior_id,
                                      width=self.canvas.winfo_width())
        self.canvas.bind('<Configure>', _configure_canvas)
        return

    def configure_scrolling(self):
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient='vertical')
        vscrollbar.grid(row=0, column=1, sticky='nsw')
        self.canvas = Canvas(self,
                             bd=0,
                             highlightthickness=0,
                             yscrollcommand=vscrollbar.set)
        self.canvas.grid(row=0, column=0, sticky='nsew')
        vscrollbar.config(command=self.canvas.yview)

        # reset the view
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(self.canvas)
        self.interior.grid(row=0, column=0, sticky='nsew')
        self.interior_id = self.canvas.create_window(0,
                                                     0,
                                                     window=interior,
                                                     anchor='nw')
Ejemplo n.º 9
0
class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    
    """
    def _configure_interior(self,event):
        # update the scrollbars to match the size of the inner frame
        size = (self.interior.winfo_reqwidth(), self.interior.winfo_reqheight())
        self.canvas.config(scrollregion="0 0 %s %s" % size)
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canvas.config(width=self.interior.winfo_reqwidth())
        self.interior.bind('<Configure>', _configure_interior)

    def _configure_canvas(self,event):
        if self.interior.winfo_reqwidth() != self.canvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.canvas.itemconfigure(self.interior_id, width=self.canvas.winfo_width())
        self.canvas.bind('<Configure>', _configure_canvas)
        return

    def configure_scrolling(self):
        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient='vertical')
        vscrollbar.grid(row=0,column=1,sticky='nsw')
        self.canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        self.canvas.grid(row=0,column=0,sticky='nsew')
        vscrollbar.config(command=self.canvas.yview)

        # reset the view
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(self.canvas)
        self.interior.grid(row=0,column=0,sticky='nsew')
        self.interior_id = self.canvas.create_window(0, 0, window=interior,
                                           anchor='nw')
Ejemplo n.º 10
0
class Map:
    def __init__(self,
                 parent,
                 name=None,
                 width=20,
                 height=20,
                 tileset_id=2,
                 blockdata_filename=None,
                 config=config):
        self.parent = parent

        self.name = name

        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__,
                                                      id(self)))

        self.blockdata_filename = blockdata_filename
        if not self.blockdata_filename and self.name:
            self.blockdata_filename = os.path.join(self.config.map_dir,
                                                   self.name + '.blk')
        elif not self.blockdata_filename:
            self.blockdata_filename = ''

        asm_filename = ''
        if self.name:
            if self.config.asm_dir is not None:
                asm_filename = os.path.join(self.config.asm_dir,
                                            self.name + '.asm')
            elif self.config.asm_path is not None:
                asm_filename = self.config.asm_path

        if os.path.exists(asm_filename):
            for props in [
                    map_header(self.name, config=self.config),
                    second_map_header(self.name, config=self.config)
            ]:
                self.__dict__.update(props)
            self.asm = open(asm_filename, 'r').read()
            self.events = event_header(self.asm, self.name)
            self.scripts = script_header(self.asm, self.name)

            self.tileset_id = eval(self.tileset_id, self.config.constants)

            self.width = eval(self.width, self.config.constants)
            self.height = eval(self.height, self.config.constants)

        else:
            self.width = width
            self.height = height
            self.tileset_id = tileset_id

        if self.blockdata_filename:
            self.blockdata = bytearray(
                open(self.blockdata_filename, 'rb').read())
        else:
            self.blockdata = []

        self.tileset = Tileset(self.tileset_id, config=self.config)

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if not hasattr(self, 'canvas'):
            self.canvas_width = self.width * 32
            self.canvas_height = self.height * 32
            self.canvas = Canvas(parent,
                                 width=self.canvas_width,
                                 height=self.canvas_height)
            self.canvas.xview_moveto(0)
            self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def crop(self, x1, y1, x2, y2):
        blockdata = self.blockdata
        start = y1 * self.width + x1
        width = x2 - x1
        height = y2 - y1
        self.blockdata = []
        for y in xrange(height):
            for x in xrange(width):
                self.blockdata += [blockdata[start + y * self.width + x]]
        self.blockdata = bytearray(self.blockdata)
        self.width = width
        self.height = height

    def draw(self):
        for i in xrange(len(self.blockdata)):
            block_x = i % self.width
            block_y = i / self.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.blockdata[block_y * self.width + block_x]
        for j, tile in enumerate(self.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * 32 + (j % 4) * 8
                tile_y = block_y * 32 + (j / 4) * 8
                self.canvas.create_image(index + tile_x,
                                         indey + tile_y,
                                         image=self.tileset.tiles[tile])
            except:
                pass
Ejemplo n.º 11
0
class TrailUI:
    def __init__(self, parent, trail=None):
        self.parent = parent
        self.trail = trail
        self.alpha_reflection = trail.alpha_reflection
        self.states = []
        self.probabilitylabels = {}
        ## scrollbar
        # create a canvas object and a vertical scrollbar for scrolling it
        self.scrollframe = Frame(parent)
        self.hsb = Scrollbar(self.scrollframe, orient=Tkinter.HORIZONTAL)
        self.hsb.pack(fill=Tkinter.X, side=BOTTOM, expand=Tkinter.FALSE)
        self.scrollcanvas = Canvas(self.scrollframe,
                                   bd=0,
                                   highlightthickness=0,
                                   xscrollcommand=self.hsb.set)
        self.scrollcanvas.pack(side=LEFT, fill=BOTH, expand=Tkinter.TRUE)
        self.hsb.config(command=self.scrollcanvas.xview)

        # reset the view
        self.scrollcanvas.xview_moveto(0)
        self.scrollcanvas.yview_moveto(0)

        # put trailframe into scrollframe and assign configs
        self.trailframe = interior = Frame(self.scrollcanvas)
        self.interior_id = self.scrollcanvas.create_window(10,
                                                           0,
                                                           window=interior,
                                                           anchor=Tkinter.NW)
        interior.bind('<Configure>', self._configure_interior)
        self.scrollcanvas.bind('<Configure>', self._configure_canvas)

        self.scrollframe.pack(fill=Tkinter.X, expand=1)
        self.infoframe = Frame(parent)
        self.infoframe.pack(fill=Tkinter.X, expand=1, side=BOTTOM)
        self.canvas = Canvas(self.infoframe, width=1000, height=200)
        self.canvas.pack()
        self.b = Button(self.infoframe,
                        text='Disable Propagation',
                        command=self.__toggle_prop)
        self.b.pack()
        self.b2 = Button(self.infoframe,
                         text='Make active only',
                         command=self.__activeonly)
        self.b2.pack()
        self.parent.title("ClusterF**k")
        self.enable_propagation = True
        self.trail.updateColorList()
        self.maxgridcol = -1
        self.trail.initUI(self)

        # Multi Cell Selection
        self.multiselection_pressed = False
        self.dynamicselection_pressed = False
        self.selectedcells = []
        self.parent.bind("<Control_L>", self.__selection_start)
        self.parent.bind("<KeyRelease-Control_L>", self.__selection_end)
        self.parent.bind("<Shift_L>", self.__dynamic_selection_start)
        self.parent.bind("<KeyRelease-Shift_L>", self.__dynamic_selection_end)

        self.parent.bind("<Escape>", lambda event: self._clear_selection())
        self.parent.bind("<Return>", lambda event: self.open_cell_dialogue())

    # track changes to the canvas and frame width and sync them,
    # also updating the scrollbar
    # taken from https://gist.github.com/EugeneBakin/76c8f9bcec5b390e45df
    def _configure_interior(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.trailframe.winfo_reqwidth(),
                self.trailframe.winfo_reqheight())
        self.scrollcanvas.config(scrollregion="0 0 %s %s" % size)
        if self.trailframe.winfo_reqwidth() != self.scrollcanvas.winfo_width():
            # update the canvas's width to fit the inner frame
            self.scrollcanvas.config(width=self.trailframe.winfo_reqwidth())

    def _configure_canvas(self, event):
        if self.trailframe.winfo_reqwidth() != self.scrollcanvas.winfo_width():
            # update the inner frame's width to fill the canvas
            self.scrollcanvas.itemconfigure(
                self.trailframe, width=self.scrollcanvas.winfo_width())

    def __selection_start(self, event):
        print "Selection start/continue"
        self.multiselection_pressed = True

    def __dynamic_selection_start(self, event):
        print "Dynamic selection start"
        self.dynamicselection_pressed = True

    def __selection_end(self, event):
        print "Selection end"
        self.multiselection_pressed = False

    def __dynamic_selection_end(self, event):
        print "Dynamic selection end"
        self.dynamicselection_pressed = False

    def open_cell_dialogue(self):
        if len(self.selectedcells) is 0:
            return

        # oldstate = self.__clickedcells[0]["oldstate"]
        # oldstatestr = ",".join(["{:x}".format(x) for x in oldstate])
        oldstatestr = ""

        dialog = StatePopup(
            self, oldstatestr,
            self.selectedcells[0]["state_probs"])  # TODO add probs

        self.trailframe.wait_window(dialog.top)

        newstate = dialog.value
        # set each cell of the selection to the new state
        if newstate is not None:
            for i, cell in enumerate(self.selectedcells):
                cell["stateUI"].state.set(cell["row"], cell["col"],
                                          set(newstate))

        # self._clear_selection()
        self.redraw_all()
        self.redraw_selection()

    def _clear_selection(self):
        for cell in self.selectedcells:
            cell["stateUI"].undraw_selection(cell)

        self.selectedcells = []

    def __toggle_prop(self):
        self.enable_propagation = not self.enable_propagation
        if self.enable_propagation:
            self.b.config(text="Disable Propagation")
            self.redraw_all()
        else:
            self.b.config(text="Enable Propagation")

    def __activeonly(self):
        self.trail.makeActiveOnly()
        self.redraw_all()

    def get_stateui_at(self, row, col):
        # retrieve state from specific grid position
        for state in self.states:
            if state._row is row and state._col is col:
                return state

        return self.get_stateui_at(row, col - 1)

    def redraw_selection(self):
        for cell in self.selectedcells:
            cell["stateUI"].draw_selection(cell)

    def redraw_all(self):
        if self.enable_propagation:
            self.trail.propagate()
            self.trail.getProbability(verbose=True)
        self.redrawColorList()
        self.redraw_states()
        self.redraw_selection()
        if self.enable_propagation:
            self.redraw_probablities()

    def redraw_states(self):
        for state in self.states:
            state.redraw_state()

        if PRINT_PROPS is True:
            for state in self.states:
                state.redraw_propagation()

    def redraw_probablities(self):
        if self.alpha_reflection is True:
            for i, prob in enumerate(self.trail.probabilities):
                overallprob, sboxprob, mixcolprob = prob.getProbability()
                if i < self.trail.rounds:
                    self.probabilitylabels["S" + str(i)].textvar.set(
                        "2^{0:.2f}".format(math.log(sboxprob, 2)))
                    self.probabilitylabels["M" + str(i + 1)].textvar.set(
                        "2^{0:.2f}".format(math.log(mixcolprob, 2)))
                elif i >= self.trail.rounds + 1:
                    self.probabilitylabels["S" + str(i + 2)].textvar.set(
                        "2^{0:.2f}".format(math.log(sboxprob, 2)))
                    self.probabilitylabels["M" + str(i + 1)].textvar.set(
                        "2^{0:.2f}".format(math.log(mixcolprob, 2)))
                else:  # inner round
                    self.probabilitylabels["I"].textvar.set("2^{0:.2f}".format(
                        math.log(overallprob, 2)))
        else:
            for i, prob in enumerate(self.trail.probabilities):
                overallprob, sboxprob, mixcolprob = prob.getProbability()
                self.probabilitylabels["S" + str(i + 1)].textvar.set(
                    "2^{0:.2f}".format(math.log(sboxprob, 2)))
                self.probabilitylabels["M" + str(i + 1)].textvar.set(
                    "2^{0:.2f}".format(math.log(mixcolprob, 2)))

    def redrawColorList(self):
        self.canvas.delete("colorlist")
        self.trail.updateColorList()
        for i, (state, color) in enumerate(self.trail.colorlist.items()):
            statestr = ",".join(["{:x}".format(x) for x in state])
            x = 15 + int(i / 5) * 250
            y = 15 + (i % 5) * 40
            self.canvas.create_rectangle(x,
                                         y,
                                         x + 25,
                                         y + 25,
                                         fill=color,
                                         tags="colorlist")

            textx = x + 40
            texty = y + 12
            self.canvas.create_text(textx,
                                    texty,
                                    text=statestr,
                                    tags="colorlist",
                                    fill="black",
                                    anchor="w")

    def cleanup(self):
        self.infoframe.destroy()
        self.trailframe.destroy()
Ejemplo n.º 12
0
class Map:
    def __init__(self, parent, name=None, width=20, height=20, tileset_id=2, blockdata_filename=None, config=config):
        self.parent = parent

        self.name = name

        self.config = config
        self.log = logging.getLogger("{0}.{1}".format(self.__class__.__name__, id(self)))

        self.blockdata_filename = blockdata_filename
        if not self.blockdata_filename and self.name:
            self.blockdata_filename = os.path.join(self.config.map_dir, self.name + '.blk')
        elif not self.blockdata_filename:
            self.blockdata_filename = ''

        asm_filename = ''
        if self.name:
            if self.config.asm_dir is not None:
                asm_filename = os.path.join(self.config.asm_dir, self.name + '.asm')
            elif self.config.asm_path is not None:
                asm_filename = self.config.asm_path

        if os.path.exists(asm_filename):
            for props in [map_header(self.name, config=self.config), second_map_header(self.name, config=self.config)]:
                self.__dict__.update(props)
            self.asm = open(asm_filename, 'r').read()
            self.events = event_header(self.asm, self.name)
            self.scripts = script_header(self.asm, self.name)

            self.tileset_id = eval(self.tileset_id, self.config.constants)

            self.width = eval(self.width, self.config.constants)
            self.height = eval(self.height, self.config.constants)

        else:
            self.width = width
            self.height = height
            self.tileset_id = tileset_id

        if self.blockdata_filename:
            self.blockdata = bytearray(open(self.blockdata_filename, 'rb').read())
        else:
            self.blockdata = []

        self.tileset = Tileset(self.tileset_id, config=self.config)

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if not hasattr(self, 'canvas'):
            self.canvas_width = self.width * 32
            self.canvas_height = self.height * 32
            self.canvas = Canvas(parent, width=self.canvas_width, height=self.canvas_height)
            self.canvas.xview_moveto(0)
            self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def crop(self, x1, y1, x2, y2):
        blockdata = self.blockdata
        start = y1 * self.width + x1
        width = x2 - x1
        height = y2 - y1
        self.blockdata = []
        for y in xrange(height):
            for x in xrange(width):
                self.blockdata += [blockdata[start + y * self.width + x]]
        self.blockdata = bytearray(self.blockdata)
        self.width = width
        self.height = height

    def draw(self):
        for i in xrange(len(self.blockdata)):
            block_x = i % self.width
            block_y = i / self.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.blockdata[block_y * self.width + block_x]
        for j, tile in enumerate(self.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * 32 + (j % 4) * 8
                tile_y = block_y * 32 + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.tileset.tiles[tile])
            except:
                pass
Ejemplo n.º 13
0
CELLSIZE=float(16)

r=Tk() # создаём окно..
r.title(u'Построитель графиков функций')
f=Frame() # фрейм..
c=Canvas(f,width=WW,height=HH,bg='white',scrollregion=(0,0,W,H)) # поверхность..
sX=Scrollbar(r,orient=HORIZONTAL) # скроллбары
sY=Scrollbar(f,orient=VERTICAL)
c['xscrollcommand']=sX.set
c['yscrollcommand']=sY.set
sX['command']=c.xview
sY['command']=c.yview
c.pack(fill=BOTH,side=LEFT,expand='1')
sY.pack(fill=Y,side=RIGHT)
f.pack(expand='1',fill=BOTH)
c.xview_moveto((W/2.0-WW/2.0)/W)
c.yview_moveto((H/2.0-HH/2.0)/H)
sX.pack(fill=X,side=TOP)
form=StringVar()
f=Frame(r)
Label(f,text='y=').pack(side=LEFT) # текстовое поле..
e=Entry(f,textvar=form)
e.pack(fill=X,side=LEFT,expand='1')
noclear=StringVar()
noclear.set('')
Checkbutton(f,onvalue='1',offvalue='',variable=noclear).pack(side=RIGHT)
f.pack(fill=X)
L=[]

# try:import graphmk_f
# except ImportError:print 'wtf'