示例#1
0
def simulation_canvas(parent, **config):
    """Initializes the canvas and sets it up to receive user input."""
    global the_canvas
    the_canvas = Canvas(parent, **config)
    the_canvas.focus_set()  # this makes tkinter canvas accept keyboard commands
    the_canvas.bind("<Key>", lambda event: model.move_ship(event))
    return the_canvas
示例#2
0
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.info = {}
        self.window = None
        self.size = (640, 480)
        self.fields = []
        self.init_ui()

    def init_ui(self):
        self.parent.title("Node Writer")
        self.style = Style()
        self.style.theme_use("alt")
        self.pack(fill="both", expand=True)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        menubar.add_command(label="New", command=self.onNew)
        menubar.add_command(label="Show Info", command=self.get_info)
        menubar.add_command(label="Exit", command=self.quit)

        self.canvas = Canvas(self, background="white", width=self.size[0], height=self.size[1])
        self.canvas.pack(fill="both", expand=1)
        self.canvas.bind("<Motion>", self.move_boxes)

    def move_boxes(self, event):
        print(event.x, event.y)
        """
        x, y = (event.x-1, event.y-1)
        x1, y1, x2, y2 = self.canvas.bbox("test")
        if x > x1 and y > y1 and x < x2 and y < y2:
            print("Hit")
        else:
            print("Missed")
        """

    def onNew(self):
        new = Node(self, "Node_entry")
        label = new.insert_entry_field("Labels")
        label2 = new.insert_entry_field("Labels2")
        text = new.insert_text_field("Text")
        new.ok_cancel_buttons()

    def get_info(self):
        x, y = (self.size[0]/2, self.size[1]/2)
        for i in self.info:
            label_frame= LabelFrame(self, text="name")
            label_frame.pack(fill="y")
            for entry in self.info[i]["Entry"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
            for text in self.info[i]["Text"]:
                frame = Frame(label_frame)
                frame.pack(fill="x")
                label = Label(label_frame, text=self.info[i]["Text"][text], width=6)
                label.pack(side="left", anchor="n", padx=5, pady=5)
        window = self.canvas.create_window(x, y, window=label_frame, tag="test")
示例#3
0
文件: dialog.py 项目: gokai/tim
class ListDialog(object):
    def __init__ (self, master, items, message, accept_func):
        self.accept_func = accept_func

        self.top = Toplevel(master)
        self.top.transient(master)
        self.top.rowconfigure(0, weight=1)
        self.top.rowconfigure(1, weight=3)
        self.top.rowconfigure(2, weight=0)
        self.top.columnconfigure(0, weight=1)
        self.top.columnconfigure(1, weight=1)
        self.top.resizable(width=True, height=True)

        self.frame = Frame(self.top)
        self.frame.rowconfigure(0, weight=1)
        self.frame.rowconfigure(1, weight=0)
        self.frame.columnconfigure(0, weight=1)
        self.frame.columnconfigure(1, weight=0)
        self.frame.grid(row=0, column=0, sticky=(N, S, W, E), columnspan=2)
        self.canvas = Canvas(self.frame)
        self.canvas.create_text(0, 0, text=message, anchor=NW)
        self.canvas.grid(row=0, column=0, sticky=(N, W, S, E))

        self.vscroll = Scrollbar(self.frame, command=self.canvas.yview)
        self.vscroll.grid(row=0, column=1, sticky=(N, S))
        self.canvas['yscrollcommand'] = self.vscroll.set

        self.hscroll = Scrollbar(self.frame, command=self.canvas.xview, orient=HORIZONTAL)
        self.hscroll.grid(row=1, column=0, sticky=(W, E), columnspan=2)
        self.canvas['xscrollcommand'] = self.hscroll.set

        self.canvas['scrollregion'] = self.canvas.bbox('all')
        self.canvas.bind('<Button-4>', self.scroll)
        self.canvas.bind('<Button-5>', self.scroll)
        self.canvas.bind('<MouseWheel>', self.scroll)

        self.view = NameView(self.top, sorted(items))
        self.view.widget.grid(row=1, column=0, columnspan=2, sticky=(N, W, E, S))

        self.delbutton = Button(self.top, text='Ok', command=self.accept )
        self.cancelbutton = Button(self.top, text='Cancel', command=self.cancel)
        self.delbutton.grid(row=2, column=0)
        self.cancelbutton.grid(row=2, column=1)
        self.view.widget.focus_set()

    def accept(self):
        self.accept_func(self.view.selection())
        self.top.destroy()

    def cancel(self):
        self.result = None
        self.top.destroy()

    def scroll(self, event):
        if event.num == 4 or event.delta > 0:
            self.canvas.yview(SCROLL, -1, UNITS)
        elif event.num == 5 or event.delta < 0:
            self.canvas.yview(SCROLL, 1, UNITS)
示例#4
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        self._canvas = canvas
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

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

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

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

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

        def _configure_canvas(event):
            """
            This function is called when the canvas is configured, that is on resize and so on,
            """
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
            if interior.winfo_reqheight() != canvas.winfo_height():
                # update the inner frame's height to fill the canvas
                canvas.itemconfigure(interior_id, height=canvas.winfo_height())

        canvas.bind('<Configure>', _configure_canvas)

        return
示例#5
0
class SolutionViewer(object):
    '''Feed it progressively enhanced solutions in a loop:
    
    solution = initial
    while sv.show_and_wait(solution):
        new_solution = elaborate(solution)
        if new_solution is None:
            return solution
    '''
    
    def __init__(self):
        self.action = None
        self.root = root = Tk()
        root.title('Fold me baby one more time')
        root.protocol("WM_DELETE_WINDOW", self.close)
        
        # exists the mainloop()
        root.bind("<space>", lambda evt: root.quit())

        root.pack_propagate(True)

        self.canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
        self.canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        self.canvas.bind("<Configure>", lambda evt: self.populate_canvas())
        self.current_solution = None


    def populate_canvas(self):
        if self.current_solution is None:
            return
        draw_solution(self.canvas, self.current_solution)


    def show_and_wait(self, solution):
        '''Return False if user closed the window'''
        self.current_solution = solution
        self.populate_canvas() 
        self.root.mainloop()
        return self.root is not None


    def close(self):
        if self.root:
            self.root.destroy()
            self.root = None
示例#6
0
    def create_album(self,playlist:vk_audio.Playlist):
        click = lambda _:self.onclick(playlist)
        f = ttk.Frame(self.f,width=self.ONE_ITEM_WIDTH,cursor="hand2");
        f.bind("<Button-1>", click)

        img = Canvas(f,width=160,height=160);
        img.pack(pady=5)        
        img.bind("<Button-1>", click)

        self.set_image_from_album(img,playlist)
        title = Label(f,text=playlist.title,font=('times',14));
        title.pack(padx=10)
        title.bind("<Button-1>", click)

        author = Label(f,text=",".join(i['name'] for i in playlist.author_info),font=self.DEFAULT_FONT,fg=self.DEF_FG);
        author.pack(padx=10)
        author.bind("<Button-1>",lambda _:self.a_onclick(playlist))
        author.bind("<Enter>", lambda _:(author.config(font=self.HOVER_FONT,fg=self.HOVER_FG),self._config()))
        author.bind("<Leave>", lambda _:(author.config(font=self.DEFAULT_FONT,fg=self.DEF_FG),self._config()))

        f.pack(side=LEFT)
示例#7
0
    def __init__(self, root):
        #Configurarea si initializarea ferestrei
        root.title('Digit Classifier')
        root.resizable(False, False)

        c = Canvas(root, width=self.c_width, height=self.c_height)
        c.configure(background=self._bg)
        c.bind('<B1-Motion>', self.draw)
        c.grid(row=0, column=0, columnspan=3, rowspan=4, pady=3)

        _reset = Button(text='Reset', command=lambda: self.reset(c))
        _reset.grid(row=3, column=1, columnspan=2, sticky=S, padx=7, pady=8)
        _predict = Button(text='Predict',
                          command=lambda: self.make_prediction(root, c, label))
        _predict.grid(row=3, column=2, sticky=S + E, padx=4, pady=8)
        #Button(text='Predict', bg="Gray", fg="Gray85").grid(row=3, column=2, sticky=S+E, padx=4, pady=4)

        label = Label(root, text='Prediction: NaN')
        label.grid(row=4, column=0, sticky=W, padx=4, pady=4)

        self.model = load_model('../best_models/{}.hdf5'.format(self._model))
class PointRec(Frame):
    """ creates a widget of siz 480 x 640 that prints the coordinates where the user has clicked
    """

    def __init__(self, master=None):
        """ Constructor - Creates canvas
        """

        Frame.__init__(self, master)
        self.pack()

        # Canvas
        self.canvas = Canvas(self, height=480, width=640)
        self.canvas.bind("<Button-1>", self.record)
        self.canvas.pack(expand=True, fill=BOTH)

    def record(self, event):
        """ Handles left button click and prints mouse position
        """

        print('you clicked at ({}, {})'.format(event.x, event.y))
示例#9
0
    def __init__(self, parent):
        Frame.__init__(self, parent, background=COLOR_TABLEBODY)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.xsc = Scrollbar(self, orient=HORIZONTAL)
        self.xsc.grid(row=1, column=0, sticky='we')

        self.ysc = Scrollbar(self)
        self.ysc.grid(row=0, column=1, sticky='ns')

        c = Canvas(
            self,
            bg="#ff2f33",  #karminrot
            xscrollcommand=self.xsc.set,
            yscrollcommand=self.ysc.set)
        c.rowconfigure(0, weight=1)
        c.columnconfigure(0, weight=1)
        c.grid(row=0, column=0, sticky='nswe', padx=0, pady=0)

        c.bind("<Configure>", self._onFrameConfigure)
        c.bind('<Enter>', self._bindToMousewheel)
        c.bind('<Leave>', self._unbindFromMousewheel)

        self.xsc.config(command=c.xview)
        self.ysc.config(command=c.yview)
        self.canvas = c
def rotateImage(angle):
    global imagePath
    global image
    global im
    global im_width
    global im_height
    global im_size
    global photo
    global canvas
    global xscrollbar
    global yscrollbar
    global t
    canvas.destroy()
    canvas = Canvas(root,
                    height=canvasHeight,
                    width=canvasWidth,
                    xscrollcommand=xscrollbar.set,
                    yscrollcommand=yscrollbar.set)
    canvas.place(x=canvasxPosition, y=canvasyPosition)
    im = Image.open(imagePath.get())
    im_width, im_height = im.size
    im = im.resize((int(im_width * imageMagnification.get()),
                    int(im_height * imageMagnification.get())),
                   Image.ANTIALIAS)
    im = im.rotate(angle * 180 / pi)
    photo = ImageTk.PhotoImage(im)
    image = canvas.create_image(0, 0, anchor=NW, image=photo)
    canvas.grid(row=0, column=0, sticky=N + S + E + W)
    canvas.config(scrollregion=canvas.bbox(ALL))
    xscrollbar.config(command=canvas.xview)
    yscrollbar.config(command=canvas.yview)
    canvas.bind("<Motion>", crop)
    canvas.bind("<ButtonPress-1>", printcoord)
    canvas.bind('<B1-Motion>', onGrow)
示例#11
0
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()
        self.width, self.height = 800, 400
        self.unit = 20
        f = Canvas(master, width=self.width, height=self.height, bg='gray')
        f.bind('<Up>', self.changedirection)
        f.bind('<Down>', self.changedirection)
        f.bind('<Left>', self.changedirection)
        f.bind('<Right>', self.changedirection)
        f.focus_set()
        f.pack()
        for i in range(0, self.height, self.unit):
            f.create_line(0, i, self.width, i)
        for i in range(0, self.width, self.unit):
            f.create_line(i, 0, i, self.height)
        self.f = f
        self.mat = [[0] * (self.width // self.unit)
                    for _ in range(self.height // self.unit)]
        print('canvas matrix', len(self.mat), len(self.mat[0]))

        # direction queue
        self.directiondict = {
            'Down': (0, 1),
            'Up': (0, -1),
            'Left': (-1, 0),
            'Right': (1, 0)
        }
        self.directionq = deque([])
示例#12
0
    def __init__(self, master):
        self.master = master
        self.master.title("Conway's Game of Life")

        self.button_frame = Frame(master)
        self.button_frame.pack(side="top")

        self.start_button = Button(self.button_frame,
                                   text="Start",
                                   command=self.start_stop)
        self.start_button.pack(side="left")

        self.clear_button = Button(self.button_frame,
                                   text="Clear",
                                   command=self.clear)
        self.clear_button.pack(side="left")

        self.next_button = Button(self.button_frame,
                                  text="→",
                                  command=self.next_frame)
        self.next_button.pack(side="left")

        canvas = Canvas(master, bg="white", height=500, width=500)
        canvas.pack(side="top", expand=True, fill="both")

        self.board = Board()
        self.grid = GameGrid(canvas, self.board)
        self.highlighter = Highlighter(self.grid)
        self.playback = Playback(self.grid, self.board, canvas)

        canvas.bind("<Motion>", self.mouse_over)
        canvas.bind("<Leave>", self.leave_canvas)
        canvas.bind("<Button-1>", self.click_canvas)
示例#13
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        parent.title("Space Invaders")

        canvas, aliens, lasers = Canvas(parent,
                                        width=800,
                                        height=400,
                                        bg='black'), {}, {}
        canvas.pack()
        i1, i2 = PhotoImage(format='gif',
                            file="alien.gif"), PhotoImage(format='gif',
                                                          file="laser.gif")
        for x, y, p in [(100 + 40 * j, 160 - 20 * i, 100 * i) for i in range(8)
                        for j in range(15)]:
            aliens[canvas.create_image(x, y, image=i1)] = p
        canvas.bind(
            '<Button-1>', lambda e: lasers.update(
                {canvas.create_image(e.x, 390, image=i2): 10}))
        while aliens:
            try:
                for l in lasers:
                    canvas.move(l, 0, -5)
                    if canvas.coords(l)[1] < 0:
                        canvas.delete(l)
                        del lasers[l]
                for a in aliens:
                    canvas.move(a, 2.0 * math.sin(time.time()), 0)
                    p = canvas.coords(a)
                    items = canvas.find_overlapping(p[0] - 5, p[1] - 5,
                                                    p[0] + 5, p[1] + 5)
                    for i in items[1:2]:
                        canvas.delete(a)
                        del aliens[a]
                        canvas.delete(i)
                        del lasers[i]
                time.sleep(0.02)
                root.update()
            except:
                pass
示例#14
0
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient='vertical')
        vscrollbar.pack(fill='y', side='right', expand=False)
        canvas = Canvas(self,
                        bd=0,
                        highlightthickness=0,
                        yscrollcommand=vscrollbar.set,
                        bg='black')
        canvas.pack(side='left', fill='both', expand=True)
        vscrollbar.config(command=canvas.yview)

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

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

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

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

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

        canvas.bind('<Configure>', _configure_canvas)
示例#15
0
    def createCanvas(self):
       f = Frame(self)
       canvas = Canvas(f, width=self.canvasH, height=self.canvasH, bg='white')

       xbar = Scrollbar( f, orient='horizontal', command=canvas.xview )
       ybar = Scrollbar( f, orient='vertical', command=canvas.yview )
       canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set )

       # Resize box
       resize = Label( f, bg='white' )
       # Layout
       canvas.grid( row=0, column=1, sticky='nsew')
       ybar.grid( row=0, column=2, sticky='ns')
       xbar.grid( row=1, column=1, sticky='ew' )
       resize.grid( row=1, column=2, sticky='nsew' )

       # Resize behavior
       f.rowconfigure( 0, weight=1 )
       f.columnconfigure( 1, weight=1 )
       f.grid( row=0, column=0, sticky='nsew' )
       f.bind( '<Configure>', lambda event: self.updateScrollRegion() )  

       # Mouse bindings

       canvas.bind( '<ButtonPress-1>', self.clickCanvas )
       canvas.bind( '<B1-Motion>', self.dragCanvas )
       canvas.bind( '<ButtonRelease-1>', self.releaseCanvas )
       
       return f, canvas
示例#16
0
class Dibujo(object):
    def __init__(self, master):
        self.master = master

        self.inicializar_gui()

    def inicializar_gui(self):
        self.canvas = Canvas(bg='white', height=300, width=300)
        self.canvas.pack()

        self.canvas.bind('<ButtonPress-1>', self.iniciar_dibujo)
        self.canvas.bind('<B1-Motion>', self.dibujar)
        self.canvas.bind('<Double-1>', self.limpiar)
        self.canvas.bind('<ButtonPress-3>', self.mover)

        self.tipos_figuras = [
            self.canvas.create_oval, self.canvas.create_rectangle
        ]
        self.dibujo = None

    def iniciar_dibujo(self, evento):
        self.figura = self.tipos_figuras[0]
        self.tipos_figuras = self.tipos_figuras[1:] + self.tipos_figuras[:1]
        self.inicio = evento
        self.dibujo = None

    def dibujar(self, evento):
        canvas = evento.widget

        if self.dibujo:
            self.canvas.delete(self.dibujo)

        id_figura = self.figura(self.inicio.x, self.inicio.y, evento.x,
                                evento.y)

        self.dibujo = id_figura

    def limpiar(self, evento):
        evento.widget.delete('all')

    def mover(self, evento):
        if self.dibujo:
            canvas = evento.widget
            diferencia_x = evento.x - self.inicio.x
            diferencia_y = evento.y - self.inicio.y

            canvas.move(self.dibujo, diferencia_x, diferencia_y)

            self.inicio = evento
示例#17
0
文件: main.py 项目: Nircek/dots
class Dots(Tk):
    def __init__(self):
        super().__init__()
        self.w = Canvas(self, bg='#aaa')
        self.d = []
        self.t = Thread(target=self.physics, daemon=True)
        self.g = .04
        self.closing = False
        self.start = BooleanVar(self)
        self.w.pack()
        self.w.bind('<Button-1>', lambda ev: self.new(ev.x, ev.y))
        self.bind('<space>', lambda ev: self.start.set(not self.start.get()))
        self.protocol('WM_DELETE_WINDOW', self.on_close)
        self.t.start()

    def on_close(self):
        self.closing = True
        self.destroy()

    def new(self, x, y):
        self.d += [Dot(x, y)]

    def physics(self):
        try:
            while not self.closing:
                if self.d:
                    x = sum([e.x for e in self.d]) / len(self.d)
                    y = sum([e.y for e in self.d]) / len(self.d)
                    self.w.delete(ALL)
                    for e in self.d:
                        if self.start.get():
                            e.vx += self.g * (x - e.x)
                            e.vy += self.g * (y - e.y)
                            e.update()
                        e.render(self.w)
                sleep(1 / 20)
        except:
            if not self.closing:
                raise
示例#18
0
class slot:

    # Canvas in a frame
    def __init__(self, wnd, x, y, board):
        self.board = board
        # colorList = ['red','yellow','blue','purple','pink','black','white','orange','green']
        self.frame = Frame(wnd, borderwidth=1, relief='solid')
        self.frame.grid(column=x, row=y, sticky='EWSN')
        self.canvas = Canvas(self.frame, width=100, height=100)
        self.canvas.bind('<Button-1>', lambda _: self.board.makeMove(x))
        self.canvas.pack(fill='both', expand=True)

    # Pass move to game engine and draw a circle
    def placePiece(self, redTurn):
        # print("clicked at", event.x, event.y)
        # self.game.placeMove(x)
        # if self.game.redTurn:
        if redTurn:
            self.canvas.create_oval(2, 2, 101, 101, fill='red')
            # self.canvas.create_oval(0,0,int(self.canvas.cget('width'))/2,int(self.canvas.cget('height'))/2, fill='red')
        else:
            self.canvas.create_oval(2, 2, 101, 101, fill='yellow')
示例#19
0
    def set_scrollbar(self):
        mainframe = Frame(self)
        mainframe.pack(fill=BOTH, expand=1, padx=5)
        lutCanvas = Canvas(mainframe)
        lutCanvas.pack(side=LEFT, fill=BOTH, expand=1)
        scroll = ttk.Scrollbar(lutCanvas,
                               orient=HORIZONTAL,
                               command=lutCanvas.xview)
        scroll.pack(side=BOTTOM, fill=X)

        lutCanvas.configure(xscrollcommand=scroll.set)
        lutCanvas.bind(
            '<Configure>',
            lambda e: lutCanvas.configure(scrollregion=lutCanvas.bbox('all')))

        def _on_mouse_wheel(event):
            lutCanvas.xview_scroll(-1 * int((event.delta / 120)), "units")

        lutCanvas.bind_all("<MouseWheel>", _on_mouse_wheel)

        self.write_frame = Frame(lutCanvas)
        lutCanvas.create_window((0, 0), window=self.write_frame, anchor=NW)
示例#20
0
class create_track:
    def __init__(self, frame, parent, childn):

        self.frame = frame
        self.parent = parent
        self.childn = childn

    def create_line(self):
        self.canvas = Canvas()
        #self.canvas.create_line(10,20,100,200,250,350,40,40)
        list = [(100, 100), (100, 200), (300, 300), (400, 300), (500, 100)]
        for x, y in list:
            print(x)
            print(y)
            self.canvas.create_oval(int(x), int(y), int(x) + 50, int(y) + 50)
            self.canvas.bind()
            self.canvas.pack()

    #frame = Frame(root, width=100, height=100)

    def create_graph(self):
        pass
示例#21
0
def main():
	gui = Tk()
	gui.title("D&C Convex Hull")

	canvas = Canvas(gui)
	canvas.focus_set()

	canvas.bind("<Button-1>", on_left_click)
	canvas.bind("<Button-3>", on_right_click)
	canvas.bind("<Motion>", on_mouse_moved)
	canvas.bind("e", do_pathfinding)
	canvas.bind("q", place_waypoint)
	canvas.pack(expand=True, fill="both")

	gui.mainloop()
示例#22
0
    def __init__(self,
                 cv: Canvas,
                 callback_click,
                 window_size: WindowSize,
                 board_size: BoardSize,
                 chess_radii=10,
                 theta=0.3):
        super().__init__(window_size, board_size)

        def draw_line_fun(x1, y1, x2, y2):
            cv.create_line(x1, y1, x2, y2)

        def draw_chess_fun(x, y, chess: Chess):
            rect = (x - chess_radii, y - chess_radii, x + chess_radii,
                    y + chess_radii)
            cv.create_oval(rect, fill='black' if chess.is_black() else 'white')

        def draw_text_fun(x, y, text):
            rect = (x - chess_radii, y - chess_radii, x + chess_radii,
                    y + chess_radii)
            cv.create_text(x, y, text=text, fill='red', font=("Purisa", 8))

        def clear_fun():
            cv.delete('all')

        def _callback_click(event):
            if callback_click is None:
                return
            x, y = event.x, event.y
            coordinate = self.get_real_coordinate(x, y, theta=theta)
            if coordinate is not None:
                x, y = coordinate
                callback_click(x, y)

        cv.bind('<Button-1>', _callback_click)

        self._draw_line_fun, self._draw_chess_fun, self._clear_fun, self._draw_text_fun = \
         draw_line_fun, draw_chess_fun, clear_fun, draw_text_fun
class SkeletonAnimationApp():
    def __init__(self, master):
        """Skeleton animation app to help understand more advanced ones."""
        
        master.title("Track mouse with up to " + str(numEvents) + " circles.") 
        self.master = master 
        
        # keep track of a fixed number of motion events
        self.events = []
        
        self.canvas = Canvas(master, width=512, height=512)        
        self.canvas.bind("<Motion>", self.track)
        self.canvas.pack()
        
        # Register handler which redraws everything at fixed interval
        self.master.after(frameDelay, self.drawEverything)
        
    def track(self, event):
        """Refresh event collection and redraw."""
        self.events.append((event.x, event.y))
        if len(self.events) > numEvents:
            del self.events[0]

    def drawEverything(self):
        """Draw at timed frequency."""
        self.master.after(frameDelay, self.drawEverything)
        self.visit()

    def visit (self):
        """Visit structure and represent graphically."""
        self.canvas.delete(ALL)
        last = None
        for shape in self.events:
            self.canvas.create_oval(shape[X] - 4, shape[Y] - 4, 
                                 shape[X] + 4, shape[Y] + 4, fill='black')
            if last:
                self.canvas.create_line(shape[X], shape[Y], last[X], last[Y])
            last = shape
示例#24
0
def main():
    squares = {(random.randrange(-15, 15), random.randrange(-15, 15))
               for i in range(30)}
    space = __space_build(squares)
    space_x, space_y = *zip(*space.keys()),
    xmin, xmax, ymin, ymax = min(space_x), max(space_x), min(space_y), max(
        space_y)
    master = Tk()
    canvas_width = (xmax - xmin + 1) * __SQUARE_SIZE
    canvas_height = (ymax - ymin + 1) * __SQUARE_SIZE
    w = Canvas(master, width=canvas_width, height=canvas_height)
    __space_draw(space, w, canvas_width, canvas_height)

    def onclick(event):
        x = (event.x // __SQUARE_SIZE) + xmin
        y = (event.y // __SQUARE_SIZE) + ymin
        squares.add((x, y))
        space = __space_build(squares)
        __space_draw(space, w, canvas_width, canvas_height)

    w.bind("<Button-1>", onclick)
    w.pack()
    mainloop()
示例#25
0
class ScrollLabelFrame(LabelFrame):
    def __init__(self, parent, label):
        super().__init__(master=parent, text=label, padx=5, pady=5)
        self._canvas = Canvas(self, background="#ffffff")
        self.inner_frame = Frame(self._canvas, background="#ffffff")
        self._scroll_bar = Scrollbar(self,
                                     orient="vertical",
                                     command=self._canvas.yview)
        self._canvas.configure(yscrollcommand=self._scroll_bar.set)
        self._scroll_bar.pack(side="right", fill="y")
        self._canvas.pack(side="left", fill="both", expand=True)
        self._canvas_window = self._canvas.create_window(
            (4, 4),
            window=self.inner_frame,
            anchor="nw",  #add view port frame to canvas
            tags="self.inner_frame")

        self.inner_frame.bind(
            "<Configure>", self.onFrameConfigure
        )  # bind an event whenever the size of the viewPort frame changes.
        self._canvas.bind(
            "<Configure>", self.onCanvasConfigure
        )  # bind an event whenever the size of the viewPort frame changes.

        self.onFrameConfigure(None)

    def onFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self._canvas.configure(
            scrollregion=self._canvas.bbox("all")
        )  # whenever the size of the frame changes, alter the scroll region respectively.

    def onCanvasConfigure(self, event):
        '''Reset the canvas window to encompass inner frame when required'''
        canvas_width = event.width
        self._canvas.itemconfig(self._canvas_window, width=canvas_width)
示例#26
0
 def __init__(self, parent=None):
     canvas = Canvas(width=300, height=300, bg='beige')
     canvas.pack()
     canvas.bind('<ButtonPress-1>', self.onStart)  # click
     canvas.bind('<B1-Motion>', self.onGrow)  # and drag
     canvas.bind('<Double-1>', self.onClear)  # delete all
     canvas.bind('<ButtonPress-3>', self.onMove)  # move latest
     self.canvas = canvas
     self.drawn = None
     self.kinds = [canvas.create_oval, canvas.create_rectangle]
示例#27
0
    def __init__(self, **kwargs):
        super(ScrollingFrame, self).__init__(**kwargs)

        style = Style()

        canvas = Canvas(master=self)
        scrollbar = Scrollbar(master=self, command=canvas.yview)
        canvas.configure(yscrollcommand=scrollbar.set)
        self.inner = inner = Frame(master=canvas)

        self.inner.bind(
            '<Configure>',
            lambda e: canvas.configure(scrollregion=canvas.bbox('all')))

        inner_id = canvas.create_window((0, 0), window=self.inner, anchor='nw')
        canvas.pack(side='left', fill='both', expand=True)
        scrollbar.pack(side='right', fill='y')

        def _bind_mouse(event=None):
            canvas.bind_all("<4>", _on_mousewheel)
            canvas.bind_all("<5>", _on_mousewheel)
            canvas.bind_all("<MouseWheel>", _on_mousewheel)

        def _unbind_mouse(event=None):
            canvas.unbind_all("<4>")
            canvas.unbind_all("<5>")
            canvas.unbind_all("<MouseWheel>")

        def _on_mousewheel(event):
            """Linux uses event.num; Windows / Mac uses event.delta"""
            if event.num == 4 or event.delta > 0:
                canvas.yview_scroll(-1, "units")
            elif event.num == 5 or event.delta < 0:
                canvas.yview_scroll(1, "units")

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

        inner.bind('<Configure>', _configure_inner)

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

        canvas.bind('<Configure>', _configure_canvas)

        canvas.bind("<Enter>", _bind_mouse)
        canvas.bind("<Leave>", _unbind_mouse)
示例#28
0
class BildaufCanvas:
    def __init__(self, frame, baseheight, bildname, im, pointer):
        self.frame = frame
        self.baseheight = baseheight
        self.bildname = bildname
        self.pointer = pointer
        self.canvas = 1

    def ShowBild(self, frame, baseheight, bildname, im, pointer):
        #im=Image.open(bildname).convert("L")
        width, height = im.size
        wpercent = baseheight / height  # Bildgroesse anpassen
        newwidth = width * wpercent
        newwidth = int(newwidth)
        newsize = (newwidth, baseheight)  # Groesse als tuple
        imnew = im.resize(newsize)
        self.canvas = Canvas(
            frame, height=baseheight, width=baseheight, bg="black"
        )  # Leinwand = Canvas definieren, auf der das Bild im Frame erscheint
        self.canvas.pack(padx=5, side="left")

        self.canvas.bind("<Enter>", lambda event: onenter(pointer))
        self.canvas.bind("<Leave>", lambda event: onleave(bildname))
        self.canvas.bind("<Double-Button-1>", lambda event: ondouble(pointer))

        self.canvas.image = ImageTk.PhotoImage(
            imnew
        )  # Bild mit neuen Maßen wird mit der Leinwand = Canvas verbunden
        bild = self.canvas.create_image(0,
                                        0,
                                        image=self.canvas.image,
                                        anchor='nw')  # Bild wird angezeigt

    def ChangeBild(self, frame, baseheight, bildname, im):
        #im=Image.open(bildname)
        width, height = im.size
        wpercent = baseheight / height  # Bildgroesse anpassen
        newwidth = width * wpercent
        newwidth = int(newwidth)
        newsize = (newwidth, baseheight)  # Groesse als tuple
        imnew = im.resize(newsize)
        self.canvas.image = ImageTk.PhotoImage(
            imnew
        )  # Bild mit neuen Maßen wird mit der Leinwand = Canvas verbunden
        bild = self.canvas.create_image(0,
                                        0,
                                        image=self.canvas.image,
                                        anchor='nw')  # Bild wird angezeigt

    def deleteBild(self):
        self.canvas.pack_forget()
    def _create_canvas(self, width, height):
        """
        Create a canvas
        :param width: Width of the canvas
        :param height: Height of the Canvas
        :return: Canvas
        """
        canvas = Canvas(self, width=width, height=height)
        canvas.pack()
        canvas.bind('<ButtonPress-1>', self._key_button_1_press)
        canvas.bind('<B1-Motion>', self._key_button_1_motion)
        canvas.bind('<ButtonRelease-1>', self._key_button_1_release)

        return canvas
示例#30
0
def draw_ROI(img, scale_horizontal, scale_vertical):
    draw_ROI_window = tk.Toplevel(Globals.tab3)
    draw_ROI_window.grab_set()
    local_frame= Frame(draw_ROI_window, bd = 2, relief=SUNKEN)
    local_frame.grid_rowconfigure(0,weight=1)
    local_frame.grid_columnconfigure(0, weight=1)

    local_canvas = Canvas(local_frame, bd=0)
    local_canvas.grid(row=0,column=0, sticky=N+S+E+W)

    w = 10 + img.width()
    h = 10 + img.height()
    draw_ROI_window.geometry("%dx%d+0+0" % (w, h))

    local_canvas.create_image(0,0,image=img,anchor="nw")
    local_canvas.config(scrollregion=local_canvas.bbox(ALL), cursor='arrow')
    local_canvas.image= img
    
    rectangle = local_canvas.create_rectangle(0,0,0,0,outline='green')

    def buttonPushed(event):
        Globals.map_dose_ROI_x_start.set(event.x)
        Globals.map_dose_ROI_y_start.set(event.y)
        
    def buttonMoving(event):
        local_canvas.coords(rectangle, Globals.map_dose_ROI_x_start.get(), Globals.map_dose_ROI_y_start.get(), \
            event.x, event.y)

    def buttonReleased(event):
        Globals.map_dose_ROI_x_end.set(event.x)
        Globals.map_dose_ROI_y_end.set(event.y)
        local_canvas.coords(rectangle, Globals.map_dose_ROI_x_start.get(), Globals.map_dose_ROI_y_start.get(),\
            Globals.map_dose_ROI_x_end.get(), Globals.map_dose_ROI_y_end.get())
        local_canvas.itemconfig(rectangle, outline='Blue')
        answer = messagebox.askquestion("Question","Happy with placement?", parent=draw_ROI_window)
        if(answer=='yes'):
            Globals.map_dose_ROI_x_start.set(Globals.map_dose_ROI_x_start.get()*scale_horizontal)
            Globals.map_dose_ROI_y_start.set(Globals.map_dose_ROI_y_start.get()*scale_vertical)
            Globals.map_dose_ROI_x_end.set(Globals.map_dose_ROI_x_end.get()*scale_horizontal)
            Globals.map_dose_ROI_y_end.set(Globals.map_dose_ROI_y_end.get()*scale_vertical)
            prepare_Image()
            draw_ROI_window.destroy()
    
    local_canvas.bind("<B1-Motion>", buttonMoving)
    local_canvas.bind("<Button-1>", buttonPushed)
    local_canvas.bind("<ButtonRelease-1>", buttonReleased)

    local_frame.pack(fill='both', expand=1)
示例#31
0
    def frame_game(self):
        """Tworzenie obszaru gry"""
        frame_main = Frame(self.master,
                           width=WINDOW_WIDTH,
                           height=WINDOW_HEIGHT)
        frame1 = Frame(frame_main)
        canvas1 = Canvas(frame1,
                         width=WINDOW_WIDTH,
                         height=float((1 / 7) * WINDOW_HEIGHT),
                         background="blue")
        canvas1.place(x=0, y=0)
        canvas1.pack()
        frame1.pack(side=TOP)

        frame2 = Frame(frame_main)
        canvas2 = Canvas(frame2,
                         width=WINDOW_WIDTH,
                         height=float((6 / 7) * WINDOW_HEIGHT),
                         background="Green")
        canvas2.place(x=0, y=0)
        canvas2.pack()
        frame2.pack(side=TOP)

        frame_main.pack(side=LEFT)

        self.action.draw_circle(self.table, canvas2)
        self.action.one_circle(canvas1)
        self.action.reset_button(self.table, canvas1, canvas2)

        canvas1.bind(
            '<Button-1>',
            lambda e: self.action.game(self.table, canvas1, canvas2, e))
        canvas2.bind(
            '<Button-1>',
            lambda e: self.action.game(self.table, canvas1, canvas2, e))
        canvas1.bind('<Motion>', lambda e: self.action.move_circle(canvas1, e))
        canvas2.bind('<Motion>', lambda e: self.action.move_circle(canvas1, e))
示例#32
0
        def __init__(self, parent=None):
            self.w, self.h = 611, 320
            self.merid = 180
            master = Tk()
            master.title('OCR Tools')
            canvas = Canvas(master, width=self.w, height=self.h)
            canvas.pack()
            canvas.bind('<ButtonPress-1>', self.onStart)
            canvas.bind('<B1-Motion>', self.onGrow)
            canvas.bind('<Double-1>', self.onClear)
            canvas.bind('<ButtonRelease-1>', self.onRelease)
            self.canvas = canvas
            self.drawn = None
            self.kind = canvas.create_rectangle
            self.coords = []

            f_lmap = dirname + '/images/lambert_cylindrical.gif'
            self.tk_im = PhotoImage(file=f_lmap)
            self.canvas.create_image(0, 0, anchor="nw", image=self.tk_im)
示例#33
0
    def createButton(self, btn: int, coords: tuple[int]) -> Canvas:
        def hoverEvent(clr: str):
            cnv.itemconfigure(tagOrId=cir, outline=clr)
            cnv.itemconfigure(tagOrId=poly, outline=clr, fill=clr)

        cnv = Canvas(master=self, height=BTN_SIZE, width=BTN_SIZE)
        # create outline
        cir: int = cnv.create_oval(0,
                                   0,
                                   BTN_SIZE - 1,
                                   BTN_SIZE - 1,
                                   outline=CLR_BTNS)
        # create symbol
        poly: int = cnv.create_polygon(*coords,
                                       outline=CLR_BTNS,
                                       fill=CLR_BTNS)
        # bind hover/click
        cnv.bind(sequence='<Enter>', func=lambda _: hoverEvent(CLR_BTN_HOVER))
        cnv.bind(sequence='<Leave>', func=lambda _: hoverEvent(CLR_BTNS))
        cnv.bind(sequence='<ButtonRelease-1>',
                 func=lambda e, b=btn: self.sendInput(e, b))
        # place the canvas
        cnv.grid(column=[0, 2, 2, 4][btn], row=0)
        return cnv
示例#34
0
def createGUIField():
    for i in range(Model.x, 0, -1):
        for j in range(Model.y - 1, -1, -1):
            c = Canvas(window,
                       width=currentModeSettings[0],
                       height=currentModeSettings[0],
                       highlightthickness=0)
            c.create_rectangle(0,
                               0,
                               currentModeSettings[0],
                               currentModeSettings[0],
                               fill='dark grey',
                               outline='black',
                               width=1)

            c.bind("<Button-1>",
                   lambda event, row=i - 1, column=j: mouseButton1(
                       event, row, column))
            if sys.platform in ("win32", "win64"):
                # windows: right mouse button = Button3
                c.bind("<Button-3>",
                       lambda event, row=i - 1, column=j: mouseButton3(
                           event, row, column))
            else:
                # macOs: right mouse button = Button2
                c.bind("<Button-2>",
                       lambda event, row=i - 1, column=j: mouseButton3(
                           event, row, column))

            c.grid(row=i, column=j)

    global firstMove
    firstMove = True

    labelGameOver.config(text="")
    labelNumberOfFlags.config(text=Model.amountMines.__str__())
示例#35
0
class GameUI(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.game = Game()
        self.row, self.col = 0, 0
        self.init_UI()


    def init_UI(self):
        self.pack(fill=BOTH, expand=1)

        self.canvas = Canvas(self,
            width=WIDTH,
            height=HEIGHT,
            highlightthickness=0,
            relief='ridge',
            bg='gray10'
        )
        self.canvas.pack(fill=BOTH, side=TOP)

        Button(self,
            text='RESTART',
            height=24,
            fg='white',
            bg='gray20',
            activeforeground='white',
            activebackground='gray15',
            border=0,
            font=('Arial', 12, 'bold'),
            highlightthickness=0,
            relief='ridge',
            command=self.restart
        ).pack(fill=BOTH, side=BOTTOM)

        self.draw_grid()
        self.canvas.bind('<Button-1>', self.play)


    def restart(self):
        self.game = Game()
        self.row, self.col = 0, 0
        self.canvas.delete('all')
        self.draw_grid()


    def draw_grid(self):
        for i in range(self.game.width + 1):
            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill='gray25')

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = HEIGHT - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill='gray25')

        self.board = [ [ self.game.get_cell_value(x, y) for x in range(self.game.width + 1) ] for y in range(self.game.height + 1) ]
        self.load_board(self.board)


    def load_board(self, board):
        for y in range(self.game.height + 1):
            for x in range(self.game.width + 1):
                player = self.game.get_cell_value(y, x)
                if player != ' ':
                    self.row, self.col = (self.game.width - 1) - x, y
                    self.draw_player(player)


    def play(self, event):
        if self.game.get_winner():
            return

        x, y = event.x, event.y

        if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN:
            row, col = int((y - MARGIN)  / SIDE), int((x - MARGIN) / SIDE)
            real_x, real_y = col, (self.game.width - 1) - row

            if self.game.is_cell_free(real_x, real_y):
                self.row, self.col = row, col
                player = self.game.get_next_players_turn()
                self.game.make_move(real_x, real_y, player)
                self.draw_player(player)
                winner = self.game.get_winner()
                if winner:
                    self.draw_victory(winner)


    def draw_player(self, player):
        if self.row >= 0 and self.col >=0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1

            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                fill=self.get_color(player),
                outline=''
            )

            x = x0 + SIDE / 2
            y = y0 + SIDE / 2

            self.canvas.create_text(
                x, y,
                text=player,
                fill='white',
                font=('Arial', 12)
            )


    def draw_victory(self, winner):
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 8
        self.canvas.create_oval(
            x0, y0, x1, y1,
            fill=self.get_color(winner),
            outline=''
        )

        x = y = MARGIN + 4 * SIDE + SIDE
        message = '{} player wins'.format(winner)
        self.canvas.create_text(
            x, y,
            text=message,
            fill='white',
            font=('Arial', 28)
        )


    def get_color(self, player):
        return 'dark slate gray' if player == 'X' else 'sea green'
示例#36
0
class Board(Tk):
    def __init__(self, width, height, cellSize,player=None,logicBoard=None):
        """

        :param width: largeur du plateau
        :param height: hauteur du plateau
        :param cellSize: largeur des cases
        :param player: joueur
        :param logicBoard: plateau logique (liste de liste)
        """
        Tk.__init__(self)
        self.cellSize = cellSize
        self.guiBoard = Canvas(self, width=width, height=height, bg="bisque")
        self.currentFixedLabel = FixedLabel(self,"CURRENT PLAYER : ",16,0)
        self.currentVariableLabel = VariableLabel(self,18,0,"string")
        self.bluePointsFixedLabel = FixedLabel(self,"BLUE CAPTURES : ",16,2)
        self.bluePointsVariableLabel = VariableLabel(self,18,2,"integer")
        self.redPointsFixedLabel = FixedLabel(self,"RED CAPTURES : ",16,4)
        self.redPointsVariableLabel = VariableLabel(self,18,4,"integer")
        self.logicBoard=logicBoard
        if not(logicBoard):
            self.logicBoard=dr.initBoard(DIMENSION)
        self.player=player
        if not(player):
            self.player=1
        self.hasPlayed=False
        self.hasCaptured=False
        self.guiBoard.bind("<Button -1>", self.bindEvent)
        self.initiateBoard()
        self.guiBoard.grid(rowspan=DIMENSION+1,columnspan=DIMENSION+1,row=0,column=4)

    def getBoard(self):
        return(self.logicBoard)

    def getPlayer(self):
        return(self.player)

    def initiateBoard(self):

        for i in range(DIMENSION):
            for j in range(DIMENSION):
                coordX1 = (i * self.cellSize)
                coordY1 = (j * self.cellSize)
                coordX2 = coordX1 + self.cellSize
                coordY2 = coordY1 + self.cellSize
                color = "white" if i%2 == j%2 else "black"
                cell = self.logicBoard[j][i]
                guiCell=self.draw_rectangle(coordX1, coordY1, coordX2, coordY2, color, "r"+str(i)+str(j))
                if cell !=0:
                    pawnColor = "red" if cell > 0 else "blue"
                    pawn=self.draw_circle(coordX1, coordY1, coordX2, coordY2, pawnColor, "c"+str(i)+str(j),pawnColor)

    def draw_rectangle(self,coordX1,coordY1,coordX2,coordY2,color,tags):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :return: Id du rectangle
        """
        self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags)
        return(self.guiBoard.create_rectangle(coordX1,coordY1,coordX2,coordY2,fill=color,outline="black",tags=tags))
    def draw_circle(self, coordX1, coordY1, coordX2,coordY2, color, tags,outline):
        """

        :param coordX1: coordonnée x du coin supérieur gauche du rectangle
        :param coordY1: coordonnée y du coin supérieur gauche du rectangle
        :param coordX2: coordonnée x du coin inférieur droit du rectangle
        :param coordY2: coordonnée y du coin inférieur droit du rectangle
        :param color: couleur du rectangle
        :param tags: tags
        :param outline: couleur du bord du cercle
        :return: Id du cercle
        """
        return(self.guiBoard.create_oval(coordX1,coordY1,coordX2,coordY2,fill=color,outline=outline,tags=tags))

    def findLength(self,i,j,ancientSelectedCellTags):

        """

        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonne
        :param ancientSelectedCellTags: tags de la case anciennement selectionnée
        :return: longueur
        """
        departJ=int(ancientSelectedCellTags[0][1])
        departI=int(ancientSelectedCellTags[0][2])
        length=None
        if(departI!=i):
            isDiago=abs(j-departJ)/abs(i-departI)

            if(isDiago==1):#la case d'arrivée se trouve sur la diagonale
                length=( ((j-departJ)**2) + ((i-departI)**2) )**(1/2) #recherche de l'hypothenuse
                length/=(2)**(1/2) #divisé par racine de 2 car l'hypothenuse d'un triangle avec 2 coté de longueur 1 = racine de 2
        return(length)

    def findDirection(self,i,j,ancientSelectedCellTags):
        """

        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonne
        :param ancientSelectedCellTags: tags de la case anciennement selectionnée
        :return: direction
        """
        dirI=(i-int(ancientSelectedCellTags[0][2]))/abs(i-int(ancientSelectedCellTags[0][2]))
        dirJ=(j-int(ancientSelectedCellTags[0][1]))/abs(j-int(ancientSelectedCellTags[0][1]))

        direction="L"
        if (dirJ==self.player): direction="R"
        if(dirI==self.player): direction+="B"
        return(direction)

    def enfOfGame(self):
        end=dr.checkEndOfGame(self.logicBoard,self.player)
        if (end is False): return #le jeu n'est pas fini
        self.guiBoard.unbind("<Button -1>")
        if(end!=0):
            winner="RED PLAYER" if end==1 else "BLUE PLAYER"
            text=winner + " WON"
        else:
            text = "DRAW"
        FixedLabel(self,text,16,6)


    def changePlayer(self,cellId,i,j):

        """

        :param cellId: Id du dernier pion joué
        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonn
        """
        self.player=-self.player
        val="RED" if self.player ==1 else "BLUE"
        self.currentVariableLabel.setVar(val)
        self.hasPlayed=False
        self.hasCaptured=False
        dr.becomeKing(self.logicBoard,j,i)
        self.enfOfGame()
        if (dr.isKing(self.logicBoard,j,i)): self.guiBoard.itemconfig(cellId,outline="gold",width=2)

    def coordToLetter(self,j):
        """

        :param j: coordonée de la colonne
        :return: coordonnée de la colonne en format lettre
        """
        return(chr(int(j)+97))


    def moveGuiPiece(self,i,j,ancientSelectedCellTags,ancientSelectedCellCoordI,ancientSelectedCellCoordJ,ancientSelectedCellId,playerColor):
        """

        :param i: coordonnée de la ligne
        :param j: coordonnée de la colonn
        :param ancientSelectedCellTags: tags de la case précédemment sélectionnée
        :param ancientSelectedCellCoordI: coordonnée x de la case précédemment sélectionnée
        :param ancientSelectedCellCoordJ: coordonnée y de la case précédemment sélectionnée
        :param ancientSelectedCellId: id de la case précédemment sélectionnée
        :param playerColor: couleur du joueur (red ou blue)
        """
        length=self.findLength(j,i,ancientSelectedCellTags)#chercher la longueur du mouvement

        if (not(length)): return
            #Le mouvement n'est pas autorisé, case d'arrivée n'est pas sur la diagonale

        direction=self.findDirection(j,i,ancientSelectedCellTags)#chercher la destination
        errCode=dr.checkMove(self.logicBoard,ancientSelectedCellCoordI,ancientSelectedCellCoordJ,direction,self.player,moves=length,hasPlayed=self.hasPlayed,hasCaptured=self.hasCaptured)

        if (errCode==NO_ERROR):
            #Le mouvement est autorisé
            dest,cap=dr.movePiece(self.logicBoard,ancientSelectedCellCoordI,ancientSelectedCellCoordJ,direction,moves=length)
            tag="c"+str(dest[1])+str(dest[0])
            self.guiBoard.delete(ancientSelectedCellId)#supression du pion déplacé

            if (cap):
                self.guiBoard.delete("c"+str(cap[1])+str(cap[0]))#supression du pion capturé
                self.hasCaptured=True
                dr.capture(self.logicBoard,cap[0],cap[1])
                if (playerColor=="red"):
                    self.redPointsVariableLabel.setVar(self.redPointsVariableLabel.getVar().get()+1)
                else:
                    self.bluePointsVariableLabel.setVar(self.bluePointsVariableLabel.getVar().get()+1)

            destCoordX1,destCoordY1,destCoordX2,destCoordY2=self.getGuiCoord(dest[1],dest[0])
            currentCellId=self.draw_circle(destCoordX2,destCoordY2,destCoordX1,destCoordY1, playerColor, tag,playerColor)#placement du pion déplacé

            if (cap): self.selectPawn(currentCellId,tag)#Après capture, le pion est toujours sélectionné
            self.hasPlayed=True

            if(not(self.hasCaptured)): self.changePlayer(currentCellId,i,j)#Aucune capture, changement de joueur

        else:
            departA=self.coordToLetter(ancientSelectedCellTags[0][1])
            departB=str(int(ancientSelectedCellTags[0][2])+1)
            destA=self.coordToLetter(i)
            destB=str(j+1)
            message="le coup "+departA+departB+"-"+destA+destB+" n'est pas permis"+"\n"+dr.strerr(errCode)
            MessageBox("ERROR "+str(errCode),message)




    def selectPawn(self,currentCellId,tag):
        """

        :param currentCellId: id de la case a selectionner
        :param tag: tags du pion
        """
        self.guiBoard.itemconfig(currentCellId,fill="green",tags=(tag,"selected"))

    def deselectPawn(self,ancientSelectedCellId,playerColor,ancientSelectedCellTags):
        """

        :param ancientSelectedCellId: id de la case précédemment sélectionnée
        :param playerColor: couleur du joueur (red ou blue)
        :param ancientSelectedCellTags: tags de la case précédemment sélectionnée
        """
        self.guiBoard.itemconfig(ancientSelectedCellId,fill=playerColor,tags=ancientSelectedCellTags[0])

    def getGuiCoord(self,i,j):

        """

        :param i: coordonnée x
        :param j: coordonnée y
        :return: les coordonnées des coins supérieur gauche et inférieur droit de la case
        """
        coordX1 = (i * self.cellSize)
        coordY1 = (j * self.cellSize)
        coordX2 = coordX1 + self.cellSize
        coordY2 = coordY1 + self.cellSize
        return(coordX1,coordY1,coordX2,coordY2)

    def bindEvent(self,event):
        i = int(event.x / self.cellSize)
        j = int(event.y / self.cellSize)
        if(dr.outside(self.logicBoard,j,i)): return
        playerColor="red" if self.player==1 else "blue"

        if(dr.caseNoire(j,i)):#Si l'on a cliqué sur une case noire

            coordX1,coordY1,coordX2,coordY2=self.getGuiCoord(i,j)
            tag="c"+str(i)+str(j)
            if (dr.isFree(self.logicBoard,j,i)):#Si l'on a cliqué sur une case vide
                currentCellId=self.guiBoard.find_withtag("r"+str(i)+str(j))[0]#recherche de l'ID de la case vide
            else:#Si l'on a cliqué sur un pion
                currentCellId=self.guiBoard.find_withtag(tag)[0]#recherche de l'ID du pion

            ancientSelectedCellId=self.guiBoard.find_withtag("selected")#recherche de l'ancienne case sélectionée

            if (ancientSelectedCellId):#Si une case à déjà été sélectionnée

                ancientSelectedCellId=ancientSelectedCellId[0]#On récupère l'id du tuple
                ancientSelectedCellTags=self.guiBoard.gettags(ancientSelectedCellId)#On récupère les tags de la case qui était selectionée
                ancientSelectedCellCoordI=int(ancientSelectedCellTags[0][1])
                ancientSelectedCellCoordJ=int(ancientSelectedCellTags[0][2])

                if (not(dr.isFree(self.logicBoard,j,i))):#Si on sélectionne une case remplie

                    if (self.hasCaptured==True):#Si l'on a déjà capturé

                        if (ancientSelectedCellCoordJ==j and ancientSelectedCellCoordI==i and dr.playerColor(self.logicBoard[j][i])==self.player):
                            #J'ai cliqué sur moi même : Tour fini
                            self.changePlayer(ancientSelectedCellId,i,j)
                            self.deselectPawn(ancientSelectedCellId,playerColor,ancientSelectedCellTags)
                            return

                    elif (dr.playerColor(self.logicBoard[j][i])==self.player):#Si on selectionne un de nos pions
                        self.deselectPawn(ancientSelectedCellId,playerColor,ancientSelectedCellTags)
                        self.selectPawn(currentCellId,tag)
                        return

                self.moveGuiPiece(i,j,ancientSelectedCellTags,ancientSelectedCellCoordJ,ancientSelectedCellCoordI,ancientSelectedCellId,playerColor)

            else:#Aucune case n'était sélectionnée

                if(not(dr.isFree(self.logicBoard,j,i))):
                    if (dr.playerColor(self.logicBoard[j][i])==self.player):
                        self.selectPawn(currentCellId,tag)
示例#37
0
class BoardArea(Observer):
    '''
    Represent the area in which the player will play.
    
    @ivar _selection: the current cell selected to move.
        If there's no selection, the value is None.
    '''
    
    def __init__(self, game, parent):
        '''Initialize the canvas, the observers and the mouse bindings.'''
        Observer.__init__(self)
        self._game = game
        self._game.add_observer(self, 'CELL_OFF')
        self._game.add_observer(self, 'CELL_ON')
        self._canvas = Canvas(parent, width=280, height=280)
        self._canvas.config(bg=CONFIG['BOARD_BG_COLOR'])
        self._canvas.grid(row=0, columnspan=4)
        self._canvas.bind("<Button-1>", self.left_button_pressed)
        self._selection = None
    
    def get_selection(self):
        '''Getter of _selection.'''
        return self._selection
    
    def set_selection(self, sel):
        '''Setter of _selection.'''
        self._selection = sel
    
    def left_button_pressed(self, event):
        '''The mouse left button was pressed, so if there's no
        selection, it's created, and if the selection exists,
        attempt to make a movement taking the selection position
        and the current position.'''
        pos = self.get_position_from_pixels(event.x, event.y)
        if pos is not None:
            if self.get_selection() is None:
                self.set_selection(pos)
                self.make_selection(pos)
            else:
                move_command = Move(self._game, self.get_selection(), pos)
                move_command.execute()
                self.clear_selection(self.get_selection())
                self.set_selection(None)
    
    def make_selection(self, pos):
        '''A selection was made.'''
        self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_SEL_COLOR'])
    
    def clear_selection(self, pos):
        '''No longer selection in the position given.'''
        self.draw_sel_rect_from_pos(pos, CONFIG['BOARD_BG_COLOR'])
    
    def draw_sel_rect_from_pos(self, pos, color):
        '''Draw the selection rectangle.'''
        rect_size = CONFIG['BOARD_RECT_SIZE']
        origin_x = pos[1] * rect_size
        origin_y = pos[0] * rect_size
        self._canvas.create_rectangle(origin_x, origin_y, \
            origin_x + rect_size, origin_y + rect_size, outline=color)
    
    def update(self, aspect, value):
        '''The board organisation in the model has changed.'''
        if aspect == 'CELL_ON':
            self.draw_circle_from_pos(value, CONFIG['CELL_COLOR'])
        elif aspect == 'CELL_OFF':
            self.draw_circle_from_pos(value, CONFIG['HOLE_COLOR'])
    
    def draw_circle_from_pos(self, pos, color):
        '''Draw a cell empty or not empty.'''
        rect_size = CONFIG['BOARD_RECT_SIZE']
        dist = CONFIG['DIST']
        origin_x = pos[1] * rect_size + dist
        origin_y = pos[0] * rect_size + dist
        corner_x = origin_x + rect_size - dist * 2
        corner_y = origin_y + rect_size - dist * 2
        self._canvas.create_oval(origin_x, origin_y, \
                                 corner_x, corner_y, fill=color)
    
    def get_position_from_pixels(self, x_coord, y_coord):
        '''Get the board position corresponding with the
        coordinates given.'''    
        pos_y = int(x_coord / CONFIG['BOARD_RECT_SIZE'])
        pos_x = int(y_coord / CONFIG['BOARD_RECT_SIZE'])
        if (pos_x, pos_y) in self._game.get_board():
            return (pos_x, pos_y)
        else:
            return None
示例#38
0
def take_screenshot_crop(path):
    pimage = _r.take_screenshot()

    _, _, width, height = pimage.getbbox()

    displays = _r.get_display_monitors()
    leftmost, topmost = 0, 0
    for d in displays:
        if d[0] < leftmost:
            leftmost = d[0]
        if d[1] < topmost:
            topmost = d[1]

    root = Tk()  # Creates a Tkinter window
    root.overrideredirect(True)  # Makes the window borderless
    root.geometry("{0}x{1}+{2}+{3}".format(width, height, leftmost, topmost))  # window size = screenshot size
    root.config(cursor="crosshair")  # Sets the cursor to a crosshair

    pimage_tk = ImageTk.PhotoImage(pimage)  # Converts the PIL.Image into a Tkinter compatible PhotoImage

    can = Canvas(root, width=width, height=height)  # Creates a canvas object on the window
    can.pack()
    can.create_image((0, 0), image=pimage_tk, anchor="nw")  # Draws the screenshot onto the canvas

    # This class holds some information about the drawn rectangle
    class CanInfo:
        rect = None
        startx, starty = 0, 0

    # Stores the starting position of the drawn rectangle in the CanInfo class
    def xy(event):
        CanInfo.startx, CanInfo.starty = event.x, event.y

    # Redraws the rectangle when the cursor has been moved
    def capture_motion(event):
        can.delete(CanInfo.rect)
        CanInfo.rect = can.create_rectangle(CanInfo.startx, CanInfo.starty, event.x, event.y)

    # Cancels screen capture
    def cancel(event):
        if event.keycode == 27:  # cancel when pressing ESC
            root.destroy()

    # Saves the image when the user releases the left mouse button
    def save_img(event):
        startx, starty = CanInfo.startx, CanInfo.starty
        endx, endy = event.x, event.y

        # Puts the starting point in the upper left and the ending point in the lower right corner of the rectangle
        if startx > endx:
            startx, endx = endx, startx
        if starty > endy:
            starty, endy = endy, starty

        crop_image = pimage.crop((startx, starty, endx, endy))
        crop_image.save(path, "PNG")
        root.destroy()  # Closes the Tkinter window

    # Binds mouse actions to the functions defined above
    can.bind("<KeyPress>", cancel)
    can.bind("<Button-1>", xy)
    can.bind("<B1-Motion>", capture_motion)
    can.bind("<ButtonRelease-1>", save_img)

    can.focus_force() # Force focus of capture screen
    root.mainloop()  # Shows the Tk window and loops until it is closed
示例#39
0
文件: game.py 项目: kevin00036/gym
class Game:

    gui_amp = 4
    FPS = 20

    def __init__(self, width, height, block_width, block_height,
                 *, task_type=TaskType.pick, human_play=False,
                 np_random=None):
        self.width = width
        self.height = height
        self.block_width = block_width
        self.block_height = block_height
        self.frame_width = width * block_width
        self.frame_height = height * block_height
        self.image = Image.new('RGB', (self.frame_width, self.frame_height),
                               'black')
        self.image_shape = (self.frame_height, self.frame_width, 3)
        self.draw = ImageDraw.Draw(self.image)

        self.state =None
        self.first_pick = True
        self.task_type = task_type

        self.player_pos = None
        self.obj_pos = None
        self.mark_pos = None

        if np_random is None:
            np_random = np.random.RandomState()
        self.randint = np_random.randint

        self.human_play = human_play
        if human_play:
            self.last_act = None

        self.tk = None

    def _seed(self, np_random):
        self.randint = np_random.randint
    
    def _randpos(self, disables=[]):
        pos = (self.randint(self.width), self.randint(self.height))
        while pos in disables:
            pos = (self.randint(self.width), self.randint(self.height))
        return pos

    def init(self, show_gui=False):
        self.show_gui = show_gui
        if show_gui:
            if self.tk is not None:
                self.tk.destroy()
            self.tk = Tk()
            self.canvas = Canvas(self.tk, 
                                 width=self.frame_width * self.gui_amp, 
                                 height=self.frame_height * self.gui_amp)
            self.canvas.pack()

        self.player_pos = self._randpos()

        self.first_pick = True
        self.state = State.start
        if self.task_type & TaskType.pick:
            self.obj_pos = self._randpos()
        else:
            self.state = State.picked
        if self.task_type & TaskType.put:
            self.mark_pos = self._randpos([self.obj_pos])

    def _get_frame_pos(self, pos):
        px = pos[0] * self.block_width + self.block_width // 2
        py = pos[1] * self.block_height + self.block_height // 2
        return px, py

    def step(self, act):
        if act is None:
            return 0
        rew = 0
        if act in Movesets:
            x, y = self.player_pos
            nx, ny = self.player_pos
            if act == Action.up:
                (nx, ny) = (x, y-1)
            elif act == Action.down:
                (nx, ny) = (x, y+1)
            elif act == Action.left:
                (nx, ny) = (x-1, y)
            elif act == Action.right:
                (nx, ny) = (x+1, y)
            real_pos = (
                max(0, min(self.width-1, nx)),
                max(0, min(self.height-1, ny)),
            )
            
            self.player_pos = real_pos
            pen = 0 if real_pos == (nx, ny) else -1
            rew += pen
        elif act == Action.pick and self.state == State.start:
            if self.obj_pos == self.player_pos:
                self.state = State.picked
                if self.first_pick:
                    self.first_pick = False
                    rew += 1
                if (not self.task_type & TaskType.put):
                    self.state = State.end
        elif act == Action.put and self.state == State.picked:
            if self.mark_pos == self.player_pos:
                self.state = State.end
                rew += 1
            else:
                self.state = State.start
                self.obj_pos = self.player_pos

        if self.state == State.end:
            rew += 5
        return rew

    def render(self):
        # clear canvas
        self.draw.rectangle((0, 0, self.frame_width, self.frame_height),
                            fill='black')

        # draw obj
        if self.obj_pos and self.state == State.start:
            px, py = self._get_frame_pos(self.obj_pos)
            self.draw.rectangle((px - 2, py - 2, px + 2, py + 2), fill='green')
            
        # draw mark
        if self.mark_pos:
            px, py = self._get_frame_pos(self.mark_pos)
            self.draw.rectangle((px - 2, py - 2, px + 2, py + 2), outline='white')

        # draw player
        px, py = self._get_frame_pos(self.player_pos)
        loc = (px - 2, py - 2, px + 2, py + 2)
        if self.state == State.picked:
            self.draw.ellipse(loc, fill=(0, 255, 255, 0))
        else:
            self.draw.ellipse(loc, fill='blue')

        if self.show_gui:
            gui_img = self.image.resize((self.frame_width * self.gui_amp,
                                         self.frame_height * self.gui_amp))
            self.pi = ImageTk.PhotoImage(gui_img)
            canvas_img = self.canvas.create_image(0, 0, anchor=NW,
                                                  image=self.pi)
            # self.canvas.create_text((self.width*self.gui_amp-20, 5), 
                                    # fill='white', text=str(self.))

            if not self.human_play:
                self.tk.update()

    def get_bitmap(self):
        arr = np.array(self.image.getdata()).reshape(self.image_shape)
        return arr.astype('float32') / 256.0

    def gui_step(self):
        if self.last_act is not None:
            rew = self.step(self.last_act)
            self.last_act = None
        else:
            rew = self.step(None)
        if abs(rew) > 1e-9:
            print('Get reward = %.2f' % rew)
        self.render()
        self.tk.after(1000//self.FPS, self.gui_step)

    def gui_start(self):
        self.canvas.bind("<Key>", self.gui_onkey)
        self.canvas.focus_set()
        self.tk.after(1000//self.FPS, self.gui_step)
        self.tk.mainloop()

    def gui_onkey(self, event):
        if event.keycode == 111 or event.keycode == 8320768:
            self.last_act = Action.up
        elif event.keycode == 116 or event.keycode == 8255233:
            self.last_act = Action.down
        elif event.keycode == 113 or event.keycode == 8124162:
            self.last_act = Action.left
        elif event.keycode == 114 or event.keycode == 8189699:
            self.last_act = Action.right
        elif event.keycode == 53 or event.keycode == 458872:
            self.last_act = Action.pick
        elif event.keycode == 52 or event.keycode == 393338:
            self.last_act = Action.put
示例#40
0
class TicTacToeGUI:

    ai = None

    def __init__(self, master):
        # Initial Frame
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)

        # Board canvas
        self.canvas = Canvas(self.frame, width=300, height=300)

        # Symbol selection buttons
        self.x_button = Button(self.frame, text='Play as X', height=4,
                               command=self.set_player_x, bg='white',
                               fg='black')
        self.o_button = Button(self.frame, text='Play as O', height=4,
                               command=self.set_player_o, bg='white',
                               fg='red')

        # Game start button and info box
        self.start_button = Button(self.frame, text="START", height=4,
                                   command=self.start, bg='white', fg='purple')
        self.info_box = Label(self.frame, text='Tic Tac Toe Game', height=4,
                              bg='white', fg='blue')

        self.clean_game_board()

    def start(self):
        """Sets up game board, starts a tic tac toe game,
        and a new AI if one doesn't exist. AI makes first move if
        playing as X
        """
        self.set_game_board()
        self.game = TicTacToe()
        self.game.start()
        if not self.ai:
            self.ai = TicTacToeAI()

        if self.ai_symbol == 'x':
            self.ai_action()

    def _board(self):
        """Draws tic tac toe board"""
        self.canvas.create_rectangle(0, 0, 300, 300, outline="black")
        self.canvas.create_rectangle(100, 300, 200, 0, outline="black")
        self.canvas.create_rectangle(0, 100, 300, 200, outline="black")

    def user_action(self, event):
        """Attempts to take action that matches user click. If the move is valid,
        then calls the AI to make the next move. If not, displays the error.
        """
        move_x = event.x // 100
        move_y = event.y // 100
        move_result = self.game.update(self.player_symbol, (move_x, move_y))
        if move_result == "Success":
            board_x = (200 * move_x + 100) / 2
            board_y = (200 * move_y + 100) / 2
            if self.player_symbol == 'x':
                self.draw_x(board_x, board_y)
            else:
                self.draw_o(board_x, board_y)
            if not self.completed():
                # Wait a bit before calling the ai, for visual style
                self.frame.after(500, self.ai_action)
        else:
            self.info_box['text'] = move_result

    def ai_action(self):
        """Gets the next move from the AI based on current game state,
        and plays.
        """
        state = self.game.get_board()
        move = self.ai.get_move(state)
        move_result = self.game.update(self.ai_symbol, move)
        if move_result == "Success":
            board_x = (200 * move[0] + 100) / 2
            board_y = (200 * move[1] + 100) / 2
            if self.ai_symbol == 'x':
                self.draw_x(board_x, board_y)
            else:
                self.draw_o(board_x, board_y)
            self.completed()

    def completed(self):
        """Checks the game status. If completed, displays the result,
        and asks whether the player would like to start another game.
        """
        status = self.game.done()
        if status == 'e':
            return False
        message = "Click to start a new game."
        if status == 't':
            message = "Tie game. " + message
        else:
            message = "Player " + status.upper() + " has won. " + message
        self.info_box.pack_forget()
        self.start_button.pack(fill="both", expand=True)
        self.start_button["text"] = message
        self.start_button["command"] = self.clean_game_board

    def draw_x(self, x, y):
        self.canvas.create_line(x + 20, y + 20, x - 20, y - 20, width=4,
                                fill="black")
        self.canvas.create_line(x - 20, y + 20, x + 20, y - 20, width=4,
                                fill="black")

    def draw_o(self, x, y):
        self.canvas.create_oval(x + 25, y + 25, x - 25, y - 25, width=4,
                                outline="red")

    def set_game_board(self):
        """Hides game start buttons, reveals the game board and info box."""
        self.start_button.pack_forget()
        self.x_button.pack_forget()
        self.o_button.pack_forget()
        self.canvas.delete(ALL)
        self.canvas.pack(fill="both", expand=True)
        self.info_box.pack(fill="both", expand=True)
        self.canvas.bind("<ButtonPress-1>", self.user_action)
        self._board()

    def clean_game_board(self):
        """Hides game board and label, reveals game start buttons."""
        self.canvas.pack_forget()
        self.info_box.pack_forget()
        self.start_button.pack_forget()
        self.x_button.pack(fill="both", expand=True)
        self.o_button.pack(fill="both", expand=True)

    def set_player_x(self):
        self.player_symbol = 'x'
        self.ai_symbol = 'o'
        self.start()

    def set_player_o(self):
        self.player_symbol = 'o'
        self.ai_symbol = 'x'
        self.start()
示例#41
0
class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def generate(self):
        n = int(self.menu_gen.get())
        seed = self.inp_seed.get()
        self.output = Generator.convert(seed, n)
        if len(self.output) > 0:
            self.generated = True
            self.butt_draw.config(    state= 'normal')
            self.chek_fullscrn.config(state= 'normal')
            self.clearOutput(self.output)

    def draw(self, n, step=False):
        p1, p2 = Draw.move(n)
        self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick)
        if step:
            self.curr_canvas.update_idletasks()

    def do(self, action, step, rainbow):
        if len(action) > 1:
            p = action[1]
        else:
            p = 1.0

        self.timebuff += step
        cmd = action[0].lower()
        if cmd == "draw":
            if rainbow:
                self.incColor()
                if self.incThickYN:
                    self.incThick(self.reverseThick, False)
            elif self.incThickYN:
                self.incThick(self.reverseThick, True)
            if self.timebuff > 1.0:
                truncate = int(self.timebuff)
                self.after(truncate, self.draw(float(p), True))
                self.timebuff -= truncate
            else:
                self.draw(float(p))
        elif cmd == "turn":
            Draw.turn(float(p))
        elif cmd == "skip":
            Draw.skip(float(p))
        elif cmd == "back":
            Draw.back(float(p))
        elif cmd == "color":
            if not rainbow:
                self.color = Color.getHexString(p)
        elif cmd == "thick":
            self.thick = int(p)
        else:
            print("Unknown command " + cmd)

    def drawAll(self, newWindow= True):
        if self.generated == True:
            self.butt_print.config(state= 'disabled')
            self.timebuff = 0.0
            self.color = Color.white()
            self.thick = 2
            l = float(self.slid_linesize.get())
            a = float(self.slid_angle.get())
            Draw.init(self.startingPoint, l, a)
            if self.fullScreen.get() == 1:
                if newWindow:
                    self.curr_canvas = dc.BigCanvas(self).canvas
                self.canvas.delete("all")
            else:
                self.curr_canvas = self.canvas
            self.curr_canvas.delete("all")
            self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get()))
            rainbow = self.rainbowCheck.get() == 1
            if rainbow or self.incThickYN:
                self.incStep = 1.0/float(self.getDrawCount(self.output))
                self.percent = 0.0
            for c in self.output:
                if c == '[':
                    Draw.push()
                elif c == ']':
                    Draw.pop()
                else:
                    for r in Rule.getDrawings():
                        if c == r[0]:
                            if len(r) > 2:
                                params = (r[1], r[2])
                            else:
                                params = (r[1],)
                            s = float(self.slid_timer.get())
                            self.do(params, s, rainbow)
                            break
            self.butt_print.config(state= 'normal')

    def incColor(self):
        self.color    = Color.getValueByPercent(self.percent)
        self.percent += self.incStep

    def incThick(self, reverse, incYN):
        maxthick = 5
        minthick = 1
        diff = maxthick - minthick
        if reverse:
            result = maxthick - int(diff * self.percent)
        else:
            result = minthick + int(diff * self.percent)
        self.thick = result
        if incYN:
            self.percent += self.incStep

    def getDrawCount(self, s):
        draw_commands = []
        for r in Rule.getDrawings():
            if r[1].lower() == "draw":
                draw_commands.append(r[0])
        draw_count = 0;
        for c in s:
            for d in draw_commands:
                if c == d:
                    draw_count += 1
                    break
        return draw_count

    def clearOutput(self, replacement=None):
        self.text_output.config(state= 'normal')
        self.text_output.delete(1.0, END)
        if replacement:
            self.text_output.insert(END, replacement)
        self.text_output.config(state= 'disabled')

    def formatRules(self, rules):
        ret = []
        for r in rules:
            entry = r[0] + " | " + r[1]
            if len(r) > 2:
                entry += " " + r[2]
            ret.append(entry)
        return ret

    def getRuleFromFormatted(self, s):
        if s:
            rule = s.split('|')
            rule[0] = rule[0].strip()
            rule[1] = rule[1].strip()
            prod = rule[1].split(" ")
            if len(prod) == 1:
                return (rule[0], prod[0])
            else:
                return (rule[0], prod[0], prod[1])

    def RefreshLists(self):
        self.list_prod.delete(0, END)
        self.list_draw.delete(0, END)

        l = self.formatRules(Rule.getProductions())
        for p in l:
            self.list_prod.insert(END, p)

        l = self.formatRules(Rule.getDrawings())
        for d in l:
            self.list_draw.insert(END, d)




    def AddProductionRule(self, edit=None):
        rule = dp.AddProductionRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeProd(edit[0])
            Rule.AddProduction(rule)
            self.RefreshLists()

    def AddDrawingRule(self, edit=None):
        rule = dd.AddDrawingRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeDraw(edit[0])
            Rule.AddDrawing(rule)
            self.RefreshLists()

    def EditProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_prod.get(idx))
            if rule:
                self.AddProductionRule(rule)

    def EditDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_draw.get(idx))
            if rule:
                self.AddDrawingRule(rule)

    def DeleteProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            Rule.removeProd(s[0])
            self.RefreshLists()

    def DeleteDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            Rule.removeDraw(s[0])
            self.RefreshLists()


    def packOutput(self):
        ret = ""
        ret += self.packAxiom()
        ret += self.packProdRules()
        ret += self.packDrawRules()
        return ret

    def packAxiom(self):
        return "@" + str(self.inp_seed.get()).strip()

    def packRules(self, rules):
        ret = "@"
        for r in rules:
            ret += "$" + str(r[0]) + "|" + str(r[1])
            if len(r) > 2:
                ret += ":" + str(r[2])
        return ret

    def packProdRules(self):
        return self.packRules(Rule.getProductions())

    def packDrawRules(self):
        return self.packRules(Rule.getDrawings())


    def parseProdRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                Rule.AddProduction((r[0], r[1]))

    def parseDrawRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                p = r[1].split(':')
                if len(p) == 1:
                    tup = (r[0], p[0])
                else:
                    tup = (r[0], p[0], p[1])
                Rule.AddDrawing(tup)


    def parseSaveFile(self, s):
        Rule.wipe()
        settings = s.split('@')
        self.inp_seed.set(str(settings[1]))
        self.parseProdRules(settings[2])
        self.parseDrawRules(settings[3])
        self.RefreshLists()


    def save(self):
        try:
            filename = filedialog.asksaveasfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'w')
                f.write(self.packOutput())
                f.close()
        except Exception as e:
            print("File IO error in save\n", e)

    def load(self):
        try:
            filename = filedialog.askopenfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'r')
                self.parseSaveFile(f.read())
                f.close()
                self.slid_linesize.set(1.0)
                self.slid_timer.set(0.0)
                self.menu_gen.set(1)
                self.clearOutput()

        except Exception as e:
            print("File IO error in load\n" + e)

    def help(self):
        help.HelpDialog(self)


    def saveImage(self):
        filename = filedialog.asksaveasfilename(**self.file_options['ps'])
        self.curr_canvas.postscript(file=filename, colormode='color')

    def click(self, event):
        self.startingPoint = (event.x, event.y)

    def clickAndRedraw(self, event):
        self.click(event)
        self.drawAll(False)

    def fileOptions(self):
        self.file_options = {}
        txt_options  = {}
        ps_options  = {}
        txt_options['defaultextension'] = '.txt'
        txt_options['filetypes'] = [('Plaintext', '.txt')]
        txt_options['initialdir'] = 'Patterns'
        ps_options['defaultextension'] = '.ps'
        ps_options['filetypes'] = [('Postscript Image', '.ps')]
        ps_options['initialdir'] = 'Images'
        self.file_options['txt'] = txt_options
        self.file_options['ps'] = ps_options

    def makeMenuBar(self):
        self.menubar = Menu(self);
        self.menubar.add_command(label="Save", command= self.save)
        self.menubar.add_command(label="Load", command= self.load)
        self.menubar.add_command(label="Help", command= self.help)
        root.config(menu= self.menubar)

    def makeInputFrame(self):
        self.inp_seed         = String()
        self.bgColor          = String()
        self.gen_value        = Int()
        self.rainbowCheck     = Int()
        self.fram_input       = Frame(self,              bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height)
        self.fram_seed        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_prod        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_draw        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_drawParams  = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_gen         = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_output      = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.menu_gen         = DropDown(self.fram_gen,  textvariable= self.gen_value, state= 'readonly')
        self.entr_seed        = Input(self.fram_seed,    textvariable= self.inp_seed)
        self.text_output      = Output(self.fram_output, width= 35, height= 10)
        self.scrl_output      = Scrollbar(self.fram_output)
        self.list_prod        = List(self.fram_prod,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.list_draw        = List(self.fram_draw,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.slid_linesize    = Slider(self.fram_drawParams,  from_= 0.1, to= 10.0,     orient= HORIZONTAL, resolution= 0.1, length= 180)
        self.slid_timer       = Slider(self.fram_drawParams,  from_= 0, to= 2,          orient= HORIZONTAL, resolution= 0.02, length= 180)
        self.slid_angle       = Slider(self.fram_drawParams,  from_= 0, to= 359,        orient= HORIZONTAL, length= 180)
        self.entr_bgcolor     = Input (self.fram_drawParams, textvariable= self.bgColor)
        self.butt_prodAdd     = Button(self.fram_prod,   text= "Add",    width=8, command= self.AddProductionRule)
        self.butt_prodEdit    = Button(self.fram_prod,   text= "Edit",   width=8, command= self.EditProductionRule)
        self.butt_prodDelete  = Button(self.fram_prod,   text= "Delete", width=8, command= self.DeleteProductionRule)
        self.butt_drawAdd     = Button(self.fram_draw,   text= "Add",    width=8, command= self.AddDrawingRule)
        self.butt_drawEdit    = Button(self.fram_draw,   text= "Edit",   width=8, command= self.EditDrawingRule)
        self.butt_drawDelete  = Button(self.fram_draw,   text= "Delete", width=8, command= self.DeleteDrawingRule)
        self.chek_incColor    = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck)
        Label(self.fram_seed,       text= "Axiom:", width=8).grid             (row=0, column=0)
        Label(self.fram_prod,       text= "Production\nRules:", width=8).grid (row=0, column=0)
        Label(self.fram_draw,       text= "Drawing\nRules:", width=8).grid    (row=0, column=0)
        Label(self.fram_drawParams, text= "Line Size:").grid                  (row=0, column=0)
        Label(self.fram_drawParams, text= "Delay (ms):").grid                 (row=1, column=0)
        Label(self.fram_drawParams, text= "Starting Angle:").grid             (row=2, column=0)
        Label(self.fram_drawParams, text= "Background Color:").grid           (row=3, column=0)
        Label(self.fram_output,     text= "Output:").grid                     (row=0, column=0)
        Label(self.fram_gen,        text= "Generations:").grid                (row=0, column=0)

        self.gen_value.set(1)
        self.menu_gen['values'] = tuple(range(1, 13))
        self.slid_linesize.set(1.0)
        self.bgColor.set( Color.default() )
        self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set)
        self.scrl_output.config(command=self.text_output.yview)

        self.fram_input.grid      (row=0, column=0)
        self.fram_seed.grid       (row=1, column=0, sticky= 'ew')
        self.fram_prod.grid       (row=2, column=0, sticky= 'ew')
        self.fram_draw.grid       (row=3, column=0, sticky= 'ew')
        self.fram_drawParams.grid (row=4, column=0, sticky= 'ew')
        self.fram_gen.grid        (row=5, column=0, sticky= 'ew')
        self.fram_output.grid     (row=6, column=0, sticky= 'ew')
        self.entr_seed.grid       (row=0, column=1, sticky= 'ew')
        self.list_prod.grid       (row=0, column=1, sticky= 'ew')
        self.butt_prodAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_prodEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew')
        self.list_draw.grid       (row=0, column=1)
        self.butt_drawAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_drawEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew')
        self.chek_incColor.grid   (row=0, column=2)
        self.slid_linesize.grid   (row=0, column=1, sticky= 'ew')
        self.slid_timer.grid      (row=1, column=1, sticky= 'ew')
        self.slid_angle.grid      (row=2, column=1, sticky= 'ew')
        self.entr_bgcolor.grid    (row=3, column=1, sticky= 'ew')
        self.menu_gen.grid        (row=0, column=1, sticky= 'ew')
        self.text_output.grid     (row=1, column=0)
        self.scrl_output.grid     (row=1, column=1, sticky= 'ns')

    def makeCanvasFrame(self):
        self.fram_canvas = Frame(self, bd=10, relief=self.style)
        self.canvas      = Canvas(self.fram_canvas, width= canvas_width, height= canvas_height)
        self.fram_canvas.grid(row=0, column=1, sticky='nesw')
        self.canvas.grid(sticky='nesw')
        self.canvas.bind("<Button-1>", self.click)
        self.curr_canvas = self.canvas

    def makeIgnitionFrame(self):
        self.fullScreen    = Int()
        self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height)
        self.butt_generate = Button(self.fram_ignition,   text= " -- GENERATE -- ", width=111, command= self.generate)
        self.butt_draw     = Button(self.fram_ignition,   text= " -- DRAW -- ",     width=100, command= self.drawAll, state= 'disabled')
        self.butt_print    = Button(self.fram_ignition,   text= "Save Image", command= self.saveImage, state= 'disabled')
        self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled')
        self.fram_ignition.grid(row=1, column=0, columnspan=2)
        self.butt_generate.grid(row=0, column=0, columnspan=2)
        self.butt_draw.grid(    row=1, column=0)
        self.butt_print.grid(   row=0, column=2, rowspan= 2, sticky='ns')
        self.chek_fullscrn.grid(row=1, column=1)

    def createWidgets(self):
        self.incThickYN    = False
        self.reverseThick  = False
        self.style         = RIDGE
        self.startingPoint = (20, 20)
        self.generated     = False
        self.fileOptions()
        self.makeMenuBar()
        self.makeInputFrame()
        self.makeCanvasFrame()
        self.makeIgnitionFrame()
示例#42
0
class ProblemBrowser(object):
    def __init__(self):
        self.action = None
        self.root = root = Tk()
        root.title('Never gonna fold you up')
        root.protocol("WM_DELETE_WINDOW", self.close)

        root.pack_propagate(True)

        scrollbar = Scrollbar(root, orient=tkinter.VERTICAL)
        self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set)
        self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        scrollbar.config(command=self.problem_list.yview)
        scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y)
        self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas())

        self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
        self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas())

        button_frame = Frame(root)
        button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT)

        # Reposition the figure so it's center of mass is at 0.5, 0.5
        v = IntVar()
        self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas())
        self.center_cb.var = v
        self.center_cb.pack(side=tkinter.TOP)

        # Use meshes.reconstruct_facets instead of polygon/hole logic.
        v = IntVar()
        self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas())
        self.reconstruct_cb.var = v
        self.reconstruct_cb.pack(side=tkinter.TOP)

        self.populate_problems()
        self.current_problem_name = None
        self.current_problem = None


    def populate_problems(self):
        self.problem_list.delete(0, tkinter.END)
        for file in sorted((get_root() / 'problems').iterdir()):
            self.problem_list.insert(tkinter.END, file.stem)


    def populate_problem_canvas(self):
        sel = self.problem_list.curselection()
        if not sel: return
        assert len(sel) == 1
        name = self.problem_list.get(sel[0])
        if name != self.current_problem_name:
            self.current_problem_name = name
            self.current_problem = load_problem(name)
        if self.current_problem:
            p = self.current_problem
            if self.center_cb.var.get():
                p = center_problem(p)
            if self.reconstruct_cb.var.get():
                facets = meshes.reconstruct_facets(p)
                facets = meshes.keep_real_facets(facets, p)
                skeleton = [e for f in facets for e in edges_of_a_facet(f)]
                p = Problem(facets, skeleton)
            draw_problem(self.problem_canvas, p)


    def run(self):
        self.root.mainloop()

    def close(self):
        if self.root:
            self.root.destroy()
            self.root = None
示例#43
0
文件: UI.py 项目: SebWitt/skyline
class SkylineUI(Frame):
    """
    GUI for the skyline game
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

    def __initUI(self):
        self.parent.title("Skyline")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self,
                             width=WIDTH,
                             height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        clear_button = Button(self,
                              text="Reset",
                              command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)

        self.__draw_grid()
        self.__draw_game()

        self.canvas.bind("<Button-1>", self.__cell_clicked)
        self.canvas.bind("<Key>", self.__key_pressed)


    def __draw_grid(self):
        """
        Draws grid divided with blue lines into 3x3 squares
        """
        for i in range(self.game.size + 3):
            color = "blue" if i % 6 == 0 else "gray"
            if i == 1 or i == self.game.size + 1:
                color = "red"

            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(x0, y0, x1, y1, fill=color)

            x0 = MARGIN
            y0 = MARGIN + i * SIDE
            x1 = WIDTH - MARGIN
            y1 = MARGIN + i * SIDE
            self.canvas.create_line(x0, y0, x1, y1, fill=color)


    def __draw_game(self):
        
        self.canvas.delete("numbers")
        for i in range(0, self.game.size):
            for j in range(0, self.game.size):
                answer = self.game.board[i][j]
                #if answer != 0:
                x = MARGIN + (j+1) * SIDE + SIDE / 2
                y = MARGIN + (i+1) * SIDE + SIDE / 2
                original = self.game.board_object.empty_board[i][j]
                color = "black" if answer == 0 else "sea green"
                self.canvas.create_text(
                    x, y, text=answer, tags="numbers", fill=color
                )
        self.__draw_hints()


    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")
        self.__draw_game()


    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:
            x0 = MARGIN + self.col * SIDE + 1
            y0 = MARGIN + self.row * SIDE + 1
            x1 = MARGIN + (self.col + 1) * SIDE - 1
            y1 = MARGIN + (self.row + 1) * SIDE - 1
            self.canvas.create_rectangle(
                x0, y0, x1, y1,
                outline="red", tags="cursor"
            )


    def __cell_clicked(self, event):
        if self.game.hasWon:
            return
        x, y = event.x, event.y
        if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN):
            self.canvas.focus_set()

            # get row and col numbers from x,y coordinates
            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

            # if cell was selected already - deselect it
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            else:
                self.row, self.col = int(row), int(col)
        else:
            self.row, self.col = -1, -1

        self.__draw_cursor()


    def __key_pressed(self, event):
        if self.game.hasWon:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234":
            self.game.board[self.row-1][self.col-1] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_game()
            self.__draw_cursor()
            if self.game.check_game():
                self.__draw_victory()


    def __draw_victory(self):
        # create text
        x = y = MARGIN + 3 * SIDE + SIDE / 2
        self.canvas.create_text(
            x, y,
            text="You win!", tags="victory",
            fill="orange", font=("Arial", 32)
        )


    def __draw_hints(self):

        #draw top hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_top[i]
            if hint == 0:
                color="white"
            x = SIDE + MARGIN + i * SIDE + SIDE / 2
            y = MARGIN + 0 * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )

        #draw bottom hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_bottom[i]
            if hint == 0:
                color="white"
            x = SIDE + MARGIN + i * SIDE + SIDE / 2
            y = MARGIN + (self.game.size+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )     

        #draw left hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_left[i]
            if hint == 0:
                color="white"
            x =  MARGIN + 0 * SIDE + SIDE / 2
            y = MARGIN + (i+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )

        #draw right hints:
        for i in range(0, self.game.size):
            color = "red"
            hint = self.game.hints_right[i]
            if hint == 0:
                color="white"
            x =  MARGIN + (self.game.size+1) * SIDE + SIDE / 2
            y = MARGIN + (i+1) * SIDE + SIDE / 2

            self.canvas.create_text(
                x, y, text=hint, tags="numbers", fill=color
            )
示例#44
0
class AppLogic(threading.Thread):

    def __init__(self, tk_root):
        self.root = tk_root
        threading.Thread.__init__(self)
        self.turn = 0
        self.update = False
        self.x = -1
        self.y = -1
        self.start()
    
    def run(self):
        self.game_gui = Canvas(self.root, width=600, height=600, background='green')
        self.game_gui.bind("<Button-1>", self.click)
        self.game_gui.focus_set()
        self.game_gui.bind("<Key>", self.key)
        self.game_gui.pack()
        for i in range(1, 8):
            self.game_gui.create_line(0, i*75, 600, i*75)
            self.game_gui.create_line(i*75, 0, i*75, 600)
        
        self.pieces = []
        for i in range(8):
            self.pieces.append([])
            for j in range(8):
                self.pieces[i].append(self.game_gui.create_oval(i*75+5, j*75+5, (i+1)*75-5, (j+1)*75-5, fill="green", outline="green"))
        
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.resizable(0,0)
        self.running = True
        config = EvaluateConfig()
        tf_util.update_memory(config.gpu_mem_fraction)
        AIPlayer.create_if_nonexistant(config)
        self.game = Othello()
        if(random() > 0.5):
            self.human = 1
        else:
            self.human = -1
        
        ai = create_player(config.model_1, config)
        #print("You are playing against", config.model_1)
        #print("Playing games with %d simulations per move" % config.game.simulation_num_per_move)
        self.side = -1
        self.draw_board()
        self.value = ai.evaluate(self.game, self.side)
        while self.running and not self.game.game_over():
            #play move
            if self.side != self.human:
                self.value = ai.evaluate(self.game, self.side)
                self.root.title("Othello (Thinking of Move) Current Value: %0.2f (1 white wins, -1 black wins)" % self.value)
                self.root.config(cursor="wait")
                t = ai.pick_move(self.game, self.side)
                self.game.play_move(t[0], t[1], self.side)
                self.draw_board()
                self.side *= -1
                self.value = ai.evaluate(self.game, self.side)
            else:
                if len(self.game.possible_moves(self.side)) == 0:
                    self.side *= -1
                    continue
                if self.side == -1:
                    color = "black"
                else:
                    color = "white"
                self.root.title("Othello (Play as %s) Current Value: %0.2f (1 white wins, -1 black wins)" % (color, self.value))
                self.root.config(cursor="")
                if self.update:
                    self.update = False
                    if (self.x, self.y) in self.game.possible_moves(self.side):
                        self.game.play_move(self.x, self.y, self.side)
                        self.draw_board()
                        self.side *= -1
            time.sleep(0.01)
        self.root.config(cursor="")
        if self.human == self.game.get_winner():
            self.root.title("Othello (You Win!)")
        elif self.game.get_winner() == 0:
            self.root.title("Othello (Its a draw!)")
        else:
            self.root.title("Othello (You Lose!)")

    def key(self, event):
        if event.char == "z":
            self.human *= -1

    def click(self, event):
        self.game_gui.focus_set()
        if self.human == self.side and not self.update:
            if self.x != event.x//75 or self.y != event.y//75:
                self.update = True
                self.x = event.x//75
                self.y = event.y//75
    
    def on_closing(self):
        self.running = False
        self.root.destroy()

    def draw_board(self):    
        for i in range(8):
            for j in range(8):
                if self.game.board[i, j] == 1:
                    self.game_gui.itemconfig(self.pieces[i][j], fill="white")
                if self.game.board[i, j] == -1:
                    self.game_gui.itemconfig(self.pieces[i][j], fill="black")
示例#45
0
class KlicketyGUI:
    """Interface pour le jeu Klickety."""
    def __init__(self):
        # initialisation des structures de données ----------------------------
        self.dim_plateau = (10,                 # nombre de colonnes du plateau
                            16)                 # nombre de lignes du plateau
        self.cote_case = 32          # la longueur du côté d'un bloc à dessiner
        self.largeur_plateau = self.cote_case * self.dim_plateau[0]
        self.hauteur_plateau = self.cote_case * self.dim_plateau[1]
        self.plateau = []
        self.compteur_de_coups = 0

        # initialisation des éléments graphiques ------------------------------
        self.window = Tk()                              # la fenêtre principale
        self.window.resizable(0, 0)           # empêcher les redimensionnements
        self.partie_haut = Frame(self.window, width=self.largeur_plateau,
                                              height=self.hauteur_plateau)
        self.partie_haut.pack(side=TOP)
        self.partie_bas = Frame(self.window)
        self.partie_bas.pack(side=BOTTOM)

        # le canevas affichant le plateau de jeu
        self.plateau_affiche = Canvas(self.partie_haut,
                                      width=self.largeur_plateau,
                                      height=self.hauteur_plateau)
        self.plateau_affiche.pack()
        self.plateau_affiche.bind('<ButtonPress-1>', self.clicPlateau)

        # le bouton "Réinitialiser"
        self.btn = Button(self.partie_bas, text='Réinitialiser',
                          command=self.reinitialiserJeu)
        self.btn.pack(fill=BOTH)

        # Zone d'affichage du nombre de coups
        self.nb_coups_affiche = Canvas(self.partie_bas,
                                       width=self.largeur_plateau, height=32)
        self.nb_coups_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Coups effectués: 0", fill="black"
        )
        self.nb_coups_affiche.pack(fill=BOTH)

        # affichage du nombre de blocs restants
        self.nb_blocs_affiche = Canvas(self.partie_bas,
                                       width=self.largeur_plateau, height=32)
        self.nb_blocs_affiche.pack(fill=BOTH)

        self.reinitialiserJeu()

        self.window.title('Klickety')
        self.window.mainloop()

    def rafraichirNombreBlocs(self, piece=None):
        """Rafraîchit l'affichage du nombre de blocs restants, sur base de la
        pièce que l'on vient de retirer."""
        self.nb_blocs_affiche.delete(ALL)
        if piece is None:  # appel initial, tous les blocs sont encore présents
            self.nb_blocs = self.dim_plateau[0] * self.dim_plateau[1]

        else:  # soustraire du nombre de blocs celui de la pièce retirée
            self.nb_blocs -= len(piece)

        self.nb_blocs_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Blocs restants: " + str(self.nb_blocs), fill="black"
        )

    def compteCoups(self, compteur_de_coups):
        """Compte le nombre de coups effectués durant cette partie."""
        self.nb_coups_affiche.delete(ALL)
        self.nb_coups_affiche.create_text(
            self.largeur_plateau // 2, self.cote_case // 2,
            text="Coups effectués: " + str(compteur_de_coups), fill="black"
        )

    def rafraichirPlateau(self):
        """Redessine le plateau de jeu à afficher."""
        # tracer les blocs
        self.plateau_affiche.delete(ALL)
        couleur_fond = "black"
        for i in range(self.dim_plateau[0]):                    # par défaut 10
            for j in range(self.dim_plateau[1]):                # par défaut 16
                case = self.plateau[i][j]
                if case is not None:  # afficher le pion
                    self.plateau_affiche.create_rectangle(
                        i * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, (j + 1) * self.cote_case,
                        outline=case, fill=case
                    )
                else:
                    self.plateau_affiche.create_rectangle(
                        i * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, (j + 1) * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond
                    )

        # tracer le contour des pièces
        # 1) tracer les séparations entre deux pièces adjacentes de
        # couleurs différentes dans la même colonne
        for i in range(0, self.dim_plateau[0]):                 # par défaut 10
            colonne = self.plateau[i]
            for j in range(1, self.dim_plateau[1]):             # par défaut 16
                if colonne[j - 1] != colonne[j]:
                    self.plateau_affiche.create_rectangle(
                        (i) * self.cote_case, j * self.cote_case,
                        (i + 1) * self.cote_case, j * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond, width=1
                    )

        # 2) tracer les séparations entre deux pièces adjacentes de
        # couleurs différentes dans la même ligne
        for i in range(1, self.dim_plateau[0]):                 # par défaut 10
            for j in range(0, self.dim_plateau[1]):             # par défaut 16
                if self.plateau[i - 1][j] != self.plateau[i][j]:
                    self.plateau_affiche.create_rectangle(
                        (i) * self.cote_case, j * self.cote_case,
                        (i) * self.cote_case, (j + 1) * self.cote_case,
                        outline=couleur_fond, fill=couleur_fond, width=1
                    )

    def clicPlateau(self, event):
        """Récupère les coordonnées de la case sélectionnée, et joue le coup
        correspondant s'il est permis."""
        # remarque: le canevas de tkinter interprète (i, j) géométriquement
        # (au lieu de (ligne, colonne)), d'où l'inversion de coordonnées dans
        # la ligne ci-dessous
        (i, j) = (event.x // self.cote_case, event.y // self.cote_case)

        if self.plateau[i][j] is not None:
            piece = set()
            detecterPiece(self.plateau, i, j, piece, self.plateau[i][j])
            #print (piece)

            if len(piece) > 1:  # si la pièce est valide, on la retire
                # retirer la piece en mettant ses cases à None
                for (p, q) in piece:
                    self.plateau[p][q] = None

                # faire descendre les blocs situés au-dessus de la pièce
                mettreAJour(self.plateau, piece)

                # tasser le restant du plateau en supprimant les colonnes vides
                eliminerColonnesVides(self.plateau)

                # rafraîchir le plateau pour répercuter les modifications
                self.rafraichirPlateau()

                self.rafraichirNombreBlocs(piece)
                self.compteur_de_coups += 1
                self.compteCoups(self.compteur_de_coups)
                messagevictoire = partieFinie(self.plateau)
                if messagevictoire:
                    self.plateau_affiche.create_text(
                        int(self.plateau_affiche.cget("width")) // 2,
                        self.cote_case // 2,
                        text=messagevictoire,
                        font=tkinter.font.Font(
                            family="Courier", size=12, weight=tkinter.font.BOLD
                        ),
                        fill="red"
                    )

    def reinitialiserJeu(self):
        """Réinitialise le plateau de jeu et les scores."""
        self.reinitialiserPlateau()
        self.rafraichirNombreBlocs()

        # réinitialiser le nombre de coups
        self.compteur_de_coups = 0
        self.nb_coups_affiche.delete(ALL)
        self.nb_coups_affiche.create_text(self.largeur_plateau // 2, self.cote_case // 2, text="Coups effectués: " + str(self.compteur_de_coups), fill="black")

    def reinitialiserPlateau(self):
        """Réinitialise le plateau de jeu."""
        # réinitialiser la matrice
        self.plateau = initialiserPlateau(*self.dim_plateau)

        # réinitialiser l'affichage
        self.plateau_affiche.delete(ALL)

        if self.plateau:
            self.rafraichirPlateau()
示例#46
0
class App:

    def __init__(self, master):
        frame = Frame(master, borderwidth=5)
        frame.grid(column=0, row=0, pady=5)

        self.state = []
        self.states = 256
        self.laststate = 2  # 0=Black, 1=White, 2=Transp.

        self.size = 16
        self.gridsz = 20

        for x in range(1024):
            self.state.append(2)

        self.screen = Canvas(frame, height=320, width=320, bg=color[2])
        self.screen.bind("<Button-1>", self.scrnclick1)
        self.screen.bind("<Button-3>", self.scrnclick2)
        self.screen.bind("<B1-Motion>", self.scrndrag)

        for x in range(16):
            self.screen.create_line((x * 20, 0, x * 20, 320), fill=color[3])
            self.screen.create_line((0, x * 20, 320, x * 20), fill=color[3])

        self.screen.grid(row=0, column=0, columnspan=5)

        frame2 = Frame(master, borderwidth=5)
        frame2.grid(column=0, row=1, pady=5)

        self.clear = Button(frame2, text="Clear", command=self.clearit)
        self.clear.grid(row=0, column=0, pady=20)

        self.doit = Button(frame2, text="Print", command=self.doit)
        self.doit.grid(row=0, column=1, pady=20)

        #self.doitlab = Label(frame2, text="(Output to stdout)");
        #self.doitlab.grid(row=1, column=1);

        self.parse = Button(frame2, text="Parse", command=self.parsetext)
        self.parse.grid(row=0, column=2, pady=20)

        self.large = 0
        self.dummy = IntVar()
        self.largeb = Checkbutton(frame2, text="Large", var=self.dummy, command=self.changesize)
        self.largeb.grid(row=0, column=3, pady=20)

        self.prev = Canvas(frame2, height=17, width=17, bg=color[2], relief=RIDGE)
        self.prev.grid(row=0, column=4, pady=20, padx=20)

        # DataParsers
        self.bmlabel = Label(frame2, text="Bitmap Data (paste hex from code)")
        self.bmlabel.grid(row=2, column=0, columnspan=5, sticky="W")

        self.bmentry = Text(frame2, width=80, height=9, font="Times 8")
        self.bmentry.bind("<Leave>", self.bmtextpaste)
        self.bmentry.grid(row=3, column=0, columnspan=5, pady=5)

        self.msklabel = Label(frame2, text="Mask Data (paste hex from code)")
        self.msklabel.grid(row=4, column=0, columnspan=5, sticky="W")

        self.mskentry = Text(frame2, width=80, height=9, font="Times 8")
        self.mskentry.bind("<Leave>", self.msktextpaste)
        self.mskentry.grid(row=5, column=0, columnspan=5, pady=5)

    def changesize(self):
        self.large = ~self.large
        if self.large:
            self.size = 32
            self.gridsz = 10
            self.states = 1024
            oldstate = self.state
            self.state = []
            for n in range(1024):
                col = (n // 2) % 16
                row = int(n // 64)
                self.state.append(oldstate[16 * row + col])
            oldstate = []
        else:
            self.size = 16
            self.gridsz = 20
            self.states = 256
            oldstate = self.state
            self.state = []
            for n in range(1024):
                if not((n % 2) or ((n // 32) % 2)):
                    self.state.append(oldstate[n])
            for n in range(256, 1024):
                self.state.append(2)
            oldstate = []

        # Insert scaling here

        self.updatescrn()
        self.prev.config(width=self.size + 1, height=self.size + 1)
        for n in range(self.states):
            self.updateprev(n)
        #self.prev.grid(row=0, column=4, padx=self.gridsz, pady=self.gridsz)

    def scrnclick1(self, event):
        self.scrnclick(event, 1)

    def scrnclick2(self, event):
        self.scrnclick(event, -1)

    def scrnclick(self, event, direction):
        if (event.x > 319) or (event.y > 319) or (event.x < 0) or (event.y < 0):
            return

        n = (event.x // self.gridsz) + self.size * (event.y // self.gridsz)

        self.state[n] += direction
        self.state[n] %= 3

        row = n % self.size
        col = n // self.size

        self.screen.create_rectangle((self.gridsz * row + 1,
                                      self.gridsz * col + 1,
                                      self.gridsz * row + self.gridsz - 1,
                                      self.gridsz * col + self.gridsz - 1),
                                     fill=color[self.state[n]], outline="")

        self.laststate = self.state[n]
        self.updateprev(n)

    def scrndrag(self, event):
        if (event.x > 319) or (event.y > 319) or (event.x < 0) or (event.y < 0):
            return

        n = (event.x // self.gridsz) + self.size * (event.y // self.gridsz)

        row = n % self.size
        col = n // self.size

        self.screen.create_rectangle((self.gridsz * row + 1,
                                      self.gridsz * col + 1,
                                      self.gridsz * row + self.gridsz - 1,
                                      self.gridsz * col + self.gridsz - 1),
                                     fill=color[self.laststate], outline="")
        self.state[n] = self.laststate

        self.updateprev(n)

    def updateprev(self, n):
        x = n % self.size + 1
        y = n // self.size + 1

        if self.large:
            pad = 12
        else:
            pad = 20

        self.prev.create_line(x + 1, y + 1, x + 2, y + 1, fill=color[self.state[n]])
        self.prev.grid(row=0, column=4, padx=pad, pady=pad)

    def updatescrn(self):
        self.screen.create_rectangle(0, 0, 320, 320, fill=color[2])
        for x in range(self.size):
            self.screen.create_line((x * self.gridsz, 0, x * self.gridsz, 320), fill=color[3])
            self.screen.create_line((0, x * self.gridsz, 320, x * self.gridsz), fill=color[3])
        for n in range(self.states):
            row = n % self.size
            col = n // self.size
            self.screen.create_rectangle((self.gridsz * row + 1,
                                          self.gridsz * col + 1,
                                          self.gridsz * row + self.gridsz - 1,
                                          self.gridsz * col + self.gridsz - 1),
                                         fill=color[self.state[n]], outline="")

    def bmtextpaste(self, event):
        string = self.bmentry.get(1.0, END)
        self.bmentry.delete(1.0, END)
        string = string.replace("\t", "")
        self.bmentry.insert(END, string)

    def msktextpaste(self, event):
        string = self.mskentry.get(1.0, END)
        self.mskentry.delete(1.0, END)
        string = string.replace("\t", "")
        self.mskentry.insert(END, string)

    def parsetext(self):
        bmstring = self.bmentry.get(1.0, END)
        bmstring = bmstring.replace(",", " ")
        bmstring = bmstring.split()

        mskstring = self.mskentry.get(1.0, END)
        mskstring = mskstring.replace(",", " ")
        mskstring = mskstring.split()

        if len(bmstring) != len(mskstring):
            print("Mismatched data. Bitmap and mask must be same size,")
            return
        elif not (len(bmstring) == 32 or len(bmstring) == 128):
            print("Size Error, input must be 32 or 128 hex bytes. ")
            return

        for n in range(self.states):
            self.state[n] = 0

        m = 0
        for entry in bmstring:
            e = int(entry, 16)
            for bit in range(8):
                self.state[m] = (e & 1)
                e = e >> 1
                m += 1

        m = 0
        for entry in mskstring:
            e = int(entry, 16)
            for bit in range(8):
                if not (e & 1):
                    self.state[m] = 2
                e = e >> 1
                m += 1

        self.updatescrn()
        for n in range(self.states):
            self.updateprev(n)

    def clearit(self):
        for n in range(self.states):
            self.state[n] = 2
            self.updateprev(n)
        self.updatescrn()
        self.bmentry.delete(0.0, END)
        self.mskentry.delete(0.0, END)

    def doit(self):
        mask = []
        bitmap = []
        numbytes = self.size * self.size // 8
        for i in range(numbytes):
            m = 0
            b = 0
            for j in range(8):
                m <<= 1
                b <<= 1
                if (self.state[(i * 8) + (7 - j)] != 2):
                    m |= 1
                if (self.state[(i * 8) + (7 - j)] == 1):
                    b |= 1
                #print((i * 8) + (7 - j), self.state[(i * 8) + (7 - j)], m)
            mask.append(m)
            bitmap.append(b)

        print("\n\nstatic char bitmap[] = {", end=' ')
        for i in range(numbytes):
            b1 = bitmap[i]
            if not(i % 8):
                print("\n\t", end=' ')
            print("0x%(b1)02x, " % vars(), end=' ')
        print("\n};")

        print("\nstatic char mask[] = {", end=' ')
        for i in range(numbytes):
            b1 = mask[i]
            if not(i % 8):
                print("\n\t", end=' ')
            print("0x%(b1)02x, " % vars(), end=' ')
        print("\n};")
示例#47
0
    pos = my_hero.findPosition(my_coord)
    try:
        if my_coord[pos-1].get("t") == 0 and pos % 10 > 0:
            my_coord[pos]["h"] = 0
            my_coord[pos-1]["h"] = 1
            my_hero.charType = PhotoImage(file = "assets/hero-left.png")
    except:
        pass
    my_map.SetTiles(canvas, my_coord, my_hero)
    
def moveTheCharRight(event):
    global my_coord
    global my_hero
    pos = my_hero.findPosition(my_coord)
    try:
        if my_coord[pos+1].get("t") == 0 and pos % 10 < 9:
            my_coord[pos]["h"] = 0
            my_coord[pos+1]["h"] = 1
            my_hero.charType = PhotoImage(file = "assets/hero-right.png")
    except:
        pass
    my_map.SetTiles(canvas, my_coord, my_hero)


canvas.bind("s", moveTheCharDown)
canvas.bind("w", moveTheCharUp)
canvas.bind("a", moveTheCharLeft)
canvas.bind("d", moveTheCharRight)
canvas.pack()
canvas.focus_set()
root.mainloop()
示例#48
0
			else:
				xplus = x+1;
			if y == 99:
				yplus = 0;
			else:
				yplus = y+1;
			neighbours = board[xplus][yplus] + board[xplus][y] + board[xplus][yminus] + board[x][yplus] + board[x][yminus] + board[xminus][yplus] + board[xminus][y] + board[xminus][yminus];
			if neighbours == 3:
				nboard[x][y] = 1;
			elif neighbours != 2:
				nboard[x][y] = 0;
			else:
				nboard[x][y] = board[x][y]
	board, nboard = nboard, board;

def loop(*args):
	if state:
		makeTurn();
		redraw();
		canvas.after(10, func=loop);

def switchState(*args):
	global state;
	state = not state;
	if state:
		loop();

canvas.bind("<Button-1>",diviveIntervention);
canvas.bind("<Button-3>",switchState);
canvas.mainloop();
class SudokuUI(Frame):
    """
    The Tkinter UI, responsible for displaying the UI.
    """
    def __init__(self, parent, game):
        self.game = game
        self.parent = parent
        Frame.__init__(self, parent)

        self.row, self.col = 0, 0

        self.__initUI()

        def __initUI(self):
            self.parent.title("Sudoku")
            self.pack(fill=BOTH, expand=1)  # Use all available space
            self.canvas = Canvas(self, width=WIDTH, heigh=HEIGHT)
            self.canvas.pack(fill=BOTH, side=TOP)  # Pull board to top of frame
            clear_button = Button(self, text="Clear answers", command=self.__clear_answers)
            clear_button.pack(fill=BOTH, side=BOTTOM)

            self.__draw_grid()
            self.__draw_puzzle()

            self.canvas.bind("<Button-1>", self.__cell_clicked)
            self.canvas.bind("<Key>", self.__key_pressed)

        def __draw_grid(self):
            """
            Draws grid divided with blue lines into 3 x 3 grid
            :return:
            """
            for i in range(10):
                color = 'blue' if i % 3 == 0 else "gray"

                x0 = MARGIN + i * SIDE
                y0 = MARGIN
                x1 = MARGIN + i * SIDE
                y1 = HEIGHT - MARGIN
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

                x0 = MARGIN
                y0 = MARGIN + i * SIDE
                x1 = WIDTH - MARGIN
                y1 = MARGIN + i * SIDE
                self.canvas.create_line(x0, y0, x1, y1, fill=color)

        def __draw_puzzle(self):
            self.canvas.delete("numbers")
            for i in xrange(9):
                for j in xrange(9):
                    answer = self.game.puzzle[i][j]
                    if answer != 0:
                        x = MARGIN + j * SIDE + SIDE / 2
                        y = MARGIN + i * SIDE + SIDE / 2
                        original = self.game.start_puzzle[i][j]
                        color = "black" if answer == original else "sea green"
                        self.canvas.create_text(x, y, text=answer, tags="number", fill=color)

        def __clear_answers(self):
            self.game.start()
            self.canvas.delete("victory")
            self.__draw_puzze()

        def __cell_clicked(self, event):  # event has x, y coords of mouse click
            if self.game.game_over:
                return

            x, y = event.x, event.y
            if (MARGIN < x < WIDTH - MARGIN) and (MARGIN < Y < HEIGHT - MARGIN):
                self.canvas.focus_set()

                # get row and col numbers from x, y coords
                row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE

                # if cell already selected then deselect it
                if (row, col) == (self.row, self.col):
                    self.row, self.col = -1, -1  # outside the grid
                elif self.game.puzzle[row][col] == 0:
                    self.row, self.col = row, col

            self.__draw_cursor()

        def __draw_cursor(self):
            self.canvas.delete("cursor")
            if self.row >= 0 and self.col >= 0:
                x0 = MARGIN + self.col * SIDE + 1
                y0 = MARGIN + self.row * SIDE + 1
                x1 = MARGIN + (self.col + 1) * SIDE - 1
                y1 = MARGIN + (self.row + 1) * SIDE - 1
                self.canvas.create_rectangle(
                    x0, y0, x1, y1,
                    outline ="red", tags ="cursor"
                )
示例#50
0
class LpoView(Frame):
    """ This class implements a LPO widget.

    This class use a canvas to draw the Hasse diagram of a LPO.
    """

    def __init__(self, parent):
        """ This method creates a new, emtpy LpoView. """
        Frame.__init__(self, parent)
        self.__parent = parent
        self.__initUI()
        
        self.__lpo = None

    def __initUI(self):
        """ Set up user interface. """
        self.pack(fill=BOTH, expand=1)
        
        self.__canvas = Canvas(self) # canvas for LPO
        self.__canvas.pack(fill=BOTH, expand=1)
        # Scroll with mouse drag gestures
        self.__canvas.bind("<ButtonPress-1>", self.__scroll_start)
        self.__canvas.bind("<B1-Motion>", self.__scroll_move)

    def __scroll_start(self, event):
        """ Scroll LPO with mouse gestures: Start of scroll event. """
        self.__canvas.scan_mark(event.x, event.y)

    def __scroll_move(self, event):
        """ Scroll LPO with mouse gestures: Drag event. """
        self.__canvas.scan_dragto(event.x, event.y, gain=1)

        
    def showLpo(self, lpo_to_show):
        """ This method show the given LPO in this LpoView. """
        self.__lpo = lpo_to_show # set LPO reference
        self.__drawLpo() # create LPO graph

    def __drawLpo(self):
        """ This method draws the LPO. """
        # draw LPO arcs (arc layer is behind event layer)
        for arc in self.__lpo.arcs:
            # LPOs consists of all transitive arcs, the view shows only user defined arcs.
            if arc.user_drawn == True: 
                self.__drawArc(arc)

        # draw events
        for id, event in self.__lpo.events.items():
            self.__drawEvent(event)

    def __drawEvent(self, event):
        """ Draw the given event. """
        self.__canvas.create_rectangle(event.position[0] - 10, event.position[1] - 10, event.position[0] + 10, event.position[1] + 10, outline="#000", fill="#AAAAAA", width=2)
        self.__canvas.create_text(event.position[0], event.position[1] + 20, text=event.label)


    def __drawArc(self, arc):
        """ Draw the given arc. """
        start_event = self.__lpo.events[arc.source] # get start event
        end_event = self.__lpo.events[arc.target] # get end event

        intersections = self.__calculateIntersections(start_event, end_event) # calculate intersection points

        # start point of arc
        start = start_event.position[0] + intersections[0][0], start_event.position[1] + intersections[0][1]
        # end point of arc
        end = end_event.position[0] + intersections[1][0], end_event.position[1] + intersections[1][1]
        # create line with arrow head as end
        self.__canvas.create_line(start[0], start[1], end[0], end[1], arrow=LAST, arrowshape=(8.6, 10, 5), width=2)


    def __calculateIntersections(self, start, end):
        """ Calculate intersection point of start and end events with the arc.

        This method calculates two vectors which describe the intersection point of the arc from the
        given start event to the given end event.
        """

        # vector from the center of the start event to the center of the end event
        vector = float(end.position[0] - start.position[0]), float(end.position[1] - start.position[1])
        #calculate a factor to scale the x-component to 10px (half of side length)
        fact = 1
        if vector[0] != 0:
            fact = 10 / math.fabs(vector[0])
        # scale the vector
        start_vector = vector[0] * fact, vector[1] * fact

        # if y-component of vector is larger than 10px or x-component is 0, scale with y-component
        if math.fabs(start_vector[1]) > 10 or vector[0] == 0:
            fact = 10 / math.fabs(vector[1])
            start_vector = vector[0] * fact, vector[1] * fact
        #calculate intersection for arc end
        if vector[0] != 0:
            fact = 10 / math.fabs(vector[0])

        end_vector = -vector[0] * fact, -vector[1] * fact

        if math.fabs(end_vector[1]) > 10 or vector[0] == 0:
            fact = 10 / math.fabs(vector[1])
            end_vector = -vector[0] * fact, -vector[1] * fact

        return start_vector, end_vector
示例#51
0
class Graph(object):
    def __init__(self, title="GoBang15", gem_sz=600, board_sz=15):
        self.title = title
        self.sz = gem_sz
        self.board_cols = board_sz
        self.board_rows = board_sz

        self.init_root()
        self.init_canvas()
        self.init_bind()

    def init_root(self):
        self.root = tk.Tk()
        self.root.title(self.title)
        self.root.geometry(str(self.sz) + "x" + str(self.sz))

    def init_canvas(self):
        self.canvas = Canvas(self.root,width=600,height=600,borderwidth=3,background='white')
        self.canvas.pack()
        # CheckerBoard
        self.startX = (600 - 15 * 30) / 2
        self.startY = (600 - 15 * 30) / 2
        for num in range(0, self.board_cols + 1):
            self.canvas.create_line(self.startX + num * 30, 0 + self.startY, self.startX + num * 30, self.startY + 450, width=2)
        for num in range(0, self.board_rows + 1):
            self.canvas.create_line(self.startX + 0, self.startY + num * 30, self.startX + 450, self.startY + num * 30, width=2)

    def init_bind(self):
        global msg
        global player_id
        global player_move
        self.root.bind("<<showmsg>>", lambda event: self.show_msg(event, msg))
        self.canvas.bind("<<update>>", lambda event: self.update_graph(event,player_id, player_move))

    def show(self):
        self.root.mainloop()

    def cross(self, X, Y):
        """
        :param X:  小方格左上角的坐标
        :param Y:
        """
        cross_sz = 10
        self.canvas.create_line(X + cross_sz, Y + cross_sz, X - cross_sz, Y - cross_sz, width=4, fill="red")
        self.canvas.create_line(X - cross_sz, Y + cross_sz, X + cross_sz, Y - cross_sz, width=4, fill="red")
    def circle(self, X, Y):
        d = 20
        self.canvas.create_oval(X - d / 2, Y - d / 2, X + d / 2, Y + d / 2, width=4, outline='green')

    def update_graph(self, event, player_id, move):
        # AI确定落子位置后,在tkinter上显示出来
        row, col = move
        boardX = col * 30 + self.startX
        boardY = row * 30 + self.startY
        if player_id == 1:
            self.cross(boardX + 15, boardY + 15) #AI用cross
        else:
            self.circle(boardX + 15, boardY + 15)


    def show_msg(self, event, msg):
        tk.messagebox.showinfo(title="Game Over", message=msg)
示例#52
0
    mouseI.parentOn(cx,cy)
    mouseI.draw()
        

"""
Global Variables, main script
"""
#global variables
WIDTH, HEIGHT = 640, 480
mouseDown = 0

#window initialization, more declarations
gwindow = Tk()
canvas = Canvas(gwindow, width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
mouseI = GraphWindow(100,100,25,25,"blue")
mouseI.setCanvas(canvas)
iwindow = Tk()
canvasi = Canvas(iwindow, width=WIDTH, height=HEIGHT, bg="#000000")
canvasi.pack()
mouseI.addInfoWindow(canvasi)

#bind in mouse handlers
canvas.bind("<Button-1>", mouseDown)
canvas.bind("<ButtonRelease-1>", mouseUp)
canvas.bind("<B1-Motion>", mouseClick)   

#initial draw and start loop
mouseI.draw()
mainloop()
示例#53
0
def simulation_canvas  (parent,**config):
    global the_canvas
    the_canvas = Canvas(parent,**config)
    the_canvas.bind("<ButtonRelease>", lambda event : model.mouse_click(event.x,event.y))
    return the_canvas
示例#54
0
class BoardArea(Observer):
    '''
    Represent the area in which the player will play.
    
    @ivar _regions: Dictionary <game cell, screen rectangle>
    @ivar _selection: the current cell selected to move.
        If there's no selection, the value is None.
    '''
    
    def __init__(self, game, parent):
        '''Initialize the canvas, the observers and the mouse bindings.'''
        
        Observer.__init__(self)
        self._game = game
        self._game.add_observer(self, 'CELL_OFF')
        self._game.add_observer(self, 'CELL_ON')
        
        self._canvas = Canvas(parent, bg=BOARD_BG_COLOR, width=280, height=280)
        self._canvas.grid(row=0, columnspan=3)
        self._canvas.bind("<Button-1>", self.left_button_pressed)
        
        self._regions = {}
        self.__init_regions(self._game)
        self._selection = None
    
    
    def get_selection(self):
        '''Getter of _selection.'''
        
        return self._selection
    
    
    def set_selection(self, sel):
        '''Setter of _selection.'''
        
        self._selection = sel
    
    
    def __init_regions(self, game):
        '''Complete the _regions dictionary.'''
        
        canvas_x = 0
        canvas_y = 0
        for x_index in range(7):
            for y_index in range(7):
                if (x_index, y_index) in game.get_board():
                    self._regions[(x_index, y_index)] =         \
                        Rectangle((canvas_x, canvas_y),         \
                        (canvas_x + BOARD_RECTANGLE_SIZE - 1,   \
                        canvas_y + BOARD_RECTANGLE_SIZE - 1))
                canvas_x += BOARD_RECTANGLE_SIZE
            canvas_x = 0
            canvas_y += BOARD_RECTANGLE_SIZE
    
    
    def left_button_pressed(self, event):
        '''The mouse left button was pressed, so if there's no
        selection, it's created, and if the selection exists,
        attempt to make a movement taking the selection position
        and the current position.'''
        
        pos = self.get_position_from_pixels(event.x, event.y)
        if pos is not None:
            if self.get_selection() is None:
                self.set_selection(pos)
                self.make_selection(pos)
            else:
                self._game.move(self.get_selection(), pos)
                self.clear_selection(self.get_selection())
                self.set_selection(None)
    
    
    def make_selection(self, pos):
        '''A selection was made.'''
        
        self.__selection(pos, BOARD_SEL_COLOR)
    
    
    def clear_selection(self, pos):
        '''No longer selection in the position given.'''
        
        self.__selection(pos, BOARD_BG_COLOR)
    
    
    def __selection(self, pos, color):
        '''Draw the selection rectangle.'''
        
        self._regions[pos].display_on(self._canvas, outline=color)
    
    
    def update(self, aspect, value):
        '''The board organization in the model has changed.'''
        
        if aspect == 'CELL_ON':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_NOT_EMPTY_COLOR)
        elif aspect == 'CELL_OFF':
            self.draw_circle_from_rect(self._regions[value], \
                CELL_EMPTY_COLOR)
    
    
    def draw_circle_from_rect(self, rect, color):
        '''Draw a cell empty or not empty.'''
        
        origin_x = rect.upper_left()[0] + DIST
        origin_y = rect.upper_left()[1] + DIST
        corner_x = rect.lower_right()[0] - DIST
        corner_y = rect.lower_right()[1] - DIST
        
        self._canvas.create_oval(origin_x, origin_y, \
                                 corner_x, corner_y, fill=color)
    
    
    def get_position_from_pixels(self, x_coord, y_coord):
        '''Get the board position corresponding with the
        coordinates given.'''
        
        for cell, rect in self._regions.items():
            if rect.contains((x_coord, y_coord)):
                return cell
        return None
示例#55
0
class QuickHull(Tk):
	def __init__(self,points):
		Tk.__init__(self)
		board = Frame(self)
		self.title("Diagram") 

		width = 800 #setting height and width
		height = 600

		windowx = self.winfo_screenwidth()
		windowy = self.winfo_screenheight()
		x = (windowx - width)/2		#getting center
		y = (windowy - height)/2

		self.geometry("%dx%d+%d+%d" % (width,height,x,y)) #creates window of size _width by _height, and positions it at the center of the screen

		board.pack(fill=BOTH, expand=1)
	
		self.canvas = Canvas(board,height=600,width=800,background="white")
		self.canvas.place(x=0,y=0)
		
		self.drawPoints(points) #Draw points and the first line from the highest an lowest points
		

					

		
		def point(event):  #Add points by clicking on the screen
			self.canvas.create_text(event.x, event.y,text = "+")
			points.append([event.x,event.y])

		def start():
			if(points != []):
				startB.destroy()
				quickHullStart(points)
				self.nextButton()
	
		self.canvas.bind("<Button-1>", point)
		
		startB = Button(self, text = "Start QuickHull", command = start)
		startB.pack()
	
		
	
		self.mainloop()
	
				
	def nextButton(self):					#Button that steps forward one step in the QuickHull
		def callBack():
			self.animate()

		continueB = Button(self, text="-->",command=callBack)
		continueB.place(x=350,y=550)


	def animate(self):						#animation loop
		if(triList == []):
			self.onExit()
			return
		self.canvas.create_polygon(triList.pop(0),fill="red",outline="black")
			





	def onExit(self):  #Window popup signaling that the Quick Hull is complete
		alert = Tk()
		finish = Window(alert)
		finish.config(title="Complete",w = 200, h=50)
		finish.positionWindow()

		done = Label(alert,text="QuickHull Complete")
		done.pack()

		ok = Button(alert,text="OK",command=alert.destroy)
		ok.pack()
		alert.mainloop()
		return
		


	def drawPoints(self,points):			#Draw points Imported from a file
		for p in points:
			self.canvas.create_text(p[0],p[1],text="+")
示例#56
0
            can.delete(line1[int(y/50)])
            can.delete(line2[int(y/50)])
            line1[int(y/50)] = [can.create_line(pos1, fill='#000')]
            line2[int(y/50)] = [can.create_line(pos2, fill='#f00',
                                dash=(3, 2))]
        can.update()

"""
본문
캔버스를 선언하고 원과 선들을 초기화
"""
master = Tk()
can = Canvas(master, width=500, height=500)
obj = can.create_oval(240, 240, 260, 260, fill='#aafcdf')
can.pack()

# 라인 초기화
line1 = [can.create_line(0, 0, 1, 1)]*11
line2 = [can.create_line(0, 0, 1, 1)]*11

# 애니메이션 구동
can.after(0, web)
onTarget = False

# bind: 미리 정해져 있는 입력에 따라서 함수를 실행
# 사용자의 드래그 동작은 클릭과 클릭한 후 이동으로 구성되어 있다.
can.bind('<Button-1>', onClick)
can.bind('<B1-Motion>', onDrag)

master.mainloop()
示例#57
0
class ImageViewer(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master=master, bg="gray", width=600, height=400)

        self.shown_image = None
        self.x = 0
        self.y = 0
        self.crop_start_x = 0
        self.crop_start_y = 0
        self.crop_end_x = 0
        self.crop_end_y = 0
        self.draw_ids = list()
        self.rectangle_id = 0
        self.ratio = 0

        self.canvas = Canvas(self, bg="gray", width=600, height=400)
        self.canvas.place(relx=0.5, rely=0.5, anchor=CENTER)

    def show_image(self, img=None):
        self.clear_canvas()

        if img is None:
            image = self.master.processed_image.copy()
        else:
            image = img

        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        height, width, channels = image.shape
        ratio = height / width

        new_width = width
        new_height = height

        if height > self.winfo_height() or width > self.winfo_width():
            if ratio < 1:
                new_width = self.winfo_width()
                new_height = int(new_width * ratio)
            else:
                new_height = self.winfo_height()
                new_width = int(new_height * (width / height))

        self.shown_image = cv2.resize(image, (new_width, new_height))
        self.shown_image = ImageTk.PhotoImage(Image.fromarray(
            self.shown_image))

        self.ratio = height / new_height

        self.canvas.config(width=new_width, height=new_height)
        self.canvas.create_image(new_width / 2,
                                 new_height / 2,
                                 anchor=CENTER,
                                 image=self.shown_image)

    def activate_draw(self):
        self.canvas.bind("<ButtonPress>", self.start_draw)
        self.canvas.bind("<B1-Motion>", self.draw)

        self.master.is_draw_state = True

    def activate_crop(self):
        self.canvas.bind("<ButtonPress>", self.start_crop)
        self.canvas.bind("<B1-Motion>", self.crop)
        self.canvas.bind("<ButtonRelease>", self.end_crop)

        self.master.is_crop_state = True

    def deactivate_draw(self):
        self.canvas.unbind("<ButtonPress>")
        self.canvas.unbind("<B1-Motion>")

        self.master.is_draw_state = False

    def deactivate_crop(self):
        self.canvas.unbind("<ButtonPress>")
        self.canvas.unbind("<B1-Motion>")
        self.canvas.unbind("<ButtonRelease>")

        self.master.is_crop_state = False

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

    def draw(self, event):
        self.draw_ids.append(
            self.canvas.create_line(self.x,
                                    self.y,
                                    event.x,
                                    event.y,
                                    width=2,
                                    fill="red",
                                    capstyle=ROUND,
                                    smooth=True))

        cv2.line(self.master.processed_image,
                 (int(self.x * self.ratio), int(self.y * self.ratio)),
                 (int(event.x * self.ratio), int(event.y * self.ratio)),
                 (0, 0, 255),
                 thickness=int(self.ratio * 2),
                 lineType=8)

        self.x = event.x
        self.y = event.y

    def start_crop(self, event):
        self.crop_start_x = event.x
        self.crop_start_y = event.y

    def crop(self, event):
        if self.rectangle_id:
            self.canvas.delete(self.rectangle_id)

        self.crop_end_x = event.x
        self.crop_end_y = event.y

        self.rectangle_id = self.canvas.create_rectangle(self.crop_start_x,
                                                         self.crop_start_y,
                                                         self.crop_end_x,
                                                         self.crop_end_y,
                                                         width=1)

    def end_crop(self, event):
        if self.crop_start_x <= self.crop_end_x and self.crop_start_y <= self.crop_end_y:
            start_x = int(self.crop_start_x * self.ratio)
            start_y = int(self.crop_start_y * self.ratio)
            end_x = int(self.crop_end_x * self.ratio)
            end_y = int(self.crop_end_y * self.ratio)
        elif self.crop_start_x > self.crop_end_x and self.crop_start_y <= self.crop_end_y:
            start_x = int(self.crop_end_x * self.ratio)
            start_y = int(self.crop_start_y * self.ratio)
            end_x = int(self.crop_start_x * self.ratio)
            end_y = int(self.crop_end_y * self.ratio)
        elif self.crop_start_x <= self.crop_end_x and self.crop_start_y > self.crop_end_y:
            start_x = int(self.crop_start_x * self.ratio)
            start_y = int(self.crop_end_y * self.ratio)
            end_x = int(self.crop_end_x * self.ratio)
            end_y = int(self.crop_start_y * self.ratio)
        else:
            start_x = int(self.crop_end_x * self.ratio)
            start_y = int(self.crop_end_y * self.ratio)
            end_x = int(self.crop_start_x * self.ratio)
            end_y = int(self.crop_start_y * self.ratio)

        x = slice(start_x, end_x, 1)
        y = slice(start_y, end_y, 1)

        self.master.processed_image = self.master.processed_image[y, x]

        self.show_image()

    def clear_canvas(self):
        self.canvas.delete("all")

    def clear_draw(self):
        self.canvas.delete(self.draw_ids)
示例#58
0
class text_canvas(Frame):

    def __init__(self, parent, font_size, input_handler, filename):
        Frame.__init__(self, parent)
        self.parent = parent
        self.text_font = tkFont.Font(
            family='Monaco', size=font_size, weight='bold'
        )
        self.filename = filename
        self.cheight, self.cwidth = font_size, self.text_font.measure('c')
        self.line_num_spacing = 50
        self.line_height = (
            (self.winfo_screenheight() - self.cheight)//(self.cheight + 2) - 4
        )
        self.init_UI(input_handler)

    def init_UI(self, input_handler):
        self.parent.title('')
        self.pack(fill=BOTH, expand=1)
        self.init_canvas(input_handler)

    def get_dimensions(self):
        """
        Getting the dimensions might be helpful
        for plugin writers
        """
        return {
            'cheight': self.cheight,
            'cwidth': self.cwidth,
            'line_num_spacing': self.line_num_spacing,
            'line_height': self.line_height,
            'screen_width': self.winfo_screenwidth(),
            'screen_height': self.winfo_screenheight()
        }

    def init_canvas(self, input_handler):
        self.canvas = Canvas(
            self, highlightthickness=0, width=self.winfo_screenwidth(),
            height=self.winfo_screenheight(), bg=options['background_color']
        )
        self.canvas.pack()
        self.canvas.focus_set()
        self.bind_events(input_handler)

    def clear_all(self):
        self.canvas.delete('all')

    def get_line_height(self):
        """
        return number of lines per page
        """
        return self.line_height

    def get_grid_y(self, y):
        """
        return character height * y
        in addition distane of the spaces inbetwen
        """
        return self.cheight * y + (y * 2)

    def write_line_grid(self, y, line):
        """
        Write to line of text on grid using tokens passed in
        """
        for token in line:
            self.write_text_grid(token[0], y, token[1], token[2])

    def write_text_grid(self, x, y, text, color=options['text_color']):
        """
        Write text to x, y location on grid
        """
        x_val = self.cwidth * x + self.line_num_spacing
        y_val = self.cheight * y + (y * 2)  # 2 pixel spacing between each line
        self.canvas.create_text(
            x_val, y_val, anchor='nw', text=text,
            font=self.text_font, fill=color
        )

    def write_status_line(
        self, text, textcolor=options['status_text_color'],
        backgroundcolor=options['status_background_color']
    ):
        """
        Writen a line of text to status line
        this function could take in different data if desired
        """
        y = self.line_height + 1
        self.canvas.create_rectangle(
            0, self.cheight * y + (y * 2), self.winfo_screenwidth(),
            self.cheight * y + (y * 2) + self.cheight + 4,
            fill=backgroundcolor, outline=backgroundcolor
        )
        self.write_text_grid(0, self.line_height + 1, text, textcolor)

    def draw_highlight_grid(
        self, y, x1, x2,
        highlightcolor=options['text_highlight_color']
    ):
        """
        Draw highlights onto text canvas
        i.e selections during visual mode
        """
        y_val = self.cheight * y + (y * 2)
        x1_val = self.cwidth * x1 + self.line_num_spacing
        x2_val = self.cwidth * x2 + self.line_num_spacing
        self.canvas.create_rectangle(
            x1_val, y_val, x2_val, y_val + self.cheight + 4,
            fill=highlightcolor, outline=highlightcolor
        )

    def draw_line_numbers(
        self, start,
        highlightcolor=options['line_num_highlight_color'],
        textcolor=options['line_num_text_color']
    ):
        self.canvas.create_rectangle(
            0, 0, self.line_num_spacing / 2,
            self.winfo_screenheight(),
            fill=highlightcolor, outline=highlightcolor
        )
        for i in range(self.line_height + 1):
            self.canvas.create_text(
                0, self.cheight * i + (i * 2), anchor='nw',
                text=str(start + i), font=self.text_font,
                fill=textcolor
            )

    def draw_cursor(
        self, x, y,
        highlightcolor=options['cursor_highlight_color'],
        cursorcolor=options['cursor_color']
    ):
        """
        draw cursor as well as line and column highlights
        TODO: users should have the option to disable line
        and column highlights
        """
        x_val = self.cwidth * x + self.line_num_spacing
        y_val = self.cheight * y + (y * 2)

        self.canvas.create_rectangle(
            0, y_val, self.winfo_screenwidth(),
            y_val + self.cheight + 4,
            fill=highlightcolor, outline=highlightcolor
        )
        self.canvas.create_rectangle(
            x_val, 0, x_val + self.cwidth,
            self.winfo_screenheight(), fill=highlightcolor,
            outline=highlightcolor
        )
        self.canvas.create_rectangle(
            x_val, y_val, x_val + self.cwidth,
            y_val + self.cheight + 4,
            fill=cursorcolor, outline=cursorcolor
        )

    def draw_rectangle_absolute(
        self, x1, y1, x2, y2, color
    ):
        """
        draw rectangle onto screen
        TODO: flesh out what this function should actually
        look like
        """
        self.canvas.create_rectangle(
            x1, y1, x2, y2,
            fill=color, outline=color
        )

    def bind_events(self, input_handler):
        """
        bind events for use in input_handler
        TODO: this should be cleaned up ideally into a separate handler list
        """
        input_handler.set_GUI_reference(self)
        self.canvas.bind('<Key>', input_handler.key)
        self.canvas.bind_all('<Escape>', input_handler.escape)
        self.canvas.bind_all('<Control-a>', input_handler.control_a)
        self.canvas.bind_all('<Control-b>', input_handler.control_b)
        self.canvas.bind_all('<Control-c>', input_handler.control_c)
        self.canvas.bind_all('<Control-d>', input_handler.control_d)
        self.canvas.bind_all('<Control-e>', input_handler.control_e)
        self.canvas.bind_all('<Control-f>', input_handler.control_f)
        self.canvas.bind_all('<Control-g>', input_handler.control_g)
        self.canvas.bind_all('<Control-h>', input_handler.control_h)
        self.canvas.bind_all('<Control-i>', input_handler.control_i)
        self.canvas.bind_all('<Control-j>', input_handler.control_j)
        self.canvas.bind_all('<Control-k>', input_handler.control_k)
        self.canvas.bind_all('<Control-l>', input_handler.control_l)
        self.canvas.bind_all('<Control-m>', input_handler.control_m)
        self.canvas.bind_all('<Control-n>', input_handler.control_n)
        self.canvas.bind_all('<Control-o>', input_handler.control_o)
        self.canvas.bind_all('<Control-p>', input_handler.control_p)
        self.canvas.bind_all('<Control-q>', input_handler.control_q)
        self.canvas.bind_all('<Control-r>', input_handler.control_r)
        self.canvas.bind_all('<Control-s>', input_handler.control_s)
        self.canvas.bind_all('<Control-t>', input_handler.control_t)
        self.canvas.bind_all('<Control-u>', input_handler.control_u)
        self.canvas.bind_all('<Control-v>', input_handler.control_v)
        self.canvas.bind_all('<Control-w>', input_handler.control_w)
        self.canvas.bind_all('<Control-x>', input_handler.control_x)
        self.canvas.bind_all('<Control-y>', input_handler.control_y)
        self.canvas.bind_all('<Control-z>', input_handler.control_z)
        self.canvas.bind_all("<MouseWheel>", input_handler.mouse_scroll)
        self.canvas.bind_all(
            '<Control-braceright>', input_handler.control_braceright
        )
        self.canvas.bind_all(
            '<Control-braceleft>', input_handler.control_braceleft
        )
示例#59
0
文件: view.py 项目: poussin87/haptiq
class Scene(object):
    def __init__(self, master, device, mouse_tracking=False):
        self.master = master
        self.device = device
        self.frame = tk.Frame(master)
        self.feedbackButton = tk.Button(
            self.frame,
            text="Feedback window",
            width=25,
            command=self.open_feedback
        )
        self.feedbackButton.pack()
        self.explore_canvas = Canvas(master, width=500, height=500)
        self.explore_canvas.pack()

        if mouse_tracking:
            self.explore_canvas.bind(
                '<Motion>', lambda event, device=device: motion(event, device))

        self.enable_position_feedback()
        self.network_drawings = []

        self.frame.pack()
        self.app = None
        self.update()

    def activate_key_listening(self, listener):
        # Will focus frame, needed for key binding
        self.explore_canvas.bind(
            "<Button-1>",
            lambda event,
            frame=self.explore_canvas: focus(event, frame)
        )
        self.explore_canvas.bind(
            "<Key>",
            lambda event: listener.update_pressed_key(str(event.char))
        )

    def desactivate_key_listening(self):
        self.explore_canvas.unbind("<Button-1>")
        self.explore_canvas.unbind("<Key>")

    def enable_position_feedback(self):
        self.device_cursor = self.explore_canvas.create_oval(
            self.device.position.x - 2.5, self.device.position.y - 2.5,
            self.device.position.x + 2.5, self.device.position.y + 2.5)

    def draw_network(self, network):
        self.explore_canvas.delete('all')
        self.enable_position_feedback()
        for node in network.nodes:
            pos_x = node.x - 5
            pos_y = node.y - 5
            self.explore_canvas.create_oval(
                pos_x, pos_y, pos_x + 10, pos_y + 10, fill="blue")
        for link in network.links:
            pt_a = link.first
            pt_b = link.sec
            self.explore_canvas.create_line(
                pt_a.x, pt_a.y, pt_b.x, pt_b.y)

    def update(self):
        coords = self.explore_canvas.coords(self.device_cursor)
        if len(coords) <= 3:
            self.master.after(50, self.update)
            return
        center = ((coords[0] + coords[2]) / 2, (coords[1] + coords[3]) / 2)
        self.explore_canvas.move(
            self.device_cursor,
            self.device.position.x - center[0],
            self.device.position.y - center[1])
        if self.app and not self.app.closed:
            self.app.update()
        self.master.after(50, self.update)

    def open_feedback(self):
        self.feedbackWindow = tk.Toplevel(self.master)
        self.app = Feedback(self.feedbackWindow, self.device)
示例#60
-19
class IsometricViewer:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.wireframe = True
        self.drawables = []
        self.items = {}
        self.text = ""
        self.theta = 0
        self.phi = 0
        self.scale = 0
        self.x_offset = 0
        self.y_offset = 0
        self.canvas = Canvas(Tk(), width=self.width, height=self.height)
        self.reset_viewport()
        self.init_gui()
    @property
    def camera_coords(self):
        return Point3(math.cos(self.theta) * math.cos(self.phi), -math.sin(self.theta) * math.cos(self.phi), math.sin(self.phi))
    def reset_viewport(self):
        self.theta = math.pi / 8
        self.phi = math.pi / 16
        self.scale = 1
        self.x_offset = self.width / 2
        self.y_offset = self.height / 2
    def init_gui(self):
        self.canvas.pack()
        self.canvas.focus_set()
        self.canvas.bind("<Up>", self._callback_commandline_up)
        self.canvas.bind("<Down>", self._callback_commandline_down)
        self.canvas.bind("<Left>", self._callback_commandline_left)
        self.canvas.bind("<Right>", self._callback_commandline_right)
        self.canvas.bind("=", self._callback_commandline_equal)
        self.canvas.bind("-", self._callback_commandline_minus)
        self.canvas.bind("<Shift-Up>", self._callback_commandline_shift_up)
        self.canvas.bind("<Shift-Down>", self._callback_commandline_shift_down)
        self.canvas.bind("<Shift-Left>", self._callback_commandline_shift_left)
        self.canvas.bind("<Shift-Right>", self._callback_commandline_shift_right)
        self.canvas.bind("<Shift-Return>", self._callback_commandline_shift_return)
        self.canvas.bind("<Button-1>", self._callback_button_1)
        self.canvas.bind("<B1-Motion>", self._callback_button_1_motion)
    def add_drawable(self, drawable):
        assert isinstance(drawable, Drawable)
        self.drawables.append(drawable)
    def project(self, point):
        projected = point.rotate(self.theta, self.phi)
        return Point2(projected.y * self.scale + self.x_offset, -projected.z * self.scale + self.y_offset)
    def unproject(self, point):
        return point.rotate(0, -self.phi).rotate(-self.theta, 0)
    def move_camera(self, theta, phi):
        self.theta += theta
        if self.theta > 2 * math.pi:
            self.theta -= 2 * math.pi
        elif self.theta < 0:
            self.theta += 2 * math.pi
        if -math.pi / 2 <= self.phi + phi <= math.pi / 2:
            self.phi += phi
    def clear(self):
        for item in self.items:
            self.canvas.delete(item)
    def draw_line(self, owner, p1, p2, **kargs):
        assert isinstance(p1, Point3)
        assert isinstance(p2, Point3)
        p1 = self.project(p1)
        p2 = self.project(p2)
        item = self.canvas.create_line(p1.x, p1.y, p2.x, p2.y, **kargs)
        self.items[item] = owner
        return item
    def draw_ellipse(self, owner, corners, **kargs):
        assert all(isinstance(p, Point3) for p in corners)
        item = self.draw_polygon(owner, corners, outline="#000000", smooth=1, **kargs)
        self.items[item] = owner
        return item
    def draw_polygon(self, owner, pts, **kargs):
        assert all(isinstance(p, Point3) for p in pts)
        args = []
        for p in pts:
            p = self.project(p)
            args.extend((p.x, p.y))
        item = self.canvas.create_polygon(*args, **kargs)
        self.items[item] = owner
        return item
    def draw_wireframe(self):
        for drawable in self.drawables:
            drawable.draw_wireframe(self)
    def draw(self):
        for drawable in self.drawables:
            drawable.draw(self)
    def update(self):
        self.clear()
        header = [
            "(theta, phi): ({:.3f}, {:.3f})".format(self.theta, self.phi),
            "(x, y, z): {}".format(self.camera_coords),
        ]
        text = "\n".join(header) + "\n\n" + self.text
        item = self.canvas.create_text((10, 10), anchor="nw", text=text)
        self.items[item] = None
        if self.wireframe:
            self.draw_wireframe()
        else:
            self.draw()
    def display(self):
        self.update()
        mainloop()
    def _callback_commandline_up(self, event):
        self.move_camera(0, math.pi / 16)
        self.update()
    def _callback_commandline_down(self, event):
        self.move_camera(0, -math.pi / 16)
        self.update()
    def _callback_commandline_left(self, event):
        self.move_camera(math.pi / 16, 0)
        self.update()
    def _callback_commandline_right(self, event):
        self.move_camera(-math.pi / 16, 0)
        self.update()
    def _callback_commandline_equal(self, event):
        self.scale *= 1.2
        self.update()
    def _callback_commandline_minus(self, event):
        self.scale /= 1.2
        self.update()
    def _callback_commandline_shift_up(self, event):
        self.y_offset -= 10
        self.update()
    def _callback_commandline_shift_down(self, event):
        self.y_offset += 10
        self.update()
    def _callback_commandline_shift_left(self, event):
        self.x_offset -= 10
        self.update()
    def _callback_commandline_shift_right(self, event):
        self.x_offset += 10
        self.update()
    def _callback_commandline_shift_return(self, event):
        self.reset_viewport()
        self.update()
    def _callback_button_1(self, event):
        text = []
        closest = self.canvas.find_closest(event.x, event.y)[0]
        overlapping = self.canvas.find_overlapping(event.x, event.y, event.x+1, event.y+1)
        if closest in overlapping and closest in self.items and self.items[closest] is not None:
            text.append(self.items[closest].clicked(self, event, closest))
        self.text = "\n".join(text)
        self.update()
    def _callback_button_1_motion(self, event):
        pass