diff --git a/board.py b/board.py index 0f1d701..2e0543c 100644 --- a/board.py +++ b/board.py @@ -130,10 +130,34 @@ class Board: (idx, idx + (die * player))): return True return False + + @staticmethod + def num_of_checkers_for_player(board,player): + return player * sum([board[idx] for idx in Board.idxs_with_checkers_of_player(board, player)]) @staticmethod - def is_winner(board, player): - return Board.idxs_with_checkers_of_player(board, player) == [] + def outcome(board): + def all_checkers_in_first_quadrant(player): + checker_idxs = Board.idxs_with_checkers_of_player(board, player) + if player == 1: + return all([(idx <= 6) for idx in checker_idxs]) + else: + return all([(idx >= 19) for idx in checker_idxs]) + winner = None + + for player in [1, -1]: + if Board.idxs_with_checkers_of_player(board, player) == []: + winner = player + + if winner == None: + return None + + #backgammon = all_checkers_in_first_quadrant(-winner) + gammon = Board.num_of_checkers_for_player(board, -winner) == 15 + score = 2 if gammon else 1 + return {winner: score, -winner: -score} + + @staticmethod def calculate_legal_states(board, player, roll): diff --git a/test.py b/test.py index 6581eff..4324624 100644 --- a/test.py +++ b/test.py @@ -131,6 +131,26 @@ class TestIsMoveValid(unittest.TestCase): # TODO: More tests for bearing off are needed +class TestNumOfChecker(unittest.TestCase): + def test_simple_1(self): + board = ( 0, + 2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 5, + 0, 0, 0, 0, 3, 0, + 4, 0, 1, 0, 0, 0, + 0 ) + self.assertEqual(Board.num_of_checkers_for_player(board,1), 2+5+3+4+1) + self.assertEqual(Board.num_of_checkers_for_player(board,-1), 0) + + board = ( 0, + -2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, -5, + 0, 0, 0, 0, -3, 0, + -4, 0, -1, 0, 0, 0, + 0 ) + self.assertEqual(Board.num_of_checkers_for_player(board,-1), 2+5+3+4+1) + self.assertEqual(Board.num_of_checkers_for_player(board,1), 0) + class TestIsWinner(unittest.TestCase): def test_is_winner(self): board = ( 0, @@ -139,8 +159,7 @@ class TestIsWinner(unittest.TestCase): 0, 0, 0, 0, 3, 0, 4, 0, 1, 0, 0, 0, 0 ) - self.assertEqual(Board.is_winner(board, 1), False) - self.assertEqual(Board.is_winner(board, -1), True) + self.assertEqual(Board.outcome(board), {1: -2, -1: 2}) board = ( 0, 0, 0, 0, -1, 0, -4, @@ -148,8 +167,23 @@ class TestIsWinner(unittest.TestCase): -5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0 ) - self.assertEqual(Board.is_winner(board, 1), True) - self.assertEqual(Board.is_winner(board, -1), False) + self.assertEqual(Board.outcome(board), {1: 2, -1: -2}) + + board = ( 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, -2, + 0 ) + self.assertEqual(Board.outcome(board), {1: 1, -1: -1}) + + board = ( 0, + 2, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 5, + 0, 0, 0, 0, 3, 0, + 5, 0, 0, 0, 0, 0, + 0 ) + self.assertEqual(Board.outcome(board), {1: -2, -1: 2}) class TestDoMove(unittest.TestCase): def test_simple_move(self):