Example #1
0
    def run(self):

        if len(self.argv) == 1:
            self.help()
            return

        command = self.argv[1]

        if command == "play":
            self.game = Game(0, 10, "random", 20)
            self.game.run()

        elif command == "graph":
            nb_npc = int(self.argv[2])
            stack_size = int(self.argv[3])
            min_pop = int(self.argv[4])
            max_pop = int(self.argv[5])

            self.game = Game(0, nb_npc, "random", stack_size, min_pop, max_pop)
            self.grapher = Grapher(self.game)
            self.graph = self.grapher.all_paths()

            file_name = str(nb_npc) + "." + str(stack_size) + "." + str(
                min_pop) + "." + str(max_pop) + ".pdf"
            Grapher.draw_pdf(self.graph, file_name)
Example #2
0
    def __init__(self):
        """
        Инициализация объекта
        """

        self.allowed_users_id_for_final = {}

        self.qualifying_game = Game(Room.DEFAULT_NAME, self)
        self.final_game = Game(Room.FINAL_NAME, self)
Example #3
0
def main() -> None:
    ai_vs_ai = False if input("AI vs Human, AI vs AI [0,1]") == str(
        0) else True
    if (ai_vs_ai):
        game = Game()
        game.play_ia_vs_ia()
    else:
        ai_player = 1 if input("AI plays first? [Y/n]") != "n" else 2
        game = Game(ai_player)
        game.play()
Example #4
0
    def test_overwriting_transposition_dict(
            self, clean_tree_search_caches_before_tests):
        game = Game()
        best_moves = get_legal_abstract_moves(game.player_1, False)[0:1]

        store_in_transposition_dict(best_moves, 20, EvaluationType.exact,
                                    game.player_1, 2, False)

        # We should never overwrite an exact evaluation
        store_in_transposition_dict([], 50, EvaluationType.beta_cutoff,
                                    game.player_1, 3, False)

        # We should never overwrite an evaluation with higher depth
        store_in_transposition_dict([], 50, EvaluationType.beta_cutoff,
                                    game.player_1, 1, False)

        stored_moves, stored_score, _ = get_best_move_from_transposition_dict(
            game.player_1, 1, False, 0, 0)
        assert len(stored_moves) == 1
        assert stored_score == 20

        store_in_transposition_dict([], 30, EvaluationType.exact,
                                    game.player_1, 4, False)

        _, stored_score, _ = get_best_move_from_transposition_dict(
            game.player_1, 1, False, 0, 0)
        assert stored_score == 30
Example #5
0
def handle_command(command, channel, user):
    """
		Receives commands directed at the bot and determines if they
		are valid commands. If so, then acts on the commands. If not,
		returns back what it needs for clarification.
	"""

    if command.startswith('start game'):
        print "{} started a game".format(user)
        send_message("Generating map...", channel)
        games[user] = Game()
        send_message(
            "Game started! Type `end game` to stop. Don't forget to use the `help` command!",
            channel)
        send_message(
            "You wake up in a stone dungeon. It seems like you were " +
            "chained to the wall but something or someone broke you" +
            " break from it. Although you don't remember much about" +
            " how you got hear, you do remember one thing: " +
            "You need to escape the *Coveo Lab*", channel)
    elif command.startswith('end game'):
        games.pop(user, None)
        send_message("Game stopped. You can now start a new one.", channel)
    elif user in games:
        send_message(games[user].update(command), channel)
    else:
        send_message("Please type the command `start game` to play", channel)
Example #6
0
def test_devvic():
    g = Game(random_init=False)
    g.dev_cards_discovered[0, defines.DEV_VICTORYPOINT] = 2
    g.dev_cards_discovered[2, defines.DEV_VICTORYPOINT] = 3

    print(g.dev_cards_discovered)
    print(g.get_victory_points())
Example #7
0
    def test_player_must_use_last_piece(self, clean_tree_search_caches_before_tests):
        # Here we set up a scenario where player 1 can win by playing his last available piece
        # If he plays a 3 at (2, 4), he wins
        game = Game()
        game.starting_player = game.player_2

        one = game.player_1.get_piece_by_type(PieceType.one)
        one.set_movement_direction(Direction.north)
        game.board.get_tile(3, 3).place_piece(one)

        two = game.player_1.get_piece_by_type(PieceType.two)
        two.set_movement_direction(Direction.east)
        game.board.get_tile(3, 2).place_piece(two)

        four = game.player_1.get_piece_by_type(PieceType.four)
        four.set_movement_direction(Direction.north)
        game.board.get_tile(2, 0).place_piece(four)

        five = game.player_1.get_piece_by_type(PieceType.five)
        five.set_movement_direction(Direction.south)
        game.board.get_tile(2, 2).place_piece(five)

        enemy_two = game.player_2.get_piece_by_type(PieceType.two)
        enemy_two.set_movement_direction(Direction.west)
        game.board.get_tile(4, 1).place_piece(enemy_two)

        best_move = get_best_move(game.player_1, game.player_2, is_first_move=False, depth=1)

        assert best_move is not None
        assert best_move.piece_type == PieceType.three
        assert best_move.x == 2
        assert best_move.y == 4
Example #8
0
def play_game(args):
    assert isinstance(args.field_paths, list) or isinstance(
        args.field_paths, str)
    if isinstance(args.field_paths, str):
        args.field_paths = [args.field_paths]
    fields = read_fields(args.field_paths)
    if args.players is None:
        args.players = int(input('How many players will play? — '))
    positions = []
    if args.start_positions is not None:
        for position in args.start_positions:
            x, y = map(int, position[1:-1].split(','))
            positions.append(Position(x, y))
    if not args.random_positions:
        if args.players - len(positions) > 0:
            print('Field size: {}x{}'.format(fields[0].x_size,
                                             fields[0].y_size))
            for i in range(len(positions), args.players):
                position = input(
                    'Start position as x,y or "random" for Player {}: '.format(
                        i))
                if position == 'random':
                    positions.append(random_position_on_field(fields[0]))
                else:
                    x, y = position.split(',')
                    positions.append(Position(int(x), int(y)))
    game = Game(fields, args.players, positions)
    game.start_game()
Example #9
0
    def __init__(self, pos, offline=False):

        states = ['base']

        components = Spec.formatter.get_components(
            'ui/data/script_analyser.json')

        super().__init__(states, components, pos)

        self.offline = offline
        self.client = None
        self.n_tb_lines = 12
        self.script_status = False

        # create game object -> test script
        self.game = Game(None, connected=False)

        # store script module -> know if need to load or reload module
        self.script_module = None

        self.set_states_components(
            None,
            ['cadre', 'title', 'b analyse', 'b load', 'b save', 't status'])

        self.add_button_logic('b analyse', self.b_analyse)
        self.add_button_logic('b save', self.b_save)
        self.add_button_logic('b load', self.b_load)
Example #10
0
class Handler(BaseHTTPRequestHandler):
    game = Game()

    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_POST(self):
        self._set_headers()
        payload = self.rfile.read(int(self.headers['Content-Length']))

        # Hive object from request payload
        hive = json.loads(payload.decode('utf-8').lower())

        orders = self.game.do_turn(hive)

        response = json.dumps(orders)

        try:  # For python 3
            out = bytes(response, "utf8")
        except TypeError:  # For python 2
            out = bytes(response)

        self.wfile.write(out)

        print("Trick:", hive['tick'], response)
Example #11
0
 def test_play_moves(self):
     game = Game(num_rows=8, num_cols=9, line_length_to_win=4)
     game.play_move(0)
     game.play_move(0)
     game.play_move(4)
     game.play_move(2)
     game.play_move(4)
     game.play_move(8)
     game.play_move(8)
     game.play_move(8)
     for i in range(8):
         game.play_move(7)
     self.assertListEqual(
         game.get_board(),
         board_utils.from_char_matrix([
             ["-", "-", "-", "-", "-", "-", "-", "O", "-"],
             ["-", "-", "-", "-", "-", "-", "-", "X", "-"],
             ["-", "-", "-", "-", "-", "-", "-", "O", "-"],
             ["-", "-", "-", "-", "-", "-", "-", "X", "-"],
             ["-", "-", "-", "-", "-", "-", "-", "O", "-"],
             ["-", "-", "-", "-", "-", "-", "-", "X", "O"],
             ["O", "-", "-", "-", "X", "-", "-", "O", "X"],
             ["X", "-", "O", "-", "X", "-", "-", "X", "O"],
         ]),
     )
     self.assertTrue(game.is_p1_to_move())
     self.assertEqual(game.get_outcome(), Outcome.ONGOING)
Example #12
0
def create_game():
    game_room.remove(request.sid)
    game = Game()
    games.append(game)
    game.add_player(request.sid, player_names[request.sid])
    player_games[request.sid] = game
    update_game_room()
Example #13
0
    def run(self):

        if self.readFile:
            print("** Reading population from file **")
            self.agent.population = self.loadData()
        elif not self.collectWholeGameData:
            self.agent.initPopulation(NUMBER_OF_STARTING_TOWERS)

        for generation in range(MAX_GENERATIONS):
            self.gameRecords = []
            self.correctNumberOfTowers = generation + 1

            if self.collectWholeGameData:
                self.agent.initPopulation(self.correctNumberOfTowers)

            # play all of the games for each member of the population
            for i in range(POPULATION_SIZE):
                self.agent.setTowers(self.agent.population[i])
                # bool: visualMode, Towers: Agent.currentTowers, blank GameRecord, returns a record of the game stats,
                # None for the deepQagent the game now expects
                game = Game(self.visualMode, self.agent.currentTowers,
                            GameRecord(), self.collectInnerGameData, None)
                # collects stats for the whole game
                record = game.run()
                # print(len(record.randomChoicesRecord))

                # print('\nList Size: ' + str(len(record.randomChoicesMade)))

                self.gameRecords.append(record)

            self.postGameProcessing()

        return
Example #14
0
 def run(self):
     while True:
         if self.state == -1:
             self.draw_background()
             self.draw_footer()
             self.window.getch()
             # start main menu
             m = Menu()
             if m.selection < 0:
                 break
             self.state = m.selection
         elif self.state == 0:
             self.window.erase()
             self.draw_footer(main=False)
             self.window.getch()
             # get game difficulty
             m = Menu(main=False)
             if m.selection < 0:
                 # go back to main menu
                 self.state = -1
                 continue
             # start game
             game = Game(self.height, self.width, difficulty=m.selection)
             game.start()
             # If quit game back to main menu
             self.state = -1
         elif self.state == 2:
             # TODO Controls State
             break
         elif self.state == 4:
             # TODO Exit State (Message for exiting)
             break
Example #15
0
def main():
    """Program főkontrollere ami elindítja a játékot"""

    # Alap inicializáció
    pygame.mouse.set_visible(False)
    menu = Menu()

    while True:
        # Menü kezelő
        start_menu(menu)

        # Játék indul ha nem kilépést választottunk
        if menu.full_exit:
            break

        # Player lista elkésztése a menü adatai és a MenuData class alapértékei alapján
        players = player_init(menu)

        # Játék elindítása
        game = Game(players)
        if game.start(
        ):  # Visszatér True értékkel ha a felhasználó megnyomta az X-et
            break

        # Amint vége a játéknak az EndScreen következik
        endscreen = EndScreen(game.players)
        endscreen.draw()

        # Folyamatosan várunk az enter billenytu lenyomására majd visszatérünk a menübe
        if enter_listener(
        ):  # Visszatér True értékkel ha a felhasználó megnyomta az X-et
            break
Example #16
0
def test_initial_position_bias():
    # Using the initial fixed setup

    # Iterate some turns for player and letting it sample randomly from all possible actions
    for i in range(100):
        g = Game(random_init=False, action_space='building_and_trade')
        while True:
            actions = g.get_possible_actions(g.current_player)
            if sum(actions) >= 1:
                chosen_action = np.random.choice(len(actions),
                                                 1,
                                                 p=actions / sum(actions))
                _, __, clabel = g.take_action(chosen_action[0],
                                              g.current_player)
                if clabel == 'build_road':
                    buildroad[g.current_player - 1] += 1
                elif clabel == 'build_settlement':
                    buildsettlement[g.current_player - 1] += 1
                elif clabel == 'build_city':
                    buildcity[g.current_player - 1] += 1
                elif clabel == 'trade_4vs1':
                    trade4vs1[g.current_player - 1] += 1
                elif clabel == 'trade_3vs1':
                    trade3vs1[g.current_player - 1] += 1
                elif clabel == 'trade_2vs1':
                    trade2vs1[g.current_player - 1] += 1
            if (np.any(g.get_victory_points() >= 8)):
                victories.append(np.argmax(g.get_victory_points()))
                points.append(g.get_victory_points())
                print('game ' + str(i))
                print(g.get_victory_points())
                break
Example #17
0
def main():

    running = True

    pg.init()
    pg.mixer.init()
    screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
    clock = pg.time.Clock()

    # implement menus
    start_menu = StartMenu(screen, clock)
    game_menu = GameMenu(screen, clock)

    # implement game
    game = Game(screen, clock)

    while running:

        # start menu goes here
        playing = start_menu.run()

        while playing:
            # game loop here
            game.run()
            # pause loop here
            playing = game_menu.run()
Example #18
0
 def test_player_1_to_move(self):
     game = Game(num_rows=8, num_cols=9, line_length_to_win=4)
     game.play_move(1)
     game.play_move(7)
     game.play_move(4)
     game.play_move(7)
     self.assertTrue(game.is_p1_to_move())
Example #19
0
def main():
    """ Reversi game with human player vs AI player.
    """

    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--timeout',
        help=
        "Number of seconds the brain is allowed to think before making its move",
        type=int,
        default=1)
    parser.add_argument('--text',
                        help="Display the game in text mode",
                        action='store_false')
    parser.add_argument('--player', help="Player first", action='store_true')
    parser.add_argument('--ai', help="AI first", action='store_true')
    parser.add_argument('--verify',
                        help="Verify AI using a random player",
                        action='store_true')

    args = parser.parse_args()

    if args.timeout < 0:
        exit()

    players = ['player', 'player']
    if args.player:
        players = ['player', 'ai']
    if args.ai:
        players = ['ai', 'player']
    elif args.verify:
        players = ['ai', 'random']

    game = Game(timeout=args.timeout, colour=args.text, players=players)
    game.run()
Example #20
0
 def test_exceed_max_height(self):
     game = Game(num_rows=8, num_cols=9, line_length_to_win=4)
     for i in range(8):
         game.play_move(7)
     with self.assertRaisesRegex(Exception,
                                 r"Tried to illegally play move 7"):
         game.play_move(7)
def create_game():
    # preconditions
    game = Game()
    game.start()
    # default players are in a row
    game.add_default_players()
    return game
Example #22
0
    def __init__(self):

        # Create the main app Log file
        log.basicConfig(filename="MeoTech.log",
                        level=log.DEBUG,
                        format="%(asctime)s %(levelname)s: %(message)s",
                        datafmt="%d-%m-%Y %H:%M:%S")

        # Init Panda
        ShowBase.__init__(self)

        # Init Engine
        self.engine = Engine(self)

        # Init Game
        self.game = Game(self)

        # Debug stuff
        wantDebug = True

        if wantDebug:
            self.engine.showBulletDebug()
            print " "
            print "Panda Render.ls()"
            print "--------------------------------------------------------"
            print render.ls()
            print "--------------------------------------------------------"
Example #23
0
    def post(self):  # Move can be either hit or stay.
        parser = reqparse.RequestParser()
        parser.add_argument("move",
                            type=str,
                            help="Move can be either hit or stay.")
        parser.add_argument("new_game",
                            type=str,
                            help="If true, a new game is to be prepared.")
        args = parser.parse_args()
        username, user, game = _get_username_user_and_game()
        if args.get("move") == "hit":
            if game.game_table.turn_indicator == PLAYER_TURN_INDICATOR:
                game.hit()
                return {"msg": "Move ok."}, 200
            return {"msg": "It is not player's turn."}, 400
        elif args.get("move") == "stay":
            game.stay()
            return {"msg": "Move ok."}, 200

        if args.get("new_game") == "true":
            game = Game(user, new_game=True)
            return {"msg": "The deed has been done, good sir."}

        return {
            "msg":
            'Request posted to /move should contain "new_game" or "move". Move can be hit or stay. New_game has to be "true"'
        }, 400
Example #24
0
    def test_obvious_first_movement(self, clean_tree_search_caches_before_tests):
        # Here we are going to set up a game where player 1 is about to win the game, except if
        # player 2 (who goes first) prevents it by placing a piece on the square player 1 needs to use
        # to win
        game = Game()
        game.starting_player = game.player_2

        five = game.player_1.get_piece_by_type(PieceType.five)
        five.set_movement_direction(Direction.east)
        game.board.get_tile(1, 1).place_piece(five)

        four = game.player_1.get_piece_by_type(PieceType.four)
        four.set_movement_direction(Direction.west)
        game.board.get_tile(3, 2).place_piece(four)

        opponent_four = game.player_2.get_piece_by_type(PieceType.four)
        opponent_four.set_movement_direction(Direction.west)
        game.board.get_tile(1, 3).place_piece(opponent_four)

        best_moves, _, eval_type = get_best_moves(game.player_2, game.player_1, is_first_move=True, depth=1)
        assert len(best_moves) == 1
        assert eval_type == EvaluationType.exact

        # Player 2 can only avoid losing this turn by playing anything on tile (2, 4)
        best_move = get_best_move(game.player_2, game.player_1, is_first_move=True, depth=1)

        assert best_move.x == 2
        assert best_move.y == 4

        # Should be true for any depth level (using 2 for test speed reasons)
        best_move_depth_2 = get_best_move(game.player_2, game.player_1, is_first_move=True, depth=2)

        assert best_move_depth_2.x == 2
        assert best_move_depth_2.y == 4
Example #25
0
    def __init__(self,
                 interactive=False,
                 max_actions_per_turn=None,
                 max_proposed_trades_per_turn=4,
                 validate_actions=True,
                 debug_mode=False,
                 win_reward=500,
                 vp_reward=True,
                 policies=None):
        if max_actions_per_turn is None:
            self.max_actions_per_turn = np.inf
        else:
            self.max_actions_per_turn = max_actions_per_turn
        self.max_proposed_trades_per_turn = max_proposed_trades_per_turn
        """
        can turn validate actions off to increase speed slightly. But if you send invalid
        actions it will probably f**k everything up.
        """
        self.validate_actions = validate_actions
        self.game = Game(interactive=interactive,
                         debug_mode=debug_mode,
                         policies=policies)

        self.win_reward = win_reward
        self.vp_reward = vp_reward
Example #26
0
def test_develop_two_player():
    # Using the initial fixed setup
    g = Game(random_init=False)

    # Putting settlement and roads to places so that all resources are accessible
    g.place_settlement(42, 1)
    g.place_settlement(35, 1)

    g.place_road(36, 1)
    g.place_road(38, 1)

    g.place_settlement(40, 2)
    g.place_settlement(13, 2)

    g.place_road(18, 2)
    g.place_road(44, 2)

    # Iterate some turns for player and letting it sample randomly from all possible actions
    for i in range(20):
        g.current_player = 1 if g.current_player == 2 else 2
        g.roll_dice()  # automatically distributes resources
        actions = g.get_possible_actions(g.current_player)
        if sum(actions) >= 1:
            chosen_action = np.random.choice(len(actions),
                                             1,
                                             p=actions / sum(actions))
            g.take_action(chosen_action[0], g.current_player)

    # As player 2 is intially worsely placed than player 1 we expect him to have fewer buildings and resources
    print("From test_develop_two_player() :")
    print(g.cards)
    print(g.building_state)
    print(g.roads.get_state())
Example #27
0
    def test_player_has_no_legal_moves(self, clean_tree_search_caches_before_tests):
        game = Game()
        game.starting_player = game.player_2

        one = game.player_1.get_piece_by_type(PieceType.one)
        one.set_movement_direction(Direction.north)
        game.board.get_tile(3, 3).place_piece(one)

        two = game.player_1.get_piece_by_type(PieceType.two)
        two.set_movement_direction(Direction.east)
        game.board.get_tile(3, 2).place_piece(two)

        three = game.player_1.get_piece_by_type(PieceType.three)
        three.set_movement_direction(Direction.north)
        game.board.get_tile(1, 3).place_piece(three)

        four = game.player_1.get_piece_by_type(PieceType.four)
        four.set_movement_direction(Direction.north)
        game.board.get_tile(2, 0).place_piece(four)

        five = game.player_1.get_piece_by_type(PieceType.five)
        five.set_movement_direction(Direction.south)
        game.board.get_tile(2, 2).place_piece(five)

        best_move = get_best_move(game.player_1, game.player_2, is_first_move=False, depth=1)

        assert best_move.to_placement_move(game.player_1) is None
        assert best_move.score > 0
Example #28
0
def test_develop_four_player_w_init():
    # Using the initial fixed setup
    g = Game(random_init=True)

    # Iterate some turns for player and letting it sample randomly from all possible actions
    for i in range(1000):
        actions = g.get_possible_actions(g.current_player)
        print('Anzahl möglicher Aktionen: Iteration ' + str(i) + '  ' +
              str(sum(actions)))
        if sum(actions) >= 1:
            chosen_action = np.random.choice(len(actions),
                                             1,
                                             p=actions / sum(actions))

            g.take_action(chosen_action[0], g.current_player)
        if (np.any(g.get_victory_points() >= 8)):
            break

    print("From test_develop_four_player() :")
    print('Cards: ' + str(g.cards))
    print('Victory Points: ' + str(g.get_victory_points()))
    print('Player 1 Settlements:' + str(np.where(g.building_state == 1)))
    print('PLayer 1 Streets' + str(np.where(g.roads.get_state() == 1)))
    print('Player 2 Settlements:' + str(np.where(g.building_state == 2)))
    print('PLayer 2 Streets' + str(np.where(g.roads.get_state() == 2)))
    print('Player 3 Settlements:' + str(np.where(g.building_state == 3)))
    print('PLayer 3 Streets' + str(np.where(g.roads.get_state() == 3)))
    print('Player 4 Settlements:' + str(np.where(g.building_state == 4)))
    print('PLayer 4 Streets' + str(np.where(g.roads.get_state() == 4)))

    print(g.get_state_space())  # lots of ones and zeros
Example #29
0
    def test_player_must_use_four_piece(self, clean_tree_search_caches_before_tests):
        game = Game()
        game.starting_player = game.player_2

        five = game.player_2.get_piece_by_type(PieceType.five)
        five.set_movement_direction(Direction.south)
        game.board.get_tile(2, 3).place_piece(five)

        two = game.player_2.get_piece_by_type(PieceType.two)
        two.set_movement_direction(Direction.south)
        game.board.get_tile(3, 3).place_piece(two)

        three = game.player_2.get_piece_by_type(PieceType.three)
        three.set_movement_direction(Direction.north)
        game.board.get_tile(1, 1).place_piece(three)

        player_two = game.player_1.get_piece_by_type(PieceType.two)
        player_two.set_movement_direction(Direction.west)
        game.board.get_tile(1, 3).place_piece(player_two)

        # Player 1 can only avoid losing this turn by player the four piece on either
        # the (2, 0) or the (2, 4) tile or on the (0, 3) tile
        best_move = get_best_move(game.player_1, game.player_2, is_first_move=False, depth=1)

        assert (best_move.x == 2 and best_move.y == 0) or\
               (best_move.x == 2 and best_move.y == 4) or\
               (best_move.x == 0 and best_move.y == 3)
        assert best_move.piece_type == PieceType.four
Example #30
0
def main():

    running = True
    playing = False

    pg.init()
    pg.mixer.init()
    #screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
    screen = pg.display.set_mode((1200, 800), pg.SRCALPHA)
    clock = pg.time.Clock()

    start_menu = StartMenu(screen, clock)
    game_menu = GameMenu(screen, clock)

    while running:

        start_menu = StartMenu(screen, clock)
        start_timer = pg.time.get_ticks()
        game_menu = GameMenu(screen, clock)
        game = Game(screen, clock)

        playing = start_menu.run()
        while playing:
            complete, lost = game.run()
            if complete:
                end_game_menu = EndGameMenu(screen, clock, start_timer)
                end_game_menu.run()
                running = False
            elif lost:
                playing = False
            else:
                playing = game_menu.run()