Пример #1
0
class canvasInterface(interfaceScreen):
    def __init__(self,master,width,height):
        interfaceScreen.__init__(self)
        self.canvas = Canvas(master, width=width, height=height,bg='white')
        self.canvas.grid(row=0,column=1)

    """
    ---------------Interfaz con objeto dibujante---------------------
    """

    def deleteFromCanvas(self,id):
        self.canvas.delete(id)
        pass

    def create_rectangle(self,x1, y1, x2, y2,*arg,**kargs):
        return self.canvas.create_rectangle(x1, y1, x2, y2,*arg,**kargs)
        pass

    def create_line(self,x1, y1, x2,  y2, *args,**kwargs):
        return self.canvas.create_line(x1, y1, x2,  y2, *args,**kwargs)

    def create_text(self,x1, y1,*args,**kargs):
        return self.canvas.create_text(x1, y1,*args,**kargs)

    def scan_mark(self,x,y):
        self.canvas.scan_mark(x, y)
    def scan_dragto(self,x, y, *args,**kwargs):
        self.canvas.scan_dragto(x, y, *args,**kwargs)

    def winfo_height(self):
        return self.canvas.winfo_height()
    def winfo_width(self):
        return self.canvas.winfo_width()
Пример #2
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.x0=[x*0.1 for x in range(10, 15)]
        self.y0=[0 for x in range(10, 15)]
        #self.tet1 = [i for i in range(90)]
        #self.tet2 = [i for i in range(45, 135)]
        self.tet1_con = 0
        self.tet2_con = 0
        
        self.count1 = 0
        self.count2 = 0
        self.sign1 = 1
        self.sign2 = -1
        self.parent = parent
        self.initUI()
        self.parent.after(0, self.animation)
        
    def initUI(self):
        self.parent.title("Arm")        
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self)
        #self.canvas.create_line(0, 0, 200, 100+self.count, width=arm_width)
        line = Line(self.canvas, points['1'], (800/2, 400))
        arms.append(line)
        line = Line(self.canvas, 90-(points['2']-points['1']), line.cor1)
        arms.append(line)
        
        self.canvas.pack(fill=BOTH, expand=1)
        
    def animation(self):
        self.canvas.delete("all")
        #self.canvas.create_line(0, 0, 200, 100+self.count, width=arm_width)
        '''if points['1'] > 90 and self.sign1 == 1:
            self.sign1 = -1
        elif points['1'] == 45 and self.sign1 == -1:
            self.sign1 = 1
        if points['2'] > 135 and self.sign2 == 1:
            self.sign2 = -1
        elif points['2'] == 90 and self.sign2 == -1:
            self.sign2 = 1
            
        points['2']+=self.sign2
        points['1']+=self.sign1'''
        if self.count1 >= len(self.x0) and self.sign1 == 1:
            self.sign1 = -1
        if self.count1 <= 0 and self.sign1 == -1:
            self.sign1 = 1

        self.count1+=self.sign1
        tet1, tet2 = getAngles(self.x0[self.count1-1], self.y0[self.count1-1])
	print tet1, tet2
        line = arms[0].draw(tet1)
        arms[1].draw(90-(tet2+tet1), line, 'red')
        #line = arms[0].draw(points['1'])
        #arms[1].draw(90-(points['2']-points['1']), line)

        self.canvas.update()
        #self.count +=1
        self.parent.after(50, self.animation)
Пример #3
0
class Visualizer(object):

    def __init__(self, toplevel, **kwargs):
        self.toplevel = toplevel
        self.canvas = Canvas(
            self.toplevel, width=600, height=400, background='black'
        )
        self.canvas.pack()
        self._playing_lines = {}

    def add_point(self, phrase, point, color):
        if point in self._playing_lines:
            self.remove_point(phrase, point)
        if point.type == 'Rest':
            return
        if point not in phrase.points:
            return
        px,py, px2,py2 = phrase.get_line(point)
        self._playing_lines[point] = self.canvas.create_line(
            px,py, px2,py2, fill=color
        )

    def remove_point(self, phrase, point):
        if point not in self._playing_lines:
            return
        self.canvas.delete(self._playing_lines[point])
        del self._playing_lines[point]
Пример #4
0
class CoordsCanvas(object):
    def __init__(self, parent, **kwargs):
        self._canvas = Canvas(parent, **kwargs)
        self._canvas.pack(fill=BOTH, expand=YES)
        self._canvas.bind("<Double-Button-1>", self.on_double_click)
        self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click)
        self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click)
        self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click)
        self._canvas.bind("<Option-Button-1>", self.on_alt_button_click)
        self._canvas.bind("<Double-Button-1>", self.on_double_click)
        self._canvas.bind("<ButtonPress-1>", self.on_button_press)
        self._canvas.bind("<ButtonRelease-1>", self.on_button_release)
        self._event_receiver = None
        self._dragger = Dragger()

    def on_double_click(self, _):
        if hasattr(self._event_receiver, 'zoom_in'):
            self._event_receiver.zoom_in()

    def on_shift_button_click(self, _):
        if hasattr(self._event_receiver, 'zoom_out'):
            self._event_receiver.zoom_out()

    def on_ctrl_button_click(self, event):
        if hasattr(self._event_receiver, 'add'):
            self._event_receiver.add(event.x, event.y)

    def on_alt_button_click(self, event):
        if hasattr(self._event_receiver, 'remove'):
            self._event_receiver.remove(event.x, event.y)

    def on_button_press(self, event):
        self._dragger.start(event.x, event.y)

    def on_button_release(self, event):
        if hasattr(self._event_receiver, 'move'):
            self._dragger.drag_to(
                event.x, event.y,
                self._event_receiver.move)

    def create_circle(self, x, y, r, **kwargs):
        return self._canvas.create_oval(x-r, y-r, x+r, y+r, **kwargs)

    def create_text(self, x, y, **kwargs):
        return self._canvas.create_text(x, y, **kwargs)

    def get_width(self):
        return self._canvas.winfo_reqwidth()

    def get_height(self):
        return self._canvas.winfo_reqheight()

    def set_event_receiver(self, receiver):
        self._event_receiver = receiver

    def destroy(self, item):
        self._canvas.delete(item)

    def destroy_all(self):
        self._canvas.delete("all")
Пример #5
0
class CanvasFrame(Frame):
    
    def initializeCanvas(self):
        self.canvas = Canvas(self.master, width=200, height=100)
        self.canvas.pack()
        self.pack()
        
    def setup_timer(self):
        self.x = 10
        self.y = 10
        self.timer_tick()
        
        
    def timer_tick(self):
        self.canvas.delete('all')
        self.canvas.create_line(self.x, self.y, 50, 50)
        self.x = self.x + 1
        self.y = self.y + 2
        print 'in loop'
        print self.x
        print self.y
        self.master.after(1000, self.timer_tick)
        
    
    def __init__(self):
        Frame.__init__(self, Tk())
        self.pack()
        self.initializeCanvas()
        self.setup_timer()
class CanvasFrame(Frame):
    
    def __initialize_canvas(self):
        self.__canvas = Canvas(self.master,
                            width=Constants.DEFAULT_FRAME_WIDTH() + 120,
                            height=Constants.DEFAULT_FRAME_HEIGHT())
        self.__canvas.pack()
        self.pack()
        
    def __setup_timer(self):
        RefreshTimer(self.master, 10, self)
        MonsterTimer(self.master, 1000)
        
    def __setup_handlers(self):
        ArrowHandler(self.master)
        KeyMovementHandler(self.master)
        MouseClickHandler(self.master)
        
    def refresh(self):
        self.__canvas.delete('all')
        BoardPrinter.print_board(self.__canvas)
        SelectPrinter.print_selected(self.__canvas)
        TurnMenuPrinter.print_turn_menu(self.__canvas)
        
    def __init__(self):
        Frame.__init__(self, Tk())
        self.pack()
        
        self.__initialize_canvas()
        self.__setup_timer()
        self.__setup_handlers()
Пример #7
0
class Wall(object):
    MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
    MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF

    PIXEL_WIDTH = 96

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._tk_init()
        self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]

    def _tk_init(self):
        self.root = Tk()
        self.root.title("ColorWall %d x %d" % (self.width, self.height))
        self.root.resizable(0, 0)
        self.frame = Frame(self.root, bd=5, relief=SUNKEN)
        self.frame.pack()

        self.canvas = Canvas(self.frame,
                             width=self.PIXEL_WIDTH * self.width,
                             height=self.PIXEL_WIDTH * self.height,
                             bd=0, highlightthickness=0)
        self.canvas.pack()
        self.root.update()

    def set_pixel(self, x, y, hsv):
        self.pixels[self.width * y + x] = hsv

    def get_pixel(self, x, y):
        return self.pixels[self.width * y + x]

    def draw(self):
        self.canvas.delete(ALL)
        for x in range(len(self.pixels)):
            x_0 = (x % self.width) * self.PIXEL_WIDTH
            y_0 = (x / self.width) * self.PIXEL_WIDTH
            x_1 = x_0 + self.PIXEL_WIDTH
            y_1 = y_0 + self.PIXEL_WIDTH
            hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
            self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
        self.canvas.update()

    def clear(self):
        for i in range(self.width * self.height):
            self.pixels[i] = (0, 0, 0)

    def _hsv_to_rgb(self, hsv):
        rgb = colorsys.hsv_to_rgb(*hsv)
        red = self.MAX_RED * rgb[0]
        green = self.MAX_GREEN * rgb[1]
        blue = self.MAX_BLUE * rgb[2]
        return (red, green, blue)

    def _get_rgb(self, hsv):
        red, green, blue = self._hsv_to_rgb(hsv)
        red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
        green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
        blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
        return (red, green, blue)
Пример #8
0
class CoordsCanvas(object):
    def __init__(self, parent, **kwargs):
        self._canvas = Canvas(parent, **kwargs)
        self._canvas.pack(fill=BOTH, expand=YES)
        self._canvas.bind("<Double-Button-1>", self.on_double_click)
        self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click)
        self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click)
        self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click)
        self._canvas.bind("<Option-Button-1>", self.on_alt_button_click)
        self._canvas.bind("<Double-Button-1>", self.on_double_click)
        self._canvas.bind("<ButtonPress-1>", self.on_button_press)
        self._canvas.bind("<ButtonRelease-1>", self.on_button_release)
        self._event_receiver = None
        self._dragger = Dragger()

    def on_double_click(self, _):
        if hasattr(self._event_receiver, 'zoom_in'):
            self._event_receiver.zoom_in()

    def on_shift_button_click(self, _):
        if hasattr(self._event_receiver, 'zoom_out'):
            self._event_receiver.zoom_out()

    def on_ctrl_button_click(self, event):
        if hasattr(self._event_receiver, 'add'):
            self._event_receiver.add(event.x, event.y)

    def on_alt_button_click(self, event):
        if hasattr(self._event_receiver, 'remove'):
            self._event_receiver.remove(event.x, event.y)

    def on_button_press(self, event):
        self._dragger.start(event.x, event.y)

    def on_button_release(self, event):
        if hasattr(self._event_receiver, 'move'):
            self._dragger.drag_to(event.x, event.y, self._event_receiver.move)

    def create_circle(self, x, y, r, **kwargs):
        return self._canvas.create_oval(x - r, y - r, x + r, y + r, **kwargs)

    def create_text(self, x, y, **kwargs):
        return self._canvas.create_text(x, y, **kwargs)

    def get_width(self):
        return self._canvas.winfo_reqwidth()

    def get_height(self):
        return self._canvas.winfo_reqheight()

    def set_event_receiver(self, receiver):
        self._event_receiver = receiver

    def destroy(self, item):
        self._canvas.delete(item)

    def destroy_all(self):
        self._canvas.delete("all")
Пример #9
0
class GUI(object):
    def __init__(self, world):
        self.ticks = 0
        self.world = world
        self.width = world.width
        self.height = world.height

        self.root = Tk()
        self.root.title("Mars Explorer")
        window_x, window_y = self._compute_window_coords()
        self.root.geometry('%dx%d+%d+%d' %
                           (self.width, self.height, window_x, window_y))

        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.after(1, self._tick)

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

    def _tick(self):
        # Stop if done.
        if self.world.is_done():
            return

        self.world.tick()
        self._draw()

        self.ticks += 1
        self.canvas.after(1, self._tick)

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

        self.world.draw(self.canvas)
        for entity in self.world.entities:
            entity.draw(self.canvas)

        self.canvas.create_text(self.width - 20, 10, text=str(self.ticks))
        self.canvas.create_text(self.width - 70,
                                30,
                                text='Rocks in explorers: %d' %
                                self.world.rocks_in_explorers())
        self.canvas.create_text(self.width - 70,
                                50,
                                text='Rocks delivered: %d' %
                                self.world.rocks_collected)
        self.canvas.create_text(self.width - 55,
                                70,
                                text='Total rocks: %d' % self.world.num_rocks)

    def _compute_window_coords(self):
        # http://stackoverflow.com/a/14912644/742501
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_x = screen_width / 2 - self.width / 2
        window_y = screen_height / 2 - self.height / 2
        return window_x, window_y
Пример #10
0
class Screen(Observer):
    def __init__(self,parent,bg="white"):
        self.canvas=Canvas(parent,bg=bg)
        print("parent",parent.cget("width"),parent.cget("height"))

        parent.bind("<Configure>", self.resize)
        self.parent=parent
        self.width=int(self.canvas.cget("width"))
        self.height=int(self.canvas.cget("height"))
        self.models=[]
    def update(self,model):
        if model not in self.models:
            self.models.append(model)
        print("View update")
        signal=model.get_signal()
        self.plot_signal(signal,model.get_color(),model.get_name())


    def plot_signal(self,signal,color,name):
        w,h=self.canvas.winfo_width(),self.canvas.winfo_height()
        width,height=int(w),int(h)
        print(self.canvas.find_withtag("signal"+name))
        if self.canvas.find_withtag("signal"+name) :
            self.canvas.delete("signal"+name)
        if signal and len(signal) > 1:
            if name=="X-Y" :
                plot = [((x+2)*width/4, (2*y/self.m+1)*height/2) for (x, y) in signal]
            else :
                plot = [(x*width, y*height/self.m + height/2) for (x, y) in signal]

            signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal"+name)
        return

    def packing(self) :
        self.canvas.pack(fill="both", expand=1)
    def grid(self,n,m):
        self.n=n
        self.m=m
        w,h=self.canvas.winfo_width(),self.canvas.winfo_height()
        self.width,self.height=int(w),int(h)
        self.canvas.create_line(0,self.height/2.0,self.width-4,self.height/2,arrow="last",tags="line",fill="blue")
        self.canvas.create_line(self.width/2,self.height,self.width/2,5,arrow="last",tags="line",fill="blue")
        step1=self.width/n
        for t in range(1,n):
            x =t*step1
            self.canvas.create_line(x,0,x,self.height,tags="line")
        step=self.height/m
        for t in range(1,m):
            y =t*step
            self.canvas.create_line(0,y,self.width,y,tags="line")
    def resize(self,event):
        self.canvas.delete("line")
        self.grid(self.n,self.m)
        for model in self.models :
            self.plot_signal(model.get_signal(),
                model.get_color(),
                model.get_name())
Пример #11
0
class View(Observer):
    def __init__(self,parent,subject,bg="white"):
        print("View : __init__")
        Observer.__init__(self)
        self.subject=subject
        self.parent=parent
        self.signal_id=None
        self.canvas=Canvas(parent,bg=bg)
        self.canvas.bind("<Configure>", self.resize)
        self.width=int(self.canvas.cget("width"))
        self.height=int(self.canvas.cget("height"))

    def update(self,subject):
        print("View : update")
        signal=subject.get_signal()
        self.signal_id=self.plot_signal(signal)
    def plot_signal(self,signal,color="red"):
        width,height=self.width,self.height
        if self.signal_id!=None :
            self.canvas.delete(self.signal_id)
        if signal and len(signal)>1:
            plot=[(x*width, height/2.0*(y+1)) for (x, y) in signal]
            self.signal_id=self.canvas.create_line(plot,fill=color,smooth=1,width=3)
        return self.signal_id

    def resize(self, event):
        """
        En cas de reconfiguration de fenetre
        """
        if event:
            self.width = event.width
            self.height = event.height
##            self.width = int(event.widget.cget("width"))
##            self.height = int(event.widget.cget("height"))
##            print("View : resize cget",event.widget.cget("width"),event.widget.cget("height"))
        print("View : resize event",event.width,event.height)
        self.canvas.delete("grid")
        self.plot_signal(self.subject.get_signal())
        self.grid()

    def grid(self, steps=8):
        width,height=self.width,self.height
#        self.canvas.create_line(10,height/2,width,height/2,arrow="last",tags="grid")
#        self.canvas.create_line(10,height-5,10,5,arrow="last",tags="grid")
        step=width/steps*1.
        for t in range(1,steps+2):
            x =t*step
            self.canvas.create_line(x,0,x,height,tags="grid")
            self.canvas.create_line(0,x,width,x,tags="grid")
            self.canvas.create_line(x,height/2-4,x,height/2+4,tags="grid")
    def packing(self) :
        self.canvas.pack(expand=1,fill="both",padx=6)
Пример #12
0
class GUI(object):
    def __init__(self, world):
        self.ticks = 0
        self.world = world
        self.width = world.width
        self.height = world.height

        self.root = Tk()
        self.root.title("Mars Explorer")
        window_x, window_y = self._compute_window_coords()
        self.root.geometry('%dx%d+%d+%d' % (self.width, self.height,
                                            window_x, window_y))

        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.after(1, self._tick)

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

    def _tick(self):
        # Stop if done.
        if self.world.is_done():
            return

        self.world.tick()
        self._draw()

        self.ticks += 1
        self.canvas.after(1, self._tick)

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

        self.world.draw(self.canvas)
        for entity in self.world.entities:
            entity.draw(self.canvas)

        self.canvas.create_text(self.width - 20, 10, text=str(self.ticks))
        self.canvas.create_text(self.width - 70, 30,
                                text='Rocks in carriers: %d' % self.world.rocks_in_carriers())
        self.canvas.create_text(self.width - 70, 50, text='Rocks delivered: %d' % self.world.rocks_collected)
        self.canvas.create_text(self.width - 55, 70, text='Total rocks: %d' % self.world.num_rocks)

    def _compute_window_coords(self):
        # http://stackoverflow.com/a/14912644/742501
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_x = screen_width / 2 - self.width / 2
        window_y = screen_height / 2 - self.height / 2
        return window_x, window_y
Пример #13
0
class Display:
    def __init__(self, fps=FPS, width=WIDTH, height=HEIGHT,
        board_offset_bottom=BOARD_OFFSET_BOTTOM,
        board_width=BOARD_WIDTH,
        board_height=BOARD_HEIGHT):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.root.destroy)
        self.width = width
        self.height = height
        self.canvas=Canvas(self.root, bg="black",width=width,height=height)
        self.board_width = board_width
        self.board_height = board_height
        self.board_offset_bottom = board_offset_bottom
        self.canvas.pack()
        self.fps = fps
        self.controllers = []
        #For reset
        self.root.bind("<space>", lambda e:self.reset_all())
        self.root.bind("<Escape>", lambda e:self.root.destroy())
    def run(self):
        self.root.after(1000//self.fps, self.loop)
        try:
            self.root.mainloop()
        except KeyboardInterrupt:
            self.root.destroy()
    def loop(self):
        actions = [controller.get_action(self.model) for controller in self.controllers]
        self.model.update(1./self.fps, actions)
        self.draw()
        self.root.after(1000//self.fps, self.loop)
    def draw(self):
        self.canvas.delete('all')
        self.board = self.canvas.create_rectangle(
            self.model.x()-self.board_width/2,
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.board_width/2,
            self.board_offset_bottom+self.height, fill="green")
        self.pendulum = self.canvas.create_line(
            self.model.x(),
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.model.arm_length*math.sin(self.model.alpha()),
            self.board_offset_bottom+self.height-self.board_height-self.model.arm_length*math.cos(self.model.alpha()),
            fill="blue", width=20)
    def attach_model(self, model):
        self.model = model
        self.draw()
    def attach_controller(self, controller):
        self.controllers.append(controller)
    def reset_all(self):
        self.model.randomize()
Пример #14
0
class Lissajou(Observer):
    def __init__(self, parent,subjects,bg="black"):
        self.subjects=subjects
        self.canvas=Canvas(parent,bg=bg)
        self.width = int(self.canvas.cget("width"))
        self.height = int(self.canvas.cget("height"))
        self.signalXY_id = None
        self.canvas.bind("<Configure>", self.resize)
        self.packing()

    def update(self):
        print("Lissajou update")
        self.signalXY_id = self.plot_lissajou()

    def resize(self, event):
        if event:
            self.width=event.width
            self.height=event.height
            self.grid()
            self.update()

    def grid(self, n=10, m=10,color="white"):
        self.canvas.delete("all")
        w,h=self.width,self.height
        width,height=int(w),int(h)
        self.canvas.create_line(n,(height/2.0),width,(height/2.0),arrow="last",fill=color)
        self.canvas.create_line(width/2.0,height,width/2.0,5.0,arrow="last",fill=color)
        stepX=(width)/m*1.0
        stepY=(height)/n*1.0

        for t in range(1,m+1):
            x =t*stepX
            self.canvas.create_line(x,height,x,20,fill=color)

        for t in range(1,n+1):
            y =t*stepY
            self.canvas.create_line(10.0,y,width-10,y,fill=color)

    def plot_lissajou(self,color='green'):
        width,height=int(self.width-12),int(self.height)
        signalXY = self.subjects.getSignalXY()
        if signalXY!=None:
            self.canvas.delete(self.signalXY_id)
        if signalXY and len(signalXY)>1:
            plot=[((x+1)*(width/2)+5, height/2.0*(y+1)) for (x, y) in signalXY]
            signalValue = self.canvas.create_line(plot, fill=color, smooth=1, width=2)
        return signalValue

    def packing(self):
        self.canvas.pack(expand=1, fill='both',side='top')
Пример #15
0
class Viewport(Frame):
    def __init__(self, parent=None, canvassize=500):
        Frame.__init__(self, parent)

# Incredibly, it's a pain to extract the canvas width,height directly
# from the canvas widget itself, so we store these here and push them
# down to the actual canvas widget whenever they change.
        self.canvaswidth = canvassize
        self.canvasheight = canvassize

# The flag for whether we display the camera or not is in menu.py
# as part the of menubar class.
        self.readoutid = 0

        self.framewidth = -1  # Will be set elsewhere
        self.frameheight = -1
        self.pack(side=BOTTOM, anchor=S, expand=YES, fill=BOTH)
        self.canvas = Canvas(self, width=canvassize, \
                  height=canvassize, bg='white')
        self.canvas.pack()


###########################
# DRAW_READOUT class function:
# - Build the text strings for the camera readout display
# - If a readout is already on the screen, remove it
# - Draw the new readout
# This routine does NOT check the menu.py variable that determines
# whether or not we should actually draw the readout.  It's the
# caller's responsibility to do that.
#
    def draw_readout(self, camera):
        text1 = 'Camera:'
        text2 = "x=%d y=%d z=%d" % (round(camera.t[0]), \
                          round(camera.t[1]), round(camera.t[2]))
        text3 = "Rotation = %d" % (round(degrees(camera.yrot)))
        text4 = "%s\n%s\n%s" % (text1, text2, text3)

        if self.readoutid:
          self.canvas.delete(self.readoutid)
        self.readoutid = self.canvas.create_text(5,5, text=text4, \
                                         anchor=NW)


    def undraw_readout(self):
      if self.readoutid:
        self.canvas.delete(self.readoutid)
        self.readoutid = 0
Пример #16
0
class Viewport(Frame):
    def __init__(self, parent=None, canvassize=500):
        Frame.__init__(self, parent)

        # Incredibly, it's a pain to extract the canvas width,height directly
        # from the canvas widget itself, so we store these here and push them
        # down to the actual canvas widget whenever they change.
        self.canvaswidth = canvassize
        self.canvasheight = canvassize

        # The flag for whether we display the camera or not is in menu.py
        # as part the of menubar class.
        self.readoutid = 0

        self.framewidth = -1  # Will be set elsewhere
        self.frameheight = -1
        self.pack(side=BOTTOM, anchor=S, expand=YES, fill=BOTH)
        self.canvas = Canvas(self, width=canvassize, \
                  height=canvassize, bg='white')
        self.canvas.pack()

###########################
# DRAW_READOUT class function:
# - Build the text strings for the camera readout display
# - If a readout is already on the screen, remove it
# - Draw the new readout
# This routine does NOT check the menu.py variable that determines
# whether or not we should actually draw the readout.  It's the
# caller's responsibility to do that.
#

    def draw_readout(self, camera):
        text1 = 'Camera:'
        text2 = "x=%d y=%d z=%d" % (round(camera.t[0]), \
                          round(camera.t[1]), round(camera.t[2]))
        text3 = "Rotation = %d" % (round(degrees(camera.yrot)))
        text4 = "%s\n%s\n%s" % (text1, text2, text3)

        if self.readoutid:
            self.canvas.delete(self.readoutid)
        self.readoutid = self.canvas.create_text(5,5, text=text4, \
                                         anchor=NW)

    def undraw_readout(self):
        if self.readoutid:
            self.canvas.delete(self.readoutid)
            self.readoutid = 0
Пример #17
0
class Clock(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.parent = parent
		self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
		self.initTime()
		self.draw()
		self.onTimer()

	def initTime(self):
		self.hourHand = time.localtime().tm_hour % 12 * 5
		self.minuteHand = time.localtime().tm_min
		self.secondHand = time.localtime().tm_sec

	def draw(self):
		self.pack(fill=BOTH, expand=1)		
		radius = 300
		x, y = 50, 50		
		centerX, centerY = 180, 180
		hourX = centerX + 0.3 * radius/2.0 * math.cos(self.toRadian(self.hourHand))
		hourY = centerY + 0.3 * radius/2.0 * math.sin(self.toRadian(self.hourHand))
		minuteX = centerX + 0.6 * radius/2.0 * math.cos(self.toRadian(self.minuteHand))
		minuteY = centerY + 0.6 * radius/2.0 * math.sin(self.toRadian(self.minuteHand))
		secondX = centerX + 0.75 * radius/2.0 * math.cos(self.toRadian(self.secondHand))
		secondY = centerY + 0.75 * radius/2.0 * math.sin(self.toRadian(self.secondHand))		
		self.canvas.create_oval(x, y, radius, radius, outline="black", fill="black")
		self.canvas.create_line(centerX, centerY, hourX, hourY, width=3, fill="green")
		self.canvas.create_line(centerX, centerY, minuteX, minuteY, width=3, fill="green")
		self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red")
		self.canvas.pack(fill=BOTH, expand=1)

	def toRadian(self, x):
		return (x * math.pi/30.0) - (math.pi/2.0)
		
	def onTimer(self):
		self.tick()
		self.canvas.delete(ALL)
		self.draw()
		self.after(DELAY, self.onTimer)
		
	def tick(self):
		self.secondHand = (self.secondHand + 1) % 60
		if self.secondHand == 0:
			self.minuteHand = (self.minuteHand + 1) % 60
			if self.minuteHand == 0:
				self.hourHand = (self.hourHand + 5) % 60
Пример #18
0
class ResultsTable(Frame):
    """A custom table widget which displays words alongside the users guesses"""
    def __init__(self, parent, width=400, height=200):

        Frame.__init__(self, parent)
        self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF")
        self.canvas.configure(bd=2, relief=SUNKEN)
        self.canvas.pack(side=LEFT)
        self.centre_line = self.canvas.create_line(0, 0, 0, 0)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)
        scrollbar.configure(command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0,                               width, height))
        self.width=width
        self.height_in_lines = height/18
        self.item_count = 0
        self.font = ("Helvetica", 12)

    def add_word(self, word):
        """Add a word to the table"""
        top = 20*self.item_count
        if top > 200:
            #If necessary extend scroll region downwards
            self.canvas.configure(scrollregion=(0, 0, self.width, top+20))
        colour = "#139E1C" if word.isCorrect else "#F30000"
        #Draw the word in the left column
        self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font)
        #Draw the guess in the right column
        self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour)
        #Draw a line to separate this row from those below
        self.canvas.create_line(0, top+19, self.width, top+19)
        #Extend centre line of tablr
        self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2,
                           top+19)
        self.item_count += 1

    def add_list(self, word_list):
        """Add a list to the table"""
        for word in word_list:
            self.add_word(word)

    def clear(self):
        """Clear the table of all words"""
        self.item_count = 0
        self.canvas.delete(ALL)
Пример #19
0
class PRMViewer(object):
    def __init__(self, width=500, height=500, title='PRM', background='tan'):
        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)
        self.width = width
        self.height = height
        self.canvas = Canvas(top, width=self.width, height=self.height, background=background)
        self.canvas.pack()

    def pixel_from_point(self, point):
        (x, y) = point
        # return (int(x*self.width), int(self.height - y*self.height))
        return (x * self.width, self.height - y * self.height)

    def draw_point(self, point, radius=5):
        (x, y) = self.pixel_from_point(point)
        self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill='black')

    def draw_line(self, segment):
        (point1, point2) = segment
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2)

    def draw_arrow(self, point1, point2):
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2, arrow=LAST)

    def draw_rectangle(self, box, width=2, color='brown'):
        (point1, point2) = box
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, width=width)

    def draw_circle(self, center, radius, width=2, color='black'):
        (x1, y1) = self.pixel_from_point(np.array(center) - radius * np.ones(2))
        (x2, y2) = self.pixel_from_point(np.array(center) + radius * np.ones(2))
        self.canvas.create_oval(x1, y1, x2, y2, outline='black', fill=color, width=width)

    def clear(self):
        self.canvas.delete('all')
Пример #20
0
class Application(Frame):
  def __init__(self, parent, game):
    Frame.__init__(self, parent, background="green")
    self.parent = parent
    self.game = game
    self.initUI()
    self.canvas = Canvas(self)
    self.draw()

  def initUI(self):
    self.parent.title("Football")
    self.pack(fill=BOTH, expand=1)
 
  def draw(self):
    self.game.next_round()
    LAYOUT = self.game.get_layout()
    self.canvas.delete("all")
    self.canvas.create_text(300, 20, anchor=W, font="Purisa", text="RESULT " + str(LAYOUT[7][0]) + ":" + str(LAYOUT[7][1])) 
    self.canvas.create_text(50, 20, anchor=W, font="Purisa", text="Control WSAD" )
    self.canvas.create_text(650, 20, anchor=W, font="Purisa", text="Control ARROWS" )
    x0 = 10
    y0 = 40
    # WHOLE FIELD
    self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0], y0 + LAYOUT[1], outline="white", fill="green", width=2)
    self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0]/2, y0 + LAYOUT[1], outline="white", fill="green", width=1)
    self.canvas.create_oval(x0 + LAYOUT[0]/2 -1 , y0 + LAYOUT[1]/2 - 1, x0 + LAYOUT[0]/2, y0 + LAYOUT[1]/2, outline="white", 
        fill="white", width=4)
    # GOALKEEPER FIELDS
    self.canvas.create_rectangle(x0, y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[3][0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2)
    self.canvas.create_rectangle(x0 + LAYOUT[0] - LAYOUT[3][0], y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2)

    # GOALPOSTS
    self.canvas.create_rectangle(x0 - 5, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black")

    self.canvas.create_rectangle(x0 + LAYOUT[0]-1, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0 + LAYOUT[0] + 5, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black")

    # PLAYERS
    self.canvas.create_oval(x0 + LAYOUT[4][0]-LAYOUT[8][0][0], y0 + LAYOUT[4][1]-LAYOUT[8][0][0], x0 + LAYOUT[4][0] + LAYOUT[8][0][0], y0 + LAYOUT[4][1] + LAYOUT[8][0][0], fill="blue")
    self.canvas.create_oval(x0 + LAYOUT[5][0]-LAYOUT[8][1][0], y0 + LAYOUT[5][1]-LAYOUT[8][1][0], x0 + LAYOUT[5][0] + LAYOUT[8][1][0], y0 + LAYOUT[5][1] + LAYOUT[8][1][0], fill="gray")
    # BALL
    self.canvas.create_oval(x0 + LAYOUT[6][0]-LAYOUT[8][2][0], y0 + LAYOUT[6][1]-LAYOUT[8][2][0], x0 + LAYOUT[6][0] + LAYOUT[8][2][0], y0 + LAYOUT[6][1] + LAYOUT[8][2][0], fill="white")

    self.canvas.pack(fill=BOTH, expand=1)
    self.after(1, self.draw)    
Пример #21
0
class Screen(Observer):
    def __init__(self,parent,bg="white"):
        self.canvas=Canvas(parent,bg=bg)
        print("parent",parent.cget("width"),parent.cget("height"))
        self.magnitude=Scale(parent,length=250,orient="horizontal",
                         label="Magnitude", sliderlength=20,
                         showvalue=0,from_=0,to=5,
                         tickinterval=25)
    def update(self,model):
        print("View update")
        signal=model.get_signal()
        self.plot_signal(signal)

    def get_magnitude(self):
        return self.magnitude
        
    def plot_signal(self,signal,color="red"):
        w,h=self.canvas.cget("width"),self.canvas.cget("height")
        width,height=int(w),int(h)
#        print(self.canvas.find_withtag("signal"))
        if self.canvas.find_withtag("signal") :
            self.canvas.delete("signal")
        if signal and len(signal) > 1:
            plot = [(x*width, height/2.0*(y+1)) for (x, y) in signal]
            signal_id = self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="signal")
        return

    def grid(self, steps):
        w,h=self.canvas.cget("width"),self.canvas.cget("height")
        width,height=int(w),int(h)
        self.canvas.create_line(10,height/2,width,height/2,arrow="last")
        self.canvas.create_line(10,height-5,10,5,arrow="last")
        step=(width-10)/steps*1.
        for t in range(1,steps+2):
            x =t*step
            self.canvas.create_line(x,height/2-4,x,height/2+4)

    def packing(self) :
        self.canvas.pack()
        self.magnitude.pack()
Пример #22
0
class SimWin(Tk,object):
    
    WIN_HEIGHT = 600
    WIN_WIDTH = 600    
    WIN_BG = '#fff'
    
    def __init__(self, parent=None):
        
        super(SimWin, self).__init__(parent)
        self.canvas = Canvas(master=self, 
                             height=SimWin.WIN_HEIGHT, 
                             width=SimWin.WIN_WIDTH, 
                             background=SimWin.WIN_BG)
        self.canvas.pack()
    
    def changeProps(self, height, width, bg):
        
        SimWin.WIN_HEIGHT = height
        SimWin.WIN_WIDTH = width
        SimWin.WIN_BG = bg
        
    def envDraw(self, redius, C):
        # C is a 2D numpy array
        
        if(not (type(C)==type(np.array([1])))):
            print 'Input a valid NUMPY array'
        else:
            
            n = 0
            for (i,j) in C:
                self.canvas.create_oval(i-redius[n],j-redius[n],i+redius[n],j+redius[n],
                                        fill='#f00',
                                        outline='#f00')
                n = n + 1
    
    def cleanCanvas(self):
        
        self.canvas.delete('delete')
Пример #23
0
class Plotter:
	def __init__(self):
		self.colors = ["red", "green"]
		self.window = Tk()
		self.window.title("R-L Reinfolge")
		self.c = Canvas(master=self.window, width = 300, height= 250, bg="white")
		self.c.create_text(20, 20, text="rechts")
		self.c.create_text(20, 220, text="links")
		self.c.pack()
		t = right - left
		self.pens = []
		for i in range(len,(t)):
			self.pens.append(Pen (self.c, t[i], self.colors[i%4]))
			thread.start_new_thread(self.update, ())
			self.window.mainloop()
			
	def update(self):
		while True:
			for i in range(60):
				for pen in self.pens:
					pen.draw(i*5)
				time.sleep(1)
			self.c.delete("point")
Пример #24
0
class ResultsTable(Frame):
    
    def __init__(self, parent, width=400, height=200):

        Frame.__init__(self, parent)
        self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF")
        self.canvas.configure(bd=2, relief=SUNKEN)
        self.canvas.pack(side=LEFT)
        self.centre_line = self.canvas.create_line(0, 0, 0, 0)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)
        scrollbar.configure(command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0,                               width, height))
        self.width=width
        self.height_in_lines = height/18
        self.item_count = 0
        self.font = ("Helvetica", 12)

    def add_word(self, word):
        top = 20*self.item_count
        if top > 200:
            self.canvas.configure(scrollregion=(0, 0, self.width, top+20))
        colour = "#139E1C" if word.isCorrect else "#F30000"
        self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font)
        self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour)
        self.canvas.create_line(0, top+19, self.width, top+19)
        self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2,
                           top+19)
        self.item_count += 1

    def add_list(self, word_list):
        for word in word_list:
            self.add_word(word)

    def clear(self):
        self.item_count = 0
        self.canvas.delete(ALL)
Пример #25
0
                canv.delete(rects[i][j])
                rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")
            else: new_grid[i][j]=grid[i][j]
    for i in range(len(new_grid)):
        for j in range(len(new_grid[i])):
            grid[i][j]=new_grid[i][j]
    canv.after(20, tick, grid, rects)
w, h = 600, 600
n, m = 20, 20
paused = True
grid=[]; new_grid=[]; rects=[]
root = Tk()
canv = Canvas(root, width=w, height=h, bg="white")
##for i in range(n+1):canv.create_line(w*i/n,0,w*i/n,h, fill = "lightblue")
##for i in range(m+1):canv.create_line(0,h*i/m,w,h*i/m, fill = "lightblue")
for i in range(n):
    grid.append([])
    rects.append([])
    for j in range(m):
        grid[i].append(0)
        rects[i].append(canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="white", outline="lightblue"))

for (i, j) in [(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)]:
    grid[i][j]=1
    canv.delete(rects[i][j])
    rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")

canv.pack()
root.bind('<1>', lambda e: left(e, grid, rects))
root.bind('<space>', begin)
root.mainloop()
class MainWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title(mainWindowTitle)
        self.resizable(width=0, height=0)
        self.__setStyles()
        self.__initializeComponents()
        self.__dataController = DataController();
        self.mainloop()
            
    def __initializeComponents(self):
        self.imageCanvas = Canvas(master=self, width=imageCanvasWidth,
                                  height=windowElementsHeight, bg="white")
        self.imageCanvas.pack(side=LEFT, padx=(windowPadding, 0),
                              pady=windowPadding, fill=BOTH)
        
        self.buttonsFrame = Frame(master=self, width=buttonsFrameWidth,
                                  height=windowElementsHeight)
        self.buttonsFrame.propagate(0)
        self.loadFileButton = Button(master=self.buttonsFrame,
                                     text=loadFileButtonText, command=self.loadFileButtonClick)
        self.loadFileButton.pack(fill=X, pady=buttonsPadding);
        
        self.colorByLabel = Label(self.buttonsFrame, text=colorByLabelText)
        self.colorByLabel.pack(fill=X)
        self.colorByCombobox = Combobox(self.buttonsFrame, state=DISABLED,
                                        values=colorByComboboxValues)
        self.colorByCombobox.set(colorByComboboxValues[0])
        self.colorByCombobox.bind("<<ComboboxSelected>>", self.__colorByComboboxChange)
        self.colorByCombobox.pack(fill=X, pady=buttonsPadding)
        self.rejectedValuesPercentLabel = Label(self.buttonsFrame, text=rejectedMarginLabelText)
        self.rejectedValuesPercentLabel.pack(fill=X)
        self.rejectedValuesPercentEntry = Entry(self.buttonsFrame)
        self.rejectedValuesPercentEntry.insert(0, defaultRejectedValuesPercent)
        self.rejectedValuesPercentEntry.config(state=DISABLED)
        self.rejectedValuesPercentEntry.pack(fill=X, pady=buttonsPadding)        
        
        self.colorsSettingsPanel = Labelframe(self.buttonsFrame, text=visualisationSettingsPanelText)
        self.colorsTableLengthLabel = Label(self.colorsSettingsPanel, text=colorsTableLengthLabelText)
        self.colorsTableLengthLabel.pack(fill=X)
        self.colorsTableLengthEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableLengthEntry.insert(0, defaultColorsTableLength)
        self.colorsTableLengthEntry.config(state=DISABLED)
        self.colorsTableLengthEntry.pack(fill=X)
        self.scaleTypeLabel = Label(self.colorsSettingsPanel, text=scaleTypeLabelText)
        self.scaleTypeLabel.pack(fill=X)
        self.scaleTypeCombobox = Combobox(self.colorsSettingsPanel, state=DISABLED,
                                          values=scaleTypesComboboxValues)
        self.scaleTypeCombobox.set(scaleTypesComboboxValues[0])
        self.scaleTypeCombobox.bind("<<ComboboxSelected>>", self.__scaleTypeComboboxChange)
        self.scaleTypeCombobox.pack(fill=X)
        self.colorsTableMinLabel = Label(self.colorsSettingsPanel, text=colorsTableMinLabelText)
        self.colorsTableMinLabel.pack(fill=X)
        self.colorsTableMinEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMinEntry.insert(0, defaultColorsTableMin)
        self.colorsTableMinEntry.config(state=DISABLED)
        self.colorsTableMinEntry.pack(fill=X)
        self.colorsTableMaxLabel = Label(self.colorsSettingsPanel, text=colorsTableMaxLabelText)
        self.colorsTableMaxLabel.pack(fill=X)
        self.colorsTableMaxEntry = Entry(self.colorsSettingsPanel)
        self.colorsTableMaxEntry.insert(0, defaultColorsTableMax)
        self.colorsTableMaxEntry.config(state=DISABLED)
        self.colorsTableMaxEntry.pack(fill=X)
        self.colorsSettingsPanel.pack(fill=X, pady=buttonsPadding)
        
        self.redrawButton = Button(master=self.buttonsFrame, text=redrawButtonText,
                                   state=DISABLED, command=self.__redrawButtonClick)
        self.redrawButton.pack(fill=X, pady=buttonsPadding)
        self.buttonsFrame.pack(side=RIGHT, padx=windowPadding, pady=windowPadding, fill=BOTH)
        
    def __setStyles(self):
        Style().configure("TButton", padding=buttonsTextPadding, font=buttonsFont)
    
    def loadFileButtonClick(self):
        fileName = tkFileDialog.askopenfilename(filetypes=[('Tablet files', '*.mtb'), ('Tablet files', '*.htd')])
        if (fileName):
            if (not self.__getInputParams()):
                self.__showInvalidInputMessage()
                return
            
            self.lastFileName = fileName;
            self.title(mainWindowTitle + " " + fileName)
            self.__draw(fileName)
            tkMessageBox.showinfo(measureDialogTitle, 
                                  measureDialogText + str(self.__dataController.getMeasure(fileName)))
            
            self.redrawButton.config(state=NORMAL)
            self.colorByCombobox.config(state="readonly")
            self.colorsTableLengthEntry.config(state=NORMAL)
            self.scaleTypeCombobox.config(state="readonly")
            
    def __redrawButtonClick(self):
        if (not self.__getInputParams()):
            self.__showInvalidInputMessage()
            return
        
        self.__draw(self.lastFileName)

    def __scaleTypeComboboxChange(self, event):
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            self.colorsTableMinEntry.config(state=DISABLED)
            self.colorsTableMaxEntry.config(state=DISABLED)
        else:
            self.colorsTableMinEntry.config(state=NORMAL)
            self.colorsTableMaxEntry.config(state=NORMAL)
        
    def __colorByComboboxChange(self, event):
        if (self.colorByCombobox.get() == colorByNoneOption):
            self.rejectedValuesPercentEntry.config(state=DISABLED)
        else:
            self.rejectedValuesPercentEntry.config(state=NORMAL)
        
    def __draw(self, fileName):
        self.imageCanvas.delete(ALL)

        dataForDrawing = self.__dataController.getDataForDrawing(
            fileName, self.colorByCombobox.get(), self.colorsTableLength,
            self.scaleTypeCombobox.get(), self.colorsTableMinValue,
            self.colorsTableMaxValue, self.rejectedValuesPercent)
        
        for package in dataForDrawing:
            x = package[0];
            y = package[1];
            color = package[2];
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=color)
            
    def __drawColorBySpeed(self, dataPackages, minX, minY, ratio, hsv):   
        allSpeeds = self.__getAllSpeeds(dataPackages)
        minSpeed = min(allSpeeds)
        maxSpeed = max(allSpeeds)
        
        if (self.scaleTypeCombobox.get() == relativeScaleType):
            colorsTableMinValue = minSpeed
            colorsTableMaxValue = maxSpeed
        else:
            colorsTableMinValue = self.colorsTableMinValue
            colorsTableMaxValue = self.colorsTableMaxValue
        
        i = 0
        for package in dataPackages:
            x = (package[dataXNumber] - minX) * ratio
            y = (package[dataYNumber] - minY) * ratio
            
            color = hsv.getColorByValue(colorsTableMinValue,
                                        colorsTableMaxValue,
                                        allSpeeds[i])
                
            tk_rgb = "#%02x%02x%02x" % color
            self.imageCanvas.create_line(x, y, x + 1, y + 1, fill=tk_rgb)
            i += 1
            
    def __showInvalidInputMessage(self):
        tkMessageBox.showinfo(invalidInputMessageTitle, invalidInputMessageText)
    
    def __getInputParams(self):
        try:
            self.colorsTableLength = int(self.colorsTableLengthEntry.get())
            self.colorsTableMinValue = float(self.colorsTableMinEntry.get())
            self.colorsTableMaxValue = float(self.colorsTableMaxEntry.get())
            self.rejectedValuesPercent = float(self.rejectedValuesPercentEntry.get())
        
            if (self.colorsTableLength < 1 or
                self.colorsTableMinValue >= self.colorsTableMaxValue or
                self.rejectedValuesPercent < 0 or self.rejectedValuesPercent >= 100):
                raise
            return True
        except:
            return False
Пример #27
0
while True:
    
    #maps arm coordinates to servo values, and periodically move the rover's head there
    coords = x.coords
    servos = phantom_to_servos(coords)
    if time() - t > 0.5 and not locked:
        r.pan_servo(-servos[0])
        r.tilt_servo(servos[1])
        t = time()

    #display arm's coordinates in tkinter window
    x_label["text"] = "X: {}".format(coords[0])
    y_label["text"] = "Y: {}".format(coords[1])
    z_label["text"] = "Z: {}".format(coords[2])

    #visual representation of where the arm's pen point is
    c.delete(pointer)
    pointer = c.create_circle(coords[0]+300, 600-coords[1]-300, (coords[2]+120)/15, fill="black")

    #locks the head if button two is pressed
    if coords[4]:
		print("Toggled camera lock!")
		locked = not locked
		sleep(1)
    
    #saves an image from the rover if button one is pressed
    if coords[3]:
        capture_image()
        
    root.update_idletasks()
    root.update()
Пример #28
0
class main:

	def __init__ (self):
		self.app = Tk()
		self.app.title('Tic Tac Toe')
		#self.app.resizable(width=False, height=False)
		#width and hight of window
		w = 900
		h = 1100
		#width and hight of screen
		ws = self.app.winfo_screenwidth()
		hs = self.app.winfo_screenheight()
		#calculate position
		x = ws/2 - w/2
		y = hs/2 - h/2
		#place window -> pramaters(visina, dolzina, pozicija x, pozicija y)
		self.app.geometry("%dx%d+%d+%d" % (w,h, x, y))

		#======================================
		self.frame = Frame() #main frame
		self.frame.pack(fill = 'both', expand = True)
		self.label = Label(self.frame, text	= 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue')
		self.label.pack(fill='both', expand = True)
		#self.label2 = Label(self.frame, text	= 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop-------------
		#self.label2.pack(fill='both', expand = True)
		self.canvas = Canvas(self.frame, width = 900, height = 900)
		self.canvas.pack(fill = 'both', expand = True)
		self.framepod = Frame(self.frame)#sub frame
		self.framepod.pack(fill = 'both', expand = True)
		self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue')
		self.Single.pack(fill='both', expand = True, side=RIGHT)
		self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue')
		self.Multi.pack(fill='both', expand = True, side=RIGHT)
		self.board = AI()
		self.draw()

	def double(self): 
		#cleans the all simbols from canvas
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.place)
		self.draw() #---------------------------------------
		self.table=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
		self.c=0 #counter
		self.e=False #flag for end game

	def draw(self): #draws the outline lines
		self.canvas.create_rectangle(0,0,900,900, outline='black')
		self.canvas.create_rectangle(300,900,600,0, outline='black')
		self.canvas.create_rectangle(0,300,900,600, outline='black')

	def place(self, event):
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						if self.c % 2 == 0:
							#calculate points to draw circle
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
							self.table[y2][x2] = 4
							self.c+=1
						else:
							#calculate points to draw cross
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
							self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")
							self.table[y2][x2] = 1
							self.c+=1
		self.check() 


	def startsingle(self):
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.placeone)
		self.draw()
		self.board = AI()

	def placeone(self, event):
		player = 'X'
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						x=(2*i+300)/2
						y=(2*j+300)/2
						x2=int(i/300)
						y2=int(j/300)
						self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
						self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")

						
						player_move = x2 + 3*y2 #spremeni
						self.board.make_move(player_move, player)
						
		if self.board.complete():
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		elif self.board.winner() != None:
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		else:
			player = self.board.get_enemy(player)
			computer_move = self.board.determine(self.board, player)
			self.board.make_move(computer_move, player)

			ti = computer_move % 3
			tj = computer_move / 3

			x=(600*ti+300)/2
			y=(600*tj+300)/2
			#self.label2['text'] = str(computer_move) + '  ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x)
			self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
			
			if self.board.winner() != None:
				self.label['text'] = (self.board.winner())
				self.canvas.unbind("ButtonPress-1")
				self.board = AI()

 

	def check(self):
		#checks for win
		#horitontal
		for i in range(3):
			if sum(self.table[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.table[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#vertical
		self.vs=[[row[i] for row in self.table] for i in range(3)]
		for i in range(3):
			if sum(self.vs[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.vs[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#diagonals
		self.dig1=0
		self.dig2=0
		for i in range(3):
			self.dig1+=self.table[i][i]
		for i in range(3):
			self.dig2+=self.table[2-i][i]

		if self.dig1==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig1==12:
			self.label['text'] = ('O wins')
			self.end()
		if self.dig2==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig2==12:
			self.label['text'] = ('O wins')
			self.end()

		#draw
		if self.e==False:
			a=0
			for i in range(3):
				a+=sum(self.table[i])
			if a == 24: #5 *4 + 4 * 1 --> 5 circles and 4 crosses
				self.label['text'] = ('Draw')
				self.end()

	def end(self):
		self.canvas.unbind("<ButtonPress-1>")
		self.e=True

	def mainloop(self):
		self.app.mainloop()
Пример #29
0
class PinceauCanvas:
    def __init__(self, master, width, height):
        self.__master = master
        self.__width = width
        self.__height = height
        self.__tmp = {}
        self.__tmp_rendered = None
        self.__shapes = []
        # Default constants
        self.__draw_mode = 'add'
        self.__shape_mode = 'normal'
        self.__shape_type = 'rectangle'
        self.__tmp_color = '#E57373'
        self.__final_color = '#F44336'
        # Main canvas
        self.__canvas = Canvas(self.__master,
                               width=self.__width,
                               height=self.__height)
        self.bind_events()

    def set_send(self, send_func):
        # Method sending the drawn shape to the server.
        self.__send = send_func

    def switch_shape_mode(self):
        # Method enabling to switch from a straight shape to a nomrmal shape
        # and vice-versa.
        self.__shape_mode = ('straight'
                             if self.__shape_mode == 'normal' else 'normal')

    def switch_draw_mode(self):
        # Method enabling to switch from the drawing mode to the erasing mode
        # and vice-versa.
        self.__draw_mode = ('erase' if self.__draw_mode == 'add' else 'add')

    def change_color(self, tmp_color, color):
        # Method enabling to switch from one color to another.
        self.__tmp_color = tmp_color
        self.__final_color = color

    def change_shape(self, shape_type):
        # Method enabling to switch from one shape to another.
        self.__shape_type = shape_type

    def pack(self):
        self.__canvas.pack()

    def bind_events(self):
        self.__canvas.bind('<KeyPress>', self.key_press)
        self.__canvas.bind('<KeyRelease>', self.key_press)
        self.__canvas.bind('<Button-1>', self.mouse_click)
        self.__canvas.bind('<B1-Motion>', self.mouse_drag)
        self.__canvas.bind('<ButtonRelease-1>', self.mouse_release)

    def key_press(self, event):
        # Method to detect if the 'CTRL' key or 'MAJ' key is pressed using the
        # keycodes from iOS and Windows.
        # Indeed, if 'CTRL' is pressed, we turn to erasing mode.
        # And if 'MAJ" is pressed, we turn to straight shapes mode.
        keycode = event.keycode
        if keycode == 262145 or keycode == 262401 or keycode == 17:  # Ctrl key is pressed
            self.switch_draw_mode()
        if keycode == 131330 or keycode == 131074 or keycode == 131076 or keycode == 16:  # Maj key is pressed
            self.switch_shape_mode()

    def mouse_click(self, event):
        self.__canvas.focus_set()
        x, y = event.x, event.y
        if self.__draw_mode == 'erase':
            action = {'action': 'erase', 'x': x, 'y': y}
            self.erase(action)
            self.__send(action)
        elif self.__draw_mode == 'add':
            self.__tmp = {
                'action': 'add',
                'x1': x,
                'y1': y,
                'x2': x,
                'y2': y,
                'mode': self.__shape_mode,
                'type': self.__shape_type,
                'fill': self.__tmp_color
            }

    def erase(self, action):
        # Method erasing a shape on the canvas.
        x, y = action['x'], action['y']
        shape = self.__canvas.find_closest(x, y)
        if shape:
            self.__canvas.delete(shape)

    def mouse_drag(self, event):
        if self.__draw_mode == 'add':
            self.__canvas.focus_set()
            self.__tmp['x2'] = event.x
            self.__tmp['y2'] = event.y
            self.__tmp['mode'] = self.__shape_mode
            self.__tmp_rendered = self.draw(self.__tmp)

    def mouse_release(self, event):
        if self.__draw_mode == 'add':
            self.__tmp['fill'] = self.__final_color
            if self.__tmp['type'] is not None:
                final_shape = self.draw(self.__tmp)
                self.__shapes.append(final_shape)
                self.__send(self.__tmp)
            # Reset temp shape
            self.__tmp = {}
            self.__tmp_rendered = None

    def draw(self, shape):
        # Method drawing a shape on the canvas.
        self.__canvas.delete(self.__tmp_rendered)
        rendered_shape = None
        if shape['type'] == 'rectangle' and shape['mode'] == 'normal':
            rendered_shape = Rectangle(shape)
        elif shape['type'] == 'rectangle' and shape['mode'] == 'straight':
            rendered_shape = Square(shape)
        elif shape['type'] == 'oval' and shape['mode'] == 'normal':
            rendered_shape = Oval(shape)
        elif shape['type'] == 'oval' and shape['mode'] == 'straight':
            rendered_shape = Circle(shape)
        elif shape['type'] == 'line' and shape['mode'] == 'normal':
            rendered_shape = Line(shape)
        elif shape['type'] == 'line' and shape['mode'] == 'straight':
            rendered_shape = Diagonal(shape)
        shape_id = rendered_shape.draw_on(self.__canvas)
        return shape_id
Пример #30
0
class MapUI:
    def __init__(self, master):
        def center(win):
            win.update_idletasks()
            width = win.winfo_width()
            height = win.winfo_height()
            x = (win.winfo_screenwidth() // 4) - (width // 2) + 40
            y = (win.winfo_screenheight() // 4) - (height // 2) + 40
            win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

        def callback(event):
            event.widget.focus_set()
            print "clicked at", event.x, event.y

            if self.add_tasks_flg.get() == 1:
                # Select number of robots
                # Define elements of pop up window
                self.top = Toplevel()

                self.num_robots = StringVar(self.top)
                self.num_robots.set("1")  # default value
                w = OptionMenu(self.top, self.num_robots, '1', '2', '3',
                               '4').grid(row=0, column=1)
                text1 = Message(self.top, text="Number of robots:",
                                width=150).grid(row=0, column=0)

                self.e = Entry(self.top, width=10)
                self.e.grid(row=1, column=1)
                text2 = Message(self.top, text="Task duration:",
                                width=150).grid(row=1, column=0)
                text3 = Message(self.top, text="(s)", width=60).grid(row=1,
                                                                     column=2)

                newline = Message(self.top, text=" ").grid(row=2)

                button = Button(self.top,
                                text='Enter',
                                command=lambda: self.enter_task(event)).grid(
                                    row=3, column=1)
                button_cancel = Button(self.top,
                                       text='Cancel',
                                       command=self.cancel_task).grid(row=3,
                                                                      column=2)

                center(self.top)

        master.title("Map Interface")
        master.minsize(width=1000, height=750)
        master.maxsize(width=1000, height=750)
        master.config(bg=BKG_COLOUR)
        self.master = master

        # Canvas for overlaying map
        self.map_canvas = Canvas(master,
                                 width=CANVAS_W,
                                 height=CANVAS_H,
                                 bg='gray85',
                                 highlightthickness=0)
        self.map_canvas.pack(side='right', padx=50)
        self.map_canvas.bind("<Button-1>", callback)
        global CANVAS_PTR
        CANVAS_PTR = self.map_canvas
        self.master.update()
        w = self.map_canvas.winfo_width()
        h = self.map_canvas.winfo_height()
        # Overlay a grid
        for i in range(0, w, SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(i, 0, i, h, dash=1)
        for i in range(0, h, SQ_SIZE):
            if i != 0:
                self.map_canvas.create_line(0, i, w, i, dash=1)

        # Load in flame icon from flame.gif
        self.flame_icon = PhotoImage(file="flame.gif")
        # Load in the drone icon from drone.gif
        global DRONE_ICON
        DRONE_ICON = PhotoImage(file="drone.gif")

        buttons_frame = Canvas(master,
                               width=163,
                               height=230,
                               bg=BUTTONS_BKG_COLOUR,
                               highlightthickness=1,
                               highlightbackground='dim grey')
        buttons_frame.place(x=40, y=200)

        # Define UI buttons
        self.add_tasks_flg = IntVar()
        self.add_tasks_b = Checkbutton(master,
                                       text="Add Tasks",
                                       variable=self.add_tasks_flg,
                                       highlightbackground=BUTTONS_BKG_COLOUR,
                                       background=BUTTONS_BKG_COLOUR)
        self.add_tasks_b.place(x=77, y=240)

        self.clear_wp_b = Button(master,
                                 text='Clear Tasks',
                                 command=self.clear_wp,
                                 highlightbackground=BUTTONS_BKG_COLOUR)
        self.clear_wp_b.config(width=10)
        self.clear_wp_b.place(x=65, y=270)
        '''
        self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR)
        self.gen_wp_file_b.config(width=20)
        self.gen_wp_file_b.place(x=20, y=250)
        '''

        self.land_b = Button(master,
                             text='Land',
                             command=self.land,
                             highlightbackground=BUTTONS_BKG_COLOUR)
        self.land_b.config(width=10)
        self.land_b.place(x=65, y=350)

        # Set up coordinate system conversion and display corners of room:
        file_obj = open('antenna_locations.txt', 'r')
        anchors = []
        for line in file_obj:
            cur_anchors = map(float, line.split())
            anchors.append(cur_anchors)
        file_obj.close()
        anchors = (np.array(anchors)).T

        # Find largest (abs) x and y values to use a reference for conversion ratio
        x_vals = anchors[0]
        largest_x_val = x_vals[np.argmax(abs(x_vals))]
        y_vals = anchors[1]
        largest_y_val = y_vals[np.argmax(abs(y_vals))]

        if largest_x_val > largest_y_val:
            largest_y_val = largest_x_val
        else:
            largest_x_val = largest_y_val

        global m_per_pixel_x
        m_per_pixel_x = float(largest_x_val / (CANVAS_W / 2))
        global m_per_pixel_y
        m_per_pixel_y = float(largest_y_val / (CANVAS_H / 2))

        # Place antenna (anchors) on UI
        anchors = anchors.T
        for cur_anchor in anchors:
            x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W / 2
            y_pixel_loc = -1 * (cur_anchor[1] / m_per_pixel_y) + CANVAS_H / 2

            # Draw antenna @ location
            global ANTENNA_LIST
            antenna_id = self.map_canvas.create_oval(x_pixel_loc - 15,
                                                     y_pixel_loc - 15,
                                                     x_pixel_loc + 15,
                                                     y_pixel_loc + 15,
                                                     fill='red')

        self.master.update()

    global SQ_SIZE
    SQ_SIZE = 20
    global BKG_COLOUR
    BKG_COLOUR = 'gray95'
    global BUTTONS_BKG_COLOUR
    BUTTONS_BKG_COLOUR = 'grey66'
    global CANVAS_W
    CANVAS_W = 700
    global CANVAS_H
    CANVAS_H = 700
    global TASK_LIST
    TASK_LIST = None
    global m_per_pixel_x
    m_per_pixel_x = None
    global m_per_pixel_y
    m_per_pixel_y = None
    global NEW_TASK_FLAG
    NEW_TASK_FLAG = False
    global ANTENNA_LIST
    ANTENNA_LIST = None
    global DRONE_ICON
    DRONE_ICON = None

    flame_icon = None
    ui_wp_list = None
    #task_list = None
    add_wp_flag = False
    task_id = 0
    add_tasks_flg = None

    def add_tasks(self):
        print "adding tasks"
        # function imp here
        self.add_wp_flag = True
        self.map_canvas.config(cursor='pencil')

    def clear_wp(self):
        print "clear tasks"
        global TASK_LIST
        TASK_LIST = None
        for element_id in self.ui_wp_list:
            self.map_canvas.delete(element_id[0])
        self.ui_wp_list = None

    '''
    def gen_wp_file(self):
        print "generate wp file"
        # function imp here
    '''

    def land(self):
        # Send a new task with position (0,0,0) z=0 tells drone to land
        print("land")

    def enter_task(self, event):
        # Determine square (top left corner coords):
        w_start = event.x - event.x % SQ_SIZE
        h_start = event.y - event.y % SQ_SIZE

        #Translate pixel location to physical location
        x_pixel = event.x
        y_pixel = event.y
        # Find out how many pixels from center:
        x_pixel = x_pixel - CANVAS_W / 2
        x_physical = x_pixel * m_per_pixel_x

        #vertical case, note this is flipped
        y_pixel = y_pixel - CANVAS_W / 2
        y_pixel = -1 * y_pixel
        y_physical = y_pixel * m_per_pixel_y

        try:
            # Add to task list
            global TASK_LIST
            if TASK_LIST == None:
                TASK_LIST = [[
                    self.task_id,
                    int(self.num_robots.get()),
                    float(self.e.get()), x_physical, y_physical
                ]]
                global NEW_TASK_FLAG
                NEW_TASK_FLAG = True
            else:
                TASK_LIST.append([
                    self.task_id,
                    int(self.num_robots.get()),
                    float(self.e.get()), x_physical, y_physical
                ])
                global NEW_TASK_FLAG
                NEW_TASK_FLAG = True

            # Indicate task in UI
            element_id = self.map_canvas.create_image(event.x,
                                                      event.y,
                                                      image=self.flame_icon)
            if self.ui_wp_list == None:
                self.ui_wp_list = [[element_id]]
            else:
                self.ui_wp_list.append([element_id])
        except:
            print("Invalid Task Entry")

        self.map_canvas.config(cursor='arrow')
        self.add_wp_flag = False

        print(TASK_LIST)

        self.task_id = self.task_id + 1
        self.top.destroy()

    def cancel_task(self):
        self.top.destroy()
Пример #31
0
class Screen(Observer):
    def __init__(self, parent, model_x, model_y, bg="white"):
        self.canvas = Canvas(parent, bg=bg)
        self.model_x = model_x
        self.model_y = model_y
        print("parent", parent.cget("width"), parent.cget("height"))

        self.showX = True
        self.showY = True

        self.frame = Frame(parent)
        # Signal X
        self.magnitude_x = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="m_x",
                                 label="Magnitude X",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.frequency_x = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="f_x",
                                 label="Frequency X",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.phase_x = Scale(self.frame,
                             length=250,
                             orient="horizontal",
                             name="p_x",
                             label="Phase X",
                             sliderlength=20,
                             showvalue=0,
                             from_=0,
                             to=5,
                             tickinterval=25)
        # Signal Y
        self.magnitude_y = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="m_y",
                                 label="Magnitude Y",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.frequency_y = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="f_y",
                                 label="Frequency Y",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.phase_y = Scale(self.frame,
                             length=250,
                             orient="horizontal",
                             name="p_y",
                             label="Phase Y",
                             sliderlength=20,
                             showvalue=0,
                             from_=0,
                             to=5,
                             tickinterval=25)

        self.frame2 = Frame(parent, bg="black")
        self.varX = IntVar()
        self.varY = IntVar()
        self.varXY = IntVar()
        self.lbl = Label(self.frame2, text="Courbes", fg="black")
        # Boutons de sélection (X, Y ou X-Y)
        self.caseX = Checkbutton(self.frame2,
                                 text="X",
                                 variable=self.varX,
                                 command=self.getX)
        self.caseY = Checkbutton(self.frame2,
                                 text="Y",
                                 variable=self.varY,
                                 command=self.getY)
        self.caseXY = Checkbutton(self.frame2,
                                  text="XY",
                                  variable=self.varXY,
                                  command=self.getXY)

        self.caseXY.select()

        self.wi = self.canvas.cget("width")
        self.hi = self.canvas.cget("height")

        self.stepx = 0
        self.stepy = 0
        # Step x
        self.step_x = Entry(parent, name="x")
        # Step y
        self.step_y = Entry(parent, name="y")

    def update(self, model):
        print("View update")
        if model.getId() == 0:
            signal = model.get_signal()
            self.plot_signal(signal)
        elif model.getId() == 1:
            signal = model.get_signal()
            self.plot_signal(signal, "blue")
        else:
            raise ("Error")

    # Signal X
    def get_magnitude(self, whichOne):
        if whichOne == 0:
            return self.magnitude_x
        elif whichOne == 1:
            return self.magnitude_y
        else:
            raise ("Error")

    def get_frequency(self, whichOne):
        if whichOne == 0:
            return self.frequency_x
        elif whichOne == 1:
            return self.frequency_y
        else:
            raise ("Error")

    def get_phase(self, whichOne):
        if whichOne == 0:
            return self.phase_x
        elif whichOne == 1:
            return self.phase_y
        else:
            raise ("Error")

    def get_step_x(self):
        return self.step_x

    def get_step_y(self):
        return self.step_y

    def getX(self):
        print("update_X(self,event)")
        self.caseY.deselect()
        self.caseXY.deselect()
        self.showX = True
        self.showY = False
        self.update(self.model_x)
        if self.canvas.find_withtag("signal_y"):
            self.canvas.delete("signal_y")

    def getY(self):
        print("update_Y(self,event)")
        self.caseX.deselect()
        self.caseXY.deselect()
        self.showX = False
        self.showY = True
        self.update(self.model_y)
        if self.canvas.find_withtag("signal_x"):
            self.canvas.delete("signal_x")

    def getXY(self):
        print("update_XY(self,event)")
        self.caseX.deselect()
        self.caseY.deselect()
        self.showX = True
        self.showY = True
        self.update(self.model_x)
        self.update(self.model_y)

    def plot_signal(self, signal, color="red"):
        w, h = self.wi, self.hi
        width, height = int(w), int(h)
        if color == "red" and self.showX == True:
            if self.canvas.find_withtag("signal_x"):
                self.canvas.delete("signal_x")
            if signal and len(signal) > 1:
                plot = [(x * width, height / 2.0 * (y + 1))
                        for (x, y) in signal]
                signal_id = self.canvas.create_line(plot,
                                                    fill=color,
                                                    smooth=1,
                                                    width=3,
                                                    tags="signal_x")
        elif color == "blue" and self.showY == True:
            if self.canvas.find_withtag("signal_y"):
                self.canvas.delete("signal_y")
            if signal and len(signal) > 1:
                plot = [(x * width, height / 2.0 * (y + 1))
                        for (x, y) in signal]
                signal_id = self.canvas.create_line(plot,
                                                    fill=color,
                                                    smooth=1,
                                                    width=3,
                                                    tags="signal_y")

    def grid(self, step_x, step_y):
        w, h = self.wi, self.hi
        width, height = int(w), int(h)
        self.stepx = (width - 10) / step_x * 1.
        self.stepy = (height - 10) / step_y * 1.
        for t in range(1, step_x + 2):
            x = t * self.stepx
            self.canvas.create_line(x, 0, x, height, tags="grid")
            #self.canvas.create_line(x,height/2-4,x,height/2+4)
        for t in range(1, step_y + 2):
            y = t * self.stepy
            self.canvas.create_line(0, y, width, y, tags="grid")
            #self.canvas.create_line(width/2-4,y,width/2+4,y)

    def resize(self, event):
        if event:
            self.wi = event.width
            self.hi = event.height

            self.canvas.delete("grid")
            self.plot_signal(self.model_x.get_signal())
            self.plot_signal(self.model_y.get_signal(), "blue")
            self.grid(25, 25)

    def packing(self):
        self.canvas.pack(fill="both", expand=1)
        self.step_x.pack(expand=1, fill="both")
        self.step_y.pack(expand=1, fill="both")
        self.frame.pack(expand=1, fill="both")
        self.magnitude_x.grid(row=0, column=0)
        self.magnitude_y.grid(row=0, column=1)
        self.frequency_x.grid(row=1, column=0)
        self.frequency_y.grid(row=1, column=1)
        self.phase_x.grid(row=2, column=0)
        self.phase_y.grid(row=2, column=1)
        self.frame2.pack(side="bottom", expand=1)
        self.lbl.grid(row=0, column=0)
        self.caseX.grid(row=0, column=1)
        self.caseY.grid(row=0, column=2)
        self.caseXY.grid(row=0, column=3)
Пример #32
0
class FullScreenWindow:

    def __init__(self, label_timeout, max_elements):
        self.count = 0
        self.colors_count = 0
        self.tk = Tk()
        self.max_elements = max_elements
        self.frame = Frame(self.tk)
        self.frame.bind("<Key>", self.key_press)
        self.frame.focus_set()
        self.state = False
        self.tk.attributes("-fullscreen", True)
        self.label_timeout = label_timeout

        self.screen_width = self.tk.winfo_screenwidth()
        self.screen_height = self.tk.winfo_screenheight()
        screen_resolution = str(self.screen_width) + 'x' + str(self.screen_height)
        self.tk.geometry(screen_resolution)
        self.canvas = Canvas(self.frame, height=self.screen_height, width=self.screen_width)
        self.canvas.pack(fill=BOTH)

        self.frame.pack()
        self.objects = deque()

    def key_press(self, key):
        self.draw_triangle()

    def draw_triangle(self):
        x1 = random.uniform(0, 1) * self.screen_width
        y1 = random.uniform(0, 1) * self.screen_height

        x2 = random.uniform(0, 1) * self.screen_width
        y2 = random.uniform(0, 1) * self.screen_height

        x3 = random.uniform(0, 1) * self.screen_width
        y3 = random.uniform(0, 1) * self.screen_height

        x4 = random.uniform(0, 1) * self.screen_width
        y4 = random.uniform(0, 1) * self.screen_height

        x5 = random.uniform(0, 1) * self.screen_width
        y5 = random.uniform(0, 1) * self.screen_height

        colors = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta']
        if self.colors_count % 7 == 0:
            self.colors_count = 0

        if self.count == 0:
            o = self.canvas.create_line(x1, y1, x2, y2, x3, y3, x1, y1)
            self.count = 1
        elif self.count == 1:
            o = self.canvas.create_rectangle(x1, y1, x2, y2, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 2
        elif self.count == 2:
            o = self.canvas.create_oval(x1, y1, x2, y2, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 3
        elif self.count == 3:
            o = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 0
        if len(self.objects) >= self.max_elements:
            obj_to_remove = self.objects.pop()
            self.canvas.delete(obj_to_remove)
        self.objects.appendleft(o)
        self.canvas.after(self.label_timeout,self.canvas.delete, o)
        self.frame.pack(fill=BOTH, expand=1)
Пример #33
0
class DiscreteTAMPViewer(object):
    def __init__(self,
                 rows,
                 cols,
                 width=500,
                 height=250,
                 side=25,
                 block_buffer=10,
                 title='Grid',
                 background='tan',
                 draw_fingers=False):
        assert (rows <= MAX_ROWS)
        assert (cols <= MAX_COLS)

        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)

        self.width = width
        self.height = height
        self.rows = rows
        self.cols = cols
        self.canvas = Canvas(top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        self.side = side
        self.block_buffer = block_buffer
        self.draw_fingers = draw_fingers
        self.cells = {}
        self.robot = []
        self.draw_environment()

    def transform_r(self, r):
        return self.table_y1 + r * (self.side + 2 * self.block_buffer
                                    ) + 2 * self.block_buffer + self.side / 2

    def transform_c(self, c):
        # assert r >= 0 and r < self.width
        return self.table_x1 + c * (self.side + 2 * self.block_buffer
                                    ) + 2 * self.block_buffer + self.side / 2

    def draw_environment(self, table_color='lightgrey', bin_color='grey'):
        table_width = self.cols * (
            self.side + 2 * self.block_buffer) + 2 * self.block_buffer
        table_height = self.rows * (
            self.side + 2 * self.block_buffer) + 2 * self.block_buffer

        border_buffer = 50
        #self.table_x1 = border_buffer
        self.table_y1 = self.height - table_height - border_buffer
        self.table_x1 = self.width / 2 - table_width / 2
        #self.table_y1 = self.height/2-table_height/2

        bin_width = 20
        self.environment = [
            self.canvas.create_rectangle(self.table_x1,
                                         self.table_y1,
                                         self.table_x1 + table_width,
                                         self.table_y1 + table_height,
                                         fill=table_color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(self.table_x1 - bin_width,
                                         self.table_y1,
                                         self.table_x1,
                                         self.table_y1 + table_height,
                                         fill=bin_color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(self.table_x1 + table_width,
                                         self.table_y1,
                                         self.table_x1 + table_width +
                                         bin_width,
                                         self.table_y1 + table_height,
                                         fill=bin_color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(self.table_x1,
                                         self.table_y1 + table_height,
                                         self.table_x1 + table_width,
                                         self.table_y1 + table_height +
                                         bin_width,
                                         fill=bin_color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(
                self.table_x1 - bin_width,
                self.table_y1 + table_height,
                self.table_x1 + table_width + bin_width,
                self.table_y1 + table_height + bin_width,
                fill=bin_color,
                outline='black',
                width=2),
        ]

        pose_radius = 2
        for r in range(self.rows):
            for c in range(self.cols):
                x = self.transform_c(c)
                y = self.transform_r(r)
                self.environment.append(
                    self.canvas.create_oval(x - pose_radius,
                                            y - pose_radius,
                                            x + pose_radius,
                                            y + pose_radius,
                                            fill='black'))

    def draw_robot(self, r, c, color='yellow'):
        # TODO - could also visualize as top grasps instead of side grasps
        grasp_buffer = 3  # 0 | 3 | 5
        finger_length = self.side + grasp_buffer  # + self.block_buffer
        finger_width = 10
        gripper_length = 20
        if self.draw_fingers:
            gripper_width = self.side + 2 * self.block_buffer + finger_width
        else:
            gripper_width = self.side
        stem_length = 50
        stem_width = 20

        x = self.transform_c(c)
        y = self.transform_r(
            r) - self.side / 2 - gripper_length / 2 - grasp_buffer
        finger_x = gripper_width / 2 - finger_width / 2
        self.robot = [
            self.canvas.create_rectangle(x - stem_width / 2.,
                                         y - stem_length,
                                         x + stem_width / 2.,
                                         y,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(x - gripper_width / 2.,
                                         y - gripper_length / 2.,
                                         x + gripper_width / 2.,
                                         y + gripper_length / 2.,
                                         fill=color,
                                         outline='black',
                                         width=2),
        ]
        if self.draw_fingers:
            self.robot += [
                self.canvas.create_rectangle(x + finger_x - finger_width / 2.,
                                             y,
                                             x + finger_x + finger_width / 2.,
                                             y + finger_length,
                                             fill=color,
                                             outline='black',
                                             width=2),
                self.canvas.create_rectangle(x - finger_x - finger_width / 2.,
                                             y,
                                             x - finger_x + finger_width / 2.,
                                             y + finger_length,
                                             fill=color,
                                             outline='black',
                                             width=2),
            ]
        self.canvas.update()

    def draw_block(self, r, c, name='', color='red'):
        x = self.transform_c(c)
        y = self.transform_r(r)
        self.cells[(x, y)] = [
            self.canvas.create_rectangle(x - self.side / 2.,
                                         y - self.side / 2.,
                                         x + self.side / 2.,
                                         y + self.side / 2.,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text(x, y, text=name),
        ]

    # def delete(self, (x, y)):
    #  if (x, y) in self.cells:
    #    self.canvas.delete(self.cells[(x, y)])

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

    def save(self, filename):
        self.canvas.postscript(file='%s.ps' % filename, colormode='color')
        from PIL import ImageGrab
        ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
Пример #34
0
class SurfaceManipulator(Frame):
    r"""
    A translation surface editor in tk.
    """

    # STATIC METHODS AND OBJECTS

    current = None
    # boolean variable to remember if the hook was run!
    _clear_hook_was_run = 0

    @staticmethod
    def launch(geometry="800x700+10+10"):
        r"""Prefered way to gain access to a SurfaceManipulator window."""
        if SurfaceManipulator.current is None:
            SurfaceManipulator._clear_hook()
            root = Tk()
            root.geometry(geometry)
            SurfaceManipulator.current = SurfaceManipulator(root)
        return SurfaceManipulator.current

    @staticmethod
    def _window_destroyed(surface_manipulator):
        if SurfaceManipulator.current is surface_manipulator:
            SurfaceManipulator.current = None

    @staticmethod
    def _clear_hook():
        if not SurfaceManipulator._clear_hook_was_run:
            # Hack due to Nathan Dunfield (http://trac.sagemath.org/ticket/15152)
            import IPython.lib.inputhook as ih
            ih.clear_inputhook()
            SurfaceManipulator._clear_hook_was_run = 1

    # NORMAL METHODS

    def __init__(self, parent, surface=None, surfaces=[]):
        r"""
        INPUT:
        - ``surfaces`` -- a list of surfaces that the editor may modify
        - ``surface`` -- surface selected by default
        - ``parent`` -- parent Tk window
        """
        Frame.__init__(self, parent)
        self._parent = parent
        self.pack(fill="both", expand=1)

        # Run something when closing
        self._parent.wm_protocol("WM_DELETE_WINDOW", self.exit)

        # Surface currently being manipulated
        self._surface = None
        # List of surfaces in editor
        self._surfaces = []
        # More variables to initialize
        self._currentActor = None
        # Initialization of GUI
        self._init_menu()
        self._init_gui()
        # Setup surface list
        for s in surfaces:
            self.add_surface(s)
        # Setup initial surface
        if surface is not None:
            self.add_surface(surface)
        self.set_surface(surface)

    def __repr__(self):
        return "Surface manipulator"

    def add_mega_wollmilchsau(self):
        from geometry.mega_wollmilchsau import MegaWollmilchsau
        s = MegaWollmilchsau()
        sm, sb = s.get_bundle()
        self.set_surface(sb)

    def add_octagon(self):
        from geometry.similarity_surface_generators import TranslationSurfaceGenerators
        ss = TranslationSurfaceGenerators.regular_octagon()
        ss.edit()

    def _init_menu(self):

        self._menubar = Menu(self._parent)
        menubar = self._menubar
        self._parent.config(menu=menubar)

        #new_menu = Menu(menubar, tearoff=0)
        #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface)

        file_menu = Menu(menubar, tearoff=0)
        #file_menu.add_cascade(label="New", menu=new_menu)
        file_menu.add_command(label="Octagon", command=self.add_octagon)
        file_menu.add_command(label="MegaWollmilchsau",
                              command=self.add_mega_wollmilchsau)
        file_menu.add_separator()
        file_menu.add_command(label="About", command=self.on_about)
        file_menu.add_command(label="Export PostScript",
                              command=self.on_export)
        file_menu.add_command(label="Exit",
                              command=self.exit,
                              accelerator="Alt+F4")
        menubar.add_cascade(label="File", underline=0, menu=file_menu)

        self._surface_menu = Menu(menubar, tearoff=0)
        self._selected_surface = IntVar()
        self._selected_surface.set(-1)
        menubar.add_cascade(label="Surface",
                            underline=0,
                            menu=self._surface_menu)
        self._surface_menu.add_radiobutton(label="None",
                                           command=self.menu_select_surface,
                                           variable=self._selected_surface,
                                           value=-1)

    def _init_gui(self):
        self._parent.title("FlatSurf Editor")

        self._canvas = Canvas(self, bg="#444", width=300, height=200)
        self._canvas.pack(fill="both", expand=1)

        self.bottom_text = Label(self, text="Welcome to FlatSurf.", anchor="w")
        self.bottom_text.pack(fill="x", expand=0)

        self.set_actor(None)

    def add_surface(self, newsurface):
        r"""
        Add a surface to the display list for the window.
        Returns the index of the new surface in the surface list.
        """
        if (newsurface == None):
            return -1
        i = 0
        for s in self._surfaces:
            if (s == newsurface):
                return i
            i = i + 1
        self._surfaces.append(newsurface)
        newsurface.zoom_fit_nice_boundary()
        self._reset_surface_menu()
        return len(self._surfaces) - 1

    def exit(self):
        SurfaceManipulator._window_destroyed(self)
        self._parent.destroy()

    def find_bundle(self, surface):
        for surface_bundle in self._surfaces:
            if surface is surface_bundle.get_surface():
                return surface_bundle
        return None

    def get_bundle(self):
        return self._surface

    def get_bundles(self):
        return self._surfaces

    def get_canvas(self):
        return self._canvas

    def get_center(self):
        r"""
        Return the center of the canvas as a pair of integers.
        """
        return (self.get_width() / 2, self.get_height() / 2)

    def get_height(self):
        r"""
        Return the height of the canvas (an integer).
        """
        return self.get_canvas().winfo_height()

    def get_parent(self):
        return self._parent

    def get_surface_bundle(self):
        r"""
        Get the current surface bundle, or None if there is none.
        """
        return self._surface

    def get_width(self):
        r"""
        Return the width of the canvas (an integer).
        """
        return self.get_canvas().winfo_width()

    def menu_select_surface(self):
        r"""
        Called when a surface is selected from a menu.
        """
        i = self._selected_surface.get()
        if i == -1:
            self.set_surface(None)
        else:
            self.set_surface(self._surfaces[i])

    def on_about(self):
        self.set_text("Written by Vincent Delecroix and Pat Hooper.")

    def on_delete_junk(self):
        self._canvas.delete("junk")

    def on_export(self):
        r"""
        Export image as postscript file.
        """
        myFormats = [('PostScript', '*.ps')]
        fileName = tkFileDialog.asksaveasfilename(parent=self,
                                                  filetypes=myFormats,
                                                  title="Save image as...")
        if len(fileName) > 0:
            self._canvas.update()
            self._canvas.postscript(file=fileName)
            self.set_text("Wrote image to " + fileName)

#    def on_new_similarity_surface(self):
#        s = CreateSimilaritySurfaceBundle(len(self._surfaces),self)
#        if s is not None:
#            i = self.set_surface(s)
#            self.set_text("Created new surface `"+self._surfaces[i].get_name()+"'.")

    def _on_no_surface(self):
        self._canvas.delete("all")

    def _on_zoom(self):
        self.set_actor(ZoomActor(self))

    def _on_zoom_box(self):
        self.set_actor(ZoomBoxActor(self))

    def _on_redraw_all(self):
        if self._surface is not None:
            self._surface.redraw_all()

    def _on_recenter(self):
        self.set_actor(RecenterActor(self))

    def _reset_menus(self):
        r"""
        Reset all menus except the file and surface menu
        """
        # The following loop removes all but the first two menus (File and Surface).
        num = len(self._menubar.children)
        for i in range(num, 2, -1):
            self._menubar.delete(i)
        if self._surface != None:
            self._surface.make_menus(self._menubar)

    def _reset_surface_menu(self):
        r"""
        Reset the surface menu.
        """
        ### This is a hack to get the number of items in the menu:
        num = self._surface_menu.index(100) + 1
        # First we remove everything but the first entry ("None")
        for i in range(num - 1, 0, -1):
            #print("removing a child2: "+str(i)+" of "+str(num))
            self._surface_menu.delete(i)
        # Add an entry for every surface in the list.
        for i in range(len(self._surfaces)):
            surface = self._surfaces[i]
            self._surface_menu.add_radiobutton(
                label=surface.get_name(),
                command=self.menu_select_surface,
                variable=self._selected_surface,
                value=i)

    def set_text(self, text):
        self.bottom_text["text"] = text

    def set_actor(self, actor):
        r"""
        Set the current mode of user interaction.
        """
        if (actor != self._currentActor):
            if self._currentActor != None:
                self._currentActor.on_deactivate()
            if (actor == None):
                self.set_text("Nothing going on.")
                # Event bindings
                self._canvas.unbind('<Button-1>')
                self._canvas.unbind('<Button-2>')
                self._canvas.unbind('<Button-3>')
                self._canvas.unbind('<Double-Button-1>')
                self._canvas.unbind('<Shift-Button-1>')
                self._canvas.unbind('<Motion>')
                self.unbind('<FocusIn>')
                self.unbind('<FocusOut>')
                #self._canvas.unbind('<ButtonPress-1>')
                self._canvas.unbind('<ButtonRelease-1>')
                self._canvas.unbind('<B1-Motion>')
                self._parent.unbind('<Key>')
                self._parent.unbind('<KeyRelease>')
            else:
                # Event bindings
                self._canvas.bind('<Button-1>', actor.single_left_click)
                self._canvas.bind('<Double-Button-1>', actor.double_left_click)
                self._canvas.bind('<Triple-Button-1>', actor.double_left_click)
                self._canvas.bind('<Button-2>', actor.single_middle_click)
                self._canvas.bind('<Double-Button-2>',
                                  actor.double_middle_click)
                self._canvas.bind('<Triple-Button-2>',
                                  actor.double_middle_click)
                self._canvas.bind('<Button-3>', actor.single_right_click)
                self._canvas.bind('<Double-Button-3>',
                                  actor.double_right_click)
                self._canvas.bind('<Triple-Button-3>',
                                  actor.double_right_click)
                self._canvas.bind('<Shift-Button-1>', actor.shift_click)
                self._canvas.bind('<Motion>', actor.mouse_moved)
                #self._canvas.bind('<ButtonPress-1>', actor.left_mouse_pressed)
                self._canvas.bind('<ButtonRelease-1>',
                                  actor.left_mouse_released)
                self._canvas.bind('<B1-Motion>', actor.left_dragged)
                self.bind('<FocusIn>', actor.focus_in)
                self.bind('<FocusOut>', actor.focus_out)
                self._parent.bind('<Key>', actor.key_press)
                self._parent.bind('<KeyRelease>', actor.key_release)
                self._currentActor = actor
                self._currentActor.on_activate()

    def set_surface(self, surface_bundle):
        r"""
        Set the current surface to the one given by surface_bundle
        """
        i = self.add_surface(surface_bundle)
        if surface_bundle != self._surface:
            self._canvas.delete("all")
            self._surface = surface_bundle
            self._surface_menu.invoke(i + 1)
            if i >= 0:
                self.set_text("Switched to `" + self._surface.get_name() +
                              "'.")
                self._parent.title(self._surface.get_name())
                self._reset_menus()
                # stop the actor (was a bug).
                self.set_actor(None)
                if isinstance(self._surface, EditorRenderer):
                    self._surface.initial_render()
            else:
                self.set_text("No surface selected.")
                self._parent.title("FlatSurf Editor")
                self._reset_menus()
                self.set_actor(None)
        return i

    def surface_renamed(self):
        if self._surface is not None:
            self._parent.title(self._surface.get_name())
            self._reset_surface_menu()
Пример #35
0
class TutorWindow( Toplevel ):
    """
    Window for displaying a basic help
    """
    labels      = {}            # Dictionary for keeping clickable labels
    size_x      = 600           # horizontal size of canvas
    size_y      = 800           # vertical size of canvas
    last_images = []            # handle on images currently on the canvas
    images      = []            # new images to go on the canvas
    curr_key    = None          # Current key that is looked at
    
    # Names of label links and list of pictures to load. These pictures are generated from a pdf by save as, type .png
    help_dict = { "Get Pictures"    : [ "Get_Pictures_Page_1.png" , "Get_Pictures_Page_2.png" , "Get_Pictures_Page_3.png"  ],
                  "Save Pictures"   : [ "Save_Pictures_Page_1.png", "Save_Pictures_Page_2.png", "Save_Pictures_Page_3.png" ],
                  "Pictures Effects": [ "Pic_Effects_Page_1.png"  , "Pic_Effects_Page_2.png"                               ],
                  "Options"         : [ "Options.png"                                                                      ],
                }

    def __init__( self ):
        """
        Initialize window settings
        """
        
        Toplevel.__init__( self )
        self.title( "Tutorial" )
        self.iconbitmap( ICON_FILENAME )
        self.geometry( "+100+50" )
        
        # init frames for window. This window contains complicated frames. i.e. frames with frames inside them.
        fr11 = Frame( self )
        fr1  = Frame( fr11 )
        fr2  = Frame( fr11 )
        fr3  = Frame( self )
        
        # create labels links for displaying different help information
        for name in self.help_dict:
            self.labels[ name ] = Label( fr1, text=name, fg="blue" ) 
            self.labels[ name ].bind( "<ButtonPress-1>", lambda e, arg=name: self.HandleLB( e, arg ) )
            self.labels[ name ].pack( fill=X )
        fr1.pack( side=LEFT )
        
        # create/configure canvas and scrollbar for displaying help pictures
        self.canv = Canvas( fr2, width=self.size_x, height=self.size_y, scrollregion=( 0, 0, 300, 0 ) )
        self.sbar = Scrollbar( fr2 )
        self.sbar.config( command=self.canv.yview )
        self.canv.config( yscrollcommand=self.sbar.set )
        self.canv.focus_set()
        self.sbar.pack( side=RIGHT, fill=Y )
        self.canv.pack( side=LEFT, fill=Y )

        fr2.pack( side=LEFT )
        fr11.pack()
    
        # create ok button for closing the window
        btn = Button( fr3, text="Ok", width=10, command=self.quit )
        btn.pack( side=LEFT )
        fr3.pack()
        
        self.mainloop()
        self.destroy()
        
    def HandleLB( self, event, key ):
        """
        handle clicking a label link
        """
        
        if( key != self.curr_key ):
        
        
            # reset the position of the scrollbar to the top
            self.canv.yview_moveto( 0.0 )

            # load new images
            print "Key: ", key
            self.LoadImages( key )
            
            # change formatting on labels, color red for current one clicked
            self.FormatLabels( key )
            
            # remove old pictures from the canvas before adding new ones
            if( len( self.last_images ) != 0 ):
                for image in self.last_images:
                    self.canv.delete( image )
            self.last_images = []
    
            # There's an offset required in order to show everything correctly, don't know why...
            image_y = 390
    
            # change scrollable area for the canvas to be exact size of all pictures
            self.canv.config( scrollregion=( 0, 0, 300, 776*len( self.images ) ) )
            
            # add new pictures to canvas stacking them on top of each other and making them seamless
            for i in range( len( self.images ) ):
                self.last_images.append( self.canv.create_image( ( self.size_x/2, image_y ), image=self.images[ i ] ) )
                image_y += self.images[ i ].height()
                
            self.curr_key = key
            
    def LoadImages( self, key ):
        """
        load new inmages into class storage
        """
        self.images = []
        print "help_dict: ", self.help_dict        
        # get images from hardcoded array
        for image in self.help_dict[ key ]:
            
            # open PIL image
            print "image: ", path.join( HELP_DIR, image )

            image1 = PILopen( path.join( HELP_DIR, image ) )
    
            # resize to fit canvas area
            image1 = image1.resize( ( self.size_x , self.size_y ), ANTIALIAS )
            
            # make into a tkimage
            im = PhotoImage( image1 )
             
            # add to list of images to display 
            self.images.append( im )
    
    def FormatLabels( self, key ):
        for name in self.labels:
            self.labels[ name ].config( fg="blue" )
            
        self.labels[ key ].config( fg="red" )
Пример #36
0
class liuyao:
	def __init__(self,root,gua64):
		self.cntoint={u'少阳-----':'1',u'少阴-- --':'2',u'老阳--O--':'3',u'老阴--X--':'4'}
		self.tfont=tkFont.Font(family='Fixdsys',size=25,weight=tkFont.BOLD)
		self.gfont=tkFont.Font(family='Fixdsys',size=13,weight=tkFont.BOLD)
		self.dgua=[] #动爻
		self.ygua=[] #原始卦
		self.bbgua=[] #变卦
		self.yguastr=[] #原始卦
		self.gua=[] #只有12的卦
		self.pabout=True #右键显示消失淮南标题
		self.guax=200
		self.guay=100
		self.liushen={'甲':0,'乙':0,'丙':1,'丁':1,'戊':2,'己':3,'庚':4,'辛':4,'壬':5,'癸':5}
		self.liushencn=['青龙','朱雀','勾陈','腾蛇','白虎','玄武']
		self.tiangan={'甲':1,'乙':2,'丙':3,'丁':4,'戊':5,'己':6,'庚':7,'辛':8,'壬':9,'癸':10}
		self.dizhi={'子':1,'丑':2,'寅':3,'卯':4,'辰':5,'巳':6,'午':7,'未':8,'申':9,'酉':10,'戌':11,'亥':12}
		self.kongwangzu=['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥']
		self.root=root
		self.root.title(u'===六爻排盘===[淮南内部专用]')
		self.root.minsize(550,380)
		self.root.maxsize(550,380)
		self.canvas=Canvas(root,width=460,height=380,bg='gray')
		# self.picyang=PhotoImage(file='tk\\yang.gif')
		# self.picyin=PhotoImage(file='tk\\yin.gif')
		self.canvas.place(relx=0,rely=0)
		self.com={}
		for i in xrange(6):
			self.com[i]=Combobox(root,state='readonly')
			self.com[i]['values']=(u'少阳-----',u'少阴-- --',u'老阳--O--',u'老阴--X--')
			self.com[i].current(0)
			self.com[i].place(relx=0.85,rely=0.36-0.07*i,width=80)


		bt1=Button(self.root,text=u'排盘',command=self.paipan)
		bt2=Button(self.root,text=u'清除',command=self.cls)
		l1=Label(self.root,text=u'右键水印')
		l1.place(x=480,y=327)
		# bt1.place(relx=0.85,rely=0.35+0.7)
		# bt1.pack(side='right')
		bt1.place(x=467,y=170,width=78)
		bt2.place(x=467,y=350,width=78)
		self.date() #干支
		#===========================
		self.root.bind('<Button-3>',self.about)
	def cls(self):
		self.canvas.delete('pic')   #删除所有上次产生的ITEMS
		self.canvas.delete('liushen')



	def liushenf(self):  #配六神
		xu=self.liushen[self.ritian.encode('utf-8')]
		for i in xrange(6):
			self.canvas.create_text(self.guax-170,100+150-30*i,font=self.gfont,text=self.liushencn[xu],tag='liushen')
			xu+=1
			if xu>5:
				xu-=6

	def date(self):
		turl=urllib2.urlopen('http://www.nongli.com/item4/index.asp',timeout=10).read()
		soup=BeautifulSoup(turl)
		zu=soup.findAll('td',{'width':'74%','bgcolor':'#FFFFFF'})[1].text
		# print zu
		wanzu=[] #wanzu里面是完成的年月日干支
		wanzu.append(zu.split(' ')[0])
		wanzu.append(zu.split(' ')[2])
		wanzu.append(zu.split(' ')[3])
		for i in xrange(3):
			# print u'干支',wanzu[i]
			self.canvas.create_text(self.guax-90+60*i,30,text=wanzu[i],font=self.gfont,tag='riqi')
		ri=wanzu[2]
		self.ritian=list(ri)[0]
		self.ridi=list(ri)[1]
		self.kongwang()

	def kongwang(self):
		# print u'日干支:',self.ridi,self.ritian
		cha=self.dizhi[self.ridi.encode('utf-8')]-self.tiangan[self.ritian.encode('utf-8')]
		if cha<0:
			cha+=+10
		self.canvas.create_text(self.guax-90+120+30,30,font=self.gfont,text='(',tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+15,30,font=self.gfont,text=self.kongwangzu[cha-2],tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+30,30,font=self.gfont,text=self.kongwangzu[cha-1],tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+45,30,font=self.gfont,text=')',tag='riqi')

	def about(self,event):
		if self.pabout:
			self.canvas.create_text(self.guax,100+250,text='淮南法教专用水印',fill='tan',font=self.tfont,tag='about')
			self.canvas.create_text(self.guax+140,370,text='--无名',fill='tan',tag='about')
			self.pabout=False
		else:
			self.canvas.delete('about')
			self.pabout=True


	def paipan(self):
		for i in xrange(6):
			self.ygua.append(self.cntoint[self.com[i].get()]) #得到原始爻名,转换为1234,添加入gua
		self.gua=self.ygua
		bbgua=self.gua
		print '======================='
		print 'sel.gua',self.gua
		for i in xrange(6):
			if self.ygua[i]=='3':
				self.gua[i]='1'
				self.dgua.append(str(i))
				self.dgua.append('1') 
			elif  self.ygua[i]=='4':
				self.gua[i]='2'
				self.dgua.append(str(i))
				self.dgua.append('2')
		self.guastr=''.join(self.gua)
		# print u'变卦',bbgua
		# print u'字符串卦数',self.guastr
		# print u'数列卦',self.gua
		# print u'动卦',self.dgua
		# print gua64[guastr]
		self.draw()
		self.liushenf()#六神


	def draw(self):
		self.canvas.delete('pic')   #删除所有上次产生的ITEMS
		self.canvas.delete('liushen')
		# print u'当前itme数',self.canvas.find_all()
		#本卦
		for i in xrange(6):
			if self.gua[i]=='1':
				# self.canvas.create_image(self.guax,100+150-30*i,image=self.picyang,tag='pic')
				self.canvas.create_text(self.guax,95+150-30*i,text='▅▅▅',font=('Fixdsys',17,tkFont.BOLD),tag='pic')
			else:
				# self.canvas.create_image(self.guax,100+150-30*i,image=self.picyin,tag='pic')	
				self.canvas.create_text(self.guax,95+150-30*i,text='▅  ▅',font=('Fixdsys',17,tkFont.BOLD),tag='pic')
		
				#下面是六亲
		for i in xrange(6):
			self.canvas.create_text(self.guax-70,100+30*i,font=self.gfont,text=gua64[self.guastr][i],tag='pic')

			#动爻标记
		for i in xrange(0,len(self.dgua),2):
			if self.dgua[i+1]=='1':
				self.canvas.create_text(self.guax+70,247-30*int(self.dgua[i]),font=self.gfont,text='O',tag='pic',fill='red')
			else:
				self.canvas.create_text(self.guax+70,247-30*int(self.dgua[i]),font=self.gfont,text='X',tag='pic',fill='red')
			#世
		syw=gua64[self.guastr][6]
		self.canvas.create_text(self.guax+55,280-30*syw,font=self.gfont,text='世',tag='pic')
			#应
		yyw=gua64[self.guastr][7]
		self.canvas.create_text(self.guax+55,280-30*yyw,font=self.gfont,text='应',tag='pic')
			#六合、冲
		hc=gua64[self.guastr][8]
		self.canvas.create_text(self.guax-70,100-30,font=self.gfont,text=hc,tag='pic')
			#游魂、归魂
		zg=gua64[self.guastr][9]
		self.canvas.create_text(self.guax-70,100-30,font=self.gfont,text=zg,tag='pic')
			#卦宫
		gg=gua64[self.guastr][10]
		self.canvas.create_text(self.guax,100-30,font=self.gfont,text=gg,tag='pic')
		#变卦	
		self.biangua()
		self.guastr=''
		self.dgua=[] #动爻
		self.ygua=[] #原始卦
		self.bbgua=[] #变卦
		self.yguastr=[] #原始卦
		self.gua=[] #只有12的卦

	def biangua(self):
		self.bbgua=self.gua
		# print 'biangua',self.bbgua
		'''
sel.gua ['4', '4', '3', '3', '4', '3']
字符串卦数 221121
数列卦 ['2', '2', '1', '1', '2', '1']
动卦 ['0', '2', '1', '2', '2', '1', '3', '1', '4', '2', '5', '1']
当前itme数 (1, 2, 3, 4, 5, 6, 7)
biangua ['1', '1', '2', '2', '1', '2']
bguastr 112212
		'''
		for i in xrange(0,len(self.dgua),2):
			if self.dgua[i+1]=='1':
				self.bbgua[int(self.dgua[i])]='2'
			else:
				self.bbgua[int(self.dgua[i])]='1'
		print 'biangua',self.bbgua
		self.bguastr=''.join(self.bbgua)
		print 'bguastr',self.bguastr
		for i in xrange(6):
			if self.bbgua[i]=='1':
				# self.canvas.create_image(self.guax+130,100+150-30*i,image=self.picyang,tag='pic')
				self.canvas.create_text(self.guax+130,95+150-30*i,text=u'▅▅▅',font=('Fixdsys',17,tkFont.BOLD),tag='pic')
			else:
				# self.canvas.create_image(self.guax+130,100+150-30*i,image=self.picyin,tag='pic')
				self.canvas.create_text(self.guax+130,95+150-30*i,text=u'▅  ▅',font=('Fixdsys',17,tkFont.BOLD),tag='pic')
						#下面是六亲
		for i in xrange(6):
			self.canvas.create_text(self.guax+200,100+30*i,font=self.gfont,text=gua64[self.bguastr][i],tag='pic')
Пример #37
0
class App(object):
    def __init__(self, tk_root, monsters_initdata, board_dim, board_signs):
        self.board = [[None for i in range(board_dim[0])]
                      for j in range(board_dim[0])]
        self.jump_counter = 0
        self.meet_counter = 0
        self.data = monsters_initdata
        self.signs = board_signs

        self.collect = {
            'red': [],
            'blue': [],
            'green': [],
            'yellow': [],
            'pink': [],
            'brown': []
        }
        self.init_gui(tk_root)
        self.monsters = self.init_monsters()
        self.draw_board()

    def init_gui(self, tk_root):
        # GUI
        frame = Frame(tk_root)

        canvas_width = 600
        canvas_height = 600

        self.canvas = Canvas(frame, width=canvas_width, height=canvas_height)
        self.canvas.pack()
        frame.pack()

        self.quit_button = Button(frame,
                                  text="QUIT",
                                  fg="red",
                                  command=frame.quit)
        self.quit_button.pack(side=LEFT)
        self.jump_button = Button(frame, text="JUMP", command=self.jump)
        self.jump_button.pack(side=LEFT)

        self.text_counter = StringVar()
        self.text_counter.set('Round: {}'.format(self.jump_counter))
        self.label_counter = Label(frame,
                                   textvariable=self.text_counter,
                                   justify=LEFT)
        self.label_counter.pack()

        self.text_meet_counter = StringVar(self.meet_counter)
        self.label_meet_counter = Label(frame,
                                        textvariable=self.text_meet_counter,
                                        justify=LEFT)
        self.label_meet_counter.pack()

    def init_monsters(self):
        monsters = []
        for color, values in self.data.iteritems():
            for start_position in values['start']:
                monsters.append(
                    Monster(self.board, color, start_position,
                            values['pattern']))
        return monsters

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

        canvas_width = 600
        canvas_height = 600

        self.board
        space = canvas_width / (len(self.board) + 2)
        font = tkFont.Font(family='Helvetica', size=12, weight='bold')
        for i in range(1, len(self.board) + 2):
            self.canvas.create_line(space,
                                    space * i,
                                    canvas_width - space,
                                    space * i,
                                    fill='#476042')
            self.canvas.create_line(space * i,
                                    space,
                                    space * i,
                                    canvas_width - space,
                                    fill='#476042')
        for i in range(len(self.board)):
            self.canvas.create_text(space * (i + 1) + 12,
                                    18,
                                    text=i,
                                    font=font)
            self.canvas.create_text(18,
                                    space * (i + 1) + 12,
                                    text=i,
                                    font=font)

        font = tkFont.Font(family='Helvetica', size=20, weight='bold')
        for x, y, sign in self.signs:
            self.canvas.create_text(space * x + 39,
                                    space * y + 39,
                                    text=sign,
                                    font=font,
                                    fill='lightgrey')

        color_r = {
            'red': (1, 1),
            'green': (1, 2),
            'blue': (1, 3),
            'yellow': (2, 1),
            'pink': (2, 2),
            'brown': (2, 3)
        }
        for monster in self.monsters:
            x1, y1 = monster.position
            #            r = color_r.get(monster.color) * 2
            r = 2
            shift_x, shift_y = color_r.get(monster.color)
            # self.canvas.create_oval((1.5 + x1) * space - r, (1.5 + y1) * space - r,
            #                     (1.5 + x1) * space + r, (1.5 + y1) * space + r,
            #                     outline=monster.color, width=2)
            self.canvas.create_oval((1.5 + x1) * space - 14 - r + shift_y * 7,
                                    (1.5 + y1) * space - 14 - r + shift_x * 10,
                                    (1.5 + x1) * space - 14 + r + shift_y * 7,
                                    (1.5 + y1) * space - 14 + r + shift_x * 10,
                                    outline=monster.color,
                                    width=2)

    def jump(self):
        print
        print('ROUND {0}'.format(self.jump_counter + 1))
        print

        track_positions = {}
        for m in self.monsters:
            if m.rest:
                x, y = m.stay()
            else:
                x, y = m.jump()
                # check for signs on the board
                item = self.check_fields(m, self.signs)
                if item:
                    self.collect[m.color].append(item)
            # track position of all monsters in this round
            if (x, y) in track_positions:
                # already one monster on this location
                track_positions[(x, y)].append(m)
            else:
                track_positions[(x, y)] = [m]

        self.meet(track_positions)

        print(self.collect)
        print

        self.draw_board()
        self.jump_counter += 1

        print('Meet counter: {}'.format(self.meet_counter))
        self.text_counter.set(str(self.jump_counter))

    def check_fields(self, monster, fields):
        x, y = monster.position
        for x_f, y_f, value in fields:
            if x == x_f and y == y_f:
                monster.collection += value
                print '{} > {} -- {}'.format(monster.color, monster.collection,
                                             monster.positions)
                return value
        return ''

    def meet(self, track_positions):
        pass
Пример #38
0
class GridUI(Frame):
    def __init__(self, parent, height, width, cellSize, grid, robots,
                 frontier):

        Frame.__init__(self, parent)
        self.parent = parent
        self.initialize(height, width, cellSize, grid, robots, frontier)

    # Method to draw a grid of specified height and width
    def initialize(self, height, width, cellSize, grid, robots, frontier):

        self.parent.title('Grid')
        self.pack(fill=BOTH, expand=1)

        self.canvas = Canvas(self)

        startX = cellSize
        startY = cellSize
        endX = startX + (cellSize * width)
        endY = startY + (cellSize * height)

        curX = startX
        curY = startY
        rectIdx = 0
        xIdx = 0
        yIdx = 0

        while curX != endX and curY != endY:

            # print 'x, y:', xIdx, yIdx
            # First, check if the current location corresponds to that of any robot
            robotFlag = False
            for robot in robots:
                if robot.curX == xIdx and robot.curY == yIdx:
                    robotFlag = True
                    self.canvas.create_rectangle(curX,
                                                 curY,
                                                 curX + cellSize,
                                                 curY + cellSize,
                                                 outline='#0000FF',
                                                 fill='#00FF00',
                                                 width=2)
            # Then check if it corresponds to an obstacle
            if grid.cells[xIdx][yIdx].obstacle == True:
                self.canvas.create_rectangle(curX,
                                             curY,
                                             curX + cellSize,
                                             curY + cellSize,
                                             outline='#0000FF',
                                             fill='#000000',
                                             width=2)
            elif robotFlag == False:
                # Then check if it corresponds to a frontier cell
                frontierFlag = False
                for pt in frontier:
                    if pt[0] == xIdx and pt[1] == yIdx:
                        self.canvas.create_rectangle(curX,
                                                     curY,
                                                     curX + cellSize,
                                                     curY + cellSize,
                                                     outline='#0000FF',
                                                     fill='#00FFFF',
                                                     width=2)
                        frontierFlag = True

                if frontierFlag == False:
                    if grid.cells[xIdx][yIdx].visited == True:
                        self.canvas.create_rectangle(curX,
                                                     curY,
                                                     curX + cellSize,
                                                     curY + cellSize,
                                                     outline='#0000FF',
                                                     fill='#FFFFFF',
                                                     width=2)
                    else:
                        self.canvas.create_rectangle(curX,
                                                     curY,
                                                     curX + cellSize,
                                                     curY + cellSize,
                                                     outline='#0000FF',
                                                     fill='#777777',
                                                     width=2)

            curX = curX + cellSize
            if curX == endX and curY != endY:
                curX = startX
                xIdx += 1
                curY = curY + cellSize
                yIdx = 0
                # Move to the next iteration of the loop
                continue
            elif curX == endX and curY == endY:
                break
            rectIdx += 1
            yIdx += 1

        self.canvas.pack(fill=BOTH, expand=1)

    # Method to redraw the positions of the robots and the frontier
    def redraw(self, height, width, cellSize, grid, robots, frontier):

        self.parent.title('Grid2')
        self.pack(fill=BOTH, expand=1)

        # canvas = Canvas(self.parent)

        self.canvas.delete('all')

        startX = cellSize
        startY = cellSize
        endX = startX + (cellSize * width)
        endY = startY + (cellSize * height)

        curX = startX
        curY = startY
        rectIdx = 0
        xIdx = 0
        yIdx = 0

        while curX != endX and curY != endY:

            # print 'x, y:', xIdx, yIdx
            # First, check if the current location corresponds to that of any robot
            robotFlag = False
            if grid.cells[xIdx][yIdx].centroid == True:
                self.canvas.create_rectangle(curX,
                                             curY,
                                             curX + cellSize,
                                             curY + cellSize,
                                             outline='#0000FF',
                                             fill='indian red',
                                             width=2)
            else:

                for robot in robots:
                    if robot.curX == xIdx and robot.curY == yIdx:
                        robotFlag = True
                        self.canvas.create_rectangle(curX,
                                                     curY,
                                                     curX + cellSize,
                                                     curY + cellSize,
                                                     outline='#0000FF',
                                                     fill='#00FF00',
                                                     width=2)
                # Then check if it corresponds to an obstacle
                if grid.cells[xIdx][yIdx].obstacle == True:
                    self.canvas.create_rectangle(curX,
                                                 curY,
                                                 curX + cellSize,
                                                 curY + cellSize,
                                                 outline='#0000FF',
                                                 fill='#000000',
                                                 width=2)
                elif robotFlag == False:
                    # Then check if it corresponds to a frontier cell
                    frontierFlag = False
                    for pt in frontier:
                        if pt[0] == xIdx and pt[1] == yIdx:
                            if grid.cells[xIdx][yIdx].cluster == -1:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='#00FFFF',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 0:
                                self.canvas.create_rectangle(
                                    curX,
                                    curY,
                                    curX + cellSize,
                                    curY + cellSize,
                                    outline='#0000FF',
                                    fill='midnight blue',
                                    width=2)
                            if grid.cells[xIdx][yIdx].cluster == 1:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='peach puff',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 2:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='gold',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 3:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='slate blue',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 4:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='royal blue',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 5:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='red',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 6:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='dark green',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 7:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='dim gray',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 8:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='orange',
                                                             width=2)
                            if grid.cells[xIdx][yIdx].cluster == 9:
                                self.canvas.create_rectangle(curX,
                                                             curY,
                                                             curX + cellSize,
                                                             curY + cellSize,
                                                             outline='#0000FF',
                                                             fill='hot pink',
                                                             width=2)
                            frontierFlag = True

                    if frontierFlag == False:
                        if grid.cells[xIdx][yIdx].visited == True:
                            self.canvas.create_rectangle(curX,
                                                         curY,
                                                         curX + cellSize,
                                                         curY + cellSize,
                                                         outline='#0000FF',
                                                         fill='#FFFFFF',
                                                         width=2)
                        #else:
                        #if grid.cells[xIdx][yIdx].cluster != -1:
                        #	if grid.cells[xIdx][yIdx].cluster == 0:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'midnight blue', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 1:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'peach puff', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 2:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'dim gray', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 3:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'slate blue', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 4:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'royal blue', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 5:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'red', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 6:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'dark green', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 7:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'gold', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 8:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'orange', width = 2)
                        #	if grid.cells[xIdx][yIdx].cluster == 9:
                        #		self.canvas.create_rectangle(curX, curY, curX + cellSize, curY + cellSize, outline = '#0000FF', fill = 'hot pink', width = 2)
                        else:
                            self.canvas.create_rectangle(curX,
                                                         curY,
                                                         curX + cellSize,
                                                         curY + cellSize,
                                                         outline='#0000FF',
                                                         fill='#777777',
                                                         width=2)

            curX = curX + cellSize
            if curX == endX and curY != endY:
                curX = startX
                xIdx += 1
                curY = curY + cellSize
                yIdx = 0
                # Move to the next iteration of the loop
                continue
            elif curX == endX and curY == endY:
                break
            rectIdx += 1
            yIdx += 1

        self.canvas.pack(fill=BOTH, expand=1)
Пример #39
0
class PhraseEditor(HasTraits):
    """A graphical editor for musical phrases."""

    phrase = Instance(Phrase)
    """The phrase which is edited."""

    selected_point = Instance(Point)
    """The point that is currently moved around."""

    use_grid = Bool
    """Whether added points shall be snapped to a grid."""

    grid_resolution = Range(2,64, 16)
    """The resolution of the grid."""

    point_handle_size = Int(4)
    """The size of the handles used to move points around."""

    def __init__(self, toplevel, phrase, **kwargs):
        """
        Initializes a PhraseEditor.

        @param toplevel: the Tk Toplevel window
        @param phrase: the phrase to be edited
        """

        # The Tk Toplevel object to which the editor will be attached 
        self.toplevel = toplevel

        control_frame = Frame(self.toplevel)
        control_frame.pack(side=TOP)

        title_frame = Frame(control_frame, padx=8)
        title_frame.pack(side=LEFT)

        Label(title_frame, text="Title").pack(side=LEFT)

        self.title_entry_manager = EntryManager(
            title_frame, self, 'phrase.name'
        )
        self.title_entry_manager.entry.pack(side=LEFT)

        grid_frame = Frame(control_frame, padx=8)
        grid_frame.pack(side=LEFT)

        self.grid_checkbutton_manager = CheckbuttonManager(
            grid_frame, self, 'use_grid', text="Grid"
        )
        self.grid_checkbutton_manager.checkbutton.pack(side=LEFT)

        Label(grid_frame, text="Resolution").pack(side=LEFT)

        self.grid_resolution_spinbox_manager = SpinboxManager(
            grid_frame, self, 'grid_resolution',
        )
        self.grid_resolution_spinbox_manager.spinbox.pack(side=LEFT)

        steps_frame = Frame(control_frame, padx=8)
        steps_frame.pack(side=LEFT)

        Label(steps_frame, text="Steps").pack(side=LEFT)

        self.steps_spinbox_manager = SpinboxManager(
            steps_frame, self, 'phrase.steps',
        )
        self.steps_spinbox_manager.spinbox.pack(side=LEFT)

        transpose_frame = Frame(control_frame, padx=8)
        transpose_frame.pack(side=LEFT)

        Label(transpose_frame, text="Transpose").pack(side=LEFT)

        self.transpose_spinbox_manager = SpinboxManager(
            transpose_frame, self, 'phrase.transpose',
        )
        self.transpose_spinbox_manager.spinbox.pack(side=LEFT)

        self.v_point_type = StringVar()
        self.v_point_type.set('Note')

        OptionMenu(
            control_frame, self.v_point_type, 'Note', 'Rest',
        ).pack(side=LEFT)

        self.canvas = Canvas(self.toplevel, width=600, height=400)
        self.canvas.pack(side=BOTTOM)

        # Maps a Point to the ID of its handle, which is a rectangle on the
        # canvas. 
        self._point_handles = {}

        # Maps a tuple of two Points to the ID of the line connecting them on
        # the canvas.
        self._point_lines = {}

        # Maps a Point to the line to its next Point that is currently played.
        self._playing_lines = {}

        # A set of dotted lines marking the grid on the canvas.
        self._grid_lines = set()

        super(PhraseEditor, self).__init__(
            phrase=phrase, use_grid=True, **kwargs
        )

        def find_point(x,y):
            """
            @return: the point at the specified position on the canvas.
            """
            s = self.point_handle_size
            for point in self.phrase.points:
                px,py = point.pos
                if px-s <= x <= px+s and py-s <= y <= py+s:
                    return point
            return None

        def snap_to_grid(x,y):
            """
            Rounds the given coordinates to the grid defined by
            L{PhraseEditor.grid_resolution}.
            """
            res = self.grid_resolution
            return round(x/float(res))*res, round(y/float(res))*res

        def button_pressed(event):
            """
            When the left mouse button is pressed over a point, it becomes the
            L{PhraseEditor.selected_point}, which can be moved around by
            L{button_motion()}.

            If there is no point under the mouse pointer, a new point is
            appended to the L{Phrase}.
            """
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is None:
                if self.use_grid:
                    x,y = snap_to_grid(x,y)
                point = Point(
                    pos=(int(x),int(y)),
                    type=self.v_point_type.get(),
                )
                self.phrase.points.append(point)
            self.selected_point = point
        self.canvas.bind('<Button-1>', button_pressed)

        def button_motion(event):
            """
            If the mouse is moved while the left or miffle mouse button is held
            down and a point is selected, this point is moved to the current
            mouse pointer position.
            """
            if self.selected_point is None:
                return
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            if self.use_grid:
                x,y = snap_to_grid(x,y)
            canvas_config = self.canvas.config()
            canvas_width = int(canvas_config['width'][-1])
            canvas_height = int(canvas_config['height'][-1])
            self.selected_point.pos = (
                min(canvas_width, max(0, int(x))),
                min(canvas_height, max(0, int(y)))
            )
        self.canvas.bind('<B1-Motion>', button_motion)
        self.canvas.bind('<B2-Motion>', button_motion)

        def button_released(event):
            """
            When releasing the left or middle mouse button, the currently
            selected point is deselected.
            """
            self.selected_point = None
        self.canvas.bind('<ButtonRelease-1>', button_released)
        self.canvas.bind('<ButtonRelease-2>', button_released)

        def right_button_pressed(event):
            """
            Pressing the right mouse button over a point removes it from the
            L{Phrase}.
            """
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is not None:
                self.phrase.points.remove(point)
        self.canvas.bind('<Button-3>', right_button_pressed)

        def middle_button_pressed(event):
            if self.selected_point is not None:
                return
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is None:
                return
            new_point = Point(pos=point.pos, type=self.v_point_type.get())
            self.phrase.points.insert(
                self.phrase.points.index(point)+1,
                new_point
            )
            self.selected_point = new_point
        self.canvas.bind('<Button-2>', middle_button_pressed)

    def close(self):
        """
        Closes the editor, destroying its Toplevel window.
        """
        #del self.phrase
        #del self.selected_point
        #del self._point_handles
        #del self._point_lines
        #del self._playing_lines
        self.toplevel.destroy()

    def _add_point_handle(self, point):
        """
        Adds a point handle for the given point to the canvas.
        """
        s = self.point_handle_size
        px, py = point.pos
        self._point_handles[point] = self.canvas.create_rectangle(
            px-s,py-s, px+s,py+s,
        )

    def _remove_point_handle(self, point):
        """
        Removes the point handle for the given point.
        """
        self.canvas.delete(self._point_handles[point])
        del self._point_handles[point]

    def _add_point_line(self, point1, point2):
        """
        Adds a line between two points on the canvas.
        """
        px1, py1 = point1.pos
        px2, py2 = point2.pos
        self._point_lines[
            (point1, point2)
        ] = self.canvas.create_line(
            px1,py1, px2,py2,
            dash=[2,2] if point2.type == 'Rest' else None
        )

    def _remove_point_line(self, point1, point2):
        """
        Removes the line between two given points.
        """
        px1, py1 = point1.pos
        px2, py2 = point2.pos
        self.canvas.delete(self._point_lines[(point1, point2)])
        del self._point_lines[(point1, point2)]

    def _remove_point_lines(self):
        for points, line in self._point_lines.iteritems():
            self.canvas.delete(line)
        self._point_lines = {}

    def _remove_point_handles(self):
        for point, handle in self._point_handles.iteritems():
            self.canvas.delete(handle)
        self._point_handles = {}

    @on_trait_change('phrase, phrase:points')
    def _points_changed(self, obj, name, old, new):
        if self.phrase is None:
            return
        self._remove_point_handles()
        self._remove_point_lines()
        points = self.phrase.points
        for i, point in enumerate(points):
            self._add_point_handle(point)
            if i > 0:
                self._add_point_line(points[i-1], point)

    @on_trait_change('phrase:points:pos')
    def _point_pos_changed(self, point, name, old, new):
        """
        When a point's position changes, its handle and lines to its
        surrounding points are redefined.
        """
        self._remove_point_handle(point)
        self._add_point_handle(point)
        points = self.phrase.points
        assert point in points
        i = points.index(point)
        if i > 0:
            source_point = points[i-1]
            self._remove_point_line(source_point, point)
            self._add_point_line(source_point, point)
        if i < len(points)-1:
            target_point = points[i+1]
            self._remove_point_line(point, target_point)
            self._add_point_line(point, target_point)

    @on_trait_change('phrase.name')
    def _phrase_name_changed(self):
        """
        When the name of the phrase changes, the window title is update.
        """
        if self.phrase is None:
            return
        self.toplevel.title("Phrase: %s" % self.phrase.name)

    def add_playing_point(self, point, color):
        if point in self._playing_lines:
            self.remove_playing_point(point, color)
        if point not in self.phrase.points:
            return
        px,py, px2,py2 = self.phrase.get_line(point)
        self._playing_lines[point] = self.canvas.create_line(
            px,py, px2,py2, fill=color, width=2.0,
            dash=[2,2] if point.type == 'Rest' else None
        )

    def remove_playing_point(self, point, color):
        if point not in self._playing_lines:
            return
        self.canvas.delete(self._playing_lines[point])
        del self._playing_lines[point]

    @on_trait_change('use_grid, grid_resolution')
    def _grid_changed(self):
        """
        Draws a grid if L{PhraseEditor.use_grid} is True, otherwise removes it.
        """
        for rect in self._grid_lines:
            self.canvas.delete(rect)
        self._grid_lines.clear()
        if self.use_grid:
            config = self.canvas.config()
            w = int(config['width'][-1])
            h = int(config['height'][-1])
            res = self.grid_resolution
            for y in range(0, h, res):
                self._grid_lines.add(self.canvas.create_line(
                    0,y, w,y, dash=[1,res-1], fill="#666666"
                ))
Пример #40
0
class Palette(Frame):
    """
  Tkinter Frame that displays all items that can be added to the board.
  """
    def __init__(self,
                 parent,
                 board,
                 width=PALETTE_WIDTH,
                 height=PALETTE_HEIGHT):
        """
    |board|: the board on to which items will be added from this palette.
    |width|: the width of this palette.
    |height|: the height of this palette.
    """
        assert isinstance(board, Board), 'board must be a Board'
        Frame.__init__(self, parent, background=PALETTE_BACKGROUND_COLOR)
        self.board = board
        # canvas on which items are displayed
        self.canvas = Canvas(self,
                             width=width,
                             height=height,
                             highlightthickness=0,
                             background=PALETTE_BACKGROUND_COLOR)
        self.width = width
        self.height = height
        # x-position of last item added on the LEFT side of this palette
        self.current_left_x = PALETTE_PADDING
        # x-position of last item added on the RIGHT side of this palette
        self.current_right_x = self.width
        # line to separate left and right sides of palette
        self.left_right_separation_line_id = None
        # setup ui
        self.canvas.pack()
        self.pack()

    def _add_item_callback(self, drawable_type, desired_offset_x, **kwargs):
        """
    Returns a callback method that, when called, adds an item of the given
        |drawable_type| to the board, at the given |desired_offset_x|.
    """
        assert issubclass(drawable_type,
                          Drawable), ('drawable must be a Drawable '
                                      'subclass')

        def callback(event):
            # clear current message on the board, if any
            self.board.remove_message()
            # create new drawable
            new_drawable = drawable_type(**kwargs)
            desired_offset_y = (self.board.height - new_drawable.height -
                                PALETTE_PADDING)
            desired_offset = (desired_offset_x, desired_offset_y)
            self.board.add_drawable(new_drawable, desired_offset)
            return new_drawable

        return callback

    def _spawn_types_callback(self, types_to_add, desired_offset_x):
        """
    Returns a callback method that, when called, adds the items given in
        |types_to_add| to the board, starting at the given |desired_offset_x|.
    """
        assert isinstance(types_to_add, list), 'types_to_add must be a list'

        def callback(event):
            dx = 0
            # assign the same color and group_id to the types being spawned
            color = '#%02X%02X%02X' % (randint(0, 200), randint(
                0, 200), randint(0, 200))
            group_id = int(round(time() * 1000))
            num_drawables_added = 0
            for add_type, add_kwargs in types_to_add:
                add_kwargs['color'] = color
                add_kwargs['group_id'] = group_id
                new_drawable = self._add_item_callback(add_type,
                                                       desired_offset_x + dx,
                                                       **add_kwargs)(event)
                if new_drawable:
                    num_drawables_added += 1
                    dx += new_drawable.width + BOARD_GRID_SEPARATION
            if num_drawables_added > 1:
                self.board._action_history.combine_last_n(num_drawables_added)

        return callback

    def add_drawable_type(self,
                          drawable_type,
                          side,
                          callback,
                          types_to_add=None,
                          **kwargs):
        """
    Adds a drawable type for display on this palette.
    |drawable_type|: a subclass of Drawable to display.
    |side|: the side of this palette on which to put the display (LEFT or
        RIGHT).
    |callback|: method to call when display item is clicked. If None, the
        default callback adds an item of the display type to the board.
    |types_to_add|: a list of Drawables to add to the board when this item is
        clicked on the palette, or None if such a callback is not desired.
    |**kwargs|: extra arguments needed to initialize the drawable type.
    """
        assert issubclass(drawable_type,
                          Drawable), ('drawable must be a Drawable '
                                      'subclass')
        # create a sample (display) drawable
        display = drawable_type(**kwargs)
        # draw the display on the appropriate side of the palette
        if side == RIGHT:
            offset_x = self.current_right_x - PALETTE_PADDING - display.width
            self.current_right_x -= display.width + PALETTE_PADDING
            # update left-right separation line
            if self.left_right_separation_line_id:
                self.canvas.delete(self.left_right_separation_line_id)
            separation_x = self.current_right_x - PALETTE_PADDING
            self.left_right_separation_line_id = self.canvas.create_line(
                separation_x,
                0,
                separation_x,
                self.height,
                fill=PALETTE_SEPARATION_LINE_COLOR)
        else:
            # if given |side| is illegal, assume LEFT
            offset_x = self.current_left_x + PALETTE_PADDING
            self.current_left_x += PALETTE_PADDING + display.width + PALETTE_PADDING
        offset_y = (self.height - display.height) / 2
        if offset_y % BOARD_GRID_SEPARATION:
            offset_y = (offset_y /
                        BOARD_GRID_SEPARATION) * BOARD_GRID_SEPARATION
        offset = (offset_x, offset_y)
        display.draw_on(self.canvas, offset)
        display.draw_connectors(self.canvas, offset)
        # attach callback to drawn parts
        # default callback adds items of this drawable type to the board
        if callback is None:
            callback = self._add_item_callback(
                drawable_type, offset_x, **kwargs) if (
                    types_to_add is None) else self._spawn_types_callback(
                        types_to_add, offset_x)
        else:
            assert types_to_add is None, (
                'if callback is provided, types_to_add '
                'will not be used')
        # bind callback
        for part in display.parts:
            self.canvas.tag_bind(part, '<Button-1>', callback)
            self.canvas.tag_bind(part, '<Double-Button-1>', callback)
        for connector in display.connectors:
            self.canvas.tag_bind(connector.canvas_id, '<Button-1>', callback)
            self.canvas.tag_bind(connector.canvas_id, '<Double-Button-1>',
                                 callback)
        return display

    def draw_separator(self):
        """
    Draws a separation line at the current left position.
    """
        self.canvas.create_line(self.current_left_x,
                                0,
                                self.current_left_x,
                                self.height,
                                fill=PALETTE_SEPARATION_LINE_COLOR)
        self.current_left_x += PALETTE_PADDING
Пример #41
0
class Visualization(Tk):
  """
  Window displaying a pretty version of the given simulation, with the state
  shown around a circle of the given diameter. Pressing enter steps through
  the simulation and refreshes the visualization.
  """

  def __init__(self, simulator, diameter = 300, margin = 50, parent = None):
    Tk.__init__(self, parent)
    self.simulator = simulator
    self.diameter = diameter
    self.margin = margin
    self.parent = parent
    self.text_labels = []
    self.initialize()

  def initialize(self):
    """
    Setup work for UI.
    """
    self.title('Number Squares')
    # Set window size. Don't allow resizing.
    self.minsize(width = self.diameter + 2 * self.margin,
        height = self.diameter + 2 * self.margin)
    self.resizable(width = False, height = False)
    # Draw circle.
    self.canvas = Canvas(self)
    self.canvas.create_oval(self.margin, self.margin,
        self.diameter + self.margin, self.diameter + self.margin,
        outline = 'black', fill = 'white', width = 2)
    self.canvas.pack(fill = BOTH, expand = 1)
    # Bind arrow keys to step through simulation.
    self.bind('<Left>', lambda event: self.step_backward())
    self.bind('<Right>', lambda event: self.step_forward())
    # Draw initial state.
    self.draw_state()

  def draw_state(self):
    """
    Writes the numbers in the state of the simulation to the visualization.
    Does not update the simulator.
    """
    # Delete all of the old text labels.
    for text_label in self.text_labels:
      self.canvas.delete(text_label)
    self.text_labels = []
    # Make new text labels, adding them to the list.
    state = self.simulator.state
    num_points = len(state)
    for idx in range(num_points):
      text_loc = self._get_text_loc(num_points, idx)
      number = state[idx]
      text_label = self.canvas.create_text(text_loc[0], text_loc[1],
          text = str(number), font = ('Helvetica', '24'),
          fill = 'red' if number == 0 else 'blue')
      self.text_labels.append(text_label)

  def step_backward(self):
    """
    Steps the simulation backward and refreshes the UI.
    """
    self.simulator.step_backward()
    self.draw_state()

  def step_forward(self):
    """
    Steps the simulation forward and refreshes the UI.
    """
    self.simulator.step_forward()
    self.draw_state()

  def _get_text_loc(self, num_points, idx):
    """
    Returns the coordinates of point <idx> when <num_points> points are spaced
    evenly on the circumference of the circle. The first (0th) point will be
    placed north.
    """
    text_radius = (self.diameter + self.margin) * 0.5
    center = (self.margin + self.diameter / 2, self.margin + self.diameter / 2)
    angle = (2 * math.pi * idx) / num_points - (math.pi / 2)
    displacement = (text_radius * math.cos(angle),
        text_radius * math.sin(angle))
    return [int(center[i] + displacement[i]) for i in range(2)]
Пример #42
0
class Clock(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.initTime()
        self.draw()
        self.onTimer()

    def initTime(self):
        self.hourHand = time.localtime().tm_hour % 12 * 5
        self.minuteHand = time.localtime().tm_min
        self.secondHand = time.localtime().tm_sec

    def draw(self):
        self.pack(fill=BOTH, expand=1)
        radius = 300
        x, y = 50, 50
        centerX, centerY = 180, 180
        hourX = centerX + 0.3 * radius / 2.0 * math.cos(
            self.toRadian(self.hourHand))
        hourY = centerY + 0.3 * radius / 2.0 * math.sin(
            self.toRadian(self.hourHand))
        minuteX = centerX + 0.6 * radius / 2.0 * math.cos(
            self.toRadian(self.minuteHand))
        minuteY = centerY + 0.6 * radius / 2.0 * math.sin(
            self.toRadian(self.minuteHand))
        secondX = centerX + 0.75 * radius / 2.0 * math.cos(
            self.toRadian(self.secondHand))
        secondY = centerY + 0.75 * radius / 2.0 * math.sin(
            self.toRadian(self.secondHand))
        self.canvas.create_oval(x,
                                y,
                                radius,
                                radius,
                                outline="black",
                                fill="black")
        self.canvas.create_line(centerX,
                                centerY,
                                hourX,
                                hourY,
                                width=3,
                                fill="green")
        self.canvas.create_line(centerX,
                                centerY,
                                minuteX,
                                minuteY,
                                width=3,
                                fill="green")
        self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red")
        self.canvas.pack(fill=BOTH, expand=1)

    def toRadian(self, x):
        return (x * math.pi / 30.0) - (math.pi / 2.0)

    def onTimer(self):
        self.tick()
        self.canvas.delete(ALL)
        self.draw()
        self.after(DELAY, self.onTimer)

    def tick(self):
        self.secondHand = (self.secondHand + 1) % 60
        if self.secondHand == 0:
            self.minuteHand = (self.minuteHand + 1) % 60
            if self.minuteHand == 0:
                self.hourHand = (self.hourHand + 5) % 60
Пример #43
0
class at_graph(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.u = utils('atoutput.pkl')
        self.km = dict()
        self.price = dict()
        self.km[0] = (min(self.u.all_km), max(self.u.all_km))
        self.price[0] = (min(self.u.all_price), max(self.u.all_price))
        self.zoom_level = 0
        try:
            self.parent.title("Auto trader results")
            self.is_standalone = True
        except:
            self.is_standalone = False
        self.style = Style()
        self.style.theme_use("classic")
        # Assume the parent is the root widget; make the frame take up the
        # entire widget size.
        print self.is_standalone
        if self.is_standalone:
            self.w, self.h = map(int,
                self.parent.geometry().split('+')[0].split('x'))
            self.w, self.h = 800, 800
        else:
            self.w, self.h = 600, 600
        self.c = None
        # Are they hovering over a data point?
        self.is_hovering = False
        # Filter the description strings: lower and whiten any non-matching
        # data point.
        self.filter = ''
        self.re = list()
        self.replot()

    def replot(self, zlfrac=None):
        """Replot the graph. If zlfrac is not None, then it should be a
        fractional value between 0 and 1; this is used to do smooth zooming,
        which doesn't plot the axes (it only redraws the car points)."""
        if self.c is not None:
            self.c.destroy()
        self.c = Canvas(self, height=self.h, width=self.w, bd=1, bg='#f3f5f9')
        self.c.grid(sticky=S, pady=1, padx=1)
        zl = self.zoom_level
        if zlfrac is not None:
            z1l, z1h = self.zoom_price_start
            z2l, z2h = self.zoom_price_end
            price_low = z1l + (z2l - z1l) * zlfrac
            price_high = z1h + (z2h - z1h) * zlfrac
            z1l, z1h = self.zoom_km_start
            z2l, z2h = self.zoom_km_end
            km_low = z1l + (z2l - z1l) * zlfrac
            km_high = z1h + (z2h - z1h) * zlfrac
            self.axis((price_low, price_high), 'y', draw=False)
            self.axis((km_low, km_high), 'x', draw=False)
            self.car_points(draw=False)
        else:
            self.axis(self.price[zl], 'y')
            self.axis(self.km[zl], 'x')
            self.car_points()
        self.pack(fill=BOTH, expand=1)

    def xyp(self, x, y):
        "Given x in km and y in $, return canvas position (xp, yp)."
        xp = int(math.floor((1.0 * x - self.x1) / (self.x2 - self.x1) \
            * (self.xp2 - self.xp1) + self.xp1 + 0.5))
        yp = int(math.floor((1.0 * y - self.y1) / (self.y2 - self.y1) \
            * (self.yp2 - self.yp1) + self.yp1 + 0.5))
        return (xp, yp)

    def axis(self, arange, ax, draw=True):
        "Add an axis ax='x' or 'y', with arange=(min, max) values."
        if draw:
            a1, a2, ast = self.u.axis(*arange)
        else:
            a1, a2 = arange
            ast = (a2 - a1) * 0.2
        nt = int(math.floor((a2 - a1) / ast + 0.5)) + 1
        st_offset = 50
        # Remember the min and max axis values, along with the canvas points
        # that correspond to each location (xp1 and xp2). This allows us to
        # calculate where on the canvas a particular (x, y) value falls.
        if ax == 'x':
            self.x1, self.x2 = a1, a2
            self.xp1, self.xp2 = st_offset, self.w - st_offset
            self.xtick = [a1 + i * ast for i in range(nt)]
            # Remember where the midpoint of the axis is, relative to canvas.
            self.xmid = (self.xp1 + self.xp2) / 2
        else:
            self.y1, self.y2 = a1, a2
            self.yp1, self.yp2 = self.h - st_offset, st_offset
            self.ytick = [a1 + i * ast for i in range(nt)]
            # Remember where the midpoint of the axis is, relative to canvas.
            self.ymid = (self.yp1 + self.yp2) / 2
        # Figure out tick labels.
        atick = ['%g' % ((a1 + i * ast) / 1000) for i in range(nt)]
        # Figure out maximum decimal places on all tick labels, and ensure
        # they all have that many decimal places.
        max_dec = max(map(lambda x: 0 if '.' not in x
            else len(x.split('.')[1]), atick))
        if max_dec > 0:
            atick = map(lambda x: x + '.' + '0'*max_dec if '.' not in x
                else x + '0'*(max_dec - len(x.split('.')[1])), atick)
        yst, xst = self.h - st_offset, st_offset
        # Draw axis line proper, and axis label.
        if draw:
            if ax == 'x':
                self.c.create_line(xst, yst, self.w - st_offset, yst)
                xp = (xst + self.w - st_offset) / 2
                self.c.create_text(xp, yst + 30, text='Mileage (km x 1000)')
            else:
                self.c.create_line(xst, yst, xst, st_offset)
                self.c.create_text(xst, st_offset - 30, text='Price')
                self.c.create_text(xst, st_offset - 15, text='($000)')
        tick_anchor = [N, E][ax == 'y']
        tick_x, tick_y = xst, yst
        tick_step = ([self.w, self.h][ax == 'y'] - st_offset * 2 * 1.0) / \
            (nt - 1)
        label_offset = 3
        for i1, tick in enumerate(atick):
            x_of, y_of = -label_offset, label_offset
            if ax == 'y':
                y_of = int(-i1 * tick_step)
            else:
                x_of = int(i1 * tick_step)
            if draw:
                self.c.create_text(tick_x + x_of, tick_y + y_of,
                    text=tick, anchor=tick_anchor)
            x_mini, y_mini = 0, 0
            x_maxi, y_maxi = 0, 0
            if ax == 'y':
                x_of += label_offset
                x_mini, x_maxi = 8, self.w - st_offset * 2
                # Remember what y coord this grid line is at.
                if i1 == 0:
                    self.y_grid = []
                self.y_grid.append(tick_y + y_of)
            else:
                y_of -= label_offset
                y_mini, y_maxi = -8, st_offset * 2 - self.h
                # Remember what x coord this grid line is at.
                if i1 == 0:
                    self.x_grid = []
                self.x_grid.append(tick_x + x_of)
            if draw:
                # Draw the little solid tick, next to the axis.
                self.c.create_line(tick_x + x_of, tick_y + y_of,
                    tick_x + x_of + x_mini, tick_y + y_of + y_mini)
                # Draw a dashed grid line, across the entire graph.
                self.c.create_line(tick_x + x_of, tick_y + y_of,
                    tick_x + x_of + x_maxi, tick_y + y_of + y_maxi,
                    dash=(1, 3))

    def car_points(self, draw=True):
        "Plot the cars themselves."
        # 199 215 151 151 199 224 230 162 157 250 224 167 178 165 192 249 200 216 204 204 204 191 173 158
        color_order = ['#c7d797', '#97c7e0', '#e6a29d', '#fae0a7', '#b2a5c0',
            '#f9c8d8', '#bfad9e', '#cccccc']
        #color_order = ['#98df8a', '#dbdb8d', '#aec7e8', '#c9acd4', '#f7b6d2',
        #    '#ffbb80', '#dc9b8d', '#e9ab17', '#dddddd']
        # Those colors above aren't saturated enough. Saturate them more.
        color_order = map(lambda x: resaturate(x, -80), color_order)
        # Change color depending on year.
        cy = dict()
        for i1, year in enumerate(reversed(sorted(set(self.u.all_year)))):
            cy[year] = color_order[-1]
            if i1 < len(color_order):
                cy[year] = color_order[i1]
        i1 = -1
        # Tuples of (index into self.u.all_* arrays, x position, y position).
        self.ov_dict = dict()
        if draw:
            self.c.focus_set()
            self.c.bind('<Button-1>', func=self.zoom)
            self.c.bind('<Button-2>', func=self.unzoom)
            self.c.bind('<Left>', func=self.left_key)
            self.c.bind('<Right>', func=self.right_key)
            self.c.bind('<Up>', func=self.up_key)
            self.c.bind('<Down>', func=self.down_key)
        legend = set()
        osz = 3 + self.zoom_level * 1
        # Total vehicle count, and vehicles which pass the filter count.
        self.vcount = self.fcount = 0
        for year, km, price in zip(self.u.all_year, self.u.all_km,
            self.u.all_price):
            x, y = self.xyp(km, price)
            i1 += 1
            if x < self.x_grid[0] or x > self.x_grid[-1] or \
                y > self.y_grid[0] or y < self.y_grid[-1]:
                continue
            self.vcount += 1
            legend.add((year, cy[year]))
            filtered = False
            if not re.search(self.filter, self.u.all_descr[i1], re.I):
                filtered = True
            # If a data point is filtered out, make its outline reflect its
            # model year, and fill it with white.
            #
            # Else, make its outline and fill color reflect the model year, and
            # upon mouseover, make it entirely red.
            ov = self.c.create_oval(x-osz, y-osz, x+osz, y+osz,
                outline=cy[year],
                activeoutline=['red', cy[year]][filtered],
                fill=[cy[year], 'white'][filtered],
                activefill=['red', 'white'][filtered],
            )
            self.ov_dict[ov] = (i1, x, y, cy[year], filtered)
            # If a data point is filtered out, mousing over it does nothing,
            # and also, lower it behind everything else.
            if filtered:
                self.c.lower(ov)
            else:
                self.fcount += 1
                if draw:
                    use_tag = 'Tag %d' % i1
                    self.c.addtag_withtag(use_tag, ov)
                    self.c.tag_bind(use_tag, sequence='<Enter>',
                        func=self.mouseover)
                    self.c.tag_bind(use_tag, sequence='<Leave>',
                        func=self.mouseoff)
                    self.c.tag_bind(use_tag, sequence='<Button-1>',
                        func=self.select)
        if draw:
            # OK, add a legend for every year that's displayed.
            i1 = 0
            for yr, color in reversed(sorted(legend)):
                xp, yp = self.x_grid[-1] + 10, self.y_grid[-1] + 15 * i1
                self.c.create_oval(xp-osz, yp-osz, xp+osz, yp+osz,
                    outline=color, fill=color)
                self.c.create_text(xp + 8, yp, text=str(yr), anchor=W)
                i1 += 1
            # And, add a title.
            tistr = 'Vehicle count: %d' % self.vcount
            if self.fcount != self.vcount:
                tistr = 'Filtered vehicle count: %d' % self.fcount
            xp = (self.x_grid[0] + self.x_grid[-1]) / 2
            yp = self.y_grid[-1] - 30
            self.c.create_text(xp, yp, text=tistr, font=('Helvetica', '16'))
            zstr1 = 'Click on a blank graph location to zoom in'
            zstr2 = 'Right click to zoom out'
            if self.zoom_level == 0:
                zstr = zstr1
            elif self.zoom_level == 2:
                zstr = zstr2
            else:
                zstr = zstr1 + ', or r' + zstr2[1:]
            self.c.create_text(xp, yp + 16, text=zstr, font=('Helvetica', '14'))

    def mouseover(self, event):
        oval = event.widget.find_closest(event.x, event.y)[0]
        # XXX Sometimes, the closest widget is an axis grid line, not an oval.
        # Need to handle this correctly eventually.
        if oval not in self.ov_dict:
            return
        self.is_hovering = True
        ind, x, y, color, filtered = self.ov_dict[oval]
        # Figure out how high the box needs to be by creating the text off-
        # graph, then getting its bbox and deleting it.
        w = 200
        de_text = self.u.all_descr[ind]
        deobj = self.c.create_text(self.w + 3, self.h + 3, text=de_text,
            anchor=N+W, width=w-6, font=('Helvetica', '14'))
        bbox = self.c.bbox(deobj)
        self.c.delete(deobj)
        h = 18 + bbox[3] - bbox[1]
        border = 5
        if x > self.xmid:
            x -= (w + border)
        else:
            x += border
        if y > self.ymid:
            y -= (h + border)
        else:
            y += border
        self.re = list()
        self.re.append(self.c.create_rectangle(x, y, x + w, y + h,
            fill=resaturate(color, 50)))
        pr_text = '$%s' % self.u.commafy(self.u.all_price[ind])
        self.re.append(self.c.create_text(x + 3, y + 3, text=pr_text,
            anchor=N+W, font=('Helvetica', '10')))
        km_text = '%skm' % self.u.commafy(self.u.all_km[ind])
        self.re.append(self.c.create_text(x + w - 3, y + 3, text=km_text,
            anchor=N+E, font=('Helvetica', '10')))
        wh_text = self.u.all_wherestr[ind]
        if wh_text[0].isdigit():
            wh_text += ' away'
        self.re.append(self.c.create_text(x + w/2, y + 3, text=wh_text,
            anchor=N, font=('Helvetica', '10')))
        self.re.append(self.c.create_text(x + 3, y + 16, text=de_text,
            anchor=N+W, width=w-6, font=('Helvetica', '14')))

    def set_filter(self, st):
        "Given a string 'st', filter ovals whose description doesn't match."
        self.filter = st
        self.replot()

    def mouseoff(self, event):
        "Code for mousing off a data point."
        # The tooptip rectangle and all its sub-objects need to be destroyed.
        map(self.c.delete, self.re)
        # Also, need to note that we're no longer over an oval -- that way,
        # Button-1 events will cause a zoom, rather than launching a web page.
        self.is_hovering = False

    def _zoom_animation(self):
        import time
        from math import tanh
        scale = 5
        for i1 in range(-scale, scale+1):
            self.replot(zlfrac=0.5 + 0.5*tanh(i1*2.0/scale)/tanh(2.0))
            self.c.update()

    def zoom(self, event):
        # Only zoom in if we're actually within the graph boundaries.
        if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]:
            return
        if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]:
            return
        # Don't zoom if we're hovering over a data point: let the web browser
        # event handler operate.
        if self.is_hovering:
            return
        # Don't zoom in more than twice.
        if self.zoom_level >= 2:
            return
        # Find the grid square which we're inside.
        for i1 in range(len(self.x_grid) - 1):
            if event.x <= self.x_grid[i1 + 1]:
                xgrid = i1 + 1
                break
        for i1 in range(len(self.y_grid) - 1):
            if event.y >= self.y_grid[i1 + 1]:
                ygrid = i1 + 1
                break
        self.zoom_level += 1
        zl = self.zoom_level
        # Make the limits of the new graph be those of the grid square which
        # was clicked inside.
        self.km[zl] = (self.xtick[xgrid-1], self.xtick[xgrid])
        self.price[zl] = (self.ytick[ygrid-1], self.ytick[ygrid])
        if zl == 1:
            self.zoom_price_start = self.u.axis(*self.price[0])[:2]
            self.zoom_km_start = self.u.axis(*self.km[0])[:2]
        else:
            self.zoom_price_start = self.price[zl - 1]
            self.zoom_km_start = self.km[zl - 1]
        self.zoom_price_end = self.price[zl]
        self.zoom_km_end = self.km[zl]
        self._zoom_animation()
        self.replot()

    def unzoom(self, event):
        # If already at maximum zoom, nothing to be done.
        if self.zoom_level == 0:
            return
        # If not clicking inside graph boundaries, don't unzoom.
        if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]:
            return
        if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]:
            return
        self.zoom_level -= 1
        zl = self.zoom_level
        self.zoom_price_start = self.price[zl + 1]
        self.zoom_km_start = self.km[zl + 1]
        if zl == 0:
            self.zoom_price_end = self.u.axis(*self.price[0])[:2]
            self.zoom_km_end = self.u.axis(*self.km[0])[:2]
        else:
            self.zoom_price_end = self.price[zl]
            self.zoom_km_end = self.km[zl]
        self._zoom_animation()
        self.replot()

    def left_key(self, event):
        zl = self.zoom_level
        if zl == 0:
            return
        # If at left edge already, don't scroll.
        kz = self.km[zl]
        if self.km[0][0] > kz[0]:
            return
        self.zoom_price_start = self.zoom_price_end = self.price[zl]
        self.zoom_km_start = kz
        self.km[zl] = (kz[0] - (kz[1] - kz[0]), kz[0])
        self.zoom_km_end = self.km[zl]
        self._zoom_animation()
        self.replot()

    def right_key(self, event):
        zl = self.zoom_level
        if zl == 0:
            return
        # If at right edge already, don't scroll.
        kz = self.km[zl]
        if self.km[0][1] < kz[1]:
            return
        self.zoom_price_start = self.zoom_price_end = self.price[zl]
        self.zoom_km_start = kz
        self.km[zl] = (kz[1], kz[1] + (kz[1] - kz[0]))
        self.zoom_km_end = self.km[zl]
        self._zoom_animation()
        self.replot()

    def down_key(self, event):
        zl = self.zoom_level
        if zl == 0:
            return
        # If at bottom edge already, don't scroll.
        pz = self.price[zl]
        if self.price[0][0] > pz[0]:
            return
        self.zoom_km_start = self.zoom_km_end = self.km[zl]
        self.zoom_price_start = pz
        self.price[zl] = (pz[0] - (pz[1] - pz[0]), pz[0])
        self.zoom_price_end = self.price[zl]
        self._zoom_animation()
        self.replot()

    def up_key(self, event):
        zl = self.zoom_level
        if zl == 0:
            return
        # If at top edge already, don't scroll.
        pz = self.price[zl]
        if self.price[0][1] < pz[1]:
            return
        self.zoom_km_start = self.zoom_km_end = self.km[zl]
        self.zoom_price_start = pz
        self.price[zl] = (pz[1], pz[1] + (pz[1] - pz[0]))
        self.zoom_price_end = self.price[zl]
        self._zoom_animation()
        self.replot()


    def select(self, event):
        "Open a web page, when a data point has been clicked on."
        oval = event.widget.find_closest(event.x, event.y)[0]
        # XXX As above, sometimes the closest widget is a grid line, not an
        # oval. Need to handle this correctly, eventually.
        if oval not in self.ov_dict:
            return
        ind, xp, yp, color, filtered = self.ov_dict[oval]
        webbrowser.open(self.u.all_alink[ind])
Пример #44
0
class SudokuUI(Frame):
    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)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        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):
        for i in xrange(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="numbers",
                                            fill=color)

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

    def __cell_clicked(self, event):
        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()

            row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1
            elif self.game.puzzle[row][col] == 0 or self.game.puzzle[row][
                    col] != self.game.start_puzzle[row][col]:
                self.row, self.col = row, col
        else:
            self.row, self.col = -1, -1

        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")

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234567890":
            self.game.puzzle[self.row][self.col] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
            if self.game.check_win():
                self.__draw_victory()

    def __draw_victory(self):
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0,
                                y0,
                                x1,
                                y1,
                                tags="victory",
                                fill="dark orange",
                                outline="orange")
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(x,
                                y,
                                text="You win!",
                                tags="winner",
                                fill="white",
                                font=("Arial", 32))
Пример #45
0
class CraterViz(Tk):
    """
    Visualization class using Tkinter to build objects
    and track them on a canvas
    """

    def __init__(self, surface):
        Tk.__init__(self)
        self.title("Crater Density Visualization")
        self.surface = surface
        self.craters = {}
        fr = Frame(self)
        fr.pack()
        self.canvas = Canvas(fr, height = 580, width = 500)
        self.canvas.pack()
        self.init_ui()
        self.counter = 0;
        self.text_year = None
        self.text_craters = None


    #Builds canvas and adds the craters to it
    def init_ui(self):
        self._create_grid(self.canvas)
        self.canvas.pack()
        counter = 1
        for crater in self.surface.get_all_craters():
            self.after(counter * 100, self._add_crater, crater)
            counter += 1


    #Creates the grid on the canvas
    def _create_grid(self, canvas):
        """ Create 10km Grid """
        for i in range(50):
            canvas.create_line(10 * i, 0, 10 * i, 500, fill="#eee")
            canvas.create_line(0, 10 * i, 500, 10 * i, fill="#eee")


    #Adds a single crater to the map
    def _add_crater(self, crater):
        x, y = crater.get_location()
        outer_left = x - (25 * 1.2)
        outer_right = x + (25 * 1.2)
        outer_top = y - (25 * 1.2)
        outer_bottom = y + (25 * 1.2)
        outer = self.canvas.create_oval(
            outer_left, outer_top,
            outer_right,
            outer_bottom,
            outline="#f11",
            fill="#1f1",
            width=2)
        inner_left = x - 25
        inner_right = x + 25
        inner_top = y - 25
        inner_bottom = y + 25
        inner = self.canvas.create_oval(
            inner_left,
            inner_top,
            inner_right,
            inner_bottom,
            outline="#ccc",
            fill="green",
            width=2)
        craters_to_obliterate = self._find_obliterated_craters(crater)
        for obliterated in craters_to_obliterate:
            self._obliterate_crater(obliterated)

        self.craters[crater] = (x, y, inner, outer)
        self.counter += 1
        self._update_hud(self.counter, len(self.craters))


    #Removes crater from surface
    def _obliterate_crater(self, crater):
        x, y, inner, outer = self.craters[crater]
        del self.craters[crater]
        self.canvas.delete(inner)
        self.canvas.delete(outer)


    #Finds all Craters that need to be removed
    def _find_obliterated_craters(self, new_crater):
        obliterated_craters = []

        #Check if other craters are within cover radius
        cover_radius = new_crater.get_covering_radius()
        for crater in self.craters:
            if cover_radius > self._get_distance(crater, new_crater):
                obliterated_craters.append(crater)

        return obliterated_craters


    #Gets the distance between crater centers
    def _get_distance(self, crater1, crater2):
        x1, y1 = crater1.get_location()
        x2, y2 = crater2.get_location()
        return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)


    #Updates the heads up display on the bottom of the canvas
    def _update_hud(self, year, craters):
        if self.text_year:
            self.canvas.delete(self.text_year)
        self.text_year = self.canvas.create_text(480, 560, anchor="e", text="Year: "+str(year)+"000")
        if self.text_craters:
            self.canvas.delete(self.text_craters)
        self.text_craters = self.canvas.create_text(20, 560, anchor="w", text="Craters: "+str(craters))
Пример #46
0
class App:
    grid_size = 15
    num_pixels = 30
    ser = None
    t = None
    pixel_dictionary = {}

    def __init__(self, master):
        # Set main window's title
        master.title("ADNS3080ImageGrabber")

        frame = Frame(master)
        frame.grid(row=0, column=0)

        self.comPortStr = StringVar()
        ports = serial_ports()
        if not ports:
            ports = ['No serial ports found']
        self.comPortStr.set(ports[0])  # Set first port as default

        comports = apply(OptionMenu, (frame, self.comPortStr) + tuple(ports))
        comports.grid(row=0, column=0)

        self.baudrateStr = StringVar()
        self.baudrateStr.set('115200')

        baudrates = apply(OptionMenu, (frame, self.baudrateStr) + tuple(Serial.BAUDRATES))
        baudrates.grid(row=0, column=1)

        button = Button(frame, text="Open", command=self.open)
        button.grid(row=0, column=2)

        button = Button(frame, text="Close", command=self.close)
        button.grid(row=0, column=3)

        self.canvas = Canvas(master, width=self.grid_size*self.num_pixels, height=self.grid_size*self.num_pixels)
        self.canvas.grid(row=1)

    def __del__(self):
        self.close()

    def close(self):
        self.stop_read_loop()
        self.close_serial()

    def open(self):
        # Close the serial port
        self.close_serial()

        # Open the serial port
        try:
            self.ser = Serial(port=self.comPortStr.get(), baudrate=self.baudrateStr.get(), timeout=.1)
            print("Serial port '" + self.comPortStr.get() + "' opened at " + self.baudrateStr.get())
            self.read_loop()  # Read from serial port
        except SerialException:
            print("Failed to open serial port '" + self.comPortStr.get() + "'")

    def close_serial(self):
        if self.ser and self.ser.isOpen():
            try:
                self.ser.close()
                print("Closed serial port")
            except SerialException:
                pass  # Do nothing

    def read_loop(self):
        if self.t:
            self.stop_read_loop()

        if self.ser.isOpen():
            try:
                self.read_from_serial()
            except (IOError, TypeError):
                pass

        self.t = Timer(0.0, self.read_loop)
        self.t.start()

    def stop_read_loop(self):
        try:
            self.t.cancel()
        except AttributeError:
            print("Failed to cancel timer")

    def read_from_serial(self):
        while self.ser and self.ser.isOpen() and self.ser.inWaiting() > 0:
            # Process the line read
            line = self.ser.readline()
            if line.find("start") == 0:
                # print('Started reading image')
                pixels = self.ser.read(self.num_pixels * self.num_pixels)
                if len(pixels) == self.num_pixels * self.num_pixels:
                    for row in range(self.num_pixels):
                        # print(row)
                        col = 0
                        for p in pixels[row * self.num_pixels:(row + 1) * self.num_pixels]:
                            try:
                                colour = ord(p)
                            except TypeError:
                                colour = 0
                            # print('Colour', colour)
                            self.display_pixel(self.num_pixels - 1 - row, self.num_pixels - 1 - col, colour)
                            col += 1
                    # print('Done reading image')
                else:
                    print(len(pixels))
                    # print("Bad line: " + pixels)
            else:
                # Display the line if we couldn't understand it
                print('Error while processing string:', line)
                self.ser.flushInput()  # Flush the input, as this was likely caused by a timeout

    def display_default_image(self):
        # Display the grid
        for x in range(self.num_pixels):
            for y in range(self.num_pixels):
                colour = x * y / 3.53
                self.display_pixel(x, y, colour)

    def display_pixel(self, x, y, colour):
        if 0 <= x < self.num_pixels and 0 <= y < self.num_pixels:
            # Find the old pixel if it exists and delete it
            if x+y*self.num_pixels in self.pixel_dictionary:
                old_pixel = self.pixel_dictionary[x+y*self.num_pixels]
                self.canvas.delete(old_pixel)
                del old_pixel

            fill_colour = "#%02x%02x%02x" % (colour, colour, colour)
            # Draw a new pixel and add to pixel_array
            new_pixel = self.canvas.create_rectangle(x*self.grid_size, y*self.grid_size, (x+1)*self.grid_size,
                                                     (y+1)*self.grid_size, fill=fill_colour)
            self.pixel_dictionary[x+y*self.num_pixels] = new_pixel
Пример #47
0
class SudokuUI(Frame):  # Frame is a rectangular region on a screen
    """
	The Tkinter UI, responsible for drawing the board and accepting user input
	"""

    def __init__(self, parent, game):
        self.game = game
        Frame.__init__(self, parent)
        self.parent = parent  # all widgets belong to a parent

        self.row, self.col = -1, -1  # initialize row and col to use later

        self.__initUI()  # calls the initUI function

    def __initUI(self):
        self.parent.title("Sudoku")  # our parent window will be called Sudoku
        self.pack(
            fill=BOTH, expand=1
        )  # Frame attribute, organizes geometry relative to parent, fill options: both, none, x, y
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)  # canvas attribute, helps display our board
        clear_button = Button(self, text="Clear answers", command=self.__clear_answers)
        clear_button.pack(fill=BOTH, side=BOTTOM)  # Clear button is at the bottom and fills the space

        self.__draw_grid()  # helper functions
        self.__draw_puzzle()

        self.canvas.bind(
            "<Button-1>", self.__cell_clicked
        )  # binds Button-1 to a callback, another method: cell_clicked
        # in Tkinter, Button-1 is a default left mouse click
        self.canvas.bind("<Key>", self.__key_pressed)  # binds the key (guesed number) to the key presseed method

    def __draw_grid(
        self
    ):  # make the sudoku layout, do all private functions take self and then other potential arguments?
        """
		Draws grid divided with blue lines into 3x3 squares
		"""

        for i in xrange(10):
            color = "blue" if i % 3 == 0 else "gray"  # blue lines if divisible by 3

            # draw vertical lines
            x0 = MARGIN + i * SIDE
            y0 = MARGIN
            x1 = MARGIN + i * SIDE
            y1 = HEIGHT - MARGIN
            self.canvas.create_line(
                x0, y0, x1, y1, fill=color
            )  # draw the vertical lines coordinates are (x0, y0) (x1, y1)

            # draw horizontal lines
            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")  # delete old 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  # in the middle of the applicable cell
                    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="numbers", fill=color)

    def __draw_cursor(self):
        self.canvas.delete("cursor")
        if self.row >= 0 and self.col >= 0:  # you set these variables as 0 first in init
            x0 = MARGIN + self.col * SIDE + 1  # what does -1 do to these variables?
            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 __draw_victory(self):
        # creates an oval/circle
        x0 = y0 = MARGIN + SIDE * 2  # upper left box of circle starts margin + 2 rows in
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange")

        # create text
        x = y = MARGIN + 4 * SIDE + SIDE / 2  # middle of the circle
        self.canvas.create_text(x, y, text="You win!", tags="victory", fill="white", font=("Arial", 32))

    def __cell_clicked(self, event):  # event parameter: gives us x&y coordinates of where user clicked
        if self.game.game_over:
            return  # do nothing if game is over

        x, y = event.x, event.y
        if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN:  # if our puzzle grid is clicked
            self.canvas.focus_set()  # focus_set: move focus to a widget

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

            # if cell was selected already, another click should de-select it
            if (row, col) == (self.row, self.col):
                self.row, self.col = -1, -1  # I assume -1 means de-selecting?
            elif self.game.puzzle[row][col] == 0:  # otherwise, grab corresponding cell
                self.row, self.col = row, col
            else:
                self.row, self.col = -1, -1

            self.__draw_cursor()

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234567890":  # where does event.char come from? tkinter?
            self.game.puzzle[self.row][self.col] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
            if self.game.check_win():  # every time you enter in a number, the game checks to see if you have won
                self.__draw_victory()

    def __clear_answers(self):
        self.game.start()
        self.canvas.delete("victory")  # remove the victory circle
        self.__draw_puzzle()
Пример #48
0
class main:
   
    def __init__(self,master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue')
        self.label.pack(fill="both", expand=True)
        self.frameb=Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple')
        self.Start1.pack(fill="both", expand=True, side=RIGHT)
        self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white')
        self.Start2.pack(fill="both", expand=True, side=LEFT)     
        self._board()

    def start1(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.sgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False

    def start2(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.dgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False
        self.trigger=False

    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.j=True
        
    
    def _board(self):
        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 sgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if event.x in range(k,k+100) and event.y in range(j,j+100):
                    if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                        if self.i%2==0:
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                        else:                         
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            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")
                            self.TTT[Y1][X1]+=9
                            self.i+=1
        self.check()

    def dgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if self.i%2==0:
                    if event.x in range(k,k+100) and event.y in range(j,j+100):
                        if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                            self.check()
                            self.trigger=False                           
                else:
                    print(self.i)
                    self.check()
                    print("checked")
                    self.AIcheck()
                    print("AIchecked")
                    self.trigger=False
                    
                    

                        
                        
    def check(self):
        #horizontal check
        for i in range(0,3):
            if sum(self.TTT[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.TTT[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #vertical check
        #the matrix below transposes self.TTT so that it could use the sum fucntion again
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        for i in range(0,3):            
            if sum(self.ttt[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.ttt[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #check for diagonal wins
        if self.TTT[1][1]==9:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
        #check for draws
        if self.j==False:
            a=0
            for i in range(0,3):
                a+= sum(self.TTT[i])
            if a==41:
                self.label['text']=("It's a pass!")
                self.end()

                
    def AIcheck(self):
        #This is built on the self.check function
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        #DEFENSE
        #this is the horizontal checklist    
        for h in range(0,3): 
            k=0
            j=0            
            if sum(self.TTT[h])==2:
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.TTT[k][j]==0:
                                    self.cross(j,k)
                                    break
                            j+=1
                    k+=1
        #this is the vertical checklist
        for h in range(0,3):
            k=0
            j=0
            if sum(self.ttt[h])==2:                        
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.ttt[k][j]==0:
                                    self.cross(k,j)
                                    break
                            j+=1
                    k+=1                    
        #this is the diagonal checklist
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==1:
                if self.trigger==False:
                    if self.TTT[2][2]==0:
                        self.cross(2,2)
            if self.TTT[0][2]==1:
                if self.trigger==False:
                    if self.TTT[2][0]==0:
                        self.cross(0,2)
            if self.TTT[2][0]==1:
                if self.trigger==False:
                    if self.TTT[0][2]==0:
                        self.cross(2,0)
            if self.TTT[2][2]==1:
                if self.trigger==False:
                    if self.TTT[0][0]==0:
                        self.cross(0,0)
                        
        if self.TTT[1][1]==0:
            if self.trigger==False:
                self.cross(1,1)
                self.trigger=True
        else:
            if self.trigger==False:
                self.randmove()

    def cross(self, k, j):
        # k is the x coords
        # j is the y coords
        X=(200*k+100)/2
        Y=(200*j+100)/2
        X1=int(k)
        Y1=int(j)
        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")
        self.TTT[Y1][X1]+=9
        self.check()
        self.i+=1
        self.trigger=True

                

    def randmove(self):
        while True:
            k=(randint(0,2))
            j=(randint(0,2))
            if self.TTT[j][k]==0:
                X=(200*k+100)/2
                Y=(200*j+100)/2
                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")
                self.TTT[j][k]+=9
                self.check()
                self.i+=1
                self.trigger=True
                break
            else:
                k=(randint(0,2))*100
                j=(randint(0,2))*100
Пример #49
0
class World(Tk):
    #    def __init__(self,filename=None,block=50,debug=True,delay=0.25,image=False,width=10,height=10):
    def __init__(self,
                 filename=None,
                 block=50,
                 debug=True,
                 delay=0.25,
                 image=True,
                 width=10,
                 height=10):
        Tk.__init__(self)
        self.title("")
        arg, self.width, self.height = block, width, height
        self.photos = [
            PhotoImage(file=(k + ".gif"))
            for k in ["east", "north", "west", "south"]
        ]
        self.beepers, self.ovals, self.numbers, self.robots, self.walls = {},{},{},{},{}
        self.m, self.n, self.t, self.delay = arg * (width + 3), arg * (
            height + 3), arg, delay
        self.debug, self.useImage = debug, image
        a, b, c = self.t + self.t / 2, self.m - self.t - self.t / 2, self.n - self.t - self.t / 2
        self.canvas = Canvas(self, bg="white", width=self.m, height=self.n)
        self.canvas.pack()
        count = 1
        for k in range(2 * self.t, max(self.m, self.n) - self.t, self.t):
            if k < b:
                self.canvas.create_line(k, c, k, a, fill="red")
                self.canvas.create_text(k,
                                        c + self.t / 2,
                                        text=str(count),
                                        font=("Times",
                                              max(-self.t * 2 / 3, -15), ""))
            if k < c:
                self.canvas.create_line(b, k, a, k, fill="red")
                self.canvas.create_text(a - self.t / 2,
                                        self.n - k,
                                        text=str(count),
                                        font=("Times",
                                              max(-self.t * 2 / 3, -15), ""))
            count += 1
        self.canvas.create_line(a, c, b, c, fill="black", width=3)
        self.canvas.create_line(a, a, a, c, fill="black", width=3)
        if filename is not None:
            self.readWorld(filename)
        self.refresh()

    def readWorld(self, filename):
        try:
            infile = open("worlds\\%s.wld" % filename, "r")
        except IOError:
            try:
                infile = open("worlds/%s.wld" % filename, "r")
            except IOError:
                infile = open(filename, "r")
        text = infile.read().split("\n")
        infile.close()
        for t in text:
            if t.startswith("eastwestwalls"):
                s = t.split(" ")
                y, x = int(s[1]), int(s[2])
                self.addWall(x, y, -1, y)
            if t.startswith("northsouthwalls"):
                s = t.split(" ")
                x, y = int(s[1]), int(s[2])
                self.addWall(x, y, x, -1)
            if t.startswith("beepers"):
                s = t.split(" ")
                y, x, n = int(s[1]), int(s[2]), int(s[3])
                if n is infinity:
                    self.addInfiniteBeepers(x, y)
                else:
                    for k in range(n):
                        self.addBeeper(x, y)

    def pause(self):
        sleep(self.delay)

    def isBeeper(self, x, y):
        return (x, y) in self.beepers.keys() and not self.beepers[(x, y)] == 0

    def countRobots(self, x, y):
        if (x, y) not in self.robots.keys():
            return 0
        return len(self.robots[(x, y)])

    def crash(self, x1, y1, x2, y2):
        if 0 in (x1, y1, x2, y2):
            return True
        if (x2, y2) in self.walls.keys() and (x1, y1) in self.walls[(x2, y2)]:
            return True
        if (x1, y1) in self.walls.keys() and (x2, y2) in self.walls[(x1, y1)]:
            return True
        return False

    def addInfiniteBeepers(self, x, y):
        flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0
        self.beepers[(x, y)] = infinity
        text = "oo"
        a, b = self.t + x * self.t, self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a - t,
                                                         b - t,
                                                         a + t,
                                                         b + t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(
                a,
                b,
                text=text,
                fill="white",
                font=("Times", max(-self.t / 2, -20), ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def addBeeper(self, x, y):
        if (x, y) in self.beepers.keys() and self.beepers[(x, y)] is infinity:
            return
        flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0
        if flag:
            self.beepers[(x, y)] = 1
        else:
            self.beepers[(x, y)] += 1
        text = str(self.beepers[(x, y)])
        a, b = self.t + x * self.t, self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a - t,
                                                         b - t,
                                                         a + t,
                                                         b + t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(
                a,
                b,
                text=text,
                fill="white",
                font=("Times", max(-self.t / 2, -20), ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def removeBeeper(self, x, y):
        if self.beepers[(x, y)] is infinity:
            return
        self.beepers[(x, y)] -= 1
        flag = self.beepers[(x, y)] is 0
        text = str(self.beepers[(x, y)])
        if flag:
            self.canvas.delete(self.ovals[(x, y)])
            self.canvas.delete(self.numbers[(x, y)])
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def addWall(self, x1, y1, x2, y2):
        if not x1 == x2 and not y1 == y2:
            return
        if x1 == x2:
            y1, y2 = min(y1, y2), max(y1, y2)
            if y1 == -1:
                y1 = y2
            for k in range(y1, y2 + 1):
                self.walls.setdefault((x1, k), []).append((x1 + 1, k))
                a, b = self.t + x1 * self.t + self.t / 2, self.n - (
                    self.t + k * self.t) + self.t / 2
                c, d = self.t + x1 * self.t + self.t / 2, self.n - (
                    self.t + k * self.t) - self.t / 2
                self.canvas.create_line(a,
                                        b + 1,
                                        c,
                                        d - 1,
                                        fill="black",
                                        width=3)
        else:
            x1, x2 = min(x1, x2), max(x1, x2)
            if x1 == -1:
                x1 = x2
            for k in range(x1, x2 + 1):
                self.walls.setdefault((k, y1), []).append((k, y1 + 1))
                a, b = self.t + k * self.t - self.t / 2, self.n - (
                    self.t + y1 * self.t) - self.t / 2
                c, d = self.t + k * self.t + self.t / 2, self.n - (
                    self.t + y1 * self.t) - self.t / 2
                self.canvas.create_line(a - 1,
                                        b,
                                        c + 1,
                                        d,
                                        fill="black",
                                        width=3)

    def draw(self, x, y, d, img):
        if self.useImage:
            if img is not None:
                self.canvas.delete(img)
            x, y = self.t + x * self.t, self.n - (self.t + y * self.t)
            photo = self.photos[d / 90]
            img = self.canvas.create_image(x, y, image=photo)
            return img
        else:
            t, angle = self.t / 2, 120
            x, y = self.t + x * self.t, self.n - (self.t + y * self.t)
            x1, y1 = x + 3**0.5 * t / 2 * cos(
                radians(d)), y - 3**0.5 * t / 2 * sin(radians(d))
            x2, y2 = x + t * cos(radians(d + angle)), y - t * sin(
                radians(d + angle))
            x3, y3 = x + t / 4 * cos(radians(d + 180)), y - t / 4 * sin(
                radians(d + 180))
            x4, y4 = x + t * cos(radians(d - angle)), y - t * sin(
                radians(d - angle))
            if img is not None:
                self.canvas.delete(img)
            img = self.canvas.create_polygon(x1,
                                             y1,
                                             x2,
                                             y2,
                                             x3,
                                             y3,
                                             x4,
                                             y4,
                                             fill="blue")
            return img

    def erase(self, img):
        self.canvas.delete(img)

    def recordMove(self, count, x1, y1, x2, y2):
        for robot in self.robots[(x1, y1)]:
            if robot.count == count:
                self.robots[(x1, y1)].remove(robot)
                self.robots.setdefault((x2, y2), []).append(robot)
                break

    def lift(self, img):
        self.canvas.lift(img)

    def refresh(self):
        self.canvas.update()
        self.pause()

    def register(self, x, y, robot):
        self.robots.setdefault((x, y), []).append(robot)

    def remove(self, x, y, robot):
        self.robots[(x, y)].remove(robot)
Пример #50
0
class Container(Frame):
    def __init__(self, parent, width, height):
        
        Frame.__init__(self, parent, background="#22aaff")
        self.parent = parent
        self.initUI(width, height)
        
    def initUI(self, width, height):
        self.inMenu = True
        
        self.width = width 
        self.height = height
        
        self.parent.title("Stripes")
        self.style = Style()
        self.style.theme_use('default') #clam, default, alt, classic
        
        self.pack(fill=BOTH, expand=1)
               
        self.canvas = Canvas(self, width=width, height=height-30, background='#335533')
  
        def resize(event):
            self.width = event.width
            self.height = event.height
            if self.inMenu:
                pass
            else:
                self.draw()

        self.bind('<Configure>', resize)
        self.canvas.bind('<B1-Motion>', lambda(e): motion(e, self, self.draw))
        self.canvas.bind('<ButtonRelease-1>', lambda(e): release(e, self, self.draw))
        self.canvas.bind('<MouseWheel>', lambda(e): zoom(e, self, self.draw))

        def initializeLevel(levelNum):
            
            self.currentLevel = levelNum
            
            self.inMenu = False
            self.canvas.delete('all')
            self.camera = Camera(200, pi / 40)
            self.cells = CellGroup('cube', '3', 4, self)
            
            file = open('levels.txt', 'r')
            colors = eval(file.readline())
            file.close()
            
            self.routes = RouteGroup('cube', '3', 4, levelNum, self.cells, self, colors)
            self.activeIndex = 0
            self.draw()
            
            hideIdcs(self, self.draw)

        numLevels = 10
        
        def save(toMenu):
            lines = []
            file = open('levels.txt', 'r+')
            for i in range(numLevels+2):
                lines.append(file.readline())
            levelInfo = eval(lines[self.currentLevel+1])
            percent = self.cells.percent(self.routes.routes)
            complete = self.routes.complete()
            if percent < levelInfo[2]:
                percent = levelInfo[2]
            if levelInfo[1] == True:
                complete = True
            nodes = levelInfo[0]
            lines[self.currentLevel+1] = '(' + str(nodes) + ',' + str(complete) + ',' + str(percent) + ')\n'
            file.seek(0)
            for line in lines:
                file.write(line)
            file.write('\n' + lines[len(lines)-1])
            file.close()
            if toMenu:
                showLevelSelection(self, initializeLevel, numLevels)

        frame = Frame(self, width=width, height=30,background='#999999')

        menuButton = Button(self, text="Level Select", command=lambda: save(True))
        menuButton.pack(in_=frame, side=LEFT, anchor=W, ipadx=6, padx=6)
        
        closeButton = Button(self, text="Close", command=self.quit)
        closeButton.pack(in_=frame, side=LEFT, anchor=E, padx=6)
        
        showButton = Button(self, text='Show #s', command=lambda: showIdcs(self, self.draw))
        showButton.pack(in_=frame, side=LEFT, anchor=E, padx=6)
        
        hideButton = Button(self, text='Hide #s', command=lambda: hideIdcs(self, self.draw))
        hideButton.pack(in_=frame, side=LEFT, anchor=E, padx=6)
        
        frame.pack(anchor=W, fill=BOTH, expand=1)

        self.canvas.pack(fill=BOTH, expand=1)
        showLevelSelection(self, initializeLevel, numLevels)
        
    def draw(self):
        drawCells(self)
        drawRoutes(self)
Пример #51
0
class ImageViewer(Frame, object):

    class _Panner(object):
        def __init__(self):
            self.viewers = []
            self._factor = 1
            self._drags = []
            self._cdrag = None

        def add(self, val):
            self.viewers.append(val)
            for mark, end in self._drags:
                val.canvas.scan_mark(*mark)
                val.canvas.scan_dragto(*end, gain=1)
            if self._cdrag:
                val.canvas.scan_mark(*self._cdrag[0])
                val.canvas.scan_dragto(*self._cdrag[1], gain=1)

        def move_mark(self, x, y):
            if self._cdrag:
                self._drags.append(self._cdrag)

            self._cdrag = [(x, y), (x, y)]

            for viewer in self.viewers:
                viewer.canvas.scan_mark(x, y)

        def move_actual(self, x, y):
            self._cdrag[1] = (x, y)
            for viewer in self.viewers:
                viewer.canvas.scan_dragto(x, y, gain=1)

        def update(self):
            for viewer in self.viewers:
                viewer._update()

    def __init__(self, master, panner=None):
        super(ImageViewer, self).__init__(master)

        self._image = None
        self._view = None
        self._view_id = None

        self.canvas = Canvas(self, background="#000")
        self.canvas.pack(fill='both', expand=1)
        self.canvas.bind("<MouseWheel>", self.zoom)
        self.canvas.bind("<ButtonPress-1>", self.scroll_start)
        self.canvas.bind("<B1-Motion>", self.scroll_move)
        # self.canvas.bind("<Enter>", self.focus_widget)
        # self.canvas.bind("<Leave>", self.unfocus_widget)

        self.popup_menu = PopupMenu(self.canvas)
        for val in (10, 25, 50, 75, 100, 150, 200, 250, 300, 500):
            self.popup_menu.add_command(label="%d%%"%val, command=(lambda v:(lambda :self.set_factor(v/100.)))(val))

        self.popup_menu.attach()

        self._panner = panner
        if panner is None:
            self._panner = ImageViewer._Panner()
        self._panner.add(self)

        self._focus_prev = None

    def destroy(self):
        self._panner.viewers.remove(self)
        super(ImageViewer, self).destroy()

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, value):
        self._image = value
        self.after(1, self.show)

    @property
    def factor(self):
        return self._panner._factor

    @factor.setter
    def factor(self, value):
        self._panner._factor = value
        self.after(1, self.show)

    def set_factor(self, value):
        self.factor = value

    def zoom(self, event):
        if event.delta < 0:
            if self.factor == .1:
                return
            self.factor -= .1
        elif event.delta > 0:
            if self.factor == 5:
                return
            self.factor += .1
        self.show()

    def scroll_start(self, event):
        self._panner.move_mark(event.x, event.y)

    def scroll_move(self, event):
        self._panner.move_actual(event.x, event.y)

    def focus_widget(self, event):
        self._focus_prev = self.canvas.focus_get()
        self.focus_set()

    def unfocus_widget(self, event):
        self._focus_prev.focus_set()

    def show(self):
        self._panner.update()

    def _update(self):
        if self._image is None:
            return

        if self._view_id is not None:
            self.canvas.delete(self._view_id)

        x, y = self.image.size
        x, y = int(round(x*self.factor)), int(round(y*self.factor))

        self._view = ImageTk.PhotoImage(self.image.resize((x, y)))

        self._view_id = self.canvas.create_image(0, 0, image=self._view, anchor="nw")
        self.canvas.configure(scrollregsion=self.canvas.bbox("ALL"))
Пример #52
0
class Palette(Frame):
  """
  Tkinter Frame that displays all items that can be added to the board.
  """
  def __init__(self, parent, board, width=PALETTE_WIDTH,
      height=PALETTE_HEIGHT):
    """
    |board|: the board on to which items will be added from this palette.
    |width|: the width of this palette.
    |height|: the height of this palette.
    """
    assert isinstance(board, Board), 'board must be a Board'
    Frame.__init__(self, parent, background=PALETTE_BACKGROUND_COLOR)
    self.board = board
    # canvas on which items are displayed
    self.canvas = Canvas(self, width=width, height=height,
        highlightthickness=0, background=PALETTE_BACKGROUND_COLOR)
    self.width = width
    self.height = height
    # x-position of last item added on the LEFT side of this palette
    self.current_left_x = PALETTE_PADDING
    # x-position of last item added on the RIGHT side of this palette
    self.current_right_x = self.width
    # line to separate left and right sides of palette
    self.left_right_separation_line_id = None
    # setup ui
    self.canvas.pack()
    self.pack()
  def _add_item_callback(self, drawable_type, desired_offset_x, **kwargs):
    """
    Returns a callback method that, when called, adds an item of the given
        |drawable_type| to the board, at the given |desired_offset_x|.
    """
    assert issubclass(drawable_type, Drawable), ('drawable must be a Drawable '
        'subclass')
    def callback(event):
      # clear current message on the board, if any
      self.board.remove_message()
      # create new drawable
      new_drawable = drawable_type(**kwargs)
      desired_offset_y = (self.board.height - new_drawable.height -
          PALETTE_PADDING)
      desired_offset = (desired_offset_x, desired_offset_y)
      self.board.add_drawable(new_drawable, desired_offset)
      return new_drawable
    return callback
  def _spawn_types_callback(self, types_to_add, desired_offset_x):
    """
    Returns a callback method that, when called, adds the items given in
        |types_to_add| to the board, starting at the given |desired_offset_x|.
    """
    assert isinstance(types_to_add, list), 'types_to_add must be a list'
    def callback(event):
      dx = 0
      # assign the same color and group_id to the types being spawned
      color = '#%02X%02X%02X' % (randint(0, 200), randint(0, 200),
          randint(0, 200))
      group_id = int(round(time() * 1000))
      num_drawables_added = 0
      for add_type, add_kwargs in types_to_add:
        add_kwargs['color'] = color
        add_kwargs['group_id'] = group_id
        new_drawable = self._add_item_callback(add_type, desired_offset_x + dx,
            **add_kwargs)(event)
        if new_drawable:
          num_drawables_added += 1
          dx += new_drawable.width + BOARD_GRID_SEPARATION
      if num_drawables_added > 1:
        self.board._action_history.combine_last_n(num_drawables_added)
    return callback
  def add_drawable_type(self, drawable_type, side, callback, types_to_add=None,
      **kwargs):
    """
    Adds a drawable type for display on this palette.
    |drawable_type|: a subclass of Drawable to display.
    |side|: the side of this palette on which to put the display (LEFT or
        RIGHT).
    |callback|: method to call when display item is clicked. If None, the
        default callback adds an item of the display type to the board.
    |types_to_add|: a list of Drawables to add to the board when this item is
        clicked on the palette, or None if such a callback is not desired.
    |**kwargs|: extra arguments needed to initialize the drawable type.
    """
    assert issubclass(drawable_type, Drawable), ('drawable must be a Drawable '
        'subclass')
    # create a sample (display) drawable
    display = drawable_type(**kwargs)
    # draw the display on the appropriate side of the palette
    if side == RIGHT:
      offset_x = self.current_right_x - PALETTE_PADDING - display.width
      self.current_right_x -= display.width + PALETTE_PADDING
      # update left-right separation line
      if self.left_right_separation_line_id:
        self.canvas.delete(self.left_right_separation_line_id)
      separation_x = self.current_right_x - PALETTE_PADDING
      self.left_right_separation_line_id = self.canvas.create_line(
          separation_x, 0, separation_x, self.height,
          fill=PALETTE_SEPARATION_LINE_COLOR)
    else:
      # if given |side| is illegal, assume LEFT
      offset_x = self.current_left_x + PALETTE_PADDING
      self.current_left_x += PALETTE_PADDING + display.width + PALETTE_PADDING
    offset_y = (self.height - display.height) / 2
    if offset_y % BOARD_GRID_SEPARATION:
      offset_y = (offset_y / BOARD_GRID_SEPARATION) * BOARD_GRID_SEPARATION
    offset = (offset_x, offset_y)
    display.draw_on(self.canvas, offset)
    display.draw_connectors(self.canvas, offset)
    # attach callback to drawn parts
    # default callback adds items of this drawable type to the board
    if callback is None:
      callback = self._add_item_callback(drawable_type, offset_x, **kwargs) if (
          types_to_add is None) else self._spawn_types_callback(types_to_add,
          offset_x)
    else:
      assert types_to_add is None, ('if callback is provided, types_to_add '
          'will not be used')
    # bind callback
    for part in display.parts:
      self.canvas.tag_bind(part, '<Button-1>', callback)
      self.canvas.tag_bind(part, '<Double-Button-1>', callback)
    for connector in display.connectors:
      self.canvas.tag_bind(connector.canvas_id, '<Button-1>', callback)
      self.canvas.tag_bind(connector.canvas_id, '<Double-Button-1>', callback)
    return display
  def draw_separator(self):
    """
    Draws a separation line at the current left position.
    """
    self.canvas.create_line(self.current_left_x, 0, self.current_left_x,
        self.height, fill=PALETTE_SEPARATION_LINE_COLOR)
    self.current_left_x += PALETTE_PADDING
Пример #53
0
class main(Frame):
    def __init__(self, master):
        root_frame = Frame(master)
        root_frame.pack()

        menubar = Menu(master)

        menufile = Menu(menubar, tearoff=0)
        menufile.add_command(label="Open")
        menufile.add_command(label="Save")
        menubar.add_cascade(label="File", menu=menufile)

        master.config(menu=menubar)

        right_frame = Frame(root_frame, bg="white")
        right_frame.pack(side=RIGHT)

        self.button = Button(right_frame,
                             text="quit",
                             fg="red",
                             command=root_frame.quit)
        self.button.pack(side=TOP)

        MODES = [("3D", "rectangle"), ("2D", "line")]
        self.mode = StringVar()
        self.mode.set("line")
        for text, mode in MODES:
            b = Radiobutton(right_frame,
                            text=text,
                            variable=self.mode,
                            value=mode)
            b.pack(anchor=W)

        self.camera_canvas = Canvas(right_frame, bg="red")
        self.camera_canvas.bind("<ButtonPress-1>", self.pressed)
        self.camera_canvas.bind("<B1-Motion>", self.moved)
        self.camera_canvas.bind("<ButtonRelease-1>", self.released)
        self.camera_canvas.pack(side=BOTTOM)

        self.plot_canvas = Canvas(root_frame, width=100, bg="blue")
        self.plot_canvas.pack(side=LEFT)

        self.tomogram_canvas = Canvas(root_frame, bg="black")
        self.tomogram_canvas.pack(side=LEFT)

    def pressed(self, event):
        self.start_pos = (event.x, event.y)

    def moved(self, event):
        self.camera_canvas.delete(tk.ALL)
        coordinates = self.start_pos + (event.x, event.y)
        selector = {
            "line": self.camera_canvas.create_line,
            "rectangle": self.camera_canvas.create_rectangle
        }[self.mode.get()]
        selector(*coordinates)

    def released(self, event):
        pass

    def plot(points):
        ax = self.plot_canvas
        p2 = points.roll(1)
        a = zip(points, p2)
        a.pop()
        lines = [(p[0], y1, p[1], y1 + 1) for p in a]
        create_line = lambda coordinate: ax.create_line(*coordinate)
        map(create_line, lines)
Пример #54
0
class gui:

    def __init__(self, sonar):
        self.tk = Tk()
        self.canvas = Canvas(self.tk, height=800, width=800)
        self.canvas.pack()
        self.next = Button(self.tk, text='next', command=self.step)
        self.next.pack()
        self.rb = Button(self.tk, text='run', command=self.run)
        self.rb.pack()
        self.sonar = sonar
        self.draw_map()
        self.draw_move_points()
        self.delete_old = True
        #self.tk.after(20,self.redraw)

        self.tk.mainloop()

    def run(self):
        self.next.config(state='disabled')
        self.rb.config(state='disabled')
        self.manual = False
        self.tk.after(50, self.redraw)

    def step(self):
        self.manual = True
        self.redraw()
        
    def redraw(self):
        check = self.sonar.sim_step()
        if self.delete_old:
            self.canvas.delete('scan')
            self.canvas.delete('intersect')
            self.canvas.delete('particle')
            self.canvas.delete('mvln')
            
        self.draw_sonar_data()
        self.draw_particle_data()
        if check is not -1 and self.manual is False:
            self.tk.after(50, self.redraw)
        
    def draw_sonar_data(self):
        #print 'data'
        #for line in self.sonar.scan_lines:
            #draw_line(self.canvas, line, tag='scan')
            
        #for point in self.sonar.intersection_points:
            #draw_point(self.canvas, point, tag='intersect')
        draw_point(self.canvas, self.sonar.loc, tag='sonar', colour='red')

    def draw_particle_data(self):
        particles = self.sonar.particles.list()
        for particle in particles:
            draw_point(self.canvas, particle.loc, weight=particle.wt, tag='particle')
            if particle.move_line:
                draw_line(self.canvas, particle.move_line, tag='mvln')
            #for line in particle.scan:
             #   draw_line(self.canvas, line, tag='scan')
            #for intersect in particle.int:
                #draw_point(self.canvas, intersect, tag='intersect')
        
    def draw_map(self):
        #print 'map'
        for line in self.sonar.map.lines:
            draw_line(self.canvas, line, tag='map')

    def draw_move_points(self):
        for point in self.sonar.get_move_list():
            draw_point(self.canvas, point[0], tag='mvpt')
Пример #55
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black")
        self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="Game_Logo.gif")
        starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right")
        Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def calldown(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd)>0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(
                headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a]  and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500):
            return True
        return False


    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
Пример #56
0
class Screen(Observer):
    def __init__(self, parent, bg="white"):
        self.menu_bar = MenuBar(parent)
        self.canvas = Canvas(parent, bg=bg, name="screen")
        self.frameControl = Frame(parent)
        self.frameLabelSignals = LabelFrame(self.frameControl,
                                            text="Signaux",
                                            padx=20,
                                            pady=20)
        self.frameLabelMode = LabelFrame(self.frameControl,
                                         text="Mode",
                                         padx=20,
                                         pady=20)
        self.panelControl = ttk.Notebook(self.frameLabelSignals)
        self.checkbox_signalX = Checkbutton(self.frameLabelMode,
                                            text="Signal X")
        self.checkbox_signalY = Checkbutton(self.frameLabelMode,
                                            text="Signal Y")
        self.checkbox_XY = Checkbutton(self.frameLabelMode, text="XY")

        self.panel_control_page = []  # contient les références de mes curseurs

        for p in parent.get_models():
            self.addPage(p.get_name())

    def addPage(self, name):
        page = ttk.Frame(self.panelControl)
        self.panelControl.add(page, text='signal ' + name)

        visible_checkbox = Checkbutton(page, text="Afficher")
        magnitude = Scale(page,
                          length=250,
                          orient="horizontal",
                          label="Amplitude",
                          sliderlength=20,
                          showvalue=0,
                          from_=0,
                          to=5,
                          tickinterval=1,
                          name="magnitudeScale")
        frequency = Scale(page,
                          length=250,
                          orient="horizontal",
                          label="Frequency",
                          sliderlength=20,
                          showvalue=0,
                          from_=0,
                          to=25,
                          tickinterval=5,
                          name="frequencyScale")
        phase = Scale(page,
                      length=250,
                      orient="horizontal",
                      label="Phase",
                      sliderlength=20,
                      showvalue=0,
                      from_=0,
                      to=20,
                      tickinterval=5,
                      name="phaseScale")
        visible_checkbox.pack(fill="x", pady=6)
        magnitude.pack(expand=1, fill="both", pady=6)
        frequency.pack(expand=1, fill="both", pady=6)
        phase.pack(expand=1, fill="both", pady=6)
        self.panel_control_page.append({
            'visible': visible_checkbox,
            'magnitude': magnitude,
            'frequency': frequency,
            'phase': phase
        })

    def update(self, model):
        if type(model) == list:
            for i, m in enumerate(model):
                signal = m.get_signal()
                #self.plot_signal(signal, m.get_color())
                self.plot_signal(m)
        else:
            signal = model.get_signal()
            self.plot_signal(model)
        self.grid(6, 8)

    def get_panel_control_index(self):
        return self.panelControl.index('current')

    def get_canvas(self):
        return self.canvas

    def get_panel_control_page(self):
        return self.panel_control_page

    def get_magnitude(self, index):
        return self.panel_control_page[index]['magnitude']

    def get_frequency(self, index):
        return self.panel_control_page[index]['frequency']

    def get_phase(self, index):
        return self.panel_control_page[index]['phase']

    def get_visible(self, index):
        return self.panel_control_page[index]['visible']

    def get_checkbox_signalX(self):
        return self.checkbox_signalX

    def get_checkbox_signalY(self):
        return self.checkbox_signalY

    def get_checkbox_XY(self):
        return self.checkbox_XY

    def plot_signal(self, model):
        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
        width, height = int(w), int(h)

        signal = model.get_signal()
        name = model.get_name()
        color = model.get_color()

        if self.canvas.find_withtag("signal" + name):
            self.canvas.delete("signal" + name)

        if signal and len(signal) > 1 and model.is_visible():
            plot = [(x * width, height / 2.0 * (y + 1)) for (x, y) in signal]
            self.canvas.create_line(plot,
                                    fill=color,
                                    smooth=1,
                                    width=3,
                                    tags="signal" + name)
            self.canvas.scale("signal" + name, width / 2, height / 2, 1.0,
                              0.25)

    def grid(self, row, col):
        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
        width, height = int(w), int(h)

        if self.canvas.find_withtag("grid"):
            self.canvas.delete("grid")

        # dessin des axes X et Y
        self.canvas.create_line(5,
                                height / 2,
                                width,
                                height / 2,
                                arrow="last",
                                tags=('grid', 'axe-x'))
        self.canvas.create_line(width / 2,
                                height - 5,
                                width / 2,
                                5,
                                arrow="last",
                                tags=('grid', 'axe-y'))

        # dessin des lignes verticales
        for c in range(1, int(row / 2) + 1):
            stepW = width / row
            xd = width / 2 + c * stepW
            xg = width / 2 - c * stepW
            #Creation des lignes verticales
            self.canvas.create_line(xd,
                                    height - 5,
                                    xd,
                                    5,
                                    dash=1,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')  #cote droit
            self.canvas.create_line(xg,
                                    height - 5,
                                    xg,
                                    5,
                                    dash=1,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')  #cote gauche
            #Creation des tirets sur x
            self.canvas.create_line(xd,
                                    height / 2 - 4,
                                    xd,
                                    height / 2 + 4,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            self.canvas.create_line(xg,
                                    height / 2 - 4,
                                    xg,
                                    height / 2 + 4,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')

        # dessin des lignes horizontales
        for r in range(1, int(col / 2) + 1):
            stepH = height / col
            yB = height / 2 + r * stepH
            yH = height / 2 - r * stepH
            #Creation des lignes horizontales
            self.canvas.create_line(5,
                                    yB,
                                    width,
                                    yB,
                                    dash=1,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            self.canvas.create_line(5,
                                    yH,
                                    width,
                                    yH,
                                    dash=1,
                                    tags=('grid', 'horizontal-line'),
                                    fill='grey')
            #Creation des tirets sur y
            self.canvas.create_line(width / 2 - 4,
                                    yB,
                                    width / 2 + 4,
                                    yB,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')
            self.canvas.create_line(width / 2 - 4,
                                    yH,
                                    width / 2 + 4,
                                    yH,
                                    tags=('grid', 'vertical-line'),
                                    fill='grey')

    def packing(self):
        self.menu_bar.pack(fill='x')
        self.canvas.pack(side=LEFT, expand=1, fill="both", padx=6, pady=6)
        self.panelControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
        self.frameLabelSignals.pack(expand=1, fill="both")
        self.frameLabelMode.pack(expand=1, fill="both")
        self.checkbox_signalX.pack(side=LEFT)
        self.checkbox_signalY.pack(side=LEFT)
        self.checkbox_XY.pack(side=RIGHT)
        self.frameControl.pack(side=RIGHT, expand=1, fill="both", pady=6)
class SudokuUI(Frame):
    """
    Sudoku grid UI class.
    Adapted from: http://newcoder.io/gui/part-4/
    """
    def __init__(self, parent, board):
        self.game = board
        Frame.__init__(self, parent)
        self.parent = parent

        self.row, self.col = -1, -1
        self.new_entry = None
        self.previous_guess = None

        self.game_state = 0

        self.scores = []

        self.__initUI()

    def __initUI(self):
        """
        Initialize sudoku playing field grid and bind clicking and entry handlers."""

        self.parent.title("Sudoku")
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.grid(row=1, column=0)

        self.__draw_grid()
        self.__draw_puzzle()
        self.__draw_scores()

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

    def __draw_grid(self):
        """
        Draw Sudoku 3x3 x 3x3 grid."""

        for i in xrange(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):
        """
        Draw Sudoku solution numbers."""

        self.canvas.delete("numbers")
        for i in xrange(9):
            for j in xrange(9):
                answer = self.game.board[i][j]
                if answer != 0:
                    x = MARGIN + j * SIDE + SIDE / 2
                    y = MARGIN + i * SIDE + SIDE / 2
                    self.canvas.create_text(x, y, text=answer, tags="numbers")

    def __cell_clicked(self, event):
        """
        Handle a single cell click and highlight the clicked cell.
        :param event:
        """
        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
            elif self.game.board[row][col] == 0:
                self.row, self.col = row, col

        self.__draw_cursor()

    def __draw_cursor(self):
        """
        Draw the red outline for the selected square."""

        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="green",
                                         tags="cursor")

    def __key_pressed(self, event):
        """
        Handle solution number entry."""

        if self.row >= 0 and self.col >= 0 and event.char in "123456789" and self.game_state == 1:
            self.new_entry = (self.row, self.col, int(event.char))
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()

    def __draw_scores(self):
        self.score_list = Treeview(self, columns=('name', 'score'))
        self.score_list['show'] = 'headings'
        self.score_list.heading('name', text='Name')
        self.score_list.column('name', width=80, anchor=CENTER)
        self.score_list.heading('score', text='Score')
        self.score_list.column('score', width=80, anchor=CENTER)

        self.score_list.grid(row=1, column=1, padx=(0, 20))

    def __update_scores(self, scores):
        self.score_list.delete(*self.score_list.get_children())
        for entry in scores:
            self.score_list.insert('', 'end', values=(entry[0], entry[1]))

    def show_winner(self, score, user_id):
        if score[2] == user_id:
            winner_text = "YOU HAVE WON!"
        else:
            winner_text = "Player " + str(score[0]) + " has won!"
        tkMessageBox.showwarning("A WINNER IS FOUND", winner_text)

    def update_board(self, root, board, scores, new_game_state):
        """
        Update board during the gameplay. If all players are not connected, solution entry is not permitted.
        In case of a wrong answer the selected square is flashed red for a fraction of a second to notify
        the player about his life decisions.

        :param root:
        :param board:
        :param new_game_state:
        :return entered value:
        """
        return_val = None

        self.__update_scores(scores)

        # Check for game state, if it is "0", just return, else continue the game
        if self.game_state == 0:
            root.update()

            if new_game_state != 0:
                self.game_state = new_game_state
            return return_val

        # If previous guess was not correct flash it red
        if self.previous_guess is not None and board[self.previous_guess[0]][self.previous_guess[1]] != \
                self.previous_guess[2]:
            row, col, _ = self.previous_guess
            x0 = MARGIN + col * SIDE + 1
            y0 = MARGIN + row * SIDE + 1
            x1 = MARGIN + (col + 1) * SIDE - 1
            y1 = MARGIN + (row + 1) * SIDE - 1
            self.canvas.create_rectangle(x0,
                                         y0,
                                         x1,
                                         y1,
                                         fill="red",
                                         tags="fail")
        else:
            self.canvas.delete("fail")

        # Initiate return value to none, update the board and draw it
        self.game.update_board(board)
        self.__draw_puzzle()
        root.update()

        # If user has entered anything in between, write it into the return value and previous guess and return
        if self.new_entry is not None:
            return_val = self.new_entry
            self.previous_guess = self.new_entry
            self.new_entry = None
        else:
            self.previous_guess = None

        return return_val
Пример #58
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 suction_height,
                 regions,
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=150,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()
        # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0))
        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.suction_height = suction_height
        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        # self.center()
        self.move_frame(self.tl_x, self.tl_y)

        max_width = max(
            map(get_width,
                regions.values()))  # Really should take width of max minus min
        self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER
                              ) / max_width  # Maintains aspect ratio
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.environment = []
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def scale_x(self, x):  # x \in [-self.dist_width/2, self.dist_width/2]
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def scale_y(self, y):  # y \in [0, self.dist_height]
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, x, y, width, height, name='', color='blue'):
        self.blocks.extend([
            self.canvas.create_rectangle(self.scale_x(x - width / 2.),
                                         self.scale_y(y),
                                         self.scale_x(x + width / 2.),
                                         self.scale_y(y + height),
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text(self.scale_x(x),
                                    self.scale_y(y + height / 2),
                                    text=name),
        ])

    # def draw_holding(self, x, width, height, color='blue'):
    #     self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height),
    #                                                 self.scale_x(x + width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2),
    #                                                 fill=color, outline='black', width=2)

    def draw_region(self, region, name='', color='red'):
        x1, x2 = map(self.scale_x, region)
        y1, y2 = self.ground_height, self.height
        self.environment.extend([
            self.canvas.create_rectangle(x1,
                                         y1,
                                         x2,
                                         y2,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name),
        ])

    def draw_environment(self):
        # TODO: automatically draw in order
        self.environment = []
        for name, region in sorted(self.regions.items(),
                                   key=lambda pair: get_width(pair[1]),
                                   reverse=True):
            self.draw_region(region, name=name, color=name)

    def draw_robot(
        self,
        x,
        y,
        color='yellow'
    ):  # TODO - could also visualize as top grasps instead of side grasps
        #y = self.robot_dist
        self.robot = [
            self.canvas.create_rectangle(
                self.scale_x(x - SUCTION_WIDTH / 2.),
                self.scale_y(y - self.suction_height / 2.),
                self.scale_x(x + SUCTION_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                fill=color,
                outline='black',
                width=2),
            self.canvas.create_rectangle(
                self.scale_x(x - STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                self.scale_x(x + STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT),
                fill=color,
                outline='black',
                width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

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

    def save(self, filename):
        # TODO: screen recording based on location like I did before
        # TODO: only works on windows
        # self.canvas.postscript(file='%s.ps'%filename, colormode='color')
        #from PIL import ImageGrab
        try:
            import pyscreenshot as ImageGrab
        except ImportError:
            return None
        x, y = self.top.winfo_x(), 2 * self.top.winfo_y()
        width, height = self.top.winfo_width(), self.top.winfo_height(
        )  # winfo_width, winfo_reqheight
        path = filename + '.png'
        ImageGrab.grab((x, y, x + width, y + height)).save(path)
        return path
Пример #59
0
class SudokuUI(Frame):
    """
    The Tkinter UI, responsible for drawing the board and accepting user input.
    """
    def __init__(self, parent, game):
        self.game = game
        Frame.__init__(self, parent)
        self.parent = parent

        self.row, self.col = -1, -1

        self.__initUI()

    def __initUI(self):
        self.parent.title("Sudoku")
        self.pack(fill=BOTH)
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack(fill=BOTH, side=TOP)
        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 3x3 squares
        """
        for i in range(10):
            color = "blue" if i % 3 == 0 else "grey"

            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 range(9):
            for j in range(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="numbers",
                                            fill=color)

    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 __draw_victory(self):
        # create a oval (which will be a circle)
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0,
                                y0,
                                x1,
                                y1,
                                tags="victory",
                                fill="dark orange",
                                outline="orange")
        # create text
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(x,
                                y,
                                text="You win!",
                                tags="victory",
                                fill="white",
                                font=("Arial", 32))

    def __draw_loose(self):
        # create a oval (which will be a circle)
        x0 = y0 = MARGIN + SIDE * 2
        x1 = y1 = MARGIN + SIDE * 7
        self.canvas.create_oval(x0,
                                y0,
                                x1,
                                y1,
                                tags="victory",
                                fill="yellow",
                                outline="yellow")
        # create text
        x = y = MARGIN + 4 * SIDE + SIDE / 2
        self.canvas.create_text(x,
                                y,
                                text="You loose!",
                                tags="victory",
                                fill="white",
                                font=("Arial", 32))

    def __cell_clicked(self, event):
        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 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
            elif self.game.check[row][col] == 0:
                self.row, self.col = row, col
        else:
            self.row, self.col = -1, -1

        self.__draw_cursor()

    def __key_pressed(self, event):
        if self.game.game_over:
            return
        if self.row >= 0 and self.col >= 0 and event.char in "1234567890":
            self.game.puzzle[self.row][self.col] = int(event.char)
            self.col, self.row = -1, -1
            self.__draw_puzzle()
            self.__draw_cursor()
            a = self.game.check_win()
            # print(a)
            if a == 0:
                self.__draw_loose()
                return 0
            elif a == 1:
                self.__draw_victory()

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