Exemplo n.º 1
0
    def move_action(self, move_string):
        # move_string must be of the format 'A3-A5', for piece on A3 moves to A5
        start_location, finish_location = move_string.split('-')

        start_column, start_row = Board.location_string_to_corner(
            start_location)
        finish_column, finish_row = Board.location_string_to_corner(
            finish_location)

        start_corner = self.board.get_corner(start_column, start_row)

        if not start_corner.is_occupied():
            raise KeyError(
                "Corner {} is unoccupied, so can't move from here!".format(
                    start_location))

        if start_corner.colour_of_occupant() != self.whose_turn:
            raise KeyError("It's {}'s turn but piece on {} is {}".format(
                self.whose_turn, start_location,
                start_corner.colour_of_occupant()))

        game_continues, losing_team = start_corner.get_occupant().move_piece(
            finish_column, finish_row)

        if self.whose_turn == 'red':
            self.whose_turn = 'black'
        else:
            self.whose_turn = 'red'

        print(self.board)
        time.sleep(2)

        return game_continues, losing_team, self.whose_turn, self.board
Exemplo n.º 2
0
 def print(self):
     print(f"num q_values = {len(self.cache.boards)}")
     for cells_bytes, value in self.cache.boards.items():
         cells = np.frombuffer(cells_bytes, dtype=int)
         board = Board(cells)
         board.print()
         print(f"qvalue = {value}")
Exemplo n.º 3
0
    def setUp(self, text=None):
        random.seed(0)
        self.board = Board(size=9, batch=5, colsize=None, scrub_length=5, axes=None, logfile=None
                      , drawing_callbacks=dict())

        if text:
            self.board.init_test_graph(text)
Exemplo n.º 4
0
    def play(self, tetromino_seq):
        self.tetromino_spawner = TetrominoSpawner(tetromino_seq)

        for i in range(
                1
        ):  # this range changes the number of times single game is played (more games are better in case of random spawning)
            self.is_game_over = False  # TODO
            self.board = Board()

            while not self.is_game_over:
                # get situation of top two rows
                situation = self.board.get_situation()

                # get new tetromino
                tetromino: Tetromino = self.tetromino_spawner.spawn()
                rotations_num = self.gene.get_rotation(situation,
                                                       tetromino.shape_num)
                tetromino.rotate(times=rotations_num)

                # check if last row is empty and end if not
                if not self.board.can_place_next_tetromino(tetromino):
                    self.is_game_over = True
                    break

                # place tetromino
                position = self.gene.get_position(situation,
                                                  tetromino.shape_num)
                self.board.add_tetromino(tetromino, position)

                # remove full rows and add score
                removed_count = self.board.remove_full_rows_and_return_count()
                self.score += removed_count * 10000  # give 1000 pts for each row
                self.score += 1  # give score for each dropped tetromino 30 pieces > 1 row
Exemplo n.º 5
0
 def testAssignNakedSingles(self):
     board = Board();
     board.boardFromString(self.NAKED_SINGLES)
     
     # Create a copy of the original board
     originalBoard = Board(board)
     
     easySolver = EasySolver(board)
     result = easySolver.assignNakedSingles()
     
     # Make sure all were assigned
     assert(result == 4)
     
     # Make sure that the board now has the naked singles assigned
     assert(board.getPosition(0, 8) == '3')
     assert(board.getPosition(0, 7) == '5')
     assert(board.getPosition(4, 3) == '6')
     assert(board.getPosition(6, 6) == '2')
     
     # Ensure the only changes to the board are the assigned singles
     assert(board != originalBoard)
     for y in xrange(board.getDimensions()):
         for x in xrange(board.getDimensions()):
             # Don't bother checking fields we know have changed
             if not (x, y) in [(0, 8), (0, 7), (4, 3), (6, 6)]:                         
                 assert(board.getPosition(x, y) ==
                    originalBoard.getPosition(x, y))
Exemplo n.º 6
0
class FourCornersGame(object):
    def __init__(self):
        self._players = [
            Player(self, 0),
            Player(self, 1),
            Player(self, 2),
            Player(self, 3)
        ]
        self._board = Board(self._players)
        self._viewer = FourCornersViewer(moveEvent=self.makeMove)
        self._updateViewer()

    @property
    def board(self):
        return self._board

    ######################### Move Making #########################

    def makeMove(self, piece, top_left_x, top_left_y):
        self._board.placePiece(piece, top_left_x, top_left_y)
        self._updateViewer()

    ######################### Viewer #########################

    def mainViewerProcess(self):
        self._viewer.mainViewerLoop()

    def _updateViewer(self):
        self._viewer.updateBoard(self._board)
Exemplo n.º 7
0
 def __init__(self):
     super(GraphicsBoard, self).__init__()
     self.rows = 3
     self.cols = 8
     self.info_label = Label(text='Welcome!')
     self.board = Board()
     self._initialize_board()
Exemplo n.º 8
0
    def __game_loop(self):
        """Player moves are handled by this function."""

        current_player = self.__player_one
        other_player = self.__player_two

        while True:
            print(self.__board.draw_board(self.__board.board))
            player_col_choice = input(f"{current_player.name}, choose a move: ")
            move_coordinates = self.__board.player_move(current_player, player_col_choice)
            if not move_coordinates:
                continue
            else:
                win = self.__has_won(current_player, move_coordinates)
                draw = (not win) and self.__have_drawn()
                if win or draw:
                    print(self.__board.draw_board(self.__board.board))
                    if win:
                        print(f"{current_player.name} has won!")
                        current_player.wins = 1
                    elif draw:
                        print("Game drawn!")

                    if not self.__continue_playing():
                        print(self.__statistics())
                        return
                    else:
                        self.__board = Board()

                else:
                    current_player, other_player = other_player, current_player
Exemplo n.º 9
0
class Game:
    def __init__(self, player_one: Player = None, player_two: Player = None, verbose: bool = True) -> None:
        self._move_counter = 0
        self._board = Board(MAX_ROWS, MAX_COLUMNS)
        self._players = (
            player_one if player_one is not None else Player(
                SIGN_PLAYER_ONE, 'magenta'),
            player_two if player_two is not None else Player(
                SIGN_PLAYER_TWO, 'cyan')
        )
        self._verbose = verbose

# WHY Optional[tuple[list, int]] DID NOT WORK? 
    def run(self, return_log_boards: bool = False) -> Optional[tuple]:
        board_log = []
        while(judge.is_game_over(self._board) is not True):
            current_player = self._players[self._move_counter % 2]
            self._print(self._board)
            self._print(' 1  2  3  4  5  6  7')

            move = current_player.make_move(self._board) - 1

            if judge.is_valid_move(self._board, move) is not True:
                self._print('bad move!')
                continue

            self.make_move(current_player, move)

            if return_log_boards == True:
                board_log.append(self._board.get_array_by_signs(PLAYER_SIGNS))

            self._move_counter += 1

        self._print(self._board)
        board_log = np.array(board_log)

        if judge.is_winning(self._board, SIGN_PLAYER_ONE):
            self._print('{} is a winner!'.format(SIGN_PLAYER_ONE))
            return (board_log, 1)

        elif judge.is_winning(self._board, SIGN_PLAYER_TWO):
            self._print('{} is a winner!'.format(SIGN_PLAYER_TWO))
            return (board_log, -1)

        else:
            self._print('Draw')
            return (board_log, 0)


    def make_move(self, player: Player, column: int):
        for row in reversed(range(MAX_ROWS)):
            if self._board.is_empty(column, row):
                self._board.put_piece(column, row, player.get_piece())
                return


    def _print(self, text: str):
        if self._verbose == True:
            print(text)
Exemplo n.º 10
0
def test_row(mark):
    board = Board()
    board._rows = [[' ', ' ', ' '], [' ', mark, mark], [' ', mark, ' ']]

    for _ in range(100):
        player = RandomComputer(mark)
        row, column = player.turn(board)
        assert board.is_cell_empty(row, column)
Exemplo n.º 11
0
def test_second_turn_center_opening(player_mark):
    other_mark = Game.FIRST_PLAYER_MARK
    ai = AI(player_mark)
    board = Board()
    board._rows = [[' ', ' ', ' '], [' ', other_mark, ' '], [' ', ' ', ' ']]
    for _ in range(100):
        assert ai._second_turn(board.representation()) in product((0, 2),
                                                                  (0, 2))
Exemplo n.º 12
0
    def __init__(self, upper_player, lower_player):
        """Instantiate a Mancala game."""
        self.board = Board()

        self._upper_player = upper_player
        self._lower_player = lower_player

        self._current_player = self._upper_player
Exemplo n.º 13
0
    def __init__(self):
        self.whose_turn = 'red'

        self.board = Board()
        self.setup_board(self.board)
        print(self.board)

        self.artificial_players = {'red': None, 'black': None}
Exemplo n.º 14
0
def is_winning(board: Board, sign: str) -> bool:
    if board.get_move_counter() < 7:
        return False

    board = board.get_array(sign)
    for kernel in kernels:
        if (convolve2d(board, kernel, mode='valid') == 4).any():
            return True
    return False
Exemplo n.º 15
0
def game():
    global MAP_TYPE
    board = Board(MAP_TYPE)
    screen = board.display_board_hide()

    width_pressed, height_pressed = 0, 0
    posX_pressed, posY_pressed = 0, 0
    running, r_pressed, escape_pressed = True, False, False
    while running:
        try:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                    quit()

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        r_pressed = True
                        running = False

                    elif event.key == pygame.K_ESCAPE:
                        escape_pressed = True
                        running = False
                        main()

                if not board.visible:
                    if event.type == pygame.MOUSEBUTTONUP:
                        button_pressed = board.matrix[posY_pressed][
                            posX_pressed]
                        board.action(button_pressed, event, screen)

                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        width_pressed = event.pos[0]
                        height_pressed = event.pos[1]

                        posX_pressed = int(width_pressed / 40)
                        posY_pressed = int(height_pressed / 40)

                        button_pressed = board.matrix[posY_pressed][
                            posX_pressed]

                        if button_pressed.content.status_celd() == "Invisible":
                            pic = picture.get_picture(0)
                            pic = pygame.transform.scale(
                                pic,
                                (button_pressed.width, button_pressed.height))
                            screen.blit(pic,
                                        (button_pressed.x, button_pressed.y))
                            pygame.display.flip()
        except pygame.error:
            pass

    if r_pressed:
        game()
    if escape_pressed:
        main()
Exemplo n.º 16
0
 def __init__(self, host, port):
     self.HANDLER = Handler
     self.board = Board(7, 7)
     asyncore.dispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.bind((host, port))
     self.listen(5)
     print('Waiting for connection...')
     self.connections = []
Exemplo n.º 17
0
def main():
    root = Tk()
    root.title("Othello")
    root.geometry("800x800")
    b = Board()
    b.init_board('init.csv')
    g = GuiBoard(board=b, master=root)
    g.display_gui_board()

    root.mainloop()
Exemplo n.º 18
0
 def __init__(self, player_one: Player = None, player_two: Player = None, verbose: bool = True) -> None:
     self._move_counter = 0
     self._board = Board(MAX_ROWS, MAX_COLUMNS)
     self._players = (
         player_one if player_one is not None else Player(
             SIGN_PLAYER_ONE, 'magenta'),
         player_two if player_two is not None else Player(
             SIGN_PLAYER_TWO, 'cyan')
     )
     self._verbose = verbose
Exemplo n.º 19
0
 def __init__(self):
     self._players = [
         Player(self, 0),
         Player(self, 1),
         Player(self, 2),
         Player(self, 3)
     ]
     self._board = Board(self._players)
     self._viewer = FourCornersViewer(moveEvent=self.makeMove)
     self._updateViewer()
Exemplo n.º 20
0
    def __init__(self, player_x_type, player_o_type):
        """Instantiate a tic-tac-toe game.

        :param player_x_type: type of the first player (player x)
        :type player_x_type: Player
        :param player_o_type: type of the second player (player o)
        :type player_o_type: Player
        """
        self.board = Board()
        self.player_x = player_x_type(self.FIRST_PLAYER_MARK)
        self.player_o = player_o_type(self.SECOND_PLAYER_MARK)
Exemplo n.º 21
0
class  test_board_1_lines_gen(unittest.TestCase):
    def setUp(self):
        random.seed(0)
        self.board=Board()
        self.board.init(9,5,None,5)
        
    def test_lines(self):
        for i in range(5): 
            self.board.next_move()

        lines =self.board.get_lines()
        pprint(lines)
Exemplo n.º 22
0
class test_board_2_candidates(unittest.TestCase):
    def setUp(self):
        random.seed(2)
        self.board=Board()
        self.board.init(9,1,None,5)

    def test_candidates(self):
        for i in range(10): 
            self.board.next_move()
        # import pdb;pdb.set_trace()
        cand=self.board.candidates()
        pprint(cand)
Exemplo n.º 23
0
 def __init__(self, fn = 'games.json'):
     try:
         with open(fn) as fh:
             self._games = json.load(fh)
     except FileNotFoundError:
         self._games = []
     self._logger = Console()         
     self._board = Board()
     self._user = User(self._board)
     self._computer = Computer(self._board, self._user )
     self._first = None
     self._game_over = False
     self._games_file = fn
Exemplo n.º 24
0
def main():
    b = Board()
    b.generate_tile_row(3, 0)
    b.generate_tile_row(4, 1)
    b.generate_tile_row(5, 2)
    b.generate_tile_row(4, 3)
    b.generate_tile_row(3, 4)
    print('Done')
Exemplo n.º 25
0
def test_second_turn_corner_opening(player_mark):
    other_mark = Game.FIRST_PLAYER_MARK
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', other_mark], [' ', ' ', ' '], [' ', ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', other_mark]]
    assert ai._second_turn(board.representation()) == (1, 1)

    board._rows = [[' ', ' ', ' '], [' ', ' ', ' '], [other_mark, ' ', ' ']]
    assert ai._second_turn(board.representation()) == (1, 1)
Exemplo n.º 26
0
    def test_winRow(self):
        board = Board()
        board.getBoard()[0] = [1, 1, 1, 1, 1, 0]
        b = board.checkWinRow()
        self.assertTrue(b, "Not true")

        board.getBoard()[0] = [0, 1, 1, 1, 1, 1]
        b = board.checkWinRow()
        self.assertTrue(b, "Not true")
Exemplo n.º 27
0
 def new_game(self, lobby: Lobby):
     group_code = lobby.get_group_code()
     players = initialise_players(lobby.get_players())
     tile_repo = TileRepo.get_repo_from_config(TILE_CONFIG_PATH)
     board = Board.from_config(BOARD_CONFIG_PATH, tile_repo)
     dice_roll = DiceRoll.generate_dice(2, 6)
     game = Game(board, players, 0, dice_roll, ROLL)
     self.__games[group_code] = game
Exemplo n.º 28
0
def start_ui():
    board = Board(6, 6)
    strategy = Strategy()
    p1 = Human('x', board)
    p2 = Computer("0", board, strategy)
    minimax = Minimax()
    game = Game(p1, p2, board, minimax)
    game.start()
Exemplo n.º 29
0
    def play_training_game(self, opponent, epsilon):
        move_history = deque()
        board = Board()
        player_one = self if self.turn == 1 else opponent
        player_two = self if self.turn == 2 else opponent

        while not board.is_game_over():
            player = player_two
            if board.whose_turn() == 1:
                player = player_one

            if player is self:
                board = self.training_move(board, epsilon, move_history)
            else:
                player.move(board)

        self.post_training_game_update(board, move_history)
Exemplo n.º 30
0
def test_win(player_mark):
    ai = AI(player_mark)
    board = Board()
    board._rows = [[player_mark, ' ', player_mark], [' ', ' ', ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (0, 1)

    board._rows = [[' ', player_mark, ' '], [' ', player_mark, ' '],
                   [' ', ' ', ' ']]
    assert ai.turn(board.representation()) == (2, 1)

    board._rows = [[' ', ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', player_mark]]
    assert ai.turn(board.representation()) == (0, 0)

    board._rows = [[' ', ' ', player_mark], [' ', ' ', ' '],
                   [player_mark, ' ', ' ']]
    assert ai.turn(board.representation()) == (1, 1)
Exemplo n.º 31
0
 def testFindNakedSingles(self):
     board = Board()
     board.boardFromString(self.NAKED_SINGLES)
     easySolver = EasySolver(board)
     singles = easySolver.findNakedSingles()
     
     # Check we found all the expected results
     assert(len(singles) == 4)
     
     # Validate the value of the single found
     assert((0, 8) in singles)
     assert(singles[(0, 8)] == '3')
     assert((0, 7) in singles)
     assert(singles[(0, 7)] == '5')
     assert((4, 3) in singles)
     assert(singles[(4, 3)] == '6')
     assert((6, 6) in singles)
     assert(singles[(6, 6)] == '2')
Exemplo n.º 32
0
 def restart(self):
     global root
     self.gui_board.container.destroy()
     self.gui_board = GuiBoard(Board(3, 3), root)
     self.gui_board.draw()
     self.initialize_buttons()
     # self.init_two_players_game()
     self.two_players_button.grid()
     self.init_two_players_game()
Exemplo n.º 33
0
 def testFindHiddenSingles(self):
     board = Board()
     board.boardFromString(self.NAKED_SINGLES)
     
     easySolver = EasySolver(board)
     singles = easySolver.findHiddenSingles()
     
     # Check we found all the expected results
     assert(len(singles) == 6)
     
     # Validate the value of the single found
     assert((5, 5) in singles)
     assert(singles[(5, 5)] == '3')
     assert((7, 6) in singles)
     assert(singles[(7, 6)] == '3')
     assert((3, 6) in singles)
     assert(singles[(3, 6)] == '5')
     assert((2, 0) in singles)
     assert(singles[(2, 0)] == '6')
     assert((8, 7) in singles)
     assert(singles[(8, 7)] == '7')
     assert((4, 1) in singles)
     assert(singles[(4, 1)] == '7')
Exemplo n.º 34
0
def print_board(grid):
	print grid[0:3]
	print grid[3:6]
	print grid[6:9]

if __name__ == "__main__":
	starter = raw_input("Pick player 1(1) or 2(2) (Player 1 starts...): ")
	while starter not in ['1', '2']:
		starter = raw_input("Invalid: Pick either 1 or 2: ")

	opponent = raw_input("Do you want to play X(X) or O(O): ")
	while opponent not in ['X', 'O']:
		opponent = raw_input("Invalid: Pick either X or O: ")

	board = Board()
	rules = Rules(board)
	player = ArtificialIntelligence(board)

	ai_mark = 'O' if opponent == 'X' else 'X'
	next_play = opponent if starter == '1' else ai_mark
	
	#initialize
	rules.next_play = next_play
	player.set_mark(ai_mark) #computer's mark (i.e., X)
	
	end_game = False
	while not end_game:
		print_board(board.grid)
		mark = rules.get_current_player()
Exemplo n.º 35
0
'''

from board.board import Board
from solver.easysolver import EasySolver
from board.boardutils import *

import logging

IMPOSSIBLE_STRING = '1.......2.9.4...5...6...7...5.9.3.......7.......85..4.7.....6...3...9.8...2.....1'
HARD_STRING = '6.5..2..8...1...7..9.5..6....2736.8....485....3.9217....4..3.9..5...4...3..8..1.2'
EASY_STRING = '79....3.......69..8...3..76.....5..2..54187..4..7.....61..9...8..23.......9....54'

logger = logging.getLogger('sudoku')
logging.basicConfig(level=logging.INFO)

board = Board()
board.boardFromString(HARD_STRING)
logger.info('\n' + boardToString(board))
easySolver = EasySolver(board)

assigned = -1
while assigned != 0:
    if easySolver.getAvailableMap().getUnassigned() == 0:
        break
    
    assigned = 0
    assignedNakedSingles = 0
    assignedHiddenSingles = 0
        
    assignedNakedSingles += easySolver.assignNakedSingles()
    logger.info('Found ' + str(assignedNakedSingles) + ' naked singles')
Exemplo n.º 36
0
 def testBoardToSimpleSudokuClipboard(self):
     board = Board()
     board.boardFromString(self.SUDOKU_STRING)
     result = boardToSimpleSudokuClipboard(board)
     assert(self.SIMPLE_SUDOKU == result)