def draw_patch_window(): """ 9. Write a function draw_patch_window() (without parameters) which displays, in a graphics window of size 100 × 100 pixels, the patch design which is labelled with the final digit of your student number. The patch design should be displayed in red, as in the table. It's important that your program draws the patch design accurately, but don't worry if one pixel is chopped off at the edge of the window. Note that you don't need to draw a border around the patch design. """ win = GraphWin("Patch design", 100, 100) for distance in (20, 40, 60, 80, 100): line = Line(Point(0, distance), Point(distance, 0)) line.setFill("red") line.setWidth(2) line.draw(win) line = Line(Point(100 - distance, 0), Point(100, distance)) line.setFill("red") line.setWidth(2) line.draw(win) for distance in (20, 40, 60, 80): line = Line(Point(distance, 100), Point(100, distance)) line.setFill("red") line.setWidth(2) line.draw(win) line = Line(Point(0, distance), Point(100 - distance, 100)) line.setFill("red") line.setWidth(2) line.draw(win) win.getMouse() win.close()
def draw_mark(self, move: tuple) -> None: """ Draw a mark as specified by a move :param move: a legal move: (selected_tile.x_pos, selected_tile.y_pos, player.mark) :return: none """ if self.window is None: raise ValueError('Board has no open window!') tile_x, tile_y, mark = move grid_x, grid_y = self.coord_tile_to_grid(tile_x, tile_y) rad = self.tile_size * 0.3 if mark == 'O': cir = Circle(Point(grid_x, grid_y), rad) cir.setOutline('blue') cir.setWidth(3) cir.draw(self.window) else: downstroke = Line(Point(grid_x - rad, grid_y - rad), Point(grid_x + rad, grid_y + rad)) upstroke = Line(Point(grid_x - rad, grid_y + rad), Point(grid_x + rad, grid_y - rad)) downstroke.setOutline('red') downstroke.setWidth(3) upstroke.setOutline('red') upstroke.setWidth(3) upstroke.draw(self.window) downstroke.draw(self.window)
def draw_tour(path_d, all_nodes): from graphics import Point, Circle, Line, GraphWin maxX = max([x for x, y in all_nodes]) minX = min([x for x, y in all_nodes]) maxY = max([y for x, y in all_nodes]) minY = min([y for x, y in all_nodes]) N = 750 norm_x = N/(maxX - minX) norm_y = N/(maxY - minY) win = GraphWin("TSP", N, N) for n in all_nodes: c = Point(*norm(n, norm_x, norm_y, minX, minY)) c = Circle(c, 3) c.draw(win) for (k, subdict) in path_d.iteritems(): #t = Text(Point(*subdict['center']*N), k) #t.draw(win) if not subdict['hasBeenSplit']: p = Point(*norm(subdict['center'], norm_x, norm_y, minX, minY)) c1i, c2i = subdict['connections'] c1 = Point(*norm(path_d[str(c1i)]['center'], norm_x, norm_y, minX, minY)) c2 = Point(*norm(path_d[str(c2i)]['center'], norm_x, norm_y, minX, minY)) l1 = Line(p, c1) l2 = Line(p, c2) l1.draw(win) l2.draw(win) win.getMouse() win.close()
def draw_classroom(): win = GraphWin("Stick figure", 300, 200) head = Circle(Point(100, 60), 20) body = Line(Point(100, 80), Point(100, 120)) arms = Line(Point(70, 90), Point(130, 90)) leg_l = Line(Point(100, 120), Point(80, 170)) leg_r = Line(Point(100, 120), Point(120, 170)) for body_part in [head, body, arms, leg_l, leg_r]: body_part.draw(win) # Draw the Whiteboard whiteboard = Rectangle(Point(140, 50), Point(290, 150)) whiteboard.setFill('white') whiteboard.draw(win) # Draw the blue marker pen base marker_pen = Rectangle(Point(120, 80), Point(128, 100)) marker_pen.setFill('blue') marker_pen.draw(win) # Draw the blue marker pen tip marker_pen_tip = Rectangle(Point(122, 72), Point(126, 80)) marker_pen_tip.setFill('blue') marker_pen_tip.draw(win) write_letters(win) marker_pen_tip.setFill('white')
def init(): global win win = GraphWin('Tic Tac Toe', SIZE*3, SIZE*3) Line(Point(SIZE, 0), Point(SIZE, 3*SIZE)).draw(win) Line(Point(SIZE*2, 0), Point(SIZE*2, 3*SIZE)).draw(win) Line(Point(0, SIZE), Point(3*SIZE, SIZE)).draw(win) Line(Point(0, SIZE*2), Point(3*SIZE, SIZE*2)).draw(win)
def draw(self): if self.pulsing: color = 'red' else: color = 'black' target = self.target source = self.source line = Line(source.location, target.location) line.setWidth(1) line.setFill(color) line.setOutline(color) line.draw(self.brain.win) dx = target.location.x - source.location.x dy = target.location.y - source.location.y k = dy / dx if dx != 0 else dy k = abs(k) dd = 20 sign_dx = -1 if dx < 0 else 1 sign_dy = -1 if dy < 0 else 1 dx = -sign_dx * dd / sqrt(k**2 + 1) dy = -sign_dy * k * dd / sqrt(k**2 + 1) # sleep(1) dp = Point(target.location.x + dx, target.location.y + dy) line = Line(dp, target.location) line.setWidth(3) line.setFill(color) line.draw(self.brain.win)
def main(): # Create animation window win = GraphWin("Projectile Animation", 640, 480, autoflush=False) win.setCoords(-10, -10, 210, 155) # Draw baseline Line(Point(-10, 0), Point(210, 0)).draw(win) # Draw labeled ticks every 50 meters for x in range(0, 210, 50): Text(Point(x, -5), str(x)).draw(win) Line(Point(x, 0), Point(x, 2)).draw(win) # Event loop, each time through fires a single shot angle, vel, height = 45.0, 40.0, 2.0 while True: # Interact with the user inputwin = InputDialog(angle, vel, height) choice = inputwin.interact() inputwin.close() if choice == "Quit": # Loop exit break # Create a shot and track until it hits ground or leaves window angle, vel, height = inputwin.getValues() shot = ShotTracker(win, angle, vel, height) while 0 <= shot.getY() and -10 < shot.getX() <= 210: shot.update(1/50) update(50) win.close()
def draw_grid(size): squares = size - 1 win = GraphWin("Graphical traced walk", 50 * size, 50 * size) win.setCoords(0, size, size, 0) border_rectangle = Rectangle(Point(0.5, 0.5), Point(size - 0.5, size - 0.5)).draw(win) border_rectangle.setFill("gray") border_rectangle.setWidth(2) centre_square = Rectangle( Point(size / 2 - 0.5, size / 2 - 0.5), Point(size / 2 + 0.5, size / 2 + 0.5), ).draw(win) centre_square.setFill("cyan") centre_square.setOutline("") person = Circle(Point(size / 2, size / 2), 0.25).draw(win) person.setFill("red") square_texts = [[""] * squares for _ in range(squares)] for i in range(squares): for j in range(squares): # grid lines Line(Point(1.5 + j, 0.5), Point(1.5 + j, size - 0.5)).draw(win) Line(Point(0.5, 1.5 + j), Point(size - 0.5, 1.5 + j)).draw(win) # text within each square square_text = Text(Point(1 + j, 1 + i), "").draw(win) square_texts[i][j] = square_text return win, person, square_texts
def get_k_map_lines(window_width, window_height, square_dim): k_map_lines = [] for i in range(5): # Default horizontal line h_line_x_begin = window_width/2 - 2*square_dim h_line_x_end = window_width/2 + 2*square_dim h_line_y = window_height/2 + square_dim*(i-2) # Default vertical line v_line_x = window_width/2 + square_dim*(i-2) v_line_y_begin = window_height/2 - 2*square_dim v_line_y_end = window_height/2 + 2*square_dim if i % 2 == 1: h_line_x_end += square_dim v_line_y_end += square_dim elif i == 2: h_line_x_begin -= square_dim v_line_y_begin -= square_dim k_map_lines.extend([ Line( Point(h_line_x_begin, h_line_y), Point(h_line_x_end, h_line_y) ), Line( Point(v_line_x, v_line_y_begin), Point(v_line_x, v_line_y_end) )] ) return k_map_lines
def __init__(self, puzzle): self.puzzle = puzzle self.window_size: int = GRID_SIZE * self.puzzle.size self.window: GraphWin = GraphWin("Sudoku", self.window_size, self.window_size, autoflush=False) self.assignment = self.puzzle.assignment self.locations = self.puzzle.locations self.cells = dict() self.num_colors = len(TEXT_COLORS) # grid is np array # make cell for each element in the grid # and draw them for location in self.locations: self.cells[location] =\ SudokuCell(location, self.assignment[location.row, location.column]) self.grid_lines = [] subgrid_px = sqrt(self.puzzle.size) * GRID_SIZE self.subgrid_size = int(sqrt(self.puzzle.size)) # TODO: Be consistent with 'size' and 'px' for n in range(1, self.subgrid_size): self.grid_lines.append( Line(Point(0, subgrid_px * n), Point(self.window_size, subgrid_px * n))) self.grid_lines.append( Line(Point(subgrid_px * n, 0), Point(subgrid_px * n, self.window_size))) for line in self.grid_lines: line.setWidth(GRID_WIDTH_MAJOR) line.setOutline(GRID_COLOR_MAJOR) self.draw_background() self.set_presets(self.puzzle.preset)
def set_graphicals(self): draw_x = scale(self.pos_x) draw_y = scale(self.pos_y) if self.circle is not None and self.get_trace is False: dubinc = Circle(self.circle.c.get_scaled_point(), scale_vectors(self.circle.r)) dubinc.setOutline('Green') dubinc.draw(self.win) if self.body is not None and self.get_trace is False: self.body.undraw() self.body = Circle(Point(draw_x, draw_y), self.body_radius) self.body.setFill('yellow') self.body.draw(self.win) if self.vel_arrow: self.vel_arrow.undraw() self.vel_arrow = Line( Point(draw_x, draw_y), Point(scale(self.pos_x + self.current_vel[0]), scale(self.pos_y + self.current_vel[1]))) self.vel_arrow.setFill('black') self.vel_arrow.setArrow("last") self.vel_arrow.draw(self.win) if self.acc_arrow: self.acc_arrow.undraw() self.acc_arrow = Line( Point(draw_x, draw_y), Point(scale(self.pos_x + self.current_acc[0] * 5), scale(self.pos_y + self.current_acc[1] * 5))) self.acc_arrow.setFill('blue') self.acc_arrow.setArrow('last') self.acc_arrow.draw(self.win)
def draw_iks(x, y): global items line1 = Line(Point(x*SIZE+PADDING, y*SIZE+PADDING), Point((x+1)*SIZE-PADDING, (y+1)*SIZE-PADDING)) line1.setWidth(WIDTH) line1.draw(win) items.append(line1) line2 = Line(Point(x*SIZE+PADDING, (y+1)*SIZE-PADDING), Point((x+1)*SIZE-PADDING, (y)*SIZE+PADDING)) line2.setWidth(WIDTH) line2.draw(win) items.append(line2)
def drawFieldPanel(): # Create Field panel field = GraphWin("The Field", 400, 400) # Create vertical and horizontal lines on Field panel for i in range(9): v_field_line = Line(Point(40 * (i + 1), 0), Point(40 * (i + 1), 400)) v_field_line.setOutline("light gray") v_field_line.draw(field) h_field_line = Line(Point(0, 40 * (i + 1)), Point(400, 40 * (i + 1))) h_field_line.setOutline("light gray") h_field_line.draw(field) # Color start and end squares start = Rectangle(Point(0, 0), Point(40, 40)) start.setFill("green") start.setOutline("light gray") start.draw(field) end = Rectangle(Point(360, 360), Point(400, 400)) end.setFill("red") end.setOutline("light gray") end.draw(field) # Draw black holes blackcenter1, blackcenter2 = blackHoles(field) # Create spin square Rectangle while True: # Make sure spin square is not drawn on top of black holes, and repeat # location process if it is on top of a black hole spin_x = randint(2, 9) * 40 - 20 spin_y = randint(2, 9) * 40 - 20 spin_square = Rectangle(Point(spin_x - 17, spin_y - 17), Point(spin_x + 17, spin_y + 17)) if spin_x != blackcenter1.getX() and spin_y != blackcenter1.getY( ) or spin_x != blackcenter2.getX() and spin_y != blackcenter2.getY(): break spin_square.setFill("blue") spin_square.draw(field) spin_text = Text(Point(spin_x, spin_y), "SPIN") spin_text.setTextColor("white") spin_text.draw(field) # Create initial Pete Rectangle pete = Rectangle(Point(4, 4), Point(36, 36)) pete.setFill("gold") pete.draw(field) # Draw and return sensors sensors, goodsensors = drawSensors(field) # Return objects return field, pete, sensors, spin_square, blackcenter1, blackcenter2, goodsensors
def createGameWindow(): win = GraphWin("Projectile Animation", 640, 480, autoflush=False) width = 210 win.setCoords(-10, -10, width, 155) # Draw baseline Line(Point(-10, 0), Point(210, 0)).draw(win) # Draw labeled ticks every 50 meters for x in range(0, 210, 50): Text(Point(x, -5), str(x)).draw(win) Line(Point(x, 0), Point(x, 2)).draw(win) return win, width
def draw_grid(self): total_height = self.origin_y + self.cell_height * self.ny total_width = self.origin_x + self.cell_width * self.nx for i in range(self.nx + 1): x = self.origin_x + i * self.cell_width l = Line(Point(x, self.origin_y), Point(x, total_height)) l.setOutline(self.gridcolour) l.draw(self.win) for i in range(self.ny + 1): y = self.origin_y + i * self.cell_height l = Line(Point(self.origin_x, y), Point(total_width, y)) l.setOutline(self.gridcolour) l.draw(self.win)
def frame(self, win, s): header = Text(Point(350, 650), s) header.draw(win) for i in range(6): line = Line(Point(0, (i + 1) * 100), Point(700, (i + 1) * 100)) line.draw(win) for i in range(7): horizontal = Line(Point((i + 1) * 100, 600), Point((i + 1) * 100, 0)) horizontal.draw(win) for i in range(7): day = Text(Point((i * 100) + 50, 625), self.weekDays.get(i)) day.draw(win)
def frame(): f = [ Line(Point(0, 0), Point(499, 0)), Line(Point(0, 499), Point(499, 499)), Line(Point(0, 0), Point(0, 499)), Line(Point(499, 0), Point(499, 499)) ] for line in f: line.setWidth(9) line.setFill("blue") return f
def drawAxis(win, new_view): L1 = Line(Point(0, 0), Point(new_view.xVmax, 0)) L2 = Line(Point(0, 0), Point(0, new_view.yVmax)) L3 = Line(Point(0, 0), Point(new_view.xVmin, new_view.yVmin)) L1.setFill('blue') L2.setFill('blue') L3.setFill('blue') L1.setArrow("last") L2.setArrow("last") L3.setArrow("last") L1.draw(win) L2.draw(win) L3.draw(win) return win
def five_click_stick_figure(): """ 9. [harder] Write a five_click_stick_figure() function that allows the user to draw a (symmetric) stick figure in a graphics window using five clicks of the mouse to determine the positions of its features. Each feature should be drawn as the user clicks the points. Hint: the radius of the head is the distance between points 1 and 2 — see the previous practical. Note: only the y-coordinate of point (3) should be used — its x coordinate should be copied from point (1). """ win = GraphWin("Five Click Stick Figure", 800, 600) message = Text(Point(400, 15), "Click to create your stick figure") message.draw(win) head_centre = win.getMouse() head_centreX, head_centreY = head_centre.getX(), head_centre.getY() head_perim = win.getMouse() head_perimX, head_perimY = head_perim.getX(), head_perim.getY() head_radius = math.sqrt((head_perimX - head_centreX)**2 + (head_perimY - head_centreY)**2) head = Circle(head_centre, head_radius) head.draw(win) torso = win.getMouse() torso_line = Line(Point(head_centreX, head_centreY + head_radius), Point(head_centreX, torso.getY())) torso_line.draw(win) arm_reach = win.getMouse() arm_length = head_centreX - arm_reach.getX() arms_line = Line(Point(arm_reach.getX(), arm_reach.getY()), Point(head_centreX + arm_length, arm_reach.getY())) arms_line.draw(win) leg_reach = win.getMouse() left_leg_line = Line(Point(head_centreX, torso.getY()), Point(leg_reach.getX(), leg_reach.getY())) left_leg_line.draw(win) leg_distance = head_centreX - leg_reach.getX() right_leg_line = Line(Point(head_centreX, torso.getY()), Point(head_centreX + leg_distance, leg_reach.getY())) right_leg_line.draw(win) await_user_input(win)
def createWindow(self, N): """ Create the graphics window. Arguments: self - the SkewerUI instance N - the capacity of the skewer """ self.win = GraphWin("Shish Kebab", 800, 200) self.win.setCoords( \ WIN_LOW_LEFT_X, \ WIN_LOW_LEFT_Y - 0.1, \ WIN_LOW_LEFT_X+(N+1)*FOOD_WIDTH, \ WIN_UP_RIGHT_Y + 0.1 \ ) # draw skewer line = Line( \ Point(WIN_LOW_LEFT_X, WIN_LOW_LEFT_Y+WIN_HEIGHT/2.0), \ Point(N, WIN_LOW_LEFT_Y+WIN_HEIGHT/2.0) \ ) line.setWidth(LINE_THICKNESS) line.draw(self.win) handle = Circle( \ Point(N-.1, WIN_LOW_LEFT_Y+WIN_HEIGHT/2.0), \ SKEWER_HANDLE_RADIUS \ ) handle.setFill(BKGD_COLOR) handle.setWidth(LINE_THICKNESS) handle.draw(self.win) self.items = []
def _setup(self): circle = Circle(Point(250, 250), self.r) # set center and radius circle.setWidth(3) circle.draw(self.win) line = Line(Point(250, 225), Point(250, 285)) line.setWidth(3) line.draw(self.win) line2 = Line(Point(280, 250), Point(250, 225)) line2.setWidth(3) line2.draw(self.win) line3 = Line(Point(220, 250), Point(250, 225)) line3.setWidth(3) line3.draw(self.win)
def draw_route(self, car, show_route): # TODO optimize to not have to redraw entire route each time self.clear_route(self.route) self.route = {} if not show_route: return line_width = 3 line_color = color_rgb(20, 200, 20) p0 = Point(car.x, car.y) route = car.route[:] route.append(car.next_dest_id) for vertex_id in route[::-1]: intersection = self.intersections[vertex_id] p1 = Point(intersection.x, intersection.y) line = Line(p0, p1) line.setWidth(line_width) line.setOutline(line_color) self.route[vertex_id] = line p0 = p1 old_route = { key: val for key, val in self.route.items() if key not in route } self.route = { key: val for key, val in self.route.items() if key in route } self.clear_route(old_route) for line in self.route.values(): line.draw(self.canvas)
def create_line(p0, p1, width): line = Line(p0, p1) line.setWidth(width) color = color_rgb(200, 200, 200) line.setOutline(color) line.setArrow("last") return line
def draw_line(win, colour, point1, point2, current_tile): """Helper function for drawing lines.""" current_line = Line(Point(*point1), Point(*point2)) current_line.setWidth(2) current_line.setFill(colour) current_line.draw(win) current_tile.append(current_line)
def draw_tour(tour): from graphics import Point, Circle, Line, GraphWin maxX = max([x for x, y in tour]) minX = min([x for x, y in tour]) maxY = max([y for x, y in tour]) minY = min([y for x, y in tour]) N = 750 norm_x = N / (maxX - minX) norm_y = N / (maxY - minY) win = GraphWin("TSP", N, N) for n in tour: c = Point(*norm(n, norm_x, norm_y, minX, minY)) c = Circle(c, 2) c.draw(win) for i, _ in enumerate(tour[:-1]): p1 = norm(tour[i], norm_x, norm_y, minX, minY) p2 = norm(tour[i + 1], norm_x, norm_y, minX, minY) l = Line(Point(*p1), Point(*p2)) l.draw(win) win.getMouse() win.close()
def liang_barsky_clip(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 p = [-dx, dx, -dy, dy] q = [x1 - x_min, x_max - x1, y1 - y_min, y_max - y1] for i, val in enumerate(p): if val == 0: print("Line is parallel to one of the clipping boundry") if q[i] >= 0: if i < 2: if y1 < y_min: y1 = y_min if y2 > y_max: y2 = y_max clip_line = Line(Point(x1, y1), Point(x2, y2)) clip_line.draw(win) if i > 1: if x1 < x_min: x1 = x_min if x2 > x_max: x2 = x_max clip_line = Line(Point(x1, y1), Point(x2, y2)) clip_line.draw(win) t1 = 0.0 t2 = 1.0 r = 0 print(t1, t2) for i in range(4): r = q[i] / p[i] print(q[i], p[i]) if p[i] < 0: if t1 <= r: t1 = r else: if t2 > r: t2 = r print(t1, t2, r) print(t1, t2) if t1 < t2: x11 = x1 + t1 * p[1] x22 = x1 + t2 * p[1] y11 = y1 + t1 * p[3] y22 = y1 + t2 * p[3] print("(x1: %d , y1 : %d),(x2: %d , y2 : %d)" % (x11, y11, x22, y22)) clip_line = Line(Point(int(x11), int(y11)), Point(int(x22), int(y22))) clip_line.draw(win)
def __init__(self): self.lines = frame() steps = range(99, 499, 100) for y in steps: line = Line(Point(0, y), Point(499, y)) line.setFill("blue") line.setWidth(5) self.lines.append(line) for x in steps: line = Line(Point(x, 0), Point(x, 499)) line.setFill("blue") line.setWidth(5) self.lines.append(line)
def make_new_line(g1, g2, lines, win): new_line = GraphLine(g1, g2) lines.append(new_line) g1.vertex.connect_node(g2.vertex) handle_possible_intersections(new_line, lines, win) win_line = Line(g1.point, g2.point) win_line.setWidth(3) win_line.draw(win)
def graphical_rainfall_chart(): """ 13. Now write a graphical version, graphical_rainfall_chart(), that displays a similar bar chart in a graphical window but uses filled rectangles instead of sequences of asterisks. """ win = GraphWin("Rainfall Chart", 1050, 300) # y axis Line(Point(50, 50), Point(50, 260)).draw(win) # x axis Line(Point(50, 260), Point(1025, 260)).draw(win) colours = [ "red", "green", "orange", "blue", "white", "yellow", "black", "brown", "gray", ] with open("rainfall.txt", "r", encoding="utf_8") as f: file_contents = f.read().split("\n") for i, line in enumerate(file_contents): city, rainfall = line.split() # label city axis Text(Point((i + 1) * 100, 270), city).draw(win) # rainfall rectangle rectangle = Rectangle(Point((i + 0.5) * 100, 260 - int(rainfall) * 3.7), Point((i + 1.5) * 100, 260)) rectangle.setFill(colours[i]) rectangle.draw(win) for i in range(6): # label rainfall axis Text(Point(30, 255 - i * 36), i * 10).draw(win) win.getMouse() win.close()
def set_graphicals(self, quick_draw): """Draws the graph""" self.drawables = [] self.drawable_path = [] t = time.time() for node in self.graph: curr_loc = node.get_scaled_point() draw_node = Circle(curr_loc, 1) draw_node.setFill('red') draw_node.draw(self.win) self.drawables.append(draw_node) if not quick_draw: for neighbor in self.graph[node]: if neighbor: line = Line(curr_loc, neighbor.get_scaled_point()) line.draw(self.win) self.drawables.append(line) if self.path is not None: for i in range(0, len(self.path) - 1): node_1 = self.path[i] node_2 = self.path[i + 1] cir = Circle(node_1.get_scaled_point(), 2) cir.setFill('Red') cir.setOutline('Red') self.drawable_path.append(cir) lin = Line(node_1.get_scaled_point(), node_2.get_scaled_point()) lin.setOutline('Red') lin.draw(self.win) self.drawable_path.append(lin) for i in range(0, len(self.optimal_path) - 1): node_1 = self.optimal_path[i] node_2 = self.optimal_path[i + 1] cir = Circle(node_1.get_scaled_point(), 5) cir.setFill('Blue') cir.setOutline('Blue') cir.draw(self.win) self.drawable_path.append(cir) lin = Line(node_1.get_scaled_point(), node_2.get_scaled_point()) lin.setOutline('Blue') lin.draw(self.win) self.drawable_path.append(lin) emit_verbose("Drawing RRT took", self.verbose, var=time.time() - t)