def __init__(self, board): super().__init__() self.boardColor = (255, 255, 255, 0) self.fillColor = (0, 0, 0, 0) self.scale = 8 self.board = board self.pencil = Pen(self)
def __init__(self): """Set the HUD elements.""" if Display.hud is None: Display.hud = Display.HUD() Display.hud.start() if Display.canvas is None: Display.canvas = turtle.screen.getcanvas() Display.debug_pen = Pen() self.pen = Pen()
class BoardSurface(object): def __init__(self, board): super().__init__() self.boardColor = (255, 255, 255, 0) self.fillColor = (0, 0, 0, 0) self.scale = 8 self.board = board self.pencil = Pen(self) def setSurface(self, surface): self.surface = surface self.surface.fill(self.boardColor) def getDimension(self): return (self.scale * len(self.board.cells), self.scale * len(self.board.cells[0])) def contains(self, point): rel = self.sub(point, self.surface.get_abs_offset()) dim = Rect((0, 0), self.getDimension()) return dim.collidepoint(rel) def globalToBoard(self, pos): offset = self.surface.get_abs_offset() return self.sub(pos, offset) def sub(self, u, v): return [u[i] - v[i] for i in range(len(u))] def fill(self, points): for point in points: self.board.fill(int(point[0] / self.scale), int(point[1] / self.scale)) self.update() def update(self, event=None, force=False): if self.pencil: self.pencil.update(event) if (self.board.dirty or force): self.board.dirty = False for x in range(len(self.board.cells)): for y in range(len(self.board.cells[0])): cell = self.board.cells[x][y] x1 = x * self.scale y1 = y * self.scale width = self.scale height = self.scale if (cell): pygame.draw.rect(self.surface, self.fillColor, (x1, y1, width, height)) else: pygame.draw.rect(self.surface, self.boardColor, (x1, y1, width, height))
class OptionsScreen(Screen): def __init__(self, name): super().__init__(name) self.options = defaults self.option_pos_map = {4: "bots", 3: "difficulty", 2: "grid_size"} self.text_pen = Pen() def increment_value(self): """Increases value for option according to cursor position.""" if self.curr_cursor_idx in self.option_pos_map: name = self.option_pos_map[self.curr_cursor_idx] max_value = self.options[name]["max"] curr_value = self.get_option_value(name) if curr_value < max_value: self.set_option_value(name, curr_value + 1) self.draw_option_values() def decrement_value(self): """Decreases value for option according to cursor position.""" if self.curr_cursor_idx in self.option_pos_map: name = self.option_pos_map[self.curr_cursor_idx] min_value = self.options[name]["min"] curr_value = self.get_option_value(name) if curr_value > min_value: self.set_option_value(name, curr_value - 1) self.draw_option_values() def get_option_value(self, name): return self.options[name]["value"] def set_option_value(self, name, value): self.options[name]["value"] = value def draw_option_values(self): self.text_pen.clear() y_offset = 180 options = [ self.options["bots"], self.options["difficulty"], self.options["grid_size"], ] for option in options: self.text_pen.setposition(300, y_offset) self.text_pen.pendown() value = option["value"] if "labels" in option: idx = option["value"] - 1 value = option["labels"][idx] self.text_pen.write(value, align="center", font=self.text_pen.font) self.text_pen.penup() y_offset -= 140
def drawPaint(): global mode, poslist, pList, lines, firstpos, secondpos, paintmode if mode == "paint": global weight, strokecolor, positions global firstpos, secondpos, lines stroke(strokecolor) pos = mouseX, mouseY updates(pos) drawInstruction() drawMode() if inBoard(pos): if mousePressed and paintmode == "Stroke": noStroke() fill(strokecolor) ellipse(mouseX, mouseY, weight * 2, weight * 2) col = strokecolor new = Pen(PVector(mouseX, mouseY), col, weight * 2) poslist.append(new) elif paintmode == "Line": pos = mouseX, mouseY updatescreen(pos) global lines for lineSeg in lines: lineSeg.display() """
def aStar(mazeObject, start, end, verbose=False): if verbose: pen = Pen() pen.color("yellow") q = PriorityQueue() g_cost = 0 h_cost = manhattan_distance(start, end) startNode = Node(start, g_cost, h_cost) f_cost = startNode.g + startNode.h q.put((f_cost, startNode)) closed = set() while not q.empty(): checkNode = q.get() current_F = checkNode[0] node = checkNode[1] # g_cost = 1 # h_cost = how far it is from the end node # f_cost = g_cost + h_cost if node.point == end: if verbose: pen2 = Pen() pen2.color("red") retracePath(node.parent, pen2) print("Retraced Path") return closed.add(node.point) if verbose and node.point != start: pen.draw(node.point[0], node.point[1], 300) for neighbor in mazeObject.getNeighbors(node.point[0], node.point[1]): if neighbor in closed: continue g_cost = node.g + 1 h_cost = manhattan_distance(neighbor, end) f_cost = g_cost + h_cost # print(f"Test: {f_cost}") childNode = Node(neighbor, g_cost, h_cost, node) if f_cost < current_F or neighbor not in [ element[1].point for element in q.queue ]: if neighbor not in [element[1].point for element in q.queue]: q.put((f_cost, childNode)) return 0
def dijkstra(mazeObject, destination_i, destination_j, verbose=False): if verbose: pen = Pen() pen.color("yellow") maze = np.asarray(mazeObject.maze) dmaze = [[None for _ in range(len(maze))] for __ in range(len(maze))] unvisited = set() # print(dmaze) for i in range(len(maze)): for j in range(len(maze)): if maze[i, j] == 0: if i == 0 and j == 0: dmaze[i][j] = Node(i, j, 0) unvisited.add((i, j)) else: cell = Node(i, j, math.inf) dmaze[i][j] = cell unvisited.add((i, j)) current_spot = (0, 0) while not dmaze[destination_i][destination_j].visited: x = current_spot[0] y = current_spot[1] for neighbor in mazeObject.getNeighbors(x, y): cell = dmaze[neighbor[0]][neighbor[1]] if not cell.visited: if verbose and not (x == 0 and y == 0) and not ( x == destination_i and y == destination_j): pen.draw(x, y, 300) distance = 1 + dmaze[x][y].distance if distance < cell.distance: cell.distance = distance dmaze[x][y].visited = True unvisited.remove((x, y)) min_distance = math.inf for nodes in list(unvisited): x = nodes[0] y = nodes[1] # print(f"Get Next Node{x}:{y}") if dmaze[x][y].distance < min_distance: current_spot = nodes min_distance = dmaze[x][y].distance # print(f"Next Neighbor{current_spot[0]}:{current_spot[1]}") # print(f"Done: {dmaze[destination_i][destination_j].distance}") return dmaze[destination_i][destination_j].distance, dmaze
self.bounds = [max(x2 - x, 1), max(y2 - y, 1)] self.request_redraw() def normal_left_down(self, event): print "Text [%s] selected at (%d, %d)" % (self.text, event.x, event.y) #------------------------------------------------------------------------------ # Stand-alone call: #------------------------------------------------------------------------------ if __name__ == "__main__": from godot.component.component_viewer import ComponentViewer from enthought.enable.api import Container text = Text(pen=Pen(), text="Foo", text_x=50, text_y=50, text_w=30) container = Container( # fit_window=False, auto_size=True, bounds=[30, 10], position=[50, 50], bgcolor="green") container.add(text) viewer = ComponentViewer(component=text) viewer.configure_traits() # EOF -------------------------------------------------------------------------
#!/usr/bin/env python3 from random import * from paper import Paper from pen import Pen from path import Path from point import Point fuscia = Pen(weight = 0.5, color = "#f09") cyan = Pen(weight = 0.5, color = "#09f") black = Pen(weight = 0.5) paper = Paper(pens = [black], width = 105, height = 73) def getSquare(p, size): square = Path(points = [ Point(p.x + size / 2, p.y + size / 2), Point(p.x + size / 2, p.y - size / 2), Point(p.x - size / 2, p.y - size / 2), Point(p.x - size / 2, p.y + size / 2) ], closed = True) return square def randomise(path, distance): for p in path.points: p.moveVector(360 * random(), distance * random()) square = getSquare(paper.center, 36).setPen(cyan) randomise(square, 7)
# Paddle A paddle_a = Paddle(-350) # Paddle B paddle_b = Paddle(350) # Ball ball1 = Ball(-.25) # ball2 = Ball(.25) # ball3 = Ball(-.5) # ball4 = Ball(.5) balls = [ball1] #Pen pen = Pen() #Keyboard Binding wn.listen() wn.onkeypress(paddle_a.paddle_up, "w") wn.onkeypress(paddle_a.paddle_down, "s") wn.onkeypress(paddle_b.paddle_up, "Up") wn.onkeypress(paddle_b.paddle_down, "Down") #Main game loop game_is_on = True while game_is_on: for ball in balls: wn.update()
def create_pens(self): """Initialize all pens.""" self.border_pen = Pen("blue", 2) self.score_pen = Pen() self.game_text_pen = Pen()
screenX = -300 + ((currentNode[1] + 1) * 24) screenY = 300 - ((currentNode[0] + 1) * 24) pen.goto(screenX, screenY) pen.stamp() if __name__ == "__main__": maze = Maze(5, False) test_maze = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] maze.maze = np.asarray(test_maze) maze.printMaze() blackPen = Pen() greenPen = Pen() redPen = Pen() blackPen.color("black") greenPen.color("green") redPen.color("red") wn = turtle.Screen() wn.bgcolor("gray") wn.setup(800, 800) mazeArray = maze.drawMaze() drawMaze(mazeArray, blackPen, greenPen, maze.exit) print(maze.exit[0]) distance, dmaze = d.dijkstra(maze, maze.exit[0],
colors = [ "red", "green", "blue", "pink", "orange", "Dark Red", "AliceBlue", "cyan", "brown", "azure" ] my_snake = Snake() screen.listen() screen.onkey(my_snake.move_right, "Right") screen.onkey(my_snake.move_left, "Left") screen.onkey(my_snake.move_up, "Up") screen.onkey(my_snake.move_down, "Down") # todo: add element to tail, triggered by scheduler move_on = True food_dot = Food() pen = Pen() score = 0 while move_on: pen.update_score() move_on = my_snake.move() if my_snake.head.distance(food_dot) < 15: food_dot.new_food() my_snake.add_element_to_tail() pen.increase_score() pen.update_score() screen.update() time.sleep(0.2) pen.game_over() screen.exitonclick()
from pen import Pen my_pen = Pen() print(my_pen.getModel01()) print(f'Second private method: {my_pen._Pen__getModel02()}')
self.position = [x, y] # If bounds are set to 0, horizontal/vertical lines will not render self.bounds = [max(x2 - x, 5), max(y2 - y, 5)] self.request_redraw() #------------------------------------------------------------------------------ # Standalone call: #------------------------------------------------------------------------------ if __name__ == "__main__": from component_viewer import ComponentViewer bspline = BSpline( pen=Pen(line_width=1), points=[(37.0, 90.0), (37.0, 77.0), (37.0, 61.0), (37.0, 46.0)] #[ # (0, 50), (50, 0), (150, 0), (200, 150), # (25, 225), (75, 300), (100, 275), # (125, 200), (150, 100), (200, 25) # ], ) viewer = ComponentViewer(component=bspline) viewer.configure_traits() # EOF -------------------------------------------------------------------------
from writer import Writer from pen import Pen from typewriter import Typewriter writer = Writer('John') pen = Pen('Bic') typewriter = Typewriter() print(writer.name) print(pen.brand) print(typewriter) writer.tool = pen writer.tool.write() writer.tool = typewriter writer.tool.write() del writer print(pen.brand) pen.write() typewriter.write()
#!/usr/bin/env python3 from random import * from paper import Paper from pen import Pen from path import Path from point import Point fuscia = Pen(weight=0.5, color="#f09") cyan = Pen(weight=0.5, color="#09f") black = Pen(weight=0.25) paper = Paper(pens=[black, cyan, fuscia], width=105, height=74) def drawDot(p): size = 0.5 p1 = Point(p.x, p.y) p2 = Point(p.x, p.y) p3 = Point(p.x, p.y) p1.moveVector(0, size) p2.moveVector(120, size) p3.moveVector(240, size) return Path(points=[p1, p2, p3], closed=True).setPen(fuscia) squareSize = 40
#!/usr/bin/env python3 from random import * from paper import Paper from pen import Pen from path import Path from point import Point fuscia = Pen(weight=0.5, color="#f09") cyan = Pen(weight=0.5, color="#09f") black = Pen(weight=0.35) paper = Paper(pens=[cyan, fuscia, black], width=105, height=73) def getSquare(p, size): square = Path(points=[ Point(p.x + size / 2, p.y + size / 2), Point(p.x + size / 2, p.y - size / 2), Point(p.x - size / 2, p.y - size / 2), Point(p.x - size / 2, p.y + size / 2) ], closed=True) return square def randomise(path, distance): for p in path.points: p.moveVector(360 * random(), distance * random())
#!/usr/bin/env python3 from random import random from paper import Paper from pen import Pen from path import Path from point import Point fuscia = Pen(weight = 0.5, color = "#f09") cyan = Pen(weight = 0.5, color = "#09f") black = Pen(weight = 0.35) paper = Paper(pens = [black], width = 105, height = 73) def getSquare(p, size): square = Path(points = [ Point(p.x + size / 2, p.y + size / 2), Point(p.x + size / 2, p.y - size / 2), Point(p.x - size / 2, p.y - size / 2), Point(p.x - size / 2, p.y + size / 2) ], closed = True) return square def randomise(path, distance): for p in path.points: p.moveVector(360 * random(), distance * random()) bigSize = 32
# Don't let bounds be set to 0, otherwise, horizontal and vertical # lines will not render because enable skips rendering items with # bounds=[0,0] self.bounds = [max(x2 - x, 1), max(y2 - y, 1)] self.request_redraw() #------------------------------------------------------------------------------ # Stand-alone call: #------------------------------------------------------------------------------ if __name__ == "__main__": from pylon.ui.graph.component_viewer import ComponentViewer pen = Pen() polygon = Polygon( pen=pen, points=[(50, 50), (50, 100), (100, 100)], # bounds=[50, 50], position=[50, 50] ) viewer = ComponentViewer(component=polygon) from enthought.enable.primitives.api import Box box = Box(color="red", border_color="blue", border_size=1, bounds=[50, 50], position=[100, 100]) # viewer.canvas.add(box)
FIELD_W = 2000 FIELD_H = 2000 start_pos = Point(FIELD_W // 2, FIELD_H // 2 + FIELD_H // 3) WIDTH = pygame.display.Info().current_w HEIGHT = pygame.display.Info().current_h DISPLAY_CENTRE = (WIDTH // 2, HEIGHT // 2) blit_x, blit_y = DISPLAY_CENTRE[0] - FIELD_W // 2, DISPLAY_CENTRE[ 1] - FIELD_H // 2 sc = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) field = pygame.Surface((FIELD_W, FIELD_H)) field.fill(BACKGROUND_COLOR) p = PythagorasTree_plus p.pen = Pen(field, start_pos, BRANCH_COLOR, width=BRANCH_W) p.len_segment = BRANCH_SIZE p.draw(ITERATIONS) sc.blit(field, (blit_x, blit_y)) pygame.display.update() pygame.image.save(field, "PythagorasTree_plus.png") # main loop moved = False move_way = 0 clock = pygame.time.Clock() FPS = 2 while 1: for event in pygame.event.get():
from writer import Writer from pen import Pen from typewriter import Typewriter writer = Writer('Machado de Assis') writer2 = Writer('Napoleon Hill') pen = Pen('Bic') typewriter = Typewriter() writer.tool = pen writer2.tool = typewriter writer.tool.write() writer2.tool.write()
#!/usr/bin/env python3 from random import * from paper import Paper from pen import Pen from path import Path from point import Point fuscia = Pen(weight=0.25, color="#f09") cyan = Pen(weight=0.25, color="#0ff") black = Pen(weight=0.5) paper = Paper(pens=[cyan, black], width=105, height=73) def drawGuide(p1, p2): return Path(points=[p1, p2]).setPen(fuscia) def drawDash(p1, p2): return Path(points=[p1, p2]).setPen(black) def dashAlongLine(line, g): l = line.length() d = 0 i = 0 while d <= l - 10: if i % 2 == 0:
def __init__(self, name): super().__init__(name) self.options = defaults self.option_pos_map = {4: "bots", 3: "difficulty", 2: "grid_size"} self.text_pen = Pen()
wn.tracer(0) wn.window_height() wn.listen() # Score score_a = 0 score_b = 0 # Paddle A paddle_a = Paddle('left') # Paddle B paddle_b = Paddle('right') # Pen scoreboard = Pen() # Keyboard bindings input_a = Input('w', 's', paddle_a, wn) input_b = Input('Up', 'Down', paddle_b, wn) # Block block = Block() # Ball ball = Ball(scoreboard, block, paddle_a, paddle_b) while True: threading.Thread(target=input_a.run(), args=()).start() threading.Thread(target=input_b.run(), args=()).start() threading.Thread(target=ball.move(), args=()).start()