class filterswindow: ''' Interface graphique recapitulant les caracteristique du sismogramme presentant les options de filtrage et de calculs du noyau de sensibilite ''' def __init__(self,racine): self.canvas = Canvas(racine, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(racine, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global filterVar filterVar = 1 global text6a text6a = "1" global text6c1 text6c1 = StringVar() global text6c2 text6c2 = StringVar() global text6c3 text6c3 = StringVar() Label(self.frame, text="Option Filter").grid(row=0) Label(self.frame, text="\n").grid(row=1) Label(self.frame, text="lowest frequency ?").grid(row=4) e1 = Entry(self.frame, textvariable=text6c1) e1.grid(row=5) Label(self.frame, text="highest frequency ?").grid(row=20) e2 = Entry(self.frame, textvariable=text6c2) e2.grid(row=21) Label(self.frame, text="number of poles ?").grid(row=22) e3 = Entry(self.frame, textvariable=text6c3) e3.grid(row=23) Button(self.frame, text="continue", command=self.quitter).grid(row=24) def quitter(self): global racine racine.destroy() afficheSismoFiltre(textPath.get(), float(text6c1.get()), float(text6c2.get()), float(text6c3.get())) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def createCanvas( self ): "Create and return our scrolling canvas frame." f = Frame( self ) canvas = Canvas( f, width=self.cwidth, height=self.cheight, bg=self.bg ) # Scroll bars xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas
def createWidgets(self): "Create initial widget set." # Objects title = Label(self, text='Bandwidth (Gb/s)', bg=self.bg) width = self.gwidth height = self.gheight scale = self.createScale() graph = Canvas(self, width=width, height=height, background=self.bg) xbar = Scrollbar(self, orient='horizontal', command=graph.xview) ybar = Scrollbar(self, orient='vertical', command=self.yview) graph.configure(xscrollcommand=xbar.set, yscrollcommand=ybar.set, scrollregion=(0, 0, width, height)) scale.configure(yscrollcommand=ybar.set) # Layout title.grid(row=0, columnspan=3, sticky='new') scale.grid(row=1, column=0, sticky='nsew') graph.grid(row=1, column=1, sticky='nsew') ybar.grid(row=1, column=2, sticky='ns') xbar.grid(row=2, column=0, columnspan=2, sticky='ew') self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) return title, scale, graph
def run_pinballview(width, height, configuration): """ Changed from original Pierre-Luc Bacon implementation to reflect the visualization changes in the PinballView Class. """ width, height = float(width), float(height) master = Tk() master.title('RLPY Pinball') screen = Canvas(master, width=500.0, height=500.0) screen.configure(background='LightGray') screen.pack() environment = PinballModel(configuration) environment_view = PinballView(screen, width, height, environment) actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE] done = False while not done: user_action = np.random.choice(actions) environment_view.blit() if environment.episode_ended(): done = True if environment.take_action(user_action) == environment.END_EPISODE: done = True environment_view.blit() screen.update()
def run_pinballview(width, height, configuration): """ Changed from original Pierre-Luc Bacon implementation to reflect the visualization changes in the PinballView Class. """ width, height = float(width), float(height) master = Tk() master.title('RLPY Pinball') screen = Canvas(master, width=500.0, height=500.0) screen.configure(background='LightGray') screen.pack() environment = PinballModel(configuration) environment_view = PinballView(screen, width, height, environment) actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE ] done = False while not done: user_action = np.random.choice(actions) environment_view.blit() if environment.episode_ended(): done = True if environment.take_action(user_action) == environment.END_EPISODE: done = True environment_view.blit() screen.update()
class MapRenderer: def __init__(self, config=config, **kwargs): self.config = config self.__dict__.update(kwargs) self.map = Map(**kwargs) @property def canvas_width(self): return self.map.width * self.map.block_width @property def canvas_height(self): return self.map.height * self.map.block_height def init_canvas(self, parent=None): if parent == None: parent = self.parent if hasattr(self, 'canvas'): pass else: self.canvas = Canvas(parent) self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) def kill_canvas(self): if hasattr(self, 'canvas'): self.canvas.destroy() def draw(self): self.canvas.configure(width=self.canvas_width, height=self.canvas_height) for i in xrange(len(self.map.blockdata)): block_x = i % self.map.width block_y = i / self.map.width self.draw_block(block_x, block_y) def draw_block(self, block_x, block_y): # the canvas starts at 4, 4 for some reason # probably something to do with a border index, indey = 4, 4 # Draw one block (4x4 tiles) block = self.map.blockdata[block_y * self.map.width + block_x] # Ignore nonexistent blocks. if block >= len(self.map.tileset.blocks): return for j, tile in enumerate(self.map.tileset.blocks[block]): try: # Tile gfx are split in half to make vram mapping easier if tile >= 0x80: tile -= 0x20 tile_x = block_x * self.map.block_width + (j % 4) * 8 tile_y = block_y * self.map.block_height + (j / 4) * 8 self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile]) except: pass def crop(self, *args, **kwargs): self.map.crop(*args, **kwargs) self.draw()
class ScrolledCanvas(Frame): def __init__(self, parent, width=100, height=100, bg="white", scrollregion=(0, 0, 300, 300)): Frame.__init__(self, parent) self.canvas = Canvas(self, width=width - 20, height=height - 20, bg=bg, scrollregion=scrollregion) self.canvas.grid(row=0, column=0) scv = Scrollbar(self, orient="vertical", command=self.canvas.yview) sch = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.canvas.configure(xscrollcommand=sch.set, yscrollcommand=scv.set) scv.grid(row=0, column=1, sticky="ns") sch.grid(row=1, column=0, sticky="ew") self.bind("<Configure>", self.resize) self.config = False self.bind("<Configure>", self.resize) def get_canvas(self): return self.canvas def resize(self, event): if self.config: self.width, self.height = self.winfo_width(), self.winfo_height() self.canvas.config(width=self.width - 20, height=self.height - 20) else: self.config = True
def xGC_skew(seq, window = 1000, zoom = 100, r = 300, px = 100, py = 100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y yscroll = Scrollbar(orient = VERTICAL) xscroll = Scrollbar(orient = HORIZONTAL) canvas = Canvas(yscrollcommand = yscroll.set, xscrollcommand = xscroll.set, background = 'white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command = canvas.yview) xscroll.config(command = canvas.xview) yscroll.pack(side = RIGHT, fill = Y) xscroll.pack(side = BOTTOM, fill = X) canvas.pack(fill=BOTH, side = LEFT, expand = 1) canvas.update() X0, Y0 = r + px, r + py x1, x2, y1, y2 = X0 - r, X0 + r, Y0 -r, Y0 + r ty = Y0 canvas.create_text(X0, ty, text = '%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC %3.2f%%' % (GC(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC Skew', fill = 'blue') ty +=20 canvas.create_text(X0, ty, text = 'Accumulated GC Skew', fill = 'magenta') ty +=20 canvas.create_oval(x1,y1, x2, y2) acc = 0 start = 0 for gc in GC_skew(seq, window): r1 = r acc+=gc # GC skew alpha = pi - (2*pi*start)/len(seq) r2 = r1 - gc*zoom x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'blue') # accumulated GC skew r1 = r - 50 r2 = r1 - acc x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'magenta') canvas.update() start += window canvas.configure(scrollregion = canvas.bbox(ALL))
def xGC_skew(seq, window=1000, zoom=100, r=300, px=100, py=100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y yscroll = Scrollbar(orient=VERTICAL) xscroll = Scrollbar(orient=HORIZONTAL) canvas = Canvas(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set, background='white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command=canvas.yview) xscroll.config(command=canvas.xview) yscroll.pack(side=RIGHT, fill=Y) xscroll.pack(side=BOTTOM, fill=X) canvas.pack(fill=BOTH, side=LEFT, expand=1) canvas.update() X0, Y0 = r + px, r + py x1, x2, y1, y2 = X0 - r, X0 + r, Y0 - r, Y0 + r ty = Y0 canvas.create_text(X0, ty, text='%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq))) ty += 20 canvas.create_text(X0, ty, text='GC %3.2f%%' % (GC(seq))) ty += 20 canvas.create_text(X0, ty, text='GC Skew', fill='blue') ty += 20 canvas.create_text(X0, ty, text='Accumulated GC Skew', fill='magenta') ty += 20 canvas.create_oval(x1, y1, x2, y2) acc = 0 start = 0 for gc in GC_skew(seq, window): r1 = r acc += gc # GC skew alpha = pi - (2*pi*start)/len(seq) r2 = r1 - gc*zoom x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1, y1, x2, y2, fill='blue') # accumulated GC skew r1 = r - 50 r2 = r1 - acc x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1, y1, x2, y2, fill='magenta') canvas.update() start += window canvas.configure(scrollregion=canvas.bbox(ALL))
def init_ui(self): self.rowconfigure(3, weight=1) self.columnconfigure(0, weight=1) self.button_load_type = Button(self, text="Load Type JSON", command=lambda: browse_file(self, 1, )) self.button_load_type.grid( row=0, columnspan=2, sticky=W + E, pady=4, padx=5) self.button_load_color = Button( self, text="Load Color JSON", command=lambda: browse_file(self, 2)) self.button_load_color.grid( row=1, columnspan=2, sticky=W + E, pady=4, padx=5) button_load = Button( self, text="Load Images", command=lambda: browse_images(self)) button_load.grid(row=2, columnspan=2, sticky=W + E, pady=4, padx=5) button_learn = Button( self, text="Test", command= lambda: start_testing(self.dtype, self.dcolor, self.picture_frames) ) button_learn.grid(row=4, columnspan=2, sticky=W + E, pady=4, padx=5) canvas = Canvas(self) canvas.grid(row=3, sticky=W + E + N + S, column=0, pady=4, padx=5) frame = self.picture_frame = Frame(canvas) canvas.create_window(0, 0, window=frame, anchor='nw') scroll_bar = Scrollbar(self, orient="vertical", command=canvas.yview) scroll_bar.grid(sticky=E + N + S, padx=5, row=3, column=1) canvas.configure(yscrollcommand=scroll_bar.set) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size of the inner frame size = (frame.winfo_reqwidth(), frame.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if frame.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=frame.winfo_reqwidth()) frame.bind('<Configure>', _configure_interior) def _configure_canvas(event): if frame.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(frame, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
class RecapCalculs: ''' Interface graphique recapitulant les caracteristique du sismogramme presentant les options de filtrage et de calculs du noyau de sensibilite ''' def __init__(self,root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): self.message = Label(self.frame, text="Recapitulatif du sismogramme").grid(row=0) global X X=read(textPath.get()) self.recap = Listbox(self.frame, height = 15, width = 50) self.recap.insert(1, "network: {}\n".format(X[0].stats.network)) self.recap.insert(2, "station: {}\n".format(X[0].stats.station)) self.recap.insert(3, "location: {}\n".format(X[0].stats.location)) self.recap.insert(4, "channel: {}\n".format(X[0].stats.channel)) self.recap.insert(5, "start time: {}\n".format(X[0].stats.starttime)) self.recap.insert(6, "end time: {}\n".format(X[0].stats.endtime)) self.recap.insert(7, "sampling rate: {}\n".format(X[0].stats.sampling_rate)) self.recap.insert(8, "delta: {}\n".format(X[0].stats.delta)) self.recap.insert(9, "number points: {}\n".format(X[0].stats.npts)) self.recap.insert(10, "calibration: {}\n".format(X[0].stats.calib)) self.recap.insert(11, "event latitude: {}\n".format(X[0].stats.sac.evla)) self.recap.insert(12, "event longitude: {}\n".format(X[0].stats.sac.evlo)) self.recap.insert(13, "event depth: {}\n".format(X[0].stats.sac.evdp)) self.recap.insert(14, "station latitude: {}\n".format(X[0].stats.sac.stla)) self.recap.insert(15, "station longitude: {}\n".format(X[0].stats.sac.stlo)) self.recap.grid(row=0) #afficheGraphique() def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def __init__(self, parent): master = Frame(parent, bg = 'green') master.grid(sticky = W + N + E + S) master.rowconfigure(0, weight = 1) master.columnconfigure(0, weight = 1) canvas = Canvas(master) self._canvas = canvas canvas.grid(row = 0, column = 0, sticky = W + N + E + S) hScroll = Scrollbar(master, orient = HORIZONTAL, command = canvas.xview) hScroll.grid(row = 1, column = 0, sticky = W + E) vScroll = Scrollbar(master, orient = VERTICAL, command = canvas.yview) vScroll.grid(row = 0, column = 1, sticky = N + S) canvas.configure(xscrollcommand = hScroll.set, yscrollcommand = vScroll.set) Frame.__init__(self, canvas, bg = 'blue') canvas.create_window(0, 0, window = self, anchor = N + W)
def _init_ui(self): # Load an image self.img = ImageTk.PhotoImage(Image.open(r"images\dna5.png")) # Define a canvas in a frame frame = Frame(self) c = Canvas(frame, bg="white", height=475, width=475) # Display the image in the canvas c.create_image(0, 0, image=self.img, anchor=NW) # Y-scrollbar yscrollbar = Scrollbar(frame, command=c.yview) c.configure(yscrollcommand=yscrollbar.set) # X-scrollbar xscrollbar = Scrollbar(frame, orient=HORIZONTAL, command=c.xview) c.configure(xscrollcommand=xscrollbar.set) # Display widgets using grid layout. frame.grid(row=0, column=0) yscrollbar.grid(row=0, column=2, sticky=S + N) xscrollbar.grid(row=2, column=0, sticky=W + E) c.grid(row=0, column=0) self.pack(fill=BOTH, expand=1)
def createWidgets(self): "Create initial widget set." # Objects title = Label(self, text="Bandwidth (Gb/s)", bg=self.bg) width = self.gwidth height = self.gheight scale = self.createScale() graph = Canvas(self, width=width, height=height, background=self.bg) xbar = Scrollbar(self, orient="horizontal", command=graph.xview) ybar = Scrollbar(self, orient="vertical", command=self.yview) graph.configure(xscrollcommand=xbar.set, yscrollcommand=ybar.set, scrollregion=(0, 0, width, height)) scale.configure(yscrollcommand=ybar.set) # Layout title.grid(row=0, columnspan=3, sticky="new") scale.grid(row=1, column=0, sticky="nsew") graph.grid(row=1, column=1, sticky="nsew") ybar.grid(row=1, column=2, sticky="ns") xbar.grid(row=2, column=0, columnspan=2, sticky="ew") self.rowconfigure(1, weight=1) self.columnconfigure(1, weight=1) return title, scale, graph
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)
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)
class MSTM_studio: splash_time = 0.5 # time to show splash window, seconds def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' top.withdraw() time_start = time.time() splash = sup.SplashWindow(top) self.style = ttk.Style() if sys.platform == 'win32': self.style.theme_use('winnative') self.style.configure('.', font='TkDefaultFont') #~ top.geometry('838x455+364+117') top.geometry('850x440') top.title('MSTM studio') #~ top.configure(highlightcolor='black') self.load_images() self.root_panedwin = ttk.Panedwindow(top, orient='horizontal') self.root_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.root_panedwin.configure(width=200) self.left_frame = ttk.Frame(width=220.0) self.root_panedwin.add(self.left_frame) #~ self.middle_frame = ttk.Labelframe(width=350, text='View') self.middle_frame = ttk.Frame(width=350) self.root_panedwin.add(self.middle_frame) self.right_frame = ttk.Frame() self.root_panedwin.add(self.right_frame) self.__funcid0 = self.root_panedwin.bind('<Map>', self.__adjust_sash0) self.left_panedwin = ttk.Panedwindow(self.left_frame, orient='vertical') self.left_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.left_panedwin.configure(width=200) self.materials_frame = ttk.Labelframe(height=105, text='Materials') self.left_panedwin.add(self.materials_frame) self.spheres_frame = ttk.Labelframe(text='Spheres') self.left_panedwin.add(self.spheres_frame) self.__funcid1 = self.left_panedwin.bind('<Map>', self.__adjust_sash1) self.style.configure('Treeview.Heading', font='TkDefaultFont') self.stvMaterial = ScrolledTreeView(self.materials_frame) self.stvMaterial.place(relx=0.0, y=30, relheight=0.8, relwidth=1.0) self.configure_stvMaterial() self.stvMaterial.bind('<Double-1>', sup.btChangeMatColClick) self.btAddMat = ttk.Button(self.materials_frame, command=sup.btAddMatClick, text='A', image=self.imAdd) self.btAddMat.place(x=5, y=0, height=25, width=25) self.btLoadMat = ttk.Button(self.materials_frame, command=sup.btLoadMatClick, text='L', image=self.imLoad) self.btLoadMat.place(x=30, y=0, height=25, width=25) self.btPlotMat = ttk.Button(self.materials_frame, command=sup.btPlotMatClick, text='P', image=self.imPlot) self.btPlotMat.place(x=55, y=0, height=25, width=25) self.btDelMat = ttk.Button(self.materials_frame, command=sup.btDelMatClick, text='D', image=self.imDelete) self.btDelMat.place(relx=1, x=-30, rely=0, height=25, width=25) self.stvSpheres = ScrolledTreeView(self.spheres_frame) self.stvSpheres.place(relx=0.0, y=30, relheight=0.85, relwidth=1.0) self.configure_stvSpheres() self.stvSpheres.bind('<Double-1>', sup.btEditSphClick) self.btAddSph = ttk.Button(self.spheres_frame, command=sup.btAddSphClick, text='A', image=self.imAdd) self.btAddSph.place(x=5, y=0, height=25, width=25) self.btEditSph = ttk.Button(self.spheres_frame, command=sup.btEditSphClick, text='E', image=self.imEdit) self.btEditSph.place(x=30, y=0, height=25, width=25) self.btPlotSph = ttk.Button(self.spheres_frame, command=sup.btPlotSphClick, text='R', image=self.imRefresh) self.btPlotSph.place(x=55, y=0, height=25, width=25) self.lbEnvMat = ttk.Label(self.spheres_frame, text='Matrix') self.lbEnvMat.place(relx=0.45, y=-5) self.cbEnvMat = ttk.Combobox(self.spheres_frame) self.cbEnvMat.place(relx=0.45, y=10, width=55) self.btDelSph = ttk.Button(self.spheres_frame, command=sup.btDelSphClick, text='D', image=self.imDelete) self.btDelSph.place(relx=1.0, y=0, x=-30, height=25, width=25) self.middle_panedwin = ttk.Panedwindow(self.middle_frame, orient='vertical') self.middle_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) #~ self.middle_panedwin.configure(relwidth=1.0) self.canvas_frame = ttk.Labelframe(height=360, text='View') self.middle_panedwin.add(self.canvas_frame) self.spectrum_frame = ttk.Labelframe(height=-40, text='Spectrum') self.middle_panedwin.add(self.spectrum_frame) self.__funcid2 = self.left_panedwin.bind('<Map>', self.__adjust_sash2) self.canvas = Canvas(self.canvas_frame) self.canvas.place(relx=0.0, rely=0, relheight=1.0, relwidth=1.0) self.canvas.configure(background='white') self.canvas.configure(borderwidth='2') self.canvas.configure(relief='ridge') self.canvas.configure(selectbackground='#c4c4c4') self.canvas.bind('<Button-4>', sup.mouse_wheel) # for Linux self.canvas.bind('<Button-5>', sup.mouse_wheel) # for Linux self.canvas.bind('<MouseWheel>', sup.mouse_wheel) # for Windowz self.canvas.bind('<Button-3>', sup.mouse_down) self.canvas.bind('<B3-Motion>', sup.mouse_move) self.canvas.bind('<ButtonRelease-3>', sup.mouse_up) self.lbZoom = ttk.Label( self.canvas, text='x1.00', background='white') #font=('courier', 18, 'bold'), width=10) self.lbZoom.place(relx=1.0, x=-50, rely=1.0, y=-25) self.lbLambdaMin = ttk.Label(self.spectrum_frame, text='min') self.lbLambdaMin.place(x=5, y=0) self.edLambdaMin = ttk.Entry(self.spectrum_frame) self.edLambdaMin.place(x=5, y=15, width=35) self.edLambdaMin.insert(0, '300') self.lbLambdaMax = ttk.Label(self.spectrum_frame, text='max') self.lbLambdaMax.place(x=45, y=0) self.edLambdaMax = ttk.Entry(self.spectrum_frame) self.edLambdaMax.place(x=45, y=15, width=35) self.edLambdaMax.insert(0, '800') self.lbLambdaCount = ttk.Label(self.spectrum_frame, text='count') self.lbLambdaCount.place(x=85, y=0) self.edLambdaCount = ttk.Entry(self.spectrum_frame) self.edLambdaCount.place(x=85, y=15, width=35) self.edLambdaCount.insert(0, '51') self.btCalcSpec = ttk.Button(self.spectrum_frame, command=sup.btCalcSpecClick, text='Calculate', image=self.imCalc, compound='left') self.btCalcSpec.place(x=130, y=10, width=90, height=25) self.lbSpecScale = ttk.Label(self.spectrum_frame, text='scale') self.lbSpecScale.place(relx=1, x=-115, y=0) self.edSpecScale = ttk.Entry(self.spectrum_frame) self.edSpecScale.place(relx=1, x=-115, y=15, width=50) self.edSpecScale.insert(0, '1') self.btSaveSpec = ttk.Button(self.spectrum_frame, command=sup.btSaveSpecClick, text='S', image=self.imSave) self.btSaveSpec.place(relx=1, x=-55, y=10, width=25, height=25) self.btPlotSpec = ttk.Button(self.spectrum_frame, command=sup.btPlotSpecClick, text='P', image=self.imPlot) self.btPlotSpec.place(relx=1, x=-30, y=10, width=25, height=25) self.right_panedwin = ttk.Panedwindow(self.right_frame, orient='vertical') self.right_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.right_panedwin.configure(width=200) self.plot_frame = ttk.Labelframe(height=200, text='Plot') self.right_panedwin.add(self.plot_frame) self.contribs_frame = ttk.Labelframe(height=150, text='Other contributions') self.right_panedwin.add(self.contribs_frame) self.fitting_frame = ttk.Labelframe(height=-50, text='Fitting') self.right_panedwin.add(self.fitting_frame) self.__funcid3 = self.right_panedwin.bind('<Map>', self.__adjust_sash3) # CONTRIBUTIONS self.btAddContrib = ttk.Button(self.contribs_frame, command=sup.btAddContribClick, text='A', image=self.imAdd) self.btAddContrib.place(x=5, y=0, height=25, width=25) self.btPlotAllContribs = ttk.Button(self.contribs_frame, command=sup.btPlotAllContribsClick, text='P', image=self.imPlot) self.btPlotAllContribs.place(x=30, y=0, height=25, width=25) self.btDelContrib = ttk.Button(self.contribs_frame, command=sup.btDelContribClick, text='D', image=self.imDelete) self.btDelContrib.place(relx=1.0, y=0, x=-30, height=25, width=25) self.cbContribs = [] self.edContribs = [] # actually, it will be the list of lists [[]] self.btPlotsContrib = [] self.contribs_list = [ 'ConstBkg', 'LinearBkg', 'LorentzBkg', 'Mie single', 'Mie LN', 'Lorentz peak', 'Gauss peak', 'Au film', 'bst-3Au/glass' ] self.cbContribMats = [] self.btContribDistribPlots = [] # Fitting frame self.edExpFileName = ttk.Entry(self.fitting_frame, text='Exp. file name') self.edExpFileName.place(x=5, y=0, height=25, relwidth=0.8) self.btLoadExp = ttk.Button(self.fitting_frame, command=sup.btLoadExpClick, text='L', image=self.imLoad) self.btLoadExp.place(relx=1.0, x=-55, y=0, height=25, width=25) self.btPlotExp = ttk.Button(self.fitting_frame, command=sup.btPlotExpClick, text='P', image=self.imPlot) self.btPlotExp.place(relx=1.0, x=-30, y=0, height=25, width=25) self.btStartFit = ttk.Button(self.fitting_frame, command=sup.btStartFitClick, text='>', image=self.imPlay) self.btStartFit.place(x=5, y=30, height=25, width=25) self.btStopFit = ttk.Button(self.fitting_frame, command=sup.btStopFitClick, text='|', image=self.imStop) self.btStopFit.place(x=30, y=30, height=25, width=25) self.lbChiSq = ttk.Label(self.fitting_frame, text='ChiSq:') self.lbChiSq.place(x=60, y=35) self.btConstraints = ttk.Button(self.fitting_frame, command=sup.btConstraintsClick, text='Constraints...') self.btConstraints.place(relx=1, x=-100, y=30, height=25, width=95) self._create_menu(top) time_delta = time.time() - time_start # in seconds if time_delta < self.splash_time: time.sleep(self.splash_time - time_delta) top.deiconify() splash.destroy() def configure_stvMaterial(self): self.stvMaterial.configure(columns='Col1') self.stvMaterial.heading('#0', text='MatID') self.stvMaterial.heading('#0', anchor='center') self.stvMaterial.column('#0', width='46') self.stvMaterial.column('#0', minwidth='20') self.stvMaterial.column('#0', stretch='1') self.stvMaterial.column('#0', anchor='w') self.stvMaterial.heading('Col1', text='Name') self.stvMaterial.heading('Col1', anchor='center') self.stvMaterial.column('Col1', width='150') self.stvMaterial.column('Col1', minwidth='20') self.stvMaterial.column('Col1', stretch='1') self.stvMaterial.column('Col1', anchor='w') def configure_stvSpheres(self): self.stvSpheres.configure(columns='Col1 Col2 Col3 Col4 Col5') self.stvSpheres.heading('#0', text='ID') self.stvSpheres.heading('#0', anchor='center') self.stvSpheres.column('#0', width='34') self.stvSpheres.column('#0', minwidth='20') self.stvSpheres.column('#0', stretch='1') self.stvSpheres.column('#0', anchor='w') self.stvSpheres.heading('Col1', text='R') self.stvSpheres.heading('Col1', anchor='center') self.stvSpheres.column('Col1', width='37') self.stvSpheres.column('Col1', minwidth='20') self.stvSpheres.column('Col1', stretch='1') self.stvSpheres.column('Col1', anchor='w') self.stvSpheres.heading('Col2', text='X') self.stvSpheres.heading('Col2', anchor='center') self.stvSpheres.column('Col2', width='31') self.stvSpheres.column('Col2', minwidth='20') self.stvSpheres.column('Col2', stretch='1') self.stvSpheres.column('Col2', anchor='w') self.stvSpheres.heading('Col3', text='Y') self.stvSpheres.heading('Col3', anchor='center') self.stvSpheres.column('Col3', width='34') self.stvSpheres.column('Col3', minwidth='20') self.stvSpheres.column('Col3', stretch='1') self.stvSpheres.column('Col3', anchor='w') self.stvSpheres.heading('Col4', text='Z') self.stvSpheres.heading('Col4', anchor='center') self.stvSpheres.column('Col4', width='34') self.stvSpheres.column('Col4', minwidth='20') self.stvSpheres.column('Col4', stretch='1') self.stvSpheres.column('Col4', anchor='w') self.stvSpheres.heading('Col5', text='mID') self.stvSpheres.heading('Col5', anchor='center') self.stvSpheres.column('Col5', width='32') self.stvSpheres.column('Col5', minwidth='20') self.stvSpheres.column('Col5', stretch='1') self.stvSpheres.column('Col5', anchor='w') def load_images(self): def tryload(fn): try: im = ImageTk.PhotoImage(file=os.path.normpath( os.path.join(os.path.dirname(__file__), 'images', fn))) except Exception as err: print('Can not load %s\n%s' % (fn, err)) return None return im self.imLoad = tryload('folder_open_icon&16.png') self.imDelete = tryload('delete_icon&16.png') self.imPlot = tryload('chart_bar_icon&16.png') self.imPlot2 = tryload('chart_bar2_icon&16.png') self.imAdd = tryload('sq_plus_icon&16.png') self.imSave = tryload('save_icon&16.png') self.imRefresh = tryload('refresh_icon&16.png') self.imExport = tryload('export_icon&16.png') self.imImport = tryload('import_icon&16.png') self.imPlay = tryload('playback_play_icon&16.png') self.imStop = tryload('playback_stop_icon&16.png') self.imCalc = tryload('cogs_icon&16.png') self.imEdit = tryload('doc_edit_icon&16.png') self.imExit = tryload('on-off_icon&16.png') self.imBrush = tryload('brush_icon&16.png') self.imZoomIn = tryload('round_plus_icon&16.png') self.imZoomOut = tryload('round_minus_icon&16.png') def __adjust_sash0( self, event): # mysterious functions left from previous civilizations paned = event.widget pos = [ 220, 575, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid0) del self.__funcid0 def __adjust_sash1(self, event): paned = event.widget pos = [ 145, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid1) del self.__funcid1 def __adjust_sash2(self, event): paned = event.widget pos = [ 200, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid2) del self.__funcid2 def __adjust_sash3(self, event): paned = event.widget pos = [ 200, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid3) del self.__funcid3 def _create_menu(self, top): self.menubar = Menu(top) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label='Import spheres...', command=sup.btImportSpheres, image=self.imImport, compound='left') self.filemenu.add_command(label='Export spheres...', command=sup.btExportSpheres, image=self.imExport, compound='left') self.filemenu.add_separator() self.filemenu.add_command(label='Exit', command=sup.destroy_window, image=self.imExit, compound='left') self.menubar.add_cascade(label='File', menu=self.filemenu) self.matmenu = Menu(self.menubar, tearoff=0) self.matmenu.add_command(label='Add constant...', command=sup.btAddMatClick, image=self.imAdd, compound='left') self.matmenu.add_command(label='Load function...', command=sup.btLoadMatClick, image=self.imLoad, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Delete selected', command=sup.btDelMatClick, image=self.imDelete, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Plot selected', command=sup.btPlotMatClick, image=self.imPlot, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Change view color...', command=sup.btChangeMatColClick, image=self.imBrush, compound='left') self.menubar.add_cascade(label='Materials', menu=self.matmenu) self.sphmenu = Menu(self.menubar, tearoff=0) self.sphmenu.add_command(label='Add...', command=sup.btAddSphClick, image=self.imAdd, compound='left') self.sphmenu.add_separator() self.sphmenu.add_command(label='Edit selected...', command=sup.btEditSphClick, image=self.imEdit, compound='left') self.sphmenu.add_command(label='Delete selected', command=sup.btDelSphClick, image=self.imDelete, compound='left') self.sphmenu.add_separator() self.sphmenu.add_command(label='Generate on mesh...', command=sup.btGenerateSpheresClick) self.menubar.add_cascade(label='Spheres', menu=self.sphmenu) self.viewmenu = Menu(self.menubar, tearoff=0) self.viewmenu.add_command(label='Zoom in', command=lambda: sup.mouse_wheel( type('', (), { 'num': 4, 'delta': 0 })()), image=self.imZoomIn, compound='left') self.viewmenu.add_command(label='Zoom out', command=lambda: sup.mouse_wheel( type('', (), { 'num': 5, 'delta': 0 })()), image=self.imZoomOut, compound='left') self.viewmenu.add_command(label='Reset view', command=sup.btPlotSphClick, image=self.imRefresh, compound='left') self.menubar.add_cascade(label='View', menu=self.viewmenu) self.opticsmenu = Menu(self.menubar, tearoff=0) self.opticsmenu.add_command(label='Calculate', command=sup.btCalcSpecClick, image=self.imCalc, compound='left') self.menubar.add_cascade(label='Spectrum', menu=self.opticsmenu) self.fittingmenu = Menu(self.menubar, tearoff=0) self.fittingmenu.add_command(label='Load experiment...', command=sup.btLoadExpClick, image=self.imLoad, compound='left') self.fittingmenu.add_separator() self.fittingmenu.add_command(label='Constraints...', command=sup.btConstraintsClick) self.fittingmenu.add_separator() self.fittingmenu.add_command(label='Start fit', command=sup.btStartFitClick, image=self.imPlay, compound='left') self.fittingmenu.add_command(label='Stop fit', command=sup.btStopFitClick, image=self.imStop, compound='left') self.menubar.add_cascade(label='Fitting', menu=self.fittingmenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label='About', command=sup.btAboutClick) self.menubar.add_cascade(label='Help', menu=self.helpmenu) # display the menu top.config(menu=self.menubar)
class PongGUI(Frame): player_1 = {'Up' :-5, 'Down': 5} player_2 = {'w':-5, 's': 5} cpu_level = {'Easy' : {'Up' : -3, 'Down': 3}, 'Medium': {'Up' : -9, 'Down': 9}, 'Hard' : {'Up' : -15, 'Down': 15} } score = [0,0] plays =1 cpu_enable = False cpu_turn = True buffsize = 1024 #List to check all balls balls = [] obs = [] def __init__(self, parent,screen=[600,400]): Frame.__init__(self, parent) self.parent = parent self.bg_status = 0 self.initUI() self.key_pressed = set() self.obstacles = set() self.bind_all('<KeyPress>', lambda event: self.key_pressed.add(event.keysym)) self.bind_all('<KeyRelease>', lambda event: self.key_pressed.discard(event.keysym)) self.bind_all('<Escape>',self.end) self.connect_server() def end(self, event): self.master.destroy() def connect_server(self): self.setup = True host = 'localhost' port = 9000 addr = (host, port) try: self.tcpclisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcpclisock.connect(addr) print 'Connected to: ', addr self.tcpclisock.setblocking(0) self.parent.title("Pong Client "+'Connected to: '+ str(addr)) except: print 'not able to connect to server.' self.create_server() def create_server(self): host = '' port = 9000 addr = (host, port) self.setup = True print "makeServer():" self.tcpsersock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcpsersock.bind(addr) self.tcpsersock.listen(5) self.tcpclisock, addr = self.tcpsersock.accept() self.tcpclisock.setblocking(0) print 'Connected from: ', addr self.parent.title("Pong Server: " + 'Connected from: ' + str(addr)) def initUI(self): self.parent.title("Pong") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status)) self.left = Paddle(self.canvas, 1, [30, 10], 10, 100,"#fb0") self.right = Paddle(self.canvas, 1, [570, 40], 10, 100,"#05f") self.balls.append(Ball(self.canvas,1,[70,70],10,[-2,-2])) #self.balls.append(Ball(self.canvas,1,[100,100],10,[2,2])) #self.balls.append(Ball(self.canvas,1,[200,100],10,[2,-2])) #self.balls.append(Ball(self.canvas,1,[100,200],10,[-2,2])) self.obs.append(Obstacle(self.canvas,[200,200],"Pin",6)) self.obs.append(Obstacle(self.canvas,[400,300],"Paddle",7)) self.obs.append(Obstacle(self.canvas,[350,350],"Pin",4)) self.obs.append(Obstacle(self.canvas,[210,250],"Paddle",8)) self.obs.append(Obstacle(self.canvas,[250,250],"Size",8)) self.obs.append(Obstacle(self.canvas,[300,350],"Switch",8)) self.obs.append(Obstacle(self.canvas,[400,350],"Switch",8)) self.obs.append(Obstacle(self.canvas,[420,320],"Teleport",6)) self.obs.append(Obstacle(self.canvas,[250,200],"Gravity",8)) self.obs.append(Obstacle(self.canvas,[300,50],"Reset",4,[0,1])) self.canvas.pack(fill=BOTH, expand=1) self.score_msg = ' Home 0 - 0 Visitor ' self.label_score = Label(self, text=self.score_msg, width=len(self.score_msg), bg='yellow') self.choices = ['Easy', 'Medium', 'Hard'] self.dificulty = StringVar() self.dificulty.set('Medium') self.option = OptionMenu(self, self.dificulty, *self.choices) self.option.pack(side=LEFT, fill=BOTH) self.label_score.pack(side= LEFT, fill=BOTH) self.text = "" self.text_canvas = self.canvas.create_text(300,10, text=self.text, fill="white") self.after(200, self.update) def check_keys(self): for i in self.key_pressed: if i == 'w' or i == 's': border = self.left.get_border() if 270 >= (self.player_2[i] + border[1]) >=0: self.left.update_position(self.player_2[i]) if i == 'Up' or i == 'Down': border = self.right.get_border() if 270 >= (self.player_1[i] + border[1]) >=0: self.right.update_position(self.player_1[i]) def reset(self): self.bg_status = 0 self.plays = 1 self.__dx = 2 self.__dy = -2 self.canvas.configure(bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status)) def check_collision(self): #Check obstacle contacts for i in self.obs : for j in self.balls: if i.alive and i.vel is not None: i.move() if i.update(j.get_position()) and j.get_inside(): #We have a collision! ball_pos = j.get_center() obs_pos = i.get_position() if i.get_type() == 'Pin': #If pin just ounce back if abs(ball_pos[0] - obs_pos[0]) < abs(ball_pos[1] - obs_pos[1]): j.set_velocity([ j.vel[0], -j.vel[1] ]) else: j.set_velocity([ -j.vel[0], j.vel[1] ]) j.set_inside(False) if j.get_velocity()[0]<0: self.cpu_turn = True else: self.cpu_turn = False if i.get_type() == 'Size' and 'Size' not in self.obstacles: self.obstacles.add('Size') #Increase size of ball self.text += "Size " self.update_text() i.affected = True j.set_radious(20) j.re_draw() if i.get_type() == 'Paddle': #Increase size paddle i.affected = True if j.get_velocity()[0] < 0 and 'Paddle2' not in self.obstacles: self.obstacles.add('Paddle2') self.text += "Paddle2 " self.update_text() self.right.length = 150 self.right.re_draw() elif j.get_velocity()[0] > 0 and 'Paddle1' not in self.obstacles: self.obstacles.add('Paddle1') self.text += "Paddle1 " self.update_text() self.left.length = 150 self.left.re_draw() if i.get_type() == 'Switch': #Change controller configuration i.affected = True if j.get_velocity()[0] < 0 and 'Switch2' not in self.obstacles: self.obstacles.add('Switch2') self.text += "Switch2 " self.update_text() self.player_2['w'] = -1*self.player_2['w'] self.player_2['s'] = -1*self.player_2['s'] elif j.get_velocity()[0] > 0 and 'Switch1' not in self.obstacles: self.obstacles.add('Switch1') self.text += "Switch1 " self.update_text() self.player_1['Up'] = -1*self.player_1['Up'] self.player_1['Down'] = -1*self.player_1['Down'] if i.get_type() == 'Teleport': i.affected = True j.set_position([200+int(200*random.random()), 100+int(100*random.random())]) j.set_velocity([j.vel[0],j.vel[1]*2*random.random()]) j.re_draw() if i.get_type() == "Reset": i.affected = "True" self.obstacle_reset(j) elif not i.update(j.get_position()): j.set_inside(True) #TODO CHANGE DIRECTION OF GRAVITY RANDOMLY if i.get_type() == "Gravity": if i.alive and 'Gravity' not in self.obstacles: self.obstacles.add('Gravity') self.text += "Gravity " self.update_text() j.set_gravity(j.pos[1]) elif not i.alive: self.obstacles.discard('Gravity') self.text = self.text.replace('Gravity ',"") self.update_text() if j.gravity: j.set_gravity() def update_text(self): self.canvas.delete(self.text_canvas) self.text_canvas = self.canvas.create_text(300,10, text=self.text, fill="white") def obstacle_reset(self, ball): self.text = "" self.update_text() ball.set_radious(10) ball.re_draw() self.right.length = 100 self.right.re_draw() self.left.length = 100 self.left.re_draw() self.player_2['w'] = -5 self.player_2['s'] = 5 self.player_1['Up'] = -5 self.player_1['Down'] = 5 if ball.gravity: ball.set_gravity() #ball.vel[1] = ball.vel[1]+0.1 self.obstacles.clear() def check_disable(self): for i in self.obs : for j in self.balls: if not i.affected: if i.type_obstacle == 'Size': j.set_radious(10) j.re_draw() if i.type_obstacle == 'Switch': self.player_2['w'] = -5 self.player_2['s'] = 5 self.player_1['Up'] = -5 self.player_1['Down'] = 5 if i.type_obstacle == 'Paddle': self.right.length = 100 self.left.length = 100 self.right.re_draw() self.left.re_draw() def restart(self, ball, player): ball.set_position([300,250]) ball.set_velocity([(-4*player)+2,(-4*player)+2]) ball.set_radious(10) self.left.length = 100 self.right.length = 100 self.left.set_position(self.left.pos) self.right.set_position(self.right.pos) self.player_2['w'] = -5 self.player_2['s'] = 5 self.player_1['Up'] = -5 self.player_1['Down'] = 5 if player == 1: self.cpu_turn = True self.score[player] += 1 self.update_score() self.reset() def check_paddle_collision(self, paddle, ball): if paddle.check_collision(ball.get_position()): delta_y = ball.get_center()[1] - paddle.get_center()[1] ball.set_velocity([-ball.vel[0],ball.vel[1]+0.05*delta_y]) self.plays +=1 self.cpu_turn = not self.cpu_turn def update(self): self.check_keys() self.check_collision() #self.check_disable() #Update new value fo the ball for i in self.balls: i.update() if not (self.plays % 5): print "Increasing speed" i.set_velocity([1.1*i.vel[0],1.1*i.vel[1]]) self.plays = 1 self.bg_status += 1 if self.bg_status ==9: self.bg_status = 0 self.canvas.configure(bg="#"+str(self.bg_status)+str(self.bg_status)+str(self.bg_status)) if i.get_position()[1] <= 0 or i.get_position()[1] >= 350: i.set_velocity([i.vel[0],-i.vel[1]]) if i.get_position()[2] >= 580: self.obstacle_reset(i) self.restart(i,0) elif i.get_position()[0] <= 0: self.obstacle_reset(i) self.restart(i,1) self.check_paddle_collision(self.left,i) self.check_paddle_collision(self.right,i) if self.cpu_turn and self.cpu_enable: for i in self.balls: pos = self.left.get_center() if (pos[1]>i.get_center()[1]): border = self.left.get_border() if border[1]>0: self.left.update_position(self.cpu_level[self.dificulty.get()]['Up'])# self.player_1["Up"]) else: border = self.left.get_border() if border[3]<365: self.left.update_position(self.cpu_level[self.dificulty.get()]['Down'])#self.player_1["Down"]) self.after(10, self.update) def update_score(self): self.label_score['text']=self.score_msg[:8]+str(self.score[0])+self.score_msg[9:12]+str(self.score[1])+self.score_msg[13:] self.label_score.update()
class Path: def __init__(self, root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a0 text6a0 = IntVar() global text6a1 text6a1 = IntVar() global text6b text6b = StringVar() global text6c1 text6c1 = StringVar() global text6c2 text6c2 = StringVar() global text6c3 text6c3 = StringVar() global text7_1 text7_1 = StringVar() global text7_2 text7_2 = StringVar() global text7_3 text7_3 = StringVar() global text7_4 text7_4 = StringVar() global text8 text8 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) def affiche0(): filterPara["text"]="Filter Off" text6a1.set(0) def affiche1(): filterPara["text"]="Filter On" text6a0.set(0) filterPara = Menubutton(self.frame, text="Butterworth filter ", relief=RAISED) filterPara.grid(row=0) filterPara.menu = Menu(filterPara, tearoff = 0) filterPara["menu"] = filterPara.menu filterPara.menu.add_checkbutton(label="Filter Off", variable = text6a0, command = affiche0) filterPara.menu.add_checkbutton(label="Filter On", variable = text6a1, command = affiche1) filterPara.grid(row=12) Label(self.frame, text="Filter name ?").grid(row=15) Entry(self.frame, textvariable=text6b).grid(row=16) Label(self.frame, text="\nIf butterworth = 0; \n just comment out those 3 parameters").grid(row=17) Label(self.frame, text="lowest frequency ?").grid(row=18,column=1) Entry(self.frame, textvariable=text6c1).grid(row=19, column=1) Label(self.frame, text="highest frequency ?").grid(row=20, column=1) Entry(self.frame, textvariable=text6c2).grid(row=21, column=1) Label(self.frame, text="number of poles ?").grid(row=22, column=1) Entry(self.frame, textvariable=text6c3).grid(row=23, column =1) Label(self.frame, text="time window t1 ?").grid(row=24) Entry(self.frame, textvariable=text7_1).grid(row=25) Label(self.frame, text="time window t2 ?").grid(row=26) Entry(self.frame, textvariable=text7_2).grid(row=27) Label(self.frame, text="time window t3 ?").grid(row=28) Entry(self.frame, textvariable=text7_3).grid(row=29) Label(self.frame, text="time window t4 ?").grid(row=30) Entry(self.frame, textvariable=text7_4).grid(row=31) Label(self.frame, text="itranslat (1 if you convert geodetic latitude to geocentric latitude) ?").grid(row=32) Entry(self.frame, textvariable=text8).grid(row=33) Button(self.frame, text="continue", command=writingFile).grid(row=34) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
class PigChaseHumanAgent(GuiAgent): def __init__(self, name, environment, keymap, max_episodes, max_actions, visualizer, quit): self._max_episodes = max_episodes self._max_actions = max_actions self._action_taken = 0 self._episode = 1 self._scores = [] self._rewards = [] self._episode_has_ended = False self._episode_has_started = False self._quit_event = quit super(PigChaseHumanAgent, self).__init__(name, environment, keymap, visualizer=visualizer) def _build_layout(self, root): # Left part of the GUI, first person view self._first_person_header = ttk.Label(root, text='First Person View', font=(None, 14, 'bold')) \ .grid(row=0, column=0) self._first_person_view = ttk.Label(root) self._first_person_view.grid(row=1, column=0, rowspan=10) # Right part, top self._first_person_header = ttk.Label(root, text='Symbolic View', font=(None, 14, 'bold')) \ .grid(row=0, column=1) self._symbolic_view = Canvas(root) self._symbolic_view.configure(width=ENV_BOARD_SHAPE[0]*CELL_WIDTH, height=ENV_BOARD_SHAPE[1]*CELL_WIDTH) self._symbolic_view.grid(row=1, column=1) # Bottom information self._information_panel = ttk.Label(root, text='Game stats', font=(None, 14, 'bold')) self._current_episode_lbl = ttk.Label(root, text='Episode: 0', font=(None, 12)) self._cum_reward_lbl = ttk.Label(root, text='Score: 0', font=(None, 12, 'bold')) self._last_action_lbl = ttk.Label(root, text='Previous action: None', font=(None, 12)) self._action_done_lbl = ttk.Label(root, text='Actions taken: 0', font=(None, 12)) self._action_remaining_lbl = ttk.Label(root, text='Actions remaining: 0', font=(None, 12)) self._information_panel.grid(row=2, column=1) self._current_episode_lbl.grid(row=3, column=1, sticky=W, padx=20) self._cum_reward_lbl.grid(row=4, column=1, sticky=W, padx=20) self._last_action_lbl.grid(row=5, column=1, sticky=W, padx=20) self._action_done_lbl.grid(row=6, column=1, sticky=W, padx=20) self._action_remaining_lbl.grid(row=7, column=1, sticky=W, padx=20) self._overlay = None # Main rendering callback self._pressed_binding = root.bind('<Key>', self._on_key_pressed) self._user_pressed_enter = False # UI Update callback root.after(self._tick, self._poll_frame) root.after(1000, self._on_episode_start) root.focus() def _draw_arrow(self, yaw, x, y, cell_width, colour): if yaw == 0.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .4) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y1, x2, y3, x3, y1, x2, y2, fill=colour) elif yaw == 90.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .6) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y2, x3, y1, x2, y2, x3, y3, fill=colour) elif yaw == 180.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .6) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y1, x3, y3, x2, y2, fill=colour) else: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .4) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y2, x1, y1, x3, y2, fill=colour) def _poll_frame(self): """ Main callback for UI rendering. Called at regular intervals. The method will ask the environment to provide a frame if available (not None). :return: """ cell_width = CELL_WIDTH circle_radius = 10 # are we done? if self._env.done and not self._episode_has_ended: self._on_episode_end() # build symbolic view board, _ = self._env._internal_symbolic_builder.build(self._env) if board is not None: board = board.T self._symbolic_view.delete('all') # Remove all previous items from Tkinter tracking width, height = board.shape for x in range(width): for y in range(height): cell_contents = str.split(str(board[x][y]), '/') for block in cell_contents: if block == 'sand': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="orange", tags="square") elif block == 'grass': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="lawn green", tags="square") elif block == 'lapis_block': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="black", tags="square") elif block == ENV_TARGET_NAMES[0]: self._symbolic_view.create_oval((x + .5) * cell_width - circle_radius, (y + .5) * cell_width - circle_radius, (x + .5) * cell_width + circle_radius, (y + .5) * cell_width + circle_radius, fill='pink') elif block == self.name: yaw = self._env._world_obs['Yaw'] % 360 self._draw_arrow(yaw, x, y, cell_width, 'red') elif block == ENV_AGENT_NAMES[0]: # Get yaw of other agent: entities = self._env._world_obs[ENV_ENTITIES] other_agent = list( map(Entity.create, filter(lambda e: e['name'] == ENV_AGENT_NAMES[0], entities))) if len(other_agent) == 1: other_agent = other_agent.pop() yaw = other_agent.yaw % 360 self._draw_arrow(yaw, x, y, cell_width, 'blue') # display the most recent frame frame = self._env.frame if frame is not None: from PIL import ImageTk self._first_person_view.image = ImageTk.PhotoImage(image=frame) self._first_person_view.configure(image=self._first_person_view.image) self._first_person_view.update() self._first_person_view.update() # process game state (e.g., has the episode started?) if self._episode_has_started and time.time() - self._episode_start_time < 3: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text="Get ready to catch the pig!", font=('Helvetica', '18')) self._init_overlay.create_text( 300, 140, text=str(3 - int(time.time() - self._episode_start_time)), font=('Helvetica', '18'), fill="red") self._init_overlay.create_text( 300, 220, width=460, text="How to play: \nUse the left/right arrow keys to turn, " "forward/back to move. The pig is caught if it is " "cornered without a free block to escape to.", font=('Helvetica', '14'), fill="black") self._root.update() elif self._episode_has_ended: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text='Finished episode %d of %d' % (self._episode, self._max_episodes), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 120, text='Score: %d' % sum(self._rewards), font=('Helvetica', '18')) if self._episode > 1: self._init_overlay.create_text( 300, 160, text='Average over %d episodes: %.2f' % (self._episode, np.mean(self._scores)), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 220, width=360, text="Press RETURN to start the next episode, ESC to exit.", font=('Helvetica', '14'), fill="black") self._root.update() elif hasattr(self, "_init_overlay") and self._init_overlay: self._destroy_overlay() # trigger the next update self._root.after(self._tick, self._poll_frame) def _create_overlay(self): self._init_overlay = Canvas(self._root, borderwidth=0, highlightthickness=0, width=600, height=300, bg="gray") self._init_overlay.place(relx=0.5, rely=0.5, anchor='center') def _destroy_overlay(self): self._init_overlay.destroy() self._init_overlay = None def _on_key_pressed(self, e): """ Main callback for keyboard events :param e: :return: """ if e.keysym == 'Escape': self._quit() if e.keysym == 'Return' and self._episode_has_ended: if self._episode >= self._max_episodes: self._quit() # start the next episode self._action_taken = 0 self._rewards = [] self._episode += 1 self._env.reset() self._on_episode_start() print('Starting episode %d' % self._episode) if self._episode_has_started and time.time() - self._episode_start_time >= 3: if e.keysym in self._keymap: mapped_action = self._keymap.index(e.keysym) _, reward, done = self._env.do(mapped_action) self._action_taken += 1 self._rewards.append(reward) self._on_experiment_updated(mapped_action, reward, done) def _on_episode_start(self): self._episode_has_ended = False self._episode_has_started = True self._episode_start_time = time.time() self._on_experiment_updated(None, 0, self._env.done) def _on_episode_end(self): self._episode_has_started = False self._episode_has_ended = True self._scores.append(sum(self._rewards)) self.visualize(self._episode, 'Reward', sum(self._rewards)) def _on_experiment_updated(self, action, reward, is_done): self._current_episode_lbl.config(text='Episode: %d' % self._episode) self._cum_reward_lbl.config(text='Score: %d' % sum(self._rewards)) self._last_action_lbl.config(text='Previous action: %s' % action) self._action_done_lbl.config(text='Actions taken: {0}'.format(self._action_taken)) self._action_remaining_lbl.config(text='Actions remaining: %d' % (self._max_actions - self._action_taken)) self._first_person_view.update() def _quit(self): self._quit_event.set() self._root.quit() sys.exit()
class Scrolling_Area(Frame, object): def __init__(self, master, width=None, anchor=N, height=None, mousewheel_speed = 2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, outer_background=None, inner_frame=Frame, **kw): Frame.__init__(self, master, class_=self.__class__) if outer_background: self.configure(background=outer_background) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._width = width self._height = height self.canvas = Canvas(self, background=outer_background, highlightthickness=0, width=width, height=height) self.canvas.grid(row=0, column=0, sticky=N+E+W+S) if scroll_vertically: if yscrollbar is not None: self.yscrollbar = yscrollbar else: self.yscrollbar = Scrollbar(self, orient=VERTICAL) self.yscrollbar.grid(row=0, column=1,sticky=N+S) self.canvas.configure(yscrollcommand=self.yscrollbar.set) self.yscrollbar['command']=self.canvas.yview else: self.yscrollbar = None if scroll_horizontally: if xscrollbar is not None: self.xscrollbar = xscrollbar else: self.xscrollbar = Scrollbar(self, orient=HORIZONTAL) self.xscrollbar.grid(row=1, column=0, sticky=E+W) self.canvas.configure(xscrollcommand=self.xscrollbar.set) self.xscrollbar['command']=self.canvas.xview else: self.xscrollbar = None self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.innerframe = inner_frame(self.canvas, **kw) self.innerframe.pack(anchor=anchor) self.canvas.create_window(0, 0, window=self.innerframe, anchor='nw', tags="inner_frame") self.canvas.bind('<Configure>', self._on_canvas_configure) Mousewheel_Support(self).add_support_to(self.canvas, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar) @property def width(self): return self.canvas.winfo_width() @width.setter def width(self, width): self.canvas.configure(width= width) @property def height(self): return self.canvas.winfo_height() @height.setter def height(self, height): self.canvas.configure(height = height) def set_size(self, width, height): self.canvas.configure(width=width, height = height) def _on_canvas_configure(self, event): width = max(self.innerframe.winfo_reqwidth(), event.width) height = max(self.innerframe.winfo_reqheight(), event.height) self.canvas.configure(scrollregion="0 0 %s %s" % (width, height)) self.canvas.itemconfigure("inner_frame", width=width, height=height) def update_viewport(self): self.update() window_width = self.innerframe.winfo_reqwidth() window_height = self.innerframe.winfo_reqheight() if self._width is None: canvas_width = window_width else: canvas_width = min(self._width, window_width) if self._height is None: canvas_height = window_height else: canvas_height = min(self._height, window_height) self.canvas.configure(scrollregion="0 0 %s %s" % (window_width, window_height), width=canvas_width, height=canvas_height) self.canvas.itemconfigure("inner_frame", width=window_width, height=window_height)
c.itemconfigure(mouth_sad, state=HIDDEN) return #Defining tickling def cheeky(event): toggle_tongue() toggle_pupils() hide_happy(event) root.after(3000, toggle_tongue) root.after(3000, toggle_pupils) return #Canvas root = Tk() c = Canvas(root, width=400, height=400) c.configure(bg='slateblue', highlightthickness=0) #Body c.body_color = 'mediumpurple1' body = c.create_oval(35, 20, 365, 350, outline=c.body_color, fill=c.body_color) #Ears ear_left = c.create_polygon(75, 80, 75, 10, 165, 70, outline=c.body_color, fill=c.body_color) ear_right = c.create_polygon(255, 45, 325, 10, 320, 70, outline=c.body_color, fill=c.body_color) #Feet foot_left = c.create_oval(65, 320, 145, 360, outline=c.body_color, fill=c.body_color) foot_right = c.create_oval(250, 320, 330, 360, outline=c.body_color, fill=c.body_color) #Eyes and pupils eye_left = c.create_oval(130, 110, 160, 170, outline='black', fill='white') eye_right = c.create_oval(230, 110, 260, 170, outline='black', fill='white')
class Pinball(Domain): """ The goal of this domain is to maneuver a small ball on a plate into a hole. The plate may contain obstacles which should be avoided. **STATE:** The state is given by a 4-dimensional vector, consisting of position and velocity of the ball. **ACTIONS:** There are 5 actions, standing for slanting the plat in x or y direction or a horizontal position of the plate. **REWARD:** Slanting the plate costs -4 reward in addition to -1 reward for each timestep. When the ball reaches the hole, the agent receives 10000 units of reward. **REFERENCE:** .. seealso:: G.D. Konidaris and A.G. Barto: *Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.* Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009. """ #: default location of config files shipped with rlpy default_config_dir = os.path.join( __rlpy_location__, "Domains", "PinballConfigs") def __init__(self, noise=.1, episodeCap=1000, configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg")): """ configuration: location of the configuration file episodeCap: maximum length of an episode noise: with probability noise, a uniformly random action is executed """ self.NOISE = noise self.configuration = configuration self.screen = None self.episodeCap = episodeCap self.actions_num = 5 self.actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE] self.statespace_limits = np.array( [[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]]) self.continuous_dims = [4] super(Pinball, self).__init__() self.environment = PinballModel( self.configuration, random_state=self.random_state) def showDomain(self, a): if self.screen is None: master = Tk() master.title('RLPY Pinball') self.screen = Canvas(master, width=500.0, height=500.0) self.screen.configure(background='LightGray') self.screen.pack() self.environment_view = PinballView( self.screen, 500.0, 500.0, self.environment) self.environment_view.blit() self.screen.pack() self.screen.update() def step(self, a): s = self.state [self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot] = s if self.random_state.random_sample() < self.NOISE: # Random Move a = self.random_state.choice(self.possibleActions()) reward = self.environment.take_action(a) self.environment._check_bounds() state = np.array(self.environment.get_state()) self.state = state.copy() return reward, state, self.isTerminal(), self.possibleActions() def s0(self): self.environment.ball.position[0], self.environment.ball.position[ 1] = self.environment.start_pos self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0 self.state = np.array( [self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot]) return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self, s=0): return np.array(self.actions) def isTerminal(self): return self.environment.episode_ended()
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"))
class Path: def __init__(self, root): self.canvas = Canvas(root, borderwidth=1, background="#ffffff") self.frame = Frame(self.canvas, background="#ffffff") self.vsb = Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4,4), window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.OnFrameConfigure) self.data() def data(self): global textPath textPath = StringVar() global text0a text0a = StringVar() global text0b text0b = StringVar() global text2a text2a = StringVar() global text3 text3 = StringVar() global alphaVar alphaVar = IntVar() global betaVar betaVar = IntVar() global allVar allVar = IntVar() global text6a text6a = "0" global filterVar filterVar = IntVar() global text6b text6b = StringVar() global t1x t1x = "" global t2x t2x = "" global t3x t3x = "" global t4x t4x = "" global text8_0 text8_0 = StringVar() global text8_1 text8_1 = StringVar() Label(self.frame,text="Path ? ").grid(row=0, column=0) Entry(self.frame,textvariable=textPath).grid(row=1, column=0) Button(self.frame, text="Valider et afficher", command = affiche_recap).grid(row=1, column=1) Label(self.frame, text="Green function database information file\n (for a certain depth only for the instance) ?").grid(row=3) Entry(self.frame, textvariable=text0a).grid(row=4) Label(self.frame, text="Output directory (parentdir) ?").grid(row=5) Entry(self.frame, textvariable=text0b).grid(row=6) Label(self.frame, text="Phase name ?").grid(row=9) Entry(self.frame, textvariable=text3).grid(row=10) def afficheAlpha(): seismicPara["text"]="alpha" betaVar.set(0) allVar.set(0) def afficheBeta(): seismicPara["text"]="beta" alphaVar.set(0) allVar.set(0) def afficheAll(): seismicPara["text"]="all" alphaVar.set(0) betaVar.set(0) seismicPara = Menubutton(self.frame, text="Seismic Parameter", relief=RAISED) seismicPara.grid(row=0) seismicPara.menu = Menu(seismicPara, tearoff = 0) seismicPara["menu"] = seismicPara.menu seismicPara.menu.add_checkbutton(label="alpha", variable = alphaVar, command = afficheAlpha) seismicPara.menu.add_checkbutton(label="beta", variable = betaVar, command = afficheBeta) seismicPara.menu.add_checkbutton(label="all", variable = allVar, command = afficheAll) seismicPara.grid(row=11) Label(self.frame, text="Filter name ?").grid(row=12) Entry(self.frame, textvariable=text6b).grid(row=13) Label(self.frame, text="time window t1 ?").grid(row=14) Labelt1 = Label(self.frame, text="-->").grid(row=15) Button(self.frame, text="time 1", command=self.time1).grid(row=15, column=1) Label(self.frame, text="time window t2 ?").grid(row=16) Labelt1 = Label(self.frame, text="-->").grid(row=17) Button(self.frame, text="time 2", command=self.time2).grid(row=17, column=1) ''' Label(self.frame, text="time window t3 ?").grid(row=18) Labelt1 = Label(self.frame, text="-->").grid(row=19) Button(self.frame, text="time 3", command=self.time3).grid(row=19, column=1) Label(self.frame, text="time window t4 ?").grid(row=20) Labelt1 = Label(self.frame, text="-->").grid(row=21) Button(self.frame, text="time 4", command=self.time4).grid(row=21, column=1) ''' def affiche0(): convertPara["text"]="No conversion" text8_1.set(0) def affiche1(): convertPara["text"]="Conversion" text8_0.set(0) convertPara = Menubutton(self.frame, text="Geodetic latitude to geocentric latitude conversion", relief=RAISED) convertPara.grid(row=0) convertPara.menu = Menu(convertPara, tearoff = 0) convertPara["menu"] = convertPara.menu convertPara.menu.add_checkbutton(label="No conversion", variable = text8_0, command = affiche0) convertPara.menu.add_checkbutton(label="Conversion", variable = text8_1, command = affiche1) convertPara.grid(row=22) b = Checkbutton(self.frame, text = "apply filter", variable = filterVar) b.grid(row=23, column = 0) Button(self.frame, text="continue", command=self.quitter).grid(row=23, column=1) def time1(self): global t1x global t1y t1x, t1y = Pointage() print type(t1x) print t1y def time2(self): global t2x global t2y t2x, t2y = Pointage() print t2x print t2y def time3(self): t3x, t3y = Pointage() print t3x print t3y def time4(self): t4x, t4y = Pointage() print t4x print t4y def quitter(self): root.destroy() def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all"))
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"))
class Application(Frame, object): """The application main class.""" WIDTH, HEIGHT = 1280, 720 BG = 'white' FONT = 'Verdana' FILE_OPEN_OPTIONS = { 'mode': 'rb', 'title': 'Choose *.json file', 'defaultextension': '.json', 'filetypes': [('JSON file', '*.json')] } DEFAULTS = 'default_settings.yaml' def __init__(self, master=None): """Creates application main window with sizes self.WIDTH and self.HEIGHT. :param master: instance - Tkinter.Tk instance """ super(Application, self).__init__(master) self.master.title('Engine Game') self.master.geometry('{}x{}'.format(self.WIDTH, self.HEIGHT)) self.master.protocol('WM_DELETE_WINDOW', self.exit) self.source = None self._map = None self.points = None self.lines = None self.captured_point = None self.x0 = None self.y0 = None self.scale_x = None self.scale_y = None self.font_size = None self.coordinates = {} self.captured_lines = {} self.canvas_obj = AttrDict() self.icons = { 0: PhotoImage(file=join('icons', 'player_city.png')), 1: PhotoImage(file=join('icons', 'city.png')), 2: PhotoImage(file=join('icons', 'market.png')), 3: PhotoImage(file=join('icons', 'store.png')), 4: PhotoImage(file=join('icons', 'point.png')), 5: PhotoImage(file=join('icons', 'player_train.png')), 6: PhotoImage(file=join('icons', 'train.png')), 7: PhotoImage(file=join('icons', 'crashed_train.png')), 8: PhotoImage(file=join('icons', 'collision.png')), 9: PhotoImage(file=join('icons', 'play.png')), 10: PhotoImage(file=join('icons', 'play_pressed.png')), 11: PhotoImage(file=join('icons', 'stop.png')), 12: PhotoImage(file=join('icons', 'stop_pressed.png')) } self.queue_requests = { 0: self.set_status_bar, 1: self.set_player_idx, 2: self.build_map, 3: self.refresh_map, 4: self.set_available_games, 99: self.bot_control } self.settings_window = None if exists(expanduser(self.DEFAULTS)): with open(expanduser(self.DEFAULTS), 'r') as cfg: defaults = DefaultsDict.from_yaml(cfg) self.host = None if not defaults.host else str(defaults.host) self.port = None if not defaults.port else int(defaults.port) self.timeout = None if not defaults.timeout else int(defaults.timeout) self.username = None if not defaults.username else str(defaults.username) self.password = None if not defaults.password else str(defaults.password) else: self.host, self.port, self.timeout, self.username, self.password = None, None, None, None, None self.player_idx = None self.posts = {} self.trains = {} self.select_game_window = False self.available_games = None self.game = None self.num_players = None self.num_turns = None self.bot = Bot() self.bot_thread = None self.menu = Menu(self) filemenu = Menu(self.menu) filemenu.add_command(label='Open file', command=self.file_open) filemenu.add_command(label='Server settings', command=self.open_server_settings) filemenu.add_command(label='Select game', command=self.select_game) filemenu.add_command(label='Exit', command=self.exit) self.menu.add_cascade(label='Menu', menu=filemenu) master.config(menu=self.menu) self._status_bar = StringVar() self.label = Label(master, textvariable=self._status_bar) self.label.pack() self.frame = Frame(self) self.frame.bind('<Configure>', self._resize_frame) self.canvas = Canvas(self.frame, bg=self.BG, scrollregion=(0, 0, self.winfo_width(), self.winfo_height())) self.canvas.bind('<Button-1>', self._capture_point) self.canvas.bind('<Motion>', self._move_point) self.canvas.bind('<B1-ButtonRelease>', self._release_point) self.canvas.bind('<Configure>', self._resize_canvas) hbar = Scrollbar(self.frame, orient=HORIZONTAL) hbar.pack(side=BOTTOM, fill=X) hbar.config(command=self.canvas.xview) vbar = Scrollbar(self.frame, orient=VERTICAL) vbar.pack(side=RIGHT, fill=Y) vbar.config(command=self.canvas.yview) self.canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set) self.canvas.pack(fill=BOTH, expand=True) self.play = Label(self.canvas, bg='white') self.play.configure(image=self.icons[9]) self.play.bind('<Button-1>', self._play_press) self.play.bind('<B1-ButtonRelease>', self._play_release) self.stop = Label(self.canvas, bg='white') self.stop.configure(image=self.icons[11]) self.stop.bind('<Button-1>', self._stop_press) self.stop.bind('<B1-ButtonRelease>', self._stop_release) self.frame.pack(fill=BOTH, expand=True) self.weighted = IntVar(value=1) self.weighted_check = Checkbutton(self, text='Proportionally to length', variable=self.weighted, command=self._proportionally) self.weighted_check.pack(side=LEFT) self.show_weight = IntVar() self.show_weight_check = Checkbutton(self, text='Show length', variable=self.show_weight, command=self.show_weights) self.show_weight_check.pack(side=LEFT) self.pack(fill=BOTH, expand=True) self.requests_executor() self.get_available_games() self.set_status_bar('Click Play to start the game') self.play.place(rely=0.5, relx=0.5, anchor=CENTER) @property def map(self): """Returns the actual map.""" return self._map @map.setter def map(self, value): """Clears previously drawn map and assigns a new map to self._map.""" self.clear_map() self.canvas.configure(scrollregion=(0, 0, self.canvas.winfo_width(), self.canvas.winfo_height())) self.x0, self.y0 = self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2 self._map = value @staticmethod def midpoint(x_start, y_start, x_end, y_end): """Calculates a midpoint coordinates between two points. :param x_start: int - x coordinate of the start point :param y_start: int - y coordinate of the start point :param x_end: int - x coordinate of the end point :param y_end: int - y coordinate of the end point :return: 2-tuple of a midpoint coordinates """ return (x_start + x_end) / 2, (y_start + y_end) / 2 def _resize_frame(self, event): """Calculates new font size each time frame size changes. :param event: Tkinter.Event - Tkinter.Event instance for Configure event :return: None """ self.font_size = int(0.0125 * min(event.width, event.height)) def _resize_canvas(self, event): """Redraws map each time Canvas size changes. Scales map each time visible part of Canvas is enlarged. :param event: Tkinter.Event - Tkinter.Event instance for Configure event :return: None """ if self.map: k = min(float(event.width) / float(self.x0 * 2), float(event.height) / float(self.y0 * 2)) self.scale_x, self.scale_y = self.scale_x * k, self.scale_y * k self.x0, self.y0 = self.x0 * k, self.y0 * k self.redraw_map() self.redraw_trains() x_start, y_start, x_end, y_end = self.canvas.bbox('all') x_start = 0 if x_start > 0 else x_start y_start = 0 if y_start > 0 else y_start self.canvas.configure(scrollregion=(x_start, y_start, x_end, y_end)) def _proportionally(self): """Rebuilds map and redraws trains.""" self.build_map() self.redraw_trains() def _capture_point(self, event): """Stores captured point and it's lines. :param event: Tkinter.Event - Tkinter.Event instance for ButtonPress event :return: None """ x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) obj_ids = self.canvas.find_overlapping(x - 5, y - 5, x + 5, y + 5) if not obj_ids: return for obj_id in obj_ids: if obj_id in self.canvas_obj.point.keys(): self.captured_point = obj_id point_idx = self.canvas_obj.point[obj_id]['idx'] self.captured_lines = {} for line_id, attr in self.canvas_obj.line.items(): if attr['start_point'] == point_idx: self.captured_lines[line_id] = 'start_point' if attr['end_point'] == point_idx: self.captured_lines[line_id] = 'end_point' if self.weighted.get(): self.weighted.set(0) def _release_point(self, event): """Writes new coordinates for a moved point and resets self.captured_point and self.captured_lines. :param event: Tkinter.Event - Tkinter.Event instance for ButtonRelease event :return: None """ if self.captured_point: idx = self.canvas_obj.point[self.captured_point]['idx'] x, y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) self.coordinates[idx] = (x, y) self.points[idx]['x'], self.points[idx]['y'] = (x - self.x0) / self.scale_x, (y - self.y0) / self.scale_y self.captured_point = None self.captured_lines = {} def _move_point(self, event): """Moves point and its lines. Moves weights if self.show_weight is set to 1. In case some point is moved beyond Canvas border Canvas scrollregion is resized correspondingly. :param event: Tkinter.Event - Tkinter.Event instance for Motion event :return: None """ if self.captured_point: new_x, new_y = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) self.canvas.coords(self.captured_point, new_x, new_y) indent_y = self.icons[self.canvas_obj.point[self.captured_point]['icon']].height() / 2 + self.font_size if self.canvas_obj.point[self.captured_point]['text_obj']: self.canvas.coords(self.canvas_obj.point[self.captured_point]['text_obj'], new_x, new_y - indent_y) self.coordinates[self.canvas_obj.point[self.captured_point]['idx']] = (new_x, new_y) self.canvas.configure(scrollregion=self.canvas.bbox('all')) for line_id, attr in self.captured_lines.items(): line_attrs = self.canvas_obj.line[line_id] if attr == 'start_point': x, y = self.coordinates[line_attrs['end_point']] self.canvas.coords(line_id, new_x, new_y, x, y) else: x, y = self.coordinates[line_attrs['start_point']] self.canvas.coords(line_id, x, y, new_x, new_y) if self.show_weight.get(): mid_x, mid_y = self.midpoint(new_x, new_y, x, y) self.canvas.coords(line_attrs['weight_obj'][1], mid_x, mid_y) r = self.font_size * len(str(line_attrs['weight'])) self.canvas.coords(line_attrs['weight_obj'][0], mid_x - r, mid_y - r, mid_x + r, mid_y + r) self.redraw_trains() def _play_press(self, _): """Draws play button pressed icon.""" self.play.configure(image=self.icons[10]) def _play_release(self, _): """Draws play button icon and calls bot_control method.""" self.play.configure(image=self.icons[9]) self.bot_control() def _stop_press(self, _): """Draws stop button pressed icon.""" self.stop.configure(image=self.icons[12]) def _stop_release(self, _): """Draws stop buton icon and calls bot_control method.""" self.stop.configure(image=self.icons[11]) self.bot_control() def set_player_idx(self, value): """Sets a player idx value.""" self.player_idx = value def file_open(self): """Opens file dialog and builds and draws a map once a file is chosen. Stops bot if its started.""" path = tkFileDialog.askopenfile(parent=self.master, **self.FILE_OPEN_OPTIONS) if path: if self.bot_thread: self.bot_control() self.posts, self.trains = {}, {} self.source = path.name self.weighted_check.configure(state=NORMAL) self.build_map() def open_server_settings(self): """Opens server settings window.""" ServerSettings(self, title='Server settings') def select_game(self): """Opens select game window.""" self.select_game_window = True SelectGame(self, title='Select game') self.select_game_window = False self.set_status_bar('Click Play to start the game') def exit(self): """Closes application and stops bot if its started.""" if self.bot_thread: self.bot_control() self.master.destroy() def bot_control(self): """Starts bot for playing the game or stops it if it is started.""" if not self.bot_thread: self.bot_thread = Thread(target=self.bot.start, kwargs={ 'host': self.host, 'port': self.port, 'time_out': self.timeout, 'username': self.username, 'password': self.password, 'game': self.game, 'num_players': self.num_players, 'num_turns': self.num_turns}) self.bot_thread.start() else: self.bot.stop() self.bot_thread.join() self.bot_thread = None def get_available_games(self): """Requests a list of available games.""" if self.select_game_window: self.bot.get_available_games(host=self.host, port=self.port, time_out=self.timeout) self.after(1000, self.get_available_games) def set_available_games(self, games): """Sets new value for available games list.""" self.available_games = games def set_status_bar(self, value): """Assigns new status bar value and updates it. :param value: string - status bar string value :return: None """ self._status_bar.set(value) self.label.update() def build_map(self, source=None): """Builds and draws new map. :param source: string - source string; could be JSON string or path to *.json file. :return: None """ if source: self.source = source if self.source: self.map = Graph(self.source, weighted=self.weighted.get()) self.set_status_bar('Map title: {}'.format(self.map.name)) self.points, self.lines = self.map.get_coordinates() self.draw_map() def draw_map(self): """Draws map by prepared coordinates.""" self.draw_lines() self.draw_points() def clear_map(self): """Clears previously drawn map and resets coordinates and scales.""" self.canvas.delete('all') self.scale_x, self.scale_y = None, None self.coordinates = {} def redraw_map(self): """Redraws existing map by existing coordinates.""" if self.map: self.coordinates = {} for obj_id in self.canvas_obj.line: self.canvas.delete(obj_id) self.draw_lines() self.redraw_points() def redraw_points(self): """Redraws map points by existing coordinates.""" if self.map: for obj_id, attrs in self.canvas_obj.point.items(): if attrs['text_obj']: self.canvas.delete(attrs['text_obj']) self.canvas.delete(obj_id) self.draw_points() def redraw_trains(self): """Redraws existing trains.""" if self.trains and hasattr(self.canvas_obj, 'train'): for obj_id, attrs in self.canvas_obj.train.items(): self.canvas.delete(attrs['text_obj']) self.canvas.delete(obj_id) self.draw_trains() @prepare_coordinates def draw_points(self): """Draws map points by prepared coordinates.""" point_objs = {} captured_point_idx = self.canvas_obj.point[self.captured_point]['idx'] if self.captured_point else None for idx in self.points.keys(): x, y = self.coordinates[idx] if self.posts and idx in self.posts.keys(): post_type = self.posts[idx]['type'] if post_type == 1: status = '{}/{} {}/{} {}/{}'.format(self.posts[idx]['population'], self.posts[idx]['population_capacity'], self.posts[idx]['product'], self.posts[idx]['product_capacity'], self.posts[idx]['armor'], self.posts[idx]['armor_capacity']) elif post_type == 2: status = '{}/{}'.format(self.posts[idx]['product'], self.posts[idx]['product_capacity']) else: status = '{}/{}'.format(self.posts[idx]['armor'], self.posts[idx]['armor_capacity']) image_id = 0 if post_type == 1 and self.posts[idx]['player_idx'] == self.player_idx else post_type point_id = self.canvas.create_image(x, y, image=self.icons[image_id]) y -= (self.icons[post_type].height() / 2) + self.font_size text_id = self.canvas.create_text(x, y, text=status, font="{} {}".format(self.FONT, self.font_size)) else: post_type = 4 point_id = self.canvas.create_image(x, y, image=self.icons[post_type]) text_id = None point_objs[point_id] = {'idx': idx, 'text_obj': text_id, 'icon': post_type} self.captured_point = point_id if idx == captured_point_idx else self.captured_point self.canvas_obj['point'] = point_objs @prepare_coordinates def draw_lines(self): """Draws map lines by prepared coordinates and shows their weights if self.show_weight is set to 1.""" line_objs, captured_lines_idx = {}, {} if self.captured_lines: for line_id in self.captured_lines.keys(): captured_lines_idx[self.canvas_obj.line[line_id]['idx']] = line_id for idx, attrs in self.lines.items(): x_start, y_start = self.coordinates[attrs['start_point']] x_stop, y_stop = self.coordinates[attrs['end_point']] line_id = self.canvas.create_line(x_start, y_start, x_stop, y_stop) line_objs[line_id] = {'idx': idx, 'weight': attrs['weight'], 'start_point': attrs['start_point'], 'end_point': attrs['end_point'], 'weight_obj': ()} if idx in captured_lines_idx.keys(): self.captured_lines[line_id] = self.captured_lines.pop(captured_lines_idx[idx]) self.canvas_obj['line'] = line_objs self.show_weights() @prepare_coordinates def draw_trains(self): """Draws trains by prepared coordinates.""" trains = {} for train in self.trains.values(): start_point = self.lines[train['line_idx']]['start_point'] end_point = self.lines[train['line_idx']]['end_point'] weight = self.lines[train['line_idx']]['weight'] position = train['position'] x_start, y_start = self.coordinates[start_point] x_end, y_end = self.coordinates[end_point] delta_x, delta_y = int((x_start - x_end) / weight) * position, int((y_start - y_end) / weight) * position x, y = x_start - delta_x, y_start - delta_y if train['cooldown'] > 0: icon = 7 status = None else: icon = 5 if train['player_idx'] == self.player_idx else 6 status = '{}/{}'.format(train['goods'], train['goods_capacity']) indent_y = self.icons[icon].height() / 2 train_id = self.canvas.create_image(x, y - indent_y, image=self.icons[icon]) text_id = self.canvas.create_text(x, y - (2 * indent_y + self.font_size), text=status, font="{} {}".format(self.FONT, self.font_size)) if status else None trains[train_id] = {'icon': icon, 'text_obj': text_id} self.canvas_obj['train'] = trains def show_weights(self): """Shows line weights when self.show_weight is set to 1 and hides them when it is set to 0.""" if not self.canvas_obj: return if self.show_weight.get(): for line in self.canvas_obj.line.values(): if line['weight_obj']: for obj in line['weight_obj']: self.canvas.itemconfigure(obj, state='normal') else: x_start, y_start = self.coordinates[line['start_point']] x_end, y_end = self.coordinates[line['end_point']] x, y = self.midpoint(x_start, y_start, x_end, y_end) value = line['weight'] size = self.font_size r = int(size) * len(str(value)) oval_id = self.canvas.create_oval(x - r, y - r, x + r, y + r, fill=self.BG, width=0) text_id = self.canvas.create_text(x, y, text=value, font="{} {}".format(self.FONT, str(size))) line['weight_obj'] = (oval_id, text_id) else: for line in self.canvas_obj.line.values(): if line['weight_obj']: for obj in line['weight_obj']: self.canvas.itemconfigure(obj, state='hidden') def requests_executor(self): """Dequeues and executes requests. Assigns corresponding label to bot control button.""" if not self.bot.queue.empty(): request_type, request_body = self.bot.queue.get_nowait() if request_type == 99 and request_body: self.open_server_settings() request_body = None if request_body is not None: self.queue_requests[request_type](request_body) else: self.queue_requests[request_type]() if self.bot_thread and self.bot_thread.is_alive(): if self.play.place_info(): self.play.place_forget() self.stop.place(rely=0.99, relx=0.995, anchor=SE) else: if self.stop.place_info(): self.stop.place_forget() self.play.place(rely=0.5, relx=0.5, anchor=CENTER) self.after(50, self.requests_executor) def refresh_map(self, dynamic_objects): """Refreshes map with passed dynamic objects. :param dynamic_objects: dict - dict of dynamic objects :return: None """ for post in dynamic_objects['posts']: self.posts[post['point_idx']] = post for train in dynamic_objects['trains']: self.trains[train['idx']] = train self.redraw_points() self.redraw_trains()
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="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 do_after_cancel(self, a, b): if a != 0: self.w.after_cancel(a) if b != 0: self.w.after_cancel(b) def calldown(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.down(0) def callup(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.up(0) def callright(self, key): if not self.hor: self.do_after_cancel(self.upid, self.downid) self.right(0) def callleft(self, key): if not self.hor: self.do_after_cancel(self.upid, 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()
class ConsumablePinball(Domain): """ RL NOTES: Pinball Domain has a ballmodel and environment object. Statespace augmentation will be only done in the _DOMAIN_. The goal of this domain is to maneuver a small ball on a plate into a hole. The plate may contain obstacles which should be avoided. **STATE:** The state is given by a 4-dimensional vector, consisting of position and velocity of the ball. **ACTIONS:** There are 5 actions, standing for slanting the plat in x or y direction or a horizontal position of the plate. **REWARD:** Slanting the plate costs -4 reward in addition to -1 reward for each timestep. When the ball reaches the hole, the agent receives 10000 units of reward. **REFERENCE:** .. seealso:: G.D. Konidaris and A.G. Barto: *Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.* Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009. """ #: default location of config files shipped with rlpy default_config_dir = os.path.join( __rlpy_location__, "Domains", "PinballConfigs") # seems to only have one reasonable goalfn def __init__(self, goalArray, noise=.1, episodeCap=1000, configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg"), goalfn=None, rewardFunction=None, encodingFunction=allMarkovEncoding): """ configuration: location of the configuration file episodeCap: maximum length of an episode noise: with probability noise, a uniformly random action is executed """ self.NOISE = noise self.configuration = configuration self.screen = None self.episodeCap = episodeCap self.actions_num = 5 self.actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE] self.statespace_limits = np.array( [[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]]) self.goalArray0 = np.array(goalArray) self.prev_states = [] # TODO fix initial state # statespace augmentation self.encodingFunction = encodingFunction encodingLimits = [] for i in range(0,len(self.encodingFunction(self.prev_states))): encodingLimits.append([0,1]) self.statespace_limits = np.vstack((self.statespace_limits, encodingLimits)) self.state_space_dims = len(self.statespace_limits) self.continuous_dims = np.arange(self.state_space_dims) self.DimNames = ["Dim: "+str(k) for k in range(0,2+len(self.encodingFunction(self.prev_states)))] self.rewardFunction = rewardFunction super(ConsumablePinball, self).__init__() self.environment = PinballModel( self.configuration, goalArray, goalfn=goalfn, random_state=self.random_state) def showDomain(self, a): if self.screen is None: master = Tk() master.title('RLPY Pinball') self.screen = Canvas(master, width=500.0, height=500.0) self.screen.configure(background='LightGray') self.screen.pack() self.environment_view = PinballView( self.screen, 500.0, 500.0, self.environment) self.environment_view.blit() self.screen.pack() self.screen.update() def step(self, a): s = self.state[:4] [self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot] = s if self.random_state.random_sample() < self.NOISE: # Random Move a = self.random_state.choice(self.possibleActions()) reward = self.environment.take_action(a) self.environment._check_bounds() state = np.array(self.environment.get_state()) self.prev_states.append(state[:4]) state = self.augment_state(state) self.state = state terminal = self.isTerminal() if not terminal and self.rewardFunction: sr = self.environment.STEP_PENALTY gr = self.environment.END_EPISODE reward = reward + self.rewardFunction(self.prev_states, self.goalArray(), sr, gr) return reward, state, terminal, self.possibleActions() def s0(self): #TODO reset this initial state; move logic into PinballModel self.environment.ball.position[0], self.environment.ball.position[ 1] = self.environment.start_pos self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0 self.state = np.array( [self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot]) self.prev_states = [] self.state = self.augment_state(self.state) self.environment.goalArray = np.array(self.goalArray0) return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self, s=0): return np.array(self.actions) def isTerminal(self): return self.environment.episode_ended() or len(self.prev_states) == self.episodeCap def augment_state(self, state): return np.concatenate((state, self.encodingFunction(self.prev_states))) def goalArray(self): return self.environment.goalArray
class Scrolling_Area(Frame, object): def __init__(self, master, width=None, anchor=N, height=None, mousewheel_speed = 2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, background=None, inner_frame=Frame, **kw): Frame.__init__(self, master, class_="Scrolling_Area", background=background) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._width = width self._height = height self.canvas = Canvas(self, background=background, highlightthickness=0, width=width, height=height) self.canvas.grid(row=0, column=0, sticky=N+E+W+S) if scroll_vertically: if yscrollbar is not None: self.yscrollbar = yscrollbar else: self.yscrollbar = Scrollbar(self, orient=VERTICAL) self.yscrollbar.grid(row=0, column=1,sticky=N+S) self.canvas.configure(yscrollcommand=self.yscrollbar.set) self.yscrollbar['command']=self.canvas.yview else: self.yscrollbar = None if scroll_horizontally: if xscrollbar is not None: self.xscrollbar = xscrollbar else: self.xscrollbar = Scrollbar(self, orient=HORIZONTAL) self.xscrollbar.grid(row=1, column=0, sticky=E+W) self.canvas.configure(xscrollcommand=self.xscrollbar.set) self.xscrollbar['command']=self.canvas.xview else: self.xscrollbar = None self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.innerframe = inner_frame(self.canvas, **kw) self.innerframe.pack(anchor=anchor) self.canvas.create_window(0, 0, window=self.innerframe, anchor='nw', tags="inner_frame") self.canvas.bind('<Configure>', self._on_canvas_configure) Mousewheel_Support(self).add_support_to(self.canvas, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar) @property def width(self): return self.canvas.winfo_width() @width.setter def width(self, width): self.canvas.configure(width= width) @property def height(self): return self.canvas.winfo_height() @height.setter def height(self, height): self.canvas.configure(height = height) def set_size(self, width, height): self.canvas.configure(width=width, height = height) def _on_canvas_configure(self, event): width = max(self.innerframe.winfo_reqwidth(), event.width) height = max(self.innerframe.winfo_reqheight(), event.height) self.canvas.configure(scrollregion="0 0 %s %s" % (width, height)) self.canvas.itemconfigure("inner_frame", width=width, height=height) def update_viewport(self): self.update() window_width = self.innerframe.winfo_reqwidth() window_height = self.innerframe.winfo_reqheight() if self._width is None: canvas_width = window_width else: canvas_width = min(self._width, window_width) if self._height is None: canvas_height = window_height else: canvas_height = min(self._height, window_height) self.canvas.configure(scrollregion="0 0 %s %s" % (window_width, window_height), width=canvas_width, height=canvas_height) self.canvas.itemconfigure("inner_frame", width=window_width, height=window_height)
# hello.py from sys import * from Tkinter import HIDDEN, NORMAL, Tk, Canvas import turtle import mod.data as me print(version_info) me.hello() a = me.info("JAeHO") a.hello() root = Tk() c = Canvas(root, width=500, height=400) c.configure(bg='dark green', highlightthickness=0) c.pack() painter = turtle.RawTurtle(c) painter.pencolor("blue") for i in range(10): painter.forward(10) painter.left(123) # Let's go counterclockwise this time painter.pencolor("red") for i in range(10): painter.forward(100) painter.left(123) root.mainloop()
def on_show_frame(self): self.canvas_wrappers = [] self.canvases = [] self.page_num = 0 if len(self.controller.sr_results) == 0: self.controller.show_frame(SrNoFramesFoundScreen) else: pages = int(ceil(len(self.controller.sr_results) / 10.0)) for page in range(0, pages): canvas_wrapper = Frame(self.content_wrapper, borderwidth="1", relief="solid") canvas = Canvas(canvas_wrapper, width=int(WINDOW_WIDTH * 7 / 8), height=(WINDOW_HEIGHT * 2 / 3)) scroll_bar = Scrollbar(canvas_wrapper, orient=VERTICAL, command=canvas.yview) results_list_frame = Frame(canvas) canvas.configure(yscrollcommand=scroll_bar.set) canvas.create_window(0, 0, window=results_list_frame) canvas.bind_all("<Up>", self.on_up_key) canvas.bind_all("<Down>", self.on_down_key) canvas.bind_all("<Left>", self.on_left_key) canvas.bind_all("<Right>", self.on_right_key) canvas.grid(row=0, column=0, sticky="nsew") scroll_bar.grid(row=0, column=1, sticky="ns") canvas_wrapper.grid(row=2, column=0, columnspan=3, sticky="nsew") select_buttons_on_page = [] for row in range(0, RESULTS_PER_PAGE): result_num = page * RESULTS_PER_PAGE + row if result_num < len(self.controller.sr_results): frame_num = self.controller.sr_results[result_num][ FRAME_NUM_LABEL] result_entry = Frame(results_list_frame, borderwidth="1", relief="solid") description = PLabel( result_entry, text="Frame #" + str(int(frame_num)) + ", Time: " + str(datetime.timedelta(seconds=frame_num / 30))) preview_wrapper = Frame(result_entry) left_video_preview = Label( preview_wrapper, image=self.controller.sr_results[result_num][LEFT]) right_video_preview = Label( preview_wrapper, image=self.controller.sr_results[result_num] [RIGHT]) select_button = SrSelectButton( preview_wrapper, self.controller, self.controller.sr_results[result_num] [SR_MAP_LABEL], text="Select") select_buttons_on_page.append(select_button) description.pack() left_video_preview.grid(row=row, column=0) right_video_preview.grid(row=row, column=1) select_button.grid(row=row, column=2) preview_wrapper.pack() result_entry.pack() for i in range(0, len(select_buttons_on_page)): select_buttons_on_page[i].configure( command=select_buttons_on_page[i].use_sr_map) self.master.update_idletasks() canvas.config(scrollregion=canvas.bbox("all")) canvas.yview_moveto(0) self.canvas_wrappers.append(canvas_wrapper) self.canvases.append(canvas) self.prev_result_page = Button( self.content_wrapper, text="<", command=lambda: self.prev_page_command()) self.page_info_label = PLabel( self.content_wrapper, text=get_page_info_label_message(self.page_num, len(self.canvases), RESULTS_PER_PAGE)) self.next_result_page = Button( self.content_wrapper, text=">", command=lambda: self.next_page_command()) self.prev_result_page.grid(row=3, column=0) self.page_info_label.grid(row=3, column=1) self.next_result_page.grid(row=3, column=2) self.canvas_wrappers[self.page_num].tkraise()
class tkFileSelector() : def __init__(self,master,start_dir=expanduser("~"),filetypes=[],title="Select a music file.",color_1="#000000",color_2="#00c0c0",highlight_color_items="#c9c9c9") : ''' master == root_window == Tk() use color_1 and color_2 and bg_items and fg_items and highlight_color_items for colors personalisation. filetypes must "Strictly" be a list of extension beginning with an asterix followed by a point and the extension (in lowercase) or an empty list for no filtering. filetypes=["*.mp3","*.wav"] per example. Or insert an, item '*' for all filetype in combination with defined filetypes. for borderwidth and relief settings look at the code ''' # Constrcut GUI for the file selection toplevel. self.toplevel=Toplevel(master,bg=color_1,borderwidth=1,relief="sunken") self.toplevel.resizable(width=False, height=False) self.toplevel.title(title) self.dir_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for directory fields. self.dir_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the current directory relative dirname self.dir_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator self.dir_back_button=Button(self.toplevel,width=6,relief="raised",bg=color_2,fg=color_1,text="Back",command=self.folder_go_back) # Change directory back button. self.canvas_frame=Frame(self.toplevel,borderwidth=8,relief="groove") # Frame for the file selection window canvas and his scrollbar. self.canvas=Canvas(self.canvas_frame,height=20*9,width=18*28,bg=color_2) # File selection window. self.canvas_scrollbar=Scrollbar(self.canvas_frame,orient=HORIZONTAL, bg=color_2,troughcolor=color_1,command=self.canvas.xview) # File selection window scrollbar. self.canvas.configure(xscrollcommand=self.canvas_scrollbar.set) self.file_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for filename fields. self.file_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the basename (relative) of the selected file. self.file_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator. self.file_filter_menubutton = Menubutton(self.file_selection_frame, text='',relief="groove",width=8,bg=color_2,fg=color_1) # Menubutton for filetype filter. self.file_filter_extension="" if filetypes : self.file_filter_menu= Menu(self.file_filter_menubutton,borderwidth=3,relief="groove") # We use a menu for the filetypes filtering. i=0 self.file_filter_var=StringVar(master=None, value=filetypes[i], name=None) # Control varaible for current filetype and initialize with the first filetype item. self.file_filter_menubutton.config(text=filetypes[i]) self.file_filter_extension=filetypes[i][1::] while i < len(filetypes) : # Creating radiobutton to change the filetype filter. self.file_filter_menu.add_radiobutton(label=filetypes[i], variable=self.file_filter_var,value=filetypes[i],background=color_2,command=self.set_filetype_filter ) i += 1 self.file_filter_menubutton.configure(menu= self.file_filter_menu) self.buttons_frame=Frame(self.toplevel,bg=color_2,borderwidth=8,relief="groove",height=50,width=18*3) # Frame container for the buttons. self.button_cancel=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Quit",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_quit) self.button_home=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Home",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_home) self.button_ok=Button(self.buttons_frame,bg=color_2,fg=color_1,text=" OK ",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_ok) self.start_dir=start_dir # Start folder. self.curdir=start_dir # Current folder. self.last_dir=[] # Container for the precedent folders we visit. self.last_dir.append(start_dir) # Append start folder. self.select_filepath="" # Value to return by file selection. self.dir_name_entry.insert(0,"../"+basename(self.curdir)) if not color_2 : self.items_bg="#D9D9D9" else : self.items_bg=color_2 self.items_fg=color_1 self.highlight_color_items=highlight_color_items self.init_icons() self.ls_dir() self.update_canvas() self.dir_selection_frame.grid(row=0,column=0,sticky="WE") self.dir_name_entry.grid(row=0,column=0,in_=self.dir_selection_frame,sticky="NSEW") self.dir_name_separator.grid(row=0,column=1,in_=self.dir_selection_frame,sticky="EW") self.dir_back_button.grid(row=0,column=2,in_=self.dir_selection_frame,sticky="EW") self.canvas_frame.grid(row=1,column=0,sticky="WE") self.canvas.grid(row=0,column=0,in_=self.canvas_frame) self.canvas_scrollbar.grid(row=1,column=0,in_=self.canvas_frame,sticky="WE") self.file_selection_frame.grid(row=2,column=0,sticky="WE") self.file_name_entry.grid(row=0,column=0,in_=self.file_selection_frame,sticky="NSEW") self.file_name_separator.grid(row=0,column=1,in_=self.file_selection_frame,sticky="EW") self.file_filter_menubutton.grid(row=0,column=2,in_=self.file_selection_frame,sticky="NS") self.buttons_frame.grid(row=3,column=0,sticky="NSEW") self.button_cancel.grid(row=0,column=2,padx=32+3,pady=4,in_=self.buttons_frame) self.button_home.grid(row=0,column=4,padx=32+3,pady=4,in_=self.buttons_frame) self.button_ok.grid(row=0,column=6,padx=34+3,pady=4,in_=self.buttons_frame) self.toplevel.wait_window() def init_icons(self) : # Folder and file icons, design by me. self.image_folder=Image.open("/usr/share/ScreenLocker/Images/file_selector/folder_icon.png") self.imagetk_folder=ImageTk.PhotoImage(image=self.image_folder) self.image_file=Image.open("/usr/share/ScreenLocker/Images/file_selector/file_icon.png") self.imagetk_file=ImageTk.PhotoImage(image=self.image_file) def ls_dir(self) : ''' List an directory and split the result in folders and files containers. Finally sort the 2 containers.''' folder_content=listdir(self.curdir) self.cur_folder_entries=len(folder_content) self.cur_folder_list=[] self.cur_files_list=[] folder_content.sort() for v in folder_content : if isdir(self.curdir+"/"+v) : self.cur_folder_list.append(unicode(v,encoding='utf-8')) elif isfile(self.curdir+"/"+v) : self.cur_files_list.append(unicode(v,encoding='utf-8')) self.cur_folder_list.sort() self.cur_files_list.sort() def update_canvas(self) : ''' Generating the content from the File selection window (an canvas)''' self.clear_canvas() i=0 # global folder and file iterator. pos_x=0 # Coordinates for the rows. pos_y=0 # Coordinates in the columns. max_len=0 # Column max folder|filename length. max_len_save=0 # Saved value for filling empty canvas scrollregion. while i < len(self.cur_folder_list) : # Generating the folder items of the current folder exec(u"folder_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_folder,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"))) exec(u"folder_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 bold',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"),int(len(" "+self.cur_folder_list[i])))) if int(len(" "+self.cur_folder_list[i])) > max_len : # Update longest folder name in this column. max_len=int(len(" "+self.cur_folder_list[i])) # Storing the value for max length of the longest folder name in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("folder_icon_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("folder_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("folder_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("folder_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=folder_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=folder_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of foldername in this column ( (9 pixels == font size) (17 pixels for the folder item icon) ) . max_len=0 i += 1 # Go to the next item. ii=0 # Files iterator. while ii < len(self.cur_files_list) : # Generating the files items of the current folder. if (self.file_filter_extension and self.cur_files_list[ii].lower().endswith(self.file_filter_extension)) or not self.file_filter_extension : # applying filter of no filetype filering. exec(u"file_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_file,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"))) exec(u"file_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 normal',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"),int(len(" "+self.cur_files_list[ii])))) if int(len(" "+self.cur_files_list[ii])) > max_len : # Update longest filename in this column. max_len=int(len(" "+self.cur_files_list[ii])) # Storing the value for max length of the longest filename in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("file_icon_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("file_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("file_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("file_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=file_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=file_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. # Note: we check the common file & folder iterator. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of filename in this column ( (9 pixels == font size) (17 pixels for the file item icon) ). max_len=0 i += 1 ii += 1 if not pos_x+(max_len_save*9)+17 < 18*28 : # items collection greater than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,pos_x+(max_len_save*9)+17,0)) else : # items collection littler than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,18*28,0)) def clear_canvas(self) : for child in self.canvas.children.values() : child.destroy() def highlight_item_enter(self,event) : event.widget.config(bg=self.highlight_color_items) def highlight_item_leave(self,event) : event.widget.config(bg=self.items_bg) def select_folder(self,event) : if isdir(self.curdir+"/"+event.widget.cget("text").lstrip()) : # event.widget.cget("text") return the selected folder. sea the update_canvas() method. self.select_filepath="" self.file_name_entry.delete(0,END) if self.curdir.startswith('//') : # Bugfix. self.curdir=self.curdir[1::] self.last_dir.append(self.curdir) else : self.last_dir.append(self.curdir) for v in self.last_dir : # Bigfix if self.last_dir.count(v) > 1 : self.last_dir.remove(v) try : # in case of access right this will fail immediatelly listdir(self.curdir+"/"+event.widget.cget("text")) self.curdir=self.curdir+"/"+event.widget.cget("text") self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+event.widget.cget("text")) self.ls_dir() self.update_canvas() except : pass def select_file(self,event) : if isfile(self.curdir+"/"+event.widget.cget("text")) : # Set the value to return and fill the file selection field. self.select_filepath=self.curdir+"/"+event.widget.cget("text") self.file_name_entry.delete(0,END) self.file_name_entry.insert(0,event.widget.cget("text")) def folder_go_back(self) : if len(self.last_dir) > 1 : self.curdir=self.last_dir.pop(-1) # pop the last value from the visited folder folders else : # In case we have yet only 1 folder in the visited folder container. if self.last_dir[0].rfind("/") : # The value of the container is not the root folder ( / ) but not the /home/username folder who can be only visited folder. self.last_dir[0]=self.last_dir[0][0:self.last_dir[0].rfind("/")] self.curdir=self.last_dir[0] elif self.last_dir[0].rfind("/") == 0 : # The value of the container is the root folder. self.last_dir[0]="/" self.curdir=self.last_dir[0] else : # The value is the /home/username directory self.curdir=self.last_dir[0] self.file_name_entry.delete(0,END) self.select_filepath="" self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas() def set_filetype_filter(self) : '''Change filetype filter.''' self.file_filter_menubutton.config(text=self.file_filter_var.get()) self.file_filter_extension=self.file_filter_var.get()[1::] # Contains the selected filetype ( in form '.'+filetype ). self.file_name_entry.delete(0,END) self.select_filepath="" self.ls_dir() self.update_canvas() def item_selection_ok(self) : '''Return the selected filepath or empty string and destroy File_selector instance''' if self.select_filepath : self.toplevel.destroy() return True def item_selection_quit(self) : '''destroy File_selector instance''' self.toplevel.destroy() return False def item_selection_home(self) : '''Change current directory to the /home/username folder''' self.curdir=expanduser("~") self.select_filepath="" self.file_name_entry.delete(0,END) self.last_dir=[] self.last_dir.append(expanduser("~")) self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas()
class AppAnalysis: def __init__(self, root): self.canvas = Canvas(root, width = 400, height = 350) self.canvas.configure(cursor="crosshair") self.canvas.pack(expand=YES, fill=BOTH, side='right') self.canvas.bind("<Key>", self.handle_key) self.canvas.bind("<Double-Button-1>", self.set_focus) self.canvas.bind("<Button-1>", self.set_cursor) self.canvas.bind("<Return>", self.remove_highlight) self.image, self.ponto1, self.ponto2 = (None, None, None) self.menubar = Menu(root) filemenu = Menu(self.menubar, tearoff=0) filemenu.add_command(label="Open Image", command=self.openImage) filemenu.add_command(label="Save", command=self.hello) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) self.menubar.add_cascade(label="File", menu=filemenu) editmenu = Menu(self.menubar, tearoff=0) for e in ("Cut","Copy","Paste"): editmenu.add_command(label=e, command=self.hello) self.menubar.add_cascade(label="Edit", menu=editmenu) filtermenu = Menu(self.menubar, tearoff=0) filtermenu.add_command(label="Threshold", command=self.thresholdFilter) self.menubar.add_cascade(label="Filter", menu=filtermenu) reportmenu = Menu(self.menubar, tearoff=0) reportmenu.add_command(label="Relatorio.txt", command=self.generateReport) reportmenu.add_command(label="Relatorio.pdf") reportmenu.add_command(label="Email") self.menubar.add_cascade(label="Report", menu=reportmenu) helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label="About", command=self.hello) self.menubar.add_cascade(label="Help", menu=helpmenu) root.config(menu=self.menubar) self.toolbar = Frame(root) self.toolbar.pack(side='left', fill='both') clean = Label(self.toolbar, text='Clean') clean.bind("<Button-1>", self.clean) b = Label(self.toolbar, text='B') c = Label(self.toolbar, text='C') d = Label(self.toolbar, text='D') for w in (clean,b,c,d): w.configure(relief="groove", font="Times 12 bold") w.pack(fill='both') def openImage(self): arquivo = tkFileDialog.askopenfile(parent=self.canvas,mode='rb', title='Imagem') e = ['GIF','JPEG','JPG','BMP','PNG','TIF'] if(e.__contains__(arquivo.name.split(".")[-1].upper())): self.ponto1, self.ponto2 = (None,None) img_tmp = Image.open(arquivo) #self.img_name = path.dirname(path.abspath(arquivo.name)) self.img_name = arquivo.name print self.img_name self.new_img_name = arquivo.name.split('/')[-1] + "_tmp.gif" pathtemp = mydir +"/temp/"+ self.new_img_name img_tmp.save(pathtemp) self.image = PhotoImage(file=pathtemp) self.setImage() self.canvas.bind("<Button-1>", self.click) self.proporcao = "" def clean(self, event): self.ponto1, self.ponto2 = (None,None) self.setImage() self.proporcao = "" def setImage(self): self.canvas.delete(ALL) if self.image.width() > 200 and self.image.height > 200: self.canvas.config(width = self.image.width()) self.canvas.config(height = self.image.height()) self.canvas.create_image(0, 0, image=self.image, anchor=NW) def generateReport(self): report = GeradorRelatorio(self.img_name) report.start() def hello(self): print "hello!" def thresholdFilter(self): img = Image.open(self.img_name) new_img = img.filter(ImageFilter.BLUR) aux = mydir +"/temp/"+ self.new_img_name new_img.save(aux) self.image = PhotoImage(file=aux) self.setImage() def click(self, event): if not self.ponto1: self.canvas.create_oval(event.x, event.y, event.x+5, event.y+5, fill="red") self.ponto1 = (event.x,event.y) else: if not self.ponto2: self.canvas.create_oval(event.x, self.ponto1[1], event.x+5, self.ponto1[1]+5, fill="red") self.ponto2 = (event.x,self.ponto1[1]) pontos = [self.ponto1[0]+1,self.ponto1[1]+2, self.ponto2[0]+1,self.ponto2[1]+2] self.canvas.create_line(pontos, tags="theline", fill='red') x = (self.ponto2[0] + self.ponto1[0]) / 2 self.canvas.create_text(x, self.ponto1[1]+8, text="1 umm") def remove_highlight(self,event): self.canvas.delete("highlight") def highlight(self, item): bbox = self.canvas.bbox(item) self.canvas.delete("highlight") if bbox: i = self.canvas.create_rectangle( bbox, fill="white", tag="highlight" ) self.canvas.lower(i, item) def has_focus(self): return self.canvas.focus() def has_selection(self): return self.canvas.tk.call(self.canvas._w, 'select', 'item') def set_focus(self, event): if self.canvas.type(CURRENT) != "text": return self.highlight(CURRENT) self.canvas.focus_set() self.canvas.focus(CURRENT) self.canvas.select_from(CURRENT, 0) self.canvas.select_to(CURRENT, END) def set_cursor(self, event): item = self.has_focus() if not item: return x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) self.canvas.icursor(item, "@%d,%d" % (x, y)) self.canvas.select_clear() def handle_key(self, event): item = self.has_focus() if not item: return insert = self.canvas.index(item, INSERT) if event.char >= " ": if self.has_selection(): self.canvas.dchars(item, SEL_FIRST, SEL_LAST) self.canvas.select_clear() self.canvas.insert(item, "insert", event.char) self.highlight(item) elif event.keysym == "BackSpace": if self.has_selection(): self.canvas.dchars(item, SEL_FIRST, SEL_LAST) self.canvas.select_clear() else: if insert > 0: self.canvas.dchars(item, insert-1, insert) self.highlight(item) elif event.keysym == "Home": self.canvas.icursor(item, 0) self.canvas.select_clear() elif event.keysym == "End": self.canvas.icursor(item, END) self.canvas.select_clear() elif event.keysym == "Right": self.canvas.icursor(item, insert+1) self.canvas.select_clear() elif event.keysym == "Left": self.canvas.icursor(item, insert-1) self.canvas.select_clear() else: pass
class IntroView(Frame): def __init__(self, controller, parent): # formerly init_intro_nav(): ''' using class objects for all these vars now global intro_nav, background_frame, can, button_load_game\ , button_new_game, button_quit, intro_fill_bottom\ , label_version, title_image_res\ , intro_top_padding, intro_btm_padding ''' self.controller = controller self.parent = parent self.app = self.controller.app # declare vars self.background_frame = 0 self.intro_nav = 0 self.intro_top_padding = 0 def build(self): # prev: build_intro_nav # frame setup conf = self.app.conf self.background_frame = Frame(self.parent, height=self.parent.sh, width=self.parent.sw , background=conf.window_background) self.intro_nav = Frame(self.background_frame, height=500, width=500 , background=conf.intro_background) # elements self.intro_top_padding = Canvas(self.intro_nav) self.intro_top_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) self.title_image_resource = Image.open(conf.title_image_path) self.title_image_res = ImageTk.PhotoImage(self.title_image_resource) self.can = Canvas(self.intro_nav, background=conf.intro_background , highlightbackground=conf.intro_background) self.can.title_image_res = self.title_image_res self.can.config(width=self.title_image_res.width(), height=self.title_image_res.height()) self.button_new_game = Button(self.intro_nav, text="New Game" , command=self.controller.event_button_new_game , bg=conf.intro_background) self.button_new_game.config(highlightbackground=conf.intro_background) self.button_load_game = Button(self.intro_nav, text="Load Game" , command=self.controller.event_button_load_game , bg=conf.intro_background) self.button_load_game.config(highlightbackground=conf.intro_background) self.button_load_game.config(state='disabled') self.button_quit = Button(self.intro_nav, text="Quit" , command=self.controller.event_button_quit , bg=conf.intro_background) self.button_quit.config(highlightbackground=conf.intro_background) self.label_version = Label(self.intro_nav, bg=conf.intro_background, text=conf.version) self.intro_btm_padding = Canvas(self.intro_nav) self.intro_btm_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) def hide(self): # formerly hide_intro_nav self.intro_nav.destroy() self.background_frame.destroy() self.can.destroy() self.button_load_game.destroy() self.button_new_game.destroy() self.button_quit.destroy() self.label_version.destroy() self.title_image_res.__del__() self.intro_top_padding.destroy() self.intro_btm_padding.destroy() def draw(self): # formerly draw_intro_nav() # frame setup self.intro_top_padding.pack() self.background_frame.pack(fill='both') self.intro_nav.pack(fill='both', padx=(self.parent.sw/2)-250, pady=(self.parent.sh/2)-250) self.app.debug(("Drew Intro, padding: (", (self.parent.sw/2)-250, ",", (self.parent.sh/2)-250, ")")) # elements self.can.pack(fill='both', side='top', padx=50, pady=50) self.can.create_image(2, 2, image=self.title_image_res, anchor='nw') self.button_new_game.pack(fill="x", padx=50) self.button_load_game.pack(fill="x", padx=50) self.button_quit.pack(fill="x", padx=50) self.label_version.pack(fill='y', padx=10, pady=10) self.intro_btm_padding.pack() '''
class MtgProxyView(Frame): """The View, which takes care of the visual representation of the model. Attributes: root: the root panel for the visual represantion cardModel: the cardModel class which deals with all the internal card data home: the path of where images are located safeHome: the path where PDfs are supposed to be saved cnfData: the path to the config file defaultImage: the path to the default image listFrame: the frame in which the mode is portraied canvas: tha canvas which allows scrolling and a grid myscrollbar: the scrollbar which gives the user the abilty to scroll through the list of cards buttonframe: the frame in which the action buttons are being placed wipeWorkspace: the button which corresponds with the clear worksapce function bSelectDir: the button which corresponds with the selectDir function selectSaveDir: the button which corresponds with the selectSaveDir function bMake: the button which corresponds with the makePdf function addButton: the button which corresponds with the addNewCard function """ def __init__(self): """ This is the the constructor of the MtgProxyView It takes care of all the setup and doesnt require anything from the main """ #basic setup sizex = 765 sizey = 525 posx = 0 posy = 0 self.root = Tk() self.root.title("PyProxies") self.root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) self.root.resizable(width=False, height=False) #backend data setup self.cardmodel = Cardmodel() #constants self.home = "" self.safeHome = "" self.cnfData = "upm.cnf" self.defaultImage = "noCard.jpg" self.loadConfig() #list setup self.listframe = Frame(self.root, relief=GROOVE, width=500, height=500, bd=1) self.listframe.place(x=10, y=10) self.canvas = Canvas(self.listframe) self.frame = Frame(self.canvas) self.myscrollbar = Scrollbar(self.listframe, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.myscrollbar.set) #and it scrollbar self.myscrollbar.pack(side="right", fill="y") self.canvas.pack(side="left") self.canvas.create_window((0, 0), window=self.frame, anchor='nw') #button setup self.buttonframe = Frame(self.root, relief=GROOVE, width=100, height=500, bd=1, padx=15, pady=10) self.buttonframe.place(x=535, y=10) self.wipeWorkspace = Button(self.buttonframe, text="clear Workspace", command=self.completeWipe, width=20) self.wipeWorkspace.pack(anchor="sw", pady=5) self.bSelectDir = Button(self.buttonframe, text="select a fitting Directory", command=self.selectDir, width=20) self.bSelectDir.pack(anchor="sw", pady=5) self.selectSaveDir = Button(self.buttonframe, text="Select a save directory", command=self.selectSafeDir, width=20) self.selectSaveDir.pack(anchor="sw", pady=5) self.bMake = Button(self.buttonframe, text="make PDF", command=self.makePdf, width=20) self.bMake.pack(anchor="sw", pady=5) self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.frame.bind("<Configure>", self.myfunction) self.data() self.root.mainloop() def loadConfig(self): """ This is the functions which loads the configuration. Only the place where Images can be added as sources and where PDFs can be saved, are able to be set and saved. """ configFile = open(self.cnfData, "r+") temp = configFile.read().split("\n") try: self.home = expanduser("~") if os.path.exists(temp[0]): self.home = temp[0] self.safeHome = expanduser("~") if os.path.exists(temp[1]): self.safeHome = temp[1] except IndexError: print "Error" self.home = expanduser("~") self.safeHome = expanduser("~") print "new homes" print self.home print self.safeHome configFile.close() def saveConfig(self): """ This Function takes care of writing the values of the home and the saveHome to the configuration file """ configFile = open(self.cnfData, "w") configFile.write(self.home + "\n" + self.safeHome) print "config saved" configFile.close() self.loadConfig() def completeWipe(self): """ This function clears the workspace of all of its components and resets the Model. """ for i in range(self.cardmodel.getCardCount()): #self.cardHowOften[i]=0 self.cardmodel.setCardHowOften(i, 0) self.cardmodel.setImg(self.defaultImage, i) #self.imgPaths[i] = self.defaultImage self.cardmodel.resetCardCount() for w in self.frame.winfo_children(): w.destroy() self.data() def selectSafeDir(self): """ This function sets the directory where exported PDFs are being stored. Its does this by invoking the tkFileDialog which asks for user input and returns a valid path. """ path = tkFileDialog.askdirectory( initialdir=self.safeHome, title="Select a better save directory.") if isinstance(path, basestring): self.safeHome = path self.saveConfig() def selectDir(self): """ This function provides the user with the functionality to set their starting directory for adding source images. They can do this in order to save time and optimize their workflow. Its does this by invoking the tkFileDialog which asks for user input and returns a valid path. """ path = tkFileDialog.askdirectory( initialdir=self.home, title="Select a better working directory.") if isinstance(path, basestring): self.home = path self.saveConfig() def data(self): """ The data function takes care of going over the entiry model and representing it on the canvas object. It is only supposed to be invoked when the workspace has been cleard beforehand. """ for i in range(self.cardmodel.getCardCount()): #image label pilFile = Image.open(self.cardmodel.getImg(i)) image1 = pilFile.resize((60, 80), Image.ANTIALIAS) image2 = ImageTk.PhotoImage(image1) imageLabel = Label(self.frame, image=image2) imageLabel.image = image2 imageLabel.grid(row=i, column=0, padx=2, pady=2) #other labels Label(self.frame, text="Card is being printed " + str(self.cardmodel.getCardHowOftenAt(i)) + " times.").grid( row=i, column=1) Button(self.frame, text="-", command=lambda i=i: self.decrHowOften(i)).grid(row=i, column=2) Button(self.frame, text="+", command=lambda i=i: self.incrHowOften(i)).grid(row=i, column=3) Button(self.frame, text="add Source", command=lambda i=i: self.getImgPath(i)).grid(row=i, column=4) Button(self.frame, text="X", command=lambda i=i: self.delete(i)).grid(row=i, column=5) self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.addButton.grid(row=self.cardmodel.getCardCount(), column=0, columnspan=2, padx=10, pady=20, sticky="W") def updateOne(self, i): """ This Function is supposed to only update one row of the Canvas in, which the model is displayed. Args: i: the index of the row which is supposed to be updated """ pilFile = Image.open(self.cardmodel.getImg(i)) image1 = pilFile.resize((60, 80), Image.ANTIALIAS) image2 = ImageTk.PhotoImage(image1) imageLabel = Label(self.frame, image=image2) imageLabel.image = image2 imageLabel.grid(row=i, column=0, padx=2, pady=2) # other labels Label(self.frame, text="Card is being printed " + str(self.cardmodel.getCardHowOftenAt(i)) + " times.").grid( row=i, column=1) Button(self.frame, text="-", command=lambda i=i: self.decrHowOften(i)).grid(row=i, column=2) Button(self.frame, text="+", command=lambda i=i: self.incrHowOften(i)).grid(row=i, column=3) Button(self.frame, text="add Source", command=lambda i=i: self.getImgPath(i)).grid(row=i, column=4) Button(self.frame, text="X", command=lambda i=i: self.delete(i)).grid(row=i, column=5) def delete(self, i): """ This function is supposed to delete one Card and update the model accordingly. Args: i: the indexing of the row, which is supposed to be updated """ self.cardmodel.deleteCard(i) #complete reset for w in self.frame.winfo_children(): w.destroy() self.data() def incrHowOften(self, i): """ This function takes care of increasing the counter of how often a card is supposed to be printed. Args: i: the row in which the the card is located """ self.cardmodel.incrCardHowOften(i) self.updateOne(i) def decrHowOften(self, i): """ This function takes care of decreasing the counter of how often a card is supposed to be printed. Args: i: the row in which the the card is located """ self.cardmodel.decrCardHowOften(i) self.updateOne(i) def addNewCard(self): """ This function adds a new card to the model and updates it with default values. It then invokes the updateOne-function in order to update the view. """ self.cardmodel.addCard() self.addButton.destroy() self.addButton = Button(self.frame, text="add a new Card", command=self.addNewCard) self.addButton.grid(row=self.cardmodel.getCardCount(), column=0, columnspan=2, padx=10, pady=20, sticky="W") self.updateOne(self.cardmodel.getCardCount() - 1) def myfunction(self, event): """ A function which is called in the event of a configuration concerning the frame. It sets the scrollregion of the scrollbar to be the canvas """ self.canvas.configure(scrollregion=self.canvas.bbox("all"), width=500, height=500) def getImgPath(self, i): """ This function allows the user to change the image source of a card. It does this by invoking the tkFileDialog in order to ask for a filename, limited to JPGs and PNGs. If the user input something it updates the model. Args: i: index of the row in which the card is located """ imgPath = tkFileDialog.askopenfilenames(initialdir=self.home, title="Select Image", filetypes=[ ("JPG files", "*.jpg"), ("PNG files", "*.png"), ("JPEG files", "*.jpeg") ]) print imgPath print str(imgPath) == "()" if str(imgPath) != "()" and str(imgPath) != "": print(imgPath[0]) self.cardmodel.setImg(imgPath[0], i) self.updateOne(i) else: print "user didnt select anything" def makePdf(self): """ This function gives the user the functionality to select a filename for the PDF they want to print. Afterwards if a name has been entered the function gives the model to the proxymaker module, which creates a PDF in the desired location. """ name = tkSimpleDialog.askstring( 'Input', 'Enter the desired name for the PDF, without suffix') if name is not None: proxymaker.writeData(self.cardmodel, self.safeHome + "/" + name + ".pdf")
def show_rules(self): self.windowr = Toplevel(self) self.windowr.wm_title("Optimization Rules") self.windowr.rowconfigure(0, weight=1) self.windowr.rowconfigure(1, weight=1) self.windowr.columnconfigure(0, weight=1) innerwindowr = Canvas(self.windowr) innerwindowr.pack() myscrollbar=Scrollbar(self.windowr, orient="vertical", command=innerwindowr.yview) innerwindowr.configure(yscrollcommand=myscrollbar.set) myscrollbar.pack(side="right",fill="y") #self.rtitle_label2 = Label(z, # text="Seating Chart Creator's Optimization Rules", # font=("Optima Italic", 24)) #self.rtitle_label2.pack() rtext1 = \ """ *** Seating Chart Creator's Optimization Rules *** Depending on the input data, it may or may not be possible to create a perfect seating chart. Even if there is a perfect solution, there is no fast or easy way to find it. Seating Chart Creator searches for that perfect solution using an optimization algorithm. It specifies the criteria to evaluate the solution with, then searches for the solution that best meets that criteria. The search process involves random factors, so if you run it multiple times, you will get different answers. *** The Criteria *** SCC looks for a solution with the lowest 'cost'. The cost of a solution is determined by: * The number of people sitting in the same spot multiple times. * The number of pairs sitting together multiple times. * The number of trios sitting together multiple times. * The distance of each table from its optimal category balance. The table sizes always correspond with those in the input file. *** The Process *** Step 1: Building the First Guess SCC loops through the days of the event. On each day, it considers each person individually and places him or her in the best spot available. People are shuffled each round so that no one consistently gets the 'last pick' of the tables. When considering where to seat a person, the following tables are excluded: - Tables that are already full - Tables that already have enough people of the same category as the person to be seated. The person is then assigned to the table with the fewest people he/she has already sat with. Step 2: Switching People Around The strategy above is fairly good, but not perfect. SCC uses it as a starting point, then generates new solutions by repeatedly switching individuals. The 'cost' is calculated for each new solution. If a new solution is better than the current solution, it is used as the starting point for the next round. The technique SCC uses is called 'simulated annealing'. It is a frequently-used and highly-regarded method for solving problems like this one. However, it is not guaranteed to find a perfect solution. The switching steps take a very long time (minutes - hours) because of the computational complexity of counting the number of times everyone sits together. """ #scrollbar = Scrollbar(innerwindowr) #scrollbar.pack(side=RIGHT, fill=Y) #self.foo = Label(innerwindowr, text=rtext1) self.rules_text_box = Text(innerwindowr, width=100) self.rules_text_box.insert(INSERT, rtext1) self.rules_text_box.config(highlightthickness=0) self.rules_text_box.pack(padx=20)
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()
class Pinball(Domain): """ The goal of this domain is to maneuver a small ball on a plate into a hole. The plate may contain obstacles which should be avoided. **STATE:** The state is given by a 4-dimensional vector, consisting of position and velocity of the ball. **ACTIONS:** There are 5 actions, standing for slanting the plat in x or y direction or a horizontal position of the plate. **REWARD:** Slanting the plate costs -4 reward in addition to -1 reward for each timestep. When the ball reaches the hole, the agent receives 10000 units of reward. **REFERENCE:** .. seealso:: G.D. Konidaris and A.G. Barto: *Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.* Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009. """ #: default location of config files shipped with rlpy default_config_dir = os.path.join(__rlpy_location__, "Domains", "PinballConfigs") def __init__(self, noise=.1, episodeCap=1000, configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg")): """ configuration: location of the configuration file episodeCap: maximum length of an episode noise: with probability noise, a uniformly random action is executed """ self.NOISE = noise self.configuration = configuration self.screen = None self.episodeCap = episodeCap self.actions_num = 5 self.actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE ] self.statespace_limits = np.array([[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]]) self.continuous_dims = [4] super(Pinball, self).__init__() self.environment = PinballModel(self.configuration, random_state=self.random_state) def showDomain(self, a): if self.screen is None: master = Tk() master.title('RLPY Pinball') self.screen = Canvas(master, width=500.0, height=500.0) self.screen.configure(background='LightGray') self.screen.pack() self.environment_view = PinballView(self.screen, 500.0, 500.0, self.environment) self.environment_view.blit() self.screen.pack() self.screen.update() def step(self, a): s = self.state [ self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot ] = s if self.random_state.random_sample() < self.NOISE: # Random Move a = self.random_state.choice(self.possibleActions()) reward = self.environment.take_action(a) self.environment._check_bounds() state = np.array(self.environment.get_state()) self.state = state.copy() return reward, state, self.isTerminal(), self.possibleActions() def s0(self): self.environment.ball.position[0], self.environment.ball.position[ 1] = self.environment.start_pos self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0 self.state = np.array([ self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot ]) return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self, s=0): return np.array(self.actions) def isTerminal(self): return self.environment.episode_ended()
class OfxConverter(Frame): def __init__(self, parent): Frame.__init__(self, parent, background=u"white") self.parent = parent self.guiMap = [] self.debitValue = StringVar() self.creditValue = StringVar() self.row = 0 self.frame = Frame() self.UNUSED = u"Unused" self.initUI() def writeLog(self,*msgs): self.log[u'state'] = u'normal' if self.log.index(u'end-1c')!=u'1.0': self.log.insert(u'end', u'\n') for msg in msgs: self.log.insert(u'end', msg) ## self.log['state'] = 'disabled' def help(self): t = Toplevel() t.wm_title(u"About") t.transient() photo = ImageTk.PhotoImage(file=u"chameleon.png") ## photo = PhotoImage(file="chameleon.gif") w = Label(t, image=photo) w.photo = photo w.pack(fill=constants.BOTH,side=constants.LEFT,expand=True) l = Label(t, text=u"OFX Converter\n\n"+ u"Convert files in csv format to the\nofx format " + u"which is used by a lot\nof accounting programs " + u"like gnucash\n\n Written in Python 3\nby Floris Groenendijk" ) l.pack(side=constants.TOP, fill=u"both", expand=False, padx=20, pady=20) def onComboboxChanged(self, event): if event.widget.get() == u'credit/debit': # check which checkbox in which column was changed for i in xrange(len(self.comboBoxes)-1): if self.comboBoxes[i] == event.widget: break values = [] # retrieve the values of the labels in that column for j in xrange(len(self.labels)): if self.labels[j][i][u'text'] not in values: values.append(self.labels[j][i][u'text']) self.creditCombo[u'values'] = values self.creditCombo.current( 0 ) if len( values ) > 1: self.debitCombo[u'values'] = values self.debitCombo.current( 1 ) def onFrameConfigure(self, event): # Reset the scroll region to encompass the inner frame self.canvas.configure(scrollregion=self.canvas.bbox(u"all")) def initUI(self): self.parent.title(u"OFX Converter") menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label=u"Open", command=self.openFile, accelerator=u"Ctrl-o") fileMenu.add_command(label=u"Exit", command=self.onExit, accelerator=u"Ctrl-e", underline=1 ) menubar.add_cascade(label=u"File", menu=fileMenu) helpMenu = Menu(menubar) helpMenu.add_command(label=u"About", command=self.help, accelerator=u"Ctrl-i") menubar.add_cascade(label=u"Info", menu=helpMenu) notebook = ttk.Notebook( self.parent ) tabFilesMain = Frame( notebook ) self.tabFiles = Frame( tabFilesMain ) self.tabFiles.pack(fill=constants.BOTH) button = ttk.Button( tabFilesMain, command=self.parseFile, text=u"Process" ) button.pack(side=u"bottom", fill=constants.X, padx=5, pady=5) tabLogging = Canvas( notebook ) tabLogging.grid_rowconfigure(0, weight=1) tabLogging.grid_columnconfigure(0, weight=1) # begin of custom csv frame tabCustomCsv = Frame( notebook ) verticalScrollFrame = Frame( tabCustomCsv ) verticalScrollFrame.grid( row=0, column=0, rowspan=3, sticky=u"WNS" ) tabCustomCsv.grid_columnconfigure(0, weight=0) tabCustomCsv.grid_columnconfigure(1, weight=1) tabCustomCsv.grid_rowconfigure(2,weight=1) self.comboFrame = Frame( tabCustomCsv ) self.comboFrame.grid( row=1, column=1, sticky=u"WE" ) canvasFrame = Frame( tabCustomCsv) canvasFrame.grid( row=2, column=1, sticky=u"NEWS" ) horizontalScrollFrame = Frame( tabCustomCsv ) horizontalScrollFrame.grid( row=3, column=1, columnspan=1, sticky=u"WE" ) self.canvas = Canvas( canvasFrame, highlightthickness=0 ) scrollbar=Scrollbar( horizontalScrollFrame,orient=u"horizontal",command=self.canvas.xview) self.canvas.configure(xscrollcommand=scrollbar.set) self.canvas.pack(fill=constants.BOTH,expand=True) scrollbar.pack(side=u"bottom", fill=constants.X) scrollbar=Scrollbar( verticalScrollFrame,orient=u"vertical",command=self.canvas.yview) self.canvas.configure(yscrollcommand=scrollbar.set) scrollbar.pack(side=u"left", fill=constants.Y) self.canvas.pack(fill=constants.BOTH,expand=1,anchor=u"nw") # end of custom csv frame # begin of config frame configurationFrame = Frame( tabCustomCsv ) Label( configurationFrame, text=u"Values to determine whether the debit field concerns a debit or credit transaction and set the currency" ).pack(anchor=constants.W) currencyLine = Frame( configurationFrame ) currencyLine.pack(fill=constants.X) Label( currencyLine, text=u"currency", width=7, anchor=constants.W ).pack(side=constants.LEFT) self.currencyCombo = ttk.Combobox( currencyLine,width=30,text=u"currency" ) self.currencyCombo.pack(side=constants.LEFT) config = Config() self.currencies = config.getCurrencies() self.currencyCombo[u'values'] = list(sorted(self.currencies.keys())) Label( configurationFrame, text=u"credit", width=7, anchor=constants.W ).pack(side=constants.LEFT) self.creditCombo = ttk.Combobox(configurationFrame,width=10,text=u"credit") self.creditCombo.pack(side=constants.LEFT) Label( configurationFrame, text=u"debit", width=6, anchor=constants.W ).pack(side=constants.LEFT) self.debitCombo = ttk.Combobox( configurationFrame,width=10,text=u"debit" ) self.debitCombo.pack(side=constants.LEFT) Button( configurationFrame, text=u"save configuration", command=self.saveConfig ).pack(side=constants.RIGHT ) configurationFrame.grid( row=4, column=0, columnspan=2, sticky=u"WES") # end of config frame self.log = Text(tabLogging, wrap=u'word') self.log.grid(row=0,column=0,sticky=u'news') hScroll = Scrollbar(tabLogging, orient=constants.HORIZONTAL, command=self.log.xview) hScroll.grid(row=1, column=0, sticky=u'we') vScroll = Scrollbar(tabLogging, orient=constants.VERTICAL, command=self.log.yview) vScroll.grid(row=0, column=1, sticky=u'ns') self.log.configure(xscrollcommand=hScroll.set, yscrollcommand=vScroll.set) notebook.add( tabFilesMain, text=u"Files to process" ) notebook.add( tabCustomCsv, text=u"Custom csv" ) notebook.add( tabLogging, text=u"Logging" ) notebook.pack(fill=constants.BOTH,expand=1,anchor=constants.N) self.tabFiles.grid_columnconfigure( 0, weight=1 ) def addFile(self,filename,ibans): if filename != u"" and len(ibans) > 0: Label(self.tabFiles, text=filename, borderwidth=3).grid(row=self.row,column=0,sticky=constants.W,padx=1) ibanList = [] for iban in ibans: ibanList.append( iban[:8] ) combo = ttk.Combobox(self.tabFiles,values=ibanList) combo.current(0) if len(ibanList) == 1: combo.configure(state=constants.DISABLED) combo.grid(row=self.row,column=1,sticky=constants.E,padx=1) state = IntVar() c = Checkbutton(self.tabFiles,variable=state) c.grid(row=self.row,column=2) self.row += 1 ttk.Separator(self.tabFiles).grid(row=self.row, sticky=u"ew", columnspan=3 ) self.row += 1 self.guiMap.append( [ filename, ibans, combo, c, state ] ) def addFileToCustomTab(self,filename): if filename != u"": if self.frame: self.frame.pack_forget() self.frame.destroy() self.frame = Frame( self.canvas ) self.canvas.create_window((0,0),window=self.frame,anchor=u'nw') self.frame.bind(u"<Configure>", self.onFrameConfigure) file = csv.reader( open(filename) ) lines = 1 transaction = Transaction() fields = transaction.fields fields.insert(0,u"main account") fields.insert(0,self.UNUSED) self.comboBoxes = [] self.labels = collections.defaultdict(list) for row in file: column = 0 for field in row: if lines == 1: combo = ttk.Combobox(self.frame,values=transaction.fields,state=u"readonly") combo.current(0) combo.grid(row=0,column=column,sticky=constants.W) self.comboBoxes.append( combo ) combo.bind(u'<<ComboboxSelected>>', self.onComboboxChanged) nextColumn = column + 1 ttk.Separator(self.frame,orient=constants.VERTICAL).grid(row=0, column=nextColumn, sticky=u"ns") label = Label(self.frame,text=field,borderwidth=3) label.grid(row=lines,column=column,sticky=constants.W,padx=1) self.labels[lines-1].append( label ) column = column + 1 ttk.Separator(self.frame,orient=constants.VERTICAL).grid(row=lines, column=column, sticky=u"ns") column = column + 1 lines = lines + 1 if lines > 11: break def saveConfig(self): fields = {} memos = [] for i in xrange( len(self.comboBoxes) - 1 ): key = self.comboBoxes[i].get() if key == self.UNUSED: continue elif key == u'credit/debit': fields[ key ] = u' '.join( [ unicode(i), self.creditCombo.get(), self.debitCombo.get() ] ) elif key == u'memo': memos.append( unicode(i) ) elif key == u'main account': fields[ key ] = self.labels[0][i][u'text'] else: fields[ key ] = i if len(memos) > 0: fields[u'memo'] = u' '.join( memos ) config = Config() (bankKey, bankValue) = config.addToConfig( fields ) self.writeLog( u'key', bankKey, u"with value", bankValue, u"added to config file" ) def openFile(self): if sys.version_info >= (3,0): filename = filedialog.askopenfilename(parent=self.parent, filetypes=[(u'Csv files',u'.csv'), (u'All Files',u'.*')], title=u'Select the csv') else: filename = tkFileDialog.askopenfilename(parent=self.parent, filetypes=[(u'Csv files',u'.csv'), (u'All Files',u'.*')], title=u'Select the csv') if filename != u"": self.writeLog( u'File added: ', filename ) bank = Bank() ibans = bank.searchMainIban( filename ) # If mainIban contains more than one iban, # let the user select which one is the main iban # Otherwise we know the bank this csv belongs to if len( ibans ) > 1: self.writeLog( u'there\'s too many ibans, please select one from the list' ) elif len( ibans ) == 0: self.writeLog( u'No ibans found, is the file correct?' ) ## adding file to custom csv tab else: self.writeLog( u'Found iban: ', ibans[0][:8] ) ibanType = ibans[0][:8] self.addFile(filename,ibans) self.addFileToCustomTab( filename ) def parseFile(self): for guiLine in self.guiMap: ( filename, ibans, combo, checkButton, state ) = guiLine if state.get(): ibanType = combo.get() config = Config() fields = config.getCurrentBank( ibanType ) bankStatement = BankStatement() bankStatement.account = ibans[0] csvReader = CsvReader(fields) csvReader.readFile( filename, bankStatement ) ofx = Ofx() ofx.createXmlFile( filename, bankStatement ) checkButton.configure(state=constants.DISABLED) def onExit(self): quit()
class ConsumablePinball(Domain): """ RL NOTES: Pinball Domain has a ballmodel and environment object. Statespace augmentation will be only done in the _DOMAIN_. The goal of this domain is to maneuver a small ball on a plate into a hole. The plate may contain obstacles which should be avoided. **STATE:** The state is given by a 4-dimensional vector, consisting of position and velocity of the ball. **ACTIONS:** There are 5 actions, standing for slanting the plat in x or y direction or a horizontal position of the plate. **REWARD:** Slanting the plate costs -4 reward in addition to -1 reward for each timestep. When the ball reaches the hole, the agent receives 10000 units of reward. **REFERENCE:** .. seealso:: G.D. Konidaris and A.G. Barto: *Skill Discovery in Continuous Reinforcement Learning Domains using Skill Chaining.* Advances in Neural Information Processing Systems 22, pages 1015-1023, December 2009. """ #: default location of config files shipped with rlpy default_config_dir = os.path.join(__rlpy_location__, "Domains", "PinballConfigs") # seems to only have one reasonable goalfn def __init__(self, goalArray, noise=.1, episodeCap=1000, configuration=os.path.join(default_config_dir, "pinball_simple_single.cfg"), goalfn=None, rewardFunction=None, encodingFunction=allMarkovEncoding): """ configuration: location of the configuration file episodeCap: maximum length of an episode noise: with probability noise, a uniformly random action is executed """ self.NOISE = noise self.configuration = configuration self.screen = None self.episodeCap = episodeCap self.actions_num = 5 self.actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE ] self.statespace_limits = np.array([[0.0, 1.0], [0.0, 1.0], [-2.0, 2.0], [-2.0, 2.0]]) self.goalArray0 = np.array(goalArray) self.prev_states = [] # TODO fix initial state # statespace augmentation self.encodingFunction = encodingFunction encodingLimits = [] for i in range(0, len(self.encodingFunction(self.prev_states))): encodingLimits.append([0, 1]) self.statespace_limits = np.vstack( (self.statespace_limits, encodingLimits)) self.state_space_dims = len(self.statespace_limits) self.continuous_dims = np.arange(self.state_space_dims) self.DimNames = [ "Dim: " + str(k) for k in range(0, 2 + len(self.encodingFunction(self.prev_states))) ] self.rewardFunction = rewardFunction super(ConsumablePinball, self).__init__() self.environment = PinballModel(self.configuration, goalArray, goalfn=goalfn, random_state=self.random_state) def showDomain(self, a): if self.screen is None: master = Tk() master.title('RLPY Pinball') self.screen = Canvas(master, width=500.0, height=500.0) self.screen.configure(background='LightGray') self.screen.pack() self.environment_view = PinballView(self.screen, 500.0, 500.0, self.environment) self.environment_view.blit() self.screen.pack() self.screen.update() def step(self, a): s = self.state[:4] [ self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot ] = s if self.random_state.random_sample() < self.NOISE: # Random Move a = self.random_state.choice(self.possibleActions()) reward = self.environment.take_action(a) self.environment._check_bounds() state = np.array(self.environment.get_state()) self.prev_states.append(state[:4]) state = self.augment_state(state) self.state = state terminal = self.isTerminal() if not terminal and self.rewardFunction: sr = self.environment.STEP_PENALTY gr = self.environment.END_EPISODE reward = reward + self.rewardFunction(self.prev_states, self.goalArray(), sr, gr) return reward, state, terminal, self.possibleActions() def s0(self): #TODO reset this initial state; move logic into PinballModel self.environment.ball.position[0], self.environment.ball.position[ 1] = self.environment.start_pos self.environment.ball.xdot, self.environment.ball.ydot = 0.0, 0.0 self.state = np.array([ self.environment.ball.position[0], self.environment.ball.position[1], self.environment.ball.xdot, self.environment.ball.ydot ]) self.prev_states = [] self.state = self.augment_state(self.state) self.environment.goalArray = np.array(self.goalArray0) return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self, s=0): return np.array(self.actions) def isTerminal(self): return self.environment.episode_ended() or len( self.prev_states) == self.episodeCap def augment_state(self, state): return np.concatenate((state, self.encodingFunction(self.prev_states))) def goalArray(self): return self.environment.goalArray
class Viewer(Frame): def __init__(self, master,x=600,y=200, onLeft=None, onRight=None, **kwargs): self.root=master self.xsize=x self.ysize=y self.onLeft=onLeft self.onRight=onRight self.ratio=100. Frame.__init__(self, master,width=x,height=y, **kwargs) self.canvas = Canvas(self, width=x, height=y, background="white") self.xsb = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.ysb = Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set) self.canvas.configure(scrollregion=(0,0,x,y)) self.xsb.grid(row=1, column=0, sticky="ew") self.ysb.grid(row=0, column=1, sticky="ns") self.canvas.grid(row=0, column=0, sticky="nsew") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.canvas.bind("<Button-1>", self.clickL) self.canvas.bind("<Button-3>", self.clickR) # This is what enables using the mouse: self.canvas.bind("<ButtonPress-1>", self.move_start) self.canvas.bind("<B1-Motion>", self.move_move) #linux scroll self.canvas.bind("<Button-4>", self.zoomerP) self.canvas.bind("<Button-5>", self.zoomerM) self.canvas.bind_all("<Prior>", self.zoomerP) self.canvas.bind_all("<Next>", self.zoomerM) self.canvas.bind_all("E", self.zoomExtens) #windows scroll self.canvas.bind_all("<MouseWheel>",self.zoomer) def reset(self): pass def set_title(self, title): self.root.title( title) #move def move_start(self, event): self.canvas.scan_mark(event.x, event.y) return True def move_move(self, event): self.canvas.scan_dragto(event.x, event.y, gain=1) return True #windows zoom def zoomer(self,event): if (event.delta > 0): self.ratio *= 1.1 elif (event.delta < 0): self.ratio *= 0.9 self.redraw() def redraw(self): self.canvas.delete("all") self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomExtens(self, *args): x0,y0,x1,y1 = self.canvas.bbox("all") xlen=x1-x0 ylen=y1-y0 height=self.canvas.winfo_height() width=self.canvas.winfo_width() unfit=min(width/float(xlen), height/float(ylen)) self.ratio*=unfit self.redraw() # """" if xlen and ylen: self ratio*= self.canvas.scale("all", xlen/2., ylen/2., float(self.xsize)/xlen, float(self.ysize)/ylen) self.canvas.configure(scrollregion = self.canvas.bbox("all")) """ #linux zoom def zoomerP(self,event): self.canvas.scale("all", event.x, event.y, 1.1, 1.1) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomerM(self,event): self.canvas.scale("all", event.x, event.y, 0.9, 0.9) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def pose2p(self, pose): x,y=pose[:2] return int(x*self.ratio), -int(y*self.ratio) def line2p(self, line): if type(line[0]) in (float, int): line=zip(line[::2],line[1::2]) return map(self.pose2p, line) def p2m(self, x, y): return x/self.ratio, -y/self.ratio def create_line(self, coords, **kwargs): return self.canvas.create_line(self.line2p(coords), **kwargs) def create_polygon(self, coords, **kwargs): return self.canvas.create_polygon(self.line2p(coords), **kwargs) def delete(self, object): self.canvas.delete(object) def clickL(self, event): if self.onLeft: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onLeft(x,y) return True def clickR(self, event): if self.onRight: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onRight(x,y) return True