Esempio n. 1
0
def test_white_is_not_taken_when_it_has_a_liberty():
    goban = Goban([
        '...',
        '#o#',
        '.#.',
    ])

    assert goban.is_taken(1, 1) is False
Esempio n. 2
0
    def setUp(self):
        self.goban = Goban()
        self.goban.votes = {}
        self.goban.vote_random = MagicMock()

        self.a1_move = Move('a1')
        self.a2_move = Move('a2')
        self.random_move = Move('random')
Esempio n. 3
0
def test_white_is_taken_when_surrounded_by_black():
    goban = Goban([
        '.#.',
        '#o#',
        '.#.',
    ])

    assert goban.is_taken(1, 1) is True
Esempio n. 4
0
def test_black_shape_is_taken_when_surrounded():
    goban = Goban([
        'oo.',
        '##o',
        'o#o',
        '.o.',
    ])

    assert goban.is_taken(0, 1) is True
    assert goban.is_taken(1, 1) is True
    assert goban.is_taken(1, 2) is True
Esempio n. 5
0
def test_black_shape_is_not_taken_when_it_has_a_liberty():
    goban = Goban([
        'oo.',
        '##.',
        'o#o',
        '.o.',
    ])

    assert goban.is_taken(0, 1) is False
    assert goban.is_taken(1, 1) is False
    assert goban.is_taken(1, 2) is False
Esempio n. 6
0
def test_square_shape_is_taken():
    goban = Goban([
        'oo.',
        '##o',
        '##o',
        'oo.',
    ])

    assert goban.is_taken(0, 1) is True
    assert goban.is_taken(0, 2) is True
    assert goban.is_taken(1, 1) is True
    assert goban.is_taken(1, 2) is True
Esempio n. 7
0
class PlayerInterface():
    def __init__(self, color, board_size):
        self.goban = Goban(board_size)
        self.color = color
        self._opponent = self.goban.invert_color(self.color)

    def __str__(self):
        return f"Player: {self.getPlayerName()}"

    def getPlayerName(self):
        """
        Returns your player name, as to be displayed during the game.
        """
        return NotImplementedError

    def getPlayerMove(self):
        """
        Returns your move. The move must be a couple of two integers,
        which are the coordinates of where you want to put your piece on the board.
        Coordinates are the coordinates given by the Reversy.py methods (e.g. validMove(board, x, y)
        must be true of you play '(x,y)') You can also answer (-1,-1) as "pass".
        Note: the referee will nevercall your function if the game is over
        """
        return (-1, -1)

    def playOpponentMove(self, x, y):
        """Inform you that the oponent has played this move. You must play it with no search 
        (just update your local variables to take it into account)
        """
        pass
Esempio n. 8
0
class Game(db.Model):
    size = db.IntegerProperty(required=True)
    black = db.StringProperty()
    white = db.StringProperty()
    black_caught = db.IntegerProperty(default=0)
    white_caught = db.IntegerProperty(default=0)
    turn_count = db.IntegerProperty(default=1)
    pass_count = db.IntegerProperty(default=0)
    data = db.TextProperty()
    prev_data = db.TextProperty()
    created_at = db.DateTimeProperty(auto_now_add=True)
    updated_at = db.DateTimeProperty(auto_now=True)

    @property
    def turn(self):
        logging.info(self.turn_count)
        return Goban.black if self.turn_count % 2 else Goban.white

    @property
    def turn_label(self):
        return u'黒' if self.turn is Goban.black else u'白'

    def touch(self, x, y):
        self._ensure_goban_object()
        caught = self.goban_object.touch(x, y, self.turn)
        if self.is_kou():
            raise Goban.Untouchable()
        if self.turn is Goban.black:
            self.white_caught += caught
        else:
            self.black_caught += caught
        self.prev_data = self.data
        self.data = simplejson.dumps(self.goban_object.data)
        self.turn_count += 1
        self.pass_count = 0

    def pass_touch(self):
        self.prev_data = self.data
        self.turn_count += 1
        self.pass_count += 1

    def render(self):
        self._ensure_goban_object()
        buffer = StringIO()
        self.goban_object.render(buffer, html=True)
        return buffer.getvalue()
        
    def _ensure_goban_object(self):
        if not hasattr(self, 'goban_object'):
            self.goban_object = Goban(self.size)
            if self.data is not None:
                self.goban_object.data = simplejson.loads(self.data)

    def is_kou(self):
        if self.prev_data is None: return False
        prev_goban_object = Goban(self.size)
        prev_goban_object.data = simplejson.loads(self.prev_data)
        return self.goban_object.is_kou(prev_goban_object)
Esempio n. 9
0
 async def start(self, size):
     size = int(size[1:-1])
     if (size >= 2):
         g = Goban(size)
         self.goban = g
         self.scorer = None
         self.game_state = GameState.STARTED
         await self.update()
     else:
         await self.channel.send("Please select at least a goban of size 2")
Esempio n. 10
0
def evaluate(model1_path, model2_path, rounds, device="cpu"):
    win1, win2 = 0, 0
    # Turn verbosity off
    sys.stdout = open(os.devnull, 'w')

    for _round in range(rounds):
        goban = Goban(GOBAN_SIZE)
        # Random color asignment
        color1 = random.choice([Goban._BLACK, Goban._WHITE])
        color2 = goban.invert_color(color1)
        p1 = AlphaZeroPlayer(color1, GOBAN_SIZE, model1_path)
        p2 = AlphaZeroPlayer(color2, GOBAN_SIZE, model2_path)

        winner = play(p1, p2, goban, verbose=False)

        if winner == color1:
            win1 += 1
        elif winner == color2:
            win2 += 1

    # Turn verbosity on
    sys.stdout = sys.__stdout__
    return win1 / rounds
Esempio n. 11
0
class TestVoteMove(unittest.TestCase):
    def setUp(self):
        self.goban = Goban()
        self.goban.votes = {}
        self.goban.vote_random = MagicMock()

        self.a1_move = Move('a1')
        self.a2_move = Move('a2')
        self.random_move = Move('random')

    def test_vote_succeeds(self):
        self.goban.is_valid = MagicMock(return_value=True)

        vote_move_result = self.goban.vote_move(self.a1_move, 'user')

        self.assertEqual(self.goban.votes['user'], self.a1_move)
        self.assertEqual(vote_move_result, 'Voted for `A1`.')

    def test_invalid_move(self):
        self.goban.is_valid = MagicMock(return_value=False)

        vote_move_result = self.goban.vote_move(self.a1_move, 'user')

        self.assertEqual(self.goban.votes, {})
        self.assertEqual(vote_move_result, '`A1` seems to be an invalid move.')

    def test_already_voted(self):
        self.goban.is_valid = MagicMock(return_value=True)
        self.goban.votes = {'user': self.a1_move}

        vote_move_result = self.goban.vote_move(self.a1_move, 'user')

        self.assertEqual(self.goban.votes['user'], self.a1_move)
        self.assertEqual(vote_move_result, "You've already voted for `A1`!")

    def test_change_vote(self):
        self.goban.is_valid = MagicMock(return_value=True)
        self.goban.votes = {'user': self.a2_move}

        vote_move_result = self.goban.vote_move(self.a1_move, 'user')

        self.assertEqual(self.goban.votes['user'], self.a1_move)
        self.assertEqual(vote_move_result, 'Changed vote from `A2` to `A1`!')

    def test_vote_random(self):
        self.goban.vote_move(self.random_move, 'user')

        self.goban.vote_random.assert_called_with('user', self.random_move.hidden)
Esempio n. 12
0
 def is_kou(self):
     if self.prev_data is None: return False
     prev_goban_object = Goban(self.size)
     prev_goban_object.data = simplejson.loads(self.prev_data)
     return self.goban_object.is_kou(prev_goban_object)
Esempio n. 13
0
 def _ensure_goban_object(self):
     if not hasattr(self, 'goban_object'):
         self.goban_object = Goban(self.size)
         if self.data is not None:
             self.goban_object.data = simplejson.loads(self.data)
Esempio n. 14
0
    args = parser.parse_args()

    tf.get_logger().setLevel('INFO')

    saves_path_best_folder = os.path.join("saves", args.name, "best")
    os.makedirs(saves_path_best_folder, exist_ok=True)
    saves_path_best = os.path.join(saves_path_best_folder, "model")

    saves_path_current_folder = os.path.join("saves", args.name, "current")
    os.makedirs(saves_path_current_folder, exist_ok=True)
    saves_path_current = os.path.join(saves_path_current_folder, "model")

    best_mcts = None
    for round_idx in range(1, 1 + TRAIN_ROUNDS):
        print("Starting round: ", round_idx)
        starting_goban = Goban(GOBAN_SIZE)
        current_mcts = MCTS(GOBAN_SIZE)
        current_mcts.train(starting_goban,
                           N_EPISODES,
                           N_EPOCHS,
                           FIT_EVERY_EPISODE,
                           BATCH_SIZE,
                           learning_rate=LEARNING_RATE,
                           verbose=True)

        if round_idx % EVALUATE_EVERY_ROUND == 0:
            if best_mcts is not None:
                print("End of round, evaluating mcts...")
                current_mcts.model.save_weights(saves_path_current)

                win_ratio = evaluate(saves_path_current, saves_path_best,
Esempio n. 15
0
 def load_goban(self) -> Goban:
     try:
         with open(self.STATE_FILE_NAME, 'rb') as file:
             return load(file)
     except FileNotFoundError:
         return Goban()
Esempio n. 16
0
 def __init__(self, color, board_size):
     self.goban = Goban(board_size)
     self.color = color
     self._opponent = self.goban.invert_color(self.color)
Esempio n. 17
0
    def test_move(self):
        g = Goban(3, handicap=["aa", "ab", "ac", "ba", "bc", "cc", "cb", "bc", "ca"])

        g.move("w", "bb")

        print(g.history)
Esempio n. 18
0
def test():
    from goban import Goban, Stone
    g = Goban(5)
    g.play([0, 0], Stone.WHITE)
    g.play([2, 0], Stone.BLACK)
    g.play([3, 0], Stone.WHITE)
    g.play([0, 1], Stone.BLACK)
    g.play([1, 1], Stone.BLACK)
    g.play([2, 1], Stone.BLACK)
    g.play([3, 1], Stone.WHITE)
    g.play([4, 1], Stone.WHITE)
    g.play([0, 2], Stone.WHITE)
    g.play([2, 2], Stone.BLACK)
    g.play([3, 2], Stone.WHITE)
    g.play([0, 3], Stone.BLACK)
    g.play([1, 3], Stone.BLACK)
    g.play([3, 3], Stone.WHITE)
    g.play([1, 4], Stone.BLACK)
    g.play([3, 4], Stone.WHITE)
    g.play([4, 4], Stone.BLACK)
    g.play([1, 2], Stone.BLACK)
    g.play([1, 0], Stone.BLACK)
    g.play([4, 3], Stone.WHITE)
    scorer = Scorer(g)
    scorer.kill([0, 0])
    scorer.kill([4, 4])
    print(scorer.count_territory())
    scorer.display()
    import pdb
    pdb.set_trace()
Esempio n. 19
0
        goban.play((x, y, next_player.color))
        other_player.playOpponentMove(x, y)

        # Invert players
        next_player, other_player = other_player, next_player

    if verbose:
        print(goban)
        print("The game is over")
    nbblacks, nbwhites = goban.get_score()
    winner = goban.get_winner()
    if verbose:
        print("Time:", totalTime)
        print("Winner: ", end="")
        if winner == goban._WHITE:
            print("WHITE")
        elif winner == goban._BLACK:
            print("BLACK")
        else:
            print("DEUCE")
        print("Final is: ", nbwhites, "whites and ", nbblacks, "blacks")
    return winner


if __name__ == "__main__":
    goban = Goban()
    model_path = "saves/test1/best/model"  # not well trained
    player1, player2 = AlphaZeroPlayer(
        goban._WHITE, goban.get_board_size(), model_path), MCTSPlayer(goban._BLACK, goban.get_board_size())
    play(player1, player2, goban)