def drawgrid(self): for i in range(self.h): self.blocks.append([]) for j in range(self.w): x, y, l = j * self.s, i * self.s, self.s color = (255, 255, 255) # packages if self.grid[i][j] == -3: color = (0, 255, 0) # terrain elif self.grid[i][j] == -2: color = (0, 0, 0) elif self.grid[i][j] == -2: color = (20, 20, 20) self.blocks[i].append(self.makesquare(x, y, l, color)) for i in range(self.w + 1): self.lines.append( shapes.Line(self.s * i, 0, self.s * i, len(self.grid) * self.s, color=(0, 0, 0), batch=self.statics)) for i in range(self.h): self.lines.append( shapes.Line(0, self.s * i, len(self.grid[0]) * self.s, self.s * i, color=(0, 0, 0), batch=self.statics))
def draw_game_background(): """ Draws the game-field / grid where the tetris pieces will be. """ game_background = shapes.BorderedRectangle(x=OFFSET_LEFT, y=OFFSET_BOTTOM, width=FIELD_WIDTH, height=FIELD_HEIGHT, border=2, border_color=(255, 255, 255), color=(140, 160, 160)) game_background.draw() for row in range(OFFSET_BOTTOM, FIELD_HEIGHT + OFFSET_BOTTOM, SQUARE_HEIGHT): row_line = shapes.Line(x=OFFSET_LEFT, y=row, x2=OFFSET_LEFT + FIELD_WIDTH, y2=row) row_line.draw() for column in range(OFFSET_LEFT, FIELD_WIDTH + OFFSET_LEFT, SQUARE_WIDTH): column_line = shapes.Line(x=column, y=OFFSET_BOTTOM, x2=column, y2=OFFSET_BOTTOM + FIELD_HEIGHT) column_line.draw()
def draw_grids(grid_length, batch): """draws divider and grid backgrounds""" increment = 400 / grid_length holder = [shapes.Line(480, 20, 480, 520, batch=batch, color=(255, 0, 0))] for i in range(0, int(grid_length) + 1): """Left Grid""" holder.append(shapes.Line(40 + increment * i, 70, 40 + increment * i, 470, batch=batch)) holder.append(shapes.Line(40, 70 + increment * i, 440, 70 + increment * i, batch=batch)) """Right Grid""" holder.append(shapes.Line(520 + increment * i, 70, 520 + increment * i, 470, batch=batch)) holder.append(shapes.Line(520, 70 + increment * i, 920, 70 + increment * i, batch=batch)) return holder
def on_draw(): window.clear() image.blit(0, 0) rays = world.cast_ideal_rays(mouse_pos, 360) raygrid = world.fill_point_grid(rays) spikes = world.find_spikes(rays) world.draw_spikes(raygrid, spikes) for i, position in enumerate(true_positions): est = (int(estimated_positions[i][0]), int(estimated_positions[i][1])) ded = (int(dedrec_positions[i][0]), int(dedrec_positions[i][1])) cv2.circle(raygrid, position, 4, (0, 255, 0), 2) cv2.circle(raygrid, est, 4, (255, 0, 0), 2) cv2.circle(raygrid, ded, 4, (0, 0, 255), 2) if i < len(true_positions) - 1: est2 = (int(estimated_positions[i + 1][0]), int(estimated_positions[i + 1][1])) ded2 = (int(dedrec_positions[i + 1][0]), int(dedrec_positions[i + 1][1])) cv2.line(raygrid, position, true_positions[i + 1], (0, 255, 0), 1) cv2.line(raygrid, est, est2, (255, 0, 0), 1) cv2.line(raygrid, ded, ded2, (0, 0, 255), 1) cv2.imshow('frame', raygrid) cv2.waitKey(1) lines = [] for ray in rays: if ray is not None: lines.append( shapes.Line(mouse_pos[0], mouse_pos[1], ray[0], ray[1], color=(250, 30, 30), batch=batch)) batch.draw()
def get_closest(self, pos, field='#', jump=0.2, num_steps=11, rays=12, batch=None): if batch is not None: self.rays = [] closest = np.zeros(rays) for i in range(rays): c = math.cos(i * 2 * math.pi / rays) s = math.sin(i * 2 * math.pi / rays) for j in range(1, num_steps + 1): ray = pos + Vec(c * j * jump, s * j * jump) closest[i] = j if self[ray] == field: break if batch is not None: coef = math.floor(255 * (num_steps - j) / (num_steps - 1)) self.rays.append( shapes.Line(pos.x * tile_width, pos.y * tile_width, ray.x * tile_width, ray.y * tile_width, 1, color=(coef, (255 - coef) // 2, 0), batch=batch)) return (num_steps - closest) / (num_steps - 1)
def step(self, action): action = action*max_acc car = self.car if self.color is not None: prev_pos = Vec(car.pos.x, car.pos.y) car.update(action, self.ground) if self.color is not None and self.batch is not None: line = shapes.Line(prev_pos.x*tile_width, prev_pos.y*tile_width, car.pos.x*tile_width, car.pos.y*tile_width, color=self.color, batch=self.trajectories_batch, width=self.color[0] == 255 and 2 or 1) line.opacity = self.opacity or 255 self.trajectories[self.i%self.n_trajectories].append(line) self.ground = self.map[car.pos] self.steps += 1 if self.steps >= 200: # time exceeded reward = -100 # or -150 or -50 or 0 or 50 ?? done = True end_color = (102, 0, 204) elif self.ground == ' ' or self.ground == 'O': # nothing happens reward = -self.step_cost done = False elif self.ground == '#': # we hit a wall reward = -100 done = True end_color = (255, 102, 0) elif self.ground == 'C': # we ran over a cat reward = -100 done = False elif self.ground == 'M': # we reached the finish line reward = 1000 done = True end_color = (0, 255, 0) else: raise Exception('Unsupported ground') if done and self.ground != 'M': # subtract distance from the finish line dist = math.sqrt((car.pos.x-self.map.M.x)**2+(car.pos.y-self.map.M.y)**2) reward -= dist*10 reward /= 1000 if done: if self.color is not None and self.batch is not None: end = shapes.Circle(car.pos.x*tile_width, car.pos.y*tile_width, 4, color=end_color, batch=self.trajectories_batch) # text = pyglet.text.Label(f'{reward:.3f}', x=car.pos.x*tile_width, y=car.pos.y*tile_width, font_size=8, batch=self.trajectories_batch) end.opacity = 255 self.trajectories[self.i%self.n_trajectories].append(end) # self.trajectories[self.i%self.n_trajectories].append(text) self.i += 1 if self.color is not None and self.batch is not None: self.trajectories[self.i%self.n_trajectories] = [] obs = self.get_obs() return obs, reward, done, {}
def draw(self, batch, group, screen=[1920, 1080], width=10): """Draw the line on the screen If the line is limited, it will draw the limited line in its whole. When the line is infinite, it will only draw the visible line. Args: screen: list containting ints; The width and height of the monitor in pixels. """ if self.limit == [-math.inf, math.inf] and self.rc != 0: new_limit = [0, screen[0]] if not (0 <= self.calc(0) <= screen[1]): if (self.rc > 0): new_limit[0] = 0 else: new_limit[0] = screen[0] if not (0 <= self.calc(screen[0]) <= screen[1]): if (self.rc > 0): new_limit[0] = screen[0] else: new_limit[0] = 0 else: new_limit = self.limit pos = new_limit if not (self.vertical): line = shapes.Line(pos[0], self.calc(pos[0]), pos[1], self.calc(pos[1]), width=width, color=self.color, batch=batch, group=group) else: line = shapes.Line(pos[0], self.vertical[0], pos[1], self.vertical[1], width=width, color=self.color, batch=batch, group=group) return line
def draw_line(x1, y1, x2, y2, width, color, x=0, y=0): return shapes.Line(x + x1, y + y1, x + x2, y + y2, width, color=color, batch=batch)
def __init__(self, x1, y1, x2, y2): self.point1 = Point(x1, y1) self.point2 = Point(x2, y2) self.line = shapes.Line(self.point1.x, self.point1.y, self.point2.x, self.point2.y, width=1)
def __init__(self, shape: RectangleShape, stroke_width=1, colour=(255, 255, 255, 255), **kwargs): a = shape.bottom_left b = shape.top_right rgb = colour[0:3] op = colour[3] self._lines = [ shp.Line(a.x, a.y, a.x, b.y, stroke_width, rgb, **kwargs), shp.Line(a.x, b.y, b.x, b.y, stroke_width, rgb, **kwargs), shp.Line(b.x, b.y, b.x, a.y, stroke_width, rgb, **kwargs), shp.Line(b.x, a.y, a.x, a.y, stroke_width, rgb, **kwargs) ] for line in self._lines: line.opacity = op
def draw_device(self, device, x, y, selected, batch): inside_color = (0, 0, 0) if not selected else (50, 50, 50) output = [] box = shapes.BorderedRectangle(x, y, device.size[0], device.size[1], color=inside_color, batch=batch, group=Renderer.group_device_background) output.append(box) color = (100, 100, 100) if isinstance(device, LampDevice): state = device.state light_color = (int(252 * state / 16), int(186 * state / 16), int(3 * state / 16)) light_shape = shapes.Circle(x=x + 10, y=y + 10, radius=10, color=light_color, batch=batch, group=Renderer.group_device_foreground) output.append(light_shape) for c in device.con_indices: pos0 = device.nodes_arguments[c[0]][0] pos1 = device.nodes_arguments[c[1]][0] line = shapes.Line(x + pos0[0], y + pos0[1], x + pos1[0], y + pos1[1], width=4, color=(100, 100, 100), batch=batch, group=Renderer.group_device_foreground) output.append(line) for n in device.nodes_arguments: shape = shapes.Circle(x=x + n[0][0], y=y + n[0][1], radius=NODE_SIZE / 2, color=color, batch=batch, group=Renderer.group_device_foreground) if n[1]: shape = shapes.Rectangle( x + n[0][0] - NODE_SIZE / 2, y + n[0][1] - NODE_SIZE / 2, NODE_SIZE, NODE_SIZE, color=color, batch=batch, group=Renderer.group_device_foreground) output.append(shape) return output
def render(self, scr_dim=800): window = pyglet.window.Window(scr_dim, scr_dim) draw_area = scr_dim * 0.9 count = 1 for char in self.sentence: if char != '1': break count += 1 length = scr_dim / count / 2 batch = pyglet.graphics.Batch() start_point = (scr_dim / 2, 0) lines = [] unit_vec = (0, 1) vec = start_point color_count = 1 color_step = 1 / len(self.sentence) stack = [] for char in self.sentence: if char == '0' or char == '1': # draw forward - multiply unit vector by length prev_vec = vec vec = np.multiply(length, unit_vec) + vec color = hsv2rgb(color_step * color_count, 1.0, 1.0) color_count += 1 new_line = shapes.Line(prev_vec[0], prev_vec[1], vec[0], vec[1], batch=batch, color=color) lines.append(new_line) elif char == '[': # push position and angle, turn counter clockwise pos = [vec, unit_vec] stack.append(pos) unit_vec = rotate(unit_vec, self.angle) elif char == ']': # pop position and angle, turn clockwise pos = stack.pop() vec = pos[0] unit_vec = pos[1] unit_vec = rotate(unit_vec, (2 * math.pi) - self.angle) else: pass @window.event() def on_draw(): window.clear() batch.draw() pyglet.app.run()
def __draw_line__(self, start, end, color_l): self.lines.append( shapes.Line(self.circles[start].x, self.circles[start].y, self.circles[end].x, self.circles[end].y, width=5, color=color_l, batch=self.batch, group=self.background_lines))
def step(self, action): action = action * max_acc car = self.car if self.color is not None: prev_pos = Vec(car.pos.x, car.pos.y) car.update(action, self.ground) if self.color is not None and self.batch is not None: line = shapes.Line(prev_pos.x * tile_width, prev_pos.y * tile_width, car.pos.x * tile_width, car.pos.y * tile_width, color=self.color, batch=self.batch, width=self.color[0] == 255 and 2 or 1) line.opacity = self.opacity or 63 self.trajectories[self.i % self.n_trajectories].append(line) self.ground = self.map[car.pos] self.steps += 1 if self.steps >= 200: # time exceeded reward = -100 # or -150 or -50 or 0 or 50 ?? done = True elif self.ground == ' ' or self.ground == 'O': # nothing happens reward = -self.step_cost done = False elif self.ground == '#': # we hit a wall reward = -100 done = True elif self.ground == 'C': # we ran over a cat reward = -100 done = False elif self.ground == 'M': # we reached the finish line reward = 1000 done = True else: raise Exception('Unsupported ground') if done: self.i += 1 if self.color is not None and self.batch is not None: self.trajectories[self.i % self.n_trajectories] = [] if done and self.ground != 'M': # subtract distance from the finish line dist = math.sqrt((car.pos.x - self.map.M.x)**2 + (car.pos.y - self.map.M.y)**2) reward -= dist * 10 obs = self.get_obs() return obs, reward / 1000, done, {}
def _mk_line(self, a: Vector, b: Vector, colour=None): line = shp.Line(a.x, a.y, b.x, b.y, self._stroke_width, self._colour[0:3] if colour is None else colour, batch=self._batch, group=self._group) line.opacity = self._colour[3] return line
def showintent(self): self.trace = [] if self.button.state is True: f, t, o = self.c.x, self.c.y, self.s//2 for i in range(len(self.queue)-1): point = self.queue[i] s = self.s self.trace.append(shapes.Line(f, t, point[1]*s+o, point[0]*s+o, color=self.color, width=2, batch=self.batch)) f, t = point[1]*s+o, point[0]*s+o
def add_to_batch(self, batch): super().add_to_batch(batch) self._line = shapes.Line( self.a.x, self.a.y, self.b.x, self.b.y, width=4, color=(200, 20, 20), batch=batch, )
def draw_path(self, points): path = [] rect_width = self.rect_width for i in range(len(points) - 1): start = points[i].point end = points[i + 1].point path.append( shapes.Line(*self.coord_to_window(start.x, start.y, True), *self.coord_to_window(end.x, end.y, True), width=5, color=(200, 50, 50), batch=self.batch)) self.path = path
def __init__(self, net_if): super().__init__(WIDTH, HEIGHT, f'Net Meter [{net_if}]') self.graph = [[0.0, 0.0] for _ in range(WIDTH)] self.batch = pyglet.graphics.Batch() self.upper_value = MIN_UPPER_VALUE self.shift = self.cursor = -1 self.set_icon(pyglet.image.load('icon.png', file=io.BytesIO(base64.b64decode(_ICON_BLOB)))) pyglet.gl.glClearColor(*[x / 255 for x in C_BACKGROUND], 1) kwargs = dict(x=0, y=0, x2=0, y2=0, width=1, batch=self.batch) self.dl_lines = [shapes.Line(color=C_DOWNLOAD, **kwargs) for _ in range(WIDTH)] self.ul_lines = [shapes.Line(color=C_UPLOAD, **kwargs) for _ in range(WIDTH)] self.ol_lines = [shapes.Line(color=C_OVERLAP, **kwargs) for _ in range(WIDTH)] self.cs_line = shapes.Line(color=C_CURSOR, **kwargs) self.cs_line.opacity = 120 self.cursor_label = pyglet.text.Label( 'Starting ...', font_size=8, batch=self.batch, color=C_T_CURSOR, bold=True, x=WIDTH / 2, anchor_x='center', y=HEIGHT - 10, anchor_y='center') self.horizontal_lines = [] self.horizontal_labels = [] for i in range(HOR_LINE_NUM): y = (HEIGHT - 20) * (i + 1) / HOR_LINE_NUM line = shapes.Line(0, y, WIDTH, y, width=1, color=C_HORIZON, batch=self.batch) line.opacity = 80 self.horizontal_lines.append(line) label = pyglet.text.Label( human_bytes(0) + '/s', font_size=8, batch=self.batch, color=C_T_HORIZON, x=WIDTH - 5, anchor_x='right', y=y, anchor_y='top') self.horizontal_labels.append(label) self.net_if = net_if self.tx, self.rx = self.get_net_io()
def draw(self, x, y): yield shapes.Circle(x + self.x, y + self.y, self.radius, color=self.color, batch=batch) yield shapes.Line(x + self.x, y + self.y, x + self.x + math.cos(self.angle) * self.radius * 2, y + self.y + math.sin(self.angle) * self.radius * 2, self.radius, color=self.color, batch=batch)
def draw_grid(batch, lines_arr): # grid_color = (250, 225, 30) # желтый # grid_color = (255, 0, 144) # магента # grid_color = (0, 200, 255) # голубой grid_color = (0, 255, 255) # циан for i in range(GameField.ROWS_NUM + 1): lines_arr.append( shapes.Line(GameField.CELL_SIZE * i + 1, 640 - 1, GameField.CELL_SIZE * i + 1, 640 - GameField.COLUMNS_NUM * GameField.CELL_SIZE - 1, width=1, color=grid_color, batch=batch)) for i in range(GameField.COLUMNS_NUM + 1): lines_arr.append( shapes.Line(1, 640 - GameField.CELL_SIZE * i - 1, GameField.COLUMNS_NUM * GameField.CELL_SIZE + 1, 640 - GameField.CELL_SIZE * i - 1, width=1, color=grid_color, batch=batch))
def cast(self, rotation): s = math.sin( rotation ) c = math.cos( rotation ) line = shapes.Line( self.x, self.y, self.x + 300*c, self.y + 300*s, color=(30, 30, 30), width=0.5, ) return line
def on_draw(): window.clear() shapes.Rectangle(x=0, y=0, width=board_size, height=board_size, color=(30, 100, 160)).draw() for i in range(N): p = (i + 0.5) * field_size shapes.Line(x=p, y=0, x2=p, y2=board_size).draw() shapes.Line(x=0, y=p, x2=board_size, y2=p).draw() for i, row in enumerate(board.fields): for j, color in enumerate(row): if color != Color.NONE: v = 200 if color == Color.WHITE else 30 x, y = (i + 0.5) * field_size, (j + 0.5) * field_size shapes.Circle(x=x, y=y, radius=field_size / 2 - 2, color=(v, v, v)).draw() if last_pos == (i, j): shapes.Rectangle(x=x - 2, y=y - 2, width=5, height=5, color=(255, 0, 0)).draw() if info: text.Label(info, x=window.width / 2, y=50, anchor_x='center', color=(255, 255, 0, 255), bold=True).draw()
def __init__(self, width, height): super().__init__(width, height, "Shapes") self.time = 0 self.batch = pyglet.graphics.Batch() self.circle = shapes.Circle(360, 240, 100, color=(255, 225, 255), batch=self.batch) self.circle.opacity = 127 # Rectangle with center as anchor self.square = shapes.Rectangle(360, 240, 200, 200, color=(55, 55, 255), batch=self.batch) self.square.anchor_x = 100 self.square.anchor_y = 100 # Large transparent rectangle self.rectangle = shapes.Rectangle(0, 190, 720, 100, color=(255, 22, 20), batch=self.batch) self.rectangle.opacity = 64 self.line = shapes.Line(0, 0, 0, 480, width=4, color=(200, 20, 20), batch=self.batch) self.triangle = shapes.Triangle(10, 10, 190, 10, 100, 150, color=(20, 200, 20), batch=self.batch) self.triangle.opacity = 150
def __init__(self): # self.canvas = None # self.context = None self.canvas_width = 1400 # 700 self.canvas_height = 1000 # 500 self.ai1 = Paddle(self, 'left') self.ai1.height = self.canvas_height // 3 # for debugging, need to remove. #self.ai1.speed = 5 # 6 self.ai2 = Paddle(self, 'right') self.ball = Ball(self) self.winning_score = 11 self.qagent = Qagent(self, self.ai1, self.ai2, self.ball) # self.ai2.speed = 8 # make ai2's paddle speed slower than ai1. # self.running = False # to check whether the game is running. self.turn = self.ai2 # it's the ai2's turn first. #self.round = 0 self.qlearn_mode = False # self.timer = 0 # self.color = '#000000' # color the game background black. # self.menu() # self.listen() # No need for these methods: # def end_game_menu(text): pass # def menu(): pass # def draw(): pass # def listen(): pass super().__init__(self.canvas_width, self.canvas_height, caption='Q-learning Pong') # create the paddles and the ball. self.paddle_colors = (255,255,255) self.ai1_rect = shapes.Rectangle(self.ai1.x, self.ai1.y, self.ai1.width, self.ai1.height, color=self.paddle_colors) #self.ai1_rect.opacity = 255 self.ai2_rect = shapes.Rectangle(self.ai2.x, self.ai2.y, self.ai2.width, self.ai2.height, color=self.paddle_colors) self.ball_rect = shapes.Rectangle(self.ball.x, self.ball.y, self.ball.width, self.ball.height, color=self.paddle_colors) self.line = shapes.Line(self.canvas_width//2, 0, self.canvas_width//2, self.canvas_height) self.ai1_scoreboard = text.Label("AI1: " + str(self.ai1.score), font_name='Courier New', font_size=50, x=(self.canvas_width // 2) - 500, y=800) self.ai2_scoreboard = text.Label("AI2: " + str(self.ai2.score), font_name='Courier New', font_size=50, x=(self.canvas_width // 2) + 200, y=800)
def render(self, scr_dim=800): window = pyglet.window.Window(scr_dim, 800) draw_area = scr_dim * 0.9 if self.order == 0: length = scr_dim else: length = scr_dim / pow(2, self.order) batch = pyglet.graphics.Batch() start_point = (1, 1) lines = [] unit_vec = (0, 1) vec = start_point color_count = 1 color_step = 1 / len(self.sentence) for char in self.sentence: if char == 'F' or char == 'G': # draw forward - multiply unit vector by length prev_vec = vec vec = np.multiply(length, unit_vec) + vec color = hsv2rgb(color_step * color_count, 1.0, 1.0) color_count += 1 new_line = shapes.Line(prev_vec[0], prev_vec[1], vec[0], vec[1], batch=batch, color=color) lines.append(new_line) elif char == '-': # turn right - rotate unit vector clockwise unit_vec = rotate(unit_vec, (2 * math.pi) - self.angle) elif char == '+': # turn left - rotate unit vector counter-clockwise unit_vec = rotate(unit_vec, self.angle) else: pass @window.event() def on_draw(): window.clear() batch.draw() pyglet.app.run()
def create_line(self, vertices, color): """ Creates and returns a psychopy line object. Args: vertices (list): List of x and y coordinates. color (string): Color of the line. Returns: (visual.Shapestim): A psychopy line. """ vertices = [(self.convert_pos(v)) for v in vertices] line = shapes.Line(vertices[0][0], vertices[0][1], vertices[1][0], vertices[1][1], color=self.convert_color(color)) line.visible = False return line
def simulate(evt): lines.clear() ql.run_episode() epoch_label.text = str(ql.epoch) score_label.text = str(ql.MeanScore) pos = track.car.Pos sprite_f1.x = pos.x * tile_size sprite_f1.y = (track.height - pos.y) * tile_size path = track.car.Path for i in range(len(track.car.Path) - 1): p1 = path[i] p2 = path[i + 1] lines.append( shapes.Line(p1.x * tile_size, (track.height - p1.y) * tile_size, p2.x * tile_size, (track.height - p2.y) * tile_size, 1, color=(255, 55, 255)))
def draw_node(self, node, net_color, batch): x = node.pos[0] y = node.pos[1] output = [] shape = shapes.Circle(x=x, y=y, radius=NODE_SIZE / 4, color=net_color, batch=batch, group=Renderer.group_network_nodes) output.append(shape) color = (255, 255, 255, 255) if node.current_net is not None: color = net_colors[node.current_net % len(net_colors)] color = (color[0], color[1], color[2], 255) label = text.Label(str(node.state), color=color, font_name='Arial', font_size=12, x=x, y=y + 20, anchor_x='center', anchor_y='center', batch=batch, group=Renderer.group_network_text) output.append(label) for c in node.connections: line = shapes.Line(c.node1.pos[0], c.node1.pos[1], c.node2.pos[0], c.node2.pos[1], width=2, color=net_color, batch=batch, group=Renderer.group_network_connections) output.append(line) return output
def newLines(): if active == True: fakeline.draw() for i in lines: shapes.Line(lines[i][0],lines[i][1],lines[i][2],lines[i][3],color=(0,255,0),width=2).draw()