Exemplo n.º 1
0
 def test_draw_and_check_no_match(self):
     game_state = GameState(1)
     domino = Domino(2, 3)
     game_state.dominoes.append(domino)
     player = Player(0, TestBot())
     self.assertFalse(game_state.draw_domino_and_check_for_start(player, Domino(12, 12)))
     self.assertEqual(1, len(player.dominoes))
     self.assertEqual(domino, player.dominoes.pop())
Exemplo n.º 2
0
    def h(self, game: GameState):
        if game.terminal():
            return game.winner()

        for _ in range(self.nbr_rollouts):
            self.do_rollout(game)

        return self.h_score(self.choose(game))
Exemplo n.º 3
0
 def test_draw_domino(self):
     game_state = GameState(1)
     domino = Domino(2, 3)
     game_state.dominoes.append(domino)
     player = Player(0, TestBot())
     self.assertTrue(game_state.draw_domino(player))
     self.assertEqual(1, len(player.dominoes))
     self.assertEqual(domino, player.dominoes.pop())
Exemplo n.º 4
0
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map1 = '../game_states/game1_cake.json'
        self.game_state1 = GameState(self.map1)
        self.ih1 = InputHandler(self.game_state1)
Exemplo n.º 5
0
 def _simulate(self, node: GameState):
     "Returns the reward for a random simulation (to completion) of `node`"
     invert_reward = True
     while True:
         if node.terminal():
             reward = node.reward()
             return 1 - reward if invert_reward else reward
         node = node.push(node.random_move())
         invert_reward = not invert_reward
Exemplo n.º 6
0
 def test_draw_and_check_match(self):
     game_state = GameState(1)
     # This is the next tile that the player will draw after drawing and placing the starting tile
     domino = Domino(2, 3)
     game_state.dominoes.append(domino)
     game_state.dominoes.append(Domino(12, 12))
     player = Player(0, TestBot())
     self.assertTrue(game_state.draw_domino_and_check_for_start(player, Domino(12, 12)))
     self.assertEqual(1, len(player.dominoes))
     self.assertEqual(domino, player.dominoes.pop())
Exemplo n.º 7
0
 def test_place_domino(self):
     game_state = GameState(1)
     player = Player(0, TestBot())
     domino = Domino(2, 3)
     player.dominoes.append(domino)
     train = Train(0, 2, player)
     game_state.place_domino(train, domino, player)
     self.assertEqual(0, len(player.dominoes))
     self.assertEqual(domino, game_state.played.pop())
     self.assertEqual(1, game_state.played_count[2])
     self.assertEqual(1, game_state.played_count[3])
     self.assertEqual(0, game_state.played_count[0])
Exemplo n.º 8
0
    def choose(self, node: GameState):
        def score(n):
            if self.N[n] == 0:
                return float("-inf")  # avoid unseen moves
            return self.Q[n] / self.N[n]  # average reward

        "Choose the best successor of node. (Choose a move in the game)"
        if node.terminal():
            raise RuntimeError(f"choose called on terminal node {node}")

        if node not in self.children:
            return node.random_child()

        return max(self.children[node], key=score)
Exemplo n.º 9
0
 def enter_pressed(self, e):
     try:
         GameState(join(parent_path, self.tkvar.get()))
         self.retun_val = self.tkvar.get()
         self.window.destroy()
     except Exception as e:
         self.label.config(text='' + str(e))
Exemplo n.º 10
0
class Application:
    def __init__(self):
        self.running = True
        self.window = Window(self, 900, 600, 'Boxes')
        self.game_state = GameState(self)

    def run(self):
        """
        Main function of the game
        :return: None
        """
        self.window.init()
        self.game_state.preupdate()

        while self.running:
            self.game_state.update()
            self.window.display()
Exemplo n.º 11
0
def run():
    try:
        config_files = MainUtils.get_config_files()
        game_state_file = _select(config_files, "the game")
        game_state = GameState(MainUtils.get_game_state_path(game_state_file))
        game = GameConsole(game_state)
        game.run_console()
    except GameStateFileException as e:
        print(f"Failed to read game configuration file: {e}")
Exemplo n.º 12
0
 def do_rollout(self, node: GameState):
     node = node.__copy__()
     "Make the tree one layer better. (Train for one iteration.)"
     path = self._select(node)
     leaf = path[-1]
     self._expand(leaf)
     if self.heuristic is None:
         reward = self._simulate(leaf.__copy__())
     else:
         reward = self.heuristic.h(node)
     self._backpropagate(path, reward)
Exemplo n.º 13
0
 def __init__(self):
     """!
     @pre none
     @post The members of the Battleship object are initialized, including the game view and state. The number of ships and opponent are determined and stored in the game state.
     """
     self.view = BattleshipView()
     self.gs = GameState()
     self.gs.msg = "Awaiting number of ships..."
     self.view.draw(self.gs)
     self.gs.numShipsPerPlayer = self.view.get_num_ships()
     self.gs.playerType = self.view.get_player_type()
     if not self.gs.playerType == 1:
         self.AI = AI(self.gs.playerType)
Exemplo n.º 14
0
    def action(self, game: GameState):
        if game.game_over():
            return None

        possibleMoves = game.legal_moves()
        boards = game.children()

        win_h = self.win_heuristic(boards)
        if not win_h == -1:
            return possibleMoves[win_h], 1

        evals = self.heuristic.hs(boards)
        evals = self.default_heuristic(boards, evals)

        if self.variance:
            if not game.turn():
                evals = [1 - e for e in evals]
            total = sum(evals)
            evals = [e / total for e in evals]
            choice = random.random()
            s = 0
            for idx, e in enumerate(evals):
                s += e
                if choice <= s:
                    bestIdx = idx
                    break

        else:
            if game.turn():
                bestIdx = np.argmax(evals)
            else:
                bestIdx = np.argmin(evals)

        bestMove = possibleMoves[bestIdx]

        return bestMove, evals[bestIdx]
Exemplo n.º 15
0
    def play(next_bet: Callable[[GameState], Optional[Bet]],
             end_of_game: Callable[[GameState], bool] = ExitStrategy.exit,
             initial_units: int = 1000) -> GameState:
        state = GameState.initial_state(initial_units)
        bet = next_bet(state)

        while state.can_play(bet) and not end_of_game(state):
            state = state.place_bets(bet)
            winning_number = Roulette.roll()
            state = state.end_of_round(
                winning_number,
                Roulette.evaluate(state.bet.selection, winning_number)
                if bet else 0)
            bet = next_bet(state)

        return state
Exemplo n.º 16
0
    def play(self, game: GameState, verbose=False):
        if self.alternate:
            temp = self.actionModel1
            self.actionModel1 = self.actionModel2
            self.actionModel2 = temp

        states = []
        hs = []

        if verbose:
            print(game)

        while not game.game_over():
            actingModel = self.actionModel1 if game.turn() else self.actionModel2
            move, h = actingModel.action(game)
            states.append(game.__copy__())
            hs.append(h)
            game.push(move)

            if verbose:
                print("move: " + str(move) + " h: " + str(h))
                print(game)

        return game.winner(), states, hs
Exemplo n.º 17
0
def init_game(game_path):
    game_state = GameState(game_path)
    return GameGUI(game_state)
Exemplo n.º 18
0
 def action(self, game: GameState):
     print(game.__str__())
     moves = game.legal_moves()
     print(game.moves_str())
     inp = int(input())
     return moves[inp], 0
Exemplo n.º 19
0
class Game:
    """
    The Game of Mexican Train! Yay! \m/
    """

    def __init__(self, player_count):
        """
        Create a Game for the specified number of players.
        :param player_count: How many players are playing.
        """
        self.game_state = GameState(player_count)

    def play(self, print_each_round=False):
        """
        Play the game!
        :param print_each_round: Flag to print out the results of each round.
        """
        for cur_round in range(12, -1, -1):
            self.game_state.start_round(cur_round)
            self.play_round()
            if print_each_round:
                self.print_round(cur_round)
            self.game_state.clean_up_after_round()

    def play_round(self):
        """
        Play the current round.
        """
        while not self.game_state.round_over:
            self.take_turn()
            self.check_for_victory()
            self.game_state.next_player()

    def take_turn(self):
        """
        Take a turn for the current active player, as determined by the GameState.
        """
        player = self.game_state.current_player
        player.can_play = True
        bot_game_state = BotGameState(self.game_state, player)

        drew = False
        played = False
        done = False
        first = player.turn == 0

        player.bot.start_turn(player.turn)
        while not done:
            valid_moves = bot_game_state.get_all_valid_moves()
            if len(valid_moves) == 0:
                if not played and not drew:
                    domino = self.game_state.draw_domino(player)
                    if not domino:
                        player.can_play = False
                        done = True
                    else:
                        bot_game_state.draw_domino(domino)
                    drew = True
                else:
                    done = True
            else:
                move = player.bot.get_move(bot_game_state)
                if not self.validate_move(move, player):
                    player.bot.report_invalid_move(move)
                    shuffle(valid_moves)
                    move = valid_moves.pop()
                if move.domino.is_double:
                    drew = False
                    played = False
                else:
                    played = True
                self.do_move(player, move)
                bot_game_state.do_move(move)
                if played and not first:
                    done = True
        player.turn += 1

    def validate_move(self, move: BotMove, player: Player) -> bool:
        """
        Validate if a move can be played.
        :param move: The move to attempt
        :param player: The player attempting the move
        :return: True if the move is legal, False otherwise.
        """
        return self.get_train_from_move(move).is_valid_play(move.domino, player) and \
            player.dominoes.count(move.domino) > 0 and \
            self.game_state.played.count(move.domino) == 0

    def get_train_from_move(self, move: BotMove) -> Train:
        """
        Helper method to extract the train from the game state for a given BotMove.
        This is required as the BotMove only contains a reference to the BotTrain.
        :param move: The BotMove to get the train for.
        :return: The corresponding Train.
        """
        return self.game_state.trains[move.train.identity.train_id]

    def do_move(self, player: Player, move: BotMove):
        """
        Actually execute a move!
        :param player: The player making the move.
        :param move: The move the player is attempting to make.
        :return: True if the move was executed successfully.
        """
        if player.dominoes.count(move.domino) == 0:
            raise RuntimeError(
                "Cannot add Domino that player doesn't have! \n Move: {} \n Dominoes {} \n {} \n Played {}".
                format(move, player.dominoes, self.get_train_from_move(move), self.game_state.played))
        if self.game_state.played.count(move.domino) > 0:
            raise RuntimeError(
                "Cannot play a domino that has already been played! \n Move: {} \n Dominoes {} \n {} \n Played {}".
                format(move, player.dominoes, self.get_train_from_move(move), self.game_state.played))
        train = self.get_train_from_move(move)
        if train.add_domino(move.domino, player):
            player.dominoes.remove(move.domino)
            self.game_state.played.append(move.domino)
            return True
        return False

    def check_for_victory(self):
        """
        Check to see if somebody has won. If so tell every player that the round is over.
        """
        player = self.game_state.current_player
        if len(player.dominoes) == 0:
            self.game_state.round_over = True
            self.game_state.round_winner = player
            for p in self.game_state.players:
                p.end_round(p == player)
        else:
            all_cannot_play = True
            for player in self.game_state.players:
                if player.can_play:
                    all_cannot_play = False
                    break
            if all_cannot_play:
                inter_players = iter(self.game_state.players)
                min_player = next(inter_players)
                min_player.score += min_player.calc_score()
                for p in inter_players:
                    if len(p.dominoes) < len(min_player.dominoes) or \
                            (len(p.dominoes) == len(min_player.dominoes) and p.calc_score() < min_player.calc_score()):
                        min_player = p
                self.game_state.round_over = True
                self.game_state.round_winner = min_player
                for p in self.game_state.players:
                    p.end_round(p == min_player)

    def print_round(self, round_numb: int):
        """
        Format the output for the round and print it to the console.
        :param round_numb: The current round number.
        """
        output = "Mexican Train! - Round {} Winner: Player {}!\n". \
            format(round_numb, str(self.game_state.round_winner.identity.id))
        output += '\n'.join([str(player) for player in self.game_state.players])
        output += '\n'
        output += '\n'.join([str(train) for train in self.game_state.trains])
        output += '\n===========================================\n\n'
        print(output)

    def get_stats(self):
        """
        Create a map of player ID to victories + score, for tracking across multiple games.
        :return:
        """
        return {player.identity.id: [player.victories, player.score] for player in self.game_state.players}
Exemplo n.º 20
0
 def test_draw_and_check_none_to_draw(self):
     game_state = GameState(1)
     player = Player(0, TestBot())
     # Need to use a lambda here or the test just fails with the RuntimeError
     self.assertRaises(RuntimeError, lambda: game_state.draw_domino_and_check_for_start(player, Domino(12, 12)))
     self.assertEqual(0, len(player.dominoes))
Exemplo n.º 21
0
 def test_draw_domino_none_to_draw(self):
     game_state = GameState(1)
     player = Player(0, TestBot())
     self.assertFalse(game_state.draw_domino(player))
     self.assertEqual(0, len(player.dominoes))
Exemplo n.º 22
0
 def _expand(self, node: GameState):
     "Update the `children` dict with the children of `node`"
     if node in self.children:
         return  # already expanded
     self.children[node] = set(node.children())
Exemplo n.º 23
0
 def h_score(self, game: GameState):
     s = self._score(game)
     return 1 - s if game.turn() else s
Exemplo n.º 24
0
 def __init__(self):
     self.running = True
     self.window = Window(self, 900, 600, 'Boxes')
     self.game_state = GameState(self)
Exemplo n.º 25
0
 def __init__(self, player_count):
     """
     Create a Game for the specified number of players.
     :param player_count: How many players are playing.
     """
     self.game_state = GameState(player_count)
Exemplo n.º 26
0
from src.Expectimax import Expectimax

# Parsing command line arguments
parser = argparse.ArgumentParser()

parser.add_argument('-s', dest='size', type=int)
parser.add_argument('-b', dest='blanks', action='store_true')
parser.add_argument('-e', dest='expectimax', action='store_true')
parser.add_argument('-p', dest='prune', action='store_true')
results = parser.parse_args()

if not results.size:
    results.size = 15

rules = ScrabbleRules(blanks=results.blanks, size=results.size)
state = GameState(blanks=results.blanks, size=results.size)
view = View()

agent_0 = Agent()
agent_1 = Agent()
state.add_agent(0, agent_0)
state.add_agent(1, agent_1)
state.place('A', [(results.size // 2, results.size // 2)], 0, rules)
state.draw(0)
state.draw(1)

# Play
agents = [0, 1]
try:
    while True:
        for agent in agents:
Exemplo n.º 27
0
 def test_draw_and_check_match_last_tile(self):
     game_state = GameState(1)
     game_state.dominoes.append(Domino(12, 12))
     player = Player(0, TestBot())
     self.assertTrue(game_state.draw_domino_and_check_for_start(player, Domino(12, 12)))
     self.assertEqual(0, len(player.dominoes))