class Face: def __init__(self, window, center, size): eyeSize = 0.15 * size eyeOff = size / 3.0 mouthSize = 0.8 * size mouthOff = size / 2.0 self.head = Circle(center, size) self.head.draw(window) self.leftEye = Circle(center, eyeSize) self.leftEye.move(-eyeOff, -eyeOff) self.rightEye = Circle(center, eyeSize) self.rightEye.move(eyeOff, -eyeOff) self.leftEye.draw(window) self.rightEye.draw(window) p1 = center.clone() p1.move(-mouthSize / 2, mouthOff) p2 = center.clone() p2.move(mouthSize / 2, mouthOff) self.mouth = Line(p1, p2) self.mouth.draw(window) def Move(self, dx, dy): for p in self.points: p.Move(dx, dy) def Flinch(self, center, size, window): eyesize = 0.15 * size eyeOff = size / 3.0 self.leftEye = Line(Point(center.x + eyesize / 2, center.y), Point(center.x - eyesize / 2, center.y)) self.leftEye.move(-eyeOff, -eyeOff) self.rightEye = Circle(center, eyesize) self.rightEye.move(eyeOff, -eyeOff) self.leftEye.draw(window) self.rightEye.draw(window)
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 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 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 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 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 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 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 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 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 get_right(self): x = self.position.x + (self.looking.x - self.position.x) * math.cos( -math.pi / 3) - (self.looking.y - self.position.y) * math.sin( -math.pi / 3) y = self.position.y + (self.looking.x - self.position.x) * math.sin( -math.pi / 3) + (self.looking.y - self.position.y) * math.cos( -math.pi / 3) l = Line(self.position, Point(x, y)) l.setFill(self.color) return l
def Flinch(self, center, size, window): eyesize = 0.15 * size eyeOff = size / 3.0 self.leftEye = Line(Point(center.x + eyesize / 2, center.y), Point(center.x - eyesize / 2, center.y)) self.leftEye.move(-eyeOff, -eyeOff) self.rightEye = Circle(center, eyesize) self.rightEye.move(eyeOff, -eyeOff) self.leftEye.draw(window) self.rightEye.draw(window)
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 set_graphicals(self): # draw player self.body = Circle(Point(scale(self.pos_x), scale(self.pos_y)), 7) self.body.setFill('red') # Note: downwards in Y is the positive direction for this graphics lib self.arrow = Line( Point(scale(self.pos_x), scale(self.pos_y)), Point(scale(self.pos_x + self.vel_x), scale(self.pos_y + self.vel_y))) self.arrow.setFill('black') self.arrow.setArrow('last') self.body.draw(self.win) self.arrow.draw(self.win)
def draw_searcher_move(s, i, win): ''' For drawing purposes make sure the distace moved does not jump from one side of the env to the other ''' if win is not None: if ( abs(s.X[i] - s.X[i+1]) <= s.max_speed and abs(s.Y[i] - s.Y[i+1]) <= s.max_speed ): p = Line(Point(s.X[i], s.Y[i]), Point(s.X[i+1], s.Y[i+1])) p.setOutline("green") p.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 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_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_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 table_tennis_scorer(): """ 8. Write a table_tennis_scorer() function that allows the user to keep track of the points of two players in a game of table tennis. In table tennis, the first player to reach 11 points wins the game; however, a game must be won by at least a two point margin. The points for the players should be displayed on two halves of a graphics window, and the user clicks anywhere on the appropriate side to increment a player's score. As soon as one player has won, a 'wins' message should appear on that side. """ win = GraphWin("Table tennis scorer", 500, 500) win.setCoords(0, 0, 1, 1) left_score = 0 right_score = 0 divider = Line(Point(0.5, 0), Point(0.5, 1)) divider.draw(win) left_score_text = Text(Point(0.25, 0.6), 0) left_score_text.setSize(35) left_score_text.draw(win) right_score_text = Text(Point(0.75, 0.6), 0) right_score_text.setSize(35) right_score_text.draw(win) while not ((left_score >= 11 or right_score >= 11) and (left_score >= (right_score + 2) or right_score >= (left_score + 2))): cursor = win.getMouse() if cursor.getX() <= 0.5: left_score += 1 left_score_text.setText(left_score) else: right_score += 1 right_score_text.setText(right_score) if left_score > right_score: winner_text_centre = Point(0.25, 0.5) else: winner_text_centre = Point(0.75, 0.5) winner_text = Text(winner_text_centre, "Winner") winner_text.setSize(20) winner_text.draw(win) cursor = win.getMouse() win.close()
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 graph(self): half = int(Graph.getSize(self) / 2) p1 = Point(0, half - Derivative.slope(self)[0]) p2 = Point(Graph.getSize(self), half - Derivative.slope(self)[1]) line = Line(p1, p2) return line
def draw_patch_two(win, x, y, colour): patch_shapes = [] # Loop through the diagonal points of the patch for i in range(0, 110, 10): # Define lines for the top/bottom and left/right sections line1 = Line(Point(x + i, y), Point(x + 100 - i, y + 100)) line2 = Line(Point(x, y + i), Point(x + 100, y + 100 - i)) patch_shapes.append(line1) patch_shapes.append(line2) patch_box = draw_patch_box(x, y) for shape in patch_shapes: shape.draw(win).setFill(colour) drawn, design, elements = True, "2", [patch_box, patch_shapes] return [colour, drawn, design, x, y, elements]
def get_angle_between_lines(line1: Line, line2: Line): len1 = get_line_length(line1) len2 = get_line_length(line2) if len1 == 0 or len2 == 0: return 0 len3 = get_line_length(Line(line2.p2, line1.p1)) angle = degrees( acos((pow(len1, 2) + pow(len2, 2) - pow(len3, 2)) / (2 * len1 * len2))) return angle
def draw_vertical_grid_lines(): for i_col in range(n_cols + 1): x0 = left_margin + i_col * cell_height y0 = upper_margin pt0 = Point(x0, y0) pt1 = Point(x0, y0 + grid_height) line = Line(pt0, pt1) if i_col % order == 0: line.setWidth(thick) else: line.setWidth(0) line.draw(win)
def __init__(self, window, center, size): eyeSize = 0.15 * size eyeOff = size / 3.0 mouthSize = 0.8 * size mouthOff = size / 2.0 self.head = Circle(center, size) self.head.draw(window) self.leftEye = Circle(center, eyeSize) self.leftEye.move(-eyeOff, -eyeOff) self.rightEye = Circle(center, eyeSize) self.rightEye.move(eyeOff, -eyeOff) self.leftEye.draw(window) self.rightEye.draw(window) p1 = center.clone() p1.move(-mouthSize / 2, mouthOff) p2 = center.clone() p2.move(mouthSize / 2, mouthOff) self.mouth = Line(p1, p2) self.mouth.draw(window)
def draw_horizontal_grid_lines(): for i_row in range(n_rows + 1): x0 = left_margin y0 = upper_margin + i_row * cell_height pt0 = Point(x0, y0) pt1 = Point(x0 + grid_width, y0) line = Line(pt0, pt1) if i_row % order == 0: line.setWidth(thick) else: line.setWidth(0) line.draw(win)
def draw_line(win): """Helper function for drawing a line on a graphics window.""" message = Text(Point(100, 100), "Click on first point").draw(win) p1 = win.getMouse() message.setText("Click on second point") p2 = win.getMouse() Line(p1, p2).draw(win) message.setText("")
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 CreateLines(dots): lines = [] drawnDots = [] for dot in dots: for otherDot in dots: if otherDot is not dot and otherDot not in drawnDots: lines.append(Line(dots[0].getCenter(), otherDot.getCenter())) drawnDots.append(dot) dots.remove(dot) dots.extend(drawnDots.copy()) return lines
def set_graphicals(self): draw_x = scale(self.pos_x) draw_y = scale(self.pos_y) # Draw the new path if self.sling_path_calculated is not None: for action in self.sling_path_calculated: cir = Circle(action[0].get_scaled_point(), self.body_radius) cir.setFill('yellow') cir.draw(self.win) if self.circle is not None: dubinc = Circle(self.circle.c.get_scaled_point(), scale_vectors(self.circle.r)) dubinc.setOutline('Green') dubinc.draw(self.win) if self.body: 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] * 5), scale(self.pos_y + self.current_vel[1] * 5))) 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 main(): parser = argparse.ArgumentParser() parser.add_argument("--size", type=int, default=3, help="Size of k") args = parser.parse_args() win = GraphWin("My Circle", WIN_SIZE, WIN_SIZE) k = args.size m = k * (k - 1) + 1 r = min(pi * R / m * 0.50, 20) ds = DiffState(k) ds.search() points = [] for i in range(m): ang = 2 * pi * i / m center = (CENTER[0] + R * sin(ang), CENTER[1] - R * cos(ang)) points.append(Point(center[0], center[1])) if m < 20: for i in range(m): for j in range(i, m): if not (i in ds.current and j in ds.current): l = Line(points[i], points[j]) l.draw(win) l.setOutline(all_color) for i in range(m): for j in range(i, m): if i in ds.current and j in ds.current: l = Line(points[i], points[j]) l.setWidth(3) l.draw(win) l.setOutline(set_color) for i in range(m): c = Circle(points[i], r) c.setFill("red") c.draw(win) win.getMouse() win.close()
for j, (player, entry) in enumerate(game['history'], start=1): # Box finished is_vert, r, c = entry r = int(r) c = int(c) if is_vert == '': rec = Rectangle(points[r][c], points[r+1][c+1]) rec.setFill(colors[player]) rec.draw(win) scores[player] += 1 score_text[player].undraw() score_text[player].setText('{}:{}'.format(wins[player], scores[player])) score_text[player].draw(win) else: if is_vert: line = Line(points[r][c], points[r+1][c]) else: line = Line(points[r][c], points[r][c+1]) line.draw(win) line.setFill(colors[player]) printer(win, results_dir, f, i, j) (n1, s1), (n2, s2) = scores.items() if s1 > s2: winner = n1 elif s2 > s1: winner = n2 else: winner = None if winner: