示例#1
0
    def __init__(self, master, size, player_mark, **kw):
        super().__init__(master=master, width=size, height=size, **kw)

        self.size = size
        self.field_size = size // 3
        self.moves_count = 0

        self.human = Human(mark=player_mark, board=self)
        self.computer = self.human.create_opponent()

        self.add_fields()
示例#2
0
    def test_game_result(self):
        """Tests that the game returns the correct result when passed an initial
        board with a win or draw state."""
        # Create the players
        human = Human()
        agent = MiniMaxAgent()

        # Test draw result
        game = TicTacToe([human, agent], shuffle=False)
        board = np.asarray([[1, -1, -1], [-1, 1, 1], [1, -1, -1]])
        result = game.run(board)
        self.assertEqual(result, None)

        game = TicTacToe([agent, human], shuffle=False)
        board = np.asarray([[1, -1, -1], [-1, 1, 1], [1, -1, -1]])
        result = game.run(board)
        self.assertEqual(result, None)

        # Test side 1 wins
        game = TicTacToe([human, agent], shuffle=False)
        board = np.asarray([[1, -1, -1], [1, 1, 1], [1, -1, -1]])
        result = game.run(board)
        self.assertEqual(result, 1)

        # Test side -1 wins
        game = TicTacToe([human, agent], shuffle=False)
        board = np.asarray([[-1, -1, -1], [1, 1, 1], [1, -1, -1]])
        result = game.run(board)
        self.assertEqual(result, -1)
示例#3
0
 def new_game(self, num_of_players: int, num_of_humans: int):
     self.pool: List[int] = pool_of_numbers()
     self.winner: Union[Human, Computer, None] = None
     self.cards: List[list] = deal_cards(num_of_players)
     self.table_of_players: List[Union[Human, Computer]] = []
     if num_of_humans == num_of_players:
         for pl in range(num_of_players):
             player = Human(f'Person{pl + 1}', self.cards.pop())
             self.table_of_players.append(player)
     else:
         for hm in range(num_of_humans):
             human = Human(f"Person{hm + 1}", self.cards.pop())
             self.table_of_players.append(human)
         for cm in range(num_of_players - num_of_humans):
             computer = Computer(f"Computer{cm + 1}", self.cards.pop())
             self.table_of_players.append(computer)
     self.start_match()
示例#4
0
 def get_human_player(self):
     """
     Добавление игрока - человека
     :return: новый игрок
     """
     name = ''
     while name == '':
         name = input("Введите имя игрока{0}: \n".format(self.count_players))
     self.count_players += 1
     return Human(name, self.graphic)
示例#5
0
    def __init__(self, height, width, tokens_per_player=9, max_number=9):
        window = c.newwin(height, width, 0, 0)

        super(Game, self).__init__(window)

        # se crean los diferentes paneles que se mostraran en la ventana del
        # juego
        self.table = Table(height, width)
        self.playerTable = PlayerTable(height, width)
        self.info = GameInfo(height, width)

        # se agregan los paneles a la ventana
        self.addElements(self.table)
        self.addElements(self.playerTable)
        self.addElements(self.info, False)

        # se crean las fichas del juego
        self.tokens = [
            Token(i, j) for i in range(max_number + 1)
            for j in range(i, max_number + 1)
        ]

        # se repareten fichas para cada jugador
        if self.getFirst() == PLAYER:
            self.player = Human(self.getPlayerTokens(tokens_per_player))
            self.computer = Computer(self.getPlayerTokens(tokens_per_player))
            self.turn = PLAYER
        else:
            self.computer = Computer(self.getPlayerTokens(tokens_per_player))
            self.player = Human(self.getPlayerTokens(tokens_per_player))
            self.turn = COMPUTER

        # como se esta en proceso de desarrollo, el jugador siempre hara la
        # primera jugada, si se quita esta linea la probabilidad de que el
        # jugador vaya primero es de 50%
        self.turn = PLAYER

        # se agregan las fichas del jugador al tablero del jugador
        for element in self.player.tokens:
            self.playerTable.addElements(element)

        # se actualiza la informacion de los jugadores
        self.info.initInfo(self.player.getInfo(), self.computer.getInfo())
def setup_game():

    # determine versus human or versus computer
    play_against_comp = ''
    while not play_against_comp in ['Y', 'N']:
        play_against_comp = input(
            '\nDo you want to play against the computer? (Y/N) ').upper()
    computer = True if play_against_comp == 'Y' else False

    # choose letters
    letter1 = ''
    name1 = input('Player 1, what shall we call you? ')
    name2 = ''
    if not computer: name2 = input('Player 2, What shall we call you? ')

    while not letter1 in ['X', 'O']:
        letter1 = input(
            f'{name1}, which letter do you want to be, X or O?: ').upper()
    letter2 = 'X' if letter1 == 'O' else 'O'

    # init game
    player1 = Human(letter1, name1)
    player2 = Computer(letter2) if computer else Human(letter2, name2)
    play_game(player1, player2, TicTacToe())
示例#7
0
def main():
    # Set up the logger
    logger = logging.getLogger()
    logging.basicConfig(stream=sys.stdout,
                        level=logging.INFO,
                        format="\n%(message)s")

    # Create the players
    from players import Human
    human = Human(logger=logger)
    from agents.minimax import MiniMaxAgent
    agent = MiniMaxAgent(logger=logger)

    # Run the game
    game = TicTacToe([human, agent], shuffle=True, logger=logger)
    while True:
        game.run()
示例#8
0
def load(player_name: str):
    """Returns a Strategy instance based on the name
    given as an input
    """
    if player_name == "dummy":
        return Dummy()
    elif player_name == "smart_start":
        return SmartStart()
    elif player_name == "me":
        return Human()
    else:
        # look for name in players folder
        try:
            import json

            with open("players/" + player_name + ".json") as f:
                Q = json.load(f)

            return QStrategy(Q)
        except FileNotFoundError:
            raise FileNotFoundError(
                f"Could not find {player_name + '.json'} file.")
        except:
            raise NotImplementedError(f"Could not find {player_name} player.")
示例#9
0
class TestPlayerHumanComputer:
    @pytest.mark.parametrize('player, exp_res', [
        pytest.param(
            Player('Player1', [
                1,
            ]), 'Name: Player1\nHand: [1]', id='Player'),
        pytest.param(
            Human('Player1', [
                1,
            ]), 'Name: Player1\nHand: [1]', id='Human'),
        pytest.param(Computer('Player1', [
            1,
        ]),
                     'Name: Player1\nHand: [1]',
                     id='Computer'),
    ])
    def test_repr(self, player: Union[Player, Human, Computer], exp_res: str):
        """Testing if Players and children classes return right representation"""
        assert str(player) == exp_res

    @pytest.mark.parametrize('player, given_piece, exp_res', [
        pytest.param(Computer('1', []), 1, 'win', id='Empty check_set -> win'),
        pytest.param(Computer('1', [
            1,
        ]), 1, 'win', id='Get a piece and win'),
        pytest.param(
            Computer('1', [
                2,
            ]), 1, 'pass', id='Get a piece and pass'),
        pytest.param(
            Computer('1', [2, 1]), 1, 'take', id='Get a piece and take'),
    ])
    def test_computer_choice(self, player: Computer, given_piece: list,
                             exp_res: str):
        """Testing if Computer class gives right answers"""
        assert player.take_piece(given_piece) == exp_res
示例#10
0
def test_human_init(mark):
    human = Human(mark)
    assert human.mark == mark
示例#11
0
 def test_human_right_choice_and_take(self, _user_input):
     assert Human('1', [2, 1]).take_piece(1) == 'take'
示例#12
0
class Board(ttk.Frame):
    def __init__(self, master, size, player_mark, **kw):
        super().__init__(master=master, width=size, height=size, **kw)

        self.size = size
        self.field_size = size // 3
        self.moves_count = 0

        self.human = Human(mark=player_mark, board=self)
        self.computer = self.human.create_opponent()

        self.add_fields()

    def add_fields(self):
        self.fields = []
        for i in range(3):
            fields_row = []
            for j in range(3):
                field = Field(master=self, size=self.field_size, command=lambda i=i, j=j: self.next_turn(i, j))
                field.grid(row=i, column=j)
                fields_row.append(field)
            self.fields.append(fields_row)

    def next_turn(self, i, j):
        if self.human.make_move(i, j):
            curr_status = self.check_game_status(self.human)

            if curr_status is None:
                self.computer.make_move()
                self.check_game_status(self.computer)

    def check_game_status(self, player):
        if self.moves_count == 9:
            self.display_result('Nobody')
            return 'Draw'

        r = player.moves[-1].i
        c = player.moves[-1].j
        board_size = 3

        player.row[r] += 1
        player.col[c] += 1
        if r == c:
            player.diag += 1
        if r + c == board_size - 1:
            player.anti_diag += 1

        if (player.row[r] == board_size or player.col[c] == board_size
                or player.diag == board_size or player.anti_diag == board_size):
            self.display_result(player)
            return str(player)

        return None

    def display_result(self, player):
        if messagebox.askyesno(f'{player} won!', f'{player} won!\nDo you wish to play again?'):
            self.new_game()
        else:
            self.end_game()

    def new_game(self):
        self.grid_remove()
        self.master.pick_mark()
        self.destroy()

    def end_game(self):
        self.master.destroy()

    def to_matrix(self):
        matrix = []
        for i in range(3):
            row = []
            for j in range(3):
                row.append(self.fields[i][j].get_mark())
            matrix.append(row)

        return matrix
示例#13
0
 def test_human_right_choice_and_pass(self, _user_input):
     assert Human('1', [
         2,
     ]).take_piece(1) == 'pass'
示例#14
0
    interactive = False

    if interactive:
        import logging
        import sys
        from tictactoe import TicTacToe
        # Set up the logger
        logger = logging.getLogger()
        logging.basicConfig(stream=sys.stdout,
                            level=logging.INFO,
                            format="\n%(message)s")

        # Create the players
        from players import Human
        human = Human(logger=logger)
        # from agents.minimax import MiniMaxAgent
        # human = MiniMaxAgent()

        mcts_agent = MCTSAgentRandom(logger=logger)

        # Run the game
        game = TicTacToe([human, mcts_agent], shuffle=True, logger=logger)
        while True:
            game.run()
            generate_graph(mcts_agent.root_node)

    else:
        random.seed(7)

        mcts_agent = MCTSAgentRandom()
示例#15
0
    def __init__(self, config):
        self.continents = {}
        for continent, countryDict in config['countries'].items():
            ContCountries = []
            for countryName, neighbours in countryDict.items():
                newCountry = Country(name=countryName, adj=neighbours)
                ContCountries.append(newCountry)
                self.tiles[newCountry.name] = newCountry

            self.continents[continent] = Continent(
                name=continent,
                countries=ContCountries,
                reward=config['contvals'][continent])
        cards = []
        for card in config['cards']:
            cards.append(Card(*card))
        self.deck = Deck(cards)

        for player in config['players']:
            if player['type'] == "Human":
                self.players.append(
                    Human(player['name'], player['troops'], self))
            elif player['type'] == "Machine":
                self.players.append(
                    Machine(player['name'],
                            player['troops'],
                            self,
                            terr_num=len(self.tiles),
                            play_num=len(config['players'])))
            elif player['type'] == "Random":
                self.players.append(
                    RandomAgent(player['name'], player['troops'], self))

        # by default first player in array begins turn, can be changed in config
        self.turn = Turn(self.players)

        if config['playstyle']['init_allocation'] == "uniform_random":
            print("playstyle: uniform_random")
            idx = 0
            tiles_per_player = len(self.tiles) / len(self.players)
            # Find average amount of units to add to a tile on init
            units_per_tile = {
                player.name: {
                    "min":
                    floor(player.free_units / tiles_per_player),
                    "remain":
                    int(player.free_units - tiles_per_player *
                        floor(player.free_units / tiles_per_player))
                }
                for player in self.players
            }
            for _, tile in self.tiles.items():
                tile.conquer(self.players[idx % len(self.players)])
                # randomly allocate either one more or one less to tile to
                units_to_tile = units_per_tile[tile.owner.name]['min']
                # Eat up remainder troops near beginning of loop
                if units_per_tile[tile.owner.name]['remain'] > 0:
                    units_to_tile += 1
                    units_per_tile[tile.owner.name]['remain'] -= 1
                # Add units to the tile. If no units left, use remainder
                if tile.owner.free_units >= units_to_tile:
                    tile.owner.free_units -= units_to_tile
                    tile.units += units_to_tile
                else:
                    tile.units += tile.owner.free_units
                    tile.owner.free_units = 0
                idx += 1

            # Only do initial refill if not in manual mode
            self.turn.curr.refill_troops(self.tiles, self.continents)
        elif config['playstyle']['init_allocation'] == "manual":
            # Players can pick where to place units on turn at beginning
            pass
示例#16
0
 def test_human_wrong_choice_and_lose(self, _user_input):
     assert Human('1', [
         1,
     ]).take_piece(1) == 'lose'
示例#17
0
 def test_human_wring_input(self, _user_input):
     assert Human('1', [
         2,
     ]).take_piece(1) == 'wrong input'
示例#18
0
 def __init__(self, player1='Human Player1', player2='Human Player2'):
     self.player1 = Human(name=player1, icon=IconX())
     self.player2 = Human(name=player2, icon=IconO())
示例#19
0
 def __init__(self, knowledge_base=None):
     self.player1 = Human()
     self.player2 = Computer(knowledge_base=knowledge_base)
示例#20
0
class Game(BaseContainer):
    """
    Esta se encarga de manejar todo el ciclo del juego

    Parametros
    ----------
    height(int): Entero que representa la altura de la pantalla
    width(int): Entero que representa el ancho de la pantalla
    tokens_per_player(int): Entero que indica cuantas fichas le corresponden
        a cada jugador
    max_number(int): Entero que indica el numero maximo que ira en las fichas
        del domino
    """
    def __init__(self, height, width, tokens_per_player=9, max_number=9):
        window = c.newwin(height, width, 0, 0)

        super(Game, self).__init__(window)

        # se crean los diferentes paneles que se mostraran en la ventana del
        # juego
        self.table = Table(height, width)
        self.playerTable = PlayerTable(height, width)
        self.info = GameInfo(height, width)

        # se agregan los paneles a la ventana
        self.addElements(self.table)
        self.addElements(self.playerTable)
        self.addElements(self.info, False)

        # se crean las fichas del juego
        self.tokens = [
            Token(i, j) for i in range(max_number + 1)
            for j in range(i, max_number + 1)
        ]

        # se repareten fichas para cada jugador
        if self.getFirst() == PLAYER:
            self.player = Human(self.getPlayerTokens(tokens_per_player))
            self.computer = Computer(self.getPlayerTokens(tokens_per_player))
            self.turn = PLAYER
        else:
            self.computer = Computer(self.getPlayerTokens(tokens_per_player))
            self.player = Human(self.getPlayerTokens(tokens_per_player))
            self.turn = COMPUTER

        # como se esta en proceso de desarrollo, el jugador siempre hara la
        # primera jugada, si se quita esta linea la probabilidad de que el
        # jugador vaya primero es de 50%
        self.turn = PLAYER

        # se agregan las fichas del jugador al tablero del jugador
        for element in self.player.tokens:
            self.playerTable.addElements(element)

        # se actualiza la informacion de los jugadores
        self.info.initInfo(self.player.getInfo(), self.computer.getInfo())

    def getFirst(self):
        """
        Este metodo decide que jugador va primero
        """
        return choice([PLAYER, COMPUTER])

    def getPlayerTokens(self, tokenNumber):
        """
        Este metodo elimina y retorna un numero de fichas del total de fichas
        del juego
        """
        tokens = []

        while len(tokens) < tokenNumber:
            # se van elijiendo fichas de forma aleatoria
            tokens.append(self.tokens.pop(randint(0, len(self.tokens) - 1)))
            # se posicionan las fichas de forma que esten en la misma fila y
            # de forma consecutiva
            tokens[-1].position = [1, 1 + 8 * (len(tokens) - 1)]

        return tokens

    @applyEvent(113, COVER)  # q
    def inputHandler(self, char):
        # la tecla TAB se usa para cambiar de panel, entre el panel con las
        # fichas del jugador y el panel con las fichas jugadas
        if char == 9:  # TAB
            # solo se puede cambiar panel si no se esta ubicando una ficha
            if not self.table.isLocatingToken:
                self.linter += 1
        # cuando se presiona la tecla p el jugador ha cedido el turno
        if char == 112:  # p
            self.player.skippedTurns += 1
            self.turn = COMPUTER
        else:
            pass

        # para que self.linter no tome valores no posibles
        self.linter %= self.linterableObjects

        # se maneja el turno del jugador
        if self.turn == PLAYER:
            # si el panel en el que se esta es el de las fichas del jugador
            if self.linter == 1:
                # se obtiene la ficha, si token toma el valor de None es porque
                # el jugador no ha realizado ninguna jugada
                token = self.playerTable.inputHandler(char)

                # se revisa si la jugada es valida
                if (token is not None) and self.table.isValidToken(token):
                    # cuando la jugada es valida se obtiene la ficha
                    token = self.player.getToken(token.numerator,
                                                 token.denominator)

                    # la ficha ya no esta en el panel del jugador
                    self.playerTable.elements.remove((token, True))
                    # hay una ficha menos
                    self.playerTable.linterableObjects -= 1

                    # la ficha debe estar en el panel de las fichas jugadas
                    self.table.locateToken(token)

                    # se cambia al panel de las fichas jugadas, para iniciar
                    # el posicionamiento de la nueva ficha
                    self.linter = 0
            # si el panel es el de las fichas jugadas
            else:
                # se gestiona las operaciones del jugador en el panel de fichas
                # jugadas, si nextTurn toma el valor de True, es porque el
                # jugador ha terminado su jugada, es decir, ha posicionado una
                # ficha
                nextTurn = self.table.inputHandler(char)

                if nextTurn:
                    self.turn = COMPUTER

            # se actualiza la informacion del jugador
            self.info.updateInfo(self.player.getInfo(), player=PLAYER)

        # turno de la maquina
        else:
            # se obtiene jugada del computador, si token toma el valor de None
            # es porque no habia jugada disponible
            token = self.computer.makeMove(self.table.getTokens(),
                                           self.table.right, self.table.left)

            if (token is not None) and self.table.isValidToken(token):
                # cuando la jugada es valida se obtiene la ficha
                token = self.computer.getToken(token.numerator,
                                               token.denominator)

                # se ubica la ficha del computador
                self.table.locateComputerToken(token)

            # se actualiza la informacion de la maquina
            self.info.updateInfo(self.computer.getInfo(), player=COMPUTER)

            # ahora es turno del jugador
            self.turn = PLAYER

        return NONE

    def write(self):
        """
        Este metodo dibuja todo en pantalla
        """
        # esta variable especifica si el color del borde del panel que sera
        # resaltado
        colorLinter = None
        for i in range(len(self.elements)):

            element, _ = self.elements[i]

            # si el i coincide con self.linter, entonces se debe resaltar el
            # panel
            if i == self.linter:
                colorLinter = 2

            element.write(colorLinter)

            colorLinter = None
示例#21
0
文件: worm_game.py 项目: jamad/pyxel
    def run(self) -> None:
        """ Main Program Loop """
        while not self.done:
            self.handle_events()

            for player in self.players:
                player.act()
            self.update()
            self.renderer.draw_game(self.game_state)
            pygame.display.flip()
            InputState.clear_tick_states()
            self.game_state.pizza_manager.clear_tick_changes()

            # --- Limit to 60 frames per second
            self.clock.tick(60)
        pygame.display.quit()
        self.server.shutdown()


GAME = Game()
GAME.add_player(Human('P1', GAME.inputs, (pygame.K_LEFT, pygame.K_RIGHT)))
GAME.add_player(Human('P2', GAME.inputs, (pygame.K_a, pygame.K_d)))
# GAME.add_player(Human('P3', GAME.inputs, (pygame.K_v, pygame.K_n)))
# GAME.add_player(Human('P4', GAME.inputs, (pygame.K_KP4, pygame.K_KP6)))
# GAME.add_player(Human('P5', GAME.inputs, (pygame.K_i, pygame.K_p)))
GAME.add_player(SimpleAI('Bot1'))
# GAME.add_player(SimpleAI('Bot2'))
# GAME.add_player(SimpleAI('Bot3'))

GAME.run()
示例#22
0
class PlayerController(object):
    def __init__(self, room_url, game_url, doc_url):
        self.wsconn = None
        self.player = None
        self.model = Model()
        self.wsconn_close = False
        self.room_url = room_url
        self.game_url = game_url
        self.doc_url = doc_url
        self.has_initialised = False
        self.has_initial_player_been_choosen = False

    def get_str_input(self, question):
        """
		This gets a string input

		:param question: Prompt for user to give an answer to
		:returns: str -- User answer
		"""
        choice = input(question)
        while any((choice is None, not choice.strip())):
            print("You entered any empty answer")
            choice = input(question)
        return choice

    def get_int_input(self, question):
        """
		This gets a integer

		:param question: Prompt for user to give an answer to
		:returns: int -- User answer
		"""
        while True:
            choice = input(question)
            try:
                choice = int(choice)
                return choice
            except ValueError as err:
                print(err)

    def create_new_user(self):
        """	This creates a new Human user """
        user_id = uuid.uuid4().hex
        question = 'What is your username?: '
        username = self.get_str_input(question)
        self.player = Human(user_id, self, self.model, username)

    def create_room(self):
        """ This creates a room	"""
        print("=== Creating a room ===")
        self.create_new_user()
        question = "What is the room's name? "
        room_name = self.get_str_input(question)
        question = 'How many players do you want to play with: '
        num_of_players = self.get_int_input(question)
        while num_of_players == 0:
            num_of_players = self.get_int_input(question)

        msg = {'username': self.player.get_nickname(), \
          'userid': self.player.get_user_id(), \
         'num_of_players': num_of_players,
         'room_name': room_name}
        param = {'cmd': RoomRequest.CREATE_A_ROOM.value}
        req = requests.post(self.room_url, json=msg, params=param)
        response = DiscardMessage.to_obj(req.text)
        print("Your new room id=", response.get_payload_value(value='data'))
        self.player.set_room_id(response.get_payload_value(value='data'))

    def join_room(self, room=None):
        """
		This adds current player to room

		:param room: Room to join
		"""
        print('=== Joining room ===')
        self.create_new_user()
        self.player.set_room_id(room['roomid'])
        print('You selected: ', self.player.get_room_id())
        param = {'cmd': RoomRequest.JOIN_ROOM.value}
        msg = {
            'username': self.player.get_nickname(),
            'userid': self.player.get_user_id(),
            'roomid': room['roomid']
        }
        req = requests.post(self.room_url, json=msg, params=param)
        response = DiscardMessage.to_obj(req.text)
        print(response)

    def find_room(self):
        """ 
		This finds rooms 

		:returns: bool -- True if rooms has been found. False if otherwise
		"""
        print('==== Getting rooms to play the game ====')
        param = {'cmd': RoomRequest.GET_ROOMS.value}
        req = requests.get(self.room_url, params=param)
        rooms = DiscardMessage.to_obj(req.text)
        if rooms.get_payload_value(value='data'):
            ls = [{
                key: value
                for key, value in value.items() if key != 'roomid'
            } for value in rooms.get_payload_value(value='data')]
            ls[:] = [
                str(ind) + ') ' + repr(value) for ind, value in enumerate(ls)
            ]
            room_str = '\n'.join(ls)
            print('The rooms available:', '\n', room_str)
            choice = self.get_int_input('Choose room to join: ')
            while choice >= len(ls):
                choice = self.get_int_input('Choose room to join: ')
            room_ = rooms.get_payload_value(value='data')
            room = room_[choice]
            return room
        print(
            "Can't find rooms. You can try to find rooms again(Recommended) or create a room."
        )
        return None

    def initial_menu(self):
        return '\n'.join([
            '\nChoose from these options: ',
            'j) Join an existing room(Recommended) ', 'c) Create a room',
            'e) Exit \n', 'Select option: '
        ])

    def negotiate(self):
        """ This finds or creates a room """
        print('==== Starting game ====')

        while True:
            choice = self.get_str_input(self.initial_menu())
            while choice in ['j', 'c'] == False:
                print('Wrong option')
                choice = self.get_str_input(self.initial_menu())
            if choice == 'j':
                room = self.find_room()
                if room:
                    self.join_room(room)
                    break
            elif choice == 'c':
                choice_ = self.choose_wait_or_create()
                if choice_ == 'y':
                    self.create_room()
                    break

    def show_roomates(self):
        """ This shows roomates """
        param = {
            'cmd': RoomRequest.GET_ROOMATES.value,
            'userid': self.player.get_user_id(),
            'roomid': self.player.get_room_id()
        }
        req = requests.get(self.room_url, params=param)
        response = DiscardMessage.to_obj(req.text)
        ls = [
            str(ind) + ') ' + value for ind, value in enumerate(
                response.get_payload_value(value='data'))
        ]
        if ls:
            room_str = '\n'.join(ls)
            print('My roomates:', '\n', room_str)
        else:
            print('You have no roomates yet!!')

    def choose_wait_or_create(self):
        question = 'Do you still want to create a room' + \
         '(y/n)? '
        choice = self.get_str_input(question)
        while choice in ['y', 'n'] == False:
            print('Wrong option')
            choice = self.get_str_input(question)
        return choice

    def gen_ping(self):
        """ 
		This generates a ping message to send to 
		the server to ask if roomates can actually
		start playing the game
		"""
        msg_ = DiscardMessage(cmd=RoomGameStatus.ARE_ROOMATES_IN_GAME.value,
                              room_id=self.player.get_room_id(),
                              user_id=self.player.get_user_id())
        return DiscardMessage.to_json(msg_)

    def start_game(self):
        """ This sends a START_GAME request to game server """
        msg_ = {
            'userid': self.player.get_user_id(),
            'roomid': self.player.get_room_id()
        }
        param = {'cmd': RoomRequest.START_GAME.value}
        req = requests.post(self.room_url, json=msg_, params=param)
        response = DiscardMessage.to_obj(req.text)
        print(response)

    def gen_test_message(self):
        """ This generates a user-generated message 

		:param question: Question to be asked
		"""
        choice = None
        if self.has_initialised == True:
            choice = self.gen_ping()
        else:
            choice = self.get_str_input('Send a message: ')
        if choice == "End":
            msg_ = {}
            return json.dumps(msg_)
        else:
            msg_ = DiscardMessage(cmd=RoomGameStatus.GAME_MESSAGE.value,
                                  data=choice,
                                  room_id=self.player.get_room_id(),
                                  user_id=self.player.get_user_id())
            return DiscardMessage.to_json(msg_)

    def generate_wsmessage(self):
        """ This generates the message to send to the game server """
        print("[[ In generate_wsmessage ]]")
        msg = None
        if self.has_initialised == False:
            msg = self.gen_ping()
        else:
            if self.has_initial_player_been_choosen == False:
                msg = self.gen_test_message()
            else:
                msg = self.main_loop()
            if msg == json.dumps({}):
                return None
        return msg

    def handle_msg(self, message):
        """ Handles messages received from the game server """
        print("[[ In handle_msg ]]")
        msg = DiscardMessage.to_obj(message)
        if all((msg.cmd == ClientRcvMessage.GAME_MESSAGE_REP.value,
                msg.get_payload_value(value='prompt') ==
                ClientRcvMessage.GAME_CAN_BE_STARTED_REP.value)):
            print("[[ Starting game ]]")
            if self.has_initialised == False:
                self.has_initialised = True
                self.start_game()
                self.choose_initial_player()
        elif all(
            (msg.cmd == ClientRcvMessage.GAME_MESSAGE_REP.value,
             msg.get_payload_value(
                 value='prompt') == ClientRcvMessage.GAME_HAS_STARTED_REP.value
             )):
            print("[[ Joining stared game ]]")
            if self.has_initialised == False:
                self.has_initialised = True
                self.choose_initial_player()
        elif msg.cmd == ClientRcvMessage.ASK_FOR_ROOMATES_REP:
            self.show_roomates()
        print("Received game message from server: ", msg)
        if self.has_initial_player_been_choosen == True:
            print("Setting message for eventual processing")
            self.player.set_message_to_process(msg)

    def choose_initial_player(self):
        print("[[ In choose_initial_player ]]")
        param = {'cmd': RoomRequest.SET_FIRST_PLAYER.value}
        msg_ = {
            'userid': self.player.get_user_id(),
            'roomid': self.player.get_room_id(),
            'username': self.player.get_nickname()
        }
        rep = requests.post(self.room_url, params=param, json=msg_)
        response = DiscardMessage.to_obj(rep.text)
        print(response.get_payload_value(value='prompt'),
              response.get_payload_value(value='data'))
        if self.has_initial_player_been_choosen == False:
            self.has_initial_player_been_choosen = True

    def print_currently_playing(self):
        print("[[ In print_currently_playing ]]")
        param = {
            'cmd': RoomRequest.GET_CURRENT_PLAYER.value,
            'roomid': self.player.get_room_id()
        }
        rep = requests.get(self.room_url, params=param)
        response = DiscardMessage.to_obj(rep.text)
        return (response.get_payload_value(value='prompt'),
                response.get_payload_value(value='data'))

    # Experimental
    def menu(self):
        return 'Menu Options:\n\n' + \
        'Select the option below related to an action.\n\n' + \
        'h -- Help and rules in a browser\n' + \
        'r -- Help and rules in your command line\n' + \
        'p -- Play your turn. Note you have to play to skip\n' + \
        'q -- Exit the game\n\n' + \
        'Enter your option: '

    # Experimental
    def main_loop(self):
        """This is the main loop in the game"""
        choice = None
        msg_ = {}
        prompt, player = self.print_currently_playing()
        print(prompt, player)
        choice = self.get_enum_choice(self.get_str_input(self.menu()))
        while choice == None:
            print('Wrong option')
            choice = self.get_enum_choice(self.get_str_input(self.menu()))
        if choice == MainLoopChoices.PRETTY_HELP:
            #req = requests.get(self.doc_url)
            msg_ = DiscardMessage(cmd='DOCUMENTATION')
        elif choice == MainLoopChoices.CMD_RULES:
            msg_ = DiscardMessage(cmd='DOCUMENTATION')
        elif choice == MainLoopChoices.PLAY_ROUND:
            msg_ = self.player.play()
        elif choice == MainLoopChoices.LEAVE_GAME:
            msg_ = DiscardMessage(cmd='DOCUMENTATION')
        print("[[ Out of main_loop ]] ", msg_)
        return DiscardMessage.to_json(msg_)

    @gen.coroutine
    def connect_on_websocket(self):
        """ This makes a websocket connection to the game server """
        try:
            url = self.game_url + '?userId=' + \
             self.player.get_user_id() + \
             '&roomId=' + self.player.get_room_id() + \
             '&username='******'Websocket connection closed')
        else:
            self.wsconn_close = True

    @gen.coroutine
    def communicate_with_websocket(self):
        """ 
		This receives messages from the game server and
		sends back messages to the game server on the 
		websocket connection 
		"""
        print("[[ In communicate_with_websocket ]]")
        recv_msg = None
        while True:
            if self.wsconn_close == True:
                self.wsconn.close()
                sys.exit()
            recv_msg = yield self.wsconn.read_message()
            if recv_msg is None:
                self.wsconn.close()
                sys.exit()
            self.handle_msg(recv_msg)
            yield self.send_wsmessage()
        print("IOLoop terminate")

    def get_enum_choice(self, choice):
        """ 
		Choices for the main loop. A player is expected to choose
		from them

		:param choice: The choice to return a MainLoopChoice
		:returns Enum -- A MainLoopChoice
		"""
        if choice == 'h':
            return MainLoopChoices.PRETTY_HELP
        elif choice == 'r':
            return MainLoopChoices.CMD_ROUND
        elif choice == 'p':
            return MainLoopChoices.PLAY_ROUND
        elif choice == 'q':
            return MainLoopChoices.LEAVE_GAME
        return None

    @gen.coroutine
    def main(self):
        """ Thjs is the entry point for the ioloop """
        if self.player == None:
            self.negotiate()
        yield self.connect_on_websocket()
示例#23
0
from game import Game
#from policy_value_net import PolicyValueNet
from policy_value_net_residual import PolicyValueNet
from players import MCTSPlayer,Human
from trainer import Trainer

init_model = './master'
policy_value_net = PolicyValueNet(model_file=init_model)

trainer = Trainer(policy_value_net)

#new MCTS
player_ai = MCTSPlayer(policy_value_net.policy_value_fn,5,1000,is_selfplay = 0,debug=True)
player_me = Human()
game = Game(player_ai,player_me)

while True:
    winner, game_data = game.do_play()
    player_ai.reset_player()
    trainer.feed(game_data) #这里我们加一个学习功能,让AI在和人对弈的时候也能学习。
示例#24
0
 def create_new_user(self):
     """	This creates a new Human user """
     user_id = uuid.uuid4().hex
     question = 'What is your username?: '
     username = self.get_str_input(question)
     self.player = Human(user_id, self, self.model, username)
示例#25
0
 def test_human_right_choice_and_win(self, _user_input):
     assert Human('1', [
         1,
     ]).take_piece(1) == 'win'
示例#26
0
 def __init__(self, player=None):
     self.last_tick = None
     self.board = None
     self.board_drawer = None
     self.player = player or Human()