class AdvanceOption: def __init__(self,master,position,onClick): self.master=master self.position = position self.photo = PhotoImage(file="Assets/circle.gif") self.UiOption = Button(self.master, image=self.photo, background="white", command=lambda: onClick(position)) self.UiOption.grid(row=position.Row, column=position.Column) def Delete(self): self.UiOption.destroy()
class Solider: def __init__(self, master, color, position, isKing, onClick): self.color = color self.isKing = isKing self.position = position self.master = master self.onClick = onClick self.DrawImage() def DrawImage(self): pathToFile = "Assets/" + self.color + "_solider" if (self.isKing): pathToFile = pathToFile + "_king" pathToFile = pathToFile + ".gif" self.photo = PhotoImage(file=pathToFile) self.soliderButton = Button(self.master, image=self.photo, background="white", command=lambda: self.onClick(self)) self.soliderButton.grid(row=self.position.Row, column=self.position.Column) def UpdatePosition(self, position): self.position = position self.soliderButton.grid(row=position.Row, column=position.Column) def MakeAKing(self): self.isKing = True self.Delete() self.DrawImage() def Delete(self): self.photo.__del__() self.soliderButton.destroy() @property def IsKing(self): return self.isKing @property def Color(self): return self.color @property def Position(self): return self.position
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 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() '''
def create(self, S={}): root = self.root # #BackgroundFile = Image(file='/home/dmitrey/tmp_i/Backgd01.jpg') # bgfile = '/home/dmitrey/tmp_i/Backgd01.gif' # #bgfile = '/home/dmitrey/IP.png' # BackgroundFile = PhotoImage(file=bgfile) # #RootFrame.create_image(0, 0, image=BackgroundFile) RootFrame = Canvas(root) #, image=BackgroundFile) # RootFrame.create_image(0, 0, image=BackgroundFile) # RootFrame.image = BackgroundFile RootFrame.pack() self.NameEntriesList, self.LB_EntriesList, self.UB_EntriesList, self.TolEntriesList, self.ValueEntriesList = [], [], [], [], [] self.calculated_points = S.get('calculated_points', []) # Title #root.wm_title(' FuncDesigner ' + fdversion + ' Manager') C = Canvas(root) """ Buttons """ Frame(RootFrame).pack(ipady=4) #Label(root, text=' FuncDesigner ' + fdversion + ' ').pack() # Upper Frame UpperFrame = Frame(RootFrame) ProjectNameFrame = Frame(UpperFrame) #, relief = 'ridge', bd=2) Label(ProjectNameFrame, text='Project name:').pack(side='left') ProjectNameEntry = Entry(ProjectNameFrame) ProjectNameEntry.pack(side='left') self.ProjectNameEntry = ProjectNameEntry ProjectNameFrame.pack(side='left') GoalSelectFrame = Frame(UpperFrame, relief='ridge', bd=2) GoalSelectText = StringVar(value='Goal:') Label(GoalSelectFrame, textvariable=GoalSelectText).pack(side='left') goal = StringVar() r1 = Radiobutton(GoalSelectFrame, text='Minimum', value='min', variable=goal) r1.pack(side='left') r2 = Radiobutton(GoalSelectFrame, text='Maximum', value='max', variable=goal) r2.pack(side='left') goal.set('min') GoalSelectFrame.pack(side='left', padx=10) self.goal = goal ObjectiveToleranceFrame = Frame(UpperFrame, relief='ridge', bd=2) ObjectiveToleranceFrame.pack(side='left') Label(ObjectiveToleranceFrame, text='Objective function tolerance:').pack(side='left') ObjTolEntry = Entry(ObjectiveToleranceFrame) ObjTolEntry.pack(side='left') self.ObjTolEntry = ObjTolEntry UpperFrame.pack(side='top', expand=True, fill='x') # Variables Frame varsRoot = Frame(RootFrame) # Lower frame LowerFrame = Frame(varsRoot) LowerFrame.pack(side='bottom', expand=True, fill='x') from webbrowser import open_new_tab About = Button(LowerFrame, text='About', command=lambda: open_new_tab( 'http://openopt.org/MultiFactorAnalysis')) About.pack(side='left') SaveButton = Button(LowerFrame, text='Save', command=self.save) SaveButton.pack(side='left', padx=15) SaveAsButton = Button(LowerFrame, text='Save As ...', command=self.save) SaveAsButton.pack(side='left') Write_xls_Button = Button(LowerFrame, text='Write xls report', command=self.write_xls_report) Write_xls_Button.pack(side='left', padx=15) # PlotButton = Button(LowerFrame, text = 'Plot', command = lambda: Plot(C, self.prob)) # PlotButton.pack(side='left') ExperimentNumber = IntVar() ExperimentNumber.set(1) self.ExperimentNumber = ExperimentNumber ObjVal = StringVar() ObjEntry = Entry(LowerFrame, textvariable=ObjVal) self.ObjEntry = ObjEntry NN = StringVar(LowerFrame) NN_Label = Label(LowerFrame, textvariable=NN) names, lbs, ubs, tols, currValues = \ Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot) Label(names, text=' Variable Name ').pack(side='top') Label(lbs, text=' Lower Bound ').pack(side='top') Label(ubs, text=' Upper Bound ').pack(side='top') Label(tols, text=' Tolerance ').pack(side='top') ValsColumnName = StringVar() ValsColumnName.set(' Initial Point ') Label(currValues, textvariable=ValsColumnName).pack(side='top') self.ValsColumnName = ValsColumnName # Commands Frame CommandsRoot = Frame(RootFrame) CommandsRoot.pack(side='right', expand=False, fill='y') AddVar = Button(CommandsRoot, text = 'Add Variable', command = \ lambda: self.addVar(names, lbs, ubs, tols, currValues)) AddVar.pack(side='top', fill='x') Next = Button( CommandsRoot, text='Next', command=lambda: ExperimentNumber.set(ExperimentNumber.get() + 1)) #Next.pack(side='bottom', fill='x') names.pack(side='left', ipady=5) lbs.pack(side='left', ipady=5) ubs.pack(side='left', ipady=5) tols.pack(side='left', ipady=5) currValues.pack(side='left', ipady=5) #currValues.pack_forget() varsRoot.pack() Start = Button(CommandsRoot, text = 'Start', \ command = lambda: (Start.destroy(), \ Next.pack(side='bottom', fill='x'), #C.pack(side = 'bottom', expand=True, fill='both'), r1.config(state=DISABLED), r2.config(state=DISABLED), ObjTolEntry.config(state=DISABLED), ObjEntry.pack(side='right', ipady=4), NN_Label.pack(side='right'), \ self.startOptimization(root, varsRoot, AddVar, currValues, ValsColumnName, ObjEntry, ExperimentNumber, Next, NN, goal.get(), float(ObjTolEntry.get()), C))) Start.pack(side='bottom', fill='x') self.Start = Start if len(S) != 0: for i in range(len(S['names'])): tmp = S['values'][i] if self.x0 is None else self.x0.split( ' ')[i] self.addVar(names, lbs, ubs, tols, currValues, S['names'][i], S['lbs'][i], S['ubs'][i], S['tols'][i], tmp) else: self.addVar(names, lbs, ubs, tols, currValues)
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()
def create(self, S={}): root = self.root # #BackgroundFile = Image(file='/home/dmitrey/tmp_i/Backgd01.jpg') # bgfile = '/home/dmitrey/tmp_i/Backgd01.gif' # #bgfile = '/home/dmitrey/IP.png' # BackgroundFile = PhotoImage(file=bgfile) # #RootFrame.create_image(0, 0, image=BackgroundFile) RootFrame = Canvas(root)#, image=BackgroundFile) # RootFrame.create_image(0, 0, image=BackgroundFile) # RootFrame.image = BackgroundFile RootFrame.pack() self.NameEntriesList, self.LB_EntriesList, self.UB_EntriesList, self.TolEntriesList, self.ValueEntriesList = [], [], [], [], [] self.calculated_points = S.get('calculated_points', []) # Title #root.wm_title(' FuncDesigner ' + fdversion + ' Manager') C = Canvas(root) """ Buttons """ Frame(RootFrame).pack(ipady=4) #Label(root, text=' FuncDesigner ' + fdversion + ' ').pack() # Upper Frame UpperFrame = Frame(RootFrame) ProjectNameFrame = Frame(UpperFrame)#, relief = 'ridge', bd=2) Label(ProjectNameFrame, text = 'Project name:').pack(side = 'left') ProjectNameEntry = Entry(ProjectNameFrame) ProjectNameEntry.pack(side = 'left') self.ProjectNameEntry = ProjectNameEntry ProjectNameFrame.pack(side = 'left') GoalSelectFrame = Frame(UpperFrame, relief = 'ridge', bd=2) GoalSelectText = StringVar(value = 'Goal:') Label(GoalSelectFrame, textvariable = GoalSelectText).pack(side = 'left') goal = StringVar() r1 = Radiobutton(GoalSelectFrame, text = 'Minimum', value = 'min', variable=goal) r1.pack(side = 'left') r2 = Radiobutton(GoalSelectFrame, text = 'Maximum', value = 'max', variable=goal) r2.pack(side = 'left') goal.set('min') GoalSelectFrame.pack(side = 'left', padx = 10) self.goal = goal ObjectiveToleranceFrame = Frame(UpperFrame, relief = 'ridge', bd=2) ObjectiveToleranceFrame.pack(side='left') Label(ObjectiveToleranceFrame, text='Objective function tolerance:').pack(side = 'left') ObjTolEntry = Entry(ObjectiveToleranceFrame) ObjTolEntry.pack(side='left') self.ObjTolEntry = ObjTolEntry UpperFrame.pack(side = 'top', expand=True, fill = 'x') # Variables Frame varsRoot = Frame(RootFrame) # Lower frame LowerFrame = Frame(varsRoot) LowerFrame.pack(side = 'bottom', expand=True, fill = 'x') from webbrowser import open_new_tab About = Button(LowerFrame, text = 'About', command = lambda: open_new_tab('http://openopt.org/MultiFactorAnalysis')) About.pack(side='left') SaveButton = Button(LowerFrame, text = 'Save', command = self.save) SaveButton.pack(side='left', padx = 15) SaveAsButton = Button(LowerFrame, text = 'Save As ...', command = self.save) SaveAsButton.pack(side='left') Write_xls_Button = Button(LowerFrame, text = 'Write xls report', command = self.write_xls_report) Write_xls_Button.pack(side='left', padx = 15) # PlotButton = Button(LowerFrame, text = 'Plot', command = lambda: Plot(C, self.prob)) # PlotButton.pack(side='left') ExperimentNumber = IntVar() ExperimentNumber.set(1) self.ExperimentNumber = ExperimentNumber ObjVal = StringVar() ObjEntry = Entry(LowerFrame, textvariable = ObjVal) self.ObjEntry = ObjEntry NN = StringVar(LowerFrame) NN_Label = Label(LowerFrame, textvariable = NN) names, lbs, ubs, tols, currValues = \ Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot), Frame(varsRoot) Label(names, text=' Variable Name ').pack(side = 'top') Label(lbs, text=' Lower Bound ').pack(side = 'top') Label(ubs, text=' Upper Bound ').pack(side = 'top') Label(tols, text=' Tolerance ').pack(side = 'top') ValsColumnName = StringVar() ValsColumnName.set(' Initial Point ') Label(currValues, textvariable=ValsColumnName).pack(side = 'top') self.ValsColumnName = ValsColumnName # Commands Frame CommandsRoot = Frame(RootFrame) CommandsRoot.pack(side = 'right', expand = False, fill='y') AddVar = Button(CommandsRoot, text = 'Add Variable', command = \ lambda: self.addVar(names, lbs, ubs, tols, currValues)) AddVar.pack(side = 'top', fill='x') Next = Button(CommandsRoot, text = 'Next', command = lambda: ExperimentNumber.set(ExperimentNumber.get()+1)) #Next.pack(side='bottom', fill='x') names.pack(side = 'left', ipady=5) lbs.pack(side = 'left', ipady=5) ubs.pack(side = 'left', ipady=5) tols.pack(side = 'left', ipady=5) currValues.pack(side = 'left', ipady=5) #currValues.pack_forget() varsRoot.pack() Start = Button(CommandsRoot, text = 'Start', \ command = lambda: (Start.destroy(), \ Next.pack(side='bottom', fill='x'), #C.pack(side = 'bottom', expand=True, fill='both'), r1.config(state=DISABLED), r2.config(state=DISABLED), ObjTolEntry.config(state=DISABLED), ObjEntry.pack(side='right', ipady=4), NN_Label.pack(side='right'), \ self.startOptimization(root, varsRoot, AddVar, currValues, ValsColumnName, ObjEntry, ExperimentNumber, Next, NN, goal.get(), float(ObjTolEntry.get()), C))) Start.pack(side = 'bottom', fill='x') self.Start = Start if len(S) != 0: for i in range(len(S['names'])): tmp = S['values'][i] if self.x0 is None else self.x0.split(' ')[i] self.addVar(names, lbs, ubs, tols, currValues, S['names'][i], S['lbs'][i], S['ubs'][i], S['tols'][i], tmp) else: self.addVar(names, lbs, ubs, tols, currValues)
class Interface(Frame) : # We define our window def __init__(self, window, picture, **kwargs) : style = Style() style.map('TCombobox', background=[('readonly',WIDGET_BACKGROUND)]) # Window Background Frame.__init__(self, window, width=800, height=600, **kwargs)#,background=FRAME_BACKGROUND) self.pack(fill = BOTH, expand = YES) """ # Greetings message self.message = Label(self, text = "Welcome in Super Radio Spectre Analyser!",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.message.grid(row=1,column=2,pady=5,sticky=N+E+W) # The grid method places a widget in the window; pady is a margin around the widget """ # Quit Button self.Oquit_button = Button(self, text="Quit", command=quit, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) # command = self.quit defines the callback function self.Oquit_button.grid(row=8,column=5,pady=2,padx=2,sticky=N+E+W) # padx is a margin around the widget and weight is a resizing coefficient # Compute Button self.Ocompute_button = Button(self, text="Compute", command=self.compute, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.Ocompute_button.grid(row=7,column=5,pady=2,padx=2,sticky=N+E+W) # Cancel flag self.cancel = mutex(False) # Spectrogram Image if os.path.exists(picture) : self.imagePath = str(picture) else : self.imagePath = "pictures/default.png" self.image_original = PIL.Image.open(self.imagePath) self.image_copy = self.image_original.copy() self.Oimage = PIL.ImageTk.PhotoImage(self.image_copy) # We use a label to display a picture self.Opic = Label(self,image=self.Oimage) self.Opic.grid(row=3,column=1,columnspan=3, rowspan=3, padx=10,sticky=N+W+S) self.Opic.bind('<Configure>',self.resize) self.resizeable = False # Security to avoid the resize function to get out of control # Carrier Signal Frequency self.frequency = "XXXXHz" self.Lfrequency = Label(self,text="Carrier signal's frequency: "+self.frequency,background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lfrequency.grid(row=6, column=2,pady=5,sticky=N+E+W) # Threshold self.threshold = 3 # In this, self.X is an attribute of the class, saving the current value self.Lthreshold = Label(self,text="Threshold",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) # self.Lx is the label of the corresponding object self.Lthreshold.grid(row=7,column=1,padx=2,sticky=S+E+W) self.Othreshold = Spinbox(self, from_=2, to=6, increment=1, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) # self.Ox is the actual object self.Othreshold.grid(row=8,column=1,padx=2,sticky=N+E+W) # Margin self.margin = 12 self.Lmargin = Label(self,text="Margin",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lmargin.grid(row=7,column=2,padx=2,sticky=S+E+W) # Sticky allows to place a widget off-centered from its original position, according to the cardinal points self.Omargin = Spinbox(self, from_= 5, to = 25, increment = 5, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.Omargin.grid(row=8,column=2,padx=2,sticky=N+E+W) # Box Width self.boxWidth = 6 self.LboxWidth = Label(self,text="Lines' Thickness",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.LboxWidth.grid(row=7,column=3,padx=2,sticky=S+E+W) self.OboxWidth = Spinbox(self, from_=4, to=10, increment = 2, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.OboxWidth.grid(row=8, column=3, padx=2, sticky=W+N+E) # Box Color self.color = [250,250,250] # RGB self.Lcolor = Label(self, text="Lines' Color",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lcolor.grid(row=7, column=4,padx=2,sticky=W+S+E) self.Ocolor = Combobox(self, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.Ocolor.grid(row=8, column=4,padx=2,sticky=N+E+W) self.Ocolor['values'] = ["blue","purple","red","orange","yellow","green","white","black"] # Spectrogram self.currentDir = "spectrograms/" self.file = "" #self.Lfile = Label(self, text = "Select a file",background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) #self.Lfile.grid(row=2,column=4,sticky=N+E+W) #self.Ofile = Combobox(self, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) #self.Ofile.grid(row=3,column=4,sticky=N+E+W) #self.Ofile['values'] = os.listdir("spectrograms/") self.Lfile = Label(self, text = "File selected: "+str(self.file),background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lfile.grid(row=2,column=4,columnspan = 2, sticky=N+E+W) self.Ofile = Button(self, text="Select a file", command=self.selectFile, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.Ofile.grid(row=3, column=5, sticky = N) # Console-like messages self.console = "" self.Oconsole = Label(self,text=self.console, background=WIDGET_BACKGROUND, foreground=WIDGET_FOREGROUND) self.Oconsole.grid(row=4,column=4,sticky=N+E+W+S,columnspan=2,pady=5,padx=5) # Artificial Neuronal Network Choice self.ANN = "CNN" if os.path.exists("pictures/radioCNN.png") : self.ToggleButton = PIL.ImageTk.PhotoImage(PIL.Image.open("pictures/radioCNN.png").resize((56,23),PIL.Image.ANTIALIAS)) # We use a label to display a picture self.OANN = Label(self, background=FRAME_BACKGROUND, image=self.ToggleButton) self.OANN.grid(row=2,column=1,columnspan=1, padx=5, pady=5, sticky=N+W) self.OANN.bind('<Button-1>',self.toggleANN) # Resizing column coefficients self.columnconfigure(1,weight=1,pad=10) self.columnconfigure(2,weight=1,pad=10) self.columnconfigure(3,weight=1,pad=10) self.columnconfigure(4,weight=3,pad=10) self.columnconfigure(5,weight=3,pad=10) # Resizing row coefficients self.rowconfigure(1,weight=1) self.rowconfigure(2,weight=1) self.rowconfigure(3,weight=1) self.rowconfigure(4,weight=1) self.rowconfigure(5,weight=1) self.rowconfigure(6,weight=1) self.rowconfigure(7,weight=1) self.rowconfigure(8,weight=1) return def toggleANN(self, event) : if self.ANN == "CNN" : self.ANN = "SDA" if os.path.exists("pictures/radioSDA.png") : self.ToggleButton = PIL.ImageTk.PhotoImage(PIL.Image.open("pictures/radioSDA.png").resize((56,23),PIL.Image.ANTIALIAS)) # We use a label to display a picture else : self.ANN = "CNN" if os.path.exists("pictures/radioCNN.png") : self.ToggleButton = PIL.ImageTk.PhotoImage(PIL.Image.open("pictures/radioCNN.png").resize((56,23),PIL.Image.ANTIALIAS)) # We use a label to display a picture self.OANN = Label(self, background=FRAME_BACKGROUND, image=self.ToggleButton) self.OANN.grid(row=2,column=1,columnspan=1, padx=10, pady=5, sticky=N+W) self.OANN.bind('<Button-1>',self.toggleANN) self.update() return def selectFile(self) : self.file = askopenfilename(initialdir = self.currentDir, title = "Select file") if int(sys.version[0]) == 2 : fileName = str(self.file.encode("utf-8")) else : fileName = str(self.file) #print(fileName) self.file = fileName if len(fileName) != 0 : fileName = fileName.split("/") tmp = list(fileName) fileName = tmp.pop() self.currentDir = "/".join(tmp) self.Lfile.destroy() self.Lfile = Label(self, text = "File selected: "+str(fileName),background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lfile.grid(row=2, column=4, columnspan=2, sticky=N+E+W) return def resize(self,event) : # This functions dynamically resizes the displayed picture #print(event.width,self.Opic.winfo_width(),self.image_original.size) if self.resizeable : r = self.image_copy.size #print(self.image_original.size) r = r[0]/r[1] height = int(event.height - 4) width = int(floor(height*r) -4) # New widget's dimensions self.image_original = self.image_copy.resize((width, height),PIL.Image.ANTIALIAS) self.Oimage = PIL.ImageTk.PhotoImage(self.image_original) self.Opic.configure(image = self.Oimage) #self.resizeable = False else : self.resizeable = True self.update() return def compute(self) : # This function gets all parameters and launches the computation self.cancel.set(False) self.threshold = int(float(self.Othreshold.get())) self.margin = int(float(self.Omargin.get())) self.boxWidth = int(float(self.OboxWidth.get())) tmp = str(self.Ocolor.get()) if tmp == "blue" : self.color = [15,65,220] elif tmp == "red" : self.color = [180,0,0] elif tmp == "green" : self.color = [35,200,10] elif tmp == "yellow" : self.color = [245,245,20] elif tmp == "orange" : self.color = [250,130,10] elif tmp == "purple" : self.color = [225,10,160] elif tmp == "white" : self.color = [250,250,250] elif tmp == "black" : self.color = [5,5,5] else : self.color = [250,250,250] # Default color is white if len(str(self.file)) != 0 : self.file = str(self.file) ##/////////////////////## ### START OF THE MAIN ### ##\\\\\\\\\\\\\\\\\\\\\## self.switchToCancel() self.setFrequency(str(self.file)) if not self.cancel.get() : self.printOnConsole("Opening "+str(self.file)+"...") if (self.file.endswith(".wav") or self.file.endswith(".wav/")) : self.printOnConsole("Generating spectrogram...") pic = str(spectrogram.main(str(self.file),self.threshold, self.margin)) self.printOnConsole("Done.") self.setImage(str(pic)) self.printOnConsole("Detecting signals...") files = sign_detect2.main(str(pic),self.margin,self.threshold,True) # Detection of signals on the spectrogram else : self.setImage(str(self.file)) self.printOnConsole("Detecting signals...") files = sign_detect2.main(str(self.file),self.margin,self.threshold,True) # Detection of signals on the spectrogram self.printOnConsole("Done.") else : self.printOnConsole("Fatal Error: Aborting Signal detection") self.switchToCompute() signals = list() for elt in files : if (elt[len(elt)-10:] == "signal.bmp" and os.path.exists(elt)) : signals.append(elt) if len(signals) == 0 : self.printOnConsole("Error: No signal detected") self.switchToCompute() else : W = 50 # Dimension of the ANN along the horizontal axis (wide) H = 37 # Dimension of the ANN along the vertical axis (height) #CNN_input = numpy.ndarray() nb = 0 for elt in signals : if not self.cancel.get() : self.printOnConsole("Optimizing signals...") windows = resize.main(elt,W,H) # Resizing of detected signals self.printOnConsole("Done.") # CNN_input is a numpy.ndarray object caonting float32 dtype numbers. # Each row corresponds to an image of which rows have been concatenated in order to form one long vector - in this case of 50x37 columns v,h = windows.shape[0],windows.shape[1] tmp = numpy.ndarray((1,h),dtype="float32") tmp[0,0:h] = windows[0,0:h] for i in range(1,v) : #print(tmp.shape,windows[i,0:h].shape) tmp = numpy.hstack((tmp,windows[i:i+1,0:h])) #v,h = windows.shape[0],windows.shape[1] #tmp = numpy.ndarray((1,h*v),dtype="float32") #tmp = numpy.asarray(windows,dtype="float32") #tmp = tmp.flatten() tmp = tmp/255 if nb == 0 : CNN_input = tmp else : CNN_input = numpy.vstack((CNN_input,tmp)) nb+=1 else : self.printOnConsole("Fatal Error: Aborting Signal optimisation") self.switchToCompute() if not self.cancel.get() : self.printOnConsole("Analysing signals...") #labels = use_CNN.use_CNN(CNN_input) # Classification of detected signals if self.ANN == "CNN" : ANN_to_use = 'scripts/parametres_V3/CNN/params_BdV2.5_mixed_50_37_BW_compatible.pkl' labels = use_CNN.use_CNN(CNN_input, ANN_to_use, [10,15]) # Classification of detected signals elif self.ANN == "SDA" : ANN_to_use = 'scripts/parametres_V3/autoencoder/params_BdV2.5_SDA_mix_50_37_BW_compatible.npy'#params_BdV2.5_SDA_mix_50_37_BW_compatible.pkl' labels = testSdAForPicture.test_SdAForPicture(CNN_input, ANN_to_use) # Classification of detected signals else : print("Unknown ANN type - Fatal Error.\n") return sys.exit() labels2 = list() for elt in labels : if int(elt) == 0 : tmp = "AM" if int(elt) == 1 : tmp = "FM" if int(elt) == 2 : tmp = "FSK" if int(elt) == 3 : tmp = "ASK" if int(elt) == 4 : tmp = "BLU" labels2.append(tmp) self.printOnConsole("Done.") else : self.printOnConsole("Fatal Error: Aborting Signal Classification") self.switchToCompute() if not self.cancel.get() : self.printOnConsole("Merging files...") reass.main(labels2,self.margin,self.boxWidth,self.color,True) # Reassembly of the different parts for a labeled spectrogram self.printOnConsole("Done.") self.setImage("tmp/spectrogram.jpg") self.switchToCompute() else : self.printOnConsole("Fatal Error: Aborting Reassembly") self.switchToCompute() ##///////////////////## ### END OF THE MAIN ### ##\\\\\\\\\\\\\\\\\\\## else : self.printOnConsole("Error: No file selected.") return def setImage(self,picture) : # This function updates the displayed image by replacing the old widget """ self.Oimage = ImageTk.PhotoImage(Image.open(picture).resize((700,500),Image.ANTIALIAS)) self.Opic.destroy() self.Opic = Label(self,image=self.Oimage) self.Opic.grid(row=4,column=1,columnspan=3,padx=10) """ if os.path.exists(picture) : self.imagePath = picture self.image_original = PIL.Image.open(self.imagePath) self.image_copy = self.image_original.copy() self.image_copy = self.image_copy.resize((int(self.Opic.winfo_width()-4), int(self.Opic.winfo_height())-4),PIL.Image.ANTIALIAS) self.Oimage = PIL.ImageTk.PhotoImage(self.image_copy) # We use a label to display a picture self.Opic.destroy() self.resizeable = False # Security to avoid the resize function to get out of control self.Opic = Label(self,image=self.Oimage) self.Opic.grid(row=4,column=1,columnspan=3, padx=10,sticky=N+W+S) self.Opic.bind('<Configure>',self.resize) self.update() else : self.printOnConsole("Fatal Error: Wrong Path.") return def printOnConsole(self,text) : # This function allows to print console-like messages in a label, on the window self.console = self.console.split("\n") l = len(self.console) txt = str() text = str(text) W = int(self.Oconsole.winfo_width()) H = int(self.Oconsole.winfo_height()) if H==1 : H=30 else : H-=4 H = int(floor(H/15)) if W==1 : W=30 else : W-=4 W = int(floor(W/7)) L = len(text) i = 0 while i*W < L : i+=1 txt+=text[(i-1)*W:min(i*W,L)]+"\n" if l > H : # We do not want the label to be too long, otherwise, it will change the dimensions of the whole window self.console = "\n".join(self.console[l-1-30:]) else : self.console = "\n".join(self.console) self.console = self.console + str("<$> "+txt+"\n") self.Oconsole.config(text=str(self.console)) self.update() return def clean(self) : # This cleans the console-like display self.Oconsole.destroy() self.console = "" self.Oconsole = Label(self,text=self.console,background=WIDGET_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Oconsole.grid(row=4,column=4,sticky=N+E+W+S,columnspan=2,pady=5,padx=5) self.printOnConsole("\n"*50) return def switchToCancel(self) : # Switches the compute button to a cancel button self.Ocompute_button.destroy() self.Ocompute_button = Button(self, text="Cancel", command=self.canceling,background=WIDGET_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Ocompute_button.grid(row=7,column=5,pady=2,padx=2,sticky=N+E+W) return def switchToCompute(self) : # Switches the cancel button to a compute button self.Ocompute_button.destroy() self.Ocompute_button = Button(self, text="Compute", command=self.compute,background=WIDGET_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Ocompute_button.grid(row=7,column=5,pady=2,padx=2,sticky=N+E+W) return def canceling(self) : # Cancels the current calculation self.cancel.set(True) return def setFrequency(self,picturePath) : # Updates and displays the carrier signal's frequency f = picturePath.split("/") f = f[len(f)-1] f = f.split("_") if len(f) == 4 : frequency = f[2] else : frequency = "XXXXHz" self.printOnConsole("Error: Unknowm name format.") self.frequency = str(frequency) self.Lfrequency.destroy() self.Lfrequency = Label(self,text="Carrier signal's frequency: "+self.frequency,background=FRAME_BACKGROUND,foreground=WIDGET_FOREGROUND) self.Lfrequency.grid(row=6,column=2,pady=5,sticky=N+E+W) self.update() return
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")
class GUI: def __init__(self): self.app = Tk() self.app.title('TicTacToe') self.app.resizable(width=False, height=False) self.font = Font(family="Helvetica", size=100) self.board = Board("ai") self.buttons = {} self.backBtn = None self.gameOverLabel = None #menu buttons self.mode = "" self.aiBtn = None self.hostBtn = None self.joinBtn = None #networking constructs self.conn = None self.addr = None self.TCP_IP = '127.0.0.1' self.TCP_PORT = 5007 self.BUFFER_SIZE = 128 self.s = None # begin the menu self.menuScreen() def menuScreen(self): w = 50 p = 50 self.mode = 'menu' #buttons here_---------------------------------------------------------- self.aiBtn = Button(self.app, width=w, pady=p, text='Play Against AI!', command=self.playAI) self.hostBtn = Button(self.app, width=w, pady=p, text='Host a game!', command=self.hostGame) self.joinBtn = Button(self.app, width=w, pady=p, text='Join a game!', command=self.joinGame) self.aiBtn.grid(row=0, column=0, sticky="WE") self.hostBtn.grid(row=1, column=0, sticky="WE") self.joinBtn.grid(row=2, column=0, sticky="WE") def playAI(self): self.mode = "ai" self.destroyMenu() self.createGrid() def hostGame(self): self.app.title('HOST') self.mode = "host" self.destroyMenu() waiting = Label(self.app, text="waiting for player 2!") waiting.grid(row=0, column=0, sticky="WE", pady=150, padx=150) ### connection!! self.sh = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sh.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sh.bind((self.TCP_IP, self.TCP_PORT)) self.sh.listen(1) self.conn, self.addr = self.sh.accept() data = self.conn.recv(self.BUFFER_SIZE) print(data) self.conn.send("ur gonna join") #setting up the menu stuff waiting.destroy() self.createGrid() # CLosing connection for now #self.conn.close() def joinGame(self): self.app.title('JOIN') self.mode = "join" self.destroyMenu() waiting = Label(self.app, text="waiting for player 1!") waiting.grid(row=0, column=0, sticky="WE", pady=150, padx=150) ### connection!! self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.connect((self.TCP_IP, self.TCP_PORT)) self.s.send("ur the host!!") data = self.s.recv(self.BUFFER_SIZE) print(data) #setting up the menu stuff waiting.destroy() self.createGrid() #make the player wait!! self.waitForMove() def destroyMenu(self): self.aiBtn.destroy() self.hostBtn.destroy() self.joinBtn.destroy() def createGrid(self): if (self.mode == 'ai'): self.board = Board('ai') elif (self.mode == 'host'): self.board = Board('host') elif (self.mode == 'join'): self.board = Board('join') for col, row in self.board.fields: handler = lambda x=col, y=row: self.move(x, y) button = Button(self.app, command=handler, font=self.font, disabledforeground='black', state='normal', width=4, height=2, pady=0) button.grid(row=row, column=col) self.buttons[col, row] = button self.backBtn = Button(self.app, text='Back to Menu', command=self.backButton) self.backBtn.grid(row=self.board.size, column=1, columnspan=self.board.size / 2, sticky="WE") self.update() def backButton(self): #destroy the current windows based on what mode we are on rn # ie human vs AI mode for col, row in self.board.fields: self.buttons[col, row].destroy() if (self.mode == 'host'): self.conn.close() elif (self.mode == 'join'): self.s.close() if (self.gameOverLabel != None): self.gameOverLabel.destroy() self.backBtn.destroy() self.menuScreen() def waitForMove(self): self.disableButtons() winning = self.board.won() if (winning != None): self.gameOver(winning) return if (self.mode == 'host'): ## make a label to show that it's other turn while (1): #wait for player 2's move print("waiting for joiner") data = self.conn.recv(self.BUFFER_SIZE) print(data) if (len(data) == 3): x = int(data[0]) y = int(data[2]) break elif (self.mode == 'join'): ## make a label to show that it's other turn while (1): #wait for player 1's move print("waiting for host") data = self.s.recv(self.BUFFER_SIZE) print(data) if (len(data) == 3): x = int(data[0]) y = int(data[2]) break self.board = self.board.move(x, y) self.update() def move(self, x, y): # the x and y are coords of button pushed if (self.mode == 'ai'): # player vs AI self.app.config(cursor="watch") self.app.update() self.board = self.board.move(x, y) self.update() # find the AI move via minimax move = self.board.bestMove() print(move) if (move): self.board = self.board.move(*move) self.update() self.app.config(cursor="") elif (self.mode == 'host'): # player 1 self.app.config(cursor="watch") self.app.update() self.board = self.board.move(x, y) self.update() #send move to player 2 self.conn.send(str(x) + ',' + str(y)) self.waitForMove() #self.conn.close() elif (self.mode == 'join'): # player 2 # wait for player 1 move self.app.config(cursor="watch") self.app.update() self.board = self.board.move(x, y) self.update() self.s.send(str(x) + ',' + str(y)) self.waitForMove() #self.s.close() def gameOver(self, winning): try: for x, y in self.buttons: self.buttons[x, y]['state'] = 'disabled' for x, y in winning: self.buttons[x, y]['disabledforeground'] = 'red' for col, row in self.board.fields: self.buttons[col, row].destroy() self.gameOverLabel = Label(self.app, text="GAME OVER!") self.gameOverLabel.grid(row=0, column=0, sticky="WE", pady=250, padx=250) except: self.gameOverLabel = Label(self.app, text="GAME OVER!") self.gameOverLabel.grid(row=0, column=0, sticky="WE", pady=250, padx=250) return def update(self): for (x, y) in self.board.fields: gridVal = self.board.fields[x, y] self.buttons[x, y]['text'] = gridVal if (gridVal != self.board.empty): self.buttons[x, y]['state'] = 'disabled' else: self.buttons[x, y]['state'] = 'normal' for (x, y) in self.board.fields: self.buttons[x, y].update() winning = self.board.won() # the winning coords if (winning != None): self.gameOver(winning) def disableButtons(self): try: for x, y in self.buttons: self.buttons[x, y]['state'] = 'disabled' except: return def mainloop(self): self.app.mainloop()