def test___eq__(self): square = Square("a1") same = Square("a1") other = Square("a2") self.assertEqual(True, square.__eq__(same)) self.assertEqual(False, square.__eq__(other))
def next(self): raw_entry = self.next_raw() source_x = ((raw_entry[1] >> 6) & 077) & 0x7 source_y = (((raw_entry[1] >> 6) & 077) >> 3) & 0x7 target_x = (raw_entry[1] & 077) & 0x7 target_y = ((raw_entry[1] & 077) >> 3) & 0x7 promote = (raw_entry[1] >> 12) & 0x7 move = Move( source=Square.from_x_and_y(source_x, source_y), target=Square.from_x_and_y(target_x, target_y), promotion="nbrq"[promote + 1] if promote else None) # Replace the non standard castling moves. if move.uci == "e1h1": move = Move.from_uci("e1g1") elif move.uci == "e1a1": move = Move.from_uci("e1c1") elif move.uci == "e8h8": move = Move.from_uci("e8g8") elif move.uci == "e8a8": move = Move.from_uci("e8c8") return { "position_hash": raw_entry[0], "move": move, "weight": raw_entry[2], "learn": raw_entry[3] }
def test_create_square_with_copy_constructor(self): sq = Square('e7') sq2 = Square(sq) self.assertTrue(sq2.tuple() == (4, 6)) self.assertTrue(str(sq2) == 'e7') self.assertTrue(sq2 == sq) self.assertFalse(sq.square is sq2.square) # are they really copies?
def test_decode(self): a= Square.SQ_SIZE b = a*(Square.GRID_SIZE+3) rect = [(a,a),(b,a),(b,b),(a,b)] m_d = SquareDetector(Square.generate(1),0) for i in range(32): img = Square.generate(i) sq = Square(i,m_d) m_d.gray_img=img a,b = sq._decode_rect(rect) self.assertTrue((sq.TOP_LEFT,i)==(a,b),"Wrong %d: (%d,%d)"%(i,a,b)) cv.Transpose(img, img) cv.Flip(img) a,b = sq._decode_rect(rect) self.assertTrue((sq.BOT_LEFT,i)==(a,b),"Wrong %d: (%d,%d)"%(i,a,b)) cv.Transpose(img, img) cv.Flip(img) a,b = sq._decode_rect(rect) self.assertTrue((sq.BOT_RIGHT,i)==(a,b),"Wrong %d: (%d,%d)"%(i,a,b)) cv.Transpose(img, img) cv.Flip(img) a,b = sq._decode_rect(rect) self.assertTrue((sq.TOP_RIGHT,i)==(a,b),"Wrong %d: (%d,%d)"%(i,a,b)) m_d.flip_H=True for i in range(32): img = Square.generate(i) sq = Square(i,m_d) m_d.gray_img=img cv.Flip(img,img,1) _,b = sq._decode_rect(rect) self.assertTrue(i==b,"Wrong Flip %d: (%d)"%(i,b))
def from_x88(cls, source, target, promotion=''): if not cls._x88_moves: raise ValueError # try to use the cache if not promotion: return cls._x88_moves[(source, target)] return Move(Square.from_x88(source), Square.from_x88(target), promotion)
def test_create_square_with_tuple(self): sq = Square((3, 3)) self.assertTrue(sq.tuple() == (3,3)) self.assertTrue(str(sq) == 'd4') sq = Square((999999, 999999)) self.assertTrue(sq.tuple() == (999999, 999999)) self.assertRaises(ValueError, Square, (-4, 5)) self.assertRaises(ValueError, Square, (4, -5))
def get_all(cls): '''Yield all moves combinations that do not have promotion.''' #FIXME add in promotion for source in Square.get_all(): for target in Square.get_all(): if source != target: move = cls(Square.from_x88(source.x88), Square.from_x88(target.x88)) yield(move)
def main(): sh = Shape() print sh t = Triangle(5, 10) print t.area() print "%s Static Method" % t.static_area(10, 20) s = Square(20) print s.area() print s.perimeter()
class TestSquare(unittest.TestCase): def setUp(self): self.square = Square(5) def test_perimeter(self): self.assertEqual(self.square.perimeter(), 20) def test_area(self): self.assertEqual(self.square.area(), 25)
class SquareTest(unittest.TestCase): def setUp(self): self.square = Square(side=3) def test_it_has_a_side(self): self.square.side |should| equal_to(3) def test_it_changes_its_side(self): self.square.side = 5 self.square.side |should| equal_to(5) def test_it_calculates_its_area(self): self.square.area() |should| equal_to(9)
def to_move(cls, position, san): san = str(san) # Castling moves. if san == "O-O" or san == "O-O-O": # TODO: Support Chess960, check the castling moves are valid. rank = 1 if position.fen.turn == "w" else 8 if san == "O-O": return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'g')) else: return Move( source=Square.from_rank_and_file(rank, 'e'), target=Square.from_rank_and_file(rank, 'c')) # Regular moves. else: matches = cls.san_regex.match(san) if not matches: raise ValueError("Invalid SAN: %s." % repr(san)) if matches.group(1): klass = Piece.klass(matches.group(1).lower()) else: klass = PAWN piece = Piece.from_klass_and_color(klass, position.fen._to_move) target = Square(matches.group(4)) source = None for m in position.get_legal_moves(): if position._pieces[m.source._x88] != piece or m.target != target: continue if matches.group(2) and matches.group(2) != m.source.file: continue if matches.group(3) and matches.group(3) != str(m.source.rank): continue # Move matches. Assert it is not ambiguous. if source: raise MoveError( "Move is ambiguous: %s matches %s and %s." % san, source, m) source = m.source if not source: raise MoveError("No legal move matches %s." % san) return Move(source, target, matches.group(5) or None)
def __init__(self): self.maze_squares = get_maze_squares() self.maze_map = make_maze_map(self.maze_squares) print self.maze_map self.player = Square(start = [50,50], color=BLUE) self.enemies = [] self.lasers = [] for i in range(10): x = random.randint(0, WIDTH) y = random.randint(0, HEIGHT) enemy = Square(start = (x,y), color=RED) self.enemies.append(enemy)
class GameState: def __init__(self): self.maze_squares = get_maze_squares() self.maze_map = make_maze_map(self.maze_squares) print self.maze_map self.player = Square(start = [50,50], color=BLUE) self.enemies = [] self.lasers = [] for i in range(10): x = random.randint(0, WIDTH) y = random.randint(0, HEIGHT) enemy = Square(start = (x,y), color=RED) self.enemies.append(enemy) def update(self, control_state): self.player.velocity = control_state.get_player_velocity() if control_state.firing: self.make_new_laser() self.player.update_position(self.maze_map) for laser in self.lasers: laser.update_position(self.maze_map) def get_squares(self): yield self.player for enemy in self.enemies: yield enemy for maze_square in self.maze_squares: yield maze_square for laser in self.lasers: yield laser def make_new_laser(self): laser_pos = [0,0] laser_pos[0] = self.player.pos[0] laser_pos[1] = self.player.pos[1] difference = sub_vec(pygame.mouse.get_pos(), self.player.pos) laser_speed = unit_vec(difference) laser = Square(start=laser_pos,velocity=laser_speed,color=RED) self.lasers.append(laser)
class Play(Scene): def __init__(self): Scene.__init__(self) self.BACKGROUND_COLOR = (0, 0, 0, 255) self.slider1 = Slider( (50, utils.SCREEN_H // 2 - Slider.HEIGHT), (pygame.K_w, pygame.K_s), ) self.slider2 = Slider( (utils.SCREEN_W - Slider.WIDTH - 50, utils.SCREEN_H // 2 - Slider.HEIGHT), (pygame.K_UP, pygame.K_DOWN), ) self.square = Square( (utils.SCREEN_W // 2 - Square.WIDTH // 2, utils.SCREEN_H // 2 - Square.HEIGHT // 2), ) def go_to_menu(self): from menu import Menu utils.set_scene( Menu() ) def on_escape(self): self.go_to_menu() def update(self): keys = pygame.key.get_pressed() self.slider1.update(keys) self.slider2.update(keys) self.square.update( (self.slider1.fPos, self.slider2.fPos) ) def blit(self): self.slider1.blit(utils.screen) self.slider2.blit(utils.screen) self.square.blit(utils.screen)
def __init__(self): Scene.__init__(self) self.BACKGROUND_COLOR = (0, 0, 0, 255) self.slider1 = Slider( (50, utils.SCREEN_H // 2 - Slider.HEIGHT), (pygame.K_w, pygame.K_s), ) self.slider2 = Slider( (utils.SCREEN_W - Slider.WIDTH - 50, utils.SCREEN_H // 2 - Slider.HEIGHT), (pygame.K_UP, pygame.K_DOWN), ) self.square = Square( (utils.SCREEN_W // 2 - Square.WIDTH // 2, utils.SCREEN_H // 2 - Square.HEIGHT // 2), )
def get_king(self, color): """Gets the square of the king. :param color: `"w"` for the white players king. `"b"` for the black players king. :return: The first square with a matching king or `None` if that player has no king. """ #if not color in ["w", "b"]: # raise KeyError("Invalid color: %s." % repr(color)) for square, piece in [(s, self._pieces[s._x88]) for s in Square.get_all() if self._pieces[s._x88]]: if Piece.is_klass_and_color(piece, KING, color): return square
def is_insufficient_material(self): """Checks if there is sufficient material to mate. Mating is impossible in: * A king versus king endgame. * A king with bishop versus king endgame. * A king with knight versus king endgame. * A king with bishop versus king with bishop endgame, where both bishops are on the same color. Same goes for additional bishops on the same color. Assumes that the position is valid and each player has exactly one king. :return: Whether there is insufficient material to mate. """ piece_counts = self.get_piece_counts() # King versus king. if sum(piece_counts.values()) == 2: return True # King and knight or bishop versus king. elif sum(piece_counts.values()) == 3: if piece_counts["b"] == 1 or piece_counts["n"] == 1: return True # Each player with only king and any number of bishops, # where all bishops are on the same color. elif sum(piece_counts.values()) == 2 + piece_counts[BISHOP]: white_has_bishop = self.get_piece_counts([WHITE])[BISHOP] != 0 black_has_bishop = self.get_piece_counts([BLACK])[BISHOP] != 0 if white_has_bishop and black_has_bishop: color = None for square in Square.get_all(): p = self._pieces[square._x88] if p and Piece.klass(p) == BISHOP: if color and color != square.is_light(): return False color = square.is_light() return True return False
def test_create_square_with_string(self): sq = Square('a1') self.assertTrue(sq.tuple() == (0,0)) self.assertTrue(str(sq) == 'a1') sq = Square('1A') self.assertTrue(sq.tuple() == (0,0)) self.assertTrue(str(sq) == 'a1') self.assertTrue(Square('f6').tuple() == (5,5)) self.assertTrue(str(Square('f6')) == 'f6') self.assertTrue(Square('10 J').tuple() == (9,9)) self.assertTrue(str(Square('10 J')) == 'j10') sq = Square('z999999') self.assertTrue(sq.tuple() == (25,999998)) self.assertTrue(str(sq) == 'z999999')
def generate_squares(side): squares.clear() for i in range(0, 8): for j in range(0, 8): x = int(i * SQUARESIZE) + XBUFFER y = int(j * SQUARESIZE) width = SQUARESIZE height = SQUARESIZE if i % 2 == 0: colour = LIGHT if (j % 2 == 0) else DARK else: colour = LIGHT if (j % 2 == 1) else DARK coords = FILES[i] + RANKS[(len(RANKS) - 1) - j] if ( side == "WHITE") else FILES[(len(FILES) - 1) - i] + RANKS[j] sq = Square(coords, x, y, width, height, colour, myfont) squares[coords] = sq
def get_squares(self): flags = [True] * 8 directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)] squares = [] for i in range(1, 8): for j in range(len(flags)): flag, direction = flags[j], directions[j] right, up = direction if flag: next_square = Square(self.loc.rank + i*up, self.loc.file + i*right) if self.board.exists_piece(next_square, color=self.white): flags[j] = False elif self.board.exists_piece(next_square, color=self.other): squares.append(next_square) flags[j] = False else: squares.append(next_square) return validate(squares)
def __init__(self): del globals.squares[0:len(globals.squares)] self.gameover_timer = 0 self.p1 = Player(4, 4, globals.white, globals.black, 1) self.p2 = Player(14, 4, globals.black, globals.white, 2) #initialize squares for i in range(globals.squares_per_line): globals.squares.append([]) for j in range(globals.squares_per_column): globals.squares[i].append(Square(i, j, self.p2)) for column in globals.squares[:len(globals.squares) / 2]: for square in column: square.change_owner(self.p1) del globals.bombs[0:len(globals.bombs)] del globals.explosions[0:len(globals.explosions)] del globals.powerups[0:len(globals.powerups)]
def player_turn(self): sign_placed = False while not sign_placed: user_input = input('Select a space: ') if user_input in Game.SQUARES.keys(): coords = Game.SQUARES[user_input] else: print('There is no such space!') continue if self.panel.board[coords[0]][coords[1]].sign not in Game.SIGNS: self.panel.board[coords[0]][coords[1]] = Square(self.human_player.sign) sign_placed = True self.print_board() if self.panel.check_win(): print('You win!') sys.exit() if self.panel.check_draw(): print('It is a draw!') sys.exit() else: print('Space is already taken!')
def __init__(self, parent: scene.Node, square: Square) -> None: self.coord = square.coord if square.is_white(): color = LIGHT_SQUARE_COLOR else: color = DARK_SQUARE_COLOR pos = coord_to_pos(square.coord) path = ui.Path.rect(0, 0, SQUARE_SIZE, SQUARE_SIZE) super().__init__( path=path, parent=parent, position=pos, fill_color=color, ) # Coordinate index labels if square.file == "a": self.add_child(self.IndexLabel(square.rank)) if square.rank == 1: self.add_child(self.IndexLabel(square.file))
def __init__(self, size, mines, surface, square_size=40): self.surface = surface self.size = size self.square_size = square_size self.game_lost = False self.game_won = False self.total_flags = 0 self.game_started = False self.unclicked_squares = size[0] * size[1] self.total_mines = mines len_x = self.square_size * size[1] len_y = self.square_size * size[0] self.square_grid = pygame.Rect(0, 50, len_x, len_y) # Makes a 2D list of Square objects start_x, start_y = self.square_grid.topleft end_x, end_y = self.square_grid.bottomright self.squares = [[ Square(self, i, j) for i in range(start_x, end_x, self.square_size) ] for j in range(start_y, end_y, self.square_size)] # Font object for mine counter and timer self.game_font = pygame.font.Font('freesansbold.ttf', 48) # Places the mine counter self.mine_counter = self.game_font.render(str(mines), True, (255, 0, 0)) self.counter_loc = self.mine_counter.get_rect() self.counter_loc.bottomleft = self.square_grid.topleft self.update_mine_counter() # Places the timer self.timer = self.game_font.render("999", True, (255, 0, 0)) self.timer_loc = self.timer.get_rect() self.timer_loc.bottomright = self.square_grid.topright self.start_time = 0 self.curr_time = 0
def squares(img): # Edge detection img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(img, (5, 5), 0) img = cv2.Canny(img, 100, 200) # Find contours contImg, contours, _ = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) squares = [] for c in contours: contour_length = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * contour_length, True) if 4 <= len(approx) <= 6: (x, y, w, h) = cv2.boundingRect(approx) aspectRatio = w / float(h) area = cv2.contourArea(c) hullArea = cv2.contourArea(cv2.convexHull(c)) solidity = area / float(hullArea) checkDimensions = w > 25 and h > 25 checkSolidity = solidity > 0.9 checkAspectRatio = 0.5 <= aspectRatio <= 1.5 if checkDimensions and checkSolidity and checkAspectRatio: s = Square(c, x, y, w, h) if s not in squares: squares.append(s) # Reject similar squares for s1, s2 in itertools.combinations(squares, 2): if s1.similar(s2) and s2 in squares: squares.remove(s2) print "Number of contours: %s" % len(contours) print "Total number of squares: %s" % len(squares) return squares
def hash_position(self, position): """Computes the Zobrist hash of a position. :param position: The position to hash. :return: The hash as an integer. """ key = 0 # Hash in the board setup. for square in Square.get_all(): piece = position[square] if piece: i = "pPnNbBrRqQkK".index(piece.symbol) key ^= self.__random_array[64 * i + 8 * square.y + square.x] # Hash in the castling flags. if position.get_castling_right("K"): key ^= self.__random_array[768] if position.get_castling_right("Q"): key ^= self.__random_array[768 + 1] if position.get_castling_right("k"): key ^= self.__random_array[768 + 2] if position.get_castling_right("q"): key ^= self.__random_array[768 + 3] # Hash in the en-passant file. if (position.ep_file and position.get_theoretical_ep_right(position.ep_file)): i = ord(position.ep_file) - ord("a") key ^= self.__random_array[772 + i] # Hash in the turn. if position.turn == "w": key ^= self.__random_array[780] return key
def get_grid(self): grid = [] x, y = 10, 10 id = 0 self.squares_per_row = 25 self.num_of_squares = 500 // self.squares_per_row for i in range(self.num_of_squares): grid.append([]) x = 10 for j in range(self.num_of_squares): current_sqr = Square(x, y, self.num_of_squares, self.num_of_squares, None, self.surface, id) grid[i].append(Node(self, current_sqr, i, j)) id += 1 x += self.squares_per_row y += self.squares_per_row return grid
def test_move2(self): self.piece.set_position(Square(1, 0, "white")) # Invalid double move possible, moves = self.piece.move((3, 0)) self.assertEqual(possible, False) self.assertEqual(moves, []) # Valid single move possible, moves = self.piece.move((2, 0)) self.assertEqual(possible, True) self.assertEqual(moves, [(1, 0), (2, 0)]) # Valid cross move possible, moves = self.piece.amove((2, 1)) self.assertEqual(possible, True) self.assertEqual(moves, [(1, 0), (2, 1)]) # Valid cross move possible, moves = self.piece.amove((2, -1)) self.assertEqual(possible, True) self.assertEqual(moves, [(1, 0), (2, -1)]) # Invalid cross move possible, moves = self.piece.amove((2, 2)) self.assertEqual(possible, False) self.assertEqual(moves, [])
def get_theoretical_castling_right(self, klass): """Checks if a player could have a castling right in theory from looking just at the piece positions. :param klass: The type of castling move to check. See `Position.get_castling_right(type)` for values. :return: A boolean indicating whether the player could theoretically have that castling right. """ if klass not in Piece.castleclass: raise KeyError(klass) # TODO: Support Chess960. for square, enum in Piece.castle_squares[klass]: piece = self._pieces[Square(square)._x88] if not piece or Piece.enum(piece) != enum: return False return True
def handle_data(self, data): if self._state == self.states.NEUTRAL or self._state == self.states.ACCEPTING: namePat = re.compile(r"Crossword for.+") if re.match(namePat, data): self._grid.name = data elif self._state == self.states.WHITE_SQUARE: numPat = re.compile(r"\D*(\d*)") match = re.match(numPat, data) if match: #print 'Adding white square: ' + match.group(1) self._grid.setSquare( self._row, self._col, Square(self._grid, self._row, self._col, letter='', number=match.group(1))) self._state = self.states.IN_ROW #print 'reentering IN_ROW state' else: raise HTMLParser.HTMLParseError('Expected number or blank')
def add_pieces_to_board(self): all_pieces = self.players[0].pieces + self.players[1].pieces for x in range(8): for y in range(8): square = None for piece in all_pieces: if piece.x == x and piece.y == y: square = Square(self.frame, piece, command=self.move) break else: square = Square(self.frame, Blank(img_path=IMAGE_PATH.format('blank'), x=x, y=y), command=self.move) self.squares[x][y] = square square.grid(column=x, row=y, sticky='nsew')
def create_square(ng_settings, screen, squares_l, x_number, y_number, stats): '''创建一个格子''' square = Square(screen, ng_settings) square.rect.x = 10 + x_number * (ng_settings.squares_size + ng_settings.gap_space) square.rect.y = 10 + y_number * (ng_settings.squares_size + ng_settings.gap_space) # 格子有50%可能为FILL r = randint(0, 1) if r: square.FILL = True square.NOTHING = False stats.fill_total += 1 square.set_fill_color() squares_l.append(square)
def update(self, delta_time): """ All the logic to move, and the game logic goes here. Normally, you'll call update() on the sprite lists that need it. """ self.view_bottom += self.change_bottom self.view_left += self.change_left self.frame_count += 1 # Disminuir el giro de la camara exponencialmente if self.change_angle != 0: self.change_angle = self.change_angle / 2 # Crear nuevos shapes # Probabilidad 1 en 100 if random.randrange(100) == 0: rx = random.randrange(self.view_left, self.view_left + win.WIDTH) ry = random.randrange(self.view_bottom, self.view_bottom + win.HEIGHT) square = Square(rx, ry) self.square_list.append(square) for s in self.shot_list: if arcade.geometry.check_for_collision_with_list( s, self.square_list): c.alive = False s.alive = False # Quitar balas que estan fuera de la pantalla self.shot_list = list(filter(lambda x: x.is_alive(), self.shot_list)) # Actualizar shapes for s in self.square_list + self.shot_list + [self.circle]: s.update(delta_time, self) arcade.set_viewport(self.view_left, self.view_left + win.WIDTH, self.view_bottom, self.view_bottom + win.HEIGHT)
def draw_laby(self, sprite): """Draws the labyrinth from the maze list created from maze.txt""" i = 0 while i < 600: j = 0 while j < 600: case = Square(i // 40, j // 40, maze[i // 40][j // 40]) value_case = case.name if value_case == "x": windowSurface.blit(sprite.img_mur, (case.x * 40, case.y * 40)) elif value_case == " ": windowSurface.blit(sprite.img_sol, (case.x * 40, case.y * 40)) elif value_case == "m": windowSurface.blit(sprite.img_sol, (case.x * 40, case.y * 40)) else: windowSurface.blit(sprite.img_murd, (self.murdock.x, self.murdock.y)) j = j + 40 i = i + 40
def __init__(self, length): """ Constructs a *Ship* object and creates the number of square objects equal to *Ship* object's length. Parameters: ---------- length: int Raises: ------ TypeError: when length type isn't int """ if not isinstance(length, int): raise TypeError self.length = length self.is_sunk = False self.is_hidden = False self.square_list = [] for i in range(length): square_i = Square() self.square_list.append(square_i)
def __init__(self): ''' Creates a basic structure of the world where the game will be played. Initially the world is empty but Game reads a file which states the location of game board elements, enemies, points and armament. The game will be played at full screen mode. ''' width = 120 height = 30 self.squares = [ None ] * width # we create basic list to use it as starting ground for x in range(self.get_width()): # stepper self.squares[x] = [None] * height for y in range(self.get_height()): # stepper self.squares[x][y] = Square() # fixed value self.enemies = [] # list of enemies in Game self.player = None # The player object of the game self.bullets = [ ] # list of the bullets that are currently in the "air"
def resetGlobal(): globVar.player = "W" globVar.playerCount = 0 globVar.w_NumPieces = 16 globVar.b_NumPieces = 16 globVar.r_w_NumPieces = 1 globVar.r_b_NumPieces = 1 globVar.w_check = False globVar.b_check = False globVar.removed = False globVar.removed_label = -1 globVar.removed_color = "none" globVar.last_row = -1 globVar.last_col = -1 globVar.scanning = False globVar.r_avail_Num = 1 globVar.r_w_pieces = [pieces.Pawn("none", "none")] globVar.r_b_pieces = [pieces.Pawn("none", "none")] globVar.r_avail = [Square(False, "none", pieces.Pawn("none","none"), -1, -1)] globVar.p_w_Moves = [] globVar.p_b_Moves = [] globVar.p_w_Num = -1 globVar.p_b_Num = -1
def build_new_tower(self): if self.gold >= 70 and self.build_tower and mouseX in range( 135, 165) and mouseY in range(625, 655): self.towers.append(Circle(self.build_loc[0], self.build_loc[1])) self.gold -= 70 print("tower built!") self.build_tower = False for plot in self.land_plots: if plot[0] == self.build_loc[0] and plot[1] == self.build_loc[ 1]: self.land_plots.remove(plot) self.build_loc.pop(0) self.build_loc.pop(0) if self.gold >= 90 and self.build_tower and mouseX in range( 235, 265) and mouseY in range(625, 655): self.towers.append(Square(self.build_loc[0], self.build_loc[1])) self.gold -= 90 print("tower built!") self.build_tower = False for plot in self.land_plots: if plot[0] == self.build_loc[0] and plot[1] == self.build_loc[ 1]: self.land_plots.remove(plot) self.build_loc.pop(0) self.build_loc.pop(0) if self.gold >= 80 and self.build_tower and mouseX in range( 335, 365) and mouseY in range(625, 655): self.towers.append(Ice_Tower(self.build_loc[0], self.build_loc[1])) self.gold -= 80 print("tower built!") self.build_tower = False for plot in self.land_plots: if plot[0] == self.build_loc[0] and plot[1] == self.build_loc[ 1]: self.land_plots.remove(plot) self.build_loc.pop(0) self.build_loc.pop(0)
def makeGrid(): # global grid colorSwitcher = {"white": "black", "black": "white"} # If playerColor = White, tileColor = black, and vice versa tileColor = "black" for row in range(0, 8): rowTiles = [] for col in range(0, 8): rowTiles.append(Square(None, tileColor)) tileColor = colorSwitcher[tileColor] grid.append(rowTiles) tileColor = colorSwitcher[tileColor] # init pawns for col in range(0, 8): grid[1][col].piece = pieces.Pawn("W", 1, col) grid[6][col].piece = pieces.Pawn("B", 6, col) # init rest of pieces grid[0][0].piece = pieces.Rook("W", 0, 0) grid[0][1].piece = pieces.Knight("W", 0, 1) grid[0][2].piece = pieces.Bishop("W", 0, 2) grid[0][3].piece = pieces.Queen("W", 0, 3) grid[0][4].piece = pieces.King("W", 0, 4) grid[0][5].piece = pieces.Bishop("W", 0, 5) grid[0][6].piece = pieces.Knight("W", 0, 6) grid[0][7].piece = pieces.Rook("W", 0, 7) grid[7][0].piece = pieces.Rook("B", 6, 0) grid[7][1].piece = pieces.Knight("B", 6, 1) grid[7][2].piece = pieces.Bishop("B", 6, 2) grid[7][3].piece = pieces.Queen("B", 6, 3) grid[7][4].piece = pieces.King("B", 6, 4) grid[7][5].piece = pieces.Bishop("B", 6, 5) grid[7][6].piece = pieces.Knight("B", 6, 6) grid[7][7].piece = pieces.Rook("B", 6, 7)
def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) # setting up the window self.setWindowTitle("Robot arm 9000") self.setFixedSize(QSize(1080, 720)) # setting up the dimensions of the items link1 = 150 link2 = 150 radius = link1 + link2 square_width = 50 square_height = 50 # setting up the items self.robot = Robot(link1, link2) # lengths of the links self.square = Square(square_width, square_height, radius) # add size # setting up the docks for the window self.set_manualdock() self.set_autodock() self.set_suctiondock() # setting up the graphics for the window self.set_graphics()
def fill_board(self): """Fills the board with Square objects. Args: none Returns: none """ self.board = [] for i in range(0, 10): temp_list = [] for j in range(0, 10): visibility = True if self.owner.name == "AI": visibility = False temp_list.append(Square(i, j, visibility)) self.board.append(temp_list)
def make_grid(self, width, height, reveal_callback, flag_callback): """ Populates grid to user specification Args: width: Integer for width of board height: Integer for height of board reveal_callback: function to call when a square is revealed flag_callback: function to call when a square is flagged Returns: grid: Populated 2D array to act as game board """ width = int(width) height = int(height) grid = [[0 for y in range(height)] for x in range(width)] for i in range(0, width): for j in range(0, height): grid[i][j] = Square(self.board_window, i, j, reveal_callback, flag_callback) return grid
class Matrix(): matrix = [[Square(x, y, 0) for x in range(Sett.boardWidth)] for y in range(Sett.boardHeight)] def drawMatrix(): print() for x in range(len(Matrix.matrix)): for y in range(len(Matrix.matrix)): print(Matrix.matrix[x][y].state, end=' ') if y == len(Matrix.matrix) - 1: print() print() def changeState(y, x, state): Matrix.matrix[y][x].state = state def generation(): tempMatrix = copy.deepcopy(Matrix.matrix) for y in range(len(Matrix.matrix)): for x in range(len(Matrix.matrix)): count = Matrix.matrix[y][x].checkArea(Matrix.matrix) #logic, see rules on https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life Matrix.matrix = tempMatrix def drawRects(screen: pygame.Surface): color = None for row in Matrix.matrix: for square in row: if square.state == 1: color = (200, 100, 0) elif square.state == 0: color = (100, 100, 100) pygame.draw.rect(screen, color, [ square.x * Sett.gridSize, square.y * Sett.gridSize, Sett.gridSize, Sett.gridSize ], 0)
def test_create_square_with_multiple_args(self): sq = Square(4, 5) self.assertTrue(sq.tuple() == (4, 5)) self.assertTrue(str(sq) == 'e6')
def test_create_default_square(self): sq = Square() self.assertTrue(sq.tuple() == (0,0)) self.assertTrue(str(sq) == 'a1')
import pygame from vector import Vector from square import Square import random pygame.init() screen = pygame.display.set_mode((700, 500)) pygame.display.set_caption("Studsaren") square = Square(screen, random.randint(0, screen.get_size()[0] - 50), random.randint(0, screen.get_size()[1] - 50), 50, 50) square.velocity = 200 * Vector(random.uniform(-10, 10), random.uniform(-10, 10)).normalized() clock = pygame.time.Clock() done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True t = clock.get_time() / 1000 width, height = screen.get_size() if square.pos.x <= 0 or square.pos.x >= width - square.w: square.velocity = Vector(-square.velocity.x, square.velocity.y) if square.pos.y <= 0 or square.pos.y >= height - square.h: square.velocity = Vector(square.velocity.x, -square.velocity.y) square.update(t) screen.fill((0, 0, 0))
def test_mocking_class_methods(monkeypatch): monkeypatch.setattr('test_class_pytest.Square.calculate_area', lambda: 1) assert Square.calculate_area() == 1
def create_square(self, square_column, count, column): if count in [2, 5, 8]: self._square_matrix[count // 3][column] = Square(square_column, (count // 3, column)) return [] return square_column
def populate(): place = 0 global grid # fill grid with empty Squares for i in range(16): grid.append([]) for j in range(16): grid[i].append(Square(False, "b", pieces.Piece("none", "pawn"), i, j)) # alternate colors for i in range(8): if (i % 2 == 0): place = 0 for j in range(8): grid[i][place].pieceStatus = False grid[i][place].color = "white" grid[i][place].row = i grid[i][place].col = place grid[i][place + 1].pieceStatus = False grid[i][place + 1].color = "black" grid[i][place + 1].row = i grid[i][place + 1].col = (place + 1) place += 2 else: place = 0 for k in range(8): grid[i][place].pieceStatus = False grid[i][place].color = "black" grid[i][place].row = i grid[i][place].col = place grid[i][place + 1].pieceStatus = False grid[i][place + 1].color = "white" grid[i][place + 1].row = i grid[i][place + 1].col = (place + 1) place += 2 # Fill board with pieces # black plr = "b" Grid(0,0).piece = pieces.Rook(plr, "rook") Grid(0,1).piece = pieces.Knight(plr, "knight") Grid(0,2).piece = pieces.Bishop(plr, "bishop") Grid(0,3).piece = pieces.Queen(plr, "queen") Grid(0,4).piece = pieces.King(plr, "king") Grid(0,5).piece = pieces.Bishop(plr, "bishop") Grid(0,6).piece = pieces.Knight(plr, "knight") Grid(0,7).piece = pieces.Rook(plr, "rook") for i in range(8): Grid(1,i).piece = pieces.Pawn(plr, "pawn") Grid(1,i).piece.firstMove = True globVar.firstPawns.append(Grid(1,i).piece) # set pieceStatus and piece_ID for black pieces piece_ID = 0 for i in range(2): for j in range(8): Grid(i,j).pieceStatus = True Grid(i,j).piece.label = piece_ID piece_ID += 1 globVar.b_pieces.append(Grid(i,j).piece) # white plr = "W" Grid(7,0).piece = pieces.Rook(plr, "rook") Grid(7,1).piece = pieces.Knight(plr, "knight") Grid(7,2).piece = pieces.Bishop(plr, "bishop") Grid(7,3).piece = pieces.Queen(plr, "queen") Grid(7,4).piece = pieces.King(plr, "king") Grid(7,5).piece = pieces.Bishop(plr, "bishop") Grid(7,6).piece = pieces.Knight(plr, "knight") Grid(7,7).piece = pieces.Rook(plr, "rook") for i in range(8): Grid(6,i).piece = pieces.Pawn(plr, "pawn") Grid(6,i).piece.firstMove = True globVar.firstPawns.append(Grid(6,i).piece) # set pieceStatus and assign ID to white pieces place = 6 piece_ID = 0 for i in range(2): i = place for j in range(8): Grid(i,j).pieceStatus = True Grid(i,j).piece.label = piece_ID piece_ID += 1 globVar.w_pieces.append(Grid(i,j).piece) place += 1 # set pieceStatus to false for the rest place = 2 for i in range(4): i = place for j in range(8): Grid(i,j).pieceStatus = False # copy square coordinates to pieces for i in range(8): for j in range(8): if Grid(i,j).pieceStatus: Grid(i,j).piece.row = Grid(i,j).row Grid(i,j).piece.col = Grid(i,j).col # Clip board to 8 x 8 while len(grid) > 8: grid.pop() for i in range(8): while len(grid[i]) > 8: grid[i].pop() # initialize global variables resetGlobal()
def get_pseudo_legal_moves(self, source=None): """:yield: Pseudo legal moves in the current position. :param source: The source square to limit moves or None for all possible moves. """ tomove = self.fen._to_move for x88 in [ x88 for x88 in Square._x88_squares.keys() if self._pieces[x88] and Piece.color(self._pieces[x88]) == tomove and (source is None or x88 == source._x88)]: piece = self._pieces[x88] klass = Piece.klass(piece) # pawn moves if klass == PAWN: single, double, capleft, capright = X88.PAWN_OFFSETS[tomove] # Single square ahead. Do not capture. offset = x88 + single if not self._pieces[offset]: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # Two squares ahead. Do not capture. if X88.is_secondrank(x88, tomove): offset = x88 + double if not self._pieces[offset]: yield Move.from_x88(x88, offset) # Pawn captures. for cap in [capleft, capright]: offset = x88 + cap if offset & X88.X88: continue target = self._pieces[offset] if target and Piece.color(target) != tomove: # Promotion. if X88.is_backrank(offset, tomove): for promote_to in Piece.promote_to: yield Move.from_x88(x88, offset, promote_to) else: yield Move.from_x88(x88, offset) # En-passant. elif not target and offset == self.fen._ep: yield Move.from_x88(target, self.fen._ep) #piece moves else: # for each a direction a piece moves in for offset in X88.PIECE_OFFSETS[Piece.klass(piece)]: t_x88 = x88 + offset # while we do not fall off the board while not t_x88 & 0x88: # if there was not piece to attack then yield a quiet move if not self._pieces[t_x88]: yield Move.from_x88(x88, t_x88) # do not break out # else there is a piece there else: # if we can attack generate a move if Piece.color(self._pieces[t_x88]) != tomove: yield Move.from_x88(x88, t_x88) # we hit something so break out break # Knight and king do not go multiple times in their direction. if klass in [KNIGHT, KING]: break # travel down the board in the direction t_x88 += offset # castling moves opponent = Piece.opposite_color(tomove) ok = True # get possible castling for the side to move for castle in [c for c in self.fen._castle_rights if Piece.color(c) == tomove]: (square, enum), _ = Piece.castle_squares[castle] king = Square(square) if Piece.klass(castle) == KING: direc = 1 else: direc = -1 # for offset in the squares the king will travel for offset in range(0, 3): s = Square.from_x88(king._x88 + (offset * direc)) # if we are not the king square and we are occuppied if offset and self._pieces[s._x88]: ok = False break # if we are trying to travel through check if self.is_attacked(opponent, s): ok = False break # kludge: we have to check occupancy for one more square on the queen side if direc == -1 and self._pieces[s._x88 - 1]: ok = False if ok: yield Move(king, s)
from square import Square s = Square(7) s.set_center([0, 0]) s.set_color("Yellow") s.name = "Hally" print "Area of %s is %d" % (s.name, s.area()) s.print_s()
def move_in_direction(self, direction): """ core algorithm: loop over each row twice starting from side moved towards, first time deleting empty squares second time merging identical squares implemented for left/right movement. Up/down transposes the board, moves right (down) or left (up) and transposes back implementation pseudocode - iterate rows in grid - iterate squares in row starting from side the row is moved towards - if the square is empty, delete it and append empty square at end - repeat on same square until not either empty anymore (move to next square) or row empty (move to next row) - iterate squares in row second time - if the next square is the same, merge them, delete the next square and append empty square - if the next square is non-empty non-identical, move to next square in iteration check if a move was made by comparing new board to old deepcopy of board (flatten grid and store square values in list) """ #stores a deepcopy of the board to check if any square moved later old_square_values_flattened = [ square.value for row in copy.deepcopy(self.squares) for square in row ] #case switch the direction parameter if direction == "left": #iterate rows y = 0 for x_row in self.squares: #iterate squares in row first time deleting empty squares x = 0 for sq_obj in x_row: """ if square is empty delete the list entry, append zero and repeat until not empty break if all following squares are empty NOTE: needs to use x_row[x] instead of sq_obj because iterating and modifying list at the same time """ while x_row[x].value == 0 and x <= 2: #move to next row if all others also empty rest_of_row_empty = True for n in range(x + 1, 4): if not self.get_square((n, y)).value == 0: rest_of_row_empty = False if rest_of_row_empty: break #delete current empty square and add new empty square to end of row del (self.squares[y][x]) self.squares[y].append(Square(0, (x, y))) x += 1 #repeat the loop over x-row after deleting empty x = 0 for sq_obj in x_row: #if next square is the same, double it, delete the next and add empty square to end of row if x <= 2 and x_row[x].value == x_row[x + 1].value: self.squares[y][x].value *= 2 self.squares[y][x].was_doubled = True del (self.squares[y][x + 1]) self.squares[y].append(Square(0, (x, y))) self.score += self.squares[y][x].value x += 1 y += 1 elif direction == "up": #transpose, move left, transpose back self.squares = list(map(list, zip(*self.squares))) self.move_in_direction("left") self.squares = list(map(list, zip(*self.squares))) elif direction == "right": #iterate rows y = 0 for x_row in self.squares: #loop over squares in row from right to left x = 3 for sq_obj in x_row[::-1]: """ if square is empty delete the list entry, append zero and repeat until not empty break if all following squares are empty NOTE: needs to use x_row[x] instead of sq_obj because iterating and modifying list at the same time """ while x_row[x].value == 0 and x >= 1: #move to next row if all others also empty rest_of_row_empty = True for n in range(0, x)[::-1]: if not self.get_square((n, y)).value == 0: rest_of_row_empty = False if rest_of_row_empty: break #delete current empty square and add new empty square to beginning of row del (self.squares[y][x]) self.squares[y].insert(0, Square(0, (x, y))) x -= 1 #repeat the loop over x-row after deleting empty x = 3 for sq_obj in x_row[::-1]: #if next square is the same, double it, delete the next and add empty square to beginning of row if x >= 1 and x_row[x].value == x_row[x - 1].value: self.squares[y][x].value *= 2 self.squares[y][x].was_doubled = True del (self.squares[y][x - 1]) self.squares[y].insert(0, Square(0, (x, y))) self.score += self.squares[y][x].value x -= 1 y += 1 elif direction == "down": #transpose, move left, transpose back self.squares = list(map(list, zip(*self.squares))) self.move_in_direction("right") self.squares = list(map(list, zip(*self.squares))) #compares the old deepcopy values with the current board and returns true if a square has moved, false if not square_moved = False new_square_values_flattened = [ square.value for row in self.squares for square in row ] if old_square_values_flattened != new_square_values_flattened: square_moved = True return square_moved
def test_mocking_class_methods(self, mocked_method): mocked_method.return_value = 20 self.assertEquals(Square.calculate_area(), 20)
def test_mocking_instance(self, mocked_instance): mocked_instance = mocked_instance.return_value mocked_instance.calculate_area.return_value = 1 sq = Square(100) self.assertEquals(sq.calculate_area(), 1)
def source(self): """The source square.""" return Square.from_x88(self._source_x88)
def setUp(self) -> None: self.s1 = Square(6, 3, 3, 3, 3, 0, 6, 0) self.s2 = Square(6, 3, 3, 3, 3, 0, 6, 0) self.s3 = Square(7, 4, 4, 4, 4, 1, 7, 1) self.s4 = Square(-3.5, -3.5, -1.5, -3.5, -1.5, -1.5, -3.5, -1.5) self.s5 = Square(3.5, 3.5, 1.5, 3.5, 1.5, 1.5, 3.5, 1.5)
def target(self): """The target square.""" return Square.from_x88(self._target_x88)
def __init__(self): Square.__init__(self, "corridor", " ", "") self.canPass = True
col2.append[float(i[1])] col3.append[float(i[2])] col4.append[float(i[3])] except: pass min1= np.min(col1) min2= np.min(col2) min3= np.min(col3) min4= np.min(col4) max1= np.max(col1) max2= np.max(col2) max3= np.max(col3) max4= np.max(col4) for line in data: if __name__== '__main__': print("Hello main method") my_square = Square() my_square.setSize(6) print("square surface: " + str(my_square.getSurface())) load_csv()