def run_game(): pygame.init() screen = pygame.display.set_mode( (Setting.screen_width, Setting.screen_height)) pygame.display.set_caption("Tetris") new_shape = game_function.creat_tetris() shape = Shape(new_shape) game_function.update_screen(screen, shape) pygame.time.set_timer(pygame.USEREVENT, shape.speed) pygame.time.set_timer(pygame.USEREVENT + 1, 100) # 时钟对象 控制帧率 clock = pygame.time.Clock() game_function.startgame(screen) while True: clock.tick(60) if Setting.stop_flag: new_shape = game_function.creat_tetris() shape = Shape(new_shape) Setting.stop_flag = False game_function.check_events(screen, shape) game_function.update_screen(screen, shape) if Setting.end_flag == True: game_function.gameover(screen)
def __init__(self): self.__shapes = [] self.limit = Square("limit", np.array([[]], dtype=np.int32)) self.robot = Robot(Shape("robot", np.array([[]], dtype=np.int32)), Shape("orientation", np.array([[]], dtype=np.int32))) self.target = None self.treasures = [] self.orientationForTreasure = 0
def handleDrawing(self, pos): if self.current: if self.edit and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.finalise() else: self.points = [] elif not self.outOfPixmap(pos): if self.edit: self.current = Shape(edit=self.edit) self.current.edit = self.edit self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: self.current = Shape(edit=self.edit) self.current.edit = self.edit self.line.points = [pos, pos] self.points = [] self.setHiding() self.drawingPolygon.emit(True) self.update()
def randShape(sets={}): types = ['L', 'long', 'backL', 'Z', 'backZ', 'square', 'T'] try: if sets['randShape']: return Shape('rand', sets) except: print('error in rand shape') return Shape(types[randint(0, len(types) - 1)], sets)
def main() -> None: line = Shape(Shape.TYPECODE_LINE, 0, 0, 100, 200) rectangle = Shape(Shape.TYPECODE_RECTANGLE, 10, 20, 30, 40) oval = Shape(Shape.TYPECODE_OVAL, 100, 200, 300, 400) shape = [line, rectangle, oval] for s in shape: s.draw()
def test_align_shapes(self): s1 = Shape([(1, 2), (1, 3), (1, 4), (2, 4), (3, 4), (3, 3), (3, 2), (2, 2)]) s2 = Shape([(5, 2), (6, 3), (7, 4), (8, 3), (9, 2), (8, 1), (7, 0), (6, 1)]) Shape.translate_all_to_origin([s1, s2]) s2.align(s1) npt.assert_almost_equal(s1.points, s2.points, decimal=1)
def visit_Range(self, expr): start = self.visit_expr(expr.start) stop = self.visit_expr(expr.stop) step = self.visit_expr(expr.step) slice_value = self.slice_value(start, stop, step) if slice_value.__class__ is ConstSlice: return Shape((slice_value.nelts, )) else: return Shape((any_scalar, ))
def scale_and_rotate(self, subject, s, theta, inverse=False): '''Rotate over theta and scale by s''' rotation_matrix = np.array( [[s * math.cos(theta), -1 * s * math.sin(theta)], [s * math.sin(theta), s * math.cos(theta)]]) if inverse: return Shape(np.dot(rotation_matrix.T, subject.matrix)) else: return Shape(np.dot(rotation_matrix, subject.matrix))
def test_translate_all_to_origin(self): shapes = [ Shape([(1, 2), (1, 3), (1, 4), (2, 4), (3, 4), (3, 3), (3, 2), (2, 2)]), Shape( [(11, 2), (11, 3), (11, 4), (12, 4), (13, 4), (13, 3), (13, 2), (12, 2)] ), ] Shape.translate_all_to_origin(shapes) self.assertEqual(shapes[0].points.all(), shapes[1].points.all())
def __init__(self, parent=None): super(Canvas, self).__init__(parent) self.painter = QPainter() self.pixmap = QPixmap() # self = MyLabel(self) self.mode = self.EDIT # 默认模式为编辑 self.cursor = CURSOR_DEFAULT # 默认为鼠标手型 # 初始点,move位置,结束点 self.start_point = None self.pos = None self.end_point = None self.drawingLineColor = QColor(0, 0, 255) # # 用于保存正在画的rect的2个顶点 # 长度最大为2 # 实时变化(指[1]位置) # 画下一个时会进行re操作 self.current = [] self.points = Shape(line_color=self.drawingLineColor) self.point_four = Shape(line_color=self.drawingLineColor) # 存储画好的rect # 例如:存储了两个已经画好的rect: # print(self.shapes) # [<AAA_labelImg_copy.shape.Shape object at 0x000002403CA45508>, # <AAA_labelImg_copy.shape.Shape object at 0x0000024043553FC8>] self.shapes = [] self.shapes_remove = [] # 未实现的功能 # self.ten_bottle = QPointF() # 高亮的顶点 self.hVertex = None self.visible = {} self.hShape = None self.selectedShape = None # 存放选择的rect self.scale = 1.0 # 用于同一刻度 self.offsets = QPointF(), QPointF() # 2019-11-19 # for move shape self.prevPoint = QPointF() # 2019-11-20 # for move shape self._hideBackround = False self.hideBackround = False self.setMouseTracking(True)
def setUp(self): p0 = [[0, 0], [10, 0], [10, 11], [0, 11]] p1 = [[1, 1], [9, 1], [9, 9], [1, 9]] p2 = [[2, 2], [8, 2], [8, 7], [2, 7]] poly0 = Shape() for p in p0: poly0.loadPoint(QPointF(*p)) poly1 = Shape() for p in p1: poly1.loadPoint(QPointF(*p)) poly2 = Shape() for p in p2: poly2.loadPoint(QPointF(*p)) self.shapes = [poly0, poly1, poly2]
def run(dims: Tuple[int, int] = (400, 400)): reduced_dims = (dims[0] // 10, dims[1] // 10) pygame.init() screen = pygame.display.set_mode(dims) display_surf = pygame.Surface(reduced_dims) clock = pygame.time.Clock() rate = 5 done = False grid = Grid(reduced_dims) current_shape = Shape(reduced_dims) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == KEYDOWN and event.key == K_LEFT: current_shape.move("l", grid.block_positions) elif event.type == KEYDOWN and event.key == K_RIGHT: current_shape.move("r", grid.block_positions) elif event.type == KEYDOWN and event.key == K_UP: current_shape.rotate(grid.block_positions) elif event.type == KEYDOWN and event.key == K_DOWN: current_shape.drop(grid.block_positions) grid.draw_grid(display_surf) current_shape.draw_shape(display_surf) current_shape.step(grid.block_positions) if not current_shape.can_move: if current_shape.game_over: grid.game_over(display_surf, screen, dims, clock) for event in pygame.event.get(): if event.type == KEYDOWN and event.key == "K_SPACE": print("restarting") grid = Grid(reduced_dims) current_shape = Shape(reduced_dims) else: sys.exit(0) grid.update(current_shape) current_shape = Shape(reduced_dims) rate = grid.clear_line(rate) surf = pygame.transform.scale(display_surf, dims) screen.blit(surf, (0, 0)) pygame.display.update() clock.tick(int(rate))
def update(self): for event in pygame.event.get(): if event.type == pygame.QUIT: return False if event.type == pygame.MOUSEBUTTONDOWN: if self.cur_mode[0] == 0: if self.cur_mode[1] == 0: self.shapes.append( Shape(pygame.mouse.get_pos(), self.params)) self.params['shape_idx'] = len(self.shapes) - 1 self.sort_shapes() self.cur_mode[1] += 1 if self.cur_mode[1] == 2: self.cur_mode[1] = 0 self.sort_shapes() # x = pygame.mouse.get_pos()[0] # self.params['screens_h_ratio'] = (x, self.width - x) # self.update_params() self.screen.fill(self.black) self.retrieve_info() self.draw_structure() self.draw_shapes() pygame.display.flip() return True
def _processShapes(self): """ """ sheets = ['conductor', 'silkscreen', 'soldermask'] for sheet in sheets: try: shapes = self._footprint['layout'][sheet]['shapes'] except: shapes = [] for shape_dict in shapes: layers = utils.getExtendedLayerList(shape_dict.get('layers') or ['top']) for layer in layers: # Mirror the shape if it's text and on bottom later, # but let explicit shape setting override if layer == 'bottom': if shape_dict['type'] == 'text': shape_dict['mirror'] = shape_dict.get('mirror') or 'True' shape = Shape(shape_dict) style = Style(shape_dict, sheet) shape.setStyle(style) try: self._shapes[sheet][layer].append(shape) except: self._shapes[sheet][layer] = [] self._shapes[sheet][layer].append(shape)
def run_test(self,number: int): """Cargamos las matrices a comparar""" matrix = self.load_number_file(number) """Cargamos y filtramos los indices de las imagenes donde estan los digitos""" indices_list = self.list_filter(number, self.targets) """Creamos los shapes""" shape = Shape(matrix) total_evaluated = len(indices_list) successful = 0 array_evaluated_indices = [] """Preparamos cada uno de los targets con el preprocesamiento""" for i in indices_list: preprocessed_matrix = shape.preProcessing(self.digits.images[i]) # Result es la probabilidad de que sea el número. result = shape.calculateLikeness(preprocessed_matrix) #print("%s in %s where target was %s"% (result,i,targets[i])) if result >= Main.RATE: array_evaluated_indices.append(i) successful += 1 """print(self.digits.images[i]) shape.print_matrix()""" return { self.array_evaluated_key: array_evaluated_indices, self.successful_key: successful, self.total_evaluated_key: total_evaluated }
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.lineColor = QColor(0, 255, 0) self.line = Shape(line_color=self.lineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.pixmap = QPixmap() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter() self._cursor = CURSOR_DEFAULT #鼠标形状初始化为默认形状 # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus) #通过鼠标滚轮来获取焦点事件 self.verified = False # judge can draw rotate rect self.canDrawRotatedRect = True self.hideRotated = False self.hideNormal = False self.canOutOfBounding = False self.showCenter = False
def _placeDocs(self): """ Places documentation blocks on the documentation layer """ try: docs_dict = config.brd['documentation'] except: return for key in docs_dict: location = utils.toPoint(docs_dict[key]['location']) docs_dict[key]['location'] = [0, 0] shape_group = et.SubElement(self._layers['documentation']['layer'], 'g') shape_group.set('{' + config.cfg['ns']['pcbmode'] + '}type', 'module-shapes') shape_group.set('{' + config.cfg['ns']['pcbmode'] + '}doc-key', key) shape_group.set( 'transform', "translate(%s,%s)" % (location.x, config.cfg['invert-y'] * location.y)) location = docs_dict[key]['location'] docs_dict[key]['location'] = [0, 0] shape = Shape(docs_dict[key]) style = Style(docs_dict[key], 'documentation') shape.setStyle(style) element = place.placeShape(shape, shape_group)
def search(self, test_image, starting_landmark): new_points = [] test_patches, test_points = extract_patch_normal( test_image, starting_landmark, self._search_num_pixels, self._patch_num_pixels_width, image_transformation_function=self._img_trans_func, patch_transformation_function=self._patch_trans_func) test_patches = np.squeeze(np.array(test_patches)) npts, ph = test_patches.shape original_point_location = int(ph / 2) point_idxs = [] displacements = [] error_list = [] for index, point_model in enumerate(self._point_models): location, errors = self._search_point( point_model, np.squeeze(test_patches[index, :])) displacement = location - original_point_location displacements.append(displacement) error_list.append(errors) mean_disp = np.abs(np.array(displacements)).mean() shape_points = [] for index, displacement in enumerate(displacements): if np.abs(displacement) > mean_disp: displacement = np.sign(displacement) * np.round(mean_disp) updated_point_location = int(original_point_location + displacement) point_coords = np.uint32( np.round( np.squeeze( test_points[index, updated_point_location, :]))).tolist() shape_points.append(point_coords) return Shape(np.array(shape_points)), error_list
def fit(self, test_image, tol=0.1, max_iters=10000, initial_shape=None): """ Fits the shape model to the test image to find the shape :param test_image: The test image in the form of a numpy matrix :param tol: Fraction of points changed :param max_iters: Maximum number of iterations :param initial_shape: The starting Shape - if None get_default_initial_shape() is used :return: The final Shape, the fit error and the number of iterations performed """ if initial_shape is None: current_shape = self.get_default_initial_shape() else: current_shape = initial_shape.round() num_iter = 0 fit_error = float("inf") for num_iter in range(max_iters): previous_shape = Shape(current_shape.as_numpy_matrix().copy()) new_shape_grey, error_list = self._gm.search( test_image, current_shape) current_shape, fit_error, num_iters = self._pdm.fit(new_shape_grey) moved_points = np.sum( np.sum(current_shape.as_numpy_matrix().round() - previous_shape.as_numpy_matrix().round(), axis=1) > 0) if moved_points / float(self._pdm.get_size()) < tol: break return current_shape, fit_error, num_iter
def handleDrawing(self, pos): if self.current and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() #Don't allow user to draw a no-rectangle if (minX == maxX or minY == maxY): return self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.current.addPoint(initPos) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update()
def run_new_game(self): """Run gameplay.""" if not self.music_channel.get_busy(): self.music_selection.play_music() self.board.clear_board() self.game_stats.reset_game_stats() self.scoreboard.prep_scoreboard() while not self.game_over: self.clock.tick(self.settings.fps) self.check_events() self.update_screen() if self.pause: self.music_channel.pause() self.draw_pause_screen() self.music_channel.unpause() if self.landed: self.next_shape.set_position(200, 0) self.current_shape = self.next_shape self.next_shape = Shape(self.screen, self.settings, self.sounds, self.utils, 600, 520) self.game_over = self.board.check_collision( self.current_shape.shape) if self.game_over: self.draw_game_over_wall()
def read(self): if utils.fileExists(self.filePath): self.image: np.ndarray = cv.imread(self.filePath, flags=self.flags) if self.image is None: return try: with open(utils.swapExt(self.filePath, '.im')) as fp: data: dict = json.load(fp) self.name = data.get('name', self.name) self.position = data.get('position', self.position) self.scale = data.get('scale', self.scale) self.colormap = data.get('colormap', self.colormap) self.maprange = data.get('maprange', self.maprange) self.transform = data.get('transform', self.transform) self.flags = data.get('flags', self.flags) shapesData = data.get('shapes', None) if shapesData is not None: for name, shapeSet in shapesData.items(): self.shapes[name] = [] for shapeData in shapeSet: shape = Shape() shape.data = shapeData self.shapes[name].append(shape) except OSError: pass except Exception as err: logger.error(err)
def __init__(self, screen): self.stat = "game" self.WIDTH = self.TILEW * self.W self.HEIGHT = self.TILEW * self.H self.screen = screen self.pause = False self.board = [] #save current situation same as screen for i in xrange(self.H): line = [None] * self.W self.board.append(line) #next to display self.level = 1 self.killed = 0 self.score = 0 #delay for shape fall self.time = self.SPACE * 0.8**(self.level - 1) #save the elapsed time after last fail self.elapsed = 0 #pressd firstly time self.pressing = 0 #moving shape self.shape = Shape(self.START, \ (self.WIDTH, self.HEIGHT), (self.W, self.H)) self.shape.set_board(self.board) self.board_image = pygame.Surface((self.WIDTH, self.HEIGHT)) #draw background self.screen.blit(pygame.image.load( \ util.file_path("background.jpg")).convert(), (0, 0)) self.display_info()
def generateRandomShapes(self): num = random.randint(8, 12) for i in range(0, num): shapeType = random.randint(0, 5) shape = Shape() shape.setShape(shapeType) self.targetShapes.append(shape)
def mousePressEvent(self, ev): if PYQT5: pos = self.transformPos(ev.pos()) else: pos = self.transformPos(ev.posF()) if ev.button() == Qt.LeftButton: if self.drawing(): if self.current: try: self.current.addPoint(self.line[1]) except Exception as e: print(e, file=sys.stderr) return self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: self.selectShapePoint(pos) self.prevPoint = pos self.repaint() elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.repaint()
def mousePressEvent(self, ev): pos = self.transformPos(ev.pos()) if ev.button() == Qt.LeftButton: if self.drawing(): if self.current and self.current.reachMaxPoints() is False: initPos = self.current[0] minX = initPos.x() minY = initPos.y() targetPos = self.line[1] maxX = targetPos.x() maxY = targetPos.y() self.current.addPoint(QPointF(maxX, minY)) self.current.addPoint(targetPos) self.current.addPoint(QPointF(minX, maxY)) self.current.addPoint(initPos) self.line[0] = self.current[-1] if self.current.isClosed(): self.finalise() elif not self.outOfPixmap(pos): self.current = Shape() self.current.addPoint(pos) self.line.points = [pos, pos] self.setHiding() self.drawingPolygon.emit(True) self.update() else: self.selectShapePoint(pos) self.prevPoint = pos self.repaint() elif ev.button() == Qt.RightButton and self.editing(): self.selectShapePoint(pos) self.prevPoint = pos self.repaint()
def generate_struct(self): for x in range(0, self.num_shapes[0]): for y in range(0, self.num_shapes[1]): coordinates = [ ((x) * self.size_shapes[0], (y) * self.size_shapes[1]), ((x + 1) * self.size_shapes[0], (y) * self.size_shapes[1]), ((x + 1) * self.size_shapes[0], (y + 1) * self.size_shapes[1]), ((x) * self.size_shapes[0], (y + 1) * self.size_shapes[1]) ] new_points = [] for coord in coordinates: if coord in self.points: new_points.append(self.points[coord]) else: new_point = Point(coord) self.points[coord] = new_point new_points.append(new_point) self.shapes.append(Shape(new_points)) for point in self.points.values(): if self.in_bounds(point): point.evolve()
def __init__(self, screen): self.stat = "game" self.WIDTH = self.TILEW * self.W self.HEIGHT = self.TILEW * self.H self.screen = screen self.pause = False # the array save current situation # same as screen cood self.board = [] for i in xrange(self.H): line = [None] * self.W self.board.append(line) # will display self.level = 1 self.killed = 0 self.score = 0 # after this time, shape falls self.time = self.SPACE * 0.8**(self.level - 1) # save the elapsed time after last fail self.elapsed = 0 # used for judge pressed firstly or for a long time self.pressing = 0 # the moving shape self.shape = Shape(self.START, (self.WIDTH, self.HEIGHT), (self.W, self.H)) self.shape.set_board(self.board) self.board_image = pygame.Surface((self.WIDTH, self.HEIGHT)) # draw the background once self.screen.blit( pygame.image.load(util.file_path("background.jpg")).convert(), (0, 0)) self.display_info()
def __init__(self, *args, **kwargs): super(Canvas, self).__init__(*args, **kwargs) # Initialise local state. self.mode = self.EDIT self.shapes = [] self.current = None self.selectedShape = None # save the selected shape here self.selectedShapeCopy = None self.lineColor = QColor(0, 0, 255) self.line = Shape(line_color=self.lineColor) self.prevPoint = QPointF() self.offsets = QPointF(), QPointF() self.scale = 1.0 self.pixmap = QPixmap() self.visible = {} self._hideBackround = False self.hideBackround = False self.hShape = None self.hVertex = None self._painter = QPainter() self._cursor = CURSOR_DEFAULT # Menus: self.menus = (QMenu(), QMenu()) # Set widget options. self.setMouseTracking(True) self.setFocusPolicy(Qt.WheelFocus)
def propose_shape(self, image_shape: ImageShape): """ Proposes a better shape by sliding each point along its normal axis so that the Mahalanobis distance of its profile in relation to the mean profile is normalized. """ # unpack image = image_shape.image shape = image_shape.shape # get points and vectors points = shape.as_point_list() vectors = shape.get_orthogonal_vectors() vectors = cast(List[Point], vectors) glps = self.gray_level_profiles proposed_points = [] # find m sliding profiles of (2k+1) length for each point for point, vector, glp in zip(points, vectors, glps): # Get profiles by sliding around normal axis hsz = glp.half_sampling_size profiles = glp.sliding_profiles(image, point, vector, hsz, int(hsz / 2)) # Calculate Mahalanobis distances distances = [glp.mahalanobis_distance(prof) for prof in profiles] # Find strongest edge distance_idx = np.argmin(distances) plen = len(profiles) proposed_point = GrayLevelProfile.point_pos_from_profiles_list( distance_idx, plen, point, vector) proposed_points.append(proposed_point) return Shape(proposed_points)