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 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)
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)
for i in xrange(3): for j in xrange(i,3): dots[i*3+j] = dot(v[i],v[j]) denom = dots[0]*dots[4] - dots[1]*dots[1] u = (dots[4]*dots[2] - dots[1]*dots[5]) / float(denom) v = (dots[0]*dots[5] - dots[1]*dots[2]) / float(denom) return (u > 0.) and (v > 0.) and (u+v < 1.) window = Tk() canvas = Canvas(window) canvas.pack(fill="both", expand="yes") triangle_item = canvas.create_polygon(triangle, fill='white', outline='black') def moved(event): color = 'green' if is_inside(array([event.x, event.y]), [array(p) for p in triangle]): color = 'red' canvas.itemconfig(triangle_item, fill=color) def clicked(event): global selected_corner, point_color, point_draw position = array([event.x, event.y]) point_color = 'red' point_draw = True if is_inside(position, [array(p) for p in triangle]): point_color = 'green' distances = [dot(position-array(p), position-array(p)) for p in triangle]
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 App: def __init__(self, master): self.master = master self.file = 'grid.csv' self.ownZepName = "Jack" 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) labelFont = tkFont.Font(size = 16) 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 = 20) 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=65) self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10) #Buttons #hoogte self.gemetenHoogteString = StringVar() self.gemetenHoogteString.set(str(100.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) #autopilot TODO string self.automaticFlag = False self.btnAutomaticPilot = Button(controlFrame, text = "Auto-pilot", width = 14, bg = 'gray85', command = lambda: self.toggleAutomaticPilot()) self.btnAutomaticPilot.grid(row = 1, column = 2) self.btnTest = Button(controlFrame, text = "Update", width = 14, bg = 'gray85', command = lambda: self.fetchPhoto()) self.btnTest.grid(row = 3, column = 2) self.automaticString = StringVar() self.automaticString.set("Niet Actief") self.lblAutomatic = Label(controlFrame, textvariable = self.automaticString, font = tkFont.Font(size = 14)) self.lblAutomatic.grid(row = 1, column = 3) #verbinding self.connected = False; self.btnConnect = Button(controlFrame, text = "Verbind", width = 14, bg = 'gray85', command = lambda: self.createClient()) self.btnConnect.grid(row = 2, column = 2) self.connectedString = StringVar() self.connectedString.set("Niet Verbonden") self.lblConnected = Label(controlFrame, textvariable = self.connectedString, font = tkFont.Font(size = 14)) self.lblConnected.grid(row = 2, column = 3) #motorinfo self.lblmotorUpString = Label(controlFrame, text = "MOTOR U: ", fg = "red", font = labelFont) self.lblmotorUpString.grid(row = 0, column = 0) self.lblmotorLeftString = Label(controlFrame, text = "MOTOR L: ", fg = "red", font = labelFont) self.lblmotorLeftString.grid(row = 1, column = 0) self.lblmotorRightString = Label(controlFrame, text = "MOTOR R: ", fg = "red", font = labelFont) self.lblmotorRightString.grid(row = 2, column = 0) self.lblmotorPWMString = Label(controlFrame, text = "PWM U: ", font = labelFont) self.lblmotorPWMString.grid(row = 3, column = 0) self.motorLeftString = StringVar() self.motorLeftString.set("S") self.motorRightString = StringVar() self.motorRightString.set("S") self.motorUpString = StringVar() self.motorUpString.set("S") self.motorPWMString = StringVar() self.motorPWMString.set("100") self.lblmotorUpStringValue = Label(controlFrame, textvariable = self.motorUpString, width = 5, fg = "red", font = labelFont) self.lblmotorUpStringValue.grid(row = 0, column = 1) self.lblmotorLeftStringValue = Label(controlFrame, textvariable = self.motorLeftString, width = 5, fg = "red", font = labelFont) self.lblmotorLeftStringValue.grid(row = 1, column = 1) self.lblmotorRightStringValue = Label(controlFrame, textvariable = self.motorRightString, width = 5, fg = "red", font = labelFont) self.lblmotorRightStringValue.grid(row = 2, column = 1) self.motorPWMStringValue = Label(controlFrame, textvariable = self.motorPWMString, width = 5, font = labelFont) self.motorPWMStringValue.grid(row = 3, column = 1) #self.createClient() #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) #goal original = Image.open('goalPin.png') resized = original.resize((60,60),Image.ANTIALIAS) self.goalImage = ImageTk.PhotoImage(resized) self.makeBackground() self.initZeppelins() #kan interactief gebeuren met invoer als namen en bron in debugvenster typen self.paintCanvas() def initZeppelins(self): self.zeppelins = [] self.goal = (100,100) #self.zeppelins.append(AbstractZeppelin('green', 'Weppelin', self, randomSimu.randomSimulator(self, 'Weppelin', self.goal[0], self.goal[1]))) def requestUpdate(self, n): for z in self.zeppelins: if z.name == n: z.updateInfo() 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 makeBackground(self): #rooster inlezen: f = open("../positioning/"+ str(self.file), 'r') shapesText = f.read() lofl = map(lambda l: l.split(","), shapesText.split("\n")) self.raster = [val.strip() for subl in lofl for val in subl] f.close() nrows = len(lofl) ncol = len(lofl[0]) 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)) 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 #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: 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)) 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) arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y] self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1) self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER) #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: if self.connected == False: 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") else: self.debugPrint("Al verbonden") 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 disconnect(self): self.connected = False self.connectedString.set("Niet verbonden") self.lblConnected.config(fg = "red") def fetchPhoto(self): if not self.connected or self.automaticFlag: return self.client.updateInformation() def moveForward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Voorwaarts vliegen aangevraagd") self.client.flyForward() def moveBackward(self): if not self.connected or self.automaticFlag: return self.debugPrint("Achterwaarts vliegen aangevraagd") self.client.flyBackward() def moveLeft(self): if not self.connected or self.automaticFlag: return self.debugPrint("Links draaien aangevraagd") self.client.turnLeft() def moveRight(self): if not self.connected or self.automaticFlag: return self.debugPrint("Rechts draaien aangevraagd") self.client.turnRight() def moveUp(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omhoog vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpBackward() def moveDown(self): if not self.connected or self.automaticFlag: return self.debugPrint("Omlaag vliegen aangevraagd") if(self.correctieFlag): self.toggleHeightCorrection() self.client.motorUpForward() def horizontalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Horizontale motors stoppen aangevraagd") self.client.stopHorizontalMotors() def verticalOff(self): if not self.connected or self.automaticFlag: return self.debugPrint("Verticale motor stoppen aangevraagd") self.client.motorUpStop() #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() def updateAutomatic(self, info): if info[0]: self.debugPrint(str(info[4])) def updateInfo(self, info): global realHeight if info[0] != -1: self.gemetenHoogteString.set(str(info[0])) self.motorUpString.set(info[1]) if info[1] == "V" or info[1] == "A": self.lblmotorUpString.config(fg = "green") self.lblmotorUpStringValue.config(fg = "green") else: self.lblmotorUpString.config(fg = "red") self.lblmotorUpStringValue.config(fg = "red") self.motorLeftString.set(info[2]) if info[2] == "V" or info[2] == "A": self.lblmotorLeftString.config(fg = "green") self.lblmotorLeftStringValue.config(fg = "green") else: self.lblmotorLeftString.config(fg = "red") self.lblmotorLeftStringValue.config(fg = "red") self.motorRightString.set(info[3]) if info[3] == "V" or info[3] == "A": self.lblmotorRightString.config(fg = "green") self.lblmotorRightStringValue.config(fg = "green") else: self.lblmotorRightString.config(fg = "red") self.lblmotorRightStringValue.config(fg = "red") self.motorPWMString.set(str(math.ceil(info[4]))) self.automaticFlag = info[6] if(not self.automaticFlag): self.automaticString = "Niet Actief" else: self.automaticString = "Actief"
class MainCanvas(object): """ The shapefile displaying device based on TKinter Canvas Attributes ---------- shapes : array The spatial units bbox : array The bounding box: minX, minY, maxX, maxY shp_type : integer The shape types: SHP_TYPE_POINT,SHP_TYPE_LINE,SHP_TYPE_POLYGON root : Tk The Tk Object attributeName : string The attribute name datalist : array The attribute data """ def __init__(self,shapes,bbox,shp_type,root,attributeName,datalist): self.shapes = shapes self.bbox = bbox self.shp_type = shp_type self.root = root self.attributeName = attributeName self.datalist = datalist self.__createCanvas() def __createCanvas(self): """ Create the canvas and draw all the spatial objects """ self.canvasRoot = Toplevel() self.canvasRoot.title(self.attributeName) self.canvasRoot.lower(belowThis = self.root) self.mainCanvas = Canvas(self.canvasRoot, bg = 'black', width = canvasWidth+margin_x, height = canvasHeight+margin_y, scrollregion=('-50c','-50c',"50c","50c")) #Change by Sagar for Full Screen self.canvasRoot.state('zoomed') self.canvasRoot.geometry=("1000x900+0+0") #Change End self.__drawShape() self.mainCanvas.pack() def __drawShape(self): """ Draw all the spatial objects on the canvas """ minX, minY, maxX, maxY = self.bbox[0],self.bbox[1],self.bbox[2],self.bbox[3] # calculate ratios of visualization ratiox = canvasWidth/(maxX-minX) ratioy = canvasHeight/(maxY-minY) # take the smaller ratio of window size to geographic distance ratio = ratiox if ratio>ratioy: ratio = ratioy if self.shp_type == SHP_TYPE_POINT: self.__drawPoints(minX, minY, maxX, maxY, ratio) elif self.shp_type == SHP_TYPE_LINE: self.__drawPolylines(minX, minY, maxX, maxY, ratio) elif self.shp_type == SHP_TYPE_POLYGON: self.__drawPolygons(minX, minY, maxX, maxY, ratio) def __drawPoints(self,minX, minY, maxX, maxY,ratio): """ Draw points on the canvas """ tag_count = 0 # loop through each point for point in self.shapes: #define an empty xylist for holding converted coordinates x = int((point.x-minX)*ratio)+margin_x/2 y = int((maxY-point.y)*ratio)+margin_y/2 _point = self.mainCanvas.create_oval(x-2, y-2, x+2, y+2,outline=point.color, fill=point.color, width=2, tags = self.datalist[tag_count]) self.mainCanvas.tag_bind( _point, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __drawPolylines(self,minX, minY, maxX, maxY,ratio): """ Draw polylines on the canvas """ tag_count = 0 # loop through each polyline for polyline in self.shapes: #define an empty xylist for holding converted coordinates xylist = [] # loops through each point and calculate the window coordinates, put in xylist for j in range(len(polyline.x)): pointx = int((polyline.x[j]-minX)*ratio)+margin_x/2 pointy = int((maxY-polyline.y[j])*ratio)+margin_y/2 xylist.append(pointx) xylist.append(pointy) # loop through each part of the polyline for k in range(polyline.partsNum): #get the end sequence number of points in the part if (k==polyline.partsNum-1): endPointIndex = len(polyline.x) else: endPointIndex = polyline.partsIndex[k+1] # define a temporary list for holding the part coordinates tempXYlist = [] #take out points' coordinates for the part and add to the temporary list for m in range(polyline.partsIndex[k], endPointIndex): tempXYlist.append(xylist[m*2]) tempXYlist.append(xylist[m*2+1]) # create the line _line = self.mainCanvas.create_line(tempXYlist,fill=polyline.color, tags = self.datalist[tag_count]) self.mainCanvas.tag_bind( _line, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __drawPolygons(self,minX, minY, maxX, maxY,ratio): """ Draw polygons on the canvas """ tag_count = 0 for polygon in self.shapes: #define an empty xylist for holding converted coordinates xylist = [] # loops through each point and calculate the window coordinates, put in xylist for point in polygon.points: pointx = int((point.x -minX)*ratio) + +margin_x/0.5 pointy = int((maxY- point.y)*ratio) + +margin_y/5 xylist.append(pointx) xylist.append(pointy) ## print xylist """ polyline.partsIndex is a tuple data type holding the starting points for each part. For example, if the polyline.partsIndex of a polyline equals to (0, 4, 9), and the total points, which is calcuate by len(polyline.points) equals to 13. This means that the polyline has three parts, and the each part would have the points as follows. part 1: p0,p1,p2,p3 part 2: p4,p5,p6,p7,p8 part 3: p9,p10,p11,p12 The xylist would be: xylist = [x0, y0, x1, y1, x2, y2, x3, y3, x4, y4....x12, y12] where xylist[0] = x0 xylist[1] = y0 xylist[2] = x1 xylist[3] = y1 ..... To draw the first part of polyline, we want to get tempXYlist as tempXYlist = [x0, y0, x1, y1, x2, y2, x3, y3] At this time, m is in range(0,4) xylist[m*2] would be is x0(when m=0), x1(when m=1), x2(when m=2), x3(when m=3) xylist[m*2+1] would be is y0(when m=0), y1(when m=1), y2(when m=2), y3(when m=3) """ for k in range(polygon.partsNum): #get the end sequence number of points in the part if (k==polygon.partsNum-1): endPointIndex = len(polygon.points) else: endPointIndex = polygon.partsIndex[k+1] #Define a temporary list for holding the part coordinates tempXYlist = [] tempXlist = [] tempYlist = [] #take out points' coordinates for the part and add to the temporary list for m in range(polygon.partsIndex[k], endPointIndex): tempXYlist.append(xylist[m*2]) tempXYlist.append(xylist[m*2+1]) tempXlist.append (xylist[m*2]) tempYlist.append (xylist[m*2+1]) xMax = max(tempXlist) xMin = min(tempXlist) yMax = max(tempYlist) yMin = min(tempYlist) if xMax == xMin: xMin = xMax - 1 if yMax == yMin: yMin = yMax - 1 tempVar = False #while not tempVar: xPoint = rd.randrange(xMin,xMax) yPoint = rd.randrange(yMin,yMax) tempVar = point_inside_polygon(xPoint,yPoint,tempXYlist) startIndex = polygon.partsIndex[k] #start index for our positive polygon. tempPoints = polygon.points[startIndex: endPointIndex]#we get our temppoints to help use create our polygon using positive data newPolygon = Polygon(tempPoints) #here we create our polygons using positve data area = newPolygon.getArea() # Calculate the area #Sagar Jha center added to calculate centroid of polygon center = newPolygon.getCentroid() xCenter = int((center.x -minX)*ratio) + +margin_x/0.5 yCenter = int((maxY- center.y)*ratio) + +margin_y/5 if area > 0: _polygon = self.mainCanvas.create_polygon(tempXYlist,activefill="blue",fill=polygon.color,outline="blue",tags = self.datalist[tag_count])#creating our polygon outline #print k,_polygon #Michigan Special Condition according to its 2 parts if tag_count == 48: if k==4: _oval = self.mainCanvas.create_oval(xCenter, yCenter,xCenter +5,yCenter+ 5, outline="red",fill="green", width=2,tags = center) dict1[_oval]=[center.x,center.y] else: if k==0: #print "Tag Count: ",tag_count," ",self.mainCanvas.gettags(_polygon)[0] _oval = self.mainCanvas.create_oval(xCenter, yCenter,xCenter +5,yCenter+ 5, outline="red",fill="green", width=2,tags = center) dict1[_oval]=[center.x,center.y] #_oval1 = self.mainCanvas.create_oval(xPoint, yPoint,xPoint +5,yPoint+ 5, outline="red",fill="green", width=2) else: # If it is a hole, fill with the same color as the canvas background color _polygon = self.mainCanvas.create_polygon(tempXYlist,fill="black",outline="black", tags = self.datalist[tag_count]) #self.mainCanvas.tag_bind( _polygon, '<ButtonPress-1>', self.__showAttriInfo) #self.mainCanvas.tag_bind( _oval, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __showAttriInfo(self,event): """ Show attribute information of clicked unit """ widget_id=event.widget.find_closest(event.x, event.y) if widget_id[0] in dict1.keys(): print widget_id[0], dict1[widget_id[0]][0],dict1[widget_id[0]][1] else: print "click!!!!", widget_id print self.attributeName+" is: "+self.mainCanvas.gettags(widget_id)[0]
class PigChaseHumanAgent(GuiAgent): def __init__(self, name, environment, keymap, max_episodes, max_actions, visualizer, quit): self._max_episodes = max_episodes self._max_actions = max_actions self._action_taken = 0 self._episode = 1 self._scores = [] self._rewards = [] self._episode_has_ended = False self._episode_has_started = False self._quit_event = quit super(PigChaseHumanAgent, self).__init__(name, environment, keymap, visualizer=visualizer) def _build_layout(self, root): # Left part of the GUI, first person view self._first_person_header = ttk.Label(root, text='First Person View', font=(None, 14, 'bold')) \ .grid(row=0, column=0) self._first_person_view = ttk.Label(root) self._first_person_view.grid(row=1, column=0, rowspan=10) # Right part, top self._first_person_header = ttk.Label(root, text='Symbolic View', font=(None, 14, 'bold')) \ .grid(row=0, column=1) self._symbolic_view = Canvas(root) self._symbolic_view.configure(width=ENV_BOARD_SHAPE[0]*CELL_WIDTH, height=ENV_BOARD_SHAPE[1]*CELL_WIDTH) self._symbolic_view.grid(row=1, column=1) # Bottom information self._information_panel = ttk.Label(root, text='Game stats', font=(None, 14, 'bold')) self._current_episode_lbl = ttk.Label(root, text='Episode: 0', font=(None, 12)) self._cum_reward_lbl = ttk.Label(root, text='Score: 0', font=(None, 12, 'bold')) self._last_action_lbl = ttk.Label(root, text='Previous action: None', font=(None, 12)) self._action_done_lbl = ttk.Label(root, text='Actions taken: 0', font=(None, 12)) self._action_remaining_lbl = ttk.Label(root, text='Actions remaining: 0', font=(None, 12)) self._information_panel.grid(row=2, column=1) self._current_episode_lbl.grid(row=3, column=1, sticky=W, padx=20) self._cum_reward_lbl.grid(row=4, column=1, sticky=W, padx=20) self._last_action_lbl.grid(row=5, column=1, sticky=W, padx=20) self._action_done_lbl.grid(row=6, column=1, sticky=W, padx=20) self._action_remaining_lbl.grid(row=7, column=1, sticky=W, padx=20) self._overlay = None # Main rendering callback self._pressed_binding = root.bind('<Key>', self._on_key_pressed) self._user_pressed_enter = False # UI Update callback root.after(self._tick, self._poll_frame) root.after(1000, self._on_episode_start) root.focus() def _draw_arrow(self, yaw, x, y, cell_width, colour): if yaw == 0.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .4) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y1, x2, y3, x3, y1, x2, y2, fill=colour) elif yaw == 90.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .6) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y2, x3, y1, x2, y2, x3, y3, fill=colour) elif yaw == 180.: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .5) * cell_width, (y + .6) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y1, x3, y3, x2, y2, fill=colour) else: x1, y1 = (x + .15) * cell_width, (y + .15) * cell_width x2, y2 = (x + .4) * cell_width, (y + .5) * cell_width x3, y3 = (x + .85) * cell_width, (y + .85) * cell_width self._symbolic_view.create_polygon(x1, y3, x2, y2, x1, y1, x3, y2, fill=colour) def _poll_frame(self): """ Main callback for UI rendering. Called at regular intervals. The method will ask the environment to provide a frame if available (not None). :return: """ cell_width = CELL_WIDTH circle_radius = 10 # are we done? if self._env.done and not self._episode_has_ended: self._on_episode_end() # build symbolic view board, _ = self._env._internal_symbolic_builder.build(self._env) if board is not None: board = board.T self._symbolic_view.delete('all') # Remove all previous items from Tkinter tracking width, height = board.shape for x in range(width): for y in range(height): cell_contents = str.split(str(board[x][y]), '/') for block in cell_contents: if block == 'sand': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="orange", tags="square") elif block == 'grass': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="lawn green", tags="square") elif block == 'lapis_block': self._symbolic_view.create_rectangle(x * cell_width, y * cell_width, (x + 1) * cell_width, (y + 1) * cell_width, outline="black", fill="black", tags="square") elif block == ENV_TARGET_NAMES[0]: self._symbolic_view.create_oval((x + .5) * cell_width - circle_radius, (y + .5) * cell_width - circle_radius, (x + .5) * cell_width + circle_radius, (y + .5) * cell_width + circle_radius, fill='pink') elif block == self.name: yaw = self._env._world_obs['Yaw'] % 360 self._draw_arrow(yaw, x, y, cell_width, 'red') elif block == ENV_AGENT_NAMES[0]: # Get yaw of other agent: entities = self._env._world_obs[ENV_ENTITIES] other_agent = list( map(Entity.create, filter(lambda e: e['name'] == ENV_AGENT_NAMES[0], entities))) if len(other_agent) == 1: other_agent = other_agent.pop() yaw = other_agent.yaw % 360 self._draw_arrow(yaw, x, y, cell_width, 'blue') # display the most recent frame frame = self._env.frame if frame is not None: from PIL import ImageTk self._first_person_view.image = ImageTk.PhotoImage(image=frame) self._first_person_view.configure(image=self._first_person_view.image) self._first_person_view.update() self._first_person_view.update() # process game state (e.g., has the episode started?) if self._episode_has_started and time.time() - self._episode_start_time < 3: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text="Get ready to catch the pig!", font=('Helvetica', '18')) self._init_overlay.create_text( 300, 140, text=str(3 - int(time.time() - self._episode_start_time)), font=('Helvetica', '18'), fill="red") self._init_overlay.create_text( 300, 220, width=460, text="How to play: \nUse the left/right arrow keys to turn, " "forward/back to move. The pig is caught if it is " "cornered without a free block to escape to.", font=('Helvetica', '14'), fill="black") self._root.update() elif self._episode_has_ended: if not hasattr(self, "_init_overlay") or not self._init_overlay: self._create_overlay() self._init_overlay.delete("all") self._init_overlay.create_rectangle( 10, 10, 590, 290, fill="white", outline="red", width="5") self._init_overlay.create_text( 300, 80, text='Finished episode %d of %d' % (self._episode, self._max_episodes), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 120, text='Score: %d' % sum(self._rewards), font=('Helvetica', '18')) if self._episode > 1: self._init_overlay.create_text( 300, 160, text='Average over %d episodes: %.2f' % (self._episode, np.mean(self._scores)), font=('Helvetica', '18')) self._init_overlay.create_text( 300, 220, width=360, text="Press RETURN to start the next episode, ESC to exit.", font=('Helvetica', '14'), fill="black") self._root.update() elif hasattr(self, "_init_overlay") and self._init_overlay: self._destroy_overlay() # trigger the next update self._root.after(self._tick, self._poll_frame) def _create_overlay(self): self._init_overlay = Canvas(self._root, borderwidth=0, highlightthickness=0, width=600, height=300, bg="gray") self._init_overlay.place(relx=0.5, rely=0.5, anchor='center') def _destroy_overlay(self): self._init_overlay.destroy() self._init_overlay = None def _on_key_pressed(self, e): """ Main callback for keyboard events :param e: :return: """ if e.keysym == 'Escape': self._quit() if e.keysym == 'Return' and self._episode_has_ended: if self._episode >= self._max_episodes: self._quit() # start the next episode self._action_taken = 0 self._rewards = [] self._episode += 1 self._env.reset() self._on_episode_start() print('Starting episode %d' % self._episode) if self._episode_has_started and time.time() - self._episode_start_time >= 3: if e.keysym in self._keymap: mapped_action = self._keymap.index(e.keysym) _, reward, done = self._env.do(mapped_action) self._action_taken += 1 self._rewards.append(reward) self._on_experiment_updated(mapped_action, reward, done) def _on_episode_start(self): self._episode_has_ended = False self._episode_has_started = True self._episode_start_time = time.time() self._on_experiment_updated(None, 0, self._env.done) def _on_episode_end(self): self._episode_has_started = False self._episode_has_ended = True self._scores.append(sum(self._rewards)) self.visualize(self._episode, 'Reward', sum(self._rewards)) def _on_experiment_updated(self, action, reward, is_done): self._current_episode_lbl.config(text='Episode: %d' % self._episode) self._cum_reward_lbl.config(text='Score: %d' % sum(self._rewards)) self._last_action_lbl.config(text='Previous action: %s' % action) self._action_done_lbl.config(text='Actions taken: {0}'.format(self._action_taken)) self._action_remaining_lbl.config(text='Actions remaining: %d' % (self._max_actions - self._action_taken)) self._first_person_view.update() def _quit(self): self._quit_event.set() self._root.quit() sys.exit()
class DrawingWindow: def __init__(self, width, height, x_min, x_max, y_min, y_max, title, parent=None): self.title = title if parent: self.parent = parent self.top = parent.getWindow(title) else: self.tk = Tk() self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.window_width = width self.window_height = height self.canvas = Canvas(self.top, width=self.window_width, height=self.window_height, background="white") self.canvas.pack() self.x_scale = width / float( x_max - x_min) # multiply an input value by this to get pixels self.y_scale = height / float(y_max - y_min) self.x_min = x_min self.y_min = y_min self.x_max = x_max self.y_max = y_max def scale_x(self, x): return self.x_scale * (x - self.x_min) def scale_y(self, y): return self.window_height - self.y_scale * (y - self.y_min) def draw_point(self, x, y, color="blue", radius=1): window_x = self.scale_x(x) window_y = self.scale_y(y) return self.canvas.create_rectangle(window_x - radius, window_y - radius, window_x + radius, window_y + radius, fill=color, outline=color) def draw_text(self, x, y, label): return self.canvas.create_text(self.scale_x(x), self.scale_y(y), text=label) # font="Arial 20",fill="#ff0000" def draw_poly(self, verts, color="black", outline="black"): return self.canvas.create_polygon( [(self.scale_x(point.x), self.scale_y(point.y)) for point in verts], fill=color, outline=outline) def draw_rect(self, (x1, y1), (x2, y2), color="black"):
def gnor(inp): l=[] orr=andd=[] # dictt=OrderedDict() delimit=['+','.','^'] # for i in delimit: # if(i not in inp): # delimit.remove(i) l=inp.split('+') # print(l) n=len(l) if(n>1): orr=n-1 else: orr=-1 nd=0 temp=[0]*n d=OrderedDict() for i in range(n): if(len(l[i])>1): nd+=len(l[i])-1 d[i+1]=len(l[i])-1 s='' for j in l[i]: if(j!=l[i][-1:]): s+=j+'AND' s+=l[i][-1:] temp[i]=s else: temp[i]=l[i] # print(d) print dictionary with index->no.of ands needed! # val=temp[-1:][0] # s='' # for i in temp: # # if(i!=val): # s+='('+i+')'+' OR ' # s=s[:len(s)-4] # print('OR--'+str(orr)+' AND--'+str(nd)) # print(s) data,data1,data2,data3=[],[],[],[] for j in l: if(len(j)==1): data.append(j) if(len(j)==2): data1.append(j) if(len(j)==3): data2.append(j) if(len(j)==4): data3.append(j) root=Tk() c = Canvas(master=root, width=500, height=450, bd=0, highlightthickness=0) c.master.title('NOR Gates Representation') temp=orr x1,p1=165,70 y1,q1=100,100 x2,p2=195,100 y2,q2=100,100 # c=Canvas(root) # t=Text(root) c.create_line(12,25,33,25) c.create_line(12,38,33,38) c.create_polygon(20,20,33,24,33,39,20,45,fill='#a93226') c.create_oval(33,30,37,35) c.create_text(65,30,text=': NOR') print('nor',d) while(orr>0): if(temp==orr): c.create_line(x1-15,y1+4,x2-4,y2+4) u=0 if(nd==0): y=data[u] u+=1 c.create_text(x1-20,y1,text=y,font=('Purisa',10)) data.remove(y) # if(nd==0): # c.create_oval(x2-4,y1,x2,y1+4) c.create_line(x1-15,y1+15,x2-4,y2+15) # if(nd==0 or len(d)<2): # c.create_oval(x2-4,y1+15,x2,y1+19) if(nd==0 or len(d)<2): y=data[u] u+=1 c.create_text(x1-20,y1+15,text=y,font=('Purisa',10)) data.remove(y) c.create_line(x2,y1-8,x2,y2+24) c.create_polygon(x2-1,y1-8,x2+20,y1,x2+20,y2+17,x2-1,y2+25,fill='#a93226') c.create_oval(x2+21,y1+5,x2+25,y1+9) # c.create_arc(x2-4,y1-8,x2+19,y2+20,start=220,extent=270,fill='black',style=tk.ARC) c.create_line(x2+26,y1+7,x2+44,y1+7) c.create_oval(x2+43,y1+5,x2+47,y1+9) if(orr!=1): c.create_line(x2+44,y1+8,x2+44,y1+50) y1+=50 y2+=50 orr-=1 c.pack() else: x2+=50 x1+=50 u=0 c.create_line(x1-10,y1,x2,y2) # if(nd==0): # c.create_oval(x2-4,y1,x2,y1+4) if(orr==len(data) and len(data)!=0): y=data[u] c.create_text(x1-15,y1+15,text=y,font=('Purisa',10)) data.remove(y) elif(nd==0): y=data[u] c.create_text(x1-15,y1+15,text=y,font=('Purisa',10)) data.remove(y) u+=1 c.create_line(x1-10,y1+15,x2,y2+15) # if(nd==0 or len(d)>=orr): # c.create_oval(x2-4,y1+15,x2,y1+19) c.create_line(x2,y1-8,x2,y2+24) c.create_polygon(x2-1,y1-8,x2+20,y1,x2+20,y2+17,x2-1,y2+25,fill='#a93226') c.create_oval(x2+21,y1+5,x2+25,y1+9) c.create_line(x2+22,y1+10,x2+40,y1+10) c.create_oval(x2+40,y1+5,x2+44,y1+9) if(orr!=1): c.create_line(x2+40,y1+10,x2+40,y1+50) y1+=50 y2+=50 orr-=1 u+=1 c.pack() temp1=nd cnt=1 for i in list(d.keys()): if(d[i]==1): u,v=0,0 y=data1[u] c.create_text(p1-5,q1,text=y[v],font=('Purisa',10)) v+=1 c.create_line(p1,q1,p2-4,q2) c.create_oval(p2-4,q1-2,p2,q1+2) c.create_text(p1-5,q1+15,text=y[v],font=('Purisa',10)) c.create_line(p1,q1+15,p2-4,q2+15) c.create_oval(p2-4,q1+13,p2,q2+17) c.create_line(p2,q1-8,p2,q2+24) c.create_polygon(p2-1,q1-8,p2+20,q1,p2+20,q2+17,p2-1,q2+25,fill='#a93226') c.create_oval(p2+20,q1+4,p2+24,q1+8) if(temp1==nd): c.create_line(p2+24,q1+4,p2+65,q1+4) if(orr<0): c.create_oval(p2+65,q1+2,p2+69,q1+6) else: # c.create_oval(p2+24,q1+4,p2+28,q1+8) c.create_line(p2+24,q1+4,p2+(42*cnt),q1+4) c.create_line(p2+(42*cnt),q1+4,p2+(42*cnt),q1-32) q1+=50 q2+=50 nd-=1 cnt+=1 u+=1 data1.remove(y) c.pack() elif(d[i]==2): u,v=0,0 y=data2[u] c.create_text(p1-5,q1,text=y[v],font=('Purisa',10)) v+=1 c.create_line(p1,q1,p2,q2) c.create_oval(p2-4,q1-2,p2,q1+2) c.create_text(p1-5,q1+9,text=y[v],font=('Purisa',10)) v+=1 c.create_line(p1,q1+9,p2,q2+9) c.create_oval(p2-4,q1+7,p2,q2+11) c.create_text(p1-5,q1+15,text=y[v],font=('Purisa',10)) c.create_line(p1,q1+15,p2,q2+15) c.create_oval(p2-4,q1+13,p2,q2+17) c.create_line(p2,q1-8,p2,q2+24) c.create_polygon(p2-1,q1-8,p2+20,q1,p2+20,q2+17,p2-1,q2+25,fill='#a93226') if(temp1==nd): c.create_oval(p2+20,q1+4,p2+24,q1+8) c.create_line(p2+24,q1+4,p2+54,q1+4) if(orr<0): c.create_oval(p2+54,q1+2,p2+58,q1+6) else: c.create_oval(p2+20,q1+4,p2+24,q1+8) c.create_line(p2+20,q1+4,p2+(42*cnt),q1+8) c.create_line(p2+(42*cnt),q1,p2+(42*cnt),q1-32) q1+=50 q2+=50 nd-=1 cnt+=1 u+=1 data2.remove(y) c.pack() elif(d[i]==3): u,v=0,0 y=data3[u] c.create_text(p1-5,q1,text=y[v],font=('Purisa',5)) v+=1 c.create_line(p1,q1,p2,q2) c.create_text(p1-5,q1+5,text=y[v],font=('Purisa',5)) v+=1 c.create_line(p1,q1+5,p2,q2+5) c.create_text(p1-5,q1+10,text=y[v],font=('Purisa',5)) v+=1 c.create_line(p1,q1+10,p2,q2+10) c.create_text(p1-5,q1+15,text=y[v],font=('Purisa',5)) c.create_line(p1,q1+15,p2,q2+15) c.create_line(p2,q1-8,p2,q2+24) c.create_polygon(p2-1,q1-8,p2+20,q1,p2+20,q1+12,p2,q2+23,fill='#a93226') if(temp1==nd): c.create_oval(p2+20,q1-2,p2+24,q1+2) c.create_line(p2+24,q1,p2+54,q1) if(orr==0): c.create_oval(p2+50,q1-2,p2+54,q1+2) else: c.create_oval(p2+20,q1,p2+24,q1+4) c.create_line(p2+20,q1+2,p2+(42*cnt),q1+2) c.create_line(p2+(42*cnt),q1+2,p2+(42*cnt),q1-34) q1+=50 q2+=50 nd-=1 cnt+=1 u+=1 data3.remove(y) c.pack() c.create_text(215,430,text='Fig. Probable gate diagram',anchor='s') root.mainloop()
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 StlFrame(Frame): def __init__(self, root, scale=1): Frame.__init__(self, root) self.app = root self.gridOffset = 10 self.arrangeMargin = 2 self.centerOnLoad = True self.offsetx = 0 self.offsety = 0 self.scale = scale self.zoom = 1 self.selection = None self.selectable = [] self.itemMap = {} self.canvas = Canvas(self, width=200*self.scale+13, height=200*self.scale+13, bd=2, relief=RIDGE, bg="white") self.canvas.config(takefocus="1") self.canvas.bind("<Key>", self.keyCanvas) self.canvas.bind("<Button-1>", self.clickCanvas) self.canvas.bind("<B1-Motion>", self.dragCanvas) self.canvas.bind("<MouseWheel>", self.wheelCanvas) self.canvas.bind("<Button-4>", self.wheelCanvas) self.canvas.bind("<Button-5>", self.wheelCanvas) self.root = root self.buildarea = [200, 200] self.canvas.grid(row=1,column=1,columnspan=5) self.drawGrid() def keyCanvas(self, event): self.app.setModified() if event.keysym == "Left": self.moveStl(-1, 0) elif event.keysym == "Right": self.moveStl(1, 0) elif event.keysym == "Up": if (event.state & SHIFT_MASK) != 0: self.rotateStl(1) else: self.moveStl(0, 1) elif event.keysym == "Down": if (event.state & SHIFT_MASK) != 0: self.rotateStl(-1) else: self.moveStl(0, -1) def clickCanvas(self, event): self.app.setModified() self.canvas.focus_set() self.startx = event.x/float(self.scale) self.starty = event.y/float(self.scale) itemIdList = self.canvas.find_closest(event.x, event.y) for itemId in itemIdList: if itemId in self.selectable: self.setSelection(itemId) self.app.setSelection(self.itemMap[itemId]) return def dragCanvas(self, event): self.app.setModified() self.canvas.focus_set() x = event.x/float(self.scale) y = event.y/float(self.scale) self.moveStl((x - self.startx), (self.starty - y)) self.startx = x self.starty = y def wheelCanvas(self, event): self.app.setModified() if event.num == 4 or event.delta == 120: self.rotateStl(1) elif event.num == 5 or event.delta == -120: self.rotateStl(-1) def moveStl(self, dx, dy): if self.selection is None: return self.canvas.move(self.selection, dx*self.scale, -dy*self.scale) stlObj = self.itemMap[self.selection] stlObj.deltaTranslation(dx, dy) def rotateStl(self, angle): if self.selection is None: return #self.canvas.move(self.selection, dx, -dy) stlObj = self.itemMap[self.selection] rads = math.radians(angle+stlObj.rotation) cos = math.cos(rads) sin = math.sin(rads) d = [] xMin = yMin = 99999 xMax = yMax = -99999 for x,y in stlObj.hull: xp = (x-stlObj.hxCenter)*cos - (y-stlObj.hyCenter)*sin + stlObj.hxCenter if xp < xMin: xMin=xp if xp > xMax: xMax=xp xp += stlObj.translatex yp = (x-stlObj.hxCenter)*sin + (y-stlObj.hyCenter)*cos + stlObj.hyCenter if yp < yMin: yMin=yp if yp > yMax: yMax=yp yp += stlObj.translatey d.extend(self.transform(xp,self.buildarea[1]-yp)) self.canvas.delete(stlObj.name) self.selectable.remove(self.selection) del self.itemMap[self.selection] itemId = self.canvas.create_polygon(d, fill=hilite, outline="black", tag=stlObj.name, width=3) self.selectable.append(itemId) self.itemMap[itemId] = stlObj self.setSelection(itemId) stlObj.deltaRotation(angle) stlObj.hxSize = xMax-xMin stlObj.hySize = yMax-yMin stlObj.hArea = stlObj.hxSize * stlObj.hySize def setSelection(self, itemId): if itemId not in self.selectable: return if self.selection is not None: self.canvas.itemconfig(self.selection, fill=gray) self.canvas.itemconfig(itemId, fill=hilite) self.selection = itemId def setSelectionByName(self, name): for i in self.itemMap.keys(): if self.itemMap[i].name == name: self.setSelection(i) return def getSelection(self): return self.selection def getSelectedStl(self): if self.selection is None: return None return self.itemMap[self.selection] def drawGrid(self): self.canvas.delete("GRID") ltGray = "#C0C0C0" dkGray = "#808080" yleft = 0 yright = self.buildarea[1]*self.zoom*self.scale if yright > self.buildarea[1]*self.scale: yright = self.buildarea[1]*self.scale for x in range(0, self.buildarea[0]+1, 10): if x%50 == 0: c = dkGray else: c = ltGray x = x*self.zoom*self.scale if x >= 0 and x <= self.buildarea[0]*self.scale: self.canvas.create_line(x+self.gridOffset, yleft+self.gridOffset, x+self.gridOffset, yright+self.gridOffset, fill=c, tags="GRID") xtop = 0 xbottom = self.buildarea[0]*self.zoom*self.scale if xbottom > self.buildarea[0]*self.scale: xbottom = self.buildarea[0]*self.scale for y in range(0, self.buildarea[1]+1, 10): if y%50 == 0: c = dkGray else: c = ltGray y = y*self.zoom*self.scale if y >= 0 and y <= self.buildarea[1]*self.scale: self.canvas.create_line(xtop+self.gridOffset, y+self.gridOffset, xbottom+self.gridOffset, y+self.gridOffset, fill=c, tags="GRID") def addStl(self, stlObject, highlight=False, process=True): self.canvas.delete(stlObject.name) if highlight: col = hilite else: col = gray if self.centerOnLoad and process: dx = (self.buildarea[0]/2) - stlObject.hxCenter dy = (self.buildarea[1]/2) - stlObject.hyCenter stlObject.deltaTranslation(dx, dy) stlObject.applyDeltas() d = [] for x,y in stlObject.hull: d.extend(self.transform(x,self.buildarea[1]-y)) itemId = self.canvas.create_polygon(d, fill=col, outline="black", tag=stlObject.name, width=3) self.selectable.append(itemId) self.itemMap[itemId] = stlObject if highlight: self.setSelection(itemId) def delStl(self): if self.selection is None: return stlObj = self.itemMap[self.selection] self.canvas.delete(stlObj.name) self.selectable.remove(self.selection) del self.itemMap[self.selection] self.selection = None def delAll(self): objs = self.itemMap.values() for o in objs: self.canvas.delete(o.name) self.selectable = [] self.itemMap = {} self.selection = None def commit(self): if self.selection is not None: o = self.itemMap[self.selection] name = o.name else: name = "" objs = self.itemMap.values() self.selectable = [] self.itemMap = {} for o in objs: self.canvas.delete(o.name) o.applyDeltas() self.addStl(o, highlight=(o.name == name), process=False) def getItemIdFromObject(self, obj): for itemId in self.itemMap.keys(): if obj.name == self.itemMap[itemId].name: return itemId return None def arrange(self): def cmpobj(a, b): return cmp(b.hArea, a.hArea) omap = Map(self.buildarea) maxx = maxy = -99999 minx = miny = 99999 objs = sorted(self.itemMap.values(), cmpobj) for o in objs: itemId = self.getItemIdFromObject(o) if itemId is None: continue x, y = omap.find(o.hxSize+self.arrangeMargin*2, o.hySize+self.arrangeMargin*2) if x is None or y is None: showinfo("Plate full", "Object %s does not fit" % o.name, parent=self) else: dx = x - o.hxCenter - o.translatex + o.hxSize/2 + self.arrangeMargin dy = y - o.hyCenter - o.translatey + o.hySize/2 + self.arrangeMargin self.setSelection(itemId) self.app.setSelection(o) self.moveStl(dx, dy) deltax = o.hxSize+self.arrangeMargin*2 deltay = o.hySize+self.arrangeMargin*2 omap.mark(x, y, deltax, deltay) if x < minx: minx=x if x+deltax > maxx: maxx=x+deltax if y < miny: miny=y if y+deltay > maxy: maxy=y+deltay dx = self.buildarea[0]/2-(maxx+minx)/2 dy = self.buildarea[1]/2-(maxy+miny)/2 for o in objs: itemId = self.getItemIdFromObject(o) if itemId is None: continue self.setSelection(itemId) self.app.setSelection(o) self.moveStl(dx, dy) def getStls(self): return self.itemMap.values() def countObjects(self): return len(self.selectable) def transform(self, ptx, pty): x = (ptx+self.offsetx)*self.zoom*self.scale+self.gridOffset y = (pty-self.offsety)*self.zoom*self.scale+self.gridOffset return (x, y) def triangulate(self, p1, p2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] d = math.sqrt(dx*dx + dy*dy) return d
class MainCanvas(object): """ The shapefile displaying device based on TKinter Canvas Attributes ---------- shapes : array The spatial units bbox : array The bounding box: minX, minY, maxX, maxY shp_type : integer The shape types: SHP_TYPE_POINT,SHP_TYPE_LINE,SHP_TYPE_POLYGON root : Tk The Tk Object attributeName : string The attribute name datalist : array The attribute data """ def __init__(self, shapes, bbox, shp_type, root, attributeName, datalist): self.shapes = shapes self.bbox = bbox self.shp_type = shp_type self.root = root self.attributeName = attributeName self.datalist = datalist self.__createCanvas() def __createCanvas(self): """ Create the canvas and draw all the spatial objects """ self.canvasRoot = Toplevel() self.canvasRoot.title(self.attributeName) self.canvasRoot.lower(belowThis=self.root) self.mainCanvas = Canvas(self.canvasRoot, bg='black', width=canvasWidth + margin_x, height=canvasHeight + margin_y, scrollregion=('-50c', '-50c', "50c", "50c")) #Change by Sagar for Full Screen self.canvasRoot.state('zoomed') self.canvasRoot.geometry = ("1000x900+0+0") #Change End self.__drawShape() self.mainCanvas.pack() def __drawShape(self): """ Draw all the spatial objects on the canvas """ minX, minY, maxX, maxY = self.bbox[0], self.bbox[1], self.bbox[ 2], self.bbox[3] # calculate ratios of visualization ratiox = canvasWidth / (maxX - minX) ratioy = canvasHeight / (maxY - minY) # take the smaller ratio of window size to geographic distance ratio = ratiox if ratio > ratioy: ratio = ratioy if self.shp_type == SHP_TYPE_POINT: self.__drawPoints(minX, minY, maxX, maxY, ratio) elif self.shp_type == SHP_TYPE_LINE: self.__drawPolylines(minX, minY, maxX, maxY, ratio) elif self.shp_type == SHP_TYPE_POLYGON: self.__drawPolygons(minX, minY, maxX, maxY, ratio) def __drawPoints(self, minX, minY, maxX, maxY, ratio): """ Draw points on the canvas """ tag_count = 0 # loop through each point for point in self.shapes: #define an empty xylist for holding converted coordinates x = int((point.x - minX) * ratio) + margin_x / 2 y = int((maxY - point.y) * ratio) + margin_y / 2 _point = self.mainCanvas.create_oval(x - 2, y - 2, x + 2, y + 2, outline=point.color, fill=point.color, width=2, tags=self.datalist[tag_count]) self.mainCanvas.tag_bind(_point, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __drawPolylines(self, minX, minY, maxX, maxY, ratio): """ Draw polylines on the canvas """ tag_count = 0 # loop through each polyline for polyline in self.shapes: #define an empty xylist for holding converted coordinates xylist = [] # loops through each point and calculate the window coordinates, put in xylist for j in range(len(polyline.x)): pointx = int((polyline.x[j] - minX) * ratio) + margin_x / 2 pointy = int((maxY - polyline.y[j]) * ratio) + margin_y / 2 xylist.append(pointx) xylist.append(pointy) # loop through each part of the polyline for k in range(polyline.partsNum): #get the end sequence number of points in the part if (k == polyline.partsNum - 1): endPointIndex = len(polyline.x) else: endPointIndex = polyline.partsIndex[k + 1] # define a temporary list for holding the part coordinates tempXYlist = [] #take out points' coordinates for the part and add to the temporary list for m in range(polyline.partsIndex[k], endPointIndex): tempXYlist.append(xylist[m * 2]) tempXYlist.append(xylist[m * 2 + 1]) # create the line _line = self.mainCanvas.create_line( tempXYlist, fill=polyline.color, tags=self.datalist[tag_count]) self.mainCanvas.tag_bind(_line, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __drawPolygons(self, minX, minY, maxX, maxY, ratio): """ Draw polygons on the canvas """ tag_count = 0 for polygon in self.shapes: #define an empty xylist for holding converted coordinates xylist = [] # loops through each point and calculate the window coordinates, put in xylist for point in polygon.points: pointx = int((point.x - minX) * ratio) + +margin_x / 0.5 pointy = int((maxY - point.y) * ratio) + +margin_y / 5 xylist.append(pointx) xylist.append(pointy) ## print xylist """ polyline.partsIndex is a tuple data type holding the starting points for each part. For example, if the polyline.partsIndex of a polyline equals to (0, 4, 9), and the total points, which is calcuate by len(polyline.points) equals to 13. This means that the polyline has three parts, and the each part would have the points as follows. part 1: p0,p1,p2,p3 part 2: p4,p5,p6,p7,p8 part 3: p9,p10,p11,p12 The xylist would be: xylist = [x0, y0, x1, y1, x2, y2, x3, y3, x4, y4....x12, y12] where xylist[0] = x0 xylist[1] = y0 xylist[2] = x1 xylist[3] = y1 ..... To draw the first part of polyline, we want to get tempXYlist as tempXYlist = [x0, y0, x1, y1, x2, y2, x3, y3] At this time, m is in range(0,4) xylist[m*2] would be is x0(when m=0), x1(when m=1), x2(when m=2), x3(when m=3) xylist[m*2+1] would be is y0(when m=0), y1(when m=1), y2(when m=2), y3(when m=3) """ for k in range(polygon.partsNum): #get the end sequence number of points in the part if (k == polygon.partsNum - 1): endPointIndex = len(polygon.points) else: endPointIndex = polygon.partsIndex[k + 1] #Define a temporary list for holding the part coordinates tempXYlist = [] tempXlist = [] tempYlist = [] #take out points' coordinates for the part and add to the temporary list for m in range(polygon.partsIndex[k], endPointIndex): tempXYlist.append(xylist[m * 2]) tempXYlist.append(xylist[m * 2 + 1]) tempXlist.append(xylist[m * 2]) tempYlist.append(xylist[m * 2 + 1]) xMax = max(tempXlist) xMin = min(tempXlist) yMax = max(tempYlist) yMin = min(tempYlist) if xMax == xMin: xMin = xMax - 1 if yMax == yMin: yMin = yMax - 1 tempVar = False #while not tempVar: xPoint = rd.randrange(xMin, xMax) yPoint = rd.randrange(yMin, yMax) tempVar = point_inside_polygon(xPoint, yPoint, tempXYlist) startIndex = polygon.partsIndex[ k] #start index for our positive polygon. tempPoints = polygon.points[ startIndex: endPointIndex] #we get our temppoints to help use create our polygon using positive data newPolygon = Polygon( tempPoints ) #here we create our polygons using positve data area = newPolygon.getArea() # Calculate the area #Sagar Jha center added to calculate centroid of polygon center = newPolygon.getCentroid() xCenter = int((center.x - minX) * ratio) + +margin_x / 0.5 yCenter = int((maxY - center.y) * ratio) + +margin_y / 5 if area > 0: _polygon = self.mainCanvas.create_polygon( tempXYlist, activefill="blue", fill=polygon.color, outline="blue", tags=self.datalist[tag_count] ) #creating our polygon outline #print k,_polygon #Michigan Special Condition according to its 2 parts if tag_count == 48: if k == 4: _oval = self.mainCanvas.create_oval(xCenter, yCenter, xCenter + 5, yCenter + 5, outline="red", fill="green", width=2, tags=center) dict1[_oval] = [center.x, center.y] else: if k == 0: #print "Tag Count: ",tag_count," ",self.mainCanvas.gettags(_polygon)[0] _oval = self.mainCanvas.create_oval(xCenter, yCenter, xCenter + 5, yCenter + 5, outline="red", fill="green", width=2, tags=center) dict1[_oval] = [center.x, center.y] #_oval1 = self.mainCanvas.create_oval(xPoint, yPoint,xPoint +5,yPoint+ 5, outline="red",fill="green", width=2) else: # If it is a hole, fill with the same color as the canvas background color _polygon = self.mainCanvas.create_polygon( tempXYlist, fill="black", outline="black", tags=self.datalist[tag_count]) #self.mainCanvas.tag_bind( _polygon, '<ButtonPress-1>', self.__showAttriInfo) #self.mainCanvas.tag_bind( _oval, '<ButtonPress-1>', self.__showAttriInfo) tag_count += 1 def __showAttriInfo(self, event): """ Show attribute information of clicked unit """ widget_id = event.widget.find_closest(event.x, event.y) if widget_id[0] in dict1.keys(): print widget_id[0], dict1[widget_id[0]][0], dict1[widget_id[0]][1] else: print "click!!!!", widget_id print self.attributeName + " is: " + self.mainCanvas.gettags( widget_id)[0]
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()
botMark = 'X' if randrange(0,2)==0 else 'O' playerMark = 'X' if botMark == 'O' else 'O' gameResult = 0 moveCount = 0 root = Tk() root.title('TIC-TAC-TOE') root.resizable(False,False) can = Canvas(root,background="white",width=150,height=120) can.pack(side = TOP) for i in xrange(3): st=[] for j in xrange(3): y=i*30 x=j*30 st+=[can.create_polygon(x,y,x+30,y,x+30,y+30,x,y+30,fill='lightgray',outline='black')] if botMark == 'X': botX, botY = botMakesMove(gameField, botMark) redrawField(gameField) if botMark == 'X': can.create_line(botY*30+5,botX*30+5,botY*30+25,botX*30+25) can.create_line(botY*30+5,botX*30+25,botY*30+25,botX*30+5) else: can.create_oval(botY*30+5,botX*30+5,botY*30+25,botX*30+25) def callback(event): result = evaluateField(gameField) if result != 0: print(result) gameOver = True return
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 mouth_normal = c.create_line(170, 250, 200, 282, 230, 250, smooth=1, width=2, state=NORMAL)
class GridGUI(Frame): def __init__(self, parent, dimensions=(3, 5), square_size=50, algorithm=None): Frame.__init__(self, parent) self.parent = parent (self.max_row, self.max_col) = dimensions self.board_height = square_size * self.max_row self.board_width = square_size * self.max_col self.sq_size = square_size self.polygons = PolygonContainer() self.algorithm = algorithm self.algorithm_is_paused = False self._init_ui() def _init_ui(self): self.parent.title("GridWorld") self.config(bg='#F0F0F0') self.pack(fill=BOTH, expand=1) # create canvas self.canvas = Canvas(self, width=self.board_width, height=self.board_height, bg='#CCFF99', borderwidth=0, highlightthickness=0) for row in range(self.max_row): for col in range(self.max_col): if self.algorithm.gw.is_terminal_state((row, col)): is_terminal, value = self.algorithm.gw.is_terminal_state((row, col)) if value == -100: self.canvas.create_rectangle(col * self.sq_size, row * self.sq_size, (col + 1) * self.sq_size, (row + 1) * self.sq_size, outline='gray', fill='#FF3300', width=1) else: self.canvas.create_rectangle(col * self.sq_size, row * self.sq_size, (col + 1) * self.sq_size, (row + 1) * self.sq_size, outline='gray', fill='#0066FF', width=1) continue nx0 = col * self.sq_size ny0 = row * self.sq_size nx1 = nx0 + self.sq_size ny1 = ny0 nx2 = nx0 + self.sq_size / 2 ny2 = ny0 + self.sq_size / 2 n_points = [nx0, ny0, nx1, ny1, nx2, ny2] n_polygon = self.canvas.create_polygon(n_points, outline='gray', fill='#CCFF99', width=1) self.polygons.add_polygon(n_polygon, (row, col), "N") ex0 = (col + 1) * self.sq_size ey0 = row * self.sq_size ex1 = ex0 ey1 = ey0 + self.sq_size ex2 = ex0 - self.sq_size / 2 ey2 = ey0 + self.sq_size / 2 e_points = [ex0, ey0, ex1, ey1, ex2, ey2] e_polygon = self.canvas.create_polygon(e_points, outline='gray', fill='#CCFF99', width=1) self.polygons.add_polygon(e_polygon, (row, col), "E") sx0 = col * self.sq_size sy0 = (row + 1) * self.sq_size sx1 = sx0 + self.sq_size sy1 = sy0 sx2 = sx0 + self.sq_size / 2 sy2 = sy0 - self.sq_size / 2 s_points = [sx0, sy0, sx1, sy1, sx2, sy2] s_polygon = self.canvas.create_polygon(s_points, outline='gray', fill='#CCFF99', width=1) self.polygons.add_polygon(s_polygon, (row, col), "S") wx0 = col * self.sq_size wy0 = row * self.sq_size wx1 = wx0 wy1 = wy0 + self.sq_size wx2 = wx0 + self.sq_size / 2 wy2 = wy0 + self.sq_size / 2 w_points = [wx0, wy0, wx1, wy1, wx2, wy2] w_polygon = self.canvas.create_polygon(w_points, outline='gray', fill='#CCFF99', width=1) self.polygons.add_polygon(w_polygon, (row, col), "W") self.canvas.pack(side=TOP, padx=10, pady=10) start_button = Button(self, text="Start", command=self.start_algorithm) start_button.configure(width=10) start_button.pack(side=LEFT) pause_button = Button(self, text="Pause", command=self.pause_algorithm) pause_button.configure(width=10) pause_button.pack(side=RIGHT) def start_algorithm(self): self.algorithm_is_paused = False self.run_algorithm() def run_algorithm(self): if not self.algorithm_is_paused: canvas = self.canvas self.algorithm.learn() for row in range(self.max_row): for col in range(self.max_col): if self.algorithm.gw.is_terminal_state((row, col)): continue argmax_action = self.algorithm.get_policy((row, col)) for action in self.algorithm.gw.actions: canvas.itemconfig(self.polygons.get_polygon((row, col), action), fill="#CCFF99") canvas.itemconfig(self.polygons.get_polygon((row, col), argmax_action), fill="#009900") if self.algorithm.is_online(): self.after(1, self.run_algorithm) def pause_algorithm(self): self.algorithm_is_paused = True
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 Viewer(Frame): def __init__(self, master,x=600,y=200, onLeft=None, onRight=None, **kwargs): self.root=master self.xsize=x self.ysize=y self.onLeft=onLeft self.onRight=onRight self.ratio=100. Frame.__init__(self, master,width=x,height=y, **kwargs) self.canvas = Canvas(self, width=x, height=y, background="white") self.xsb = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.ysb = Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set) self.canvas.configure(scrollregion=(0,0,x,y)) self.xsb.grid(row=1, column=0, sticky="ew") self.ysb.grid(row=0, column=1, sticky="ns") self.canvas.grid(row=0, column=0, sticky="nsew") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.canvas.bind("<Button-1>", self.clickL) self.canvas.bind("<Button-3>", self.clickR) # This is what enables using the mouse: self.canvas.bind("<ButtonPress-1>", self.move_start) self.canvas.bind("<B1-Motion>", self.move_move) #linux scroll self.canvas.bind("<Button-4>", self.zoomerP) self.canvas.bind("<Button-5>", self.zoomerM) self.canvas.bind_all("<Prior>", self.zoomerP) self.canvas.bind_all("<Next>", self.zoomerM) self.canvas.bind_all("E", self.zoomExtens) #windows scroll self.canvas.bind_all("<MouseWheel>",self.zoomer) def reset(self): pass def set_title(self, title): self.root.title( title) #move def move_start(self, event): self.canvas.scan_mark(event.x, event.y) return True def move_move(self, event): self.canvas.scan_dragto(event.x, event.y, gain=1) return True #windows zoom def zoomer(self,event): if (event.delta > 0): self.ratio *= 1.1 elif (event.delta < 0): self.ratio *= 0.9 self.redraw() def redraw(self): self.canvas.delete("all") self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomExtens(self, *args): x0,y0,x1,y1 = self.canvas.bbox("all") xlen=x1-x0 ylen=y1-y0 height=self.canvas.winfo_height() width=self.canvas.winfo_width() unfit=min(width/float(xlen), height/float(ylen)) self.ratio*=unfit self.redraw() # """" if xlen and ylen: self ratio*= self.canvas.scale("all", xlen/2., ylen/2., float(self.xsize)/xlen, float(self.ysize)/ylen) self.canvas.configure(scrollregion = self.canvas.bbox("all")) """ #linux zoom def zoomerP(self,event): self.canvas.scale("all", event.x, event.y, 1.1, 1.1) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomerM(self,event): self.canvas.scale("all", event.x, event.y, 0.9, 0.9) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def pose2p(self, pose): x,y=pose[:2] return int(x*self.ratio), -int(y*self.ratio) def line2p(self, line): if type(line[0]) in (float, int): line=zip(line[::2],line[1::2]) return map(self.pose2p, line) def p2m(self, x, y): return x/self.ratio, -y/self.ratio def create_line(self, coords, **kwargs): return self.canvas.create_line(self.line2p(coords), **kwargs) def create_polygon(self, coords, **kwargs): return self.canvas.create_polygon(self.line2p(coords), **kwargs) def delete(self, object): self.canvas.delete(object) def clickL(self, event): if self.onLeft: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onLeft(x,y) return True def clickR(self, event): if self.onRight: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onRight(x,y) return True