Exemplo n.º 1
0
    def test_model(self, model):
        steps_list = []
        scores_list = []

        for test_game in range(self.test_games):
            steps = 0
            game = Board()
            prev_observation = self.generate_observation(game)

            for goal_step in range(self.goal_steps):
                predictions = []
                for action in [-1, 0, 1]:
                    predictions.append(model.predict(np.reshape(self.add_act_to_observ(prev_observation, action), (-1, 5, 1))))
                action = np.argmax(np.array(predictions)) - 1
                game_move = self.generate_game_move(game.snake, action)
                try:
                    game.run(game_move)
                    prev_observation = self.generate_observation(game)
                    steps += 1
                except GameOver as g:
                    print("Test game %d had score %d and took %d steps" % (test_game, game.score, steps))
                    break

            steps_list.append(steps)
            scores_list.append(game.score)

        print('Average steps: ', mean(steps_list))
        print(Counter(steps_list))

        print('Average score: ', mean(scores_list))
        print(Counter(scores_list))
Exemplo n.º 2
0
 def test_print_filled_square(self):
     """
     Printing a square with a piece in it should result in that piece ('X' or 'O').
     """
     board = Board()
     board.set_square(1, 'X')
     self.assertEqual('X', board.print_square(1))
Exemplo n.º 3
0
    def generate_population(self):
        training_data = []

        for init_game in range(self.initial_games):
            game = Board()
            prev_observation = self.generate_observation(game)
            prev_food_distance = np.linalg.norm(np.array(game.food) - np.array(game.snake[-1]))
            prev_score = game.score

            for step in range(self.goal_steps):
                action, direction = self.generate_action(game.snake)
                try:
                    game.run(direction)
                    food_distance = np.linalg.norm(np.array(game.food) - np.array(game.snake[-1]))
                    score = game.score

                    if score > prev_score or food_distance < prev_food_distance:
                        training_data.append([self.add_act_to_observ(prev_observation, action), 1])
                    else:
                        training_data.append([self.add_act_to_observ(prev_observation, action), 0])

                    prev_observation = self.generate_observation(game)
                    prev_food_distance = food_distance
                except GameOver as g:
                    if str(g) == "You Win":
                        training_data.append([self.add_act_to_observ(prev_observation, action), 1])
                    else:
                        training_data.append([self.add_act_to_observ(prev_observation, action), -1])
                    break

        return training_data
Exemplo n.º 4
0
 def test_ATC_000_001(self):
     '''Board Add Bead and Get'''
     CreateBead = Bead(Location(0, 0), COLOR['WHITE'])
     GameBoard = Board()
     GameBoard.AddBead(CreateBead)
     ObtainBead = GameBoard.GetBead(Location(0, 0))
     self.assertEqual(CreateBead, ObtainBead, 'Bead Add and Set Fail')
Exemplo n.º 5
0
 def test_get_index_values(self):
     """
     Squares should be fetched using a pattern like a num-pad on a keyboard. The bottom-left square should be square
     '1', and the top-right square should be square '9'.
     """
     board = Board()
     board.set_square(3, 'X')
     self.assertEqual(board.squares[2], board.get_square(3))
Exemplo n.º 6
0
 def test_ATC_000_004(self):
     '''Human Down A Chess At duplicate place'''
     GameBoard = Board()
     HuManPlayer = Human(COLOR['BLACK'], GameBoard)
     bead = HuManPlayer.DownBeadAtPos(0, 0)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(0, 0)
     self.assertEqual(None, bead)
Exemplo n.º 7
0
 def test_get_filled_square(self):
     """
     Getting a filled square should return a string of that piece. (For now, might change to using a separate class
     for pieces later on.)
     """
     board = Board()
     board.set_square(1, 'X')
     self.assertEqual('X', board.get_square(1))
Exemplo n.º 8
0
 def test_set_square(self):
     """
     Placing a piece should set that square to the specified piece.
     """
     board = Board()
     self.assertEqual(None, board.get_square(5))
     board.set_square(5, 'X')
     self.assertEqual('X', board.get_square(5))
Exemplo n.º 9
0
 def test_possible_moves_with_empty_board(self):
     """
     Getting the possible moves from an empty board should return a list containing the numbers in the range [1, 9].
     """
     board = Board()
     self.assertListEqual(
         [1, 2, 3, 4, 5, 6, 7, 8, 9],
         board.get_possible_moves()
     )
Exemplo n.º 10
0
 def test_ATC_003_006(self):
     '''Game Draw test'''
     GameBoard = Board()
     GameBoard.InitBoard(COLOR['WHITE'])
     Arithmetic = Verdict(GameBoard.BeadArry)
     Displayer = GameIO(GameBoard)
     Displayer.PrintGameBoard()
     result = Arithmetic.VerdictDraw()
     self.assertAlmostEqual(True, True)
Exemplo n.º 11
0
    def __init__(self):
        self._running = True
        self._game_over = False
        self._game_over_message = ""
        self._no_keys_pressed = True
        self._game = Board()
        # self._frame_rate = 7 Perhaps we do not need this since we are using clock ticks?
        self._clock = pygame.time.Clock()

        self._surface = pygame.display.set_mode((600, 600), pygame.RESIZABLE)
Exemplo n.º 12
0
class LoadThread(QtCore.QThread):
  ready = QtCore.Signal()
  progress = QtCore.Signal(int,int)

  def run(self):
    self.board = Board()
    self.board.load(self.game_file.path, self.progress)
    self.board.red_team.name = self.game_file.p1
    self.board.blue_team.name = self.game_file.p2
    self.ready.emit()
Exemplo n.º 13
0
 def test_copy_with_blank_board(self):
     """
     Copying a blank board should create a new blank board. Modifying the squares on one should not change the
     squares on the other.
     """
     board = Board()
     new_board = board.copy()
     self.assertListEqual([None] * 9, new_board.squares)
     new_board.set_square(1, 'X')
     self.assertIsNone(board.get_square(1))
     self.assertEqual(new_board.get_square(1), 'X')
Exemplo n.º 14
0
def run_santorini(agent1=LinearRlAgentV2("A", 4),
                  agent2=LinearRlAgentV2("B", 4)):
    '''
    should run a game of Santorini, allow choice of AI/human players
    '''
    board = Board(agent1, agent2)
    win = None
    #initial worker placement
    board = board.PlayerA.place_workers(board)
    board = board.PlayerB.place_workers(board)
    current_player = 'A'

    def get_current_board_player(current_player):
        if current_player == 'A':
            return board.PlayerA
        else:
            return board.PlayerB

    #game loop
    while win == None:
        board_player = get_current_board_player(current_player)
        win = board.start_turn_check_win(board_player)
        if win != None:
            break
        else:
            '''
            board_levels, worker_coords = FastBoard.convert_board_to_array(board)
            fast_board = FastBoard()
            start = time.time()
            print(MinimaxWithPruning(board_levels, worker_coords, current_player, 3, fast_board))
            end = time.time()
            print(f'tree with ab pruning took {end-start}')
            '''
            """
            print(f'Current Player is {current_player}')
            board.print_board()
            print("----------------------------------------------------------------\n")
            """
            board = board_player.action(board)
            #because the board has been replaced, need to retrieve player obj again
            board_player = get_current_board_player(current_player)
            win = board.end_turn_check_win(board_player)
            if win != None:
                #board.print_board()
                break

        if current_player == 'A':
            current_player = 'B'
        else:
            current_player = 'A'

    return win
Exemplo n.º 15
0
 def test_ATC_002_002(self):
     '''LeftUp Corner Right 3 Continuous Bead,Check Winner'''
     GameBoard = Board()
     HuManPlayer = Human(COLOR['WHITE'], GameBoard)
     bead = HuManPlayer.DownBeadAtPos(0, 0)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(0, 1)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(0, 2)
     GameBoard.AddBead(bead)
     Arithmetic = Verdict(GameBoard.BeadArry)
     WinnerColor = Arithmetic.VerdictWinner(3)
     self.assertEqual(COLOR['WHITE'], WinnerColor)
Exemplo n.º 16
0
 def test_ATC_002_003(self):
     '''LeftDown Corner UP 3 Continuous Bead,Check Winner'''
     GameBoard = Board()
     HuManPlayer = Human(COLOR['WHITE'], GameBoard)
     bead = HuManPlayer.DownBeadAtPos(8, 0)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(7, 0)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(6, 0)
     GameBoard.AddBead(bead)
     Arithmetic = Verdict(GameBoard.BeadArry)
     WinnerColor = Arithmetic.VerdictWinner(3)
     Displayer = GameIO(GameBoard)
     Displayer.PrintGameBoard()
     self.assertEqual(COLOR['WHITE'], WinnerColor)
Exemplo n.º 17
0
 def test_ATC_000_002(self):
     '''Human Down A Chess'''
     GameBoard = Board()
     HumanPlayer = Human(COLOR['BLACK'], GameBoard)
     bead = HumanPlayer.DownBeadAtPos(0, 0)
     self.assertEqual(bead.Color, COLOR['BLACK'])
     self.assert_(bead.Position.AxisX == 0 and bead.Position.AxisY == 0)
Exemplo n.º 18
0
 def test_game_won_with_win(self):
     """
     If a player has 3 pieces in a line, the game should be won and the function should return true. The board's
     winner_piece variable should also be set to the winner's piece.
     """
     board = Board()
     # make sure board's winner_piece variable is initially None
     self.assertIsNone(board.winner_piece)
     board.set_square(7, 'O')
     board.set_square(5, 'X')
     board.set_square(3, 'O')
     board.set_square(8, 'X')
     board.set_square(1, 'O')
     board.set_square(4, 'X')
     board.set_square(2, 'O')
     self.assertTrue(board.game_won())
     self.assertEqual('O', board.winner_piece)
Exemplo n.º 19
0
    def test_ATC_001_001(self):
        '''Check Continuous Bead Cnt'''
        GameBoard = Board()
        HuManPlayer = Human(COLOR['WHITE'], GameBoard)
        bead = HuManPlayer.DownBeadAtPos(0, 0)
        GameBoard.AddBead(bead)
        bead = HuManPlayer.DownBeadAtPos(1, 0)
        GameBoard.AddBead(bead)
        bead = HuManPlayer.DownBeadAtPos(2, 0)
        GameBoard.AddBead(bead)
        Arithmetic = Verdict(GameBoard.BeadArry)
        SameCount = Arithmetic.GetSameColorBeadCnt(range(9), [0] * 9)
        SameCount1 = Arithmetic.GetSameColorBeadCnt([0] * 9, range(9))
        Displayer = GameIO(GameBoard)
        Displayer.PrintGameBoard()

        self.assertEqual(3, SameCount)
        self.assertEqual(1, SameCount1)
Exemplo n.º 20
0
 def __initGame(self):
     self.__winNumCondition = 3
     self.__startPlayer = 'Pc'
     self.__gameBoard = Board()
     self.__memory = Memory()
     self.__verdict = Verdict(self.__gameBoard.BeadArry)
     self.__gameIO = GameIO(self.__gameBoard)
     self.__playerHM = Human(COLOR['WHITE'], self.__gameBoard)
     self.__playerPc = Pc(COLOR['BLACK'], self.__gameBoard)
     self.SaveGame()
Exemplo n.º 21
0
def run_santorini(agent1, agent2):
    '''
    should run a game of Santorini, allow choice of AI/human players
    '''
    board = Board(agent1, agent2)
    win = None
    #initial worker placement
    board = board.PlayerA.place_workers(board)
    board = board.PlayerB.place_workers(board)
    current_player = 'A'

    def get_current_board_player(current_player):
        if current_player == 'A':
            return board.PlayerA
        else:
            return board.PlayerB

    #game loop
    while win == None:
        board_player = get_current_board_player(current_player)
        win = board.start_turn_check_win(board_player)
        if win != None:
            break
        else:
            """
            print(f'Current Player is {current_player}')
            board.print_board()
            print("----------------------------------------------------------------\n")
            """
            board = board_player.action(board)
            #because the board has been replaced, need to retrieve player obj again
            board_player = get_current_board_player(current_player)
            win = board.end_turn_check_win(board_player)
            if win != None:
                #board.print_board()
                break

        if current_player == 'A':
            current_player = 'B'
        else:
            current_player = 'A'

    return win
Exemplo n.º 22
0
def GenerateTests(NumTrials, code_length=0, num_colours=0, max_turns=0):

    for trial in range(NumTrials):
        if code_length == 0: code_length = random.randint(3, 6)
        if num_colours == 0: num_colours = random.randint(3, 7)
        if max_turns == 0: max_turns = 20

        board = Board(code_length, num_colours, max_turns)
        code = board.code

        yield code_length, num_colours, max_turns, code
Exemplo n.º 23
0
 def test_game_won_with_no_win(self):
     """
     If the game has not been won by a player yet, the function should return false.
     """
     board = Board()
     board.set_square(7, 'O')
     board.set_square(5, 'X')
     board.set_square(3, 'O')
     self.assertFalse(board.game_won())
Exemplo n.º 24
0
 def test_squares_equal_with_different_squares(self):
     """
     If the squares aren't the same, the function should return false.
     """
     board = Board()
     board.set_square(1, 'X')
     board.set_square(2, 'O')
     board.set_square(3, 'X')
     self.assertFalse(board.squares_equal((1, 2, 3)))
Exemplo n.º 25
0
 def test_squares_equal_with_same_squares(self):
     """
     If all the squares in the list have the same piece in them, the function should return true.
     """
     board = Board()
     board.set_square(1, 'X')
     board.set_square(2, 'X')
     board.set_square(3, 'X')
     self.assertTrue(board.squares_equal((1, 2, 3)))
Exemplo n.º 26
0
 def test_copy_with_filled_board(self):
     """
     Copying a board that has pieces in it should return an exact copy with all the same pieces.
     """
     board = Board()
     board.set_square(1, 'X')
     board.set_square(3, 'O')
     board.set_square(6, 'O')
     board.set_square(7, 'X')
     new_board = board.copy()
     self.assertListEqual(['X', None, 'O', None, None, 'O', 'X', None, None], new_board.squares)
Exemplo n.º 27
0
def run_generation(models, pool, two_best):
    birds = [Bird() for _ in range(BIRDS_COUNT)]
    board = Board()
    arguments = create_arguments(models, birds, board)
    start_board(board, birds)
    models = pool.map(function_wrapper, arguments)
    models.sort()
    tmp_two_best, models = update_two_best(two_best, models)
    two_best[0].copy(tmp_two_best[0])
    two_best[1].copy(tmp_two_best[1])
    new_weights = GeneticUtils.crossover(models[-1].get_model().get_weights(), models[-2].get_model().get_weights())
    print(models)
    for index, model in enumerate(models):
        weights = new_weights[0]
        if index > ((len(models) / 2) - 1):
            weights = new_weights[1]
        model.get_model().push_new_weights(GeneticUtils.mutate(weights, None))
    return models, two_best
Exemplo n.º 28
0
 def test_possible_moves_with_some_pieces(self):
     """
     Getting the possible moves from a board should return the square numbers that have no piece in them.
     """
     board = Board()
     board.set_square(2, 'X')
     board.set_square(6, 'O')
     board.set_square(8, 'X')
     board.set_square(4, 'O')
     self.assertListEqual(
         [1, 3, 5, 7, 9],
         board.get_possible_moves()
     )
Exemplo n.º 29
0
 def __init__(self, args, NN=None):
     self.args = args
     self.state = Board(RandomAgent("A"), RandomAgent("B"))
     self.training_examples = []
     self.mcts = None
     self.nn = NN if NN != None else Neural_Network()
     self.loss_array = []
     self.mappings = {
         (0, None): 0,
         (1, None): 1,
         (2, None): 2,
         (3, None): 3,
         (4, None): 4,
         (0, 'A'): 5,
         (1, 'A'): 6,
         (2, 'A'): 7,
         (3, 'A'): 8,
         (0, 'B'): 9,
         (1, 'B'): 10,
         (2, 'B'): 11,
         (3, 'B'): 12,
     }
     self.nn.to(self.nn.device)
Exemplo n.º 30
0
 def test_ATC_002_005(self):
     '''Center Corner Up 3 Continuous Bead,Check Winner'''
     GameBoard = Board()
     HuManPlayer = Human(COLOR['WHITE'], GameBoard)
     bead = HuManPlayer.DownBeadAtPos(2, 3)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(3, 3)
     GameBoard.AddBead(bead)
     bead = HuManPlayer.DownBeadAtPos(1, 3)
     GameBoard.AddBead(bead)
     PcPlayer = Pc(COLOR['BLACK'], GameBoard)
     bead = PcPlayer.DownBead()
     GameBoard.AddBead(bead)
     Arithmetic = Verdict(GameBoard.BeadArry)
     WinnerColor = Arithmetic.VerdictWinner(3)
     Displayer = GameIO(GameBoard)
     Displayer.PrintGameBoard()
     self.assertEqual(COLOR['WHITE'], WinnerColor)
Exemplo n.º 31
0
 def __init__(self, player, args, NN=None):
     self.args = args
     self.state = Board(LinearRlAgent("A"), LinearRlAgent("B"))
     self.training_examples = []
     self.mcts = None
     self.nn = NN if NN != None else ValueFunc()
     self.loss_array = []
     self.mappings = {
         (0, None): 0,
         (1, None): 1,
         (2, None): 2,
         (3, None): 3,
         (4, None): 4,
         (0, 'A'): 5,
         (1, 'A'): 6,
         (2, 'A'): 7,
         (3, 'A'): 8,
         (0, 'B'): 9,
         (1, 'B'): 10,
         (2, 'B'): 11,
         (3, 'B'): 12,
     }
     self.nn.to(self.nn.device)
     self.name = player
Exemplo n.º 32
0
 def run(self):
   self.board = Board()
   self.board.load(self.game_file.path, self.progress)
   self.board.red_team.name = self.game_file.p1
   self.board.blue_team.name = self.game_file.p2
   self.ready.emit()
Exemplo n.º 33
0
 def test_squares_equal_with_blank_squares(self):
     """
     If any squares are 'None', the function should return false, even if all the squares given are the same.
     """
     board = Board()
     self.assertFalse(board.squares_equal((1, 2, 3)))
Exemplo n.º 34
0
 def test_squares_equal_with_blank_list(self):
     """
     Trying to call 'squares_equal' with a blank list or tuple should return true.
     """
     board = Board()
     self.assertTrue(board.squares_equal(()))
Exemplo n.º 35
0
from tqdm import tqdm
from Agent import Agent
from Buffer import Buffer
from dqn import train
# from torch.utils.tensorboard import SummaryWriter

config = getConfig('config_0.0')

setSeed(config['seed'])

paths = config['paths']

# if ['tensorboard']:
#     writer = SummaryWriter(paths['tensorboard'])

game = Board(N=config['game']['N'], Ninit=config['game']['init_tiles'])
agent = Agent(config['agent'], paths['weights'], config['iterations'])
buffer = Buffer(config['buffer'])

counter = 0
episodes = 0
super_max_tile = 0
iteration_max_tile = -1
iteration_sum_maxtile = 0
for it in range(config['iterations']):
    game.reset()
    state = game.getLogBoard()

    while not game.Lost():

        action = agent.selectAction(state, counter)
Exemplo n.º 36
0
 def test_print_empty_square(self):
     """
     Printing an empty square should result in ' '.
     """
     board = Board()
     self.assertEqual(' ', board.print_square(1))
Exemplo n.º 37
0
class SnakeInterface:
    # TODO: draw borders?

    def __init__(self):
        self._running = True
        self._game_over = False
        self._game_over_message = ""
        self._no_keys_pressed = True
        self._game = Board()
        # self._frame_rate = 7 Perhaps we do not need this since we are using clock ticks?
        self._clock = pygame.time.Clock()

        self._surface = pygame.display.set_mode((600, 600), pygame.RESIZABLE)

    def run(self):
        """Game loop"""
        pygame.init()
        #self._surface = pygame.display.set_mode((600, 600), pygame.RESIZABLE)

        try:
            while self._running:
                self._clock.tick(2)
                self._no_keys_pressed = True

                # handles various events in PyGame
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        self._running = False
                    elif event.type == pygame.KEYDOWN and not self._game_over:
                        self._no_keys_pressed = False
                        self._handle_keys(event)

                # snake moves forward if no keys are pressed
                if self._no_keys_pressed:
                    try:
                        if not self._game_over:
                            self._game.run()
                    except GameOver as g:
                        # this is how interface knows when to stop
                        self._game_over = True
                        self._game_over_message = str(g)

                self._draw_frame()
        finally:
            pygame.quit()

    def _handle_keys(self, event):
        """Handles key presses"""
        # gets whatever key was pressed
        #keys = pygame.key.get_pressed()

        try:
            if event.key == pygame.K_LEFT:
                self._game.run(LEFT)
            elif event.key == pygame.K_RIGHT:
                self._game.run(RIGHT)
            elif event.key == pygame.K_UP:
                self._game.run(UP)
            elif event.key == pygame.K_DOWN:
                self._game.run(DOWN)
        except GameOver as g:
            self._game_over = True
            self._game_over_message = str(g)

    def _draw_frame(self):
        """Draws frame based on game state"""
        self._surface.fill(pygame.Color(255, 255, 255))
        self._draw_board()
        if self._game_over:
            self._display_game_over()
        pygame.display.flip()

    def _draw_board(self):
        """Draws board based on game state"""
        block_size = self._surface.get_width() / BOARD_SIZE - 5
        for y in range(BOARD_SIZE):
            for x in range(BOARD_SIZE):
                rect = pygame.Rect(x * (block_size + 1), y * (block_size + 1),
                                   block_size, block_size)
                if self._game.board[y][x].foodTile:
                    pygame.draw.rect(self._surface, (255, 0, 0), rect)
                elif self._game.board[y][x].snakeTile:
                    pygame.draw.rect(self._surface, (0, 255, 0), rect)
                else:
                    pygame.draw.rect(self._surface, (0, 0, 0), rect)

    def _display_game_over(self):
        """Displays game over message"""
        width = self._surface.get_width()
        height = self._surface.get_height()
        fontsize = int(.1 * width)
        x_ratio = .2
        y_ratio = .75
        new_x = x_ratio * width
        new_y = y_ratio * height
        font = pygame.font.SysFont("comicsansms", fontsize)
        game_over_label = font.render(self._game_over_message, 1, (0, 0, 0))
        self._surface.blit(game_over_label, (int(new_x), int(new_y)))
Exemplo n.º 38
0
 def test_get_emtpy_square(self):
     """
     Trying to get an empty square should return None.
     """
     board = Board()
     self.assertEqual(None, board.get_square(1))
Exemplo n.º 39
0
def get_init():
    board = Board(8)
    player = Player(Color.GREEN, 1, PlayerType.HUMAN)
    player2 = Player(Color.RED, -1, PlayerType.HUMAN)
    return board, player, player2
Exemplo n.º 40
0
class Bot:
    def __init__(self):
        """Initialize instance variables."""
        self.board = Board((15, 15))
        self.done = False
        self.water_rounds = []
        self.you = None

    def handle_config(self, config_info: str):
        config_info = config_info.split(maxsplit=3)
        if config_info[0] == "WATER" and config_info[1] == "ROUND":
            self.water_rounds.append(int(config_info[2]))

        elif config_info[0] == "TILE":
            coord = Bot.get_coord(config_info[1] + config_info[2])
            lookup = {
                "WATER": Tile.Water,
                "MOUNTAIN": Tile.Mountain,
                "TREE": Tile.Tree,
                "EMPTY": Tile.Empty
            }
            self.board.set(coord, lookup[config_info[3]])

        elif config_info[0] == "PLAYER":
            p_id = config_info[2]

            if p_id not in self.board.players:
                self.board.players[p_id] = {'name': None, 'pos': None,
                                            'lives': None}

            if config_info[1] == "NAME":
                self.board.players[p_id]['name'] = config_info[3]
            elif config_info[1] == "PLACE":
                self.board.players[p_id]['pos'] = Bot.get_coord(config_info[3])
            elif config_info[1] == "LIVES":
                self.board.players[p_id]['lives'] = int(config_info[3])

        elif config_info[0] == "YOU":
            self.you = config_info[1]

    def handle_update(self, update_info: str):
        update_info = update_info.split(maxsplit=2)
        if update_info[0] == "PLAYER":
            user_data = update_info[2].split(maxsplit=1)
            p_id = user_data[0]

            if update_info[1] == "LOC":
                self.board.players[p_id]['pos'] = Bot.get_coord(user_data[1])

            elif update_info[1] == "STATUS":
                if user_data[1] == "HIT":
                    self.board.players[p_id]['lives'] -= 1

                elif user_data[1] == "DEAD":
                    self.board.players[p_id]['lives'] = 0

        if update_info[0] == "BOMB":
            coord = Bot.get_coord(update_info[2])

            if update_info[1] == "PLACED":
                self.board.bombs[coord] = 8
            elif update_info[1] == "EXPLODED":
                if coord in self.board.bombs:
                    del self.board.bombs[coord]

        if update_info[0] == "TILE" and update_info[1] == "GONE":
            coord = Bot.get_coord(update_info[2])
            self.board.set(coord, Tile.Empty)

    def handle_command(self, text: str):
        """Handle the server's message."""

        tokens = text.strip().split(maxsplit=1)

        if tokens[0] == 'CONFIG':
            self.handle_config(tokens[1])
        elif tokens[0] == 'START':
            self.initialise()
        elif tokens[0] == 'REQUEST':
            for b_coord in self.board.bombs.keys():
                self.board.bombs[b_coord] -= 1
                if self.board.bombs[b_coord] == 0:
                    log("bomb exploded at: " + str(b_coord))
            self.report_move()
        elif tokens[0] == 'UPDATE':
            self.handle_update(tokens[1])
        elif tokens[0] == "YOU":
            if "LOST" in tokens[1]:
                log(tokens[1])
            self.done = True

    def do_move(self):
        raise NotImplementedError("Implement this function to do a move")

    def report_move(self):
        move = self.do_move()
        direction = move['dir']  #: Tuple[int, int]
        bomb = move['bomb']  #: bool

        if max(direction) > 1 or min(direction) < -1:
            raise ValueError("one of the dims is out of range")

        if not self.board.is_valid_move(
                tuple(map(operator.add,
                          self.board.players[self.you]['pos'],
                          direction))):
            raise ValueError("This is not a valid location: {} {} {}".format(self.board.players[self.you]['pos'],
                          direction, tuple(map(operator.add,
                          self.board.players[self.you]['pos'],
                          direction))))

        if bomb:
            print("BOMBWALK {}".format(Bot.format_dir(direction)))
        else:
            print("WALK {}".format(Bot.format_dir(direction)))

    def initialise(self):
        pass

    def run(self):
        """Run the bot."""
        self.done = False
        while not self.done:
            command = input()
            self.handle_command(command)

    def get_valid_dirs(self) -> List[Tuple[int, int]]:
        x, y = self.board.players[self.you]['pos']
        choices = ([(1, 0)] if x != 13 else []) \
                  + ([(0, 1)] if y != 13 else []) \
                  + ([(-1, 0)] if x != 1 else []) \
                  + ([(0, -1)] if y != 1 else [])
        choices = list(filter((lambda coord:
                               self.board.board[y + coord[1]][x + coord[0]]
                               == Tile.Empty),
                              choices))

        return choices

    @staticmethod
    def format_dir(coord: Tuple[int, int]):
        """Return a direction according to a coord"""
        dirs = {(0, -1): "UP", (0, 1): "DOWN",
                (-1, 0): "LEFT", (1, 0): "RIGHT",
                (0, 0): "STAY"}
        return dirs[coord]

    @staticmethod
    def format_coord(coord: Tuple[int, int]):
        """Return a properly formatted coordinate string."""
        return "(" + str(coord[0]) + ", " + str(coord[1]) + ")"

    @staticmethod
    def get_coord(coord_str: str) -> Tuple[int, int]:
        coord_strs = coord_str.split(',')
        return int(coord_strs[0][1:]), int(coord_strs[1][:-1])
Exemplo n.º 41
0
 def __init__(self):
     """Initialize instance variables."""
     self.board = Board((15, 15))
     self.done = False
     self.water_rounds = []
     self.you = None
Exemplo n.º 42
0
 def __init__(self):
     """Initialize instance variables."""
     self.ownBoard = Board((10, 10), None, own=True)
     self.enemyBoard = Board((10, 10), None, own=False)
     self.shipsToPlace = [[size, Ship(size).count] for size in Ship]
     self.lastCoord = (0, 0)
Exemplo n.º 43
0
    def __init__(self, master):
        set_params(["--parameters", "cargobot.txt"])
        self.path = params['GAME_BOARD']
        self.master = master
        self.generated_board = []
        self.initial_board = Board.Board(self.path, "init")
        self.final_board = Board.Board(self.path, "end")
        self.lift = Lift(self.path)
        self.width = 800
        self.height = 500
        master.title("Cargobot automatic programmer")
        frame0 = tk.Frame(master=master, width=self.width, height=50)
        frame0.pack()

        frame0_1 = tk.Frame(master=frame0, width=self.width // 2, height=50)
        frame0_1.pack(side="left")

        label_in = Label(frame0_1, text="Initial board")
        label_in.pack(side="left")

        frame0_2 = tk.Frame(master=frame0, width=self.width // 2, height=50)
        frame0_2.pack(side="right")

        label_fi = Label(frame0_2, text="Final board")
        label_fi.pack(side="right")

        frame1 = tk.Frame(master=master,
                          width=self.width,
                          height=self.height // 2)
        frame1.pack()

        frame1_1 = tk.Frame(master=frame1,
                            width=self.width // 2,
                            height=self.height // 2)
        frame1_1.pack(side="left")

        self.print_board(self.initial_board, frame1_1)

        frame1_2 = tk.Frame(master=frame1,
                            width=self.width // 2,
                            height=self.height // 2)
        frame1_2.pack(side="right")
        self.print_board(self.final_board, frame1_2)

        frame1_5_0 = tk.Frame(master=master, width=self.width, height=50)
        frame1_5_0.pack()

        label_in = Label(frame1_5_0, text="Generated result ")
        label_in.pack(side="left")

        frame2 = tk.Frame(master=master,
                          width=self.width,
                          height=self.height // 2)
        frame2.pack()

        self.frame2_1 = tk.Frame(master=frame2,
                                 width=int(self.width),
                                 height=self.height // 2)
        self.frame2_1.pack(side="left")

        frame3 = tk.Frame(master=master, width=self.width, height=50)
        frame3.pack()

        greet_button = Button(frame3,
                              text="Generate solution",
                              command=self.generate_solution)
        greet_button.pack()

        close_button = Button(frame3, text="Close", command=self.master.quit)
        close_button.pack()
Exemplo n.º 44
0
 def test_ATC_000_003(self):
     '''PC Down A Chess'''
     GameBoard = Board()
     PcPlayer = Pc(COLOR['WHITE'], GameBoard)
     bead = PcPlayer.DownBead()
     self.assertEqual(bead.Color, COLOR['WHITE'])
Exemplo n.º 45
0
def main():

    print('######################################################')
    print('Tobs Tic Tak Bots\n\n')
    print('Pick a type of Tic Tak Bot to Train and/or Play: ')
    print('(0) Uniformly Random')
    print('(1) Q Learn with Value Table')
    print('######################################################\n') 

    bot_num = int(input())

    if bot_num == 0:

        print('program this')

    if bot_num == 1:

        print('\nTrain against what other type:')
        print('(0) Uniformly Random')
        print('(1) Q Learn with Value Table\n')
        op_num = int(input())

        print('\nNumber Training Games, Learning Rate, Exploration rate? (Comma space seperated)')
        param = str(input())
        param = param.split(', ')
        param[0] = int(param[0])
        param[1] = float(param[1])
        param[2] = float(param[2])


        if op_num == 1:

            player0 = RLplayer(0, param[1], param[2])
            player1 = RLplayer(1, param[1], param[2])

            for _ in range(param[0]):
                board = Board()
                player0.update_board(board)
                player1.update_board(board)
                board.start_game(player0, player1)
                player0.update_values()
                player1.update_values() 
                print("\r\n{0}".format((float(_)/param[0])*100)),
                print('win percentage player0: ', player0.getWinPer())

            # Add win percentage data blah blah


            print('Would you like to play a game? [y/n]\n')
            a = str(input())

            if a == 'y':

                print('Change Learning Rate, Exploration rate to? (Comma space seperated)')
                n_l, e_l = [float(i) for i in str(input()).split(', ')]
                player0.changeRates(n_l, e_l)

                while a == 'y':

                    human = Human(1)
                    newGame = Board()
                    player0.update_board(newGame)
                    newGame.start_game(player0,human)
                    player0.update_values()

                    print('Another Game?')
                    a = str(input())
Exemplo n.º 46
0
agent1 = RandomAgent()
agent2 = RandomAgent()
moves = []

# Show progress bar if library is installed
# To install progress bar run this command: pip install tqdm
iterable = None
try:
    from tqdm import tqdm
    iterable = tqdm(range(NUMBER_EPESOIDS))
except:
    iterable = range(NUMBER_EPESOIDS)

for noGames in iterable:
    currentGame = Game(Board(7, 7), agent1, agent2)
    currentPair = currentGame.play()
    moves.append(currentPair)
    if (currentPair[1] == None):
        draw += 1
    else:
        if (currentPair[1] == agent1.getSide()):
            agent1Wins += 1
            if (agent1.getSide() == Side.SOUTH):
                agent1South += 1
            else:
                agent1North += 1
        elif (currentPair[1] == agent2.getSide()):
            agent2Wins += 1
            if (agent2.getSide() == Side.SOUTH):
                agent2South += 1
Exemplo n.º 47
0
class Bot():
    def __init__(self):
        """Initialize instance variables."""
        self.ownBoard = Board((10, 10), None, own=True)
        self.enemyBoard = Board((10, 10), None, own=False)
        self.shipsToPlace = [[size, Ship(size).count] for size in Ship]
        self.lastCoord = (0, 0)

    def handle_result(self, text):
        """Handle the server's result message."""
        if text.find("RESULT HIT") != -1:
            self.enemyBoard.set(self.lastCoord, Tile.Ship)

    def handle_update(self, text):
        """Handle the server's update message."""
        if text.find("RESULT GOTISLAND"):
            tokens = text.strip().split()
            coord = (int(re.sub("\D", "",
                                tokens[2])), int(re.sub("\D", "", tokens[3])))
            self.ownBoard.set(coord, Tile.Island)

    def handle_command(self, text):
        """Handle the server's message."""
        tokens = text.strip().split()
        if tokens[0] == 'REQUEST' and tokens[1] == 'ACTION':
            if tokens[2] == 'SHIP':
                location = self.choose_ship_location()
                self.place_ship(location[0], location[1])
            if tokens[2] == 'ISLAND':
                coord = self.choose_island_location()
                self.place_island(coord)
            if tokens[2] == 'SHOT':
                coord = self.choose_shot_location()
                self.shoot(coord)
        if tokens[0] == 'RESULT':
            self.handle_result(text)
        if tokens[0] == 'UPDATE':
            self.handle_update(text)
        if tokens[0] == 'GAME' and tokens[1] == 'RESULT':
            self.done = True

    def choose_ship_location(self):
        """Return a location where a ship should be placed."""
        raise NotImplementedError(
            "You need to implement your own choose_ship_location method.")

    def choose_ship_size(self):
        """"Return a ship size that can be placed on the board."""
        shipSize = 0
        for index, (size, count) in enumerate(self.shipsToPlace):
            if count > 0:
                self.shipsToPlace[index][1] -= 1
                return self.shipsToPlace[index][0]
        return shipSize

    def choose_island_location(self):
        """Return the next island's location."""
        self.placementIndex += 1
        return (int(self.placementIndex / 10), self.placementIndex % 10)

    def choose_shot_location(self):
        """Return the next shot's location."""
        self.placementIndex += 1
        return (int(self.placementIndex / 10), self.placementIndex % 10)

    @staticmethod
    def formatCoord(coord):
        """Return a properly formatted coordinate string."""
        return "(" + str(coord[0]) + "," + str(coord[1]) + ")"

    def place_ship(self, start, end):
        """Print a command to stdout with the next ship's desired coordinates."""
        success = self.ownBoard.placeShip(start, end)
        if not success[0]:
            raise Exception("Illegal ship placement: {0}.", success[1])
        start = "(" + str(start[0]) + "," + str(start[1]) + ")"
        end = "(" + str(end[0]) + "," + str(end[1]) + ")"
        print("PLACE SHIP", start, end)
        sys.stdout.flush()  #Nodig?

    def place_island(self, coord):
        """Print a command to stdout with the next island's desired coordinates."""
        success = self.enemyBoard.placeIsland(coord)
        if not success:
            raise Exception("Illegal island placement.")
        coord = Bot.formatCoord(coord)
        print("PLACE ISLAND", coord)

    def shoot(self, coord):
        """Print a command to stdout with the next shot's desired coordinates."""
        self.lastCoord = coord
        coord = Bot.formatCoord(coord)
        print("SHOOT", coord)

    def run(self):
        """Run the bot."""
        self.done = False
        while self.done != True:
            command = input()
            self.handle_command(command)
Exemplo n.º 48
0
def initial_state():
    state = Board(1, 4)
    return state