Exemplo n.º 1
0
    def __createBoard(self, round):
        if round == 1:
            board = Board(self.__round1Categories, round)
        else:
            board = Board(self.__round2Categories, round)

        return board
Exemplo n.º 2
0
    def __init__(self,
                 print_board_after_move=False,
                 print_move_result=False,
                 always_persist_board_state=True,
                 show_recent_moves=False):
        """
        Instantiates the game of chess. Pass parameters as needed to suit your liking

        :param print_board_after_move: False by default
        :param print_move_result: False by default
        :param always_persist_board_state: True by default
        :param show_recent_moves: False by default
        """
        self.visualiser = Visualiser()
        self.board = Board()
        self.__game_logger = GameLogger()
        self.__game_history = GameHistory()

        # Game options. Refer to variable names for the acronym meanings
        self.__pbam = print_board_after_move
        self.__pmr = print_move_result
        self.__apbs = always_persist_board_state
        self.__srm = show_recent_moves

        # Persist initial state
        if self.__apbs:
            self.persist_state_to_file()
Exemplo n.º 3
0
    def __init__(self):
        self.player1 = Player(1)
        self.player2 = Player(2)

        self.board = Board(self.player1, self.player2)

        self.players = [self.player1, self.player2]
        self.setup()

        self.focus = 0

        self.__loop()
Exemplo n.º 4
0
def play(board=None):
    if not board:
        board = Board()

    curr_player = "black" if board.LASTPLAYERCOLOR == "white" else "white"
    running = True

    while running:

        while True:
            system("clear")
            print(board)

            if board.CHECKMATE:
                print(
                    f"It's checkmate! {board.LASTPLAYERCOLOR.capitalize()} has won!"
                )
                running = False
                break
            elif board.STALEMATE:
                print(f"It's stalemate! The game is a draw.")
                running = False
                break

            move = input(f"{curr_player.capitalize()} to move: ")
            try:
                move = move.split(" ")
                l = len(move)
                if l not in (2, 3):
                    raise InvalidSquareException

                if l == 2:
                    result = board.makeMove(move[0], move[1], curr_player)
                else:
                    result = board.makeMove(move[0],
                                            move[1],
                                            curr_player,
                                            promotionTo=move[2])

                if not result:
                    print("Invalid move!")
                    sleep(2)
                    continue

                break

            except InvalidSquareException:
                print("Invalid input!")
                sleep(2)

        curr_player = "black" if curr_player == "white" else "white"
Exemplo n.º 5
0
    def print(self, board: Board):
        """
        Print the entire battlefield

        :param board: The current board in play
        :return: void
        """
        # Render first horizontal alphabetical x-axis markers
        row = ["  "]

        for x_marker in self.coordinate_map:
            row.append(" " + x_marker)

        print("".join(row))

        # Render the rest of the cheese board
        for y, y_row in enumerate(self.map):
            # Render left side row numbers
            row = [str((8 - y)) + " "]

            # Render battlefield
            for x, square in enumerate(y_row):
                # Check with Board if there is a piece on this coordinate
                anybody = board.who_is_in(*[x, y])

                # Anybody out there?
                if anybody is not None:
                    # Oh hai
                    row.append(anybody.name)
                else:
                    # Print a simple dot
                    row.append(" .")

            # Print the entire row
            print("".join(row))
Exemplo n.º 6
0
def singlePieceChecks():
    board = Board()
    print(board)

    bra = [[False] * 8 for _ in range(8)]
    bra[3][3] = True

    print(board.board_arr[3][3].attacks(bra))
Exemplo n.º 7
0
 def __init__(self):
     pygame.init()  # Initialize PyGame library.
     self.config = cp.ConfigParser()  # Init the config parser.
     self.config.read('config.ini')  # Open the config file.
     pygame.display.set_caption(
         "Conway's Game of Life")  # Set window title.
     pygame.display.set_icon(
         pygame.image.load(
             "./assets/img/window_icon.png"))  # Set window icon.
     pygame.mouse.set_cursor(*pygame.cursors.diamond)  # Set mouse cursor.
     self.window = Window(self.config)  # Init window.
     self.screen_surface = pygame.display.set_mode(
         (self.window.width, self.window.height))  # Init the main surface.
     self.background = Surface("./assets/img/background.jpg",
                               (0, 0))  # Init the background surface.
     # self.play_button = Surface("./assets/img/play-button.png", (50, self.window))  # Init the play button surface.
     self.board = Board(self.window,
                        self.config)  # Main structure of the game.
Exemplo n.º 8
0
def automove(DEBUG=True, playAfter=False):
    sleepTime = .2
    board = Board()

    #BUG GAME
    moves = [
        ("c2", "c4", "white"),
        ("a7", "a6", "black"),
        ("c4", "c5", "white"),
        ("a6", "a5", "black"),
        ("c5", "C6", "white"),
        ("a5", "a4", "black"),
        ("c6", "d7", "white"),
        ("d8", "d7", "black"),
        ("d2", "d4", "white"),
        ("d7", "d8", "black"),
        ("d4", "d5", "white"),
        ("a4", "a3", "black"),
        ("d5", "d6", "white"),
        ("b7", "b6", "black"),
        ("d6", "e7", "white"),
        ("b6", "b5", "black"),
    ]

    if not DEBUG:
        system("clear")
    print(board)
    sleep(sleepTime)

    for move in moves:
        if not DEBUG:
            system("clear")
        board.makeMove(*move)
        print(board)
        sleep(sleepTime)

    if playAfter:
        play(board)
Exemplo n.º 9
0
def run():
    """Run the game"""
    while True:
        player_symbol = input("Choose your symbol: X/O ?")
        if player_symbol == "O" or player_symbol == "X":
            print("Let's start!!")
            print("=" * 20)
            break
        print("Oops! Wrong input!! Try again")
    if player_symbol == "X":
        bot_symbol = "O"
    else:
        bot_symbol = "X"
    print(_introduction())
    user = User(player_symbol)
    bot = Bot(bot_symbol)
    global BOT_SYMBOL
    BOT_SYMBOL = bot_symbol
    players = [user, bot]
    board = Board()
    print(_get_game_result(_play_game(players, board), players))
Exemplo n.º 10
0
 def __init__(self):
     self.game_board = Board()
Exemplo n.º 11
0
class Game:
    def __init__(self):
        pygame.init()  # Initialize PyGame library.
        self.config = cp.ConfigParser()  # Init the config parser.
        self.config.read('config.ini')  # Open the config file.
        pygame.display.set_caption(
            "Conway's Game of Life")  # Set window title.
        pygame.display.set_icon(
            pygame.image.load(
                "./assets/img/window_icon.png"))  # Set window icon.
        pygame.mouse.set_cursor(*pygame.cursors.diamond)  # Set mouse cursor.
        self.window = Window(self.config)  # Init window.
        self.screen_surface = pygame.display.set_mode(
            (self.window.width, self.window.height))  # Init the main surface.
        self.background = Surface("./assets/img/background.jpg",
                                  (0, 0))  # Init the background surface.
        # self.play_button = Surface("./assets/img/play-button.png", (50, self.window))  # Init the play button surface.
        self.board = Board(self.window,
                           self.config)  # Main structure of the game.

    def draw_background(self):
        self.screen_surface.blit(self.background.image, self.background.rect)

    def draw_board(self):
        half_padding = self.board.matrix_padding // 2
        for x in range(0, self.board.width):
            for y in range(0, self.board.height):
                # Get the current cell.
                cell = self.board.structure[y + half_padding][x + half_padding]

                # Pick the color corresponding to the cell state.
                color = Color.LIGHT_GREY if cell.state is Cell.DEAD else Color.BLACK

                # Draw the current cell.
                cell_size = Cell.SIZE + self.board.zoom
                pygame.draw.rect(self.board.surface, Color.WHITE,
                                 (x * cell_size, y * cell_size, cell_size + 2,
                                  cell_size + 2))
                rect = pygame.draw.rect(
                    self.board.surface, color,
                    ((x * cell_size) + 1,
                     (y * cell_size) + 1, cell_size, cell_size))

                # Store the 2D coordinates of the cell on the surface.
                self.board.structure[y +
                                     half_padding][x +
                                                   half_padding].rect = rect
        # Blit the board surface on the screen surface.
        self.screen_surface.blit(
            self.board.surface,
            ((self.window.width -
              (self.board.width * Cell.SIZE)) >> 1, self.board.h_padding))

    def clear_board(self):
        """
        Clear the board by killing every living cells.
        """
        for y in self.board.structure:
            for x in y:
                x.state = Cell.DEAD

    def process_cell_action(self, click_pos):
        """
        Process the user action on a cell.

        :param click_pos:
        :return:
        """
        for row in self.board.structure:
            for cell in row:
                if cell.rect is not None:
                    if cell.rect.left <= click_pos[0] - self.board.w_padding <= cell.rect.right and \
                            cell.rect.top <= click_pos[1] - self.board.h_padding <= cell.rect.bottom:
                        cell.swap_state()
                        return

    def calculates_cell_next_states(self):
        """
        Calculates and saves the next cell states.
        """
        for y, row in enumerate(self.board.structure):
            for x, cell in enumerate(row):
                neighbors = self.neighbors_counter(x, y)
                if neighbors is 3 and cell.state is Cell.DEAD:
                    cell.save_next_state(Cell.ALIVE)
                if neighbors < 2 or neighbors > 3 and cell.state is Cell.ALIVE:
                    cell.save_next_state(Cell.DEAD)

    def apply_cell_next_states(self):
        for row in self.board.structure:
            for cell in row:
                cell.apply_next_state()

    def neighbors_counter(self, pos_x, pos_y) -> int:
        neighbors = 0
        y_max = self.board.height + self.board.matrix_padding - 1
        x_max = self.board.width + self.board.matrix_padding - 1

        # LEFT
        if pos_x > 0 and self.board.structure[pos_y][pos_x -
                                                     1].state is Cell.ALIVE:
            neighbors += 1
        # RIGHT
        if pos_x < x_max and self.board.structure[pos_y][
                pos_x + 1].state is Cell.ALIVE:
            neighbors += 1
        # UP
        if pos_y > 0 and self.board.structure[pos_y -
                                              1][pos_x].state is Cell.ALIVE:
            neighbors += 1
        # DOWN
        if pos_y < y_max and self.board.structure[
                pos_y + 1][pos_x].state is Cell.ALIVE:
            neighbors += 1
        # UP LEFT
        if (pos_x > 0 and pos_y > 0) and self.board.structure[pos_y - 1][
                pos_x - 1].state is Cell.ALIVE:
            neighbors += 1
        # UP RIGHT
        if (pos_x < x_max and pos_y > 0) and self.board.structure[pos_y - 1][
                pos_x + 1].state is Cell.ALIVE:
            neighbors += 1
        # DOWN LEFT
        if (pos_x > 0 and pos_y < y_max) and self.board.structure[pos_y + 1][
                pos_x - 1].state is Cell.ALIVE:
            neighbors += 1
        # DOWN RIGHT
        if (pos_x < x_max and pos_y < y_max) and self.board.structure[
                pos_y + 1][pos_x + 1].state is Cell.ALIVE:
            neighbors += 1
        return neighbors

    def refresh_board(self):
        self.draw_board()
        pygame.display.flip()
        print("Zoom: {}".format(self.board.zoom))

    # def draw_buttons(self):
    #     self.screen_surface.blit(self.play_button.image, self.play_button.rect)

    def run(self):
        pygame.transform.rotate(self.board.surface, 40)
        self.draw_background()
        self.draw_board()
        # self.draw_buttons()
        pygame.display.update()
        idle_mode = True
        while True:
            for event in pygame.event.get():
                if event.type is pygame.QUIT:
                    sys.exit()

                elif event.type is pygame.MOUSEBUTTONUP:
                    if event.button is 1:  # LEFT MOUSE CLICK
                        self.process_cell_action(event.pos)
                        self.refresh_board()
                    elif event.button is 4:  # MOUSE WHEEL UP
                        self.board.zoom_in()
                        self.refresh_board()
                    elif event.button is 5:  # MOUSE WHEEL DOWN
                        self.board.zoom_out()
                        self.refresh_board()

                elif event.type is pygame.KEYUP and event.key is pygame.K_DELETE:  # DEL BUTTON
                    self.clear_board()
                    self.refresh_board()
                    idle_mode = True

                elif event.type is pygame.KEYUP and event.key is pygame.K_SPACE:  # SPACE BUTTON
                    idle_mode = True if idle_mode is False else False

            if idle_mode is False:
                self.calculates_cell_next_states()
                self.apply_cell_next_states()
                self.refresh_board()
Exemplo n.º 12
0
class Game:
    __white_turn = True
    __dimensions = 8
    __castling_moves = ["O-O", "O-O-O"]

    def __init__(self,
                 print_board_after_move=False,
                 print_move_result=False,
                 always_persist_board_state=True,
                 show_recent_moves=False):
        """
        Instantiates the game of chess. Pass parameters as needed to suit your liking

        :param print_board_after_move: False by default
        :param print_move_result: False by default
        :param always_persist_board_state: True by default
        :param show_recent_moves: False by default
        """
        self.visualiser = Visualiser()
        self.board = Board()
        self.__game_logger = GameLogger()
        self.__game_history = GameHistory()

        # Game options. Refer to variable names for the acronym meanings
        self.__pbam = print_board_after_move
        self.__pmr = print_move_result
        self.__apbs = always_persist_board_state
        self.__srm = show_recent_moves

        # Persist initial state
        if self.__apbs:
            self.persist_state_to_file()

    def visualise(self):
        """
        Visualise the board in console. No budget for a 3D cheeseboard here, a charcuterie might be cheaper

        :return: void
        """
        self.visualiser.print(self.board)

    def persist_state_to_file(self):
        self.__game_logger.state_to_file(self.board)

    def persist_move_to_file(self, origin, destination=None):
        self.__game_logger.action_to_file(origin, destination)

    def move(self, origin, destination=None):
        """
        Move the piece if it is valid

        :param origin:
        :param destination:
        :return: the result of the move
        """

        result = None

        # Filter out non-standard moves except castling
        if destination is None and origin not in self.__castling_moves:
            return MoveStatus.ERR_UNRECOGNISED

        if origin in self.__castling_moves:
            king_side = True if origin == "O-O" else False

            if self.__apbs:
                # Get our pieces for later use before they move
                origin_piece = self.get_castling_piece()
                destination_piece = self.get_castling_piece(king_side, False)
            """ Run castling move"""
            castle_result = self.board.castle(self.__white_turn, king_side)

            if castle_result is MoveStatus.OK_CASTLED:
                # Invert current turn if move was successful
                self.__white_turn = not self.__white_turn

            result = castle_result
        else:
            # Convert atlas coordinates to cartesian coordinates
            cartesian_origin = self.atlas_to_cartesian_coordinates(origin)
            origin_piece = self.board.who_is_in(*cartesian_origin)
            cartesian_destination = self.atlas_to_cartesian_coordinates(
                destination)
            destination_piece = self.board.who_is_in(*cartesian_destination)
            """ Run normal actions """
            move = self.board.move(*cartesian_origin, *cartesian_destination,
                                   self.__white_turn)

            if move.value > 0:
                # Invert current turn if move was successful
                self.__white_turn = not self.__white_turn

            result = move

        if result.value > 0:
            """ Run needed subroutines if we have a successful move """
            separator = "-" if result is not MoveStatus.OK_KILL else "x"

            final_destination = separator + destination if destination is not None else ""

            # Print a shoddy chessboard as needed
            if self.__pbam:
                self.visualise()

            # Log and print this movement
            if self.__srm:
                self.__game_history.log(not self.__white_turn, origin,
                                        destination)
                self.print_recent_moves()

            # Persist file if set
            if self.__apbs:
                self.persist_move_to_file(origin_piece, destination_piece)

        # Print move result irregardless if successful or not
        if self.__pmr:
            print(result)

        # Give a nice separator if some game settings are up
        if self.__pbam or self.__pmr or self.__srm:
            print(("=" * 100) + "\n\n\n")

        return result

    def get_castling_piece(self, king_side=True, king=True):
        """
        Function to return the pieces involved when castling.

        :param king_side: Determines which matching rook to get. Has no effect if king is true
        :param king: Always returns the king unless specified
        :return: Piece either Rook or King. May return None if no piece is in position
        """
        x = 4
        y = 7 if self.__white_turn else 0

        if not king:
            """ Looking for our rook """
            x = 7 if king_side == "O-O" else 0

        return self.board.who_is_in(*[x, y])

    def print_recent_moves(self):
        """
        Print recent moves by both players in a horizontal fashion

        :return:
        """
        print('.' * 100)
        self.__game_history.nice_print_history()
        print('.' * 100)

    def atlas_to_cartesian_coordinates(self, cell):
        """
        Convert atlas grid coordinate to cartesian coordinates

        :param cell: Cell coordinates to translate
        :return: List consisting of x and y coordinates
        """
        cell = list(cell)

        cell[0] = self.translate_a(cell[0])  # X
        cell[1] = abs(int(cell[1]) - self.__dimensions)  # Y

        return cell

    def translate_a(self, letter):
        """
        Translate a(tlas) coordinate alphabet to its zero-indexed numeric value
        :param letter: letter to translate
        :return: integer
        """
        return self.visualiser.coordinate_map.index(letter.lower())
Exemplo n.º 13
0
import time

from classes.Board import Board


if __name__ == '__main__':
    # state = Board([5, 1, 3, 4, 2, 0, 7, 8, 10, 6, 11, 12, 9, 13, 14, 15], 4)
    # state = Board([1, 6, 2, 5, 7, 3, 0, 4, 8], 3)
    # state = Board([1, 3, 6, 5, 2, 0, 4, 7, 8], 3)
    state = Board([5, 0, 2, 1, 4, 3, 6, 7, 8], 3)
    potential_states = [state]
    visited_states = []
    max_depth = 2

    start = time.time()

    # while not state == Board([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0], 4):
    while state.board != state.goal:
        state = potential_states.pop(0)

        if state in visited_states:
            continue

        if state.empty_space() < state.size * (state.size - 1):
            new_state = state.move("UP")
            inserted = False
            for i in range(len(potential_states)):
                if new_state.h1_and_h2 < potential_states[i].h1_and_h2:
                    potential_states.insert(i, new_state)
                    inserted = True
                    break
Exemplo n.º 14
0
        return True, 0

    has_same_neighbour = False
    for y in surrounding_y:
        if my_board.positions[y].type == my_board.positions[curr_black].type:
            has_same_neighbour = True

    if not has_same_neighbour:
        return True, -1

    return False


game_over = False

my_board = Board()

my_board.print_board()

while my_board.pieces["@"]:
    my_board.make_solution_space("@")
    curr_black = my_board.pieces["@"][0]
    enemies = my_board.positions[curr_black].find_closest_enemies(
        my_board.pieces)
    surrounding_x = my_board.positions[curr_black].valid_x(
        curr_black, my_board.positions)
    surrounding_y = my_board.positions[curr_black].valid_y(
        curr_black, my_board.positions)

    if check_surrounding_same_type(curr_black)[0]:
        solution_index = check_surrounding_same_type(curr_black)[1]
Exemplo n.º 15
0
# and also mutate

players = [Player(NN.randWeights(), 0.5) for _ in range(100)]
games = []


def comp(x):
    return x.score


for _ in range(200):
    print(_)
    random.shuffle(players)

    games = [
        Board(players[2 * i], players[2 * i + 1])
        for i in range(len(players) // 2)
    ]
    winners = []

    for i in range(len(players) // 2):
        winners.append(games[i].play())

    maxscore = 0

    for i in range(len(players) // 2):
        if winners[i] == -1:
            continue

        # print(winners[i])
        maxscore = max(winners[i].score, maxscore)
Exemplo n.º 16
0
class Game:
    def __init__(self):
        self.player1 = Player(1)
        self.player2 = Player(2)

        self.board = Board(self.player1, self.player2)

        self.players = [self.player1, self.player2]
        self.setup()

        self.focus = 0

        self.__loop()

    def setup(self):

        for i in range(8):
            piece = Pawn([i, 1], "white", self.board)
            self.player1.add_piece(piece)

        for i in range(8):
            piece = Pawn([i, 6], "black", self.board)
            self.player2.add_piece(piece)

        piece = Bishop([2, 0], "white", self.board)
        self.player1.add_piece(piece)
        piece = Bishop([5, 0], "white", self.board)
        self.player1.add_piece(piece)

        piece = Bishop([2, 7], "black", self.board)
        self.player2.add_piece(piece)
        piece = Bishop([5, 7], "black", self.board)
        self.player2.add_piece(piece)

        piece = Rook([0, 0], "white", self.board)
        self.player1.add_piece(piece)
        piece = Rook([7, 0], "white", self.board)
        self.player1.add_piece(piece)

        piece = Rook([0, 7], "black", self.board)
        self.player2.add_piece(piece)
        piece = Rook([7, 7], "black", self.board)
        self.player2.add_piece(piece)

        piece = Knight([1, 0], "white", self.board)
        self.player1.add_piece(piece)
        piece = Knight([6, 0], "white", self.board)
        self.player1.add_piece(piece)

        piece = Knight([1, 7], "black", self.board)
        self.player2.add_piece(piece)
        piece = Knight([6, 7], "black", self.board)
        self.player2.add_piece(piece)

        piece = King([4, 0], "white", self.board)
        self.player1.add_piece(piece)
        self.player1.set_king_piece(piece)
        piece = King([4, 7], "black", self.board)
        self.player2.add_piece(piece)
        self.player2.set_king_piece(piece)

        piece = Queen([3, 0], "white", self.board)
        self.player1.add_piece(piece)
        piece = Queen([3, 7], "black", self.board)
        self.player2.add_piece(piece)

        pass

    def __int_input(self, message, min=0, max=7):
        while True:
            var = input(message)
            try:
                var = int(var)
                if (var >= min and var <= max):
                    break
                else:
                    print("invalid range")
                    continue
            except:
                print("that input was invalid")
        return var

    def take_move_input(self, player):
        player.print_pieces()

        while True:
            inpt = self.__int_input(
                "What piece would you like to move? (Give the corresponding index)",
                max=len(player.pieces) - 1)

            piece = player.pieces[inpt]

            possible_positions = self.board.filter(piece.possible_positions())

            if not possible_positions:
                print("No possible positions :( choose a different piece")
                continue

            print("\n")
            for i, p in enumerate(possible_positions):
                print("%d : (%d,%d)" %
                      (i, possible_positions[i][0], possible_positions[i][1]))

            coord_index = self.__int_input(
                "Pick one of these possible positions your piece can move to.",
                max=len(possible_positions) - 1)

            piece.moveTo(possible_positions[coord_index])

            player.update_turns(piece)

            break

    def checkmate_check(self, player):
        other_player = self.player2 if player.num == 1 else self.player1
        ret = self.board.check_checkmate(player.king_piece,
                                         other_player.pieces)
        if ret:
            print("%s king is in checkmate %s player has won" %
                  (player.color, other_player.color))
            time.sleep(100)

    #The game loop
    def __loop(self):
        while True:
            print("It is player %d's turn\n" % (self.focus + 1))
            player = self.players[self.focus]

            self.board.print()
            self.take_move_input(player)

            time.sleep(1)
            os.system("clear")
            if self.focus == 0:
                self.focus = 1
            else:
                self.focus = 0
Exemplo n.º 17
0
class Engine:

    # Game types
    MASSACRE_TYPE = "Massacre"
    MOVES_TYPE = "Moves"

    # Board object
    game_board = Board

    # Engine initialiser
    def __init__(self):
        self.game_board = Board()

    # Begins the game, and determines the game type
    def start(self):
        if self.game_board.type == self.MASSACRE_TYPE:
            # Run a massacre of the black pieces
            self.massacre(Piece.BLACK)

        if self.game_board.type == self.MOVES_TYPE:
            # Count and print all possible moves
            self.count_moves(self.game_board.positions)

    # Counts and prints the number of possible moves that the white and black
    # pieces can make. Whites are displayed first, then blacks are displayed
    def count_moves(self, positions):
        white_count = 0
        black_count = 0

        # Iterate over all positions on the board, and counts all the possible
        # moves that can be made
        for xy in positions.keys():
            moves = positions[xy].get_moves(xy, positions)
            if positions[xy].type == Piece.WHITE:
                white_count += len(moves[0]) + len(moves[1])
            if positions[xy].type == Piece.BLACK:
                black_count += len(moves[0]) + len(moves[1])

        # Print the possible move counts
        print(white_count)
        print(black_count)

    # Eliminates all the pieces of type "kill_type". Prints all of the moves
    # made.
    def massacre(self, kill_type):

        # Continues while there are still "kill_type" pieces on the board
        while self.game_board.pieces[kill_type]:

            # Make a solution space, select the current piece, and the
            # surrounding pieces on the x and y axes
            self.game_board.make_solution_space(kill_type)
            curr_p = self.game_board.pieces[kill_type][-1]
            enemies = self.game_board.positions[curr_p].find_closest_enemies\
                (self.game_board.pieces)
            surround_x = self.game_board.positions[curr_p].valid_xy\
                (curr_p, self.game_board.positions, Piece.X_AXIS)
            surround_y = self.game_board.positions[curr_p].valid_xy\
                (curr_p, self.game_board.positions, Piece.Y_AXIS)

            # Calculates which of the possible solutions to the current
            # "kill_type" piece are the easiest to reach, then moves the
            # playing pieces there.
            solution_index = 0
            if self.check_surrounding_same_type(curr_p, surround_x,
                                                surround_y)[0]:

                solution_index = self.check_surrounding_same_type\
                (curr_p, surround_x, surround_y)[1]

                if solution_index == 0:
                    x_manhat = 0
                    for enemy in enemies:
                        for sol in self.game_board.black_sol_space[curr_p][0]:
                            x_manhat += Piece.manhattan_dist(enemy, sol)

                    y_manhat = 0
                    for enemy in enemies:
                        for sol in self.game_board.black_sol_space[curr_p][-1]:
                            y_manhat += Piece.manhattan_dist(enemy, sol)

                    # Pick based on total manhattan distance values
                    if y_manhat > x_manhat:
                        solution_index = 0
                    else:
                        solution_index = -1

            else:
                self.game_board.pieces[Piece.BLACK].append\
                    (self.game_board.pieces[Piece.BLACK].pop())

            self.game_board.move_in_order(
                enemies,
                self.game_board.black_sol_space[curr_p][solution_index])

            self.game_board.update(Piece.BLACK)

    # Checks if a piece's surrounding spaces are occupied by a piece of the
    # same type. This allows for faster selection of which solution to go
    # for, since, for example, two adjacent black pieces on the x axis can
    # be immediately ruled out for a solution space on the x axis.
    def check_surrounding_same_type(self, curr_p, surround_x, surround_y):
        has_same_neighbour = False

        # Returns True if there is a same neighbour, and the index of the
        # solution space to be used
        for x in surround_x:
            if self.game_board.positions[x].type == \
                    self.game_board.positions[curr_p].type:

                has_same_neighbour = True

        if not has_same_neighbour:
            return True, 0

        has_same_neighbour = False
        for y in surround_y:
            if self.game_board.positions[y].type == \
                    self.game_board.positions[curr_p].type:
                has_same_neighbour = True

        if not has_same_neighbour:
            return True, -1

        return False, None
Exemplo n.º 18
0
from classes.App import App
from classes.Board import Board

app = App(title="TetrisPy")

board = Board()

app.run()