def initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(10, 10, 80, 80, outline="red", fill="green", width=2) #Here the create_oval() method is used to create a circle item. #The first four parameters are the bounding box coordinates of the circle. #In other words, they are x and y coordinates of the top-left and bottom-right points of the box, #in which the circle is drawn. canvas.create_oval(110, 10, 210, 80, outline="#f11", fill="#1f1", width=2) canvas.create_rectangle(230, 10, 290, 60, outline="#f11", fill="#1f1", width=2) #We create a rectangle item. #The coordinates are again the bounding box of the rectangle to be drawn. canvas.create_arc(30, 200, 90, 100, start=0, extent=210, outline="#f11", fill="#1f1", width=2) #This code line creates an arc. #An arc is a part of the circumference of the circle. #We provide the bounding box. #The start parameter is the start angle of the arc. #The extent is the angle size. points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] canvas.create_polygon(points, outline='red', fill='green', width=2) #A polygon is created. #It is a shape with multiple corners. #To create a polygon in Tkinter, we provide the list of polygon coordinates to the create_polygon() method. canvas.pack(fill=BOTH, expand=1)
def plot_results(self): grid_x = (self.canvas_width - 2 * self.canvas_margin) / (self.grid_size) grid_y = (self.canvas_height - 2 * self.canvas_margin) / (self.grid_size) pin_dx = grid_x / 6 pin_dy = grid_y / 6 master = Tk() w = Canvas(master, width=self.canvas_width, height=self.canvas_height) w.pack() for node in self.graph: i, j = self.id_to_coord(node) if node[-1] == 's': i += 0.5 j += 0.5 nx, ny = self.get_xy(i, j) if node[-1] == 's': fill_col = 'green' w.create_rectangle(nx - pin_dx, ny - pin_dy, nx + pin_dx, ny + pin_dy, fill=fill_col) else: fill_col = 'black' w.create_oval(nx - 2, ny - 2, nx + 2, ny + 2, fill=fill_col) self.draw_routes(w) w.update() w.postscript(file='sol35.ps', colormode='color') mainloop()
def __init__(self): canvas = Canvas(self.root, width=220, height=220) corner1 = self.corner1 corner2 = self.corner2 canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\ fill = "white", width = 3) center = self.centerPoint() def createTickMark(angle, dFromCenter, length, mark): angle -= 90.0 rads = radians(angle) p1 = center.offsetByVector(rads, dFromCenter) p2 = center.offsetByVector(rads, dFromCenter + length) mark(p1, p2) sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y) lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\ fill = 'red', width=3) for angle in range(0, 360, 6): createTickMark(angle, 90, 9, sm_Tick) for angle in range(0, 360, 30): createTickMark(angle, 80, 19, lg_Tick) for angle in range(0, 360, 90): createTickMark(angle, 60, 10, sm_Tick) canvas.pack() self.root.wm_title("Relógio Analógico") self.updateClock(canvas)
def initUI(self): self.parent.title("TNN visualization") self.pack(fill=BOTH, expand=1) canvas = Canvas(self, bg="#000") width, height = 500, 500 canvas.config(width=width, height=height) canvas.create_line(400, 0, 0, 400, width=1, fill="#fff") data = clusterize_data() #for i in range(30): # x, y = randint(1, height), randint(1, height) # canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0") min, max = -3, 3 range_data = max - min step = 500.0/range_data for d in data: x, y = (max - d[0])*step , (max - d[1])*step x, y = 500 - x, 500 - y canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0") canvas.pack(fill=BOTH, expand=1)
def __init__(self): canvas = Canvas(self.root, width=220, height=220) #Get the corners of the circle corner1 = self.corner1 corner2 = self.corner2 canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\ fill = "white", width = 3) center = self.centerPoint() def createTickMark(angle, dFromCenter, length, mark): angle -= 90.0 rads = radians(angle) p1 = center.offsetByVector(rads, dFromCenter) p2 = center.offsetByVector(rads, dFromCenter + length) mark(p1, p2) #mark is meant to be one of the below lambdas sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y) lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\ fill = 'red', width=3) #Create minute tick marks for angle in range(0, 360, 6): createTickMark(angle, 90, 9, sm_Tick) #Create hour tick marks for angle in range(0, 360, 30): createTickMark(angle, 80, 19, lg_Tick) #Create extra marks every 3 hours for angle in range(0, 360, 90): createTickMark(angle, 60, 10, sm_Tick) canvas.pack() self.root.wm_title("Clock") #Prepare the code to be run in the main loop self.updateClock(canvas)
def initUI(self): self.parent.title("TNN visualization") self.pack(fill=BOTH, expand=1) canvas = Canvas(self, bg="#000") width, height = 500, 500 canvas.config(width=width, height=height) canvas.create_line(400, 0, 0, 400, width=1, fill="#fff") data = clusterize_data() #for i in range(30): # x, y = randint(1, height), randint(1, height) # canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0") min, max = -3, 3 range_data = max - min step = 500.0 / range_data for d in data: x, y = (max - d[0]) * step, (max - d[1]) * step x, y = 500 - x, 500 - y canvas.create_oval(x, y, x + 4, y + 4, outline="#0f0", fill="#0f0") canvas.pack(fill=BOTH, expand=1)
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 initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(40, 10, 110, 80, outline="black", width=2) canvas.create_line(75, 80, 75, 180, width=2) canvas.pack(fill=BOTH, expand=1)
def initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(40, 10, 110, 80, outline="black", width=2) canvas.create_line(75, 80, 75, 180, width=2) canvas.pack(fill=BOTH, expand=1)
def init_ui(self, dict_info): """ Initializes the UI using all the information contained in dict_info """ data = dict_info['data'] color = dict_info['color'] depot = dict_info['depot'] mtour = dict_info['tour'] zoomx = dict_info['zoomx'] zoomy = dict_info['zoomy'] list_appointment = data['appointment'] self.parent.title("Simple") self.pack(fill=BOTH, expand=1) depot, mtour = zoom_before_drawing( depot, mtour, zoomx, zoomy) canvas = Canvas(self) idx = 0 for tour in mtour: tour.insert(0, model.Appointment(depot, 0, -1)) draw_tour(tour, canvas, translate_to_tkcolor(color[idx])) idx += 1 canvas.create_oval(depot.get_x(), depot.get_y(), depot.get_x()-5, depot.get_y()-5, outline="black", fill="green", width=7) for appointment in list_appointment: currentx = appointment.get_x() * zoomx currenty = appointment.get_y() * zoomy canvas.create_oval( currentx, currenty, currentx - 3, currenty - 3, outline="red", fill="red", width=5) canvas.pack(fill=BOTH, expand=1)
def start_gui(self): from Tkinter import Tk, Canvas root = Tk() root.title('Compass Heading') canvas = Canvas(root, width=300, height=300) canvas.pack() canvas.create_oval(0, 0, 300, 300, width=2) self.canvas = canvas self.compassLine = canvas.create_line(150, 150, 150, 10) root.mainloop()
def initUI(self): self.parent.title("Colors") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0") canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50") canvas.create_oval(0, 30, 30, 0) canvas.pack(fill=BOTH, expand=1)
def start_gui(self): from Tkinter import Tk, Canvas root = Tk() root.title('Compass Heading') canvas = Canvas(root, width=300, height=300) canvas.pack() canvas.create_oval(0, 0, 300, 300, width=2) self.canvas = canvas self.compassLine = canvas.create_line(150, 150, 150, 10) root.mainloop()
class JoystickFrame(LabelFrame): def __init__(self, master, tracker, text="Joystick", **options): LabelFrame.__init__(self, master, text=text, **options) self.tracker = tracker self.width = 400 self.height = 400 self.canvas = Canvas(self, height=self.height, width=self.width) self.canvas.grid() self.canvas.create_oval((self.width/2 - 3, self.height/2 - 3, self.width/2 + 3, self.height/2 + 3)) self.canvas.bind("<Button-1>", bg_caller(lambda event: self.move_tracker(event))) self.canvas.bind("<Motion>", self.update_label) self.motion_label = Label(self, text="", font=tkFont.Font(family="Courier")) self.motion_label.grid() f = LabelFrame(self, text="Sensitivity") self.sensitivity_scale = Scale(f, from_=0, to=10, resolution=0.01, orient=HORIZONTAL, length=self.width) self.sensitivity_scale.set(5) self.sensitivity_scale.grid() f.grid() @property def sensitivity(self): return self.sensitivity_scale.get() / 2000. def get_delta(self, event): dx = event.x - int(self.canvas['width'])/2. dy = event.y - int(self.canvas['height'])/2. dx_rad = dx*self.sensitivity dy_rad = dy*self.sensitivity dtheta = dy_rad dphi = -dx_rad return (dtheta, dphi) def update_label(self, event): dtheta, dphi = self.get_delta(event) self.motion_label.configure(text="<{:8.5f}, {:8.5f}>".format(dtheta, dphi)) def move_tracker(self, event): dtheta, dphi = self.get_delta(event) self.tracker.move(0, dtheta, dphi) logger.info("Moved tracker by ({}, {})".format(dtheta, dphi))
def initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(10, 10, 80, 80, outline="green", fill="red", width=2) canvas.create_oval(110, 10, 210, 80, outline="green", fill="red", width=2) canvas.create_rectangle(230, 10, 290, 60, outline="green", fill="red", width=2) canvas.create_arc(30, 200, 90, 100, start=0, extent=210, outline="green", fill="red", width=2) points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] canvas.create_polygon(points, outline="green", fill="red", width=2) canvas.pack(fill=BOTH, expand=1)
class MarcaFoto(Frame): def __init__(self, root): Frame.__init__(self, root) self.grid(column=0, row=0) self.canvas = Canvas(self, width=604, height=480) self.canvas.grid(column=0, row=0, columnspan=2) self.coords = Label(self) self.coords.grid(column=0, row=1) nome_arq_foto = 'turma1-640x480.gif' self.foto = PhotoImage(file=nome_arq_foto) self.canvas.create_image(0, 0, image=self.foto, anchor=NW) self.canvas.bind('<Motion>', self.moveu) self.canvas.bind('<ButtonPress>', self.marcar) self.marca_ativa = None def moveu(self, evento): if self.marca_ativa is not None: bbox = self.canvas.coords(self.marca_ativa) bbox[2:4] = [evento.x, evento.y] self.canvas.coords(self.marca_ativa, *bbox) def marcar(self, evento): if self.marca_ativa is None: self.marca_ativa = self.canvas.create_oval(evento.x, evento.y, evento.x, evento.y, outline='green', width=5) else: coords = [int(i) for i in self.canvas.coords(self.marca_ativa)] self.coords['text'] = coords print coords self.marca_ativa = None
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to( event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x-r, y-r, x+r, y+r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
class Move(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.animate() def initUI(self): self.parent.title("Move") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.oval = self.canvas.create_oval(40, 10, 110, 80, outline="black", width=2) self.canvas.pack(fill=BOTH, expand=1) def animate(self): location = self.canvas.coords(self.oval) self.canvas.coords(self.oval, location[0] + 2.5, location[1], location[2] + 2.5, location[3]) self.after(1000, self.animate)
class Clock(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.initTime() self.draw() self.onTimer() def initTime(self): self.hourHand = time.localtime().tm_hour % 12 * 5 self.minuteHand = time.localtime().tm_min self.secondHand = time.localtime().tm_sec def draw(self): self.pack(fill=BOTH, expand=1) radius = 300 x, y = 50, 50 centerX, centerY = 180, 180 hourX = centerX + 0.3 * radius/2.0 * math.cos(self.toRadian(self.hourHand)) hourY = centerY + 0.3 * radius/2.0 * math.sin(self.toRadian(self.hourHand)) minuteX = centerX + 0.6 * radius/2.0 * math.cos(self.toRadian(self.minuteHand)) minuteY = centerY + 0.6 * radius/2.0 * math.sin(self.toRadian(self.minuteHand)) secondX = centerX + 0.75 * radius/2.0 * math.cos(self.toRadian(self.secondHand)) secondY = centerY + 0.75 * radius/2.0 * math.sin(self.toRadian(self.secondHand)) self.canvas.create_oval(x, y, radius, radius, outline="black", fill="black") self.canvas.create_line(centerX, centerY, hourX, hourY, width=3, fill="green") self.canvas.create_line(centerX, centerY, minuteX, minuteY, width=3, fill="green") self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red") self.canvas.pack(fill=BOTH, expand=1) def toRadian(self, x): return (x * math.pi/30.0) - (math.pi/2.0) def onTimer(self): self.tick() self.canvas.delete(ALL) self.draw() self.after(DELAY, self.onTimer) def tick(self): self.secondHand = (self.secondHand + 1) % 60 if self.secondHand == 0: self.minuteHand = (self.minuteHand + 1) % 60 if self.minuteHand == 0: self.hourHand = (self.hourHand + 5) % 60
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to(event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x - r, y - r, x + r, y + r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
class PRMViewer(object): def __init__(self, width=500, height=500, title='PRM', background='tan'): tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() def pixel_from_point(self, point): (x, y) = point # return (int(x*self.width), int(self.height - y*self.height)) return (x * self.width, self.height - y * self.height) def draw_point(self, point, radius=5): (x, y) = self.pixel_from_point(point) self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill='black') def draw_line(self, segment): (point1, point2) = segment (x1, y1) = self.pixel_from_point(point1) (x2, y2) = self.pixel_from_point(point2) self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2) def draw_arrow(self, point1, point2): (x1, y1) = self.pixel_from_point(point1) (x2, y2) = self.pixel_from_point(point2) self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2, arrow=LAST) def draw_rectangle(self, box, width=2, color='brown'): (point1, point2) = box (x1, y1) = self.pixel_from_point(point1) (x2, y2) = self.pixel_from_point(point2) self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, width=width) def draw_circle(self, center, radius, width=2, color='black'): (x1, y1) = self.pixel_from_point(np.array(center) - radius * np.ones(2)) (x2, y2) = self.pixel_from_point(np.array(center) + radius * np.ones(2)) self.canvas.create_oval(x1, y1, x2, y2, outline='black', fill=color, width=width) def clear(self): self.canvas.delete('all')
def init_ui(self, dict_info): """ Initializes the UI using all the information contained in dict_info """ data = dict_info['data'] color = dict_info['color'] depot = dict_info['depot'] mtour = dict_info['tour'] zoom = dict_info['zoom'] list_appointment = data["appointment"] self.parent.title("Simple") self.pack(fill=BOTH, expand=1) depot, mtour = zoom_before_drawing(depot, mtour, zoom) canvas = Canvas(self) canvas.create_oval(depot.get_x(), depot.get_y(), depot.get_x()-5, depot.get_y()-5, outline="black", fill="green", width=3) for appointement in list_appointment: canvas.create_oval( appointement.get_x() * zoom, appointement.get_y() * zoom, appointement.get_x() * zoom - 3, appointement.get_y() * zoom - 3, outline=translate_to_tkcolor(color[appointement.group()]), fill="green", width=2) idx = 0 for tour in mtour: tour.insert(0, model.Appointment(depot, 0, -1)) draw_tour(tour, canvas, translate_to_tkcolor(color[idx])) idx += 1 canvas.pack(fill=BOTH, expand=1)
class DCGreenLanternWidget(Frame): """ Green Lantern logo from DC comics (yeah yeah, i'm shitty artist, i know) """ green = "#07A007" outline = "#FFFFFF" unpowered = '#C0C0C0' def __init__(self, parent, initial_state): Frame.__init__(self, parent) self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, cnf={'background': BACKGROUND_COLOR}) # outer circle kw = {'outline': self.outline, 'fill': self.green} base = 30 * SCALE d = 190 * SCALE s = 10 * SCALE outer_circle = ((base, base, base + d - s, base + d), (base + s, base + s, base + d - s - s, base + d - s)) self.canvas.create_oval(*outer_circle[0], **kw) kw['fill'] = BACKGROUND_COLOR self.canvas.create_oval(*outer_circle[1], **kw) # inner circle kw = {'outline': self.outline, 'fill': self.green} base = 70 * SCALE d = 100 * SCALE s = 14 * SCALE outer_circle = ((base, base + s, base + d, base + d), (base + s, base + s + s, base + d - s, base + d - s)) self.canvas.create_oval(*outer_circle[0], **kw) kw['fill'] = initial_state[1] if initial_state[0] else self.unpowered self.item = self.canvas.create_oval(*outer_circle[1], **kw) # top bar self.canvas.create_rectangle(base, base, base + d, base + s, outline=self.green, fill=self.green) # bottom bar self.canvas.create_rectangle(base, base + d, base + d, base + d + s, outline=self.green, fill=self.green) self.canvas.pack(fill=BOTH, expand=1) def change_color(self, color): self.canvas.itemconfig(self.item, outline=color, fill=color)
class Interface(Frame): def __init__(self, master=Tk()): Frame.__init__(self, master) self.grid() self.llbutton = Button(self, text="Linked List", command=self.createLL) self.llbutton.grid() self.canvas = Canvas(master, bg="white", height=750, width=1000) self.canvas.pack() def createLL(): LL.linked_list() print "Linked List chosen" def drawNode(self, coord, rad, val): self.canvas.create_oval((coord[0], coord[1], coord[0], coord[1]), state="normal", width=rad) self.canvas.create_text((coord[0], coord[1]), text=val) def drawArrow(self, src, dest): if src[0] > dest[0]: x1 = src[0] - 20 x2 = dest[0] + 20 elif src[0] < dest[0]: x1 = src[0] + 20 x2 = dest[0] - 20 if src[1] > dest[1]: y1 = src[1] - 20 y2 = dest[1] + 20 elif src[1] < dest[1]: y1 = src[1] + 20 y2 = dest[1] - 20 self.canvas.create_line(x1, y1, x2, y2, arrowshape="8 10 7", arrow="last") dx = dest[0] - src[0] dy = dest[1] - dest[0] m = dy / dx inv = (dx / dy) * -1
def initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(10, 10, 80, 80, outline="gray", fill="gray", width=2) canvas.create_oval(110, 10, 210, 80, outline="gray", fill="gray", width=2) canvas.create_rectangle(230, 10, 290, 60, outline="gray", fill="gray", width=2) canvas.create_arc(30, 200, 90, 100, start=0, extent=210, outline="gray", fill="gray", width=2) points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] canvas.create_polygon(points, outline='gray', fill='gray', width=2) canvas.pack(fill=BOTH, expand=1)
class TkFrame(Frame): BORDER = 5 LED_SIZE = 20 def __init__(self, parent, controller): Frame.__init__(self, parent) self.CONTROLLER = controller # Setup the layout method self.pack(fill=BOTH, expand=1) # Add a canvas self.canvas = Canvas(self) self.canvas.pack(fill=BOTH, expand=1) # Setup the correct geometry total_width = 2*self.BORDER + self.CONTROLLER.WIDTH*self.LED_SIZE total_height = 2*self.BORDER + self.CONTROLLER.HEIGHT*self.LED_SIZE parent.geometry('{w}x{h}+300+300'.format( w=total_width, h=total_height )) # Add all the LEDs def make_led(x, y): y_top = self.BORDER + y*self.LED_SIZE x_left = self.BORDER + x*self.LED_SIZE return self.canvas.create_oval( x_left, y_top, x_left + self.LED_SIZE, y_top + self.LED_SIZE, outline='white', fill='white', width=1 ) self.LEDS = [ [ make_led(x, y) for y in xrange(self.CONTROLLER.HEIGHT) ] for x in xrange(self.CONTROLLER.WIDTH) ] def update(self): # Update all the LEDs for y in xrange(self.CONTROLLER.HEIGHT): for x in xrange(self.CONTROLLER.WIDTH): colour = self.CONTROLLER.get_rgba_xy(x, y) self.canvas.itemconfig( self.LEDS[x][y], fill=rgba_to_hex(*colour), )
class CoordinatePlot(object): """ Shows the distribution of one coordinate of a list of solutions in the complex plane. """ def __init__(self, wdw, dim, sols, idx): """ The layout is just a square canvas, of dimension dim. The canvas represents the complex plane for the plot of the coordinate defined by index idx of the list sols. """ wdw.title('complex coordinate plot') self.cnv = Canvas(wdw, width=dim, height=dim) self.cnv.pack() self.sols = sols self.idx = idx self.dim = dim self.plot() def plot(self): """ Plots a coordinate of the list of solutions. """ from phcpy.solutions import coordinates dim = self.dim self.cnv.create_line(0, dim / 2, dim, dim / 2) # x coordinate axis self.cnv.create_line(dim / 2, 0, dim / 2, dim) # y coordinate axis (realmin, realmax, imagmin, imagmax) = windowsize(self.sols, self.idx) dimreal = max(abs(realmin), abs(realmax)) dimimag = max(abs(imagmin), abs(imagmax)) factor = dim / 2 - 10 # the origin is at (dim/2, dim/2) for sol in self.sols: (names, values) = coordinates(sol) val = values[self.idx] xpt = dim / 2 + (val.real / dimreal) * factor ypt = dim / 2 + (val.imag / dimimag) * factor self.cnv.create_oval(xpt-3, ypt-3, \ xpt+3, ypt+3, fill='red')
class CoordinatePlot(object): """ Shows the distribution of one coordinate of a list of solutions in the complex plane. """ def __init__(self, wdw, dim, sols, idx): """ The layout is just a square canvas, of dimension dim. The canvas represents the complex plane for the plot of the coordinate defined by index idx of the list sols. """ wdw.title('complex coordinate plot') self.cnv = Canvas(wdw, width=dim, height=dim) self.cnv.pack() self.sols = sols self.idx = idx self.dim = dim self.plot() def plot(self): """ Plots a coordinate of the list of solutions. """ from phcpy.solutions import coordinates dim = self.dim self.cnv.create_line(0, dim/2, dim, dim/2) # x coordinate axis self.cnv.create_line(dim/2, 0, dim/2, dim) # y coordinate axis (realmin, realmax, imagmin, imagmax) = windowsize(self.sols, self.idx) dimreal = max(abs(realmin), abs(realmax)) dimimag = max(abs(imagmin), abs(imagmax)) factor = dim/2 - 10 # the origin is at (dim/2, dim/2) for sol in self.sols: (names, values) = coordinates(sol) val = values[self.idx] xpt = dim/2 + (val.real/dimreal)*factor ypt = dim/2 + (val.imag/dimimag)*factor self.cnv.create_oval(xpt-3, ypt-3, \ xpt+3, ypt+3, fill='red')
class SimWin(Tk,object): WIN_HEIGHT = 600 WIN_WIDTH = 600 WIN_BG = '#fff' def __init__(self, parent=None): super(SimWin, self).__init__(parent) self.canvas = Canvas(master=self, height=SimWin.WIN_HEIGHT, width=SimWin.WIN_WIDTH, background=SimWin.WIN_BG) self.canvas.pack() def changeProps(self, height, width, bg): SimWin.WIN_HEIGHT = height SimWin.WIN_WIDTH = width SimWin.WIN_BG = bg def envDraw(self, redius, C): # C is a 2D numpy array if(not (type(C)==type(np.array([1])))): print 'Input a valid NUMPY array' else: n = 0 for (i,j) in C: self.canvas.create_oval(i-redius[n],j-redius[n],i+redius[n],j+redius[n], fill='#f00', outline='#f00') n = n + 1 def cleanCanvas(self): self.canvas.delete('delete')
class Interface(Frame): def __init__(self,master=Tk()): Frame.__init__(self,master) self.grid() self.llbutton = Button(self,text="Linked List", command = self.createLL) self.llbutton.grid() self.canvas = Canvas(master,bg="white",height=750,width=1000) self.canvas.pack() def createLL(): LL.linked_list() print "Linked List chosen" def drawNode(self,coord,rad,val): self.canvas.create_oval((coord[0],coord[1],coord[0],coord[1]),state="normal",width=rad) self.canvas.create_text((coord[0],coord[1]),text=val) def drawArrow(self,src,dest): if src[0] > dest[0]: x1 = src[0] - 20 x2 = dest[0] + 20 elif src[0] < dest[0]: x1 = src[0] + 20 x2 = dest[0] - 20 if src[1] > dest[1]: y1 = src[1] - 20 y2 = dest[1] + 20 elif src[1] < dest[1]: y1 = src[1] + 20 y2 = dest[1] - 20 self.canvas.create_line(x1,y1,x2,y2,arrowshape="8 10 7", arrow="last") dx = dest[0] - src[0] dy = dest[1] - dest[0] m = dy/dx inv = (dx/dy)*-1
def __init__(self): canvas = Canvas(self.root, width=220, height=220) #Get the corners of the circle corner1 = self.corner1 corner2 = self.corner2 canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\ fill = "white", width = 3) center = self.centerPoint() def createTickMark(angle, dFromCenter, length, mark): angle -= 90.0 rads = radians(angle) p1 = center.offsetByVector(rads, dFromCenter) p2 = center.offsetByVector(rads, dFromCenter + length) mark(p1, p2) #mark is meant to be one of the below lambdas sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y) lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\ fill = 'red', width=3) #Create minute tick marks for angle in range(0, 360, 6): createTickMark(angle, 90, 9, sm_Tick) #Create hour tick marks for angle in range(0, 360, 30): createTickMark(angle, 80, 19, lg_Tick) #Create extra marks every 3 hours for angle in range(0, 360, 90): createTickMark(angle, 60, 10, sm_Tick) canvas.pack() self.root.wm_title("Clock") #Prepare the code to be run in the main loop self.updateClock(canvas)
def draw( self, tree,row=0,col=0): self.findCoords(tree) self.grid(row=row,column=col,sticky=N+S+E+W) xOff, yOff = 50 - self.minX, 50 - self.minY self.minX += xOff self.maxX += xOff self.minY += yOff self.maxY += yOff canvas = Canvas(self) for line in self.linesToDraw: ((sX,sY),(eX,eY)) = line canvas.create_line(sX+xOff,sY+yOff,eX+xOff,eY+yOff) for circle in self.circlesToDraw: x,y,c = circle canvas.create_oval(x+xOff-5,y+yOff-5,x+xOff+5,y+yOff+5,fill=c) canvas.grid(row=row,column=col,sticky=N+S+E+W)
class Lamp(object): def __init__(self, queue): self.root = Tk() self.root.wm_title("lamp") self.circle = Canvas(self.root, width=100, height=100, bg='gray') self.circle.grid(padx=10, pady=10) self.queue = queue self.turnoff = True self.color = DEFAULT_COLOR self.circle.create_oval(20, 20, 80, 80, fill = self.color) def mainloop(self): self.root.mainloop() def action(self): xtype, xlen, xcolor = self.queue.get(block = True) if xcolor is not None: self.color = xcolor try: getattr(self, '_' + TYPE_MAP[xtype])() except Exception, e: error('action error %s' % e) finally:
class MemoCaras(Frame): def __init__(self, root): Frame.__init__(self, root) self.grid(column=0, row=0) self.canvas = Canvas(self, width=604, height=480) self.canvas.grid(column=0, row=0, columnspan=2) self.bt_prox = Button(self, text='Próximo', command=self.proximo) self.bt_prox.grid(column=0, row=1, sticky=W) self.nome = Label(self, text='(passe aqui para ver o nome)') self.nome.bind('<Enter>', self.mostra_nome) self.nome.bind('<Leave>', self.esconde_nome) self.nome.grid(column=1, row=1, sticky=EW) self.foto = PhotoImage(file=NOME_ARQ_FOTO) self.canvas.create_image(0, 0, image=self.foto, anchor=NW) self.caras = {} for nome, bbox in pessoas: marca = self.canvas.create_oval(*bbox, outline='green', width=5, state=HIDDEN) self.caras[nome] = marca self.sequencia = [] self.cara_ativa = None def proximo(self): if self.cara_ativa is not None: marca = self.caras[self.cara_ativa] self.canvas.itemconfigure(marca, state=HIDDEN) if len(self.sequencia) == 0: self.sequencia = self.caras.keys() shuffle(self.sequencia) self.cara_ativa = self.sequencia.pop() marca = self.caras[self.cara_ativa] self.canvas.itemconfigure(marca, state=NORMAL) def mostra_nome(self, evento): self.texto_nome = self.nome['text'] self.nome['text'] = self.cara_ativa def esconde_nome(self, evento): self.nome['text'] = self.texto_nome
class Move(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.animate() def initUI(self): self.parent.title("Move") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.oval = self.canvas.create_oval(40, 10, 110, 80, outline="black", width=2) self.canvas.pack(fill=BOTH, expand=1) def animate(self): location = self.canvas.coords(self.oval) self.canvas.coords(self.oval, location[0]+2.5, location[1], location[2]+2.5, location[3]) self.after(1000, self.animate)
class Application(Frame): def __init__(self, parent, game): Frame.__init__(self, parent, background="green") self.parent = parent self.game = game self.initUI() self.canvas = Canvas(self) self.draw() def initUI(self): self.parent.title("Football") self.pack(fill=BOTH, expand=1) def draw(self): self.game.next_round() LAYOUT = self.game.get_layout() self.canvas.delete("all") self.canvas.create_text(300, 20, anchor=W, font="Purisa", text="RESULT " + str(LAYOUT[7][0]) + ":" + str(LAYOUT[7][1])) self.canvas.create_text(50, 20, anchor=W, font="Purisa", text="Control WSAD" ) self.canvas.create_text(650, 20, anchor=W, font="Purisa", text="Control ARROWS" ) x0 = 10 y0 = 40 # WHOLE FIELD self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0], y0 + LAYOUT[1], outline="white", fill="green", width=2) self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0]/2, y0 + LAYOUT[1], outline="white", fill="green", width=1) self.canvas.create_oval(x0 + LAYOUT[0]/2 -1 , y0 + LAYOUT[1]/2 - 1, x0 + LAYOUT[0]/2, y0 + LAYOUT[1]/2, outline="white", fill="white", width=4) # GOALKEEPER FIELDS self.canvas.create_rectangle(x0, y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[3][0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2) self.canvas.create_rectangle(x0 + LAYOUT[0] - LAYOUT[3][0], y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2) # GOALPOSTS self.canvas.create_rectangle(x0 - 5, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black") self.canvas.create_rectangle(x0 + LAYOUT[0]-1, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0 + LAYOUT[0] + 5, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black") # PLAYERS self.canvas.create_oval(x0 + LAYOUT[4][0]-LAYOUT[8][0][0], y0 + LAYOUT[4][1]-LAYOUT[8][0][0], x0 + LAYOUT[4][0] + LAYOUT[8][0][0], y0 + LAYOUT[4][1] + LAYOUT[8][0][0], fill="blue") self.canvas.create_oval(x0 + LAYOUT[5][0]-LAYOUT[8][1][0], y0 + LAYOUT[5][1]-LAYOUT[8][1][0], x0 + LAYOUT[5][0] + LAYOUT[8][1][0], y0 + LAYOUT[5][1] + LAYOUT[8][1][0], fill="gray") # BALL self.canvas.create_oval(x0 + LAYOUT[6][0]-LAYOUT[8][2][0], y0 + LAYOUT[6][1]-LAYOUT[8][2][0], x0 + LAYOUT[6][0] + LAYOUT[8][2][0], y0 + LAYOUT[6][1] + LAYOUT[8][2][0], fill="white") self.canvas.pack(fill=BOTH, expand=1) self.after(1, self.draw)
class SudokuUI(Frame): """ The Tkinter UI, responsible for drawing the board and accepting user input. """ def __init__(self, parent, game): self.game = game Frame.__init__(self, parent) self.parent = parent self.row, self.col = -1, -1 # self.__popupmsg("hi") self.__initUI() def __initUI(self): self.parent.title("Super Sudoku") self.pack() self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH) clear_button = Button(self, padx=50, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=LEFT) undoOne = Button(self, text="Undo", command = self.undo) undoOne.pack(fill=BOTH, side=LEFT) hint_button = Button(self, text="Hint", command = self.__hint) hint_button.pack(fill=BOTH, side=LEFT) hint_better_button = Button(self, text="Better hint", command=self.__better_hint) hint_better_button.pack(fill=BOTH, side=LEFT) solve_button = Button(self, text="BEST hint", command = self.__solve) solve_button.pack(fill=BOTH, side=LEFT) self.__draw_grid() self.__draw_puzzle() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): """ Draws grid divided with blue lines into 3x3 squares """ for i in xrange(10): color = "red" if i % 3 == 0 else "gray" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") for i in xrange(9): for j in xrange(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "blue" self.canvas.create_text( x, y, text=answer, tags="numbers", fill=color ) def __draw_cursor(self): # removes highlighted red region self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle( x0, y0, x1, y1, outline="red", tags="cursor" ) # def __popupmsg(self,msg): # popup = Tkinter.Tk() # popup.wm_title("!") # label = ttk.Label(popup, text=msg, font=NORM_FONT) # label.pack(side="top", fill="x", pady=10) # B1 = ttk.Button(popup, text="Okay", command = popup.destroy) # B1.pack() # popup.mainloop() def __draw_victory(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 3.5 x1 = y1 = MARGIN + SIDE * 5.5 self.canvas.create_oval( x0, y0, x1, y1, tags="victory", fill="dark green", outline="orange" ) # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text( x, y, text="You win!", tags="victory", fill="white", font=("Arial", 24) ) def __draw_mistake(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 3.5 x1 = y1 = MARGIN + SIDE * 5.5 self.canvas.create_oval( x0, y0, x1, y1, tags="mistake", fill="dark orange", outline="orange" ) # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text( x, y, text="That's a mistake!!", tags="mistake", fill="white", font=("Arial", 12) ) def __cell_clicked(self, event): if self.game.game_over: return x, y = event.x, event.y if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN): self.canvas.focus_set() # get row and col numbers from x,y coordinates row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE # if cell was selected already - deselect it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.puzzle[row][col] == 0: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): # print(int(event.char)) if event.char == u'\uf700': self.row -= 1 self.__draw_cursor() if event.char == u'\uf701': self.row += 1 self.__draw_cursor() if event.char == u'\uf702': self.col -= 1 self.__draw_cursor() if event.char == u'\uf703': self.col += 1 self.__draw_cursor() if event.char == '\x7f': self.game.puzzle[self.row][self.col] = 0 self.__draw_puzzle() if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "123456789": self.game.puzzle[self.row][self.col] = int(event.char) if sud.checkMistake(self.game.puzzle) == True: self.game.lastLoc = [self.row,self.col] self.__draw_puzzle() self.__draw_mistake() # self.__draw_cursor() # sleep(2) # self.canvas.delete("mistake") else:# print("MISTAKE") self.__draw_puzzle() self.__draw_cursor() if self.game.check_win(): self.col, self.row = -10,-10 self.__draw_cursor() self.__draw_victory() def undo(self): if(len(self.game.lastLoc) > 0): row,col = self.game.lastLoc[0],self.game.lastLoc[1] self.game.puzzle[row][col] = 0 self.canvas.delete("mistake") self.__draw_puzzle() def __clear_answers(self): self.game.start() self.canvas.delete("victory") self.canvas.delete("mistake") self.__draw_puzzle() def __solve(self): # print("we need to figure this out") # self.game.puzzle = sud.sudoku_solver(self.game.puzzle) sol = sud.sudoku_solver(self.game.puzzle) if sol != None: self.game.puzzle = sol self.__draw_puzzle() if self.game.check_win(): self.__draw_victory() def __hint(self): sol = sud.one_step(self.game.puzzle) if sol != None: self.game.puzzle = sol self.__draw_puzzle() if self.game.check_win(): self.__draw_victory() # print(hint) def __better_hint(self): sol = sud.get_best_hint(self.game.puzzle) if sol == None: return self.game.puzzle[sol[1]][sol[2]] = sol[0] self.__draw_puzzle() if self.game.check_win(): self.__draw_victory()
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') pupil_left = c.create_oval(140,145,150, 155, outline='black', fill='black') pupil_right = c.create_oval(240, 145, 250, 155, outline='black',fill='black') #Normal mouth
class App(object): def __init__(self, tk_root, monsters_initdata, board_dim, board_signs): self.board = [[None for i in range(board_dim[0])] for j in range(board_dim[0])] self.jump_counter = 0 self.meet_counter = 0 self.data = monsters_initdata self.signs = board_signs self.collect = { 'red': [], 'blue': [], 'green': [], 'yellow': [], 'pink': [], 'brown': [] } self.init_gui(tk_root) self.monsters = self.init_monsters() self.draw_board() def init_gui(self, tk_root): # GUI frame = Frame(tk_root) canvas_width = 600 canvas_height = 600 self.canvas = Canvas(frame, width=canvas_width, height=canvas_height) self.canvas.pack() frame.pack() self.quit_button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.quit_button.pack(side=LEFT) self.jump_button = Button(frame, text="JUMP", command=self.jump) self.jump_button.pack(side=LEFT) self.text_counter = StringVar() self.text_counter.set('Round: {}'.format(self.jump_counter)) self.label_counter = Label(frame, textvariable=self.text_counter, justify=LEFT) self.label_counter.pack() self.text_meet_counter = StringVar(self.meet_counter) self.label_meet_counter = Label(frame, textvariable=self.text_meet_counter, justify=LEFT) self.label_meet_counter.pack() def init_monsters(self): monsters = [] for color, values in self.data.iteritems(): for start_position in values['start']: monsters.append( Monster(self.board, color, start_position, values['pattern'])) return monsters def draw_board(self): self.canvas.delete('all') canvas_width = 600 canvas_height = 600 self.board space = canvas_width / (len(self.board) + 2) font = tkFont.Font(family='Helvetica', size=12, weight='bold') for i in range(1, len(self.board) + 2): self.canvas.create_line(space, space * i, canvas_width - space, space * i, fill='#476042') self.canvas.create_line(space * i, space, space * i, canvas_width - space, fill='#476042') for i in range(len(self.board)): self.canvas.create_text(space * (i + 1) + 12, 18, text=i, font=font) self.canvas.create_text(18, space * (i + 1) + 12, text=i, font=font) font = tkFont.Font(family='Helvetica', size=20, weight='bold') for x, y, sign in self.signs: self.canvas.create_text(space * x + 39, space * y + 39, text=sign, font=font, fill='lightgrey') color_r = { 'red': (1, 1), 'green': (1, 2), 'blue': (1, 3), 'yellow': (2, 1), 'pink': (2, 2), 'brown': (2, 3) } for monster in self.monsters: x1, y1 = monster.position # r = color_r.get(monster.color) * 2 r = 2 shift_x, shift_y = color_r.get(monster.color) # self.canvas.create_oval((1.5 + x1) * space - r, (1.5 + y1) * space - r, # (1.5 + x1) * space + r, (1.5 + y1) * space + r, # outline=monster.color, width=2) self.canvas.create_oval((1.5 + x1) * space - 14 - r + shift_y * 7, (1.5 + y1) * space - 14 - r + shift_x * 10, (1.5 + x1) * space - 14 + r + shift_y * 7, (1.5 + y1) * space - 14 + r + shift_x * 10, outline=monster.color, width=2) def jump(self): print print('ROUND {0}'.format(self.jump_counter + 1)) print track_positions = {} for m in self.monsters: if m.rest: x, y = m.stay() else: x, y = m.jump() # check for signs on the board item = self.check_fields(m, self.signs) if item: self.collect[m.color].append(item) # track position of all monsters in this round if (x, y) in track_positions: # already one monster on this location track_positions[(x, y)].append(m) else: track_positions[(x, y)] = [m] self.meet(track_positions) print(self.collect) print self.draw_board() self.jump_counter += 1 print('Meet counter: {}'.format(self.meet_counter)) self.text_counter.set(str(self.jump_counter)) def check_fields(self, monster, fields): x, y = monster.position for x_f, y_f, value in fields: if x == x_f and y == y_f: monster.collection += value print '{} > {} -- {}'.format(monster.color, monster.collection, monster.positions) return value return '' def meet(self, track_positions): pass
class App: def __init__(self, master): self.master = master self.file = 'grid.csv' self.ownZepName = "goud" self.updatingFlag = False self.btnUpPressed = False self.btnDownPressed = False self.btnLeftPressed = False self.btnRightPressed = False self.btnPlusPressed = False self.btnMinusPressed = False #keyListener aanzetten master.bind("<Key>", self.keyPressed) master.bind("<KeyRelease>", self.keyReleased) leftFrame = Frame(master, width = 200, height = 640) leftFrame.grid(row = 0, column = 0) debugFrame = Frame(leftFrame, width = 200, height = 400) debugFrame.grid(row = 0, column = 0) controlFrame = Frame(leftFrame, width = 200, height = 200) controlFrame.grid(row = 1, column = 0, pady = 10) rasterFrame = Frame(master, width = 600, height = 640) rasterFrame.grid(row = 0, column = 1) #Scrolledtext in leftTopFrame self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=80) self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10) #Buttons #simulator self.btnToggleSimu = Button(controlFrame, text = "Simulator", width = 14, bg = 'gray85', command = lambda: self.toggleSimulator()) self.btnToggleSimu.grid(row = 3, column = 2) self.btnMoveToSimu = Button(controlFrame, text = "Ga naar (Sim)", width = 14, bg = 'gray85', command = lambda: self.moveTo(Name = "goudsimu")) self.btnMoveToSimu.grid(row = 1, column = 4) self.btnHeightSimu = Button(controlFrame, text = "Kies hoogte (Sim)", width = 14, bg = 'gray85', command = lambda: self.setGewensteHoogte(Name ="goudsimu")) self.btnHeightSimu.grid(row = 2, column = 4) #hoogte self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(0)) self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte: ", anchor = "w") self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20) self.lblGemetenHoogte.grid(row=0, column=2) self.lblGemetenHoogteVar.grid(row=0, column=3) #move to self.btnMoveTo = Button(controlFrame, text="Ga naar (Zep)", bg = 'gray85', width = 14, command = lambda: self.moveTo()) self.btnMoveTo.grid(row=1,column=2) self.txtMoveTo = Entry(controlFrame, width=24) self.txtMoveTo.grid(row=1, column=3) self.txtMoveTo.bind('<Return>', self.moveTo) #hoogte self.btnHeight = Button(controlFrame, text="Kies hoogte (Zep)", bg = 'gray85', width = 14, command = lambda: self.setGewensteHoogte()) self.btnHeight.grid(row=2,column=2) self.txtHeight = Entry(controlFrame, width=24) self.txtHeight.grid(row=2, column=3) self.txtHeight.bind('<Return>', self.setGewensteHoogte) #images self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0) self.display.grid(row=0, column = 0, sticky=W+E+N+S) foundFigures = Label(controlFrame, text = "Herkende figuren:") foundFigures.grid(row = 0, column = 0) self.display2 = Canvas(controlFrame, width = 220, height=165, bd=2, relief = "groove", highlightthickness=0) self.display2.grid(row=1, column = 0, sticky=W+E+N+S, rowspan=12) self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) #goal original = Image.open('goalPin.png') resized = original.resize((60,60),Image.ANTIALIAS) self.goalImage = ImageTk.PhotoImage(resized) self.makeBackground() self.initZeppelins() self.paintCanvas() self.sim = None mq.setGUI(self) def initZeppelins(self): self.zeppelins = [] self.goal = (-100,-100) # self.zeppelins.append(AbstractZeppelin('red', 'simu')) self.zeppelins.append(AbstractZeppelin('#EBB400', self.ownZepName)) def convToPixelCoords(self, pos): cmHeight = 34.6410162 cmWidth = 40.0 xcm, ycm = pos x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth y = self.yStart + (ycm/cmHeight)*self.triangleHeight result = (x,y) return result def createPhoto(self, cvresults): self.latestphoto = Image.new("RGB", (220,165), (150,150,150)) cv = eval(cvresults) width = cv[0] height = cv[1] figures = cv[2] coordinates = cv[3] for i in xrange(0,len(figures)): j = self.allShapes.index(figures[i]) image = self.shapeImages[j] xcoord = int(coordinates[i][0]/(width*1.0)*220) ycoord = int(coordinates[i][1]/(height*1.0)*165) self.latestphoto.paste(image, (xcoord-12, ycoord-12), mask = image) self.latestImage = ImageTk.PhotoImage(self.latestphoto) self.display2.create_image(0, 0, image=self.latestImage, anchor=NW) def makeBackground(self): #rooster inlezen: f = open("../positioning/"+ str(self.file), 'r') shapesText = f.read() self.raster = [] self.tabletLocations = [] nrows = 0 ncol = 0 for line in shapesText.split("\n"): temp = line.split(",") if not len(temp) == 2: nrows += 1 if ncol == 0: ncol = len(temp) for s in temp: self.raster.append(s.strip()) else: self.tabletLocations.append((int(temp[0]), int(temp[1]))) f.close() tempWidth1 = 600/ncol tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0)) tempHeight2 = 570/nrows+2 tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0)) #raster self.resizedRaster = Image.new("RGB", (600,570), (240,240,240)) #vormpjes self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS'] self.shapeImages = [] for i in range(20): imgFile = "vormpjes/" + self.allShapes[i] + ".png" original = Image.open(imgFile) self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS)) original = Image.open("tablet.png") self.tabletIm = original.resize((40,40),Image.ANTIALIAS) self.xlen = ncol self.ylen = nrows self.triangleWidth = min(tempWidth1, tempWidth2) self.triangleHeight = min(tempHeight1, tempHeight2) self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4 self.oddXStart = self.evenXStart + self.triangleWidth/2 self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4 draw = ImageDraw.Draw(self.resizedRaster) #grid tekenen for y in range(self.ylen): for x in range(self.xlen): ycoord = self.yStart + y*self.triangleHeight zelf = self.raster[y*self.xlen + x] != "XX" if y>0: boven = self.raster[(y-1)*self.xlen + x] != "XX" if y<self.ylen-1: onder = self.raster[(y+1)*self.xlen + x] != "XX" if y>0 and x < self.xlen-1: oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX" if y<self.ylen-1 and x < self.xlen-1: oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX" if x<self.xlen-1: naast = self.raster[y*self.xlen + x+1] != "XX" if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and onder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and boven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) else: xcoord = self.oddXStart + x*self.triangleWidth if x < self.xlen-1 and naast and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0) if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0) if y > 0 and x < self.xlen-1 and oddboven and zelf: draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0) del draw for loc in self.tabletLocations: conv = self.convToPixelCoords((loc[0]/10, loc[1]/10)) self.resizedRaster.paste(self.tabletIm, (int(conv[0])-20, int(conv[1])-20), mask = self.tabletIm) #vormpjes tekenen for y in range(self.ylen): for x in range(self.xlen): index = y*self.xlen + x if y % 2 == 0: xcoord = self.evenXStart + x*self.triangleWidth else: xcoord = self.oddXStart + x*self.triangleWidth ycoord = self.yStart + y*self.triangleHeight shape = self.raster[index] if shape != 'XX': image = self.shapeImages[self.allShapes.index(shape)] self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) def updatePath(self): self.rasterBackup = self.rasterImage draw = ImageDraw.Draw(self.resizedRaster) for z in self.zeppelins: length = len(z.locations) if length > 1: prev = self.convToPixelCoords(z.locations[length-2]) current = self.convToPixelCoords(z.locations[length-1]) draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3) self.rasterImage = ImageTk.PhotoImage(self.resizedRaster) del draw def paintCanvas(self): #clear the canvas #self.display.delete('all') #rooster tekenen self.updatePath() self.display.create_image(0, 0, image=self.rasterImage, anchor=NW) #Testcode voor zeppelin locatie for z in self.zeppelins: if z.orientationFound: point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20)) point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20)) point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20)) point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20)) point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation)) point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation)) arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y] self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1) self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color) self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER) def toggleSimulator(self): if self.sim == None: enemy = "goudsimu" self.zeppelins.append(AbstractZeppelin("red", enemy)) mq.initEnemy(enemy) self.sim = simulator.simulator(100,100, enemy) return self.sim.toggleActive() def updateGoal(self, location, tablet): self.debugPrint("Nieuw doel voor simulator: " + str(tablet) + " " + str(location)) self.goal = self.convToPixelCoords(location) self.paintCanvas() def updateLocation(self, location, n): self.debugPrint("Nieuwe locatie voor " + n + " ontvangen: " + str(location)) for z in self.zeppelins: if z.name == n: z.updateLocation((location[0]/10, location[1]/10)) self.paintCanvas() def updateHeight(self, height, n): self.debugPrint("Nieuwe hoogte voor " + n + " ontvangen: " + str(height)) if self.ownZepName == n: self.gemetenHoogteString.set(str(height)) def updateAngle(self, angle, n): self.debugPrint("Nieuwe orientatie voor " + n + " ontvangen: " + str(angle) + " graden") for z in self.zeppelins: if z.name == n: z.updateAngle(angle) self.paintCanvas() def showCvResults(self, body): self.debugPrint("Nieuwe foto vertaling ontvangen: " + body) self.createPhoto(body) #gewenste hoogte aanpassen def setGewensteHoogte(self, event = None, Name = "goud"): x = self.txtHeight.get() self.txtHeight.delete(0, END) self.master.focus() try: x = int(x) except: return if isinstance(x, int) and x > 0 and x < 8000: global neededHeight neededHeight = x message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd" self.debugPrint(message) mq.elevate(x, Name) #gewenste hoogte aanpassen def moveTo(self, event = None, Name = "goud"): st = self.txtMoveTo.get() self.txtMoveTo.delete(0, END) self.master.focus() try: xst, yst = st.split(',') x = int(xst) y = int(yst) except: return if isinstance(x, int) and isinstance(y, int): message = "Bewegen naar (" + str(x) + "," + str(y) + ") aangevraagd" self.debugPrint(message) self.goal = x/10,y/10 self.paintCanvas() mq.moveTo(x, y, Name) #tekst weergeven in debug venster def debugPrint(self, tekst): self.scrDebug.config(state = "normal") self.scrDebug.insert(END, ">> " + tekst + "\n") self.scrDebug.config(state = "disabled") self.scrDebug.yview_pickplace("end") def toggleAutomaticPilot(self): if not self.connected: return self.debugPrint("Automatische piloot toggle aangevraagd") self.client.toggleAutomaticPilot() def createClient(self): try: self.client = cl(self, self.ownZepName) self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client)) self.connected = True self.connectedString.set("Verbonden") self.lblConnected.config(fg = "green") self.debugPrint("Verbonden met Raspberry Pi") except: self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n -Staat de Raspberry Pi aan?\n -Staat de server aan?\n -Zit deze computer op de ad-hoc?") def moveForward(self): self.debugPrint("Voorwaarts vliegen aangevraagd") mq.setMotor1PWM(100) mq.setMotor2PWM(100) def moveBackward(self): self.debugPrint("Achterwaarts vliegen aangevraagd") mq.setMotor1PWM(-100) mq.setMotor2PWM(-100) def moveLeft(self): self.debugPrint("Links draaien aangevraagd") mq.setMotor1PWM(100) def moveRight(self): self.debugPrint("Rechts draaien aangevraagd") mq.setMotor2PWM(100) def moveUp(self): self.debugPrint("Omhoog vliegen aangevraagd") mq.setMotor3PWM(100) def moveDown(self): self.debugPrint("Omlaag vliegen aangevraagd") mq.setMotor3PWM(-100) def horizontalOff(self): self.debugPrint("Horizontale motors stoppen aangevraagd") mq.setMotor1PWM(0) mq.setMotor2PWM(0) def verticalOff(self): self.debugPrint("Verticale motor stoppen aangevraagd") mq.setMotor3PWM(0) #toetsenbord invoer def keyPressed(self, event): k = event.keysym if k == 'Up': if not self.btnUpPressed: self.btnUpPressed = True self.moveForward() elif k == 'Down': if not self.btnDownPressed: self.btnDownPressed = True self.moveBackward() elif k == 'Left': if not self.btnLeftPressed: self.btnLeftPressed = True self.moveLeft() elif k == 'Right': if not self.btnRightPressed: self.btnRightPressed = True self.moveRight() elif k == 'plus': if not self.btnPlusPressed: self.btnPlusPressed = True self.moveUp() elif k == 'minus': if not self.btnMinusPressed: self.btnMinusPressed = True self.moveDown() def keyReleased(self, event): k = event.keysym if k == 'Up': self.btnUpPressed = False self.horizontalOff() elif k == 'Down': self.btnDownPressed = False self.horizontalOff() elif k == 'Left': self.btnLeftPressed = False self.horizontalOff() elif k == 'Right': self.btnRightPressed = False self.horizontalOff() elif k == 'plus': self.btnPlusPressed = False self.verticalOff() elif k == 'minus': self.btnMinusPressed = False self.verticalOff()
class main: def __init__ (self): self.app = Tk() self.app.title('Tic Tac Toe') #self.app.resizable(width=False, height=False) #width and hight of window w = 900 h = 1100 #width and hight of screen ws = self.app.winfo_screenwidth() hs = self.app.winfo_screenheight() #calculate position x = ws/2 - w/2 y = hs/2 - h/2 #place window -> pramaters(visina, dolzina, pozicija x, pozicija y) self.app.geometry("%dx%d+%d+%d" % (w,h, x, y)) #====================================== self.frame = Frame() #main frame self.frame.pack(fill = 'both', expand = True) self.label = Label(self.frame, text = 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue') self.label.pack(fill='both', expand = True) #self.label2 = Label(self.frame, text = 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop------------- #self.label2.pack(fill='both', expand = True) self.canvas = Canvas(self.frame, width = 900, height = 900) self.canvas.pack(fill = 'both', expand = True) self.framepod = Frame(self.frame)#sub frame self.framepod.pack(fill = 'both', expand = True) self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue') self.Single.pack(fill='both', expand = True, side=RIGHT) self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue') self.Multi.pack(fill='both', expand = True, side=RIGHT) self.board = AI() self.draw() def double(self): #cleans the all simbols from canvas self.canvas.delete(ALL) self.label['text'] = ('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.place) self.draw() #--------------------------------------- self.table=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]] self.c=0 #counter self.e=False #flag for end game def draw(self): #draws the outline lines self.canvas.create_rectangle(0,0,900,900, outline='black') self.canvas.create_rectangle(300,900,600,0, outline='black') self.canvas.create_rectangle(0,300,900,600, outline='black') def place(self, event): for i in range(0,900,300): for j in range(0,900,300): if event.x in range(i,i+300) and event.y in range(j, j+300): if self.canvas.find_enclosed(i,j,i+300, j+300) == (): if self.c % 2 == 0: #calculate points to draw circle x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue") self.table[y2][x2] = 4 self.c+=1 else: #calculate points to draw cross x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red") self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red") self.table[y2][x2] = 1 self.c+=1 self.check() def startsingle(self): self.canvas.delete(ALL) self.label['text'] = ('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.placeone) self.draw() self.board = AI() def placeone(self, event): player = 'X' for i in range(0,900,300): for j in range(0,900,300): if event.x in range(i,i+300) and event.y in range(j, j+300): if self.canvas.find_enclosed(i,j,i+300, j+300) == (): x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red") self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red") player_move = x2 + 3*y2 #spremeni self.board.make_move(player_move, player) if self.board.complete(): self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() elif self.board.winner() != None: self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() else: player = self.board.get_enemy(player) computer_move = self.board.determine(self.board, player) self.board.make_move(computer_move, player) ti = computer_move % 3 tj = computer_move / 3 x=(600*ti+300)/2 y=(600*tj+300)/2 #self.label2['text'] = str(computer_move) + ' ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x) self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue") if self.board.winner() != None: self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() def check(self): #checks for win #horitontal for i in range(3): if sum(self.table[i])==3: self.label['text'] = ('X wins') self.end() if sum(self.table[i])==12: self.label['text'] = ('O wins') self.end() #vertical self.vs=[[row[i] for row in self.table] for i in range(3)] for i in range(3): if sum(self.vs[i])==3: self.label['text'] = ('X wins') self.end() if sum(self.vs[i])==12: self.label['text'] = ('O wins') self.end() #diagonals self.dig1=0 self.dig2=0 for i in range(3): self.dig1+=self.table[i][i] for i in range(3): self.dig2+=self.table[2-i][i] if self.dig1==3: self.label['text'] = ('X wins') self.end() if self.dig1==12: self.label['text'] = ('O wins') self.end() if self.dig2==3: self.label['text'] = ('X wins') self.end() if self.dig2==12: self.label['text'] = ('O wins') self.end() #draw if self.e==False: a=0 for i in range(3): a+=sum(self.table[i]) if a == 24: #5 *4 + 4 * 1 --> 5 circles and 4 crosses self.label['text'] = ('Draw') self.end() def end(self): self.canvas.unbind("<ButtonPress-1>") self.e=True def mainloop(self): self.app.mainloop()
class Clock(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.initTime() self.draw() self.onTimer() def initTime(self): self.hourHand = time.localtime().tm_hour % 12 * 5 self.minuteHand = time.localtime().tm_min self.secondHand = time.localtime().tm_sec def draw(self): self.pack(fill=BOTH, expand=1) radius = 300 x, y = 50, 50 centerX, centerY = 180, 180 hourX = centerX + 0.3 * radius / 2.0 * math.cos( self.toRadian(self.hourHand)) hourY = centerY + 0.3 * radius / 2.0 * math.sin( self.toRadian(self.hourHand)) minuteX = centerX + 0.6 * radius / 2.0 * math.cos( self.toRadian(self.minuteHand)) minuteY = centerY + 0.6 * radius / 2.0 * math.sin( self.toRadian(self.minuteHand)) secondX = centerX + 0.75 * radius / 2.0 * math.cos( self.toRadian(self.secondHand)) secondY = centerY + 0.75 * radius / 2.0 * math.sin( self.toRadian(self.secondHand)) self.canvas.create_oval(x, y, radius, radius, outline="black", fill="black") self.canvas.create_line(centerX, centerY, hourX, hourY, width=3, fill="green") self.canvas.create_line(centerX, centerY, minuteX, minuteY, width=3, fill="green") self.canvas.create_line(centerX, centerY, secondX, secondY, fill="red") self.canvas.pack(fill=BOTH, expand=1) def toRadian(self, x): return (x * math.pi / 30.0) - (math.pi / 2.0) def onTimer(self): self.tick() self.canvas.delete(ALL) self.draw() self.after(DELAY, self.onTimer) def tick(self): self.secondHand = (self.secondHand + 1) % 60 if self.secondHand == 0: self.minuteHand = (self.minuteHand + 1) % 60 if self.minuteHand == 0: self.hourHand = (self.hourHand + 5) % 60
class MapUI: def __init__(self, master): def center(win): win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 4) - (width // 2) + 40 y = (win.winfo_screenheight() // 4) - (height // 2) + 40 win.geometry('{}x{}+{}+{}'.format(width, height, x, y)) def callback(event): event.widget.focus_set() print "clicked at", event.x, event.y if self.add_tasks_flg.get() == 1: # Select number of robots # Define elements of pop up window self.top = Toplevel() self.num_robots = StringVar(self.top) self.num_robots.set("1") # default value w = OptionMenu(self.top, self.num_robots, '1', '2', '3', '4').grid(row=0, column=1) text1 = Message(self.top, text="Number of robots:", width=150).grid(row=0, column=0) self.e = Entry(self.top, width=10) self.e.grid(row=1, column=1) text2 = Message(self.top, text="Task duration:", width=150).grid(row=1, column=0) text3 = Message(self.top, text="(s)", width=60).grid(row=1, column=2) newline = Message(self.top, text=" ").grid(row=2) button = Button(self.top, text='Enter', command=lambda: self.enter_task(event)).grid( row=3, column=1) button_cancel = Button(self.top, text='Cancel', command=self.cancel_task).grid(row=3, column=2) center(self.top) master.title("Map Interface") master.minsize(width=1000, height=750) master.maxsize(width=1000, height=750) master.config(bg=BKG_COLOUR) self.master = master # Canvas for overlaying map self.map_canvas = Canvas(master, width=CANVAS_W, height=CANVAS_H, bg='gray85', highlightthickness=0) self.map_canvas.pack(side='right', padx=50) self.map_canvas.bind("<Button-1>", callback) global CANVAS_PTR CANVAS_PTR = self.map_canvas self.master.update() w = self.map_canvas.winfo_width() h = self.map_canvas.winfo_height() # Overlay a grid for i in range(0, w, SQ_SIZE): if i != 0: self.map_canvas.create_line(i, 0, i, h, dash=1) for i in range(0, h, SQ_SIZE): if i != 0: self.map_canvas.create_line(0, i, w, i, dash=1) # Load in flame icon from flame.gif self.flame_icon = PhotoImage(file="flame.gif") # Load in the drone icon from drone.gif global DRONE_ICON DRONE_ICON = PhotoImage(file="drone.gif") buttons_frame = Canvas(master, width=163, height=230, bg=BUTTONS_BKG_COLOUR, highlightthickness=1, highlightbackground='dim grey') buttons_frame.place(x=40, y=200) # Define UI buttons self.add_tasks_flg = IntVar() self.add_tasks_b = Checkbutton(master, text="Add Tasks", variable=self.add_tasks_flg, highlightbackground=BUTTONS_BKG_COLOUR, background=BUTTONS_BKG_COLOUR) self.add_tasks_b.place(x=77, y=240) self.clear_wp_b = Button(master, text='Clear Tasks', command=self.clear_wp, highlightbackground=BUTTONS_BKG_COLOUR) self.clear_wp_b.config(width=10) self.clear_wp_b.place(x=65, y=270) ''' self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR) self.gen_wp_file_b.config(width=20) self.gen_wp_file_b.place(x=20, y=250) ''' self.land_b = Button(master, text='Land', command=self.land, highlightbackground=BUTTONS_BKG_COLOUR) self.land_b.config(width=10) self.land_b.place(x=65, y=350) # Set up coordinate system conversion and display corners of room: file_obj = open('antenna_locations.txt', 'r') anchors = [] for line in file_obj: cur_anchors = map(float, line.split()) anchors.append(cur_anchors) file_obj.close() anchors = (np.array(anchors)).T # Find largest (abs) x and y values to use a reference for conversion ratio x_vals = anchors[0] largest_x_val = x_vals[np.argmax(abs(x_vals))] y_vals = anchors[1] largest_y_val = y_vals[np.argmax(abs(y_vals))] if largest_x_val > largest_y_val: largest_y_val = largest_x_val else: largest_x_val = largest_y_val global m_per_pixel_x m_per_pixel_x = float(largest_x_val / (CANVAS_W / 2)) global m_per_pixel_y m_per_pixel_y = float(largest_y_val / (CANVAS_H / 2)) # Place antenna (anchors) on UI anchors = anchors.T for cur_anchor in anchors: x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W / 2 y_pixel_loc = -1 * (cur_anchor[1] / m_per_pixel_y) + CANVAS_H / 2 # Draw antenna @ location global ANTENNA_LIST antenna_id = self.map_canvas.create_oval(x_pixel_loc - 15, y_pixel_loc - 15, x_pixel_loc + 15, y_pixel_loc + 15, fill='red') self.master.update() global SQ_SIZE SQ_SIZE = 20 global BKG_COLOUR BKG_COLOUR = 'gray95' global BUTTONS_BKG_COLOUR BUTTONS_BKG_COLOUR = 'grey66' global CANVAS_W CANVAS_W = 700 global CANVAS_H CANVAS_H = 700 global TASK_LIST TASK_LIST = None global m_per_pixel_x m_per_pixel_x = None global m_per_pixel_y m_per_pixel_y = None global NEW_TASK_FLAG NEW_TASK_FLAG = False global ANTENNA_LIST ANTENNA_LIST = None global DRONE_ICON DRONE_ICON = None flame_icon = None ui_wp_list = None #task_list = None add_wp_flag = False task_id = 0 add_tasks_flg = None def add_tasks(self): print "adding tasks" # function imp here self.add_wp_flag = True self.map_canvas.config(cursor='pencil') def clear_wp(self): print "clear tasks" global TASK_LIST TASK_LIST = None for element_id in self.ui_wp_list: self.map_canvas.delete(element_id[0]) self.ui_wp_list = None ''' def gen_wp_file(self): print "generate wp file" # function imp here ''' def land(self): # Send a new task with position (0,0,0) z=0 tells drone to land print("land") def enter_task(self, event): # Determine square (top left corner coords): w_start = event.x - event.x % SQ_SIZE h_start = event.y - event.y % SQ_SIZE #Translate pixel location to physical location x_pixel = event.x y_pixel = event.y # Find out how many pixels from center: x_pixel = x_pixel - CANVAS_W / 2 x_physical = x_pixel * m_per_pixel_x #vertical case, note this is flipped y_pixel = y_pixel - CANVAS_W / 2 y_pixel = -1 * y_pixel y_physical = y_pixel * m_per_pixel_y try: # Add to task list global TASK_LIST if TASK_LIST == None: TASK_LIST = [[ self.task_id, int(self.num_robots.get()), float(self.e.get()), x_physical, y_physical ]] global NEW_TASK_FLAG NEW_TASK_FLAG = True else: TASK_LIST.append([ self.task_id, int(self.num_robots.get()), float(self.e.get()), x_physical, y_physical ]) global NEW_TASK_FLAG NEW_TASK_FLAG = True # Indicate task in UI element_id = self.map_canvas.create_image(event.x, event.y, image=self.flame_icon) if self.ui_wp_list == None: self.ui_wp_list = [[element_id]] else: self.ui_wp_list.append([element_id]) except: print("Invalid Task Entry") self.map_canvas.config(cursor='arrow') self.add_wp_flag = False print(TASK_LIST) self.task_id = self.task_id + 1 self.top.destroy() def cancel_task(self): self.top.destroy()
class DiscreteTAMPViewer(object): def __init__(self, rows, cols, width=500, height=250, side=25, block_buffer=10, title='Grid', background='tan', draw_fingers=False): assert (rows <= MAX_ROWS) assert (cols <= MAX_COLS) tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.rows = rows self.cols = cols self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() self.side = side self.block_buffer = block_buffer self.draw_fingers = draw_fingers self.cells = {} self.robot = [] self.draw_environment() def transform_r(self, r): return self.table_y1 + r * (self.side + 2 * self.block_buffer ) + 2 * self.block_buffer + self.side / 2 def transform_c(self, c): # assert r >= 0 and r < self.width return self.table_x1 + c * (self.side + 2 * self.block_buffer ) + 2 * self.block_buffer + self.side / 2 def draw_environment(self, table_color='lightgrey', bin_color='grey'): table_width = self.cols * ( self.side + 2 * self.block_buffer) + 2 * self.block_buffer table_height = self.rows * ( self.side + 2 * self.block_buffer) + 2 * self.block_buffer border_buffer = 50 #self.table_x1 = border_buffer self.table_y1 = self.height - table_height - border_buffer self.table_x1 = self.width / 2 - table_width / 2 #self.table_y1 = self.height/2-table_height/2 bin_width = 20 self.environment = [ self.canvas.create_rectangle(self.table_x1, self.table_y1, self.table_x1 + table_width, self.table_y1 + table_height, fill=table_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1 - bin_width, self.table_y1, self.table_x1, self.table_y1 + table_height, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1 + table_width, self.table_y1, self.table_x1 + table_width + bin_width, self.table_y1 + table_height, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1, self.table_y1 + table_height, self.table_x1 + table_width, self.table_y1 + table_height + bin_width, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle( self.table_x1 - bin_width, self.table_y1 + table_height, self.table_x1 + table_width + bin_width, self.table_y1 + table_height + bin_width, fill=bin_color, outline='black', width=2), ] pose_radius = 2 for r in range(self.rows): for c in range(self.cols): x = self.transform_c(c) y = self.transform_r(r) self.environment.append( self.canvas.create_oval(x - pose_radius, y - pose_radius, x + pose_radius, y + pose_radius, fill='black')) def draw_robot(self, r, c, color='yellow'): # TODO - could also visualize as top grasps instead of side grasps grasp_buffer = 3 # 0 | 3 | 5 finger_length = self.side + grasp_buffer # + self.block_buffer finger_width = 10 gripper_length = 20 if self.draw_fingers: gripper_width = self.side + 2 * self.block_buffer + finger_width else: gripper_width = self.side stem_length = 50 stem_width = 20 x = self.transform_c(c) y = self.transform_r( r) - self.side / 2 - gripper_length / 2 - grasp_buffer finger_x = gripper_width / 2 - finger_width / 2 self.robot = [ self.canvas.create_rectangle(x - stem_width / 2., y - stem_length, x + stem_width / 2., y, fill=color, outline='black', width=2), self.canvas.create_rectangle(x - gripper_width / 2., y - gripper_length / 2., x + gripper_width / 2., y + gripper_length / 2., fill=color, outline='black', width=2), ] if self.draw_fingers: self.robot += [ self.canvas.create_rectangle(x + finger_x - finger_width / 2., y, x + finger_x + finger_width / 2., y + finger_length, fill=color, outline='black', width=2), self.canvas.create_rectangle(x - finger_x - finger_width / 2., y, x - finger_x + finger_width / 2., y + finger_length, fill=color, outline='black', width=2), ] self.canvas.update() def draw_block(self, r, c, name='', color='red'): x = self.transform_c(c) y = self.transform_r(r) self.cells[(x, y)] = [ self.canvas.create_rectangle(x - self.side / 2., y - self.side / 2., x + self.side / 2., y + self.side / 2., fill=color, outline='black', width=2), self.canvas.create_text(x, y, text=name), ] # def delete(self, (x, y)): # if (x, y) in self.cells: # self.canvas.delete(self.cells[(x, y)]) def clear(self): self.canvas.delete('all') def save(self, filename): self.canvas.postscript(file='%s.ps' % filename, colormode='color') from PIL import ImageGrab ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
# -*- coding: utf-8 -*- from Tkinter import Tk, Frame, Canvas, Label, Button, Entry, END import tkFont import time, random if __name__ == '__main__': window = Tk() window.title("Una ventana de prueba") my_font = tkFont.Font(family="Helvetica", size=24) frame = Frame(window) frame.pack() canvas = Canvas(frame, width=500, height=200, bg="green") id1 = canvas.create_oval(50, 20, 70, 40, fill="white") id2 = canvas.create_rectangle(100,100,125,125, fill ="red") canvas.pack() def click(event): print "raton en", event.x, event.y colors = ["green","yellow","red", "black", "white"] canvas.itemconfigure(id2,fill=colors[random.randint(0,len(colors)-1)]) o = canvas.coords(id1) print "origin", o, type(o) r = o[0:2]+map(lambda x: x+4,o[-2:]) print "result", r, type(r) canvas.coords(id1,r[0],r[1],r[2],r[3]) canvas.bind("<Button-1>", click) def ejecucion_boton(): print "boton"
class FullScreenWindow: def __init__(self, label_timeout, max_elements): self.count = 0 self.colors_count = 0 self.tk = Tk() self.max_elements = max_elements self.frame = Frame(self.tk) self.frame.bind("<Key>", self.key_press) self.frame.focus_set() self.state = False self.tk.attributes("-fullscreen", True) self.label_timeout = label_timeout self.screen_width = self.tk.winfo_screenwidth() self.screen_height = self.tk.winfo_screenheight() screen_resolution = str(self.screen_width) + 'x' + str(self.screen_height) self.tk.geometry(screen_resolution) self.canvas = Canvas(self.frame, height=self.screen_height, width=self.screen_width) self.canvas.pack(fill=BOTH) self.frame.pack() self.objects = deque() def key_press(self, key): self.draw_triangle() def draw_triangle(self): x1 = random.uniform(0, 1) * self.screen_width y1 = random.uniform(0, 1) * self.screen_height x2 = random.uniform(0, 1) * self.screen_width y2 = random.uniform(0, 1) * self.screen_height x3 = random.uniform(0, 1) * self.screen_width y3 = random.uniform(0, 1) * self.screen_height x4 = random.uniform(0, 1) * self.screen_width y4 = random.uniform(0, 1) * self.screen_height x5 = random.uniform(0, 1) * self.screen_width y5 = random.uniform(0, 1) * self.screen_height colors = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta'] if self.colors_count % 7 == 0: self.colors_count = 0 if self.count == 0: o = self.canvas.create_line(x1, y1, x2, y2, x3, y3, x1, y1) self.count = 1 elif self.count == 1: o = self.canvas.create_rectangle(x1, y1, x2, y2, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 2 elif self.count == 2: o = self.canvas.create_oval(x1, y1, x2, y2, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 3 elif self.count == 3: o = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, fill=colors[self.colors_count]) self.colors_count += 1 self.count = 0 if len(self.objects) >= self.max_elements: obj_to_remove = self.objects.pop() self.canvas.delete(obj_to_remove) self.objects.appendleft(o) self.canvas.after(self.label_timeout,self.canvas.delete, o) self.frame.pack(fill=BOTH, expand=1)
class SudokuUI(Frame): """ The Tkinter UI, responsible for drawing the board and accepting user input. """ def __init__(self, parent, game): self.game = game Frame.__init__(self, parent) self.parent = parent self.row, self.col = -1, -1 self.__initUI() def __initUI(self): self.parent.title("Sudoku") self.pack(fill=BOTH) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) self.__draw_grid() self.__draw_puzzle() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): """ Draws grid divided with blue lines into 3x3 squares """ for i in range(10): color = "blue" if i % 3 == 0 else "grey" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") for i in range(9): for j in range(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __draw_victory(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You win!", tags="victory", fill="white", font=("Arial", 32)) def __draw_loose(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="yellow", outline="yellow") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You loose!", tags="victory", fill="white", font=("Arial", 32)) def __cell_clicked(self, event): if self.game.game_over: return x, y = event.x, event.y if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN): self.canvas.focus_set() # get row and col numbers from x,y coordinates row, col = (y - MARGIN) // SIDE, (x - MARGIN) // SIDE # if cell was selected already - deselect it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.check[row][col] == 0: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() a = self.game.check_win() # print(a) if a == 0: self.__draw_loose() return 0 elif a == 1: self.__draw_victory() def __clear_answers(self): self.game.start() self.canvas.delete("victory") self.__draw_puzzle()
# -*- coding: utf-8 -*- from Tkinter import Tk, Frame, Canvas, Label import time, random if __name__ == '__main__': window = Tk() window.title("Una ventana de prueba") frame = Frame(window) frame.pack() canvas = Canvas(frame, width=800, height=500) canvas.create_oval(50, 20, 100, 70, fill="white") canvas.create_rectangle(100, 100, 150, 150, fill ="red") canvas.pack() l = Label(frame, text="Un texto de etiqueta") l.pack() window.mainloop()
class RoomDisplay(Frame): def __init__(self, parent, actionList, room): Frame.__init__(self, parent) self.actionList = actionList self.room = room self.parent = parent self.initUI() self.displayMotion() def initUI(self): self.parent.title("Room") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) for level in xrange(0, len(self.room)): for grid in xrange(0, len(self.room[level])): if self.room[level][grid] == 0.0: self.canvas.create_line((grid+1)*50, 50+100*(len(self.room)-level), (grid+2)*50, 50+100*(len(self.room)-level), width=2) else: self.canvas.create_rectangle((grid+1)*50, 50+100*(len(self.room)-level), (grid+2)*50, 50+100*(len(self.room)-level-self.room[level][grid]), outline="black", fill="black", width=2) self.canvas.create_line(50, 50, 50, 50+100*len(self.room), width=2) self.canvas.create_line(400, 50, 400, 50+100*len(self.room), width=2) character_one = self.characterXYCoordinates(self.actionList[0][0], LEFT) character_two = self.characterXYCoordinates(self.actionList[0][1], RIGHT) self.character_one_side = LEFT self.character_two_side = RIGHT self.character_one = self.canvas.create_oval(character_one[0], character_one[1], character_one[2], character_one[3], outline="red", fill="red", width=2) self.character_two = self.canvas.create_oval(character_two[0], character_two[1], character_two[2], character_two[3], outline="blue", fill="blue", width=2) self.currentAction = 0 self.canvas.pack(fill=BOTH, expand=1) def characterXYCoordinates(self, state, side): left_boundary = 52.5 + 50*state[0] if side == LEFT: left_boundary = left_boundary + 25 bottom_boundary = 50 + 100*(len(self.room)-state[1]-self.room[state[1]][state[0]]) - 20 return (left_boundary, bottom_boundary, left_boundary+20, bottom_boundary-20) def displayMotion(self): if self.currentAction < len(self.actionList)-1: print self.actionList[self.currentAction+1] if self.actionList[self.currentAction][2] == self.actionList[self.currentAction+1][2] and \ self.actionList[self.currentAction][3] == 0 and \ self.actionList[self.currentAction+1][3] == 0: # Switch sides old_character_one = self.characterXYCoordinates(self.actionList[self.currentAction][0], self.character_one_side) old_character_two = self.characterXYCoordinates(self.actionList[self.currentAction][1], self.character_two_side) self.character_one_side = switchSides(self.character_one_side) self.character_two_side = switchSides(self.character_two_side) new_character_one = self.characterXYCoordinates(self.actionList[self.currentAction+1][0], self.character_one_side) new_character_two = self.characterXYCoordinates(self.actionList[self.currentAction+1][1], self.character_two_side) else: old_character_one = self.characterXYCoordinates(self.actionList[self.currentAction][0], self.character_one_side) old_character_two = self.characterXYCoordinates(self.actionList[self.currentAction][1], self.character_two_side) new_character_one = self.characterXYCoordinates(self.actionList[self.currentAction+1][0], self.character_one_side) new_character_two = self.characterXYCoordinates(self.actionList[self.currentAction+1][1], self.character_two_side) self.animate(self.character_one, old_character_one, new_character_one, 0, 0) self.animate(self.character_two, old_character_two, new_character_two, 0, 1) self.currentAction = self.currentAction+1 def animate(self, character, start, end, iteration, thread_index): interpolate0 = start[0] + (end[0]-start[0])*iteration/NUM_ITERATIONS interpolate1 = start[1] + (end[1]-start[1])*iteration/NUM_ITERATIONS interpolate2 = start[2] + (end[2]-start[2])*iteration/NUM_ITERATIONS interpolate3 = start[3] + (end[3]-start[3])*iteration/NUM_ITERATIONS self.canvas.coords(character, interpolate0, interpolate1, interpolate2, interpolate3) if iteration < NUM_ITERATIONS: self.after(10, self.animate, character, start, end, iteration+1, thread_index) elif thread_index == 0: self.after(10, self.displayMotion)
random.seed((0, 0)) hlavni = Tk() w = Canvas(hlavni, width=800, height=800) w.pack() points = list( set([(random.randint(50, 750), random.randint(50, 750)) for i in range(0, 200)])) #get rid of duplicities random.shuffle(points) tkinterpoints = {} for point in points: tkinterpoints[point] = w.create_oval(point[0], point[1], point[0], point[1], width=1) aqueue = [] hull = chan_hull(points, aqueue) ddict = {} def do_something(tkintevent): draw_queue_step(w, aqueue, ddict) def skip_something(tkintevent): for i in range(50): draw_queue_step(w, aqueue, ddict)
class at_graph(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.u = utils('atoutput.pkl') self.km = dict() self.price = dict() self.km[0] = (min(self.u.all_km), max(self.u.all_km)) self.price[0] = (min(self.u.all_price), max(self.u.all_price)) self.zoom_level = 0 try: self.parent.title("Auto trader results") self.is_standalone = True except: self.is_standalone = False self.style = Style() self.style.theme_use("classic") # Assume the parent is the root widget; make the frame take up the # entire widget size. print self.is_standalone if self.is_standalone: self.w, self.h = map(int, self.parent.geometry().split('+')[0].split('x')) self.w, self.h = 800, 800 else: self.w, self.h = 600, 600 self.c = None # Are they hovering over a data point? self.is_hovering = False # Filter the description strings: lower and whiten any non-matching # data point. self.filter = '' self.re = list() self.replot() def replot(self, zlfrac=None): """Replot the graph. If zlfrac is not None, then it should be a fractional value between 0 and 1; this is used to do smooth zooming, which doesn't plot the axes (it only redraws the car points).""" if self.c is not None: self.c.destroy() self.c = Canvas(self, height=self.h, width=self.w, bd=1, bg='#f3f5f9') self.c.grid(sticky=S, pady=1, padx=1) zl = self.zoom_level if zlfrac is not None: z1l, z1h = self.zoom_price_start z2l, z2h = self.zoom_price_end price_low = z1l + (z2l - z1l) * zlfrac price_high = z1h + (z2h - z1h) * zlfrac z1l, z1h = self.zoom_km_start z2l, z2h = self.zoom_km_end km_low = z1l + (z2l - z1l) * zlfrac km_high = z1h + (z2h - z1h) * zlfrac self.axis((price_low, price_high), 'y', draw=False) self.axis((km_low, km_high), 'x', draw=False) self.car_points(draw=False) else: self.axis(self.price[zl], 'y') self.axis(self.km[zl], 'x') self.car_points() self.pack(fill=BOTH, expand=1) def xyp(self, x, y): "Given x in km and y in $, return canvas position (xp, yp)." xp = int(math.floor((1.0 * x - self.x1) / (self.x2 - self.x1) \ * (self.xp2 - self.xp1) + self.xp1 + 0.5)) yp = int(math.floor((1.0 * y - self.y1) / (self.y2 - self.y1) \ * (self.yp2 - self.yp1) + self.yp1 + 0.5)) return (xp, yp) def axis(self, arange, ax, draw=True): "Add an axis ax='x' or 'y', with arange=(min, max) values." if draw: a1, a2, ast = self.u.axis(*arange) else: a1, a2 = arange ast = (a2 - a1) * 0.2 nt = int(math.floor((a2 - a1) / ast + 0.5)) + 1 st_offset = 50 # Remember the min and max axis values, along with the canvas points # that correspond to each location (xp1 and xp2). This allows us to # calculate where on the canvas a particular (x, y) value falls. if ax == 'x': self.x1, self.x2 = a1, a2 self.xp1, self.xp2 = st_offset, self.w - st_offset self.xtick = [a1 + i * ast for i in range(nt)] # Remember where the midpoint of the axis is, relative to canvas. self.xmid = (self.xp1 + self.xp2) / 2 else: self.y1, self.y2 = a1, a2 self.yp1, self.yp2 = self.h - st_offset, st_offset self.ytick = [a1 + i * ast for i in range(nt)] # Remember where the midpoint of the axis is, relative to canvas. self.ymid = (self.yp1 + self.yp2) / 2 # Figure out tick labels. atick = ['%g' % ((a1 + i * ast) / 1000) for i in range(nt)] # Figure out maximum decimal places on all tick labels, and ensure # they all have that many decimal places. max_dec = max(map(lambda x: 0 if '.' not in x else len(x.split('.')[1]), atick)) if max_dec > 0: atick = map(lambda x: x + '.' + '0'*max_dec if '.' not in x else x + '0'*(max_dec - len(x.split('.')[1])), atick) yst, xst = self.h - st_offset, st_offset # Draw axis line proper, and axis label. if draw: if ax == 'x': self.c.create_line(xst, yst, self.w - st_offset, yst) xp = (xst + self.w - st_offset) / 2 self.c.create_text(xp, yst + 30, text='Mileage (km x 1000)') else: self.c.create_line(xst, yst, xst, st_offset) self.c.create_text(xst, st_offset - 30, text='Price') self.c.create_text(xst, st_offset - 15, text='($000)') tick_anchor = [N, E][ax == 'y'] tick_x, tick_y = xst, yst tick_step = ([self.w, self.h][ax == 'y'] - st_offset * 2 * 1.0) / \ (nt - 1) label_offset = 3 for i1, tick in enumerate(atick): x_of, y_of = -label_offset, label_offset if ax == 'y': y_of = int(-i1 * tick_step) else: x_of = int(i1 * tick_step) if draw: self.c.create_text(tick_x + x_of, tick_y + y_of, text=tick, anchor=tick_anchor) x_mini, y_mini = 0, 0 x_maxi, y_maxi = 0, 0 if ax == 'y': x_of += label_offset x_mini, x_maxi = 8, self.w - st_offset * 2 # Remember what y coord this grid line is at. if i1 == 0: self.y_grid = [] self.y_grid.append(tick_y + y_of) else: y_of -= label_offset y_mini, y_maxi = -8, st_offset * 2 - self.h # Remember what x coord this grid line is at. if i1 == 0: self.x_grid = [] self.x_grid.append(tick_x + x_of) if draw: # Draw the little solid tick, next to the axis. self.c.create_line(tick_x + x_of, tick_y + y_of, tick_x + x_of + x_mini, tick_y + y_of + y_mini) # Draw a dashed grid line, across the entire graph. self.c.create_line(tick_x + x_of, tick_y + y_of, tick_x + x_of + x_maxi, tick_y + y_of + y_maxi, dash=(1, 3)) def car_points(self, draw=True): "Plot the cars themselves." # 199 215 151 151 199 224 230 162 157 250 224 167 178 165 192 249 200 216 204 204 204 191 173 158 color_order = ['#c7d797', '#97c7e0', '#e6a29d', '#fae0a7', '#b2a5c0', '#f9c8d8', '#bfad9e', '#cccccc'] #color_order = ['#98df8a', '#dbdb8d', '#aec7e8', '#c9acd4', '#f7b6d2', # '#ffbb80', '#dc9b8d', '#e9ab17', '#dddddd'] # Those colors above aren't saturated enough. Saturate them more. color_order = map(lambda x: resaturate(x, -80), color_order) # Change color depending on year. cy = dict() for i1, year in enumerate(reversed(sorted(set(self.u.all_year)))): cy[year] = color_order[-1] if i1 < len(color_order): cy[year] = color_order[i1] i1 = -1 # Tuples of (index into self.u.all_* arrays, x position, y position). self.ov_dict = dict() if draw: self.c.focus_set() self.c.bind('<Button-1>', func=self.zoom) self.c.bind('<Button-2>', func=self.unzoom) self.c.bind('<Left>', func=self.left_key) self.c.bind('<Right>', func=self.right_key) self.c.bind('<Up>', func=self.up_key) self.c.bind('<Down>', func=self.down_key) legend = set() osz = 3 + self.zoom_level * 1 # Total vehicle count, and vehicles which pass the filter count. self.vcount = self.fcount = 0 for year, km, price in zip(self.u.all_year, self.u.all_km, self.u.all_price): x, y = self.xyp(km, price) i1 += 1 if x < self.x_grid[0] or x > self.x_grid[-1] or \ y > self.y_grid[0] or y < self.y_grid[-1]: continue self.vcount += 1 legend.add((year, cy[year])) filtered = False if not re.search(self.filter, self.u.all_descr[i1], re.I): filtered = True # If a data point is filtered out, make its outline reflect its # model year, and fill it with white. # # Else, make its outline and fill color reflect the model year, and # upon mouseover, make it entirely red. ov = self.c.create_oval(x-osz, y-osz, x+osz, y+osz, outline=cy[year], activeoutline=['red', cy[year]][filtered], fill=[cy[year], 'white'][filtered], activefill=['red', 'white'][filtered], ) self.ov_dict[ov] = (i1, x, y, cy[year], filtered) # If a data point is filtered out, mousing over it does nothing, # and also, lower it behind everything else. if filtered: self.c.lower(ov) else: self.fcount += 1 if draw: use_tag = 'Tag %d' % i1 self.c.addtag_withtag(use_tag, ov) self.c.tag_bind(use_tag, sequence='<Enter>', func=self.mouseover) self.c.tag_bind(use_tag, sequence='<Leave>', func=self.mouseoff) self.c.tag_bind(use_tag, sequence='<Button-1>', func=self.select) if draw: # OK, add a legend for every year that's displayed. i1 = 0 for yr, color in reversed(sorted(legend)): xp, yp = self.x_grid[-1] + 10, self.y_grid[-1] + 15 * i1 self.c.create_oval(xp-osz, yp-osz, xp+osz, yp+osz, outline=color, fill=color) self.c.create_text(xp + 8, yp, text=str(yr), anchor=W) i1 += 1 # And, add a title. tistr = 'Vehicle count: %d' % self.vcount if self.fcount != self.vcount: tistr = 'Filtered vehicle count: %d' % self.fcount xp = (self.x_grid[0] + self.x_grid[-1]) / 2 yp = self.y_grid[-1] - 30 self.c.create_text(xp, yp, text=tistr, font=('Helvetica', '16')) zstr1 = 'Click on a blank graph location to zoom in' zstr2 = 'Right click to zoom out' if self.zoom_level == 0: zstr = zstr1 elif self.zoom_level == 2: zstr = zstr2 else: zstr = zstr1 + ', or r' + zstr2[1:] self.c.create_text(xp, yp + 16, text=zstr, font=('Helvetica', '14')) def mouseover(self, event): oval = event.widget.find_closest(event.x, event.y)[0] # XXX Sometimes, the closest widget is an axis grid line, not an oval. # Need to handle this correctly eventually. if oval not in self.ov_dict: return self.is_hovering = True ind, x, y, color, filtered = self.ov_dict[oval] # Figure out how high the box needs to be by creating the text off- # graph, then getting its bbox and deleting it. w = 200 de_text = self.u.all_descr[ind] deobj = self.c.create_text(self.w + 3, self.h + 3, text=de_text, anchor=N+W, width=w-6, font=('Helvetica', '14')) bbox = self.c.bbox(deobj) self.c.delete(deobj) h = 18 + bbox[3] - bbox[1] border = 5 if x > self.xmid: x -= (w + border) else: x += border if y > self.ymid: y -= (h + border) else: y += border self.re = list() self.re.append(self.c.create_rectangle(x, y, x + w, y + h, fill=resaturate(color, 50))) pr_text = '$%s' % self.u.commafy(self.u.all_price[ind]) self.re.append(self.c.create_text(x + 3, y + 3, text=pr_text, anchor=N+W, font=('Helvetica', '10'))) km_text = '%skm' % self.u.commafy(self.u.all_km[ind]) self.re.append(self.c.create_text(x + w - 3, y + 3, text=km_text, anchor=N+E, font=('Helvetica', '10'))) wh_text = self.u.all_wherestr[ind] if wh_text[0].isdigit(): wh_text += ' away' self.re.append(self.c.create_text(x + w/2, y + 3, text=wh_text, anchor=N, font=('Helvetica', '10'))) self.re.append(self.c.create_text(x + 3, y + 16, text=de_text, anchor=N+W, width=w-6, font=('Helvetica', '14'))) def set_filter(self, st): "Given a string 'st', filter ovals whose description doesn't match." self.filter = st self.replot() def mouseoff(self, event): "Code for mousing off a data point." # The tooptip rectangle and all its sub-objects need to be destroyed. map(self.c.delete, self.re) # Also, need to note that we're no longer over an oval -- that way, # Button-1 events will cause a zoom, rather than launching a web page. self.is_hovering = False def _zoom_animation(self): import time from math import tanh scale = 5 for i1 in range(-scale, scale+1): self.replot(zlfrac=0.5 + 0.5*tanh(i1*2.0/scale)/tanh(2.0)) self.c.update() def zoom(self, event): # Only zoom in if we're actually within the graph boundaries. if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]: return if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]: return # Don't zoom if we're hovering over a data point: let the web browser # event handler operate. if self.is_hovering: return # Don't zoom in more than twice. if self.zoom_level >= 2: return # Find the grid square which we're inside. for i1 in range(len(self.x_grid) - 1): if event.x <= self.x_grid[i1 + 1]: xgrid = i1 + 1 break for i1 in range(len(self.y_grid) - 1): if event.y >= self.y_grid[i1 + 1]: ygrid = i1 + 1 break self.zoom_level += 1 zl = self.zoom_level # Make the limits of the new graph be those of the grid square which # was clicked inside. self.km[zl] = (self.xtick[xgrid-1], self.xtick[xgrid]) self.price[zl] = (self.ytick[ygrid-1], self.ytick[ygrid]) if zl == 1: self.zoom_price_start = self.u.axis(*self.price[0])[:2] self.zoom_km_start = self.u.axis(*self.km[0])[:2] else: self.zoom_price_start = self.price[zl - 1] self.zoom_km_start = self.km[zl - 1] self.zoom_price_end = self.price[zl] self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def unzoom(self, event): # If already at maximum zoom, nothing to be done. if self.zoom_level == 0: return # If not clicking inside graph boundaries, don't unzoom. if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]: return if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]: return self.zoom_level -= 1 zl = self.zoom_level self.zoom_price_start = self.price[zl + 1] self.zoom_km_start = self.km[zl + 1] if zl == 0: self.zoom_price_end = self.u.axis(*self.price[0])[:2] self.zoom_km_end = self.u.axis(*self.km[0])[:2] else: self.zoom_price_end = self.price[zl] self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def left_key(self, event): zl = self.zoom_level if zl == 0: return # If at left edge already, don't scroll. kz = self.km[zl] if self.km[0][0] > kz[0]: return self.zoom_price_start = self.zoom_price_end = self.price[zl] self.zoom_km_start = kz self.km[zl] = (kz[0] - (kz[1] - kz[0]), kz[0]) self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def right_key(self, event): zl = self.zoom_level if zl == 0: return # If at right edge already, don't scroll. kz = self.km[zl] if self.km[0][1] < kz[1]: return self.zoom_price_start = self.zoom_price_end = self.price[zl] self.zoom_km_start = kz self.km[zl] = (kz[1], kz[1] + (kz[1] - kz[0])) self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def down_key(self, event): zl = self.zoom_level if zl == 0: return # If at bottom edge already, don't scroll. pz = self.price[zl] if self.price[0][0] > pz[0]: return self.zoom_km_start = self.zoom_km_end = self.km[zl] self.zoom_price_start = pz self.price[zl] = (pz[0] - (pz[1] - pz[0]), pz[0]) self.zoom_price_end = self.price[zl] self._zoom_animation() self.replot() def up_key(self, event): zl = self.zoom_level if zl == 0: return # If at top edge already, don't scroll. pz = self.price[zl] if self.price[0][1] < pz[1]: return self.zoom_km_start = self.zoom_km_end = self.km[zl] self.zoom_price_start = pz self.price[zl] = (pz[1], pz[1] + (pz[1] - pz[0])) self.zoom_price_end = self.price[zl] self._zoom_animation() self.replot() def select(self, event): "Open a web page, when a data point has been clicked on." oval = event.widget.find_closest(event.x, event.y)[0] # XXX As above, sometimes the closest widget is a grid line, not an # oval. Need to handle this correctly, eventually. if oval not in self.ov_dict: return ind, xp, yp, color, filtered = self.ov_dict[oval] webbrowser.open(self.u.all_alink[ind])
class SudokuUI(Frame): def __init__(self, parent, game): self.game = game self.parent = parent Frame.__init__(self, parent) self.row, self.col = 0, 0 self.__initUI() def __initUI(self): self.parent.title("Sudoku") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) self.__draw_grid() self.__draw_puzzle() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): for i in xrange(10): color = "blue" if i % 3 == 0 else "gray" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") for i in xrange(9): for j in xrange(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __clear_answers(self): self.game.start() self.canvas.delete("victory") self.__draw_puzzle() def __cell_clicked(self, event): if self.game.game_over: return x, y = event.x, event.y if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN): self.canvas.focus_set() row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.puzzle[row][col] == 0 or self.game.puzzle[row][ col] != self.game.start_puzzle[row][col]: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() if self.game.check_win(): self.__draw_victory() def __draw_victory(self): x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You win!", tags="winner", fill="white", font=("Arial", 32))
class CraterViz(Tk): """ Visualization class using Tkinter to build objects and track them on a canvas """ def __init__(self, surface): Tk.__init__(self) self.title("Crater Density Visualization") self.surface = surface self.craters = {} fr = Frame(self) fr.pack() self.canvas = Canvas(fr, height = 580, width = 500) self.canvas.pack() self.init_ui() self.counter = 0; self.text_year = None self.text_craters = None #Builds canvas and adds the craters to it def init_ui(self): self._create_grid(self.canvas) self.canvas.pack() counter = 1 for crater in self.surface.get_all_craters(): self.after(counter * 100, self._add_crater, crater) counter += 1 #Creates the grid on the canvas def _create_grid(self, canvas): """ Create 10km Grid """ for i in range(50): canvas.create_line(10 * i, 0, 10 * i, 500, fill="#eee") canvas.create_line(0, 10 * i, 500, 10 * i, fill="#eee") #Adds a single crater to the map def _add_crater(self, crater): x, y = crater.get_location() outer_left = x - (25 * 1.2) outer_right = x + (25 * 1.2) outer_top = y - (25 * 1.2) outer_bottom = y + (25 * 1.2) outer = self.canvas.create_oval( outer_left, outer_top, outer_right, outer_bottom, outline="#f11", fill="#1f1", width=2) inner_left = x - 25 inner_right = x + 25 inner_top = y - 25 inner_bottom = y + 25 inner = self.canvas.create_oval( inner_left, inner_top, inner_right, inner_bottom, outline="#ccc", fill="green", width=2) craters_to_obliterate = self._find_obliterated_craters(crater) for obliterated in craters_to_obliterate: self._obliterate_crater(obliterated) self.craters[crater] = (x, y, inner, outer) self.counter += 1 self._update_hud(self.counter, len(self.craters)) #Removes crater from surface def _obliterate_crater(self, crater): x, y, inner, outer = self.craters[crater] del self.craters[crater] self.canvas.delete(inner) self.canvas.delete(outer) #Finds all Craters that need to be removed def _find_obliterated_craters(self, new_crater): obliterated_craters = [] #Check if other craters are within cover radius cover_radius = new_crater.get_covering_radius() for crater in self.craters: if cover_radius > self._get_distance(crater, new_crater): obliterated_craters.append(crater) return obliterated_craters #Gets the distance between crater centers def _get_distance(self, crater1, crater2): x1, y1 = crater1.get_location() x2, y2 = crater2.get_location() return math.sqrt((x1 - x2)**2 + (y1 - y2)**2) #Updates the heads up display on the bottom of the canvas def _update_hud(self, year, craters): if self.text_year: self.canvas.delete(self.text_year) self.text_year = self.canvas.create_text(480, 560, anchor="e", text="Year: "+str(year)+"000") if self.text_craters: self.canvas.delete(self.text_craters) self.text_craters = self.canvas.create_text(20, 560, anchor="w", text="Craters: "+str(craters))
class PhyUI(): def callback_switcher(self): """ Callback function for switching status between 'freezed' and 'on going'. """ play_ref = self.button_play if not self.locked : play_ref.config(text = "Play") self.locked = True else: play_ref.config(text = "Freeze") self.locked = False def keyevent_up_press(self, event): """ Callback for pressing up key. """ self.mouse_lock = True self.selected_user_accel_factor[0] = 1 def keyevent_up_release(self, event): """ Callback for releasing up key. """ self.mouse_lock = False self.selected_user_accel_factor[0] = 0 def keyevent_down_press(self, event): """ Callback for pressing down key. """ self.mouse_lock = True self.selected_user_accel_factor[1] = 1 def keyevent_down_release(self, event): """ Callback for releasing down key. """ self.mouse_lock = False self.selected_user_accel_factor[1] = 0 def keyevent_left_press(self, event): """ Callback for pressing left key. """ self.mouse_lock = True self.selected_user_accel_factor[2] = 1 def keyevent_left_release(self, event): """ Callback for releasing left key. """ self.mouse_lock = False self.selected_user_accel_factor[2] = 0 def keyevent_right_press(self, event): """ Callback for pressing right key """ self.mouse_lock = True self.selected_user_accel_factor[3] = 1 def keyevent_right_release(self, event): """ Callback for releasing right key """ self.mouse_lock = False self.selected_user_accel_factor[3] = 0 def __init__(self, root_handle, canvas_width, canvas_height): """ Setup the whole application.""" self.locked = True # True for freeze. self.mouse_lock = False # True for locking the mouse behavior. self.selected = None # What ball is selected now? self.selected_user_accel_factor = [0, 0, 0, 0] # Acceleration from user's keypress event self.selected_user_accel_val = [Vect2D(0, 15), Vect2D(0, -5), Vect2D(-5, 0), Vect2D(5, 0)] self.circles = [] # Reference to all the balls. # Initialize the main variables for the application self.frm_main = Frame(root_handle) self.frm_side_top = LabelFrame(root_handle, text = "Realtime Parameters:") self.frm_side_bot = Frame(root_handle) # Setup the frames self.canv_width = canvas_width self.canv_height = canvas_height self.canvas_base = Vect2D(0, self.canv_height) self.canvas = Canvas( self.frm_main, width = self.canv_width, height = self.canv_height, bg = "#cccccc") # Setup the canvas self.canvas.bind_all("<KeyPress-w>", self.keyevent_up_press) self.canvas.bind_all("<KeyRelease-w>", self.keyevent_up_release) self.canvas.bind_all("<KeyPress-a>", self.keyevent_left_press) self.canvas.bind_all("<KeyRelease-a>", self.keyevent_left_release) self.canvas.bind_all("<KeyPress-d>", self.keyevent_right_press) self.canvas.bind_all("<KeyRelease-d>", self.keyevent_right_release) self.canvas.bind_all("<KeyPress-s>", self.keyevent_down_press) self.canvas.bind_all("<KeyRelease-s>", self.keyevent_down_release) # Setup all keys self.button_play = Button(self.frm_side_bot, text = "Play", command = self.callback_switcher) self.button_add = Button(self.frm_side_bot, text = "Exit", command = root_handle.quit) # Setup all the buttons side_names = ["Mass", "Positioin", "Velocity", "Acceleration"] self.side_label = [] self.side_entry = [] for name in side_names: self.side_label.append(Label(self.frm_side_top, text = name + ":")) self.side_entry.append(Label(self.frm_side_top, width = 20)) # Setup information area located on the sidebar self.frm_main.grid(row = 0, column = 0, rowspan = 2) self.frm_side_top.grid(row = 0, column = 1, sticky = "S") self.frm_side_bot.grid(row = 1, column = 1, sticky = "S") self.canvas.grid(row = 0, column = 0, columnspan = 2) self.button_play.grid(row = 1, column = 0, sticky = "E") self.button_add.grid(row = 1, column = 1, sticky = "W") for i in xrange(len(self.side_label)): self.side_label[i].grid(row = i, column = 0) self.side_entry[i].grid(row = i, column = 1) # Build up the layout def set_viewport(self, math_bl, math_tr): """ Set the translation rate. You should call this before calling trans or rev_trans. """ self.scale_factor = Vect2D( self.canv_width / float(math_tr.x - math_bl.x), -self.canv_height / float(math_tr.y - math_bl.y)) self.math_base = math_bl def trans(self, pos): """ Translation (from math coord to canvas coord).""" return (pos - self.math_base).scale(self.scale_factor) + \ self.canvas_base def rev_trans(self, pos): """ Reverse translation (from canvas coord to math coord).""" return (pos - self.canvas_base).rev_scale(self.scale_factor) + \ self.math_base def canvas_refresh(self, id, vertexes): """ Refresh the canvas """ self.canvas.coords(id, vertexes) def update_side_bot(self): """ Update the information posted on the side bar.""" if self.selected: self.side_entry[0].config(text = str(self.selected.mass)) self.side_entry[1].config(text = self.selected.shift.get_str()) self.side_entry[2].config(text = self.selected.velo.get_str()) self.side_entry[3].config(text = self.selected.accel.get_str()) else: for i in xrange(4): self.side_entry[i].config(text = "") def create_circle(self, vertexes): """ Create a circle graphically and return the id of the object. """ return self.canvas.create_oval( vertexes, fill="white" ) def create_line(self, vertexes): """ Create a line graphically and return the id of the object.""" return self.canvas.create_line(vertexes) def register_trigger(self, obj, real_interval, math_interval): """ Call this for hooking any simulated objects.""" self.canvas.after( real_interval, obj.refresh, real_interval, math_interval)
class SudokuUI(Frame): # Frame is a rectangular region on a screen """ The Tkinter UI, responsible for drawing the board and accepting user input """ def __init__(self, parent, game): self.game = game Frame.__init__(self, parent) self.parent = parent # all widgets belong to a parent self.row, self.col = -1, -1 # initialize row and col to use later self.__initUI() # calls the initUI function def __initUI(self): self.parent.title("Sudoku") # our parent window will be called Sudoku self.pack( fill=BOTH, expand=1 ) # Frame attribute, organizes geometry relative to parent, fill options: both, none, x, y self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) # canvas attribute, helps display our board clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) # Clear button is at the bottom and fills the space self.__draw_grid() # helper functions self.__draw_puzzle() self.canvas.bind( "<Button-1>", self.__cell_clicked ) # binds Button-1 to a callback, another method: cell_clicked # in Tkinter, Button-1 is a default left mouse click self.canvas.bind("<Key>", self.__key_pressed) # binds the key (guesed number) to the key presseed method def __draw_grid( self ): # make the sudoku layout, do all private functions take self and then other potential arguments? """ Draws grid divided with blue lines into 3x3 squares """ for i in xrange(10): color = "blue" if i % 3 == 0 else "gray" # blue lines if divisible by 3 # draw vertical lines x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line( x0, y0, x1, y1, fill=color ) # draw the vertical lines coordinates are (x0, y0) (x1, y1) # draw horizontal lines x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") # delete old numbers? for i in xrange(9): for j in xrange(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 # in the middle of the applicable cell y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: # you set these variables as 0 first in init x0 = MARGIN + self.col * SIDE + 1 # what does -1 do to these variables? y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __draw_victory(self): # creates an oval/circle x0 = y0 = MARGIN + SIDE * 2 # upper left box of circle starts margin + 2 rows in x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 # middle of the circle self.canvas.create_text(x, y, text="You win!", tags="victory", fill="white", font=("Arial", 32)) def __cell_clicked(self, event): # event parameter: gives us x&y coordinates of where user clicked if self.game.game_over: return # do nothing if game is over x, y = event.x, event.y if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN: # if our puzzle grid is clicked self.canvas.focus_set() # focus_set: move focus to a widget # get row and col numbers from x, y coordinates row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE # if cell was selected already, another click should de-select it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 # I assume -1 means de-selecting? elif self.game.puzzle[row][col] == 0: # otherwise, grab corresponding cell self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": # where does event.char come from? tkinter? self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() if self.game.check_win(): # every time you enter in a number, the game checks to see if you have won self.__draw_victory() def __clear_answers(self): self.game.start() self.canvas.delete("victory") # remove the victory circle self.__draw_puzzle()
class main: def __init__(self,master): self.frame = Frame(master) self.frame.pack(fill="both", expand=True) self.canvas = Canvas(self.frame, width=300, height=300) self.canvas.pack(fill="both", expand=True) self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue') self.label.pack(fill="both", expand=True) self.frameb=Frame(self.frame) self.frameb.pack(fill="both", expand=True) self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple') self.Start1.pack(fill="both", expand=True, side=RIGHT) self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white') self.Start2.pack(fill="both", expand=True, side=LEFT) self._board() def start1(self): self.canvas.delete(ALL) self.label['text']=('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.sgplayer) self._board() self.TTT=[[0,0,0],[0,0,0],[0,0,0]] self.i=0 self.j=False def start2(self): self.canvas.delete(ALL) self.label['text']=('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.dgplayer) self._board() self.TTT=[[0,0,0],[0,0,0],[0,0,0]] self.i=0 self.j=False self.trigger=False def end(self): self.canvas.unbind("<ButtonPress-1>") self.j=True def _board(self): self.canvas.create_rectangle(0,0,300,300, outline="black") self.canvas.create_rectangle(100,300,200,0, outline="black") self.canvas.create_rectangle(0,100,300,200, outline="black") def sgplayer(self,event): for k in range(0,300,100): for j in range(0,300,100): if event.x in range(k,k+100) and event.y in range(j,j+100): if self.canvas.find_enclosed(k,j,k+100,j+100)==(): if self.i%2==0: X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black") self.TTT[Y1][X1]+=1 self.i+=1 else: X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[Y1][X1]+=9 self.i+=1 self.check() def dgplayer(self,event): for k in range(0,300,100): for j in range(0,300,100): if self.i%2==0: if event.x in range(k,k+100) and event.y in range(j,j+100): if self.canvas.find_enclosed(k,j,k+100,j+100)==(): X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black") self.TTT[Y1][X1]+=1 self.i+=1 self.check() self.trigger=False else: print(self.i) self.check() print("checked") self.AIcheck() print("AIchecked") self.trigger=False def check(self): #horizontal check for i in range(0,3): if sum(self.TTT[i])==27: self.label['text']=('2nd player wins!') self.end() if sum(self.TTT[i])==3: self.label['text']=('1st player wins!') self.end() #vertical check #the matrix below transposes self.TTT so that it could use the sum fucntion again self.ttt=[[row[i] for row in self.TTT] for i in range(3)] for i in range(0,3): if sum(self.ttt[i])==27: self.label['text']=('2nd player wins!') self.end() if sum(self.ttt[i])==3: self.label['text']=('1st player wins!') self.end() #check for diagonal wins if self.TTT[1][1]==9: if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] : self.label['text']=('2nd player wins!') self.end() if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] : self.label['text']=('2nd player wins!') self.end() if self.TTT[1][1]==1: if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] : self.label['text']=('1st player wins!') self.end() if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] : self.label['text']=('1st player wins!') self.end() #check for draws if self.j==False: a=0 for i in range(0,3): a+= sum(self.TTT[i]) if a==41: self.label['text']=("It's a pass!") self.end() def AIcheck(self): #This is built on the self.check function self.ttt=[[row[i] for row in self.TTT] for i in range(3)] #DEFENSE #this is the horizontal checklist for h in range(0,3): k=0 j=0 if sum(self.TTT[h])==2: while k <3: if k==h: while j <3: if self.trigger==False: if self.TTT[k][j]==0: self.cross(j,k) break j+=1 k+=1 #this is the vertical checklist for h in range(0,3): k=0 j=0 if sum(self.ttt[h])==2: while k <3: if k==h: while j <3: if self.trigger==False: if self.ttt[k][j]==0: self.cross(k,j) break j+=1 k+=1 #this is the diagonal checklist if self.TTT[1][1]==1: if self.TTT[0][0]==1: if self.trigger==False: if self.TTT[2][2]==0: self.cross(2,2) if self.TTT[0][2]==1: if self.trigger==False: if self.TTT[2][0]==0: self.cross(0,2) if self.TTT[2][0]==1: if self.trigger==False: if self.TTT[0][2]==0: self.cross(2,0) if self.TTT[2][2]==1: if self.trigger==False: if self.TTT[0][0]==0: self.cross(0,0) if self.TTT[1][1]==0: if self.trigger==False: self.cross(1,1) self.trigger=True else: if self.trigger==False: self.randmove() def cross(self, k, j): # k is the x coords # j is the y coords X=(200*k+100)/2 Y=(200*j+100)/2 X1=int(k) Y1=int(j) self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[Y1][X1]+=9 self.check() self.i+=1 self.trigger=True def randmove(self): while True: k=(randint(0,2)) j=(randint(0,2)) if self.TTT[j][k]==0: X=(200*k+100)/2 Y=(200*j+100)/2 self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[j][k]+=9 self.check() self.i+=1 self.trigger=True break else: k=(randint(0,2))*100 j=(randint(0,2))*100
class World(Tk): # def __init__(self,filename=None,block=50,debug=True,delay=0.25,image=False,width=10,height=10): def __init__(self, filename=None, block=50, debug=True, delay=0.25, image=True, width=10, height=10): Tk.__init__(self) self.title("") arg, self.width, self.height = block, width, height self.photos = [ PhotoImage(file=(k + ".gif")) for k in ["east", "north", "west", "south"] ] self.beepers, self.ovals, self.numbers, self.robots, self.walls = {},{},{},{},{} self.m, self.n, self.t, self.delay = arg * (width + 3), arg * ( height + 3), arg, delay self.debug, self.useImage = debug, image a, b, c = self.t + self.t / 2, self.m - self.t - self.t / 2, self.n - self.t - self.t / 2 self.canvas = Canvas(self, bg="white", width=self.m, height=self.n) self.canvas.pack() count = 1 for k in range(2 * self.t, max(self.m, self.n) - self.t, self.t): if k < b: self.canvas.create_line(k, c, k, a, fill="red") self.canvas.create_text(k, c + self.t / 2, text=str(count), font=("Times", max(-self.t * 2 / 3, -15), "")) if k < c: self.canvas.create_line(b, k, a, k, fill="red") self.canvas.create_text(a - self.t / 2, self.n - k, text=str(count), font=("Times", max(-self.t * 2 / 3, -15), "")) count += 1 self.canvas.create_line(a, c, b, c, fill="black", width=3) self.canvas.create_line(a, a, a, c, fill="black", width=3) if filename is not None: self.readWorld(filename) self.refresh() def readWorld(self, filename): try: infile = open("worlds\\%s.wld" % filename, "r") except IOError: try: infile = open("worlds/%s.wld" % filename, "r") except IOError: infile = open(filename, "r") text = infile.read().split("\n") infile.close() for t in text: if t.startswith("eastwestwalls"): s = t.split(" ") y, x = int(s[1]), int(s[2]) self.addWall(x, y, -1, y) if t.startswith("northsouthwalls"): s = t.split(" ") x, y = int(s[1]), int(s[2]) self.addWall(x, y, x, -1) if t.startswith("beepers"): s = t.split(" ") y, x, n = int(s[1]), int(s[2]), int(s[3]) if n is infinity: self.addInfiniteBeepers(x, y) else: for k in range(n): self.addBeeper(x, y) def pause(self): sleep(self.delay) def isBeeper(self, x, y): return (x, y) in self.beepers.keys() and not self.beepers[(x, y)] == 0 def countRobots(self, x, y): if (x, y) not in self.robots.keys(): return 0 return len(self.robots[(x, y)]) def crash(self, x1, y1, x2, y2): if 0 in (x1, y1, x2, y2): return True if (x2, y2) in self.walls.keys() and (x1, y1) in self.walls[(x2, y2)]: return True if (x1, y1) in self.walls.keys() and (x2, y2) in self.walls[(x1, y1)]: return True return False def addInfiniteBeepers(self, x, y): flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0 self.beepers[(x, y)] = infinity text = "oo" a, b = self.t + x * self.t, self.n - (self.t + y * self.t) t = self.t / 3 if flag: self.ovals[(x, y)] = self.canvas.create_oval(a - t, b - t, a + t, b + t, fill="black") self.numbers[(x, y)] = self.canvas.create_text( a, b, text=text, fill="white", font=("Times", max(-self.t / 2, -20), "")) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def addBeeper(self, x, y): if (x, y) in self.beepers.keys() and self.beepers[(x, y)] is infinity: return flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0 if flag: self.beepers[(x, y)] = 1 else: self.beepers[(x, y)] += 1 text = str(self.beepers[(x, y)]) a, b = self.t + x * self.t, self.n - (self.t + y * self.t) t = self.t / 3 if flag: self.ovals[(x, y)] = self.canvas.create_oval(a - t, b - t, a + t, b + t, fill="black") self.numbers[(x, y)] = self.canvas.create_text( a, b, text=text, fill="white", font=("Times", max(-self.t / 2, -20), "")) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def removeBeeper(self, x, y): if self.beepers[(x, y)] is infinity: return self.beepers[(x, y)] -= 1 flag = self.beepers[(x, y)] is 0 text = str(self.beepers[(x, y)]) if flag: self.canvas.delete(self.ovals[(x, y)]) self.canvas.delete(self.numbers[(x, y)]) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def addWall(self, x1, y1, x2, y2): if not x1 == x2 and not y1 == y2: return if x1 == x2: y1, y2 = min(y1, y2), max(y1, y2) if y1 == -1: y1 = y2 for k in range(y1, y2 + 1): self.walls.setdefault((x1, k), []).append((x1 + 1, k)) a, b = self.t + x1 * self.t + self.t / 2, self.n - ( self.t + k * self.t) + self.t / 2 c, d = self.t + x1 * self.t + self.t / 2, self.n - ( self.t + k * self.t) - self.t / 2 self.canvas.create_line(a, b + 1, c, d - 1, fill="black", width=3) else: x1, x2 = min(x1, x2), max(x1, x2) if x1 == -1: x1 = x2 for k in range(x1, x2 + 1): self.walls.setdefault((k, y1), []).append((k, y1 + 1)) a, b = self.t + k * self.t - self.t / 2, self.n - ( self.t + y1 * self.t) - self.t / 2 c, d = self.t + k * self.t + self.t / 2, self.n - ( self.t + y1 * self.t) - self.t / 2 self.canvas.create_line(a - 1, b, c + 1, d, fill="black", width=3) def draw(self, x, y, d, img): if self.useImage: if img is not None: self.canvas.delete(img) x, y = self.t + x * self.t, self.n - (self.t + y * self.t) photo = self.photos[d / 90] img = self.canvas.create_image(x, y, image=photo) return img else: t, angle = self.t / 2, 120 x, y = self.t + x * self.t, self.n - (self.t + y * self.t) x1, y1 = x + 3**0.5 * t / 2 * cos( radians(d)), y - 3**0.5 * t / 2 * sin(radians(d)) x2, y2 = x + t * cos(radians(d + angle)), y - t * sin( radians(d + angle)) x3, y3 = x + t / 4 * cos(radians(d + 180)), y - t / 4 * sin( radians(d + 180)) x4, y4 = x + t * cos(radians(d - angle)), y - t * sin( radians(d - angle)) if img is not None: self.canvas.delete(img) img = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, fill="blue") return img def erase(self, img): self.canvas.delete(img) def recordMove(self, count, x1, y1, x2, y2): for robot in self.robots[(x1, y1)]: if robot.count == count: self.robots[(x1, y1)].remove(robot) self.robots.setdefault((x2, y2), []).append(robot) break def lift(self, img): self.canvas.lift(img) def refresh(self): self.canvas.update() self.pause() def register(self, x, y, robot): self.robots.setdefault((x, y), []).append(robot) def remove(self, x, y, robot): self.robots[(x, y)].remove(robot)
class WorldWar(Frame): canvas = None menu = None selected = None selected_2 = None state = SELECT player = PLAYER_ALLY def __init__(self, parent): # IMAGES ######### self.NODE_IMG = [ ImageTk.PhotoImage(Image.open("img/node1.png")), ImageTk.PhotoImage(Image.open("img/node2.png")), ImageTk.PhotoImage(Image.open("img/node3.png")), ImageTk.PhotoImage(Image.open("img/node4.png")), ] self.BG = ImageTk.PhotoImage(Image.open("img/map.png")) self.FLAG_AXIS = ImageTk.PhotoImage(Image.open("img/flag_axis.png")) self.FLAG_ALLY = ImageTk.PhotoImage(Image.open("img/flag_ally.png")) self.CANNON = ImageTk.PhotoImage(Image.open("img/cannon.png")) self.FORTRESS = ImageTk.PhotoImage(Image.open("img/fort.png")) ################# Frame.__init__(self, parent) self.parent = parent self.init_ui() self.update_ui() self.update_menu() def init_ui(self): self.parent.title("World War II") self.pack(fill=tk.BOTH, expand=1) self.canvas = Canvas(self, width=WINDOW_W - 200, height=WINDOW_H) # self.canvas.bind("<Motion>",self.motion) self.canvas.bind("<Button-1>", self.click) self.canvas.pack(side=tk.LEFT) def update_ui(self): self.canvas.create_image(0, 0, anchor=tk.NW, image=self.BG) for n in Logic.network: self.canvas.create_image(n.x, n.y, anchor=tk.CENTER, image=self.NODE_IMG[n.rank]) if n.occupant == PLAYER_AXIS: self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_AXIS) if n.occupant == PLAYER_ALLY: self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_ALLY) if n.cannon or n.cannon_time > -1: self.canvas.create_image(n.x - NODE_R[n.rank] - 5, n.y, anchor=tk.E, image=self.CANNON) if n.cannon_time > -1: self.canvas.create_text( n.x - NODE_R[n.rank] - 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NE, text=str(Logic.cannon_makers) ) if n.fortress or n.fortress_time > -1: self.canvas.create_image(n.x + NODE_R[n.rank] + 5, n.y, anchor=tk.W, image=self.FORTRESS) if n.fortress_time > -1: self.canvas.create_text( n.x + NODE_R[n.rank] + 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NW, text=str(Logic.fortress_makers) ) self.canvas.create_text(n.x, n.y + NODE_R[n.rank] + 5, anchor=tk.N, text=str(n.allowed)) if self.selected is not None: self.canvas.create_oval( self.selected.x - NODE_R[self.selected.rank] - 5, self.selected.y - NODE_R[self.selected.rank] - 5, self.selected.x + NODE_R[self.selected.rank] + 5, self.selected.y + NODE_R[self.selected.rank] + 5, width=3, outline="#0000FF", ) for n in Logic.adjacent_levels(self.selected): self.canvas.create_line(self.selected.x, self.selected.y, n.x, n.y, arrow=tk.LAST, dash=(3, 3)) if self.selected_2 is not None: self.canvas.create_oval( self.selected_2.x - NODE_R[self.selected_2.rank] - 5, self.selected_2.y - NODE_R[self.selected_2.rank] - 5, self.selected_2.x + NODE_R[self.selected_2.rank] + 5, self.selected_2.y + NODE_R[self.selected_2.rank] + 5, width=3, outline="#FF0000", ) def update_menu(self): if self.menu is not None: self.menu.destroy() self.menu = Frame(self, width=200, height=WINDOW_H) self.menu.pack(fill=tk.X) plr = Label(self.menu, text=("Player: ALLIES" if self.player is PLAYER_ALLY else "Player: AXIS")) plr.pack(fill=tk.X, padx=5, pady=5) if self.selected_2 is not None: if self.selected_2.cannon_time > -1: txt = "%d moves to build" % (Logic.cannon_ready - self.selected_2.cannon_time) if self.selected_2.cannon: txt = "cannon present" lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.selected_2.fortress_time > -1: txt = "%d moves to build" % (Logic.fortress_ready - self.selected_2.fortress_time) if self.selected_2.fortress: txt = "fortress present" lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) move = Button(self.menu, text="CONFIRM MOVE", command=self.confirm_move) move.pack(fill=tk.X, padx=5, pady=5) PHOTO = ImageTk.PhotoImage(Image.open(self.selected_2.image)) data = Label( self.menu, text=self.selected_2.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM ) data.pack(fill=tk.X, padx=5, pady=5) return if self.state == MOVE: an = Label(self.menu, text="Select another node") an.pack(fill=tk.X, padx=5, pady=5) return if self.selected is not None: if self.selected.cannon_time > -1: txt = "%d moves to build" % (Logic.cannon_ready - self.selected.cannon_time) if self.selected.cannon: txt = "cannon present" lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.selected.fortress_time > -1: txt = "%d moves to build" % (Logic.fortress_ready - self.selected.fortress_time) if self.selected.fortress: txt = "fortress present" lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.player == self.selected.occupant: move = Button(self.menu, text="MOVE", command=self.move) move.pack(fill=tk.X, padx=5, pady=5) if not self.selected.cannon: mk_can = Button(self.menu, text="MAKE CANNON", command=self.mk_cannon) mk_can.pack(fill=tk.X, padx=5, pady=5) if not self.selected.fortress: mk_ft = Button(self.menu, text="MAKE FORTRESS", command=self.mk_fortress) mk_ft.pack(fill=tk.X, padx=5, pady=5) PHOTO = ImageTk.PhotoImage(Image.open(self.selected.image)) data = Label( self.menu, text=self.selected.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM ) data.pack(fill=tk.X, padx=5, pady=5) def confirm_move(self): num = askinteger("Troops:", "Enter number of troops :", parent=self) if num == 0: showerror("Error", "Kuch to hila") else: result = None if self.selected.cannon: if askyesno("Move cannon?", parent=self): result = Logic.move(self.selected, self.selected_2, num, True, 0, 0) else: result = Logic.move(self.selected, self.selected_2, num, False, 0, 0) else: result = Logic.move(self.selected, self.selected_2, num, False, 0, 0) if result[0]: self.next_move() else: showerror("Error", result[1]) self.selected_2 = None self.state = SELECT self.update_ui() self.update_menu() def move(self): self.state = MOVE self.update_ui() self.update_menu() def mk_cannon(self): result = Logic.move(self.selected, None, 0, False, 1, 0) if result[0]: self.next_move() else: showerror("Error", result[1]) def mk_fortress(self): result = Logic.move(self.selected, None, 0, False, 0, 1) if result[0]: self.next_move() else: showerror("Error", result[1]) def click(self, event): if self.state == SELECT: self.selected = get_node_at(event.x, event.y) else: self.selected_2 = get_node_at(event.x, event.y) if self.selected_2 == self.selected: self.selected_2 = None self.update_ui() self.update_menu() def next_move(self): if Logic.network[0].occupant == PLAYER_AXIS: showinfo("Game Ends", "Player AXIS wins!") sys.exit() if Logic.network[17].occupant == PLAYER_ALLY: showinfo("Game Ends", "Player ALLY wins!") sys.exit() self.selected = None self.selected_2 = None self.state = SELECT self.player = PLAYER_AXIS if self.player is PLAYER_ALLY else PLAYER_ALLY self.update_ui() self.update_menu()
def initUI(self, tree, scaling): self.parent.title("MST") self.pack(fill=BOTH, expand=1) canvas = Canvas(self, width=10000, height=10000) #canvas.create_oval(10, 10, 15, 15, outline="red", fill="red", width=1) tempMax1 = 0 tempMax2 = 0 for node in tree.nodes: tempMax1 = max(tempMax1, node.GetLoc()[0]) tempMax2 = max(tempMax2, node.GetLoc()[1]) for x in range(tempMax1 + 1): for y in range(tempMax2 + 1): canvas.create_oval(scaling * (x + 1) - 1, scaling * (tempMax2 - y + 1) - 1, scaling * (x + 1) + 1, scaling * (tempMax2 - y + 1) + 1, outline="black", fill="black", width=1) for edge in tree.edges: point1 = edge.GetPoints()[0] point2 = edge.GetPoints()[1] point3 = edge.GetPoints()[2] canvas.create_oval(scaling * (point1[0] + 1) - 2, scaling * (tempMax2 - point1[1] + 1) - 2, scaling * (point1[0] + 1) + 2, scaling * (tempMax2 - point1[1] + 1) + 2, outline="red", fill="red", width=1) canvas.create_oval(scaling * (point2[0] + 1) - 2, scaling * (tempMax2 - point2[1] + 1) - 2, scaling * (point2[0] + 1) + 2, scaling * (tempMax2 - point2[1] + 1) + 2, outline="red", fill="red", width=1) if point3 != None: point3 = edge.GetPoints()[2] canvas.create_line(scaling * (point1[0] + 1), scaling * (tempMax2 - point1[1] + 1), scaling * (point3[0] + 1), scaling * (tempMax2 - point3[1] + 1), fill="red") canvas.create_line(scaling * (point2[0] + 1), scaling * (tempMax2 - point2[1] + 1), scaling * (point3[0] + 1), scaling * (tempMax2 - point3[1] + 1), fill="red") else: canvas.create_line(scaling * (point1[0] + 1), scaling * (tempMax2 - point1[1] + 1), scaling * (point2[0] + 1), scaling * (tempMax2 - point2[1] + 1), fill="red") canvas.pack(fill=BOTH, expand=1) canvas.update() canvas.postscript(file="graph.6.ps", colormode='color')