Esempio n. 1
0
 def __init__(self):
     self.fps_clock = pygame.time.Clock()
     self.display = pygame.display
     self.font = pygame.font.Font('freesansbold.ttf', 15)
     self.difficulty = self.select_difficulty_menu()
     self.board_state = BoardState(self.difficulty[0], self.difficulty[1], self.difficulty[2])
     self.loop()
Esempio n. 2
0
    def convert_pos_to_canvas(self, pos):
        pos_x, pos_y = pos
        net_width = self._master.winfo_screenwidth() - (BoardState.get_cols() - 1) * BORDER_BETWEEN_TILES_PXL
        tile_width = net_width // BoardState.get_cols()
        x_start = (tile_width + BORDER_BETWEEN_TILES_PXL) * pos_x
        x_end = x_start + tile_width

        net_height = self._master.winfo_screenheight() - (BoardState.get_rows() - 1) * BORDER_BETWEEN_TILES_PXL
        tile_height = net_height // BoardState.get_rows()
        y_start = (tile_height + BORDER_BETWEEN_TILES_PXL) * pos_y
        y_end = y_start + tile_height

        return x_start, y_start, x_end, y_end
Esempio n. 3
0
    def parse_next_game(self):
        """
        IT'S A DOCSTRING NOW
        """
        game = chess.pgn.read_game(self.pgn)
        if game is None:
            raise ValueError("End of file")
        board = game.board()

        if len(list(game.main_line())) <= 1:
            return None

        stop = randint(1, len(list(game.main_line())))
        node = game
        while stop != 0:
            stop -= 1
            next_node = node.variations[0]

            if next_node.comment.find("eval") == -1:
                return None
            board.push(next_node.move)
            node = next_node

        state_evaluation = float(
            node.comment.split(']')[0].replace('[%eval ', '').replace("#", ""))

        return BoardState(board, state_evaluation)
Esempio n. 4
0
def _h_get_path_len_for_rect(rect, start_pos, end_pos):
    # print("starting get_path_len_for_rect()")
    visited = set()
    bnd_x, bnd_y = len(rect[0])-1, len(rect)-1
    to_check = [(start_pos, 0)]
    for position, travel_time in to_check:
        # print("position: {}, travel_time: {}".format(position, travel_time))
        if position in visited:
            # print("visited position {}".format(position))
            continue
        if position == end_pos:
            # print("returning {}\n\n".format(travel_time))
            return travel_time
        x, y = position
        if not (0 <= x <= bnd_x and 0 <= y <= bnd_y) or rect[y][x] > 0:  # illegal positions to go through
            # print("bad position {}".format(position))
            continue
        visited.add(position)
        for move in BoardState.ALL_MOVES:
            new_pos = BoardState.add_positions(position, move)
            # print("new_pos: {}".format(new_pos))
            to_check.append((new_pos, travel_time+1))
    # reached here? no path was found
    # print("returning 0\n\n")
    return 0
Esempio n. 5
0
def iterative_dfs(board: [[]]):
    """
    """
    # Initializing boardstate
    # Checking size
    size = len(board)
    for i in range(size):
        if len(board[i]) != size:
            raise Exception("Board matrix is not a square")
    # Creating BoardState from a matrix
    root_board = BoardState(board)
    root_board.generate_islands()
    root_board.evaluate()

    # IDFS Algorithm
    global visited
    visited = 0
    depth = 0
    final_node = None
    while final_node == None:
        depth += 1
        final_node, final_tree = dfs(root_board, depth)
    return final_node, depth, final_tree, visited
Esempio n. 6
0
class Game:
    DIFFICULTY_EASY = [5, 5, 5]
    DIFFICULTY_MEDIUM = [10, 10, 25]
    DIFFICULTY_HARD = [15, 15, 45]
    DIFFICULTY_DEFAULT = DIFFICULTY_MEDIUM

    BLACK = (38, 50, 56)
    WHITE = (245, 245, 245)
    RED = (255, 205, 210)
    BLUE_GRAY = (84, 110, 122)
    BURGUNDY = (106, 27, 154)
    GREEN = (46, 125, 50)
    ORANGE = (245, 124, 0)

    BACKGROUND_COLOR = BLUE_GRAY
    CLOSED_FIELD = BLACK
    OPEN_FIELD = WHITE
    OPEN_FIELD_WITH_VALUE = RED
    MINE_FIELD_BACKGROUND_COLOR = BURGUNDY

    FIELD_SIZE = 30
    GAP_SIZE = 4
    PANEL_HEIGHT = 45

    def __init__(self):
        self.fps_clock = pygame.time.Clock()
        self.display = pygame.display
        self.font = pygame.font.Font('freesansbold.ttf', 15)
        self.difficulty = self.select_difficulty_menu()
        self.board_state = BoardState(self.difficulty[0], self.difficulty[1], self.difficulty[2])
        self.loop()

    def loop(self):
        board = self.board_state.board
        self.display = pygame.display.set_mode(
            (board.width * (self.FIELD_SIZE + self.GAP_SIZE) + self.GAP_SIZE,
             board.height * (self.FIELD_SIZE + self.GAP_SIZE) + self.GAP_SIZE + self.PANEL_HEIGHT))
        pygame.display.set_caption("Minesweeper")
        while True:
            button = None
            mouse_clicked = False

            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                    self.exit_game()
                elif event.type == MOUSEBUTTONUP:
                    button = event.button
                    mouse_x, mouse_y = event.pos
                    mouse_clicked = True

            if mouse_clicked:
                x, y = self.get_selected_mine_field(mouse_x, mouse_y)
                if (x, y) != (None, None):
                    if button == 1:
                        self.board_state.touch_cell(y, x)
                    elif button == 3:
                        self.board_state.mark_cell(y, x)

            self.board_state.check_won()
            self.draw_board(board)

            if self.board_state.game_state == BoardState.GAME_STATE_WON:
                message = "You won!"
                self.add_message_on_lower_panel(message)
                pygame.display.update()
                pygame.time.wait(3000)
                self.__init__()

            elif self.board_state.game_state == BoardState.GAME_STATE_LOST:
                message = "You lost!"
                self.add_message_on_lower_panel(message)
                pygame.display.update()
                pygame.time.wait(3000)
                self.__init__()

            pygame.display.update()
            self.fps_clock.tick(50)

    def draw_board(self, board):
        self.display.fill(self.BACKGROUND_COLOR)
        for x in range(board.width):
            for y in range(board.height):
                cell = board.get_cell(x, y)
                self.draw_cell(cell, x, y)

    def draw_cell(self, cell, x, y):
        left, top = self.get_top_left_coordinates_of_cell(y, x)
        if cell.marked:
            pygame.draw.rect(self.display, self.GREEN, (left, top, self.FIELD_SIZE, self.FIELD_SIZE))
            text_surface_obj = self.font.render("#", True, self.BLACK)
            text_rect_obj = text_surface_obj.get_rect()
            text_rect_obj.center = (left + (self.FIELD_SIZE / 2), top + (self.FIELD_SIZE / 2))
            self.display.blit(text_surface_obj, text_rect_obj)
        elif not cell.touched:
            pygame.draw.rect(self.display, self.CLOSED_FIELD, (left, top, self.FIELD_SIZE, self.FIELD_SIZE))
        elif cell.has_mine:
            pygame.draw.rect(self.display, self.BURGUNDY, (left, top, self.FIELD_SIZE, self.FIELD_SIZE))
            pygame.draw.circle(self.display, self.BLACK,
                               (int(left + (self.FIELD_SIZE / 2)), int(top + (self.FIELD_SIZE / 2))), 9, 0)
            pygame.draw.circle(self.display, self.WHITE,
                               (int(left + (self.FIELD_SIZE / 2)), int(top + (self.FIELD_SIZE / 2))), 3, 0)
        elif cell.touched:
            if cell.value == 0:
                pygame.draw.rect(self.display, self.OPEN_FIELD, (left, top, self.FIELD_SIZE, self.FIELD_SIZE))
            else:
                pygame.draw.rect(self.display, self.OPEN_FIELD_WITH_VALUE,
                                 (left, top, self.FIELD_SIZE, self.FIELD_SIZE))
                text_surface_obj = self.font.render(str(cell.value), True, self.BLACK)
                text_rect_obj = text_surface_obj.get_rect()
                text_rect_obj.center = (left + (self.FIELD_SIZE / 2), top + (self.FIELD_SIZE / 2))
                self.display.blit(text_surface_obj, text_rect_obj)

    def get_selected_mine_field(self, mouse_x, mouse_y):
        for x in range(self.board_state.width):
            for y in range(self.board_state.height):
                left, top = self.get_top_left_coordinates_of_cell(x, y)
                fieldRect = pygame.Rect(left, top, self.FIELD_SIZE, self.FIELD_SIZE)
                if fieldRect.collidepoint(mouse_x, mouse_y):
                    return x, y
        return None, None

    def get_top_left_coordinates_of_cell(self, x, y):
        left = self.GAP_SIZE + x * (self.FIELD_SIZE + self.GAP_SIZE)
        top = self.GAP_SIZE + (y * (self.FIELD_SIZE + self.GAP_SIZE))
        return left, top

    def select_difficulty_menu(self):
        self.display = pygame.display.set_mode((400, 50))
        self.display.fill(self.BACKGROUND_COLOR)
        self.display.blit(self.font.render("Press 'e' for easy, 'm' for medium and 'h' for hard", 1, self.ORANGE),
                          (15, 15))
        pygame.display.set_caption("Select difficulty")
        pygame.display.flip()
        pygame.display.update()
        while 1:
            inkey = self.get_key_or_quit_game()
            if inkey == K_e:
                return self.DIFFICULTY_EASY
            elif inkey == K_m:
                return self.DIFFICULTY_MEDIUM
            elif inkey == K_h:
                return self.DIFFICULTY_HARD
            else:
                return self.DIFFICULTY_MEDIUM

    def get_key_or_quit_game(self):
        while 1:
            event = pygame.event.poll()
            if event.type == KEYDOWN:
                return event.key
            elif event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                self.exit_game()
            else:
                pass

    def add_message_on_lower_panel(self, message):
        text_surface_obj = self.font.render(message, True, self.ORANGE)
        text_rect_obj = text_surface_obj.get_rect()
        text_rect_obj.center = (self.board_state.width * len(message),
                                self.board_state.height * (self.FIELD_SIZE + self.GAP_SIZE) + self.GAP_SIZE * 4)
        self.display.blit(text_surface_obj, text_rect_obj)

    def exit_game(self):
        pygame.quit()
        quit()
Esempio n. 7
0
from boardstate import BoardState

b = BoardState()

b[(0, 0)] = 0
b[(1, 0)] = 1
b[(2, 0)] = 2
b[(3, 0)] = 3

assert b.win_state == BoardState.WinType.VERTICAL

b = BoardState()

b[(0, 0)] = 0
b[(0, 1)] = 1
b[(0, 2)] = 2
b[(0, 3)] = 3

assert b.win_state == BoardState.WinType.HORIZONTAL

b = BoardState()

b[(0, 0)] = 0
b[(1, 1)] = 1
b[(2, 2)] = 2
b[(3, 3)] = 3

assert b.win_state == BoardState.WinType.DIAGNAL

b = BoardState()
Esempio n. 8
0
import GUI
from boardstate import BoardState
from manager_ai import SnakeAIManager
from manager_laser import LaserManager
from manager_sound import SoundManager
# python3 from tkinter import Tk
from Tkinter import Tk

laser_manager = LaserManager(BoardState.get_cols(), BoardState.get_rows())
laser_manager.start_when_ready()   # starts when all 4 corners captured
sound_manager = SoundManager()
init_board = BoardState()
snake_mind = SnakeAIManager(init_board)
root = Tk()
GUI.GUI(root, init_board, snake_mind, laser_manager, sound_manager)
root.mainloop()
Esempio n. 9
0
def a_star(board: [[]]):
    """Function a_star

    Searches for a solution using the A* algorithm

    args:
        board ([[]]): the starting board

    returns:
        final_node (Tree.Node): the final node of the tree containing the solution
        moves_tree (Tree): the whole tree generated in the process
        nodes_visited (int): the number of tree nodes visited by the algorithm
    """
    # Checking size
    size = len(board)
    for i in range(size):
        if len(board[i]) != size:
            raise Exception("Board matrix is not a square")
    # Creating BoardState from a matrix
    root_board = BoardState(board)
    root_board.generate_islands()
    root_board.evaluate()
    root_board.objective_function = 2 * heuristic.board_cohesion(
        root_board) - heuristic.board_mass(root_board)
    island_count = len(root_board.islands)

    # Initiating Tree
    moves_tree = Tree(root_board)

    # Initiating stack
    to_visit = [moves_tree.root]
    nodes_visited = 0
    final_node = None

    while len(to_visit) > 0:

        # Take element from stack
        to_visit.sort(key=lambda node: node.content.objective_function,
                      reverse=True)
        node_current = to_visit.pop()
        nodes_visited += 1

        node_current.content.evaluate()
        if node_current.content.solved:
            final_node = node_current
            return final_node, moves_tree, nodes_visited

        # Generate neighbors
        board_next = deepcopy(node_current).content
        # Making all possible moves
        for i in range(island_count):
            for j in range(i + 1, island_count):
                # If bridge added succesfully, add to tree and stack and copy again
                if board_next.add_bridge(i, j):
                    board_next.objective_function = 2 * heuristic.board_cohesion(
                        board_next) - heuristic.board_mass(board_next)
                    child = node_current.add_child(board_next)
                    to_visit.append(child)
                    board_next = deepcopy(node_current).content

    return final_node, moves_tree, nodes_visited