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 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 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 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 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 reset(self): self.board = [] for row in range(self.height): self.board.append([0] * self.width) self.pending_shape = Shape() self.add_shape()
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)
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 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 __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 __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 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 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 testShapeIsValid(): 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) print(shapeIsValid(s))
def __init__(self, width=500, height=500, dfps=100, objnum=5): super().__init__() self.width = width self.height = height self.dfps = dfps self.objlist = [] self.time = 0 shape = Shape('circle', radius=20) for i in range(0, objnum): self.objlist.append(BaseObj(shape, random=True)) self.initUI()
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 __get_mean_shape(self, shapes): s = shapes[0].pointsToVec() for shape in shapes[1:]: s = s + shape.pointsToVec() vec = s / len(shapes) shape = Shape([]) shape.points = shape.vecToPoints(vec) shape.pts = shape.vecToPoints(vec) return shape
def timeShapeIsValid(): nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.0, 0], 0.1, 1, 1)) nodes.append(Node([-0.0, -1.3], 0.1, 1, 2)) nodes.append(Node([0.4, -1.3], 0.1, 1, 3)) s = Shape(nodes) start = time() for i in range(1): x = shapeIsValid(s) end = time() print(f"Time taken: {end-start:.2f} seconds")
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 testGetWalk(): 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) poss, rots = getWalk(s) #animateWalk(s, poss, rots) nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.3, 0], 0.1, 1, 1)) nodes.append(Node([-0.3, -0.9], 0.1, 1, 2)) nodes.append(Node([0.4, -0.9], 0.1, 1, 3)) s = Shape(nodes) poss, rots = getWalk(s) #animateWalk(s, poss, rots) nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.3, 0], 0.1, 1, 1)) nodes.append(Node([-0.3, -1.3], 0.1, 1, 2)) nodes.append(Node([0.4, -1.3], 0.1, 1, 3)) nodes.append(Node([0.6, -0.6], 0.4, -1, 4)) s = Shape(nodes) poss, rots = getWalk(s) #print(f"Length: {len(poss)}") #animateWalk(s, poss, rots) nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.0, 0], 0.1, 1, 1)) nodes.append(Node([-0.0, -1.3], 0.1, 1, 2)) nodes.append(Node([0.4, -1.3], 0.1, 1, 3)) s = Shape(nodes) poss, rots = getWalk(s) print(f"Length: {len(poss)}") animateWalk(s, poss, rots)
def testWalkAnimation(): nodes = [Node([0.4, 0], 0.1, 1, 0)] nodes.append(Node([-0.3, 0], 0.1, 1, 1)) nodes.append(Node([-0.3, -0.5], 0.1, 1, 2)) nodes.append(Node([0.4, -0.5], 0.1, 1, 3)) s = Shape(nodes) ys = np.linspace(0, 1, 1000) xs = np.zeros(1000) poss = np.column_stack((xs, ys)) rots = np.linspace(0, 0.5, 1000) animateWalk(s, poss, rots)
def __init__(self, path): # Clearing shapes from last time self.shapes = [] self.points = [] # Setting up the cv2 window self.path = path self.image = cv2.imread(path) cv2.namedWindow("Focus") cv2.setMouseCallback("Focus", self.create_polygon) # Infinite loop to run polygon creation while(True): # Drawing the original/modified image every time cv2.imshow('Focus', self.image) # Key presses command = cv2.waitKey(10) & 0xFF # Local parameters pts = np.asarray(self.points, np.int32).reshape(-1, 1, 2) color = (0, 0, 255) thickness = 2 # Submit shape if command == ord('a'): # Save the points as a new shape self.shapes.append(Shape(len(self.shapes), self.points)) # Debugging lines # print(self.shapes) # Draw the polygon cv2.polylines(self.image, [pts], True, color, thickness, lineType = cv2.LINE_AA) # Clear the points for a new polygon self.points = [] # Delete previous shape if a mistake was made elif command == ord('d'): self.shapes = self.shapes[:-1] self.image = cv2.imread(path) for shape in self.shapes: cv2.polylines(self.image, [np.asarray(shape.coordinates, np.int32).reshape(-1, 1, 2)], True, color, thickness, lineType = cv2.LINE_AA) # Exit condition elif command == ord('q'): break # Close all windows after exit cv2.destroyAllWindows()
def getSimpleShape(index): # Script to run to get the basic Shape info _script = ''' return {{ state: PlayState.shapes[{0}].state, startX: PlayState.shapes[{0}].startX, startY: PlayState.shapes[{0}].startY }}; '''.format(index) # Executing scripts rawShape = driver.execute_script(_script) return Shape(rawShape)
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 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 __init__(self,Chromosome_Length,Population_Size,mutation_rate,shapeType,image,picture_h,picture_w): self.chromosome_length=Chromosome_Length self.population_size=Population_Size self.shapeType=shapeType self.picture_h=picture_h self.picture_w=picture_w self.original_image=image self.mutation_rate=mutation_rate self.population=[] for i in range(Population_Size): chromosome = [] for j in range(Chromosome_Length): chromosome.append(Shape(shapeType,picture_h,picture_w)) self.population.append(chromosome)
def __init__(self, mode): super().__init__() self.setStyleSheet( "QMainWindow {background-image: url(../../data/border_part.png); border: 2px solid rgb(251, 226, 19); border-radius: 3px;}" ) self.setPalette(QPalette(Qt.white)) self.setAutoFillBackground(True) self.setMinimumSize(300, 600) self.curPiece = Shape() self.curPiece.setRandomShape() self.nextCurPiece = Shape() self.nextCurPiece.setRandomShape() self.initBoard() self.mode = mode if mode == "n": self.Speed = 70 self.level = 0 self.counter = 0 self.msg2Level.emit(str(self.level)) elif mode == "f": self.Speed = 5 self.level = 5 self.counter = 0 self.msg2Level.emit(str(self.level)) self.start() self.newPiece() self.player_main_music = QMediaPlayer() self.player_main_fast = QMediaPlayer() self.player_delete1row = QMediaPlayer() self.player_delete4row = QMediaPlayer() self.player_pause_sound = QMediaPlayer() self.playlist_main = QMediaPlaylist() if mode == "n": self.start_main_music() elif mode == "f": self.start_main_music_fast()
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 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())