Beispiel #1
0
    def solveAStart(self):
        """
        Solve function, read the neighbours
        append the dist and moves to the queue
        Queue picks small distances and puzzle is
        solved
        """
        startTime = time.time()
        board = Board(self.boardList, goalState=self.goalState, n=self.n)
        print("Start State .............")
        print(board)

        goal = Board(board.goalState, goalState=None, n=self.n)
        print("Goal State ..............")
        print(goal)

        queue = PriorityQueue()
        queue.put(board.getPriority(0))
        i = 1

        while not queue.empty():
            board = queue.get()[2]
            if not board.isGoal():
                for neighbour in board.getNeighbours():
                    if neighbour != board.previous:
                        queue.put(neighbour.getPriority(i))
                        i += 1
            else:
                self.analytics("A star", board.move, i,
                               time.time() - startTime, board)
                return
 def test_large_board(self):
     player = Board(10, 10)
     cpu = Board(10, 10)
     self.assertIsInstance(player, Board)
     self.assertIsInstance(cpu, Board)
     self.assertEqual(
         player.render(),
         "  1 2 3 4 5 6 7 8 9 10 \nA . . . . . . . . . . \nB . . . . . . . . . . \nC . . . . . . . . . . \nD . . . . . . . . . . \nE . . . . . . . . . . \nF . . . . . . . . . . \nG . . . . . . . . . . \nH . . . . . . . . . . \nI . . . . . . . . . . \nJ . . . . . . . . . . "
     )
    def test_start_fen_black(self):
        board = Board()
        board.parse_fen(START_FEN)
        board.side = BLACK
        moves = board.moveGenerator.generate_all_moves()

        self.assertEqual(len(moves), 20)
    def search(self, n=10, retries=20):
        """
        Attempts to find the optimal solution to the n-Queens problem using local search
        where the maximum number of retries is given. Each retry has a maximum of 'n'
        search steps.
        :param n: The maximum number of search steps for each retry.
        :param retries: The number of retries.
        :return: The optimum found by the local search algorithm.
        """

        for retry in range(retries):
            curr_optimum = Board(self.size)

            for step in range(n):
                x = self.search_step(curr_optimum)
                if x is None:
                    break

                curr_optimum = x
            if curr_optimum.cost() < self.optimal_cost:
                self.optimum = curr_optimum
                self.optimal_cost = curr_optimum.cost()

            if self.optimal_cost == 0:
                return self.optimum
        return self.optimum
Beispiel #5
0
def main():
    pygame.display.init()
    pygame.display.set_caption(TITLE)

    scrSize = (WIDTH + 1, HEIGHT + 1) if DRAW_GRID else (WIDTH, HEIGHT)
    screen = pygame.display.set_mode(scrSize)

    board = Board(screen, (WIDTH, HEIGHT),
                  PIXEL_NUM,
                  draw_grid=DRAW_GRID,
                  map=MAP,
                  animations=ANIMATIONS)

    # board = Board_cy(screen, (WIDTH, HEIGHT), PIXEL_NUM,
    #                  draw_grid=DRAW_GRID, map=MAP, animations=ANIMATIONS)

    isAlgorithmStarted = False

    while True:
        if (rv := runTime(board, isAlgorithmStarted)):
            if rv == 2:
                if not board.startAlgorithm(lambda: runTime(board, True)):
                    break
        else:
            break
    def test_complex_fen_white_2(self):
        board = Board()
        complex_fen = "R6R/3Q4/1Q4Q1/4Q3/2Q4Q/Q4Q2/pp1Q4/kBNN1KB1 w -- 0 1"

        board.parse_fen(complex_fen)
        moves = board.moveGenerator.generate_all_moves()

        self.assertEqual(len(moves), 218)
    def test_complex_fen_black(self):
        board = Board()
        complex_fen = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1"

        board.parse_fen(complex_fen)
        moves = board.moveGenerator.generate_all_moves()

        self.assertEqual(len(moves), 43)
Beispiel #8
0
def test_place_a_ship_horizontally():
    board = Board(board_width, board_height)
    ship = Ship(3, 'horizontal')
    board.place_ship(ship, 2, 2)
    board.print()
    assert board.squares[0] == [False, False, False, False, False, False]
    assert board.squares[1] == [False, ship, ship, ship, False, False]
    assert board.squares[2] == [False, False, False, False, False, False]
Beispiel #9
0
    def __init__(self, screen_width, screen_height):
        self.canvas = pygame.display.set_mode((screen_width, screen_height))
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.clock = pygame.time.Clock()

        self.helpers = Helpers()  # class defines helper functions

        # indicates if board should be drawn in reverse i.e. black is on the bottom of the screen
        self.revesed_board = False
        self.square_loc = self.helpers.compute_square_locations(
            self.revesed_board)

        # --- Board related vars
        self.board = Board()
        self.board.parse_fen(
            START_FEN)  # mate in two '3k4/8/8/3K4/8/8/1Q6/8 w --'
        self.move_history = []
        # --- Engine process
        self.stub = None
        self.engine_info = None
        self.movetime = '1500'  # default engine move time in ms
        # --

        self.highlighted_moves = []
        self.promotion_moves = []
        # after promotion moves are drawn, this stores info about where each promotion move is drawn on the board
        self.promotion_choices = {}
        self.clicked_square_idx = None
        # --- Images
        # -- Squares
        dark_square = pygame.image.load(
            'assets/square brown dark_png_128px.png')
        light_square = pygame.image.load(
            'assets/square brown light_png_128px.png')
        black_square = pygame.image.load(
            'assets/square gray dark _png_128px.png')
        highlight_check_square = pygame.image.load('assets/highlighted_1.png')
        highlight_square = pygame.image.load('assets/highlighted_2.png')
        highlight_move_square = pygame.image.load('assets/highlighted_3.png')
        self.dark_square = pygame.transform.scale(dark_square,
                                                  (SQUARE_SIZE, SQUARE_SIZE))
        self.light_square = pygame.transform.scale(light_square,
                                                   (SQUARE_SIZE, SQUARE_SIZE))
        self.black_square = pygame.transform.scale(black_square,
                                                   (SQUARE_SIZE, SQUARE_SIZE))
        self.highlight_check_square = highlight_check_square
        self.highlight_square = highlight_square
        self.highlight_move_square = highlight_move_square

        self.piece_images = self.helpers.load_assets()

        self.user_side = WHITE
        self.user_name = 'Player1'
        self.fen = ''
        self.last_move = ''
        self.in_check_sq = None
        self.engine_triggered = False
Beispiel #10
0
    def test_valid_coordinates(self):
        board = Board()

        self.assertTrue(board.valid_coordinate("A1"))
        self.assertTrue(board.valid_coordinate("A3"))
        self.assertTrue(board.valid_coordinate("D3"))

        self.assertFalse(board.valid_coordinate("Q7"))
        self.assertFalse(board.valid_coordinate("Coordinate"))
        self.assertFalse(board.valid_coordinate("1A"))
Beispiel #11
0
 def __init__(self):
     pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT, caption="Pyxel Othello")
     pyxel.mouse(True)
     self.board = Board()
     self.current = 'black'
     self.black_player = RandomPlayer(pyxel, self.board, 'black')
     self.white_player = RandomPlayer(pyxel, self.board, 'white')
     self.winner = None
     self.previous_frame_count = 0
     pyxel.run(self.update, self.draw)
 def test_placing_ship(self):
     board = Board(4, 4)
     cruiser = Ship("Cruiser", 3)
     submarine = Ship("Submarine", 2)
     board.place(cruiser, ["A1", "A2", "A3"])
     self.assertEqual(board.cells["A1"].ship, cruiser)
     self.assertEqual(board.cells["A2"].ship, cruiser)
     self.assertEqual(board.cells["A3"].ship, cruiser)
     self.assertTrue(board.cells["A1"].ship == board.cells["A3"].ship)
     # Test for overlap
     self.assertFalse(board.isValidPlacement(submarine, ["A1", "B1"]))
Beispiel #13
0
 def __init__(self, pnames):
     """
     :param pnames: An Array. Name of the players as Strings
     """
     self.board = Board()
     self.players = tuple([Player(pn, self.board, self) for pn in pnames])
     self.plookup = {p.getId(): p for p in self.players}
     self.lastRoll = None
     self.p = None
     self.getFirstPlayer()
     self.state = 0
Beispiel #14
0
    def reset_board(self):
        self.board = Board()
        self.board.parse_fen(START_FEN)
        self.move_history = []
        self.movetime = '1500'

        self.reset_highlighted_moves()

        self.user_side = WHITE
        self.fen = ''
        self.last_move = ''
        self.in_check_sq = None
        self.engine_triggered = False
Beispiel #15
0
def classify_orbs(frame):
    """ classifies the orbs in a given BGR frame and returns a board object """

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV_FULL)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    plus = cv2.imread(
        r'C:\Users\cuish\Documents\PersonalProjects\pad-auto\resources\plus.png',
        0)
    kpp, desp = sift.detectAndCompute(plus, None)

    xstart, xend, ystart, yend, size = get_canvas_position(frame)

    data = []
    for y in range(5):
        for x in range(6):
            ycor = int(y * size + ystart)
            xcor = int(x * size + xstart)
            cellhsv = hsv[ycor:ycor + size, xcor:xcor + size, slice(None)]
            cellgray = gray[ycor:ycor + size, xcor:xcor + size]

            # assign cell base value
            cut = crop_center_square(cellhsv, size / 3)
            avg = np.mean(cut[:, :, 0])
            # print(x,y,avg)
            for k, v in ORB_DATA.items():
                if v.huerange:
                    lower, upper = v.huerange
                    if lower < avg < upper:
                        cellvalue = k
                        break
            else:
                raise Exception("Unidentifiable Cell (%s, %s). Hue: %s" %
                                (x, y, avg))

            # determine cell + status
            kp2, des2 = sift.detectAndCompute(cellgray, None)
            matches = matcher.knnMatch(desp, trainDescriptors=des2, k=2)
            if count_matches(matches) > 10:
                cellvalue |= 0x10

            data.append(cellvalue)

    assert len(data) == 30
    piece_dic = {1: Fire, 2: Water, 3: Wood, 4: Light, 5: Dark, 6: Heart}
    piece_list = [piece_dic[n] for n in data]
    number_of_rows = 5
    number_of_columns = 6
    board = Board(piece_list, number_of_rows, number_of_columns)
    return board
Beispiel #16
0
def action(board):
    """
    :param board: current board on which we must make action
    :return: returns all child nodes
    """
    parent_array = board.get_board_as_list()
    parent_coords = board.get_coords()
    result = []
    for move in MOVES:
        new_coords = (parent_coords[0] + move[0], parent_coords[1] + move[1])
        if verify_coords(new_coords):
            b = Board(parent_array)
            b.swap(parent_coords, new_coords)
            result.append(b)
    return result
Beispiel #17
0
    def __init__(self,
                 columns,
                 rows,
                 fps,
                 countdown,
                 interval,
                 score_increment,
                 level_increment,
                 interval_increment,
                 pygame_instance=None):
        self.COLUMNS = columns
        self.ROWS = rows
        self.FPS = fps
        self.COUNTDOWN = countdown
        self.INTERVAL = interval
        self.SCORE_INCREMENT = score_increment
        self.LEVEL_INCREMENT = level_increment
        self.INTERVAL_INCREMENT = interval_increment

        if pygame_instance is None:
            self.pygame = pygame
        else:
            self.pygame = pygame_instance

        self.sensehat = SenseHat()
        self.db = TinyDB('data/database.json')

        try:
            self.WIDTH = self.BLOCK_SIZE * self.COLUMNS + 150
            self.HEIGHT = self.BLOCK_SIZE * self.ROWS

            self.BACKGROUND_GRID = [[
                8 if x % 2 == y % 2 else 0 for x in range(self.COLUMNS)
            ] for y in range(self.ROWS)]

            self.pygame.init()
            self.pygame.key.set_repeat(0, 0)
            self.pygame_font = self.pygame.font.Font(
                self.pygame.font.get_default_font(), 12)
            self.pygame_screen = self.pygame.display.set_mode(
                (self.WIDTH, self.HEIGHT), 0, 24)
            self.pygame.event.set_blocked(self.pygame.MOUSEMOTION)

            self.board = Board(self.COLUMNS, self.ROWS)
            self.__generate_snake()
            self.__generate_apple()
        except AttributeError:
            print("[Game][error] An error occurred initialising game")
Beispiel #18
0
    def reset(self):
        print("[Game][info] Resetting game")

        self.PAUSED = False
        self.GAMEOVER = False
        self.SCORE = 0
        self.APPLES = 0
        self.LEVEL = 1
        self.SNAKE_MOVED = True

        self.board = Board(self.COLUMNS, self.ROWS)
        self.snake = None
        self.apple = None
        self.__generate_snake()
        self.__generate_apple()

        self.sensehat.clear()
        self.pygame.time.set_timer(pygame.USEREVENT + 1, 0)
        self.pygame.display.update()
 def test_render_boad(self):
     board = Board(4, 4)
     cruiser = Ship("Cruiser", 3)
     board.place(cruiser, ["A1", "A2", "A3"])
     self.assertEqual(
         board.render(),
         "  1 2 3 4 \nA . . . . \nB . . . . \nC . . . . \nD . . . . ")
     self.assertEqual(
         board.render(True),
         "  1 2 3 4 \nA S S S . \nB . . . . \nC . . . . \nD . . . . ")
     board.cells['A1'].fire_upon()
     self.assertEqual(
         board.render(True),
         "  1 2 3 4 \nA H S S . \nB . . . . \nC . . . . \nD . . . . ")
     board.cells['A2'].fire_upon()
     board.cells['A3'].fire_upon()
     self.assertEqual(
         board.render(True),
         "  1 2 3 4 \nA X X X . \nB . . . . \nC . . . . \nD . . . . ")
Beispiel #20
0
  def __init__(self, parent, options, dic='./dics/sowpods.txt'):
    Frame.__init__(self, parent, bg='azure')
    self.grid(row=0, column=0, sticky=S+N+E+W)

    self.dict = Dict(dic)
    self.bag = Bag()
    self.board = Board()

    self.set_variables()

    # There isn't a play_num key in the options, it is a game joined on lan
    if options.get('play_num', False):
      self.joined_lan = False
      self.resolve_options(options)
    else:
      self.joined_lan = True
      self.thread = threading.Thread(target=lh.join_lan_game, args=(options, self.queue))
      self.thread.start()
      self.resolve_options(options)

    self.run()
Beispiel #21
0
def time_evaluation():
    testBoard = Board()
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(2, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(3, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(5, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(6, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(7, 1)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 2)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 3)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 5)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 6)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(1, 7)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(2, 2)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(3, 3)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(2, 4)))
    testBoard.add_piece(Piece(Color.WHITE, Coordinate(4, 2)))
    """
    BOARD BEING BUILT

    ###########################
    # x                       #   
    # x                       #   
    # x                       #   
    #   x                     #   
    # x   x                   #   
    # x x   x                 #   
    # x x x   x x x           #   
    ###########################

    """

    # print(sets_of_adjacent(1, testBoard.all_friendly()))
    # print(sets_of_adjacent(2, testBoard.all_friendly()))
    # print(sets_of_adjacent(3, testBoard.all_friendly()))
    # print(sets_of_adjacent(4, testBoard.all_friendly()))
    # print(sets_of_adjacent(5, testBoard.all_friendly()))

    brain = Brain()
    print(brain.evaluation_function(testBoard))
Beispiel #22
0
    def test_board_attributes(self):
        board = Board()
        example = {
            "A1": board.cells["A1"],
            "A2": board.cells["A2"],
            "A3": board.cells["A3"],
            "A4": board.cells["A4"],
            "B1": board.cells["B1"],
            "B2": board.cells["B2"],
            "B3": board.cells["B3"],
            "B4": board.cells["B4"],
            "C1": board.cells["C1"],
            "C2": board.cells["C2"],
            "C3": board.cells["C3"],
            "C4": board.cells["C4"],
            "D1": board.cells["D1"],
            "D2": board.cells["D2"],
            "D3": board.cells["D3"],
            "D4": board.cells["D4"]
        }

        self.assertDictEqual(example, board.cells)
 def test_is_valid_placement(self):
     board = Board(4, 4)
     cruiser = Ship("Cruiser", 3)
     submarine = Ship("Submarine", 2)
     self.assertEqual(board.isValidPlacement(cruiser, ["A1", "A2"]), False)
     self.assertEqual(board.isValidPlacement(submarine, ["A2", "A3", "A4"]),
                      False)
     self.assertEqual(board.isValidPlacement(cruiser, ["A1", "A2", "A4"]),
                      False)
     self.assertEqual(board.isValidPlacement(submarine, ["A1", "C1"]),
                      False)
     self.assertEqual(board.isValidPlacement(cruiser, ["A3", "A2", "A1"]),
                      False)
     self.assertEqual(board.isValidPlacement(submarine, ["C1", "B1"]),
                      False)
     self.assertEqual(board.isValidPlacement(cruiser, ["A1", "B2", "C3"]),
                      False)
     self.assertEqual(board.isValidPlacement(submarine, ["C2", "D3"]),
                      False)
     self.assertEqual(board.isValidPlacement(submarine, ["A1", "A2"]), True)
     self.assertEqual(board.isValidPlacement(cruiser, ["B1", "C1", "D1"]),
                      True)
Beispiel #24
0
    def solveDFS(self):
        """
        Solve function for DFS algorithm
        """
        startTime = time.time()
        board = Board(self.boardList, goalState=self.goalState, n=self.n)

        visited = list()
        queue = LifoQueue()
        queue.put(board.getPriority(0)[2])
        i = 1

        while not queue.empty():
            board = queue.get()
            if not board.isGoal():
                for neighbour in board.getNeighbours():
                    if neighbour not in visited:
                        visited.append(neighbour)
                        queue.put(neighbour)
                        i += 1
            else:
                self.analytics("DFS", board.move, i,
                               time.time() - startTime, board)
                return
Beispiel #25
0
 def __init__(self, config: Configuration = default_config) -> None:
     """Setup new game"""
     self.config = config
     self.board = Board(self.config)
     self.status = Status.IN_PROGRESS
Beispiel #26
0
import lib.defs as defs
from lib.board import Board


board = Board()
print(board.files)
print(board.ranks)
print(board.pieces)
board.parse_fen(defs.start_fen)
# print(board.piece_num)
print(not board.sq_attacked(71, defs.colors["black"]))
board.print_sq_attacked(defs.colors["white"])
board.print_board()
print(board.position_key)
print(board.check_board())
board.generate_moves()
print(board.move_list)
board.print_move_list()
board.make_move(board.move_list[0])
board.print_board()
print(board.history[0])
print(board.check_board())
Beispiel #27
0
 def setUp(self):
     self.testBoard = Board()
     self.brain = Brain()
Beispiel #28
0
from lib.board import Board
from lib.helpers import *
from random import choice

if __name__ == "__main__":
    (options, args) = parse_options()

    board = Board(options.size, options.length)
    turn = OPPONENT_A
    player_a = choice([OPPONENT_A, OPPONENT_B])
    player_b = OPPONENT_B if player_a == OPPONENT_A else OPPONENT_A
    messages = {
        player_a: "%s won!" % player_a,
        player_b: "%s won!" % player_b,
        DRAW: "It's a draw."
    }

    while not board.game_over[0]:
        if turn == player_a:
            next_move = take_coordinates(turn)
        else:
            next_move = take_coordinates(turn)
        board[next_move] = turn
        turn = OPPONENT_B if turn == OPPONENT_A else OPPONENT_A
        print board
    print messages[board.game_over[1]]
Beispiel #29
0
def test_board():
    board = Board(board_width, board_height)
    assert type(board.squares).__name__ == 'list'
Beispiel #30
0
def test_sink_square():
    board = Board(board_width, board_height)
    ship = Ship(3, 'horizontal')
    board.place_ship(ship, 2, 2)
    board.sink_square(2, 2)
    assert board.squares[1] == [False, 'Sunk', ship, ship, False, False]