Example #1
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.buttons = {}
        self.nodes = {}
        self.edges = {}
        self.active_node = None
        self.active_edge = None
        self.start = None
        self.x = None
        self.y = None
        self.cycles = None
        self.show_cycles_only_mode = False
        self.steps = None
        self.step_index = None

        self.parent.title("Demonstrační aplikace - nalezení elementárních cyklů v orientovaném grafu")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, pad=7)

        self.label = Label(self, text="graf1.graphml")
        self.label.grid(sticky=W, pady=4, padx=5)

        self.canvas = Canvas(self)
        self.canvas.bind('<Double-Button-1>', self.event_add_node)
        self.canvas.bind('<Button-1>', self.event_add_edge_start)
        self.canvas.bind('<B1-Motion>', self.event_add_edge_move)
        self.canvas.bind('<ButtonRelease-1>', self.event_add_edge_end)
        self.canvas.bind('<Button-3>', self.event_move_node_start)
        self.canvas.bind('<B3-Motion>', self.event_move_node)
        self.canvas.pack()
        self.canvas.grid(row=1, column=0, columnspan=2, rowspan=6,
                         padx=5, sticky=E + W + S + N)

        self.buttons['start'] = b = Button(self, text="Start", width=15)
        b.bind('<Button-1>', self.event_start)
        b.grid(row=1, column=3)

        self.buttons['next'] = b = Button(self, text=">>", width=15, state=DISABLED)
        b.bind('<Button-1>', self.event_next_step)
        b.grid(row=2, column=3, pady=4)

        self.buttons['prev'] = b = Button(self, text="<<", width=15, state=DISABLED)
        b.bind('<Button-1>', self.event_prev_step)
        b.grid(row=3, column=3, pady=4)

        b = Checkbutton(self, text="Pouze cykly", command=self.event_change_mode)
        b.grid(row=4, column=3, pady=4)

        self.buttons['reset'] = b = Button(self, text="Reset", width=15)
        b.bind('<Button-1>', self.event_reset)
        b.grid(row=6, column=3)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Načíst", command=self.onLoad)
        fileMenu.add_command(label="Uložit", command=self.onSave)
        fileMenu.add_separator()
        fileMenu.add_command(label="Konec", command=self.onExit)
        menubar.add_cascade(label="Soubor", menu=fileMenu)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="O aplikaci", command=self.onAbout)
        menubar.add_cascade(label="Nápověda", menu=fileMenu)

    def onExit(self):
        self.quit()

    def onLoad(self):
        fileTypes = [('Soubory typu GraphML', '*.graphml')]

        dialog = tkFileDialog.Open(self, filetypes=fileTypes)
        filename = dialog.show()

        if filename != '':
            self.readFile(filename)

    def onSave(self):
        fileTypes = [('GraphML files', '*.graphml')]

        dialog = tkFileDialog.SaveAs(self, filetypes=fileTypes)
        filename = dialog.show()

        if filename != '':
            if not filename.endswith(".graphml"):
                filename += ".graphml"

            self.writeFile(filename)


    def onAbout(self):
        box.showinfo("O aplikaci",
                     "Demonstrace algoritmu nalezení elementárních cyklů v orientovaném grafu podle D. B. Johnsona. \n\n"
                     "Autoři:\n"
                     "Paulík Miroslav\n"
                     "Pavlů Igor\n"
                     "FIT VUT v Brně 2013")


    def readFile(self, filename):
        self.reset()

        try:
            parser = GraphMLParser()
            g = parser.parse(filename)
        except Exception:
            box.showerror("Chyba při zpracování vstupního souboru", "Chybný formát souboru.")
            return

        nodeMap = {}

        try:
            for gnode in g.nodes():
                nodeMap[gnode.id] = self.__add_node(int(gnode['x']), int(gnode['y']))
        except KeyError:
            box.showerror("Chyba při zpracování vstupního souboru", "Uzlum chybi udaje o pozici (atributy x a y).")
            self.reset()
            return

        try:
            for gedge in g.edges():
                start = nodeMap[gedge.node1.id]
                end = nodeMap[gedge.node2.id]
                isCurve = gedge.node1.id == gedge.node2.id
                self.__add_edge(start, end, isCurve)
            self.label.configure(text=os.path.basename(filename))
        except KeyError:
            box.showerror("Chyba při zpracování vstupního souboru",
                          "Soubor obsahuje hrany spojujici neexistujici hrany")
            self.reset()
            return

        self.repaint()

    def writeFile(self, filename):
        g = Graph()

        for i in self.nodes:
            node = self.nodes[i]
            node.name = str(i)
            gnode = g.add_node(i)
            gnode['label'] = i
            gnode['x'] = node.x
            gnode['y'] = node.y

        for i in self.edges:
            edge = self.edges[i]
            edge.name = i

        parser = GraphMLParser()
        parser.write(g, filename)

    def repaint(self):
        for e in self.edges:
            edge = self.edges[e]
            self.canvas.itemconfigure(e, fill=edge.color)
        for v in self.nodes:
            node = self.nodes[v]
            self.canvas.itemconfigure(v, fill=node.color)

    def reset_colors(self):
        for n in self.nodes:
            self.nodes[n].color = "white"
        for e in self.edges:
            self.edges[e].color = "grey"

    def reset(self):
        self.nodes = {}
        self.edges = {}
        self.canvas.delete("all")
        self.buttons['prev'].config(state=DISABLED)
        self.buttons['next'].config(state=DISABLED)

    def run(self):
        x = ElementaryCircuitsDetector(self.nodes, self.edges)
        x.detect_cycles()
        self.cycles = x.cycles
        self.step_index = 0
        self.steps = x.get_all_steps()

        self.algorithm_step_move(0)

        if len(self.steps) > 0:
            self.buttons['prev'].config(state=1)
            self.buttons['next'].config(state=1)

    def event_reset(self, event):
        self.reset()

    def event_prev_step(self, event):
        if str(self.buttons['prev'].cget("state")) != str(DISABLED):
            self.algorithm_step_move(-1)

    def event_next_step(self, event):
        if str(self.buttons['next'].cget("state")) != str(DISABLED):
            self.algorithm_step_move(1)

    def event_start(self, event):
        self.run()

    def event_change_mode(self):
        self.show_cycles_only_mode = not self.show_cycles_only_mode
        self.run()

    def event_add_edge_start(self, event):
        self.x = event.x
        self.y = event.y

    def event_add_edge_move(self, event):
        if self.active_edge is None:
            self.active_edge = self.canvas.create_line(self.x, self.y, event.x, event.y, arrow="last", width=2)
        else:
            x1, y1, x2, y2 = self.canvas.coords(self.active_edge)
            self.canvas.coords(self.active_edge, x1, y1, event.x, event.y)

    def event_add_edge_end(self, event):
        if self.active_edge is None:
            return
        x1, y1, x2, y2 = self.canvas.coords(self.active_edge)
        start = self.__get_node_from_position(x1, y1)
        end = self.__get_node_from_position(x2, y2)
        if start is None or end is None:
            self.canvas.delete(self.active_edge)
        elif start == end:
            self.canvas.delete(self.active_edge)
            edge = Edge(start, start, True)
            points = edge.get_coords()
            self.active_edge = self.canvas.create_line(points, width=2, smooth=True, arrow="last")
            self.canvas.tag_lower(self.active_edge, min(self.nodes.keys()))
            self.edges[self.active_edge] = edge
        else:
            x, y = self.__calculate_edge_end_from_nodes(start, end)
            self.canvas.coords(self.active_edge, start.x, start.y, x, y)
            self.canvas.tag_lower(self.active_edge, min(self.nodes.keys()))
            edge = Edge(start, end)
            self.edges[self.active_edge] = edge
        self.active_edge = None
        self.x = None
        self.y = None

    def event_move_node_start(self, event):
        id = self.__get_id_from_position(event.x, event.y)
        if id is None:
            return
        self.__activate_node(id)
        self.x = event.x
        self.y = event.y

    def event_move_node(self, event):
        id = self.active_node
        if id is None:
            return
        deltax = event.x - self.x
        deltay = event.y - self.y
        self.canvas.move(id, deltax, deltay)
        self.x = event.x
        self.y = event.y
        coord = self.canvas.coords(id)
        self.nodes[self.active_node].x = (coord[2] - coord[0]) / 2 + coord[0]
        self.nodes[self.active_node].y = (coord[3] - coord[1]) / 2 + coord[1]
        self.__repair_edge_starting_in_node(self.nodes[self.active_node])
        self.__repair_edge_ending_in_node(self.nodes[self.active_node])

    def event_add_node(self, event):
        id = self.__get_id_from_position(event.x, event.y, reverse=True)
        if id is None or id not in self.nodes:
            self.__add_node(event.x, event.y)

    def __repair_edge_ending_in_node(self, node):
        list_of_edge_ids = []
        for edge_id in self.edges:
            edge = self.edges[edge_id]
            if edge.end == node:
                list_of_edge_ids.append(edge_id)
        for edge_id in list_of_edge_ids:
            edge = self.edges[edge_id]
            x, y = self.__calculate_edge_end_from_nodes(edge.start, edge.end)
            if edge.is_curve:
                coords = edge.get_coords()
                self.canvas.coords(edge_id, coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0],
                                   coords[2][1], coords[3][0], coords[3][1])
            else:
                self.canvas.coords(edge_id, edge.start.x, edge.start.y, x, y)

    def __repair_edge_starting_in_node(self, node):
        list_of_edge_ids = []
        for edge_id in self.edges:
            edge = self.edges[edge_id]
            if edge.start == node:
                list_of_edge_ids.append(edge_id)
        for edge_id in list_of_edge_ids:
            edge = self.edges[edge_id]
            x, y = self.__calculate_edge_end_from_nodes(edge.start, edge.end)
            if edge.is_curve:
                coords = edge.get_coords()
                self.canvas.coords(edge_id, coords[0][0], coords[0][1], coords[1][0], coords[1][1], coords[2][0],
                                   coords[2][1], coords[3][0], coords[3][1])
            else:
                self.canvas.coords(edge_id, edge.start.x, edge.start.y, x, y)

    def __calculate_edge_end_from_nodes(self, start_node, end_node):
        diffx = end_node.x - start_node.x
        diffy = end_node.y - start_node.y
        distance = math.sqrt(diffx ** 2 + diffy ** 2)
        if distance > 0:
            ratio = NODE_SIZE / 2 / distance
            x = end_node.x - diffx * ratio
            y = end_node.y - diffy * ratio
            return x, y
        return end_node.x, end_node.y

    def __activate_node(self, id):
        self.__deactivate_node()
        if id in self.nodes:
            self.active_node = id

    def __deactivate_node(self):
        self.active_node = None

    def __get_id_from_position(self, x, y, reverse=False):
        overlaping = self.canvas.find_overlapping(x, y, x, y)
        if len(overlaping) > 0:
            if reverse:
                return overlaping[-1]
            else:
                return overlaping[0]
        else:
            return None

    def __get_node_from_position(self, x, y):
        id = self.__get_id_from_position(x, y)
        if id is not None and id in self.nodes:
            return self.nodes[id]
        else:
            return None

    def __add_node(self, x, y):
        node = Node(x, y)
        id = self.canvas.create_oval(node.get_coord(), fill="blue")
        self.nodes[id] = node
        return node

    def __add_edge(self, start, end, is_curve=False):
        edge = Edge(start, end, is_curve)
        if is_curve:
            id = self.canvas.create_line(edge.get_coords(), width=2, smooth=True, arrow="last")
        else:
            id = self.canvas.create_line(start.x, start.y, end.x, end.y, arrow="last", width=2)
        self.edges[id] = edge
        self.canvas.tag_lower(id, min(self.nodes.keys()))
        self.__repair_edge_starting_in_node(start)
        return edge

    def algorithm_step_move(self, move):
        if self.show_cycles_only_mode:  # cycles only
            if (self.step_index + move) < len(self.cycles) and self.step_index + move >= 0:
                self.step_index += move
                self.reset_colors()
                colors = ['green', 'blue', 'red', 'yellow', 'purple', 'brown']
                color_index = self.step_index % len(colors)
                for edge in self.cycles[self.step_index]:
                    edge.color = edge.start.color = edge.end.color = colors[color_index]
                self.repaint()
        else:
            if (self.step_index + move) < len(self.steps) and self.step_index + move >= 0:
                self.step_index += move
                self.reset_colors()
                for i in range(self.step_index + 1):
                    colors = self.steps[i]
                    for id in colors:
                        if id in self.nodes.keys():
                            self.nodes[id].color = colors[id]
                        elif id in self.edges.keys():
                            self.edges[id].color = colors[id]
                self.repaint()
class histogramWidget:
    BACKGROUND = "#222222"
    EDGE_HISTOGRAM_COLOR = "#999999"
    NODE_HISTOGRAM_COLOR = "#555555"
    TOOLTIP_COLOR="#FFFF55"
    
    PADDING = 8
    CENTER_WIDTH = 1
    CENTER_COLOR = "#444444"
    ZERO_GAP = 1
    UPDATE_WIDTH = 9
    UPDATE_COLOR = "#FFFFFF"
    HANDLE_WIDTH = 5
    HANDLE_COLOR = "#FFFFFF"
    HANDLE_LENGTH = (HEIGHT-2*PADDING)
    TICK_COLOR = "#FFFFFF"
    TICK_WIDTH = 10
    TICK_FACTOR = 2
    
    LOG_BASE = 10.0
    
    def __init__(self, parent, x, y, width, height, data, logScale=False, callback=None):
        self.canvas = Canvas(parent,background=histogramWidget.BACKGROUND, highlightbackground=histogramWidget.BACKGROUND,width=width,height=height)
        self.canvas.place(x=x,y=y,width=width,height=height,bordermode="inside")
        
        self.logScale = logScale
        
        self.callback = callback
        
        self.edgeBars = []
        self.nodeBars = []
        
        self.binValues = []
        self.numBins = len(data) - 1
        
        self.currentBin = self.numBins     # start the slider at the highest bin
        
        edgeRange = 0.0
        nodeRange = 0.0
        
        for values in data.itervalues():
            if values[0] > edgeRange:
                edgeRange = values[0]
            if values[1] > nodeRange:
                nodeRange = values[1]
        
        edgeRange = float(edgeRange)    # ensure that it will yield floats when used in calculations...
        nodeRange = float(nodeRange)
        
        if logScale:
            edgeRange = math.log(edgeRange,histogramWidget.LOG_BASE)
            nodeRange = math.log(nodeRange,histogramWidget.LOG_BASE)
        
        # calculate the center line - but don't draw it yet
        self.center_x = histogramWidget.PADDING
        if self.logScale:
            self.center_x += histogramWidget.TICK_WIDTH+histogramWidget.PADDING
        self.center_y = height/2
        self.center_x2 = width-histogramWidget.PADDING
        self.center_y2 = self.center_y + histogramWidget.CENTER_WIDTH
        
        # draw the histograms with background-colored baseline rectangles (these allow tooltips to work on very short bars with little area)
        self.bar_interval = float(self.center_x2 - self.center_x) / (self.numBins+1)
        bar_x = self.center_x
        edge_y2 = self.center_y-histogramWidget.PADDING
        edge_space = edge_y2-histogramWidget.PADDING
        node_y = self.center_y2+histogramWidget.PADDING
        node_space = (height-node_y)-histogramWidget.PADDING
        
        thresholds = sorted(data.iterkeys())
        for threshold in thresholds:
            self.binValues.append(threshold)
            edgeWeight = data[threshold][0]
            nodeWeight = data[threshold][1]
            if logScale:
                if edgeWeight > 0:
                    edgeWeight = math.log(edgeWeight,histogramWidget.LOG_BASE)
                else:
                    edgeWeight = 0
                if nodeWeight > 0:
                    nodeWeight = math.log(nodeWeight,histogramWidget.LOG_BASE)
                else:
                    nodeWeight = 0
            
            bar_x2 = bar_x + self.bar_interval
            
            edge_y = histogramWidget.PADDING + int(edge_space*(1.0-edgeWeight/edgeRange))
            edge = self.canvas.create_rectangle(bar_x,edge_y,bar_x2,edge_y2,fill=histogramWidget.EDGE_HISTOGRAM_COLOR,width=0)
            baseline = self.canvas.create_rectangle(bar_x,edge_y2+histogramWidget.ZERO_GAP,bar_x2,edge_y2+histogramWidget.PADDING,fill=histogramWidget.BACKGROUND,width=0)
            self.canvas.addtag_withtag("Threshold: %f" % threshold,edge)
            self.canvas.addtag_withtag("No. Edges: %i" % data[threshold][0],edge)
            self.canvas.tag_bind(edge,"<Enter>",self.updateToolTip)
            self.canvas.tag_bind(edge,"<Leave>",self.updateToolTip)
            self.edgeBars.append(edge)
            self.canvas.addtag_withtag("Threshold: %f" % threshold,baseline)
            self.canvas.addtag_withtag("No. Edges: %i" % data[threshold][0],baseline)
            self.canvas.tag_bind(baseline,"<Enter>",self.updateToolTip)
            self.canvas.tag_bind(baseline,"<Leave>",self.updateToolTip)
            
            node_y2 = node_y + int(node_space*(nodeWeight/nodeRange))
            node = self.canvas.create_rectangle(bar_x,node_y,bar_x2,node_y2,fill=histogramWidget.NODE_HISTOGRAM_COLOR,width=0)
            baseline = self.canvas.create_rectangle(bar_x,node_y-histogramWidget.PADDING,bar_x2,node_y-histogramWidget.ZERO_GAP,fill=histogramWidget.BACKGROUND,width=0)
            self.canvas.addtag_withtag("Threshold: %f" % threshold,node)
            self.canvas.addtag_withtag("No. Nodes: %i" % data[threshold][1],node)
            self.canvas.tag_bind(node,"<Enter>",self.updateToolTip)
            self.canvas.tag_bind(node,"<Leave>",self.updateToolTip)
            self.nodeBars.append(node)
            self.canvas.addtag_withtag("Threshold: %f" % threshold,baseline)
            self.canvas.addtag_withtag("No. Nodes: %i" % data[threshold][1],baseline)
            self.canvas.tag_bind(baseline,"<Enter>",self.updateToolTip)
            self.canvas.tag_bind(baseline,"<Leave>",self.updateToolTip)
            
            bar_x = bar_x2
        
        # now draw the center line
        self.centerLine = self.canvas.create_rectangle(self.center_x,self.center_y,self.center_x2,self.center_y2,fill=histogramWidget.CENTER_COLOR,width=0)
        
        # draw the tick marks if logarithmic
        if self.logScale:
            tick_x = histogramWidget.PADDING
            tick_x2 = histogramWidget.PADDING+histogramWidget.TICK_WIDTH
            
            start_y = edge_y2
            end_y = histogramWidget.PADDING
            dist = start_y-end_y
            while dist > 1:
                dist /= histogramWidget.TICK_FACTOR
                self.canvas.create_rectangle(tick_x,end_y+dist-1,tick_x2,end_y+dist,fill=histogramWidget.TICK_COLOR,width=0)
            
            start_y = node_y
            end_y = height-histogramWidget.PADDING
            dist = end_y-start_y
            while dist > 1:
                dist /= histogramWidget.TICK_FACTOR
                self.canvas.create_rectangle(tick_x,end_y-dist,tick_x2,end_y-dist+1,fill=histogramWidget.TICK_COLOR,width=0)
        
        # draw the update bar
        bar_x = self.currentBin*self.bar_interval + self.center_x
        bar_x2 = self.center_x2
        bar_y = self.center_y-histogramWidget.UPDATE_WIDTH/2
        bar_y2 = bar_y+histogramWidget.UPDATE_WIDTH
        self.updateBar = self.canvas.create_rectangle(bar_x,bar_y,bar_x2,bar_y2,fill=histogramWidget.UPDATE_COLOR,width=0)
        
        # draw the handle
        handle_x = self.currentBin*self.bar_interval-histogramWidget.HANDLE_WIDTH/2+self.center_x
        handle_x2 = handle_x+histogramWidget.HANDLE_WIDTH
        handle_y = self.center_y-histogramWidget.HANDLE_LENGTH/2
        handle_y2 = handle_y+histogramWidget.HANDLE_LENGTH
        self.handleBar = self.canvas.create_rectangle(handle_x,handle_y,handle_x2,handle_y2,fill=histogramWidget.HANDLE_COLOR,width=0)
        self.canvas.tag_bind(self.handleBar, "<Button-1>",self.adjustHandle)
        self.canvas.tag_bind(self.handleBar, "<B1-Motion>",self.adjustHandle)
        self.canvas.tag_bind(self.handleBar, "<ButtonRelease-1>",self.adjustHandle)
        parent.bind("<Left>",lambda e: self.nudgeHandle(e,-1))
        parent.bind("<Right>",lambda e: self.nudgeHandle(e,1))
        
        # init the tooltip as nothing
        self.toolTipBox = self.canvas.create_rectangle(0,0,0,0,state="hidden",fill=histogramWidget.TOOLTIP_COLOR,width=0)
        self.toolTip = self.canvas.create_text(0,0,state="hidden",anchor="nw")
        self.canvas.bind("<Enter>",self.updateToolTip)
        self.canvas.bind("<Leave>",self.updateToolTip)
    
    def adjustHandle(self, event):
        newBin = int(self.numBins*(event.x-self.center_x)/float(self.center_x2-self.center_x)+0.5)
        if newBin == self.currentBin or newBin < 0 or newBin > self.numBins:
            return
        
        self.canvas.move(self.handleBar,(newBin-self.currentBin)*self.bar_interval,0)
        self.currentBin = newBin
        if self.callback != None:
            self.callback(self.binValues[newBin])
    
    def nudgeHandle(self, event, distance):
        temp = self.currentBin+distance
        if temp < 0 or temp > self.numBins:
            return
        
        self.canvas.move(self.handleBar,distance*self.bar_interval,0)
        self.currentBin += distance
        
        if self.callback != None:
            self.callback(self.binValues[self.currentBin])
    
    def update(self, currentBins):
        currentBar = self.canvas.coords(self.updateBar)
        self.canvas.coords(self.updateBar,currentBins*self.bar_interval+self.center_x,currentBar[1],currentBar[2],currentBar[3])
    
    def updateToolTip(self, event):
        allTags = self.canvas.gettags(self.canvas.find_overlapping(event.x,event.y,event.x+1,event.y+1))
        
        if len(allTags) == 0:
            self.canvas.itemconfig(self.toolTipBox,state="hidden")
            self.canvas.itemconfig(self.toolTip,state="hidden")
            return
        
        outText = ""
        for t in allTags:
            if t == "current":
                continue
            outText += t + "\n"
        
        outText = outText[:-1]  # strip the last return
        
        self.canvas.coords(self.toolTip,event.x+20,event.y)
        self.canvas.itemconfig(self.toolTip,state="normal",text=outText,anchor="nw")
        # correct if our tooltip is off screen
        textBounds = self.canvas.bbox(self.toolTip)
        if textBounds[2] >= WIDTH-2*histogramWidget.PADDING:
            self.canvas.itemconfig(self.toolTip, anchor="ne")
            self.canvas.coords(self.toolTip,event.x-20,event.y)
            if textBounds[3] >= HEIGHT-2*histogramWidget.PADDING:
                self.canvas.itemconfig(self.toolTip, anchor="se")
        elif textBounds[3] >= HEIGHT-2*histogramWidget.PADDING:
            self.canvas.itemconfig(self.toolTip, anchor="sw")
        
        # draw the box behind it
        self.canvas.coords(self.toolTipBox,self.canvas.bbox(self.toolTip))
        self.canvas.itemconfig(self.toolTipBox, state="normal")
Example #3
0
    class Breakout(Tk):
        def __init__(self):
            Tk.__init__(self)
            #self.canvas.delete('all')
            self.geometry('790x600')
            self.resizable(
                0, 0
            )  #set both parameters to false and to check whether window is resizable in x and y directions
            self.func()

            # game screen
        def func(self):

            self.canvas = Canvas(self,
                                 bg='skyblue',
                                 width=990,
                                 height=600,
                                 highlightcolor='green')
            self.canvas.pack(
                expand=1, fill=BOTH
            )  #when it is true and widget expands to fill any space

            # ball
            self._initiate_new_ball()
            #self.level=choice([1])

            # paddle
            self.canvas.create_rectangle(375,
                                         975,
                                         525,
                                         585,
                                         fill='red',
                                         tags='paddle')
            self.bind('<Key>', self._move_paddle)

            # bricks
            self.bricks = {}
            brick_coords = [15, 12, 60, 45]
            for i in range(56):
                self.canvas.create_rectangle(brick_coords,
                                             outline='green',
                                             fill=('yellow'),
                                             tags='brick' + str(i))
                self.bricks['brick' + str(i)] = None
                brick_coords[0] += 55
                brick_coords[2] += 55
                if brick_coords[2] > 790:
                    brick_coords[0] = 15
                    brick_coords[2] = 60
                    brick_coords[1] += 55
                    brick_coords[3] += 55

        def _initiate_new_ball(self):
            if self.canvas.find_withtag('ball'):
                self.canvas.delete('ball')
            self.x = 300
            self.y = 350
            self.angle = 240
            self.speed = 10
            self.level = 0
            self.score = 0

            self.canvas.create_oval(self.x,
                                    self.y,
                                    self.x + 10,
                                    self.y + 10,
                                    fill='orange',
                                    outline='red',
                                    tags='ball')

            self.after(2000, self._move_ball)

        def _move_paddle(self, event):
            if event.keysym == 'Left':
                if self.canvas.coords('paddle')[0] > 0:
                    self.canvas.move('paddle', -20, 0)
            elif event.keysym == 'Right':
                if self.canvas.coords('paddle')[2] < 990:
                    self.canvas.move('paddle', +20, 0)

        #def _move_ball1(self):
        #	call1()
        #self._initiate_new_ball1()

        def _move_ball(self):

            # variables to determine where ball is in relation to other objects
            ball = self.canvas.find_withtag('ball')[0]
            bounds = self.canvas.find_overlapping(0, 0, 790, 600)
            paddle = self.canvas.find_overlapping(
                *self.canvas.coords('paddle'))
            for brick in self.bricks.iterkeys():
                self.bricks[brick] = self.canvas.find_overlapping(
                    *self.canvas.bbox(brick))

            # calculate change in x,y values of ball
            angle = self.angle - 120  # correct for quadrant IV
            increment_x = cos(radians(angle)) * self.speed
            increment_y = sin(radians(angle)) * self.speed
            #self.level += choice([1])
            #score=self.score
            #score=0
            # finite state machine to set ball state

            if ball in bounds:
                self.ball_state = 'moving'
                for brick, hit in self.bricks.iteritems():
                    if ball in hit:
                        self.ball_state = 'hit_brick'
                        delete_brick = brick
                    elif ball in paddle:
                        self.ball_state = 'hit_wall'
                    elif (self.score) // 3 == 56:
                        self.canvas.create_text(
                            WIDTH / 4,
                            HEIGHT / 2.3,
                            text="CONGRATS!! GAME COMPLETED!",
                            font=("Helvetica", 20),
                            fill="orange")

                        self.canvas.create_text(WIDTH / 4,
                                                HEIGHT / 2,
                                                text=(self.score // 3),
                                                font=("Helvetica", 20),
                                                fill="red")
                        self.canvas.create_text(WIDTH / 4,
                                                HEIGHT / 1.7,
                                                text="YOUR SCORE ",
                                                font=("Helvetica", 20),
                                                fill="darkorange")
                        #image()
                        quit_to_exit()

                        call()

            elif ball not in bounds:
                if self.canvas.coords('ball')[1] < 600:
                    self.ball_state = 'hit_wall'
                else:
                    self.ball_state = 'out_of_bounds'

                    #self.level += choice([1])

                    self.canvas.create_text(
                        WIDTH / 2.5,
                        HEIGHT / 2.3,
                        text="GAME OVER !!PLEASE CLOSE THE WINDOW TO RESTART!",
                        tag="cr2",
                        font=("Helvetica", 20),
                        fill="orange")
                    self.canvas.create_text(WIDTH / 4,
                                            HEIGHT / 2,
                                            text="YOUR SCORE IS",
                                            tag="cr1",
                                            font=("Helvetica", 20),
                                            fill="orange")
                    self.canvas.create_text(WIDTH / 4,
                                            HEIGHT / 1.7,
                                            text=(self.score // 3) + 1,
                                            tag="cr",
                                            font=("Helvetica", 20),
                                            fill="red")
                    quit_to_exit()
                    call()

                    self._initiate_new_ball()

                    #self.bind('<key>',self.game_over)
                    #game = Breakout()
                    #game.mainloop()

            # handler for ball state
            if self.ball_state is 'moving':
                self.canvas.move('ball', increment_x, increment_y)
                self.after(35, self._move_ball)
#		        self.level +=choice([1])

            elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall':
                if self.ball_state == 'hit_brick':
                    self.canvas.delete(delete_brick)
                    del self.bricks[delete_brick]
                self.canvas.move('ball', -increment_x, -increment_y)
                #		        self.level += choice([1])
                self.score += choice([1])
                self.angle += choice([135])
                self.canvas.delete("cr")
                self.canvas.delete("cr1")
                self.canvas.delete("cr2")
                #canvas.create_text(WIDTH/4,HEIGHT/5,text="GAME OVER!")
                self._move_ball()
Example #4
0
class Breakout(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.geometry('400x400')
        self.resizable(0, 0)

        # game screen
        self.canvas = Canvas(self, bg='black', width=400, height=400)
        self.canvas.pack(expand=1, fill=BOTH)

        # ball
        self._initiate_new_ball()

        # paddle
        self.canvas.create_rectangle(175,
                                     375,
                                     225,
                                     385,
                                     fill='black',
                                     outline='white',
                                     tags='paddle')
        self.bind('<Key>', self._move_paddle)

        # bricks
        self.bricks = {}
        brick_coords = [5, 5, 35, 15]
        for i in range(39):
            self.canvas.create_rectangle(*brick_coords,
                                         outline='white',
                                         fill=('#{}'.format(
                                             randint(100000, 999999))),
                                         tags='brick' + str(i))
            self.bricks['brick' + str(i)] = None
            brick_coords[0] += 30
            brick_coords[2] += 30
            if brick_coords[2] > 395:
                brick_coords[0] = 5
                brick_coords[2] = 35
                brick_coords[1] += 10
                brick_coords[3] += 10

    def _initiate_new_ball(self):
        if self.canvas.find_withtag('ball'):
            self.canvas.delete('ball')
        self.x = 60
        self.y = 100
        self.angle = 140
        self.speed = 5
        self.canvas.create_oval(self.x,
                                self.y,
                                self.x + 10,
                                self.y + 10,
                                fill='lawn green',
                                outline='white',
                                tags='ball')
        self.after(1000, self._move_ball)

    def _move_paddle(self, event):
        if event.keysym == 'Left':
            if self.canvas.coords('paddle')[0] > 0:
                self.canvas.move('paddle', -10, 0)
        elif event.keysym == 'Right':
            if self.canvas.coords('paddle')[2] < 400:
                self.canvas.move('paddle', +10, 0)

    def _move_ball(self):

        # variables to determine where ball is in relation to other objects
        ball = self.canvas.find_withtag('ball')[0]
        bounds = self.canvas.find_overlapping(0, 0, 400, 400)
        paddle = self.canvas.find_overlapping(*self.canvas.coords('paddle'))
        for brick in self.bricks.iterkeys():
            self.bricks[brick] = self.canvas.find_overlapping(
                *self.canvas.bbox(brick))

        # calculate change in x,y values of ball
        angle = self.angle - 90  # correct for quadrant IV
        increment_x = cos(radians(angle)) * self.speed
        increment_y = sin(radians(angle)) * self.speed

        # finite state machine to set ball state
        if ball in bounds:
            self.ball_state = 'moving'
            for brick, hit in self.bricks.iteritems():
                if ball in hit:
                    self.ball_state = 'hit_brick'
                    delete_brick = brick
                elif ball in paddle:
                    self.ball_state = 'hit_wall'
        elif ball not in bounds:
            if self.canvas.coords('ball')[1] < 400:
                self.ball_state = 'hit_wall'
            else:
                self.ball_state = 'out_of_bounds'
                self._initiate_new_ball()

        # handler for ball state
        if self.ball_state is 'moving':
            self.canvas.move('ball', increment_x, increment_y)
            self.after(15, self._move_ball)
        elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall':
            if self.ball_state == 'hit_brick':
                self.canvas.delete(delete_brick)
                del self.bricks[delete_brick]
            self.canvas.move('ball', -increment_x, -increment_y)
            self.angle += choice([119, 120, 121])
            self._move_ball()
class Breakout(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.geometry('400x400')
        self.resizable(0,0)

        # game screen
        self.canvas = Canvas(self, bg='black', width=400, height=400)
        self.canvas.pack(expand=1, fill=BOTH)

        # ball
        self._initiate_new_ball()

        # paddle
        self.canvas.create_rectangle(175,375,225,385, fill='black',
                                     outline='white', tags='paddle')
        self.bind('<Key>', self._move_paddle)

        # bricks
        self.bricks = {}
        brick_coords = [5,5,35,15]
        for i in range(39):
            self.canvas.create_rectangle(*brick_coords, outline='white',
                                         fill=('#{}'.format(randint(100000,999999))),
                                         tags='brick' + str(i))
            self.bricks['brick' + str(i)] = None
            brick_coords[0] += 30; brick_coords[2] += 30
            if brick_coords[2] > 395:
                brick_coords[0] = 5; brick_coords[2] = 35
                brick_coords[1] += 10; brick_coords[3] += 10

    def _initiate_new_ball(self):
        if self.canvas.find_withtag('ball'):
            self.canvas.delete('ball')
        self.x = 60; self.y = 100
        self.angle = 140; self.speed = 5
        self.canvas.create_oval(self.x,self.y,self.x+10,self.y+10,
                                fill='lawn green', outline='white', tags='ball')
        self.after(1000, self._move_ball)
        
    def _move_paddle(self, event):
        if event.keysym == 'Left':
            if self.canvas.coords('paddle')[0] > 0:
                self.canvas.move('paddle', -10, 0)
        elif event.keysym == 'Right':
            if self.canvas.coords('paddle')[2] < 400:
                self.canvas.move('paddle', +10, 0)

    def _move_ball(self):

        # variables to determine where ball is in relation to other objects
        ball = self.canvas.find_withtag('ball')[0]
        bounds = self.canvas.find_overlapping(0,0,400,400)
        paddle = self.canvas.find_overlapping(*self.canvas.coords('paddle'))
        for brick in self.bricks.iterkeys():
            self.bricks[brick] = self.canvas.find_overlapping(*self.canvas.bbox(brick))

        # calculate change in x,y values of ball
        angle = self.angle - 90 # correct for quadrant IV
        increment_x = cos(radians(angle)) * self.speed
        increment_y = sin(radians(angle)) * self.speed

        # finite state machine to set ball state
        if ball in bounds:
            self.ball_state = 'moving'
            for brick, hit in self.bricks.iteritems():
                if ball in hit:
                    self.ball_state = 'hit_brick'
                    delete_brick = brick
                elif ball in paddle:
                    self.ball_state = 'hit_wall'
        elif ball not in bounds:
            if self.canvas.coords('ball')[1] < 400:
                self.ball_state = 'hit_wall'
            else:
                self.ball_state = 'out_of_bounds'
                self._initiate_new_ball()

        # handler for ball state
        if self.ball_state is 'moving':
            self.canvas.move('ball', increment_x, increment_y)
            self.after(15, self._move_ball)
        elif self.ball_state is 'hit_brick' or self.ball_state is 'hit_wall':
            if self.ball_state == 'hit_brick':
                self.canvas.delete(delete_brick)
                del self.bricks[delete_brick]
            self.canvas.move('ball', -increment_x, -increment_y)
            self.angle += choice([119, 120, 121])
            self._move_ball()
Example #6
0
class MazePlannerCanvas(Frame):
    """
    MazePlannerCanvas contains the main frontend workhorse functionality of the entire
    application.
    it allows the user to graphically place nodes and define the edges between them
    """
    def __init__(self, parent, status=None, manager=DataStore()):
        """
        Construct an instance of the MazePlannerCanvas

        :param parent:              The parent widget that the mazePlannerCanvas will sit in
        :param status:              The statusbar that will receive mouse updates
        :type manager: DataStore
        :return:
        """
        Frame.__init__(self, parent)
        self._manager = manager
        self._canvas = Canvas(self, bg="grey", cursor="tcross")
        self._canvas.pack(fill=BOTH, expand=1)
        self._commands = {
            (ControlSpecifier.DRAG_NODE,    ExecutionStage.START)       : self._begin_node_drag,
            (ControlSpecifier.CREATE_EDGE,  ExecutionStage.START)       : self._begin_edge,
            (ControlSpecifier.DRAG_NODE,    ExecutionStage.END)         : self._end_node_drag,
            (ControlSpecifier.CREATE_EDGE,  ExecutionStage.END)         : self._end_edge,
            (ControlSpecifier.DRAG_NODE,    ExecutionStage.EXECUTE)     : self._execute_drag,
            (ControlSpecifier.CREATE_EDGE,  ExecutionStage.EXECUTE)     : self._execute_edge,
            (ControlSpecifier.MENU,         ExecutionStage.EXECUTE)     : self._launch_menu,
            (ControlSpecifier.CREATE_NODE,  ExecutionStage.EXECUTE)     : self.create_new_node,
        }
        self._commands = load_controls(self._commands)
        self._edge_cache = \
            {
                "x_start"       : None,
                "y_start"       : None,
                "x_end"         : None,
                "y_end"         : None,
                "item_start"    : None,
                "item_end"      : None,
                "edge"          : None
            }
        self._command_cache = None
        self._cache = \
            {
                "item"  : None,
                "x"     : 0,
                "y"     : 0,
                "event" : None
            }
        self._status = status
        self._edge_bindings = {}
        self._node_listing = {}
        self._object_listing = {}
        self._curr_start = None
        self._construct(parent)

    def _construct(self, parent):
        """
        Construct all of the event bindings and callbacks for mouse events
        """
        self._canvas.focus_set()
        self._canvas.bind("<B1-Motion>", lambda event, m_event=Input_Event.DRAG_M1: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<B2-Motion>", lambda event, m_event=Input_Event.DRAG_M2: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<B3-Motion>", lambda event, m_event=Input_Event.DRAG_M3: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonPress-2>", lambda event, m_event=Input_Event.CLICK_M2: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonRelease-2>", lambda event, m_event=Input_Event.RELEASE_M2: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonPress-1>", lambda event, m_event=Input_Event.CLICK_M1: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonPress-3>", lambda event, m_event=Input_Event.CLICK_M3: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonRelease-1>", lambda event, m_event=Input_Event.RELEASE_M1: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<ButtonRelease-3>", lambda event, m_event=Input_Event.RELEASE_M3: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<Return>", lambda event, m_event=Input_Event.RETURN: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<Double-Button-1>", lambda event, m_event=Input_Event.D_CLICK_M1: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<Double-Button-2>", lambda event, m_event=Input_Event.D_CLICK_M2: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<Double-Button-3>", lambda event, m_event=Input_Event.D_CLICK_M3: self._handle_mouse_events(m_event, event))
        self._canvas.bind("<Motion>", lambda event, m_event=None : self._handle_mot(m_event, event))
        self._canvas.bind("<Enter>", lambda event: self._canvas.focus_set())
        self._canvas.bind("<space>", lambda event, m_event=Input_Event.SPACE: self._handle_mouse_events(m_event, event))

    def _handle_mot(self, m_event, event):
        """
        Callback function to handle movement of the mouse

        Function updates the mouse location status bar as well as setting cache values to the current location
        of the mouse

        :m_event:           The specifier for the type of event that has been generated
        :event:             The tk provided event object
        """
        event.x = int(self._canvas.canvasx(event.x))
        event.y = int(self._canvas.canvasy(event.y))
        self._status.set_text("Mouse X:" + str(event.x) + "\tMouse Y:" + str(event.y))
        item = self._get_current_item((event.x, event.y))
        if self._is_node(item):
            Debug.printi("Node: " + str(item), Debug.Level.INFO)
        if self._is_edge(item):
            d_x = self._edge_bindings[item].x_start - self._edge_bindings[item].x_end
            d_y = self._edge_bindings[item].y_start - self._edge_bindings[item].y_end
            square = (d_x * d_x) + (d_y * d_y)
            distance = int(math.sqrt(square))
            Debug.printi("Edge: " + str(item) + " | Source: "
                         + str(self._edge_bindings[item].item_start) + " | Target: "
                         + str(self._edge_bindings[item].item_end) + " | Length: "
                         + str(distance))
        self._cache["x"] = event.x
        self._cache["y"] = event.y

    def _handle_mouse_events(self, m_event, event):
        """
        Function that routes mouse events to the appropriate handlers

        Prints logging and UI information about the state of the mouse and then routes
        the mouse event to the appropriate handler

        :m_event:           The specifier for the tupe of event that has been generated
        :event:             The tk provided event object
        """
        event.x = int(self._canvas.canvasx(event.x))
        event.y = int(self._canvas.canvasy(event.y))
        self._status.set_text("Mouse X:" + str(self._cache["x"]) + "\tMouse Y:" + str(self._cache["y"]))
        Debug.printet(event, m_event, Debug.Level.INFO)
        self._cache["event"] = event
        try:
            self._commands[m_event]((event.x, event.y))
        except KeyError:
            Debug.printi("Warning, no control mapped to " + m_event, Debug.Level.ERROR)
        self._command_cache = m_event


    def _begin_node_drag(self, coords):
        """
        Handles starting operations for dragging a node

        Updates the cache information regarding a node drag event, we will used this cache value
        as the handle on which node to update the information for

        :coords:            The mouse coordinates associated with this event
        """
        # Determine which node has been selected, cache this information
        item = self._get_current_item(coords)
        if item in self._node_listing:
            self._update_cache(item, coords)

    def _end_node_drag(self, coords):
        """
        Performs actions to complete a node drag operation

        Validates node location, and other associated object information and updates the cache
        when a node drag is completed

        :coords:            The coordinates associated with this event
        """
        if self._cache["item"] is None:
            return

        # Obtain the final points
        x = coords[0]
        y = coords[1]
        item = self._cache["item"]
        self._validate_node_position(coords)

        container = self._manager.request(DataStore.DATATYPE.NODE, item)
        container.x_coordinate = x
        container.y_coordinate = y
        self._manager.inform(DataStore.EVENT.NODE_EDIT, container.empty_container(), self._cache["item"])
        Debug.printi("Node " + str(self._cache["item"]) + " has been moved", Debug.Level.INFO)
        # Clean the cache
        self._clear_cache(coords)

    def _validate_node_position(self, coords):
        """
        if x < 0:
            x = 0
        if y < 0:
            y = 0
        if x > self._canvas.winfo_width():
            x = self._canvas.winfo_width()-25
        if y > self._canvas.winfo_height():
            y = self._canvas.winfo_height()-25
        self._canvas.move(item, x, y)
        """
        pass

    def _execute_drag(self, coords):
        """
        Updates object position on canvas when user is dragging a node

        :param coords:          The coordinates associated with this event
        """
        # Abort drag if the item is not a node
        if self._cache["item"] not in self._node_listing:
            return
        # Update the drawing information
        delta_x = coords[0] - self._cache["x"]
        delta_y = coords[1] - self._cache["y"]

        # move the object the appropriate amount as long as the drag event has not been done on the empty canvas
        if not self._cache["item"] is None:
            self._canvas.move(self._cache["item"], delta_x, delta_y)

        # record the new position
        self._cache["x"] = coords[0]
        self._cache["y"] = coords[1]

        self._update_attached_edges(self._cache["item"], coords)
        self._update_attached_objects(self._cache["item"], coords)

    def _update_attached_objects(self, item, coords):
        if item not in self._object_listing:
            return
        container = self._manager.request(DataStore.DATATYPE.OBJECT, item)
        container.x_coordinate = coords[0]
        container.y_coordinate = coords[1]
        self._manager.inform(DataStore.EVENT.OBJECT_EDIT, container.empty_container(), item)

    def _update_attached_edges(self, node, coords):
        """
        Updates all associated edges related to a node drag event

        :param node:            The node that has been dragged
        :param coords:          The mouse coordinates which are the new coordinates of the node
        """
        # Go through dictionary and gather list of all attached edge bindings for a node
        start_bindings = []
        for key, binding in self._edge_bindings.iteritems():
            if binding.item_start == node:
                start_bindings.append(binding)

        end_bindings = []
        for key, binding in self._edge_bindings.iteritems():
            if binding.item_end == node:
                end_bindings.append(binding)

        #  Adjust the bindings with this node as the starting edge
        for binding in start_bindings:
            self._canvas.delete(binding.edge)
            del self._edge_bindings[binding.edge]
            old_edge = binding.edge
            binding.edge = self._canvas.create_line(coords[0], coords[1], binding.x_end,
                                                    binding.y_end, tags="edge", activefill="RoyalBlue1", tag="edge")
            self._edge_bindings[binding.edge] = binding
            self._manager.update_key(DataStore.EVENT.EDGE_EDIT, binding.edge, old_edge)
            binding.x_start = coords[0]
            binding.y_start = coords[1]

        # Adjust the bindings with this node as the ending edge
        for binding in end_bindings:
            self._canvas.delete(binding.edge)
            del self._edge_bindings[binding.edge]
            old_edge = binding.edge
            binding.edge = self._canvas.create_line(binding.x_start, binding.y_start,
                                                    coords[0], coords[1], tags="edge", activefill="RoyalBlue1", tag="edge")
            self._edge_bindings[binding.edge] = binding
            self._manager.update_key(DataStore.EVENT.EDGE_EDIT, binding.edge, old_edge)
            binding.x_end = coords[0]
            binding.y_end = coords[1]

        # Remember to adjust all of the edges so that they sit under the node images
        self._canvas.tag_lower("edge")

    def _launch_menu(self, coords):
        """
        Callback function in response to the pressing of the Return key

        Launches a context menu based on the location of the mouse
        :param coords:
        :return:
        """
        # Configure the "static" menu entries -- they can't be static without seriously destroying readability
        # due to the Python version that is being used -.- so now it has to be not optimal until I find a better
        # solution
        p_menu = Menu(self._canvas)
        item = self._get_current_item((self._cache["x"], self._cache["y"]))
        updated_coords = self._canvas_to_screen((self._cache["x"], self._cache["y"]))
        if item is None:
            # No node is currently selected, create the general menu
            p_menu.add_command(label="Place Room", command=lambda: self.create_new_node((self._cache["x"], self._cache["y"])))
            p_menu.add_command(label="Delete All", command=lambda: self.delete_all())
            p_menu.tk_popup(updated_coords[0], updated_coords[1])
            return

        if self._is_node(item):
            # Create the node specific menu
            p_menu.add_command(label="Place Object", command=lambda: self._mark_object((self._cache["x"], self._cache["y"])))
            p_menu.add_command(label="Edit Room", command=lambda: self._selection_operation((self._cache["x"], self._cache["y"])))
            p_menu.add_command(label="Delete Room", command=lambda: self.delete_node(self._get_current_item((self._cache["x"], self._cache["y"]))))
            p_menu.add_command(label="Mark as start", command=lambda: self._mark_start_node(self._get_current_item((self._cache["x"], self._cache["y"]))))

            if self._is_object(item):
                # Launch the node menu as well as an an added option for selecting stuff to edit an object
                p_menu.add_command(label="Edit Object", command=lambda: self._edit_object(coords))
                p_menu.add_command(label="Delete Object", command=lambda: self._delete_object(self._get_current_item((self._cache["x"], self._cache["y"]))))
                p_menu.delete(0)
            p_menu.tk_popup(updated_coords[0], updated_coords[1])
            return

        if self._is_edge(item):
            p_menu.add_command(label="Edit Corridor", command=lambda: self._selection_operation((self._cache["x"], self._cache["y"])))
            p_menu.add_command(label="Delete Corridor", command=lambda: self.delete_edge(self._get_current_item((self._cache["x"], self._cache["y"]))))
            p_menu.tk_popup(updated_coords[0], updated_coords[1])
            return

        self._clear_cache(coords)

    def _edit_object(self, coords):

        """
        Awkward moment when you find a threading related bug in the Tkinter library, caused by some
        Tcl issue or something like that.
        The below line must be left commented out otherwise the window_wait call in the dialog will crash
        out with a Tcl ponter based issue :/
        item = self._get_current_item((self._cache["x"], self._cache["y"]))
        This means that we can only use the mouse to edit objects
        """

        item = self._get_current_item(coords)

        if item not in self._object_listing:
            Debug.printi("Not a valid object to edit", Debug.Level.ERROR)
            return
        obj = ObjectDialog(self, coords[0] + 10, coords[1] + 10, populator=self._manager.request(DataStore.DATATYPE.OBJECT, item))
        Debug.printi("Editing object " + str(item), Debug.Level.INFO)
        self._manager.inform(DataStore.EVENT.OBJECT_EDIT, obj._entries, item)
        Debug.printi("Editing object " + str(item), Debug.Level.INFO)

    def _delete_object(self, item):
        if item not in self._object_listing:
            Debug.printi("Object does not exist to delete", Debug.Level.ERROR)
            return
        del self._object_listing[item]
        self._manager.inform(DataStore.EVENT.OBJECT_DELETE, data_id=item)
        self._canvas.itemconfig(item, outline="red", fill="black", activeoutline="black", activefill="red")

    def _mark_object(self, coords, prog=False, data=None):
        """
        Mark a node as containing an object
        :param coords:
        :return:
        """
        # Retrieve the item
        item = self._get_current_item(coords)

        if not prog:
            if item not in self._node_listing:
                Debug.printi("Invalid object placement selection", Debug.Level.ERROR)
                return

            if item in self._object_listing:
                Debug.printi("This room already has an object in it", Debug.Level.ERROR)
                return
            # Retrieve its coordinates
            # Launch the object maker dialog
            obj = ObjectDialog(self, coords[0] + 10, coords[1] + 10, populator=Containers.ObjectContainer(key_val={
                "x_coordinate"  :   coords[0],
                "y_coordinate"  :   coords[1],
                "name"          :   "Object_"+str(item),
                "mesh"          :   None,
                "scale"         :   None
            }))
            entries = obj._entries
        else:
            entries = {
                "x_coordinate": coords[0],
                "y_coordinate": coords[1],
                "name": data["name"],
                "mesh": data["mesh"],
                "scale": data["scale"]
            }
        # Save informatoin to the manager
        self._manager.inform(DataStore.EVENT.OBJECT_CREATE, entries, item)
        self._object_listing[item] = item
        self._canvas.itemconfig(item, fill="blue")
        Debug.printi("Object created in room " + str(item), Debug.Level.INFO)

    def _valid_edge_cache(self):
        """
        Return true if the edge cache contains a valid edge descriptor

        A valid edge descriptor is when the edge has a valid starting node, if the
        edge does not contain a valid starting node, this means that the edge was not
        created in the proper manner and should thus be ignored by any edge operations
        """
        valid = not self._edge_cache["item_start"] == (None,)
        return valid

    def _canvas_to_screen(self, coords):
        """
        Convert canvas coordinates into screen coordinates

        :param coords:              The current canvas coordinates
        :return:
        """
        """
        # upper left corner of the visible region
        x0 = self._canvas.winfo_rootx()
        y0 = self._canvas.winfo_rooty()

        # given a canvas coordinate cx/cy, convert it to window coordinates:
        wx0 = x0 + coords[0]
        wy0 = y0 + coords[1]


        # upper left corner of the visible region

        x0 = self._canvas.canvasx(0)
        y0 = self._canvas.canvasy(0)

        # given a canvas coordinate cx/cy, convert it to window coordinates:
        wx0 = coords[0] - x0
        wy0 = coords[1] - y0
        #"""
        return (self._cache["event"].x_root, self._cache["event"].y_root)

    def _begin_edge(self, coords):
        """
        Begin recording information regarding the placement of an edge

        :param coords:               The coordinates associated with this event
        """
        # Record the starting node
        self._edge_cache["item_start"] = self._get_current_item((self._cache["x"], self._cache["y"]))

        # Abort the operation if the item was not a valid node to be selecting
        if self._edge_cache["item_start"] is None or self._edge_cache["item_start"] not in self._node_listing:
            self._clear_edge_cache()
            return

        self._edge_cache["x_start"] = self._cache["x"]
        self._edge_cache["y_start"] = self._cache["y"]

    def _end_edge(self, coords, prog=False, data=None):
        """
        Perform the operations required to complete an edge creation operation
        :param coords:
        :return:
        """
        # Check if the cursor is over a node, if so continue, else abort
        curr = self._get_current_item((coords[0], coords[1]))
        if not prog:
            if curr is None or not self._valid_edge_cache() or curr not in self._node_listing:
                # Abort the edge creation process
                self._canvas.delete(self._edge_cache["edge"])
                self._clear_edge_cache()
                return

            # Check if this edge already exists in the program
            if self._check_duplicate_edges(self._edge_cache["item_start"], curr):
                self.delete_edge(self._edge_cache["edge"])
                Debug.printi("Multiple edges between rooms not permitted", Debug.Level.ERROR)
                return

            #Ensure that edges arent made between the same room
            if curr == self._edge_cache["item_start"]:
                Debug.printi("Cannot allow paths starting and ending in the same room", Debug.Level.ERROR)
                return

        self._canvas.tag_lower("edge")
        self._edge_cache["item_end"] = curr

        # Note that we use the edge ID as the key
        self._edge_bindings[self._edge_cache["edge"]] = EdgeBind(self._edge_cache)
        self._edge_bindings[self._edge_cache["edge"]].x_end = coords[0]
        self._edge_bindings[self._edge_cache["edge"]].y_end = coords[1]
        # Inform the manager
        if not prog:
            self._manager.inform(
                DataStore.EVENT.EDGE_CREATE,
                    {
                        "source"    :   self._edge_cache["item_start"],
                        "target"    :   self._edge_cache["item_end"],
                        "height"    :   None,
                        "wall1"     :   {
                            "height":Defaults.Edge.WALL_HEIGHT,
                            "textures":{
                                Defaults.Wall.PATH: {
                                    "path":Defaults.Wall.PATH,
                                    "tile_x":Defaults.Wall.TILE_X,
                                    "tile_y":Defaults.Wall.TILE_Y,
                                    "height":None
                                }
                            }
                        } if Defaults.Config.EASY_MAZE else None,
                        "wall2"     : {
                            "height": Defaults.Edge.WALL_HEIGHT,
                            "textures": {
                                Defaults.Wall.PATH: {
                                    "path": Defaults.Wall.PATH,
                                    "tile_x": Defaults.Wall.TILE_X,
                                    "tile_y": Defaults.Wall.TILE_Y,
                                    "height":None
                                }
                            }
                        }
                    } if Defaults.Config.EASY_MAZE else None,
                self._edge_cache["edge"])
        else:
            # We are programmatically adding the edges in
            self._manager.inform(
                DataStore.EVENT.EDGE_CREATE,
                {
                    "source": self._edge_cache["item_start"],
                    "target": self._edge_cache["item_end"],
                    "height": None,
                    "wall1": data["wall1"],
                    "wall2": data["wall2"]
                },
                self._edge_cache["edge"])

        Debug.printi("Edge created between rooms "
                     + str(self._edge_cache["item_start"])
                     + " and "
                     + str(self._edge_cache["item_end"])
                     , Debug.Level.INFO)
        self._clear_edge_cache()
        self._clear_cache(coords)

    def _check_duplicate_edges(self, start_node, end_node):
        for binding in self._edge_bindings.itervalues():
            if ( start_node == binding.item_start and end_node == binding.item_end )\
            or ( start_node == binding.item_end and end_node == binding.item_start):
                return True
        return False

    def _execute_edge(self, coords):
        """
        Perform the operations that occur during the motion of an edge drag

        :param coords:
        :return:
        """
        # Update the line position
        # We will update the line position by deleting and redrawing
        if not self._valid_edge_cache():
            return

        self._canvas.delete(self._edge_cache["edge"])
        self._edge_cache["edge"] = self._canvas.create_line( \
            self._edge_cache["x_start"], self._edge_cache["y_start"],
            coords[0]-1, coords[1]-1, tags="edge", activefill="RoyalBlue1", tag="edge")
        d_x = self._edge_cache["x_start"] - coords[0]
        d_y = self._edge_cache["y_start"] - coords[1]
        square = (d_x * d_x) + (d_y * d_y)
        distance = math.sqrt(square)
        Debug.printi("Current corridor distance: " + str(int(distance)))

    def _update_cache(self, item, coords):
        """
        Update the local cache with the item id and coordinates of the mouse

        :param item:                The item with which to update the cache
        :param coords:              The current event coordinates
        """
        self._cache["item"] = item
        self._cache["x"] = coords[0]
        self._cache["y"] = coords[1]

    def _clear_cache(self, coords):
        """
        Clear the cache

        Set the cache values to the current mouse position and None the item
        :param coords:              The coordinates of the mouse at that event time
        """
        self._cache["item"] = None
        self._cache["x"] = coords[0]
        self._cache["y"] = coords[1]

    def _clear_edge_cache(self):
        """
        Clear the edge cache to None for all values
        :return:
        """
        self._edge_cache["x_start"]       = None,
        self._edge_cache["y_start"]       = None,
        self._edge_cache["x_end"]         = None,
        self._edge_cache["y_end"]         = None,
        self._edge_cache["item_start"]    = None,
        self._edge_cache["item_end"]      = None,
        self._edge_cache["edge"]          = None


    def _get_current_item(self, coords):
        """
        Return the item(if any) that the mouse is currently over
        :param coords:                  The current coordinates of the mouse
        :return:
        """
        item = self._canvas.find_overlapping(coords[0]-1, coords[1]-1, coords[0]+1, coords[1]+1)

        if item is ():
            return None

        # Hacky solution
        # Return the first node that we come across, since they seem to be returned by tkinter
        # in reverse order to their visual positioning, we'll go through the list backwards
        for val in item[::-1]:
            if val in self._node_listing:
                return val

        # Else, just return the first item and be done with it
        return item[0]

    def _is_node(self, obj):
        """
        Returns true if the supplied object is a node
        :param obj:             The object id to id
        :return:
        """
        return obj in self._node_listing

    def _is_edge(self, obj):
        """
        Returns true if the supplied object is an edge

        :param obj:             The object id to id
        :return:
        """
        return obj in self._edge_bindings

    def _is_object(self, obj):
        """
        Returns true if the supplied object is an object

        :param obj:             The object id to id
        :return:
        """
        return obj in self._object_listing

    def _get_obj_type(self, obj):
        """
        Returns the Object type of the supplied object

        :param obj:             The object to identify
        :return:
        """
        if self._is_node(obj):
            return EditableObject.NODE
        if self._is_edge(obj):
            return EditableObject.EDGE
        if self._is_object(obj):
            return EditableObject.OBJECT
        return None

    def _selection_operation(self, coords):
        """
        Contextually create or edit a node
        :param coords:
        :return:
        """
        # Determine the item ID
        item = self._get_current_item(coords)
        self._cache["item"] = item
        true_coords = self._canvas_to_screen((self._cache["x"], self._cache["y"]))

        if self._is_node(item):
            Debug.printi("Node Selected : " + str(item) + " | Launching Editor", Debug.Level.INFO)
            # Make request from object manager using the tag assigned
            populator = self._manager.request(DataStore.DATATYPE.NODE, item)
            updated_node = NodeDialog(self, true_coords[0] + 10, true_coords[1] + 10, populator=populator)
            # post information to object manager, or let the dialog handle it, or whatever
            self._manager.inform(DataStore.EVENT.NODE_EDIT, updated_node._entries, item)
            return

        if self._is_edge(item):
            Debug.printi("Edge Selected : " + str(item) + " | Launching Editor", Debug.Level.INFO)
            # Make a request from the object manager to populate the dialog
            populator = self._manager.request(DataStore.DATATYPE.EDGE, item)
            updated_edge = EdgeDialog(self, true_coords[0] + 10, true_coords[1] + 10, populator=populator)
            # Make sure that information is posted to the object manager
            self._manager.inform(DataStore.EVENT.EDGE_EDIT, updated_edge._entries, item)

            return

        if self._is_object(item):
            self._edit_object(coords)
            return

    def create_new_node(self, coords, prog = False, data=None):
        """
        Creates a new node on the Canvas and adds it to the datastore
        :param coords:
        :return:
        """
        # Create the node on Canvas
        self._cache["item"] = self._canvas.create_rectangle(coords[0], coords[1], coords[0]+25, coords[1]+25,
                                                            outline="red", fill="black", activeoutline="black", activefill="red", tag="node")

        self._node_listing[self._cache["item"]] = self._cache["item"]
        if not prog:
            if not Defaults.Config.EASY_MAZE:

                true_coords = self._canvas_to_screen((self._cache["x"], self._cache["y"]))
                new_node = NodeDialog(self, true_coords[0] + 25, true_coords[1] + 25,
                                      populator=Containers.NodeContainer(
                                          {
                                              "node_id": self._cache["item"],
                                              "x_coordinate": self._cache["x"],
                                              "y_coordinate": self._cache["y"],
                                              "room_texture": None,
                                              "wall_pictures": None
                                          }))
                entries = new_node._entries
            else:
                entries = {
                    "node_id": self._cache["item"],
                    "x_coordinate": self._cache["x"],
                    "y_coordinate": self._cache["y"],
                    "room_texture": Defaults.Node.ROOM_TEXTURE,
                    "wall_pictures": None
                }
        else:
            pics = data[1]
            data = data[0]
            entries = {
                "node_id": data["id"],
                "x_coordinate": data["x"],
                "y_coordinate": data["y"],
                "room_texture": data["texture"],
                "wall_pictures": pics
            }
        # Inform the datastore
        self._manager.inform(DataStore.EVENT.NODE_CREATE, entries, self._cache["item"])
        self._clear_cache(coords)

    def delete_all(self):
        """
        Delete all nodes and associated edges and objects from the canvas
        """
        # Iterate over each node in the node listing and delete it using delete node
        for key in self._node_listing.keys():
            self.delete_node(key)

        # Delete any rouge edge bindings that may exist
        for binding in self._edge_bindings:
            self.delete_edge(binding)

        self._object_listing.clear()

        # Delete any naughty objects that are left
        self._canvas.delete("all")
        self._manager.inform(DataStore.EVENT.DELETE_ALL)

    def delete_node(self, node_id):
        """
        Delete a node and all its associated edges and object from the canvas

        :param node_id:             The tkinter id of the node to be deleted
        """
        # Delete from our internal representations
        if node_id not in self._node_listing:
            return

        del self._node_listing[node_id]
        # Delete from the canvas
        self._canvas.delete(node_id)

        # Iterate through the edge bindings and delete all of those
        for key in self._edge_bindings.keys():
            if self._edge_bindings[key].item_start == node_id or self._edge_bindings[key].item_end == node_id:
                self.delete_edge(key)
        # Inform the object manager that a node as been deleted
        if node_id in self._object_listing:
            self._delete_object(node_id)
        self._manager.inform(DataStore.EVENT.NODE_DELETE, data_id=node_id)

    def delete_edge(self, edge_id):
        """
        Delete the specified edge from the MazeCanvas

        :param edge_id:             The edge to be deleted
        :return:
        """
        # Go through the edge bindings and delete the appropriate edge
        try:
            # try to delete the edge binding if it exists
            del self._edge_bindings[edge_id]
        except KeyError:
            # Terrible I know, but I dont have the time to find the root cause
            pass
        # Delete the edge from the canvas
        self._canvas.delete(edge_id)
        # Inform the object manager that an edge has been deleted
        self._manager.inform(DataStore.EVENT.EDGE_DELETE, data_id=edge_id)

    def _mark_start_node(self, node_id):
        """
        Mark the passed in node as the starting node
        :param node_id:
        :return:
        """
        # Print the debug information
        # Mark as the new starting node on the canvas, first check that it is a node
        if node_id in self._node_listing:
            Debug.printi("Node:" + str(node_id) + " has been marked as the new starting node", Debug.Level.INFO)
            if self._curr_start is not None:
                # Return the old starting node to its normal colour
                self._canvas.itemconfig(self._curr_start, outline="red", fill="black", activeoutline="black", activefill="red")
            self._curr_start = node_id
            self._canvas.itemconfig(node_id, outline="black", fill="green", activeoutline="green", activefill="black")

        # Inform the object manager that there is a new starting node
        environment_container = self._manager.request(DataStore.DATATYPE.ENVIRONMENT)
        environment_container.start_node = node_id
        self._manager.inform(DataStore.EVENT.ENVIRONMENT_EDIT, environment_container)
Example #7
0
class Application(Frame, object):
    """The application main class."""
    WIDTH, HEIGHT = 1280, 720
    BG = 'white'
    FONT = 'Verdana'
    FILE_OPEN_OPTIONS = {
        'mode': 'rb',
        'title': 'Choose *.json file',
        'defaultextension': '.json',
        'filetypes': [('JSON file', '*.json')]
    }
    DEFAULTS = 'default_settings.yaml'

    def __init__(self, master=None):
        """Creates application main window with sizes self.WIDTH and self.HEIGHT.

        :param master: instance - Tkinter.Tk instance
        """
        super(Application, self).__init__(master)
        self.master.title('Engine Game')
        self.master.geometry('{}x{}'.format(self.WIDTH, self.HEIGHT))
        self.master.protocol('WM_DELETE_WINDOW', self.exit)

        self.source = None
        self._map = None
        self.points = None
        self.lines = None
        self.captured_point = None
        self.x0 = None
        self.y0 = None
        self.scale_x = None
        self.scale_y = None
        self.font_size = None
        self.coordinates = {}
        self.captured_lines = {}
        self.canvas_obj = AttrDict()
        self.icons = {
            0: PhotoImage(file=join('icons', 'player_city.png')),
            1: PhotoImage(file=join('icons', 'city.png')),
            2: PhotoImage(file=join('icons', 'market.png')),
            3: PhotoImage(file=join('icons', 'store.png')),
            4: PhotoImage(file=join('icons', 'point.png')),
            5: PhotoImage(file=join('icons', 'player_train.png')),
            6: PhotoImage(file=join('icons', 'train.png')),
            7: PhotoImage(file=join('icons', 'crashed_train.png')),
            8: PhotoImage(file=join('icons', 'collision.png')),
            9: PhotoImage(file=join('icons', 'play.png')),
            10: PhotoImage(file=join('icons', 'play_pressed.png')),
            11: PhotoImage(file=join('icons', 'stop.png')),
            12: PhotoImage(file=join('icons', 'stop_pressed.png'))
        }
        self.queue_requests = {
            0: self.set_status_bar,
            1: self.set_player_idx,
            2: self.build_map,
            3: self.refresh_map,
            4: self.set_available_games,
            99: self.bot_control
        }

        self.settings_window = None
        if exists(expanduser(self.DEFAULTS)):
            with open(expanduser(self.DEFAULTS), 'r') as cfg:
                defaults = DefaultsDict.from_yaml(cfg)
            self.host = None if not defaults.host else str(defaults.host)
            self.port = None if not defaults.port else int(defaults.port)
            self.timeout = None if not defaults.timeout else int(defaults.timeout)
            self.username = None if not defaults.username else str(defaults.username)
            self.password = None if not defaults.password else str(defaults.password)
        else:
            self.host, self.port, self.timeout, self.username, self.password = None, None, None, None, None
        self.player_idx = None
        self.posts = {}
        self.trains = {}
        self.select_game_window = False
        self.available_games = None
        self.game = None
        self.num_players = None
        self.num_turns = None
        self.bot = Bot()
        self.bot_thread = None

        self.menu = Menu(self)
        filemenu = Menu(self.menu)
        filemenu.add_command(label='Open file', command=self.file_open)
        filemenu.add_command(label='Server settings', command=self.open_server_settings)
        filemenu.add_command(label='Select game', command=self.select_game)
        filemenu.add_command(label='Exit', command=self.exit)
        self.menu.add_cascade(label='Menu', menu=filemenu)
        master.config(menu=self.menu)

        self._status_bar = StringVar()
        self.label = Label(master, textvariable=self._status_bar)
        self.label.pack()

        self.frame = Frame(self)
        self.frame.bind('<Configure>', self._resize_frame)
        self.canvas = Canvas(self.frame, bg=self.BG, scrollregion=(0, 0, self.winfo_width(), self.winfo_height()))
        self.canvas.bind('<Button-1>', self._capture_point)
        self.canvas.bind('<Motion>', self._move_point)
        self.canvas.bind('<B1-ButtonRelease>', self._release_point)
        self.canvas.bind('<Configure>', self._resize_canvas)
        hbar = Scrollbar(self.frame, orient=HORIZONTAL)
        hbar.pack(side=BOTTOM, fill=X)
        hbar.config(command=self.canvas.xview)
        vbar = Scrollbar(self.frame, orient=VERTICAL)
        vbar.pack(side=RIGHT, fill=Y)
        vbar.config(command=self.canvas.yview)
        self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
        self.canvas.pack(fill=BOTH, expand=True)
        self.play = Label(self.canvas, bg='white')
        self.play.configure(image=self.icons[9])
        self.play.bind('<Button-1>', self._play_press)
        self.play.bind('<B1-ButtonRelease>', self._play_release)
        self.stop = Label(self.canvas, bg='white')
        self.stop.configure(image=self.icons[11])
        self.stop.bind('<Button-1>', self._stop_press)
        self.stop.bind('<B1-ButtonRelease>', self._stop_release)
        self.frame.pack(fill=BOTH, expand=True)

        self.weighted = IntVar(value=1)
        self.weighted_check = Checkbutton(self, text='Proportionally to length', variable=self.weighted,
                                          command=self._proportionally)
        self.weighted_check.pack(side=LEFT)

        self.show_weight = IntVar()
        self.show_weight_check = Checkbutton(self, text='Show length', variable=self.show_weight,
                                             command=self.show_weights)
        self.show_weight_check.pack(side=LEFT)

        self.pack(fill=BOTH, expand=True)
        self.requests_executor()
        self.get_available_games()
        self.set_status_bar('Click Play to start the game')
        self.play.place(rely=0.5, relx=0.5, anchor=CENTER)

    @property
    def map(self):
        """Returns the actual map."""
        return self._map

    @map.setter
    def map(self, value):
        """Clears previously drawn map and assigns a new map to self._map."""
        self.clear_map()
        self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self.canvas.winfo_height()))
        self.x0, self.y0 = self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2
        self._map = value

    @staticmethod
    def midpoint(x_start, y_start, x_end, y_end):
        """Calculates a midpoint coordinates between two points.

        :param x_start: int - x coordinate of the start point
        :param y_start: int - y coordinate of the start point
        :param x_end: int - x coordinate of the end point
        :param y_end: int - y coordinate of the end point
        :return: 2-tuple of a midpoint coordinates
        """
        return (x_start + x_end) / 2, (y_start + y_end) / 2

    def _resize_frame(self, event):
        """Calculates new font size each time frame size changes.

        :param event: Tkinter.Event - Tkinter.Event instance for Configure event
        :return: None
        """
        self.font_size = int(0.0125 * min(event.width, event.height))

    def _resize_canvas(self, event):
        """Redraws map each time Canvas size changes. Scales map each time visible part of Canvas is enlarged.

        :param event: Tkinter.Event - Tkinter.Event instance for Configure event
        :return: None
        """
        if self.map:
            k = min(float(event.width) / float(self.x0 * 2), float(event.height) / float(self.y0 * 2))
            self.scale_x, self.scale_y = self.scale_x * k, self.scale_y * k
            self.x0, self.y0 = self.x0 * k, self.y0 * k
            self.redraw_map()
            self.redraw_trains()
            x_start, y_start, x_end, y_end = self.canvas.bbox('all')
            x_start = 0 if x_start > 0 else x_start
            y_start = 0 if y_start > 0 else y_start
            self.canvas.configure(scrollregion=(x_start, y_start, x_end, y_end))

    def _proportionally(self):
        """Rebuilds map and redraws trains."""
        self.build_map()
        self.redraw_trains()

    def _capture_point(self, event):
        """Stores captured point and it's lines.

        :param event: Tkinter.Event - Tkinter.Event instance for ButtonPress event
        :return: None
        """
        x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
        obj_ids = self.canvas.find_overlapping(x - 5, y - 5, x + 5, y + 5)
        if not obj_ids:
            return
        for obj_id in obj_ids:
            if obj_id in self.canvas_obj.point.keys():
                self.captured_point = obj_id
                point_idx = self.canvas_obj.point[obj_id]['idx']
                self.captured_lines = {}
                for line_id, attr in self.canvas_obj.line.items():
                    if attr['start_point'] == point_idx:
                        self.captured_lines[line_id] = 'start_point'
                    if attr['end_point'] == point_idx:
                        self.captured_lines[line_id] = 'end_point'
        if self.weighted.get():
            self.weighted.set(0)

    def _release_point(self, event):
        """Writes new coordinates for a moved point and resets self.captured_point and self.captured_lines.

        :param event: Tkinter.Event - Tkinter.Event instance for ButtonRelease event
        :return: None
        """
        if self.captured_point:
            idx = self.canvas_obj.point[self.captured_point]['idx']
            x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
            self.coordinates[idx] = (x, y)
            self.points[idx]['x'], self.points[idx]['y'] = (x - self.x0) / self.scale_x, (y - self.y0) / self.scale_y
            self.captured_point = None
            self.captured_lines = {}

    def _move_point(self, event):
        """Moves point and its lines. Moves weights if self.show_weight is set to 1.

        In case some point is moved beyond Canvas border Canvas scrollregion is resized correspondingly.
        :param event: Tkinter.Event - Tkinter.Event instance for Motion event
        :return: None
        """
        if self.captured_point:
            new_x, new_y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)
            self.canvas.coords(self.captured_point, new_x, new_y)
            indent_y = self.icons[self.canvas_obj.point[self.captured_point]['icon']].height() / 2 + self.font_size
            if self.canvas_obj.point[self.captured_point]['text_obj']:
                self.canvas.coords(self.canvas_obj.point[self.captured_point]['text_obj'], new_x, new_y - indent_y)
            self.coordinates[self.canvas_obj.point[self.captured_point]['idx']] = (new_x, new_y)
            self.canvas.configure(scrollregion=self.canvas.bbox('all'))

            for line_id, attr in self.captured_lines.items():
                line_attrs = self.canvas_obj.line[line_id]
                if attr == 'start_point':
                    x, y = self.coordinates[line_attrs['end_point']]
                    self.canvas.coords(line_id, new_x, new_y, x, y)
                else:
                    x, y = self.coordinates[line_attrs['start_point']]
                    self.canvas.coords(line_id, x, y, new_x, new_y)
                if self.show_weight.get():
                    mid_x, mid_y = self.midpoint(new_x, new_y, x, y)
                    self.canvas.coords(line_attrs['weight_obj'][1], mid_x, mid_y)
                    r = self.font_size * len(str(line_attrs['weight']))
                    self.canvas.coords(line_attrs['weight_obj'][0], mid_x - r, mid_y - r, mid_x + r, mid_y + r)

            self.redraw_trains()

    def _play_press(self, _):
        """Draws play button pressed icon."""
        self.play.configure(image=self.icons[10])

    def _play_release(self, _):
        """Draws play button icon and calls bot_control method."""
        self.play.configure(image=self.icons[9])
        self.bot_control()

    def _stop_press(self, _):
        """Draws stop button pressed icon."""
        self.stop.configure(image=self.icons[12])

    def _stop_release(self, _):
        """Draws stop buton icon and calls bot_control method."""
        self.stop.configure(image=self.icons[11])
        self.bot_control()

    def set_player_idx(self, value):
        """Sets a player idx value."""
        self.player_idx = value

    def file_open(self):
        """Opens file dialog and builds and draws a map once a file is chosen. Stops bot if its started."""
        path = tkFileDialog.askopenfile(parent=self.master, **self.FILE_OPEN_OPTIONS)
        if path:
            if self.bot_thread:
                self.bot_control()
            self.posts, self.trains = {}, {}
            self.source = path.name
            self.weighted_check.configure(state=NORMAL)
            self.build_map()

    def open_server_settings(self):
        """Opens server settings window."""
        ServerSettings(self, title='Server settings')

    def select_game(self):
        """Opens select game window."""
        self.select_game_window = True
        SelectGame(self, title='Select game')
        self.select_game_window = False
        self.set_status_bar('Click Play to start the game')

    def exit(self):
        """Closes application and stops bot if its started."""
        if self.bot_thread:
            self.bot_control()
        self.master.destroy()

    def bot_control(self):
        """Starts bot for playing the game or stops it if it is started."""
        if not self.bot_thread:
            self.bot_thread = Thread(target=self.bot.start, kwargs={
                'host': self.host,
                'port': self.port,
                'time_out': self.timeout,
                'username': self.username,
                'password': self.password,
                'game': self.game,
                'num_players': self.num_players,
                'num_turns': self.num_turns})
            self.bot_thread.start()
        else:
            self.bot.stop()
            self.bot_thread.join()
            self.bot_thread = None

    def get_available_games(self):
        """Requests a list of available games."""
        if self.select_game_window:
            self.bot.get_available_games(host=self.host, port=self.port, time_out=self.timeout)
        self.after(1000, self.get_available_games)

    def set_available_games(self, games):
        """Sets new value for available games list."""
        self.available_games = games

    def set_status_bar(self, value):
        """Assigns new status bar value and updates it.

        :param value: string - status bar string value
        :return: None
        """
        self._status_bar.set(value)
        self.label.update()

    def build_map(self, source=None):
        """Builds and draws new map.

        :param source: string - source string; could be JSON string or path to *.json file.
        :return: None
        """
        if source:
            self.source = source
        if self.source:
            self.map = Graph(self.source, weighted=self.weighted.get())
            self.set_status_bar('Map title: {}'.format(self.map.name))
            self.points, self.lines = self.map.get_coordinates()
            self.draw_map()

    def draw_map(self):
        """Draws map by prepared coordinates."""
        self.draw_lines()
        self.draw_points()

    def clear_map(self):
        """Clears previously drawn map and resets coordinates and scales."""
        self.canvas.delete('all')
        self.scale_x, self.scale_y = None, None
        self.coordinates = {}

    def redraw_map(self):
        """Redraws existing map by existing coordinates."""
        if self.map:
            self.coordinates = {}
            for obj_id in self.canvas_obj.line:
                self.canvas.delete(obj_id)
            self.draw_lines()
        self.redraw_points()

    def redraw_points(self):
        """Redraws map points by existing coordinates."""
        if self.map:
            for obj_id, attrs in self.canvas_obj.point.items():
                if attrs['text_obj']:
                    self.canvas.delete(attrs['text_obj'])
                self.canvas.delete(obj_id)
            self.draw_points()

    def redraw_trains(self):
        """Redraws existing trains."""
        if self.trains and hasattr(self.canvas_obj, 'train'):
            for obj_id, attrs in self.canvas_obj.train.items():
                self.canvas.delete(attrs['text_obj'])
                self.canvas.delete(obj_id)
        self.draw_trains()

    @prepare_coordinates
    def draw_points(self):
        """Draws map points by prepared coordinates."""
        point_objs = {}
        captured_point_idx = self.canvas_obj.point[self.captured_point]['idx'] if self.captured_point else None
        for idx in self.points.keys():
            x, y = self.coordinates[idx]
            if self.posts and idx in self.posts.keys():
                post_type = self.posts[idx]['type']
                if post_type == 1:
                    status = '{}/{} {}/{} {}/{}'.format(self.posts[idx]['population'],
                                                        self.posts[idx]['population_capacity'],
                                                        self.posts[idx]['product'],
                                                        self.posts[idx]['product_capacity'],
                                                        self.posts[idx]['armor'],
                                                        self.posts[idx]['armor_capacity'])
                elif post_type == 2:
                    status = '{}/{}'.format(self.posts[idx]['product'], self.posts[idx]['product_capacity'])
                else:
                    status = '{}/{}'.format(self.posts[idx]['armor'], self.posts[idx]['armor_capacity'])
                image_id = 0 if post_type == 1 and self.posts[idx]['player_idx'] == self.player_idx else post_type
                point_id = self.canvas.create_image(x, y, image=self.icons[image_id])
                y -= (self.icons[post_type].height() / 2) + self.font_size
                text_id = self.canvas.create_text(x, y, text=status, font="{} {}".format(self.FONT, self.font_size))
            else:
                post_type = 4
                point_id = self.canvas.create_image(x, y, image=self.icons[post_type])
                text_id = None
            point_objs[point_id] = {'idx': idx, 'text_obj': text_id, 'icon': post_type}
            self.captured_point = point_id if idx == captured_point_idx else self.captured_point
        self.canvas_obj['point'] = point_objs

    @prepare_coordinates
    def draw_lines(self):
        """Draws map lines by prepared coordinates and shows their weights if self.show_weight is set to 1."""
        line_objs, captured_lines_idx = {}, {}
        if self.captured_lines:
            for line_id in self.captured_lines.keys():
                captured_lines_idx[self.canvas_obj.line[line_id]['idx']] = line_id
        for idx, attrs in self.lines.items():
            x_start, y_start = self.coordinates[attrs['start_point']]
            x_stop, y_stop = self.coordinates[attrs['end_point']]
            line_id = self.canvas.create_line(x_start, y_start, x_stop, y_stop)
            line_objs[line_id] = {'idx': idx, 'weight': attrs['weight'], 'start_point': attrs['start_point'],
                                  'end_point': attrs['end_point'], 'weight_obj': ()}
            if idx in captured_lines_idx.keys():
                self.captured_lines[line_id] = self.captured_lines.pop(captured_lines_idx[idx])
        self.canvas_obj['line'] = line_objs
        self.show_weights()

    @prepare_coordinates
    def draw_trains(self):
        """Draws trains by prepared coordinates."""
        trains = {}
        for train in self.trains.values():
            start_point = self.lines[train['line_idx']]['start_point']
            end_point = self.lines[train['line_idx']]['end_point']
            weight = self.lines[train['line_idx']]['weight']
            position = train['position']
            x_start, y_start = self.coordinates[start_point]
            x_end, y_end = self.coordinates[end_point]
            delta_x, delta_y = int((x_start - x_end) / weight) * position, int((y_start - y_end) / weight) * position
            x, y = x_start - delta_x, y_start - delta_y
            if train['cooldown'] > 0:
                icon = 7
                status = None
            else:
                icon = 5 if train['player_idx'] == self.player_idx else 6
                status = '{}/{}'.format(train['goods'], train['goods_capacity'])
            indent_y = self.icons[icon].height() / 2
            train_id = self.canvas.create_image(x, y - indent_y, image=self.icons[icon])
            text_id = self.canvas.create_text(x, y - (2 * indent_y + self.font_size), text=status,
                                              font="{} {}".format(self.FONT, self.font_size)) if status else None
            trains[train_id] = {'icon': icon, 'text_obj': text_id}
        self.canvas_obj['train'] = trains

    def show_weights(self):
        """Shows line weights when self.show_weight is set to 1 and hides them when it is set to 0."""
        if not self.canvas_obj:
            return
        if self.show_weight.get():
            for line in self.canvas_obj.line.values():
                if line['weight_obj']:
                    for obj in line['weight_obj']:
                        self.canvas.itemconfigure(obj, state='normal')
                else:
                    x_start, y_start = self.coordinates[line['start_point']]
                    x_end, y_end = self.coordinates[line['end_point']]
                    x, y = self.midpoint(x_start, y_start, x_end, y_end)
                    value = line['weight']
                    size = self.font_size
                    r = int(size) * len(str(value))
                    oval_id = self.canvas.create_oval(x - r, y - r, x + r, y + r, fill=self.BG, width=0)
                    text_id = self.canvas.create_text(x, y, text=value, font="{} {}".format(self.FONT, str(size)))
                    line['weight_obj'] = (oval_id, text_id)
        else:
            for line in self.canvas_obj.line.values():
                if line['weight_obj']:
                    for obj in line['weight_obj']:
                        self.canvas.itemconfigure(obj, state='hidden')

    def requests_executor(self):
        """Dequeues and executes requests. Assigns corresponding label to bot control button."""
        if not self.bot.queue.empty():
            request_type, request_body = self.bot.queue.get_nowait()
            if request_type == 99 and request_body:
                self.open_server_settings()
                request_body = None
            if request_body is not None:
                self.queue_requests[request_type](request_body)
            else:
                self.queue_requests[request_type]()
        if self.bot_thread and self.bot_thread.is_alive():
            if self.play.place_info():
                self.play.place_forget()
                self.stop.place(rely=0.99, relx=0.995, anchor=SE)
        else:
            if self.stop.place_info():
                self.stop.place_forget()
                self.play.place(rely=0.5, relx=0.5, anchor=CENTER)
        self.after(50, self.requests_executor)

    def refresh_map(self, dynamic_objects):
        """Refreshes map with passed dynamic objects.

        :param dynamic_objects: dict - dict of dynamic objects
        :return: None
        """
        for post in dynamic_objects['posts']:
            self.posts[post['point_idx']] = post
        for train in dynamic_objects['trains']:
            self.trains[train['idx']] = train
        self.redraw_points()
        self.redraw_trains()