def illustrateProblem(self): a = ArrayOfHexagons() a.setRadius(40) a.addHexagon(0, 0) a.populate(6) h = Shape() h.loadFromFile('sampleTiles/hexagon.tile') b = Shape() b.loadFromFile('sampleTiles/smallBend.tile') s = Shape() s.loadFromFile('sampleTiles/simple.tile') t = Shape() t.loadFromFile('sampleTiles/triangle.tile') c = Shape() c.loadFromFile('sampleTiles/cross.tile') p = Shape() p.loadFromFile('sampleTiles/prang.tile') ss = Shape() ss.loadFromFile('sampleTiles/singleSide.tile') a.hexagon(-12,0).addShape(h) a.hexagon(-8,0).addShape(b) a.hexagon(-4,0).addShape(s) a.hexagon(0,0).addShape(t) a.hexagon(4,0).addShape(c) a.hexagon(8,0).addShape(p) a.hexagon(12,0).addShape(ss) svg = SvgWriter() svg.offset(400,400) for coordinates in a: svg.addHexagon(a.hexagon(coordinates[0], coordinates[1])) svg.write('hexagons.svg')
def shapePoints(self): a = ArrayOfHexagons() a.setRadius(40) a.addHexagon(0, 0) a.populate(2) h = Shape() h.loadFromFile('sampleTiles/hexagon.tile') b = Shape() b.loadFromFile('sampleTiles/smallBend.tile') s = Shape() s.loadFromFile('sampleTiles/simple.tile') t = Shape() t.loadFromFile('sampleTiles/triangle.tile') c = Shape() c.loadFromFile('sampleTiles/cross.tile') p = Shape() p.loadFromFile('sampleTiles/prang.tile') ss = Shape() ss.loadFromFile('sampleTiles/singleSide.tile') shapes = ShapeManager(h, b, s) a.hexagon(-2,0).addShape(h) a.hexagon(0,0).addShape(b) #a.hexagon(0,0).shape().rotate(5) a.hexagon(-1,-1).addShape(b) a.hexagon(-1,-1).shape().rotate(3) a.hexagon(2,0).addShape(h) a.hexagon(1,1).addShape(c) a.hexagon(4,0).addShape(p) a.hexagon(1,-1).addShape(p) a.hexagon(1,-1).shape().rotate(5) a.hexagon(-1,1).addShape(ss) svg = SvgWriter() svg.offset(200,200) svg.rotate(0) for coordinates in a: svg.addHexagon(a.hexagon(coordinates[0], coordinates[1])) svg.write('hexagons.svg') print 'Done'
def testShapeOrientation(): nodes = [Node([0, 0], 1, 1, 0)] nodes.append(Node([5, 1], 1, -1, 1)) nodes.append(Node([4, -6], 1, 1, 2)) nodes.append(Node([7, 3], 1, 1, 3)) s1 = Shape(nodes) fig, ax = plt.subplots() ax.set_ylim(-10, 10) ax.set_xlim(-10, 10) plotShape(s1, ax) ax.set_title(f"Shape orientation is {s1.o}") nodes2 = [Node([0, 0], 1, -1, 0)] nodes2.append(Node([7, 3], 1, -1, 3)) nodes2.append(Node([4, -6], 1, -1, 2)) nodes2.append(Node([5, 1], 1, 1, 1)) s2 = Shape(nodes2) fig2, ax2 = plt.subplots() ax2.set_ylim(-10, 10) ax2.set_xlim(-10, 10) plotShape(s2, ax2) ax2.set_title(f"Shape orientation is {s2.o}") plt.show()
def newPiece(self): '''creates a new shape''' self.curPiece = Shape() self.curPiece.setRandomShape() self.tempCurPiece = Shape() self.tempCurPiece = self.nextCurPiece self.nextCurPiece = self.curPiece self.curPiece = self.tempCurPiece self.msg2NextBoard.emit(str(self.nextCurPiece.nextNum)) self.curPiece.set_congif(1) if self.mode == "n": self.curX = self.BoardWidth // 2 self.skynet(self.curPiece.shape()) else: self.skynet(self.curPiece.shape()) self.rotatePiece(int(dlv.getRotation())) self.curX = int(dlv.getX()) self.curY = self.BoardHeight - 1 + self.curPiece.minY() if not self.tryMove(self.curPiece, self.curX, self.curY): self.endGame() self.msg2State.emit(str("LOSE")) self.start_lose_sound()
def __init__(self, position=Coordinate(), text=u'', fontsize=12.0, id=None, classes=None): """ @param position: A Coordinate defining the position in the SVG document @type position: Coordinate @param text: The text of the element @type text: string @param fontsize: the fontsize of the text (for calculating width/height) @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ if isinstance(position, Coordinate): Shape.__init__(self, tag=u'text', id=id, classes=classes) self.position = position self.text = text self.fontsize = fontsize else: raise TypeError("position must be of type 'Coordinate'")
def reset(self): self.board = [] for row in range(self.height): self.board.append([0] * self.width) self.pending_shape = Shape() self.add_shape()
def __init__(self, center, inner_radius, outer_radius, img_name, rot=None): Shape.__init__(self, center=center, rot=rot, painter=RingPainter(self, img_name)) self.inner_radius = inner_radius self.outer_radius = outer_radius
def __init__(self): super().__init__() self.setPalette(QPalette(Qt.white)) self.setAutoFillBackground(True) self.curPiece = Shape() self.shape = 1 self.BoardWidth = 6 self.BoardHeight = 6
def __init__(self, pos=[0, 0, 0], radius=0.2, color=[0, 1, 0]): Shape.__init__(self) self.radius = radius self.pos = self.pos = np.array(pos + color, np.float32) self.drawing_type = GL_TRIANGLE_FAN self.color = color self.setup_shaders() self.build_buffer()
def fuzzification(nilai, tipe): hasil=[] result=[] jenis=[] if (tipe== "emosi"): vlow= Shape(0, 10, 30) low= Shape(10, 30, 50) norm= Shape(30, 50, 70) high= Shape(50, 70, 90) vhigh= Shape(70, 90, 100) elif (tipe=="provokasi"): vlow= Shape(0, 10, 30) low= Shape(10, 30, 39) norm= Shape(30, 50, 74) high= Shape(71, 85, 90) vhigh= Shape(75, 81, 100) if nilai < vlow.c and nilai >vlow.a or nilai==0: if(nilai>=vlow.a and nilai<=vlow.b): result.append(1) else: hasil.append(vlow) jenis.append(0) if nilai >low.a and nilai <low.c: hasil.append(low) jenis.append(1) if nilai>norm.a and nilai <norm.c : hasil.append(norm) jenis.append(2) if nilai>high.a and nilai<high.c: hasil.append(high) jenis.append(3) if nilai>vhigh.a and nilai<vhigh.c: if(nilai>=vhigh.b and nilai<=vhigh.c): result.append(1) else: hasil.append(vhigh) jenis.append(4) if nilai==100: result.append(1) jenis.append(4) for index in range(len(hasil)): if nilai==100: temp=1; elif(nilai>hasil[index].a) and (nilai<=hasil[index].b): asdf=(nilai-hasil[index].a) dsa=(hasil[index].b-hasil[index].a)*1.0 temp= asdf/dsa elif (nilai>hasil[index].b and nilai<=hasil[index].c): asdf= (-(nilai-hasil[index].c)) dsa=(hasil[index].c-hasil[index].b) temp= asdf/(dsa*1.0) else: temp=1 result.append(temp) return result, jenis
def __init__(self, num_level): self.level = num_level self.shape = Shape() self.next_shape = Shape() self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size) self.last_time = time.perf_counter() self.slow_activation_time = time.perf_counter() self.done_level = False self.start_time = time.perf_counter()
def add_shape(self): self.active_shape = self.pending_shape.clone() self.active_shape.x = self.width // 2 - self.active_shape.left_edge self.active_shape.y = -1 self.pending_shape = Shape() if self.is_collision(): self.reset() self.dispatch_event('on_game_over')
class NextBoard(QMainWindow): def __init__(self): super().__init__() self.setPalette(QPalette(Qt.white)) self.setAutoFillBackground(True) self.curPiece = Shape() self.shape = 1 self.BoardWidth = 6 self.BoardHeight = 6 def display(self, msg): self.shape = msg self.update() def squareWidth(self): return self.contentsRect().width() // self.BoardWidth def squareHeight(self): return self.contentsRect().height() // self.BoardHeight def paintEvent(self, event): painter = QPainter(self) rect = self.contentsRect() boardTop = rect.bottom() - self.BoardHeight * self.squareHeight() for i in range(4): x = 1 + self.curPiece.x(i) y = 1 + self.curPiece.y(i) self.drawSquare( painter, rect.left() + x * self.squareWidth(), boardTop + (self.BoardHeight - y - 1) * self.squareHeight(), self.shape) def drawSquare(self, painter, x, y, shape): colorTable = [ 0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00 ] color = QColor(colorTable[int(shape)]) painter.fillRect(x + 1, y + 1, self.squareWidth() - 2, self.squareHeight() - 2, color) painter.setPen(color.lighter()) painter.drawLine(x, y + self.squareHeight() - 1, x, y) painter.drawLine(x, y, x + self.squareWidth() - 1, y) painter.setPen(color.darker()) painter.drawLine(x + 1, y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + self.squareHeight() - 1) painter.drawLine(x + self.squareWidth() - 1, y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
def getResult(self, deg): if deg == 1.0: f = Shape() for p in self.f.points: f.addPoint(p) return f if self.shape == "trap": f = Shape() (a, b, c, d) = self.points dx = (b - a) * deg dy = deg b = a + dx dx = (d - c) * deg c = d - dx f.setPoints([(a, 0), (b, dy), (c, dy), (d, 0)]) return f if self.shape == "tri": f = Shape() (a, b, c) = self.points dx1 = (b - a) * deg dx2 = (c - b) * deg b = a + dx1 d = c c = d - dx2 dy = deg f.setPoints([(a, 0), (b, dy), (c, dy), (d, 0)]) return f
def testGetOffspring(): nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.0, 0], 0.1, 1, 1)) nodes.append(Node([-0.0, -0.9], 0.1, 1, 2)) nodes.append(Node([0.4, -0.9], 0.1, 1, 3)) s = Shape(nodes) tmpShowShape(s) for i in range(100): s = s.getOffspring(bigMutations=True) tmpShowShape(s)
def forward(self, in_tensors: List[Tensor], out_tensors: List[Tensor]): if self.out_shape is None: self.out_shape = Shape([in_tensors[0].get_shape().axis[0], self.nb_neurons]) if self.weights is None: self.weights = Tensor(shape=Shape([in_tensors[0].get_shape().axis[1], self.nb_neurons])) for i in range(len(in_tensors)): if i >= len(out_tensors): out_tensors.append(Tensor(self.out_shape)) out_tensors[i].elements = in_tensors[i].elements.dot(self.weights.elements) + self.biases.elements
def timeRecalculate(): nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.0, 0], 0.1, 1, 1)) nodes.append(Node([-0.0, -0.9], 0.1, 1, 2)) nodes.append(Node([0.4, -0.9], 0.1, 1, 3)) s = Shape(nodes) start = time() for i in range(1000): s.recalculate() end = time() print(f"Time taken: {end-start:.2f} seconds")
def __init__(self, master_shape, slave_shape, radius, orbit_time, init_angle=0.0): Shape.__init__(self, painter=OrbitPainter(self)) self.radius = radius self.init_angle = init_angle # time it takes to complete 1 orbit self.orbit_time = orbit_time self.master_shape = master_shape self.slave_shape = slave_shape
def update(self): # Main event loop for self.event in pygame.event.get(): if self.event.type == pygame.KEYDOWN: self.key_check() delay = 0.27 - self.level * 0.005 if self.gameboard.slow_time_on: delay *= 2 if time.perf_counter() - self.slow_activation_time > 6: self.gameboard.slow_time_on = False if self.gameboard.swap_shape: self.shape = self.next_shape self.next_shape = Shape() self.gameboard.swap_shape = False if time.perf_counter() - self.last_time > delay: self.last_time = time.perf_counter() self.shape.falling() if self.shape.active == False: self.gameboard.clear_full_rows() self.shape = self.next_shape self.next_shape = Shape() if self.gameboard.check_loss(): new_score = self.gameboard.score / 2 num_lines = self.gameboard.num_lines self.gameboard = GameBoard(WHITE, self.shape.block_list[0].size) self.gameboard.score = new_score self.gameboard.num_lines = num_lines self.shape = Shape() self.next_shape = Shape() if time.perf_counter() - self.start_time > 120: self.done_level = True
def newPiece(self): # Случайным образом создает новую часть тетриса. Если часть не может # прийти в свою начальную позицию - game over. self.curPiece = Shape() self.curPiece.setRandomShape() self.curX = Board.BoardWidth // 2 + 1 self.curY = Board.BoardHeight - 1 + self.curPiece.minY() if not self.tryMove(self.curPiece, self.curX, self.curY): self.curPiece.setShape(Tetrominoe.NoShape) self.timer.stop() self.isStarted = False self.msg2Statusbar.emit("Game over")
def newPiece(self): '''creates a new shape''' self.curPiece = Shape() self.curPiece.setRandomShape() self.curX = Board.BoardWidth // 2 + 1 self.curY = Board.BoardHeight - 1 + self.curPiece.minY() if not self.tryMove(self.curPiece, self.curX, self.curY): self.curPiece.setShape(Tetrominoe.NoShape) self.timer.stop() self.isStarted = False self.msg2Statusbar.emit("Game over")
def everything(self): '''do some tests''' t1=time.time() a = ArrayOfHexagons() a.setRadius(25) a.addHexagon(0, 0) a.populate(6) #print a.hexagon(1, 1).distanceFrom(0, 0) #print a.hexagon(-2, 0).distanceFrom(0, 0) h = Shape() h.loadFromFile('sampleTiles/hexagon.tile') b = Shape() b.loadFromFile('sampleTiles/smallBend.tile') s = Shape() s.loadFromFile('sampleTiles/simple.tile') shapes = ShapeManager(h, b, s) #for i in shapes: # print i #print shapes #a.hexagon(-1,-1).addShape(h) a.hexagon(1,1).addShape(h) a.hexagon(0,0).addShape(s) #a.hexagon(-2,0).addShape(b) a.hexagon(0,0).shape().rotate(4) #a.printArray() svg = SvgWriter() svg.offset(400,400) svg.rotate(0) for coordinates in a: svg.addHexagon(a.hexagon(coordinates[0], coordinates[1])) svg.write('hexagons.svg') #print shape #shape.rotate(6) #print shape #sr = ShapeFitter(('a', '-', '-', '-', '-', '-'), ('+', '+', '+', 'A', '+', '+')) sr = ShapeFitter(a.hexagon(0,0).shape().sides(), a.gapEdges(0, 0)) print 'need to rotate', sr.fit(), 'times' #print a.gapEdges(0, 0) t2=time.time() print 'time taken', t2-t1
class Playground(): Circle=Circle(6) Polygon=Polygon(3) Square=Square(5,2) Triangle=Triangle(1,4,2) Shape=Shape() # Implement __init__() for this class def __init__(self): print("The instances you created") # Call Method find_area of each class print(f"{Circle} and area = {Circle.find_area()}") print(f"{Square} and area = {Square.find_area()}") print(f"{Triangle} and area = {Triangle.find_area()}") #find_circumference #find_perimeter # Call Methods find_circumference and find_perimeter of each class print(f"{Circle} and circumference = {Circle.find_circumference()}") print(f"{Square} and perimeter = {Square.find_perimeter()}") print(f"{Triangle} and perimeter = {Triangle.find_perimeter()}") def __str__(self): print("Playground...Shapes")
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs['x'] = self.position.x self.attrs['y'] = self.position.y return Shape.svg(self)
def NextLevel(self): self.Enm.stopMovement = True self.Lvl = self.Lvl + 1 self.canvas.itemconfig(self.image_id, image=self.images[1]) self.LinesPropertiesY.clear() self.LinesPropertiesX.clear() self.LinesPropertiesY.append(('y', 6, 6, 608, False)) self.LinesPropertiesY.append(('y', 608, 6, 608, False)) self.LinesPropertiesX.append(('x', 6, 6, 608, False)) self.LinesPropertiesX.append(('x', 608, 6, 608, False)) self.AllPoints.clear() self.AllPoints = [(6, 6, True), (608, 6, True), (608, 608, True), (6, 608, True)] self.canvas.delete(self.Shp.MainLn) del self.Shp MainLn = self.canvas.create_polygon(6, 6, 608, 6, 608, 608, 6, 608, 6, 6, fill='grey', width=1) self.Shp = Shape(MainLn, self) self.Plr.Player.pack_forget() self.Plr.Player.destroy() frmPlayer = tk.Frame(self.canvas, bg='#FF0000') self.Plr = Player(frmPlayer, self) self.Enm.EnemyV.pack_forget() self.Enm.EnemyV.destroy() frmEnemy = tk.Frame(self.canvas, bg='#00FF00') self.Enm = Enemy(frmEnemy, self)
def __init__(self, shapes=(), id=None, classes=None): """ @param shapes: Shapes to be included in the group @type shapes: sequence of Shapes @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ for shape in shapes: if not isinstance(shape, Shape): raise TypeError("shapes must contain only objects of type 'Shape'") Shape.__init__(self, tag=u'g', id=id, classes=classes) self.shapes = tuple(shapes)
def loadJSON(): if os.path.exists("data/SavedShapes.json"): # Opening the file jsonFile = open("data/SavedShapes.json", "r") jsonString = jsonFile.readline() # Loading the dictionary and extracting contents shapeDict = json.loads(jsonString) contents = shapeDict["content"] # Loading all the shapes into memory shapes = [] i = 0 for content in contents: shapes.append(Shape(content["label"], content["coordinates"])) try: shapes[i].category = content["category"] print(shapes[i].category) except: print("No categories yet") i += 1 # Closing the file and returning the loaded shapes jsonFile.close() return shapes
def update(self): if self.inputHandler.isKeyDown(pygame.K_ESCAPE): self.isAlive = False if self.inputHandler.isKeyHit(pygame.K_w): self.shape.rotateCW() if self.inputHandler.isKeyHit(pygame.K_s): self.shape.move((0, 1)) if self.inputHandler.isKeyHit(pygame.K_a): self.shape.move((-1, 0)) if self.inputHandler.isKeyHit(pygame.K_d): self.shape.move((1, 0)) if pygame.time.get_ticks() > self.movementTime: self.shape.move((0, 1)) self.movementTime = pygame.time.get_ticks() + 200 if self.shape.isPlaced: self.shape = Shape(self.board, self.randomShape())
def new_piece(self): """ 通过newPiece()方法创建一个新的方块 如果不能进入它的初始位置,游戏就结束 """ self.curPiece = Shape() self.curPiece.set_random_shape() self.curX = Board.BoardWidth // 2 + 1 self.curY = Board.BoardHeight - 1 + self.curPiece.min_y() if not self.try_move(self.curPiece, self.curX, self.curY): self.curPiece.set_shape(Tetrominoe.NoShape) self.timer.stop() self.isStarted = False self.msg2Statusbar.emit("Game over")
def __detect_shape(img, height, width, shape): """ The process to detect the shape. It detects the number of shape's edges. If a shape has 3 edges, it's a triangle. Parameters ---------- img : numpy.ndarray The image whose shapes we want to detect height : int Image's height width : int Image's width shape : Shape The shape we want to detect Returns ------- detected : Shape The detected shape last_cont : numpy.ndarray Contours of the shape. detected_shapes : list The detected shapes. center : tuple of float Center of the detected shape. angle : float Angle of rotation of the detected shape. """ font = cv2.FONT_HERSHEY_SIMPLEX contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) hull_list = __convex_hull(contours) minimal_area = 200 maximal_area = (height * width) - 2000 detected = None detected_shapes = [] last_cont = np.array([]) center = None angle = None for cont in hull_list: area = cv2.contourArea(cont) #continue if area is too small(noise) or too big if area < minimal_area or area >= maximal_area: continue approx = __approx_poly(cont, img) detected = __check_partial(detected, approx, width, height) if detected != Shape.PARTIAL.value: detected = __check_non_partial_shape(cont, area, approx) shape_name = Shape(detected).name detected_shapes.append(shape_name) if shape == Shape.ALL.value or detected == shape: x = cont[0][0][0] #x value of a point of the shape y = cont[0][0][1] #y value of a point of the shape cv2.putText(img, shape_name, (x, y), font, 0.5, (255)) if detected == shape: last_cont = approx center, _, angle = cv2.minAreaRect(cont) break return detected, last_cont, detected_shapes, center, angle
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs['cx'] = self.center.x self.attrs['cy'] = self.center.y self.attrs['r'] = self.radius return Shape.svg(self)
def __init__(self, coordinates=(), id=None, classes=None): """ @param coordinates: The coordinates of the path's vertices @type coordinates: Sequence of Coordinates @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ for coord in coordinates: if not isinstance(coord, Coordinate): raise TypeError("Coordinates must be of type 'Coordinate'") Shape.__init__(self, tag=u'path', id=id, classes=classes) self.coordinates = tuple(coordinates)
def __init__(self, shapes=(), id=None, classes=None): """ @param shapes: Shapes to be included in the group @type shapes: sequence of Shapes @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ for shape in shapes: if not isinstance(shape, Shape): raise TypeError( "shapes must contain only objects of type 'Shape'") Shape.__init__(self, tag=u'g', id=id, classes=classes) self.shapes = tuple(shapes)
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs["x1"] = self.start.x self.attrs["y1"] = self.start.y self.attrs["x2"] = self.end.x self.attrs["y2"] = self.end.y return Shape.svg(self)
def initBoard(self): self.timer = wx.Timer(self, Board.ID_TIMER) self.isWaitingAfterLine = False self.curPiece = Shape() self.nextPiece = Shape() self.curX = 0 self.curY = 0 self.numLinesRemoved = 0 self.board = [] self.isStarted = False self.isPaused = False self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.Bind(wx.EVT_TIMER, self.OnTimer, id=Board.ID_TIMER) self.clearBoard()
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs['x'] = self.position.x self.attrs['y'] = self.position.y self.attrs['width'] = self.width self.attrs['height'] = self.height return Shape.svg(self)
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs['x1'] = self.start.x self.attrs['y1'] = self.start.y self.attrs['x2'] = self.end.x self.attrs['y2'] = self.end.y return Shape.svg(self)
def __init__(self, center=Coordinate(), rx=1.0, ry=1.0, id=None, classes=None): """ @param center: -- a Coordinate defining the center coordinate in the SVG document @type center: Coordinate @param rx: -- the x-radius of the ellipse @param ry: -- the y-radius of the ellipse @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ if isinstance(center, Coordinate): Shape.__init__(self, tag=u'ellipse', id=id, classes=classes) self.center = center self.rx = float(rx) self.ry = float(ry) else: raise TypeError("center must be of type 'Coordinate'")
def __init__(self, position=Coordinate(), width=1.0, height=1.0, id=None, classes=None): """Keyword arguments: @param position: A Coordinate defining the position in the SVG document @type position: Coordinate @param width: The width of the rectangle @param height: The height of the rectangle @param id: The unique ID to be used in the SVG document @type id: string @param classes: Classnames to be used in the SVG document @type classes: string or sequence of strings """ if isinstance(position, Coordinate): Shape.__init__(self, tag=u'rect', id=id, classes=classes) self.position = position self.width = float(width) self.height = float(height) else: raise TypeError("position must be of type 'Coordinate'")
def svg(self): """Returns the SVG representation as an XML fragment.""" shapes = [] for shape in self.shapes: try: shapes.append(shape.svg()) except AttributeError: raise self.subelements = shapes return Shape.svg(self)
def __init__(self): """ Méthode "main" de l'application. """ print "Initialisation des péripheriques..." self.initPeriph() print "Initialisation des servos..." self.initServos() print "Initialisation terminée !" print "Programme prêt !" print "" ################################################# self.mode = "Manual" self.modeObj.setMode(self.mode) # Création des formes self.shape = Shape(self.horizontalServo, self.verticalServo, self.laser, self.uart) try: while 1: self.reading = self.uart.read() if self.reading != "Up" and self.reading != "Left" and self.reading != "Right" and self.reading != "Down" and self.reading != "Center" and self.reading != "Laser" and self.reading != "": self.mode = self.reading self.modeObj.setMode(self.mode) if self.mode == "Auto": self.autoMode() elif self.mode == "Semi-auto": self.semiAutoMode() elif self.mode == "Manual": self.manualMode() elif self.mode == "Wii": if self.nunchukIsConnected: self.wiiMode() else: print "La manette \"Nunchuk\" n'est pas connectée" self.mode = "Manual" else: sleep(2) self.mode = "Auto" self.modeObj.setMode(self.mode) except KeyboardInterrupt: print "Arret du programme..." self.modeObj.setMode("Stop") self.laser.OFF() self.initServos() print "Programme arreté"
def __init__(self, shape, position, rotation, color): Shape.__init__(self, position, rotation, color) self.cache_points = (None, None, None) # first, we find the shape's top-most left-most boundary, its origin (origin_x, origin_y) = (shape[0].x, shape[0].y) for p in shape: if p.x < origin_x: origin_x = p.x if p.y < origin_y: origin_y = p.y # then, we orient all of its points relative to its origin shifted = [] for p in shape: shifted.append(Point(p.x - origin_x, p.y - origin_y)) # now shift them all based on the center of gravity self.shape = shifted self.center = self._findCenter() self.shape = [] for p in shifted: self.shape.append(Point(p.x - self.center.x, p.y - self.center.y))
class ShapeFitter(object): '''Find the amount to rotate a shape to fit into a gap''' def __init__(self, shapeSides, gapSides): self._shape = Shape(shapeSides, 'shape being rotated') self._gapSides = gapSides def fit(self, random=True): '''Rotate the shape around until it fits the gap. Random by default to avoid bias''' orientationsChecked = [] timesRotated = 0 if random: #give the shape a random offset rotateNumber = randint(0, 5) timesRotated += rotateNumber self._shape.rotate(rotateNumber) else: rotateNumber = 1 if not self._fits(): while (len(orientationsChecked) < 6): if not self._fits(): if random: #rotateNumber defaults to 1 if not random rotateNumber = randint(1, 5) timesRotated += rotateNumber self._shape.rotate(rotateNumber) if self._shape.sides() not in orientationsChecked: if self._fits(): return timesRotated % 6 else: orientationsChecked += [self._shape.sides()] else: return timesRotated % 6 #if it already fits def _fits(self): '''Return True if the shape fits in the gap''' passed = True for i in range(len(self._shape.sides())): #TODO make Shape iterative if self._gapSides[i] != '+': # '+' means an empty hexagon (with no shape attached), so any tile can be adjacent to its sides if self._gapSides[i] != self._shape.sides()[i].swapcase(): #swap the case, meaning only side A can connect to side a and vice versa passed = False return passed
def __init__(self): Shape.__init__(self,4,5,0)
class Board(pyglet.event.EventDispatcher): active_shape = None pending_shape = None board = None encoding = None def __init__(self, width, height, block): self.width, self.height = width, height self.block = block self.calculated_height = self.height * block.height self.calculated_width = self.width * block.width self.reset() def reset(self): self.board = [] for row in range(self.height): self.board.append([0] * self.width) self.pending_shape = Shape() self.add_shape() def add_shape(self): self.active_shape = self.pending_shape.clone() self.active_shape.x = self.width // 2 - self.active_shape.left_edge self.active_shape.y = -1 self.pending_shape = Shape() if self.is_collision(): self.reset() self.dispatch_event('on_game_over') def rotate_shape(self): rotated_shape = self.active_shape.clone() rotated_shape.rotate() if rotated_shape.left_edge + rotated_shape.x < 0: rotated_shape.x = -rotated_shape.left_edge elif rotated_shape.right_edge + rotated_shape.x >= self.width: rotated_shape.x = self.width - rotated_shape.right_edge - 1 if rotated_shape.bottom_edge + rotated_shape.y > self.height: return False if not self.check_bottom(rotated_shape) and not self.is_collision(rotated_shape): self.active_shape = rotated_shape def move_left(self): self.active_shape.x -= 1 if self.out_of_bounds() or self.is_collision(): self.active_shape.x += 1 return False return True def move_right(self): self.active_shape.x += 1 if self.out_of_bounds() or self.is_collision(): self.active_shape.x -= 1 return False return True def move_down(self): self.active_shape.y += 1 if self.check_bottom() or self.is_collision(): self.active_shape.y -= 1 self.shape_to_board() self.add_shape() return False return True def out_of_bounds(self, shape=None): shape = shape or self.active_shape if shape.x + shape.left_edge < 0: return True elif shape.x + shape.right_edge >= self.width: return True return False def check_bottom(self, shape=None): shape = shape or self.active_shape if shape.y + shape.bottom_edge >= self.height: return True return False def is_collision(self, shape=None): shape = shape or self.active_shape for y in range(4): for x in range(4): if y + shape.y < 0: continue if shape.shape[y][x] and self.board[y + shape.y][x + shape.x]: return True return False def test_for_line(self): for y in range(self.height - 1, -1, -1): counter = 0 for x in range(self.width): if self.board[y][x] == Shape.BLOCK_FULL: counter += 1 if counter == self.width: self.process_line(y) return True return False def process_line(self, y_to_remove): for y in range(y_to_remove - 1, -1, -1): for x in range(self.width): self.board[y + 1][x] = self.board[y][x] def shape_to_board(self): # transpose onto board # while test for line, process & increase score for y in range(4): for x in range(4): dx = x + self.active_shape.x dy = y + self.active_shape.y if self.active_shape.shape[y][x] == Shape.BLOCK_FULL: self.board[dy][dx] = Shape.BLOCK_FULL lines_found = 0 while self.test_for_line(): lines_found += 1 if lines_found: self.dispatch_event('on_lines', lines_found) self.encoding = None def move_piece(self, motion_state): if motion_state == key.MOTION_LEFT: self.move_left() elif motion_state == key.MOTION_RIGHT: self.move_right() elif motion_state == key.MOTION_UP: self.rotate_shape() elif motion_state == key.MOTION_DOWN: self.move_down() def draw_game_board(self): for y, row in enumerate(self.board): for x, col in enumerate(row): if col == Shape.BLOCK_FULL or col == Shape.BLOCK_ACTIVE: self.draw_block(x, y) for y in range(4): for x in range(4): dx = x + self.active_shape.x dy = y + self.active_shape.y if self.active_shape.shape[y][x] == Shape.BLOCK_FULL: self.draw_block(dx, dy) def draw_block(self, x, y): y += 1 # since calculated_height does not account for 0-based index self.block.blit(x * self.block.width, self.calculated_height - y * self.block.height) def isoccupied(self, x, y): if self.board[y][x] == Shape.BLOCK_FULL or self.board[y][x] == Shape.BLOCK_ACTIVE: return True return False def encode_all(self): flags = [] for y in range(4): for x in range(4): dx = x + self.active_shape.x dy = y + self.active_shape.y if self.active_shape.shape[y][x] == Shape.BLOCK_FULL: self.board[dy][dx] = Shape.BLOCK_FULL for y in range(len(self.board)): for x in range(len(self.board[y])): if self.isoccupied(x, y): flags.append('1') else: flags.append('0') for y in range(4): for x in range(4): dx = x + self.active_shape.x dy = y + self.active_shape.y if self.active_shape.shape[y][x] == Shape.BLOCK_FULL: self.board[dy][dx] = Shape.BLOCK_EMPTY return ''.join(flags) def encode_only_static(self): flags = [] for y in range(len(self.board)): for x in range(len(self.board[y])): if self.isoccupied(x, y): flags.apped('1') else: flags.append('0') return ''.join(flags) def encode_distance(self): d = [str(self.active_shape.shapeidx)] for x in range(len(self.board[0])): for y in range(len(self.board)): if self.isoccupied(x, y): assert(y < 36) d.append(num2base36(y)) break if len(d) <= x+1: d.append(num2base36(len(self.board))) return ''.join(d) def encode_toprows(self): if self.encoding is not None: self.encoding[0] = str(self.active_shape.shapeidx) self.encoding[1] = str(self.active_shape.rotationidx) self.encoding[2] = num2base36(self.active_shape.x + self.width // 2 - self.active_shape.left_edge) else: # encode active shape self.encoding = [str(self.active_shape.shapeidx), str(self.active_shape.rotationidx), num2base36(self.active_shape.x + self.width // 2 - self.active_shape.left_edge)] miny = len(self.board) - 3 # find first empty row from the bottom up for y in range(len(self.board)-1, -1, -1): emptyrow = True for x in range(len(self.board[y])): if self.isoccupied(x,y): emptyrow = False break if emptyrow: miny = min(miny, y) break # collect values for y in range(miny+1, miny+3): for x, cols in enumerate(self.board[y]): if self.isoccupied(x, y): self.encoding.append('1') else: self.encoding.append('0') return ''.join(self.encoding) def encode(self): return self.encode_toprows()
def __init__(self): self.name = "InitMF" self.f = Shape() self.shape = None
def svg(self): """Returns the SVG representation as an XML fragment.""" self.attrs['d'] = self.pathString() return Shape.svg(self)
def __init__(self, position, radius, rotation, color): Shape.__init__(self, position, rotation, color) self.radius = radius
class MembershipFunction: def __init__(self): self.name = "InitMF" self.f = Shape() self.shape = None def trap(self, a, b, c, d): self.f.setPoints([(a, 0), (b, 1), (c, 1), (d, 0)]) self.f.sortPoints() self.shape = "trap" self.points = (a, b, c, d) def tri(self, a, b, c): self.f.setPoints([(a, 0), (b, 1), (c, 0)]) self.f.sortPoints() self.shape = "tri" self.points = (a, b, c) def getDegree(self, inp): inp = float(inp) if self.shape == "trap": (a, b, c, d) = self.points if inp < a: return 0 if inp < b: p = (inp - a) / (b - a) return p if inp < c: return 1 if inp < d: p = (d - inp) / (d - c) return p return 0 if self.shape == "tri": (a, b, c) = self.points if inp < a: return 0 if inp < b: p = (inp - a) / (b - a) return p if inp < c: p = (c - inp) / (c - b) return p return 0 def getResult(self, deg): if deg == 1.0: f = Shape() for p in self.f.points: f.addPoint(p) return f if self.shape == "trap": f = Shape() (a, b, c, d) = self.points dx = (b - a) * deg dy = deg b = a + dx dx = (d - c) * deg c = d - dx f.setPoints([(a, 0), (b, dy), (c, dy), (d, 0)]) return f if self.shape == "tri": f = Shape() (a, b, c) = self.points dx1 = (b - a) * deg dx2 = (c - b) * deg b = a + dx1 d = c c = d - dx2 dy = deg f.setPoints([(a, 0), (b, dy), (c, dy), (d, 0)]) return f
def main(): k = Shape("yvonne",[[1,1],[2,2],[1,3],[4,1]]) k.compute_histograms() k.serialize() k.print_picture() j = Shape.deserialize("yvonne") k2 = Shape("jeanguy",[[5,2],[3,3],[4,4],[8,2]]) k2.compute_histograms() k2.print_picture() comparator = ShapeComparator() answer = comparator.compare(k,k2) comparator.print_result() print answer mat = np.array([[17,15,9,5,12],[16,16,10,5,10],[12,15,14,11,5],[4,8,14,17,13],[13,9,8,12,17]]) comparator.hungarian_algorithm(mat,5,5) mat = np.array([[80,40,50,46],[40,70,20,25],[30,10,20,30],[35,20,25,30]]) comparator.hungarian_algorithm(mat,4,4) return 0
def __init__(self, display): GameState.__init__(self, display) self.board = Board() self.shape = Shape(self.board, self.randomShape())
def __init__(self, shapeSides, gapSides): self._shape = Shape(shapeSides, 'shape being rotated') self._gapSides = gapSides
#!/usr/bin/env python from Shape import Shape # include Shape.py from Triangle import Triangle # include Triangle.py from Rectangle import Rectangle # include Rectangle.py # create new objects and initialize data shapeObject = Shape() triangleObject = Triangle(4, 5) rectangleObject = Rectangle(4, 5) print('Shapeless area is: %24.1f' % (shapeObject.get_area())) print('Triangle (base=%d, height=%d) area is: %6.1f' % (4, 5, triangleObject.get_area())) print('Rectangle (width=%d, height=%d) area is: %4.1f' % (4, 5, rectangleObject.get_area()))