def draw( self, cr: Context, vp_matrix: np.ndarray, ): self.filled = False Polygon.draw(self, cr, vp_matrix)
def create_polygon(verticies, outline_color, outline_width, fill_color): polygon = Polygon(verticies) polygon.setOutline(outline_color) polygon.setWidth(outline_width) polygon.setFill(fill_color) return polygon
def main(): win = GraphWin("Five-Click House", 500, 400) win.setCoords(0.0, 0.0, 15.0, 15.0) message = Text(Point(7.5, 1), "Choose 5 points that draw a house and a door.") message.draw(win) p1 = win.getMouse() #choose the five points wisely for building the house p1.draw(win) p2 = win.getMouse() p2.draw(win) p3 = win.getMouse() p4 = win.getMouse() p5 = win.getMouse() x1 = p1.getX() # get the corresponding values for x and y y1 = p1.getY() x2 = p2.getX() y2 = p2.getY() x3 = p3.getX() y3 = p3.getY() x4 = p4.getX() y4 = p4.getY() last_leg_triangle = Point(x1, y2) Rectangle1 = Rectangle(p1, p2) #build the rectangle; the home Rectangle1.draw(win) #draw the building p_rect1 = Point((x3 - (((x2 - x1) / 5) / 2)), y3) p_rect2 = Point(x3 + (((x2 - x1) / 5) / 2), y1) p_square = Point(x4 + (((x2 - x1) / 5) * (3 / 4)), y4 + (((x2 - x1) / 5) * (3 / 4))) p_square_2 = Point(x4 - (((x2 - x1) / 5) * (3 / 4)), y4 - (((x2 - x1) / 5) * (3 / 4))) Rect = Rectangle(p_rect1, p_rect2) Rect.draw(win) Rect4 = Rectangle(p_square, p_square_2) Rect4.draw(win) Triangle = Polygon(p5, p2, last_leg_triangle) Triangle.draw(win) win.getMouse()
def createSegmentPolygon(center, length, degrees): halfSegmentLength = length * 0.5 radians = math.radians(degrees) xComponent = arr([math.cos(radians), math.sin(radians)]) yComponent = arr([math.sin(radians), -math.cos(radians)]) vertices = [] # left point vertex = center - (xComponent * halfSegmentLength) vertices.append(vertex) # begin upper long side vertex = vertex + (xComponent * halfSegmentWidth) + (yComponent * halfSegmentWidth) vertices.append(vertex) # end upper long side vertex = vertex + (xComponent * (length - segmentWidth)) vertices.append(vertex) # right point vertex = vertex + (xComponent * halfSegmentWidth) + (yComponent * -halfSegmentWidth) vertices.append(vertex) # begin lower long side vertex = vertex + (xComponent * -halfSegmentWidth) + (yComponent * -halfSegmentWidth) vertices.append(vertex) # end lower long side vertex = vertex + (xComponent * -(length - segmentWidth)) vertices.append(vertex) return Polygon([Point(arr[0] * scale, arr[1] * scale) for arr in vertices])
def individual(count, min_val, max_val): points = [] for i in range(count): x = randint(min_val, max_val) y = randint(min_val, max_val) points.append(Point(x, y)) return Polygon(points)
def main(): win = GraphWin("House", 600, 600) win.setCoords(0,0,600,600) Text(Point(300,10),"5 Click House").draw(win) # Draw the main house p1 = win.getMouse() p2 = win.getMouse() Rectangle(p1, p2).draw(win) # Draw the door con = (abs(p1.x) - (p2.x)) / 5 p3 = win.getMouse() d1 = Point(p3.x + con / 2, p3.y) d2 = Point(p3.x - con / 2, p1.y) Rectangle(d1, d2).draw(win) # Draw the window p4 = win.getMouse() w1 = Point(p4.x - con / 4, p4.y + con / 4) w2 = Point(p4.x + con / 4, p4.y - con / 4) Rectangle(w1, w2).draw(win) p5 = win.getMouse() Polygon(p2, Point(p1.x, p2.y), p5).draw(win) Text(Point(300,590),"I hoped you liked my house!!").draw(win) time.sleep(10) # sleep the thread for 10 seconds
def __init__(self, color, point1, point2, point3): """ Creates a Triangle. example: point1 = (1, 1) point2 = (2, 2) point3 = (2, 1) triangle = Triangle("black", point1, point2, point3) """ Character.__init__(self) self.color = color self.point1 = point1 self.point2 = point2 self.point3 = point3 self.triangle = Polygon(self.point1, self.point2, self.point3) self.triangle.setFill(color)
def __init__(self, index, window, car): self.index = index self.window = window self.x = car.x self.y = car.y self.color = "white" self.height = car.height self.width = car.width self.direction = 0 # car shape must be a polygon because rectangles are represented as two points # which prevents proper rotations and translations center = Point(self.x, self.y) p1 = (self.x - (self.width / 2), self.y - (self.height / 2)) p2 = (self.x + (self.width / 2), self.y - (self.height / 2)) p3 = (self.x + (self.width / 2), self.y + (self.height / 2)) p4 = (self.x - (self.width / 2), self.y + (self.height / 2)) points = [p1, p2, p3, p4] self.shape = Polygon(center, points) self.shape.setFill(self.color)
def draw_hexagon(): """ 3. Write a function draw_hexagon() that allows the user to draw a hexagon (a shape with six vertices (points)) on a graphics window. The function should allow the user to click on their chosen locations for the hexagon's vertices, and then draw the hexagon (filled in red). Hint: A hexagon is a Polygon, and you can make a Polygon object from a list of Point objects. """ win = GraphWin("Hexagon", 500, 500) vertexes = [] for vertices in range(6): vertexes.append(win.getMouse()) print("That's point", vertices + 1) hexagon = Polygon(*vertexes).draw(win) hexagon.setFill("red") win.getMouse() win.close()
def draw_house(door_colour, lights_on, n, size): win = GraphWin("House", 100 * size, 100 * size) win.setCoords(0, 0, 1, 1) roof = Polygon(Point(0.01, 0.7), Point(0.22, 0.992), Point(0.78, 0.992), Point(0.992, 0.7)) roof.setFill("pink") roof.draw(win) # draw wall and door draw_rectangle(win, Point(0.008, 0.008), Point(0.992, 0.7), "brown") draw_rectangle(win, Point(0.15, 0.008), Point(0.4, 0.45), door_colour) # draw door number door_n = Text(Point(0.275, 0.35), n) door_n.setSize(4 + 2 * size) if door_colour == "black": door_n.setFill("white") door_n.draw(win) # draw window if lights_on: window_colour = "yellow" else: window_colour = "black" draw_rectangle(win, Point(0.55, 0.15), Point(0.85, 0.45), window_colour)
class CarShape(): """Defines a shape object to be used for drawing the corresponding Car object with the same index""" def __init__(self, index, window, car): self.index = index self.window = window self.x = car.x self.y = car.y self.color = "white" self.height = car.height self.width = car.width self.direction = 0 # car shape must be a polygon because rectangles are represented as two points # which prevents proper rotations and translations center = Point(self.x, self.y) p1 = (self.x - (self.width / 2), self.y - (self.height / 2)) p2 = (self.x + (self.width / 2), self.y - (self.height / 2)) p3 = (self.x + (self.width / 2), self.y + (self.height / 2)) p4 = (self.x - (self.width / 2), self.y + (self.height / 2)) points = [p1, p2, p3, p4] self.shape = Polygon(center, points) self.shape.setFill(self.color) def draw(self): self.shape.draw(self.window) def render(self): dx = self.x - self.shape.center.x dy = self.y - self.shape.center.y self.rotate(dx, dy) self.shape.move(dx, dy) def rotate(self, dx, dy): if dx == 0 and dy == 0: return new_direction = math_utils.degrees_clockwise(dx, dy) degrees = float(self.direction - new_direction) if abs(degrees) > 5: self.shape.rotate(degrees) self.direction = new_direction def clicked(self, p): x_points = [point[0] for point in self.shape.points] y_points = [point[1] for point in self.shape.points] xmin = min(x_points) xmax = max(x_points) ymin = min(y_points) ymax = max(y_points) return (xmin <= p.getX() <= xmax and ymin <= p.getY() <= ymax)
def draw_house(win, door_colour, lights_on, n, size): roof = Polygon( Point(n * size + 0.01, 0.7), Point(n * size + 0.22, 0.992), Point(size * (n + 1) - 0.22, 0.992), Point(size * (n + 1) - 0.008, 0.7), ) roof.setFill("pink") roof.draw(win) # draw wall and door draw_rectangle(win, Point(n * size + 0.008, 0.008), Point(size * (n + 1) - 0.008, 0.7), "brown") draw_rectangle(win, Point(n * size + 0.15 * size, 0.008), Point(size * (n + 1) - 0.6 * size, 0.45), door_colour) # draw door number door_n = Text(Point(n * size + 0.275 * size, 0.35), n + 1) door_n.setSize(4 + 2 * size) if door_colour == "black": door_n.setFill("white") door_n.draw(win) # draw window if lights_on: window_colour = "yellow" else: window_colour = "black" draw_rectangle(win, Point(n * size + 0.55 * size, 0.15), Point(size * (n + 1) - 0.15 * size, 0.45), window_colour)
def draw_patch_one(win, x, y, colour): patch_shapes = [] even_positions, odd_positions = [20, 60], [0, 40, 80] # Loop through the rows and columns of the patch # to define the square, tilted square, and inner circle for row in range(0, 100, 20): for column in range(0, 100, 20): square = Rectangle(Point(x + column, y + row), Point(x + column + 20, y + row + 20)) # Set the square fill colour if # it is in rows 2 or 4 or columns 1, 3, or 5 if row in even_positions or column in odd_positions: square.setFill(colour) # Set the tilted square if # it is in rows 1, 3, or 5 and columns 2 or 4 if row in odd_positions and column in even_positions: tilted_square = Polygon(Point(x + column, y + row + 10), Point(x + column + 10, y + row), Point(x + column + 20, y + row + 10), Point(x + column + 10, y + row + 20)) tilted_square.setFill(colour) patch_shapes.append(tilted_square) circle = Circle(Point(x + column + 10, y + row + 10), 5) circle.setFill("white") for shape in [square, circle]: patch_shapes.append(shape) patch_box = draw_patch_box(x, y) for shape in patch_shapes: shape.draw(win).setOutline("") drawn, design, elements = True, "1", [patch_box, patch_shapes] return [colour, drawn, design, x, y, elements]
def drawPiece(pieceCode, x, y): if pieceCode == 1: color, mirror, shape, xEye = pieceColors[0], -1, horseShape, 60 elif pieceCode == 2: color, mirror, shape, xEye = pieceColors[0], 1, appleShape, 0 elif pieceCode == -1: color, mirror, shape, xEye = pieceColors[1], 1, horseShape, 40 else: color, mirror, shape, xEye = pieceColors[1], 1, appleShape, 0 poly = Polygon([Point(x + 50 + mirror * (xPoint - 50) * squareSize / 100, y + yPoint * squareSize / 100) for (xPoint, yPoint) in shape]) poly.setFill(color) poly.setOutline("black") poly.setWidth(2) poly.draw(win) if xEye > 0: eye = Circle(Point(x + xEye * squareSize / 100, y + 30), 3) eye.setFill("black") eye.setOutline("black") eye.setWidth(1) eye.draw(win)
def decode(cls, obj_file: str) -> 'Scene': from scene import Scene # Returns a Scene with the window and objects found vertices = [] objs: List[GraphicObject] = [] window = None current_name = '' filled = False for line in obj_file.splitlines(): cmd, *args = line.split(' ') if cmd == 'v': vertices.append(Vec2(float(args[0]), float(args[1]))) elif cmd == 'o': current_name = ' '.join(args) elif cmd == 'usemtl': if args[0] == 'filled': filled = True elif cmd == 'p': objs.append( Point(pos=vertices[int(args[0]) - 1], name=current_name)) elif cmd == 'l': if len(args) == 2: objs.append( Line(start=vertices[int(args[0]) - 1], end=vertices[int(args[1]) - 1], name=current_name)) elif args[0] == args[-1]: objs.append( Polygon( vertices=[vertices[int(i) - 1] for i in args[:-1]], name=current_name, filled=filled)) filled = False else: objs.append( Curve( vertices=[vertices[int(i) - 1] for i in args], name=current_name, )) elif cmd == 'w': window = Window(min=vertices[int(args[0]) - 1], max=vertices[int(args[1]) - 1]) return Scene(objs=objs, window=window)
class Triangle(Character): def __init__(self, color, point1, point2, point3): """ Creates a Triangle. example: point1 = (1, 1) point2 = (2, 2) point3 = (2, 1) triangle = Triangle("black", point1, point2, point3) """ Character.__init__(self) self.color = color self.point1 = point1 self.point2 = point2 self.point3 = point3 self.triangle = Polygon(self.point1, self.point2, self.point3) self.triangle.setFill(color) def move(self, dx, dy): """ Move the triangle to the right dx (or to left if negative) and move it up dy amount (or down if negative) """ self.point1 = (self.point1[0]+dx, self.point1[1]+dy) self.point2 = (self.point2[0]+dx, self.point2[1]+dy) self.point3 = (self.point3[0]+dx, self.point3[1]+dy) self.trianglem.move(dx, dy) def rotate(self, angle, x=0, y=0): pass def recolor(self, new_color): self.triangle.recolor(new_color) def scale(self, amount): pass def draw(self, window): self.triangle.draw(window) def undraw(self): self.triangle.undraw()
def on_ok(self, widget): window = self.builder.get_object('new_object_window') notebook = self.builder.get_object('notebook1') page_num = notebook.get_current_page() name = entry_text(self, 'entry_name') if NB_PAGES[page_num] == 'point': x = float(entry_text(self, 'entryX')) y = float(entry_text(self, 'entryY')) self.dialog.new_object = Point(Vec2(x, y), name=name) elif NB_PAGES[page_num] == 'line': y2 = float(entry_text(self, 'entryY2')) x1 = float(entry_text(self, 'entryX1')) y1 = float(entry_text(self, 'entryY1')) x2 = float(entry_text(self, 'entryX2')) self.dialog.new_object = Line(Vec2(x1, y1), Vec2(x2, y2), name=name) elif NB_PAGES[page_num] == 'polygon': if len(self.vertices) >= 3: filled = self.builder.get_object('switch_filled').get_active() self.dialog.new_object = Polygon(self.vertices, name=name, filled=filled) elif NB_PAGES[page_num] == 'curve': if self.builder.get_object('btn_bezier').get_active(): type = 'bezier' elif self.builder.get_object('btn_b-spline').get_active(): type = 'b-spline' if len(self.vertices) >= 4: self.dialog.new_object = Curve.from_control_points( self.vertices, type=type, name=name, ) else: raise ValueError('No page with given index.') window.destroy()
def main(): win = GraphWin("Five Click House", 500, 500) win.setBackground(color_rgb(43, 43, 43)) p = win.getMouse() p1 = Point(p.getX(), p.getY()) p = win.getMouse() p2 = Point(p.getX(), p.getY()) base = Rectangle(p1, p2) # Base of the house, initial rectangle. base.setOutline(color_rgb(180, 180, 180)) base.draw(win) dist = sqrt((p2.getX() - p1.getX())**2 + (p2.getY() - p1.getY())**2) # Distance between p1 and p2. baseHeight = p1.getY() - p2.getY() # Height of the 'base' object. baseWidth = p2.getX() - p1.getX() # Width of the 'base' object. doorWidth = (baseWidth / 5) p = win.getMouse() p3 = Point(p.getX(), p.getY()) # Third Mouse Click. p4 = Point((p3.getX() - doorWidth / 2), p3.getY()) # Top left of door. p5 = Point(p3.getX() + doorWidth / 2, p1.getY()) # Bottom right of the door. door = Rectangle(p4, p5) door.setOutline(color_rgb(180, 180, 180)) door.draw(win) p = win.getMouse() p6 = Point(p.getX(), p.getY()) # Fourth Click. p7 = Point(p6.getX() - doorWidth / 4, p6.getY() - doorWidth / 4) # Top left of the window. p8 = Point(p6.getX() + doorWidth / 4, p6.getY() + doorWidth / 4) # Bottom right of the window window = Rectangle(p7, p8) window.setOutline(color_rgb(180, 180, 180)) window.draw(win) p = win.getMouse() p9 = Point(p.getX(), p.getY()) # Fifth Mouse Click, also tip of roof. p10 = Point(p1.getX(), p1.getY() - baseHeight) # Left corner of roof. p11 = Point(p2.getX(), p2.getY()) # Right corner of roof. roof = Polygon(p9, p10, p11) roof.setOutline(color_rgb(180, 180, 180)) roof.draw(win) print("Distance between p1 and p2:", dist) print("p1 x:", p1.getX(), "\np1 y:", p1.getY(), "\np2 x:", p2.getX(), "\np2 y:", p2.getY()) print("Base Height:", baseHeight, "\nBase Width:", baseWidth) win.getMouse() win.close()
def evolve(pop, retain=0.2, random_select=0.05, mutate=0.01): graded = [(fitness(x), x) for x in pop] graded = [x[1] for x in sorted(graded, key=itemgetter(0))] retain_length = int(len(graded) * retain) parents = graded[:retain_length] # randomly add other individuals to promote genetic diversity for indie in graded[retain_length:]: if random_select > random(): parents.append(indie) # mutate some individuals for indie in parents: if mutate > random(): pos_to_mutate = randint(0, len(indie.points) - 1) # this mutation is not ideal, because it # restricts the range of possible values, # but the function is unaware of the min/max # values used to create the individuals, points_x = [p.x for p in indie.points] points_y = [p.y for p in indie.points] indie.points[pos_to_mutate] = Point( randint(min(points_x), max(points_x)), randint(min(points_y), max(points_y))) # crossover parents to create children parents_length = len(parents) desired_length = len(pop) - parents_length children = [] while len(children) < desired_length: male = randint(0, parents_length - 1) female = randint(0, parents_length - 1) if male != female: male = parents[male] female = parents[female] half = int(len(male.points) / 2) child = Polygon(male.points[:half] + female.points[half:]) children.append(child) parents.extend(children) return parents
def draw_pikman(pik_location, pik_color1): if pik_color1 == "yellow": pik_color1 = "orange" draw_circle(pik_location[1], pik_location[0], pik_color1, size) else: pik_color1 = "yellow" draw_circle(pik_location[1], pik_location[0], pik_color1, size) # head = Circle(Point((board_column * (size * 2) + (offsetC + dot_size)), # (board_row * (size * 2) + (offsetR + dot_size))), dot_size) head1 = Polygon( Point((pik_location[1] * (size * 2) + (offsetC + size)), (pik_location[0] * (size * 2) + (offsetR + size))), Point((pik_location[1] * (size * 2) + offsetC + size * 2), (pik_location[0] * (size * 2) + offsetR + size * 2)), Point((pik_location[1] * (size * 2) + offsetC + size * 2), (pik_location[0] * (size * 2) + (offsetR + size)))) head1.setFill("black") head1.draw(win) return pik_color1
def polygon(*points: Tuple[float, float]) -> Polygon: return Polygon([Point(x, y) for x, y in points])
from graphics import GraphWin, Circle, Point, Polygon, color_rgb, Rectangle, Line win = GraphWin("Remember Mister Yuck?", 600, 600) # Green Head head = Circle(Point(299, 299), 250) head.setFill(color_rgb(90, 255, 84)) head.draw(win) # Left Eyebrow Polygon left_brow = Polygon(Point((299 - 59), (299 - 139)), Point((299 - 67), (299 - 126)), Point((299 - 134), (299 - 149)), Point((299 - 119), (299 - 179))) left_brow.setFill('black') left_brow.draw(win) # Right Eyebrow Polygon right_brow = Polygon(Point((299 + 59), (299 - 139)), Point((299 + 67), (299 - 126)), Point((299 + 134), (299 - 149)), Point((299 + 119), (299 - 179))) right_brow.setFill('black') right_brow.draw(win) # Left Eye Polygon left_eye = Polygon(Point((299 - 58), (299 - 112)), Point((299 - 75), (299 - 82)), Point((299 - 90), (299 - 100)), Point((299 - 134), (299 - 75)), Point((299 - 141), (299 - 93)),
def display_grid(state: State, win: GraphWin, square_size: float): ''' Displays the current grid in the graphics window ''' for r in range(state.num_of_rows()): for c in range(state.num_of_cols()): square = Rectangle( Point(square_size * c, square_size * r), Point(square_size * c + square_size, square_size * r + square_size)) square.draw(win) square.setFill('white') if state.grid[r][c] == 1: if state.facing == Facing.RIGHT: robot = Polygon( Point(square_size * c, square_size * r), Point(square_size * c + square_size, square_size * r + 10), Point(square_size * c, square_size * r + square_size)) elif state.facing == Facing.LEFT: robot = Polygon( Point(square_size * c + square_size, square_size * r), Point(square_size * c, square_size * r + 10), Point(square_size * c + square_size, square_size * r + square_size)) elif state.facing == Facing.UP: robot = Polygon( Point(square_size * c, square_size * r + square_size), Point(square_size * c + square_size, square_size * r + square_size), Point(square_size * c + 10, square_size * r)) elif state.facing == Facing.DOWN: robot = Polygon( Point(square_size * c, square_size * r), Point(square_size * c + square_size, square_size * r), Point(square_size * c + 10, square_size * r + square_size)) robot.draw(win) robot.setFill('black')
from graphics import GraphWin, Polygon, Point, color_rgb from random import randint # Create Window win = GraphWin("Draw Triangle", 600, 600) # Get 3 clicks points = [] for i in range(3): point = win.getMouse() point.draw(win) points.append(point) # Take those 3 Points and Draw a triangle with random fill color shape = Polygon(*points) shape.setFill(color_rgb(randint(0, 255), randint(0, 255), randint(0, 255))) shape.draw(win) win.getMouse() win.close()
def endGame(field, game_panel, player_name, score): # Let the user know the game is finished end_game_text = Text(Point(200, 200), "Finished! Click to close") end_game_text.draw(field) # Draw graphic objects at different places that represent balloons with a # string connected to it. balloon_1 = Circle(Point(145, 110), 18) balloon_1.setFill("red") balloon_1.setOutline("red") balloon_1.draw(field) triangle_1 = Polygon(Point(137, 135), Point(145, 128), Point(153, 135)) triangle_1.setFill("red") triangle_1.setOutline('red') triangle_1.draw(field) string_1 = Line(Point(145, 135), Point(145, 180)) string_1.draw(field) balloon_2 = Circle(Point(340, 300), 18) balloon_2.setFill("red") balloon_2.setOutline("red") balloon_2.draw(field) triangle_2 = Polygon(Point(332, 325), Point(340, 318), Point(348, 325)) triangle_2.setFill("red") triangle_2.setOutline('red') triangle_2.draw(field) string_2 = Line(Point(340, 325), Point(340, 370)) string_2.draw(field) balloon_3 = Circle(Point(75, 275), 18) balloon_3.setFill("red") balloon_3.setOutline("red") balloon_3.draw(field) triangle_3 = Polygon(Point(67, 300), Point(75, 293), Point(83, 300)) triangle_3.setFill("red") triangle_3.setOutline('red') triangle_3.draw(field) string_3 = Line(Point(75, 300), Point(75, 345)) string_3.draw(field) # Create a while loop that moves the objets every 0.05 seconds upwards to # make it appear as if they are floating while True: sleep(0.05) balloon_1.move(0, -10) triangle_1.move(0, -10) string_1.move(0, -10) balloon_2.move(0, -10) triangle_2.move(0, -10) string_2.move(0, -10) balloon_3.move(0, -10) triangle_3.move(0, -10) string_3.move(0, -10) # If a click is detetced in the field, the window will close even if the # balloons are still moving in the while loop click = field.checkMouse() if click != None: break # Add player score to top_scores.txt writeScores(player_name, score) # Set close condition to True close = True # Return close condition return close
left_circle = Circle(Point(200, 200), 100) left_circle.setFill("red") left_circle.setOutline("red") left_circle.draw(win) right_circle = left_circle.clone() right_circle.move(200, 0) right_circle.draw(win) p1 = Point(110, 245) p2 = Point(300, 500) p3 = Point(490, 245) p4 = Point(300, 200) bottom = Polygon(p1, p2, p3, p4) bottom.setFill("red") bottom.setOutline("red") bottom.draw(win) happy = Text(Point(300, 240), "Happy") happy.setFill("white") happy.setSize(32) happy.draw(win) valentines = Text(Point(300, 280), "Valentine's") valentines.setFill("white") valentines.setSize(32) valentines.draw(win) day = Text(Point(300, 320), "Day")
def pause_menu(right): start = 500 if right else 0 prior = len(gw.items) pause_overlay = Image(Point(500, 250), MAP / "pause_overlay.png") pause_overlay.draw(gw) # Everything for the Character Information info_box = Rectangle(Point(551 - start, 100), Point(959 - start, 400)) info_box.setFill(color_rgb(50, 50, 50)) info_box.setWidth(3) info_box.draw(gw) # The Character Icon info_icon = Image(Point(613 - start, 163), MAPS / "characters" / f"{player.character_class}_portrait.png") info_icon.draw(gw) # Shows the Header that includes the player's name and level. info_header = Text(Point(572 - start, 179)) info_header.setAnchor("w") info_header.setSize(22) info_header.setText(f" {player.name + f'LV: {player.lvl}'.rjust(16)[len(player.name):]}\n HP:\n EXP:\nItems:") info_header.draw(gw) # Draw the HP bar. hp_bar = Bar(player.current_HP, player.base_HP, "red", Point(750 - start, 149), Point(948 - start, 173)) hp_bar.show() # Draws the EXP bar exp_bar = Bar(player.current_EXP, player.next_EXP, "green", Point(750 - start, 179), Point(948 - start, 203)) exp_bar.show() # Lists off the player's current inventory. info_header_underline = Line(Point(573 - start, 240), Point(937 - start, 240)) info_header_underline.setWidth(1) info_header_underline.setOutline("white") info_header_underline.draw(gw) info_footer = Text(Point(573 - start, 246)) info_footer.setAnchor("nw") info_footer.setSize(14) info_footer.setText(inventory()) info_footer.draw(gw) # Lists off the pause menu options. choice_box = Rectangle(Point(start + 125, 165), Point(start + 370, 335)) choice_box.setFill(color_rgb(50, 50, 50)) choice_box.setWidth(3) choice_box.draw(gw) choice_text = Text(Point(start + 260, 250)) choice_text.setAnchor("c") choice_text.setSize(20) choice_text.setText("Resume\nDrink Potion\nEat Apple\nSave Game\nQuit Game") choice_text.draw(gw) selector = Polygon(Point(start + 137, 183), Point(start + 137, 195), Point(start + 154, 189)) selector.setFill("red") selector.draw(gw) selection = 0 saved = False while True: while True: key = gw.checkKey().lower() if key != "": if key in ["space", "return"]: break elif key in ["escape"]: while selection > 0: selector.move(0, -30) selection -= 1 if key in ["up", "w", "left", "a"]: selection = (selection - 1) % 5 if selection != 4: selector.move(0, -30) else: selector.move(0, 120) elif key in ["down", "s", "right", "d"]: selection = (selection + 1) % 5 if selection != 0: selector.move(0, 30) else: selector.move(0, -120) # Resume Game if selection == 0: for i in gw.items[prior:]: i.undraw() return # Drink Potion if selection == 1: if player.items["Potions"] == 0: dialogue("You have no more potions to drink.", right=right) elif player.current_HP == player.base_HP: dialogue("You are already at max HP", right=right) else: player.items["Potions"] -= 1 player.current_HP += round(randint(4, 10) * 4.2) if player.current_HP > player.base_HP: player.current_HP = player.base_HP hp_bar.update(player.current_HP, player.base_HP) # Eat Apple if selection == 2: if player.items["Apples"] == 0: dialogue("You have no more apples to eat.", right=right) elif player.current_HP == player.base_HP: dialogue("You are already at max HP", right=right) else: player.items["Apples"] -= 1 player.current_HP += randint(1, 4) if player.current_HP > player.base_HP: player.current_HP = player.base_HP hp_bar.update(player.current_HP, player.base_HP) # Save Game if selection == 3: saved = True save_state = open("save_state.txt", "w") stats_to_save = [player.character_class, player.name, player.lvl, player.attack, player.defense, player.current_HP, player.base_HP, player.current_SP, player.base_SP, player.current_EXP, player.next_EXP, player.gold, player.items, game_stats ] line_to_save = '' for i in stats_to_save: line_to_save = line_to_save + str(i) + "\n" save_state.write(b64encode(line_to_save.encode("UTF-8")).decode("UTF-8")) save_state.close() dialogue("Game saved.", right=right) # Quit Game if selection == 4: if not saved: dialogue(f"You have not saved recently.") if dialogue("Are you sure you want to quit?", ["Yes", "No"], right=right) == 0: raise GameOver('Town Quit') info_footer.setText(inventory())
def draw_gui(): """Create the graphics window and draw the target.""" # create the window win = GraphWin("Archery game", 500, 500) win.setBackground("cyan") win.setCoords(0, 0, 1, 1) centre = Point(0.5, 0.5) # draw the grass ground_rect = Rectangle(Point(-0.01, -0.01), Point(1.01, 0.5)).draw(win) ground_rect.setFill("green") # draw the target legs left_target_stand = Polygon(Point(0.02, -0.01), Point(0.45, 0.5), Point(0.55, 0.5), Point(0.12, -0.01)).draw(win) left_target_stand.setFill("brown") left_target_stand.setWidth(2) right_target_stand = Polygon(Point(0.98, -0.01), Point(0.55, 0.5), Point(0.45, 0.5), Point(0.88, -0.01)).draw(win) right_target_stand.setFill("brown") right_target_stand.setWidth(2) # draw the target draw_circle(win, centre, 0.3, "blue") draw_circle(win, centre, 0.2, "red") draw_circle(win, centre, 0.1, "yellow") # draw the text displaying the score score = 0 score_text = Text(Point(0.5, 0.04), f"Score: {score}").draw(win) score_text.setSize(18) score_text.setStyle("bold") # draw the text displaying where an arrow has landed zone_text = Text(Point(0.5, 0.09), "").draw(win) zone_text.setSize(12) zone_text.setStyle("bold") # draw the text describing wind conditions wind_text = Text(Point(0.5, 0.97), "Wind: ").draw(win) wind_text.setSize(12) wind_text.setStyle("bold") return win, wind_text, zone_text, score_text, score
# This program draws a user's traiangle. from graphics import GraphWin, Point, Text, Polygon win = GraphWin("Draw a Triangle") win.setCoords(0.0, 0.0, 10.0, 10.0) textMessage = Text(Point(5, 0.5), "Click on Three Points") textMessage.draw(win) point1 = win.getMouse() point1.draw(win) point2 = win.getMouse() point2.draw(win) point3 = win.getMouse() point3.draw(win) triangle = Polygon(point1, point2, point3) triangle.setFill("peachpuff") triangle.setOutline("cyan") triangle.draw(win) input("Press enter to close")
def dialogue(line, choices = [], color=["white"], return_arg=False, right=False, speed=.02, type_length=0): # Initialize variables that will be used later. start = 500 if right else 0 selection = 0 prior = len(gw.items) if type(color) == str: color=[color] # Create the dialogue box dialogue_box = Rectangle(Point(start + 11, 403), Point(start + 489, 488)) dialogue_box.setFill(color_rgb(50, 50, 50)) dialogue_box.setWidth(3) dialogue_box.draw(gw) # Create the Text objects that will display dialogue. texts = [] for i in color: text = Text(Point(start + 25, 418), "") text.setTextColor(i) text.setSize(20) text.setAnchor("nw") text.draw(gw) texts.append(text) line = line.split() text_num = 0 num_texts = len(texts) line_length = 0 overflow = 0 skip = False for word in line: word_length = len(word) if line_length + word_length + 1 > 29: word = '\n' + word line_length = 0 overflow += 1 line_length += word_length + 1 if overflow > 1: for j in texts: j.setText(j.getText()[j.getText().index("\n") + 1:]) overflow = 1 for j in word + ' ': if j == '`': text_num += 1 else: for k in range(num_texts): key = gw.checkKey().lower() if key in ["return", "space", "escape"]: skip = True if k == text_num: texts[k].setText(texts[k].getText() + j) elif j == '\n': texts[k].setText(texts[k].getText() + '\n') else: texts[k].setText(texts[k].getText() + ' ') if not skip: sleep(speed) # If type_length is 0 and the array of choices that is passed in isn't empty, the player is supposed # to make a selection from a list of choices. length_choices = len(choices) if type_length == 0: center = 374 - (30 * (length_choices - 1)) selector = Polygon(Point(start + 478, center - 6), Point(start + 478, center + 6), Point(start + 461, center)) selector.setFill("red") if length_choices > 0: answer = "" longest_answer = 0 for i in choices: answer += f"{i}\n" longest_answer = max(longest_answer, len(i)) answer = answer[:-1] choice_box = Rectangle(Point(start + 473 - (16 * (longest_answer + 2)), 382 - (30 * length_choices)), Point(start + 489, 395)) choice_box.setFill(color_rgb(50, 50, 50)) choice_box.setWidth(3) choice_box.draw(gw) choice_text = Text(Point(start + 453, 390), "") choice_text.setAnchor("se") choice_text.setJustification("right") choice_text.setSize(20) choice_text.draw(gw) choice_text.setText(answer) selector.draw(gw) while True: key = gw.checkKey().lower() if key != "": if key in ["space", "return"]: break elif key in ["escape"]: while selection < length_choices - 1: selector.move(0, 30) selection += 1 elif key in ["m", "shift_l"]: pause_menu(not right) elif length_choices > 0: if key in ["up", "w", "left", "a"]: selection = (selection - 1) % length_choices if selection != length_choices - 1: selector.move(0, -30) else: selector.move(0, 30 * (length_choices - 1)) elif key in ["down", "s", "right", "d"]: selection = (selection + 1) % length_choices if selection != 0: selector.move(0, 30) else: selector.move(0, -30 * (length_choices - 1)) # Else, the player is typing in some response. # This is only used a couple times in play_game.py elif type_length > 0: selection = "" shown_name = Text(Point(250 - (16 * type_length) // 2, 467)) shown_name.setText("") shown_name.draw(gw) text_underline = shown_name.clone() text_underline.setText("-" * type_length) text_underline.move(0, 13) text_underline.draw(gw) bar = shown_name.clone() bar.move(-7, 0) bar.setText('|') bar.draw(gw) bar_flash = 0 bar_shown = True while True: key = gw.checkKey() if key: if len(selection) < type_length and key in alphabet + punctuation: if key == 'space': selection += ' ' else: selection += key bar.move(16, 0) elif len(selection) > 0 and key == 'BackSpace': selection = selection[:-1] bar.move(-16, 0) elif key == 'Return': break bar_flash = 0 if not bar_shown: bar_shown = True bar.draw(gw) shown_name.setText(selection) else: bar_flash += 1 if bar_flash == 40000: bar_flash = 0 if bar_shown: bar_shown = False bar.undraw() else: bar_shown = True bar.draw(gw) gw.clear(prior) if length_choices == 0 and type_length == 0: return -1 elif return_arg: return choices[selection].split(":")[0] else: return selection