def get_best_move_for(game: Game):
    global leaf_nodes_found
    global input_data
    global output_data
    possible_action = game.get_possible_positions()
    output_data_for_this_game = [0] * game.board.columns * game.board.rows
    action_game_map = {}
    for action in possible_action:
        game1 = game.clone()
        game1.make_move(*get_coordinates(action, game1))
        if game1.check_game_over():
            output_data_for_this_game[action] = 1
            input_data.append(game.toArray())
            output_data.append(output_data_for_this_game)
            leaf_nodes_found += 1
            if leaf_nodes_found % 10000 == 0:
                print('leaf nodes total', leaf_nodes_found, len(input_data), len(input_data) - leaf_nodes_found)
            return True
        action_game_map[action] = game1
    for action in possible_action:
        game1 = action_game_map[action]
        can_opponent_win = get_best_move_for(game1)
        if can_opponent_win:
            output_data_for_this_game[action] = 0
        else:
            output_data_for_this_game[action] = 1
    input_data.append(game.toArray())
    output_data.append(output_data_for_this_game)
    return any(output_data)
Example #2
0
    def test_clone_game(self):
        game = Game()
        game.starting_player = game.player_2

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

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

        game_clone = game.clone()

        center_piece_clone = game_clone.board.get_tile(2, 2).piece
        assert center_piece_clone is not None
        assert center_piece_clone.type == PieceType.two
        assert center_piece_clone.owner_id == game_clone.player_1.id

        center_piece_clone = game_clone.board.get_tile(1, 0).piece
        assert center_piece_clone is not None
        assert center_piece_clone.type == PieceType.three
        assert center_piece_clone.owner_id == game_clone.player_2.id

        assert game_clone.starting_player == game_clone.player_2

        game_clone.switch_starting_player()

        assert game_clone.starting_player.id != game.starting_player.id
def basic_game(tmpdir):
    g = Game()
    g.gamedir = tmpdir.mkdir("test_game")
    with open('{}/gm_passwords.json'.format(g.gamedir), 'w') as outfile:
        json.dump({'passwords': ['gmpass1', 'gmpass2']}, outfile)
    temp1 = ItemTemplate('backpack', 'Backpack', "It's a backpack", True)
    temp2 = ItemTemplate('key', 'Blue Key', 'This is a key', False)
    g.player_manager.load_gm_passwords(g.gamedir)
    room1 = Room('room1', 'Room #1', 'First room.')
    room2 = Room('room2', 'Room #2', 'Second room.')
    room3 = Room('room3', 'Room #3', 'Third room.')
    room1.adjacent_rooms.add(room2)
    room2.adjacent_rooms.add(room1)
    room2.adjacent_rooms.add(room3)
    room3.adjacent_rooms.add(room2)
    room3.adjacent_rooms.add(room1)
    char1 = Character('char1', 'First Character', '1234', room1)
    char2 = Character('char2', 'Second Character', 'qwerty', room3)
    g.room_manager.rooms['room1'] = room1
    g.room_manager.rooms['room2'] = room2
    g.room_manager.rooms['room3'] = room3
    g.char_manager.characters['char1'] = char1
    g.char_manager.characters['char2'] = char2
    g.item_manager.item_templates[temp1.short_name] = temp1
    g.item_manager.item_templates[temp2.short_name] = temp2
    backpack1 = g.item_manager.new_item(temp1.short_name)
    key1 = g.item_manager.new_item(temp2.short_name)
    backpack2 = g.item_manager.new_item(temp1.short_name)
    key2 = g.item_manager.new_item(temp2.short_name)
    backpack1.add_item(key1)
    char1.items.add_item(backpack1)
    room1.items.add_item(backpack2)
    room1.items.add_item(key2)
    return g
Example #4
0
    def __init__(self):
        # init row, col
        max_row = 5
        max_col = 12

        # init Game
        self.game = Game(max_row, max_col)
Example #5
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()
Example #6
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 #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 do_menu(prefManager, scoresFile):
    menuUtil.send_menu(MENU_OPTIONS)
    option = menuUtil.receive_option(
        len(MENU_OPTIONS))  # Receive validated menu option.

    print()
    if option == 1:
        # Play the Game
        game = Game(prefManager, scoresFile)
        game.play()

    elif option == 2:
        # See instructions
        instructions.send_instructions()

    elif option == 3:
        # Edit your preferences
        preferencesFrontend.do_menu(prefManager)

    elif option == 4:
        # View scores data
        scoresMenu.do_menu(scoresFile)

    elif option == 5:
        # Exit
        print('Bye!')

        exit()

    print()
Example #9
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 #10
0
def render_loop(stdscr, game: Game, keystroke: int, cursor: Cursor):
    # Initialization
    stdscr.clear()
    height, width = stdscr.getmaxyx()
    max_cursor = calc_max_cursor(game)
    cursor = cursor.move(keystroke, max_cursor)

    # Draw Title
    draw_centred_title(stdscr, "PENTAGO", width)

    # Draw Menu
    menu_string = f"Press 'q' to quit | row: {cursor.get_y()}, col: {cursor.get_x()} | stage: {game.get_stage()}"
    draw_menu(stdscr, menu_string, width, height)

    if not game.is_over():
        # Handle moves
        game, cursor = handle_move(keystroke, game, cursor)

        # Rotate String
        if game.get_stage() == 1:
            draw_rotate_string(stdscr, game, width)

    if game.is_over():
        draw_winner_string(stdscr, game, width)

    # Draw Board
    draw_centred_board(stdscr, game, width, cursor)

    # Wait for input
    return stdscr.getch(), game, cursor
Example #11
0
class TestBoard(unittest.TestCase):
    def setUp(self):
        self.basic_game = Game(board=None, rnd=random.Random(1))

    def test_constructor(self):
        self.assertEqual(self.basic_game.score(), 0)
        game = Game(rnd=random.Random(1))
        self.assertEqual(game.board(), self.basic_game.board())

    def test_smash(self):
        # This doesn't comprehensively test smashing because
        # the tests for Board mostly did that already.
        for direction in DIRECTIONS:
            board = Board()
            board = board.update((1, 1), 2)
            game = Game(rnd=random.Random(1), board=board)
            self.assertTrue(game.smash(direction))
            self.assertEqual(game.board()[1, 1], 0)
        for direction in DIRECTIONS:
            board = Board()
            board = board.update((0, 0), 2)
            game = Game(rnd=random.Random(1), board=board)
            if direction in {UP, LEFT}:
                self.assertFalse(game.smash(direction))
            else:
                self.assertTrue(game.smash(direction))
                self.assertEqual(game.board()[0, 0], 0)
    def render(self, screen, width, height):
        if self.network is None:
            try:
                self.network = Network(self.host, self.port, self.pw, self)
            except:
                self.event = None
                self.network = None

        if self.event is None and self.network is None:
            NoServer.render(screen, width, height)
            return
        if self.event is None:
            NoServer.render_pw_error(screen, width, height)
            return

        if "gamestate" in self.event:
            self.last_score = self.event["gamestate"]["ranking"]
            Game.render(screen, width, height, self.event["gamestate"],
                        self.selected_player, self.host, self.port)
        elif "lobby" in self.event:
            Lobby.render(screen, width, height, self.event["lobby"], self.host,
                         self.port, self.last_score)
        else:
            print("unknown state")
            print(self.event)
Example #13
0
    def joinGame(self, game_id=None, password=None):
        if password:
            password = self._generatePassword(password)
        self._refreshSeriesState()
        if not game_id:
            game = Game.getPlayerLastGame(series_id=self._seriesState['id'],
                                          player_id=self._playerState['id'])
            if not game or game['status'] == Base_Game.STATUS_ENDED:
                game = Game.getLastGameInSeries(
                    series_id=self._seriesState['id'])
                if not game:
                    raise GameWasNotCreateError
        else:
            game = Game.get(game_id=game_id)
            if not game:
                raise GameWasNotCreateError

        self._isPlayerHasAccessToGame(game['id'], password)

        if self._playerState['game_id'] != game['id']:
            Player.joinGame(player_id=self._playerState['id'],
                            role=Game.PLAYER_ROLE_MEMBER,
                            game_id=game['id'])

            if password:
                Player.setGamePassword(player_id=self._playerState['id'],
                                       game_id=game['id'],
                                       password=password)

        # self._refreshGameState(password=password, game_id=game['id'], checkGameStatus=False)

        return game, "Иииха! Ты присовокупился к игре с ID %d серии игр с ID %d" % (
            game['id'], self._seriesState['id'])
Example #14
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=20)
    parser.add_argument('--display-moves', help="Whether legal moves should be displayed or not.", action='store_true')
    parser.add_argument('--colour', help="Display the game in 256 colours.", action='store_true')
    parser.add_argument('--player', help="If you want to play against the ai", action='store_true')
    parser.add_argument('--ai', help="If you want the ais to play against each other", action='store_true')

    args = parser.parse_args()

    if args.timeout < 0:
        exit()

    players=[]
    if args.player:
        players = ['player', 'ai']
    if args.ai:
        players = ['ai', 'ai']
    if not players:
        players = ['player', 'ai']

    game = Game(timeout=args.timeout,
                display_moves=args.display_moves,
                colour=args.colour,
                players=players)
    game.run()
Example #15
0
File: bot.py Project: petia2009/BOT
async def _start(ctx):
    global GAME
    GAME = Game(player_x_id=ctx.author.id, player_o_id='bot')
    GAME.new_game()
    await ctx.send("----! Добро пожаловать в КРЕСТИКИ НОЛИКИ " + version + " !----\n"
                   " Напишите ***._rules*** чтобы получит список правил игры. Напишите ***._help кн***"
                   " или ***._help крестики-нолики*** чтобы получить список команд в крестиках ноликах!")
Example #16
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 #17
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 #18
0
def test_populate():
    zombies = 30
    victims = 29
    hunters = 33
    map_x = 20
    map_y = 20
    testgame = Game(zombies, victims, hunters, 1, map_x, map_y)
    testgame.populate()

    zomb_count, vic_count, hunt_count = 0, 0, 0
    tile_list = testgame.get_map().get_list()
    blanks = 0
    for list in tile_list:
        for tile in list:
            if tile.get_occupier() == "Zombie":
                zomb_count+=1
            elif tile.get_occupier() == "Victim":
                vic_count+=1
            elif tile.get_occupier() == "Hunter":
                hunt_count+=1
            else:
                blanks+=1

    assert_equal(zomb_count, zombies)
    assert_equal(vic_count, victims)
    assert_equal(hunt_count, hunters)
    total_tiles = map_x*map_y
    total_blanks = total_tiles - (zombies+victims+hunters)
    assert_equal(blanks, total_blanks)
Example #19
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 #20
0
 def test_black_win(self):
     game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     self.assertTrue(not game.is_over())
     self.play_game_sequence(game, ['b1', 'a1', 'c3', 'c1'])
     self.assertTrue(game.is_over())
     self.assertEqual(game.BLACK_MSG, game.get_winner_message())
Example #21
0
    def train(self,
              n_episodes=5000,
              n_validation=500,
              n_checkpoint=500,
              n_tests=1000):
        """Trains the model.

        Arguments:
        n_episodes -- number of episodes to train (default 5000)
        n_validation -- number of episodes between testing the model
            (default 500)
        n_checkpoint -- number of episodes between saving the model
            (default 500)
        n_tests -- number of episodes to test (default 1000)
        """
        logging.info("training model [n_episodes = %d]", n_episodes)
        for episode in range(1, n_episodes + 1):
            logging.info("running episode [episode = %d]", episode)
            if episode % n_validation == 0:
                self.test(n_tests)
            if episode > 1 and episode % n_checkpoint == 0:
                self.save()

            player = random.randint(0, 1)
            game = Game(TDGammonAgent(self, player),
                        TDGammonAgent(self, 1 - player))
            game.play()

            self._reset_trace()

        self.save()
Example #22
0
 def test_repeat_player_move(self):
     game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     player = next(game.players)
     self.assertEqual(player.colour, s.WHITE)
     game.repeat_player_move()
     self.assertEqual(next(game.players), player)
Example #23
0
    def init_training_environment(self, activation_function, loss_function,
                                  optimizer_function):
        """
        Initialize the reinforcement learning environment

        :param activation_function:
        	activation function used in RL environment.
        :param loss_function:
            loss function used in RL environment
        :param optimizer_function:
            optimizer function used in RL environment
        """
        env = Game(action_space=self.action_space)
        self.RL = DeepQNetwork(
            len(env.get_possible_actions(1)),
            len(env.get_state_space()),  # total action, total features/states
            learning_rate=self.learning_rate,
            reward_decay=self.reward_decay,
            e_greedy=self.e_greedy,
            replace_target_iter=self.replace_target_iter,
            memory_size=self.memory_size,
            softmax_choice=self.softmax_choice,
            batch_size=self.batch_size,
            list_num_neurons=self.list_num_neurons,
            output_graph=self.output_graph,
            activation_function=activation_function,
            loss_function=loss_function,
            optimizer_function=optimizer_function,
            with_bias=self.with_bias,
            replace_soft_target=self.replace_soft_target)
Example #24
0
    def find_best_move(self, game: Game, evaluator, depth: int):
        legal_moves = game.get_legal_moves()
        shuffle(legal_moves)
        if len(legal_moves) == 0:
            return None, None, float("-inf"), legal_moves
        elif depth > 0:
            # try all move and find max score
            best_move = None
            best_tile = None
            best_score = None
            for move in legal_moves:
                playable_tiles = list(range(game.active_size))
                shuffle(playable_tiles)
                for tile in playable_tiles:
                    hist_move = game.play(move, tile)

                    _, _, cur_score, _ = self.find_best_move(
                        game, evaluator, depth - 1)
                    if cur_score is not None and (best_score is None
                                                  or cur_score > best_score):
                        best_move = move
                        best_tile = tile
                        best_score = cur_score

                    game.undo(hist_move)
            return best_move, best_tile, best_score, legal_moves
        else:
            return None, None, evaluator.eval(game), legal_moves
Example #25
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 #26
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 #27
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 #28
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 #29
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 #30
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 #31
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 #32
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 #33
0
        def start_new_game(player_name: str, enemy_name: str, terrain: str,
                           sams: bool, midgame: bool, multiplier: float):
            if terrain == "persiangulf":
                conflicttheater = theater.persiangulf.PersianGulfTheater()
            elif terrain == "nevada":
                conflicttheater = theater.nevada.NevadaTheater()
            else:
                conflicttheater = theater.caucasus.CaucasusTheater()

            if midgame:
                for i in range(0, int(len(conflicttheater.controlpoints) / 2)):
                    conflicttheater.controlpoints[i].captured = True

            start_generator.generate_inital_units(conflicttheater, enemy_name,
                                                  sams, multiplier)
            start_generator.generate_groundobjects(conflicttheater)
            game = Game(player_name=player_name,
                        enemy_name=enemy_name,
                        theater=conflicttheater)
            game.budget = int(game.budget * multiplier)
            game.settings.multiplier = multiplier
            game.settings.sams = sams
            game.settings.version = VERSION_STRING

            if midgame:
                game.budget = game.budget * 4 * len(
                    list(conflicttheater.conflicts()))

            proceed_to_main_menu(game)
Example #34
0
class GameController(object):
    """
    This abstract class contains the shared logic for all game controllers. It is not meant to be used in itself, but
    works as a back-bone for all types of game controller.
    """

    def __init__(self):
        """
        Ctor - Initialises game controller.
        """
        pass

    def set_up_game(self):
        """
        This method sets up the game to be played by this controller.
        """
        self._game = Game()

    def get_game(self):
        """
        This method retrieves the game currently being played by the game controller.

        @return The game currently being played.
        """
        return self._game

    def play_next_turn(self):
        """
        This method plays a single turn of the game.
        """
        self._game.next_turn()
Example #35
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 #36
0
    def test_next_turn(self):
        '''
        Tests whether the Game.next_turn() method functions correctly.
        '''
        g = Game()

        g.next_turn()
        assert g._turn_count == 1
Example #37
0
 def test_game_is_over(self):
     game1 = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                  True, 5)
     self.play_game_sequence(game1, ['b1', 'a1', 'c1', 'c3'])
     self.assertTrue(game1.is_over())
     game2 = Game(2, Game.Modes.human_human, Game.DifficultyLevels.easy,
                  True, 5)
     self.assertTrue(game2.is_over())
Example #38
0
 def test_white_win(self):
     game = Game(4, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     self.assertTrue(not game.is_over())
     self.play_game_sequence(game, ['d2', 'd3', 'd4', 'b1', 'a3', 'b4',
                                    'a4', 'a2', 'c4'])
     self.assertTrue(game.is_over())
     self.assertEqual(game.WHITE_MSG, game.get_winner_message())
Example #39
0
    def test_get_turn_count(self):
        '''
        Tests whether the get_turn_count() method functions correctly.
        '''
        g = Game()
        g.next_turn()

        assert g.get_turn_count() == 1
Example #40
0
 def test_get_next_state(self):
     game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     state = (game.mover.board, s.WHITE)
     self.assertEqual(game.mover.board, state[0])
     next_state = game.get_next_state(state, (2, 1))
     self.assertNotEqual(game.mover.board, next_state[0])
     game.mover.board.make_move((2, 1), s.WHITE)
     self.assertEqual(game.mover.board, next_state[0])
Example #41
0
 def setUp(self):
     self.game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                      True, 5)
     first_move = (1, 2)
     first_state = Game.get_next_state(
         (self.game.mover.board, WHITE), first_move)
     self.root_possible_moves = self.game.mover.board.get_moves(WHITE)
     self.root = Node(first_state, first_move,
                      len(self.root_possible_moves))
Example #42
0
 def test_get_previous_state(self):
     game = Game(4, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     state = (game.mover.board, s.WHITE)
     my_state = game.get_next_state(state, (1, 0))
     game.next_move('a3')
     self.assertEqual(game.get_current_state(), my_state)
     opp_state = game.get_next_state(my_state, (2, 0))
     game.next_move('a2')
     self.assertEqual(game.get_current_state(), opp_state)
     my_prev_state = game.get_previous_state(opp_state, (2, 0))
     self.assertEqual(my_state, my_prev_state)
Example #43
0
    def __init__(self, rule_set, initial_input):
        """
        Ctor - Initialises the Game of Life with a rule set and an initial
        pattern, both defined by the user. Also initialises a calculator.
        """
        Game.__init__(self)

        # Initialise the rule set
        self._rule_set = rule_set

        # Initialise the grid objects to be used by the engine
        self._current_generation = initial_input

        # Give the game engine a calculator to use.
        self._calculator = Calculator(rule_set)
Example #44
0
 def init_ui(self, board_size, game_mode, game_difficulty_level,
             game_time_for_move):
     self.game = Game(board_size, mode=game_mode,
                      difficulty_level=game_difficulty_level,
                      is_console_game=False,
                      time_for_move=game_time_for_move)
     self.game_was_saved = False
     self.time_for_move = game_time_for_move
     self.count = self.time_for_move
     self.timer = QBasicTimer()
     self.move_timer = QTimer()
     self.ai_thread = AIThread(self)
     self.ai_thread.finished.connect(self.ai_finish)
     self.ai_finished = True
     self.load_images()
     self.add_toolbar()
     self.font_size = 10
     self.resize(board_size * s.IMG_SIZE,
                 (board_size * s.IMG_SIZE + self.toolbar.height() + 10 +
                  self.font_size))
     self.center()
     self.setWindowTitle('Reversi')
     self.show()
     self.timer.start(1, self)
     self.move_timer.timeout.connect(self.count_down)
     self.move_timer.start(1000)
Example #45
0
class TestMonteCarloAI(unittest.TestCase):
    def setUp(self):
        self.game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.hard,
                         True, 5)
        self.ai = MonteCarloAI(self.game, WHITE, Game.DifficultyLevels.hard)
        first_move = (1, 2)
        first_state = Game.get_next_state((self.game.mover.board, WHITE),
                                          first_move)
        self.root_possible_moves = self.game.mover.board.get_moves(WHITE)
        self.root = Node(first_state, first_move,
                         len(self.root_possible_moves))

    def test_get_best_move(self):
        node = Node(self.root.state, (1, 2), 2)
        children = [Node(node.state, (2, 3), 1), Node(node.state, (2, 1), 2)]
        children[0].plays, children[0].wins = 3, 2
        children[1].plays, children[1].wins = 2, 2
        for child in children:
            node.add_child(child)
        self.assertEqual(self.ai.get_best_move(node), children[0].move)
        node.children[0].plays, node.children[0].wins = 2, 1
        self.assertEqual(self.ai.get_best_move(node), children[1].move)

    def test_back_propagate(self):
        node = Node(self.root.state, (1, 2), 2)
        child = Node(node.state, (2, 3), 1)
        child.plays, child.wins = 2, 1
        node.add_child(child)
        self.assertTrue(node.plays == 0)
        self.assertTrue(node.wins == 0)
        self.ai.back_propagate(child, 1)
        self.assertTrue(child.plays == 3)
        self.assertTrue(child.wins == 2)
        self.assertTrue(node.plays == 1)
        self.assertTrue(node.wins == 1)

    def test_get_best_child(self):
        children = [Node(self.game.get_next_state(self.root.state, (1, 2)),
                    (1, 2), 3),
                    Node(self.game.get_next_state(self.root.state, (2, 1)),
                    (2, 1), 3)]
        children[0].plays, children[0].wins = 2, 1
        children[1].plays, children[1].wins = 1, 0
        self.root.plays = 3
        for child in children:
            self.root.add_child(child)
        self.assertEqual(self.ai.get_best_child(self.root), children[1])
Example #46
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.players = []
     self.players_sockets = []
     self.started = False
     self.controller = controller.Controller(self)
     self.game = Game(self)
     self.killed = False
Example #47
0
    def next_turn(self):
        """
        Runs the next turn in the Game of life.
        """
        # Takes the current generation and passes to calculator
        cur_gen = self.get_current_generation()
        nex_gen = self._calculate_next_generation(cur_gen)

        # Stores next generation in self._next_generation
        self._set_next_generation(nex_gen)

        # The state in of the next generation is stored as the current
        # generation
        self._current_generation.set_cells(nex_gen.get_cells())

        # Increment turn count
        Game.next_turn(self)
Example #48
0
def main(width=4, height=4, goal=2048, intial_value=2):
    game = Game(int(width), int(height), int(goal), int(intial_value))
    game.start()

    while True:
        try:
            pretty_print(game.grid)

            line = raw_input("> ").strip().lower()

            if line == "q" or line == "quit":
                print "bye"
                return

            dir_ = get_dir(line)

            if dir_ is None:
                print "options: %s, q" % (", ".join(sorted(dirs.keys())))
                continue

            game.slam(dir_)

            if game.is_over():
                pretty_print(game.grid)

                if game.goal_met():
                    print "You won! Yay!"
                else:
                    print "Game over! You suck!"
                return

        except KeyboardInterrupt:
            print
            return
Example #49
0
 def test_skip_player(self):
     game = Game(4, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     game.next_move('c1')
     self.assertEqual(game.current_player.colour, s.WHITE)
     game.skip_player()
     game.next_move('a2')
     self.assertEqual(game.current_player.colour, s.WHITE)
Example #50
0
	def checknn(params):
		#create a network
		nn = buildNetwork(16, 5, 5, 4)

		#assign the parameters to be what we are testing
		i = 0
		for m in nn.connections.values():
			for c in m:
				for j in xrange(len(c.params)):
					c._params[j] = params[i]
					i += 1

		map = {
			0: Game.Direction.left,
			1: Game.Direction.right,
			2: Game.Direction.up,
			3: Game.Direction.down,
		}

		# run here
		game = Game()
		while not game.over:
			if random.random() < 0.95:
				inputs = np.hstack(game.state).tolist()
				outputs = nn.activate(inputs).tolist()
				#print outputs
				m = max(outputs)
				i = outputs.index(m)
				move = map[i]
				#print move
				game.move(move)
			else:
				move = map[random.randint(0, 3)]
				game.move(move)

		error = np.log2(2048 - game.max_block)

		print 'score', game.score
		print 'max block', game.max_block
		print 'error', error
		print

		return error
Example #51
0
    def __init__(self, *args, **kwargs):
        self.game = Game(60)
        self.game_thread = threading.Thread(target=self.game.main)
        self.game_thread.daemon = True
        self.game_thread.start()

        if SINGLE_PLAYER:
            self.client_thread = threading.Thread(target=basic_client)
            self.client_thread.daemon = True
            self.client_thread.start()
Example #52
0
    def play(self):
        """Plays labels game

        Then afterwards forwards the button
        and set 0 balance player to out
        Save game state"""
        game = Game(self)
        game.play()

        while True:
            self.button += 1
            if self.button > len(self.players):
                self.button = 1
            if self.players[self.button]['status']:
                break

        for s, p in self.players.items():
            if not p['balance']:
                p['status'] = 0

        self.persist_table()
    def next_turn(self):
        '''
        Runs the next turn in the Game of life.
        '''
        # Takes the current generation and passes to calculator
        cur_gen = self.get_current_generation()
        nex_gen = self._calculate_next_generation(cur_gen)

        # Stores next generation in self._next_generation
        self._set_next_generation(nex_gen)

        # Passes current generation back to Game Control to be shown on
        # the GUI.
        pass

        # The state in of the next generation is stored as the current
        # generation
        self._current_generation.set_cells(nex_gen.get_cells())

        # Increment turn count
        Game.next_turn(self)
Example #54
0
class GameApp(object):
    def __init__(self, *args, **kwargs):
        self.game = Game(60)
        self.game_thread = threading.Thread(target=self.game.main)
        self.game_thread.daemon = True
        self.game_thread.start()

    def __call__(self, environ, start_response):
        websocket = environ['wsgi.websocket']
        player_id = self.game.on_client_connect(websocket)

        while True:
            recv_data = websocket.receive()

            if recv_data is None:
                break

            message_dict = json.loads(recv_data)
            message_dict['player_id'] = player_id
            self.game.on_message_received(message_dict)

        self.game.on_client_disconnect(player_id)
    def test_basic_path_correct_4(self):

        # create the game with the know player cards
        players = [("white", 4), ("plum", 4), ("scarlett", 5), ("green", 5)]
        test_game = Game(players)
        test_game.set_controlled_player(0)
        test_game.set_player_cards_held(0, ["rope","wrench","kitchen","white"])      
        
        self.update_unseen_cards(test_game.incorrect_cards)
        #keep playing guess until the game is not complete
        while not test_game.is_complete():

            possible_cards = []
            
            #get three unknown cards from the unknown cards
            if self.unseen_actors:
                actor = str(random.sample(self.unseen_actors, 1)[0])
                possible_cards.append(actor)
            else:
                actor = "green"

            if self.unseen_rooms:
                room = str(random.sample(self.unseen_rooms, 1)[0])
                possible_cards.append(room)
            else:
                room = "kitchen"

            if self.unseen_weapons:
                weapon = str(random.sample(self.unseen_weapons, 1)[0])
                possible_cards.append(weapon)
            else:
                weapon = "rope"         

            responder_index = self.decide_responder_index(test_game)
            card_seen = random.sample(possible_cards, 1)
            
            print("current turn: " + actor + ", " + room + ", " + weapon + ' responder index: ' + str(responder_index) + " cards seen: " + str(card_seen))
            #create a guess from above cards
            test_game.turn(0, actor, weapon, room, responder_index, card_seen)
            print(test_game.incorrect_cards)
            self.update_unseen_cards(test_game.incorrect_cards)
        
        #complete the game 
        self.assertTrue(test_game.is_complete(), "game complete")
Example #56
0
 def test_move_is_repeated(self):
     game = Game(3, Game.Modes.human_human, Game.DifficultyLevels.easy,
                 True, 5)
     self.assertIsNone(game.current_player)
     game.next_move('b1')
     self.assertIsNotNone(game.current_player)
     self.assertEqual(game.current_player.colour, s.WHITE)
     game.next_move('a1')
     self.assertEqual(game.current_player.colour, s.BLACK)
     game.next_move('c3')
     self.assertEqual(game.current_player.colour, s.BLACK)
    def render(self, screen, width, height):
        if self.network is None:
            try:
                self.network = Network(self.host, self.port, self.pw, self)
            except:
                self.event = None
                self.network = None

        if self.event is None and self.network is None:
            NoServer.render(screen, width, height)
            return
        if self.event is None:
            NoServer.render_pw_error(screen, width, height)
            return

        if "gamestate" in self.event:
            self.last_score = self.event["gamestate"]["ranking"]
            Game.render(screen, width, height, self.event["gamestate"], self.selected_player, self.host, self.port)
        elif "lobby" in self.event:
            Lobby.render(screen, width, height, self.event["lobby"], self.host, self.port, self.last_score)
        else:
            print("unknown state")
            print(self.event)
Example #58
0
    def add_n_examples(self, strategy, rnd, n,
                       starting_positions_dataset=None):
        """Runs games and adds them to the dataset until at least @p n
        examples have been added.  Returns the number of examples added.

        If @p starting_positions_dataset is set, games will be started from
        a randomly selected position from that dataset rather than from a
        blank board."""
        print("Adding", n, "examples to dataset.")
        added = 0
        while added < n:
            starting_game = None
            if starting_positions_dataset:
                random_position = starting_positions_dataset.nth_example(
                    rnd.randint(0,
                                starting_positions_dataset.num_examples() - 1))
                starting_game = Game(Board.from_vector(random_position))
                if not starting_game.board().can_move():
                    continue
            num_added = self.add_game(strategy, rnd, starting_game)
            if (added // 10000) != ((num_added + added) // 10000):
                print("Added %d so far..." % (num_added + added))
            added += num_added
        return added
Example #59
0
class GameController(object):
    '''
    This class represents a skeleton from which game controls
    can inherit. It contains all the shared functionality of
    all game controls.
    '''

    def __init__(self, time):
        '''
        Ctor - Initialises game controller.
        '''
        self._timer = Timer(time)

    def set_up_game(self):
        '''
        Sets up the game to be played by this controller.
        '''
        self._game = Game()

    def get_game(self):
        '''
        Returns the game currently being played.
        '''
        return self._game

    def get_time_remaining(self):
        '''
        Returns the timer being used on this game controller.
        '''
        return self._timer.get_time_remaining()

    def play_next_turn(self):
        '''
        Plays a single turn of the game.
        '''
        self._game.next_turn()