예제 #1
0
 def create_ai_vs_ai_game(cls):
     ai1_diff = cls._prompt_difficulty("AI 1")
     ai2_diff = cls._prompt_difficulty("AI 2")
     print()
     ai1 = AIPlayer("Bot 1", ai1_diff)
     ai2 = AIPlayer("Bot 2", ai2_diff)
     return Game(ai1, ai2)
예제 #2
0
    def make_two_players(self):

        player1 = AIPlayer('W')
        player2 = AIPlayer('B')


        return player1, player2
예제 #3
0
 def humanVsBot(self):
     while True:
         print(
             "\033[94m===================================================================\033[0m\033[22m"
         )
         control = input("Do you want to play first: (y/n)? ")
         if control == "y":
             self.redSide = HumanPlayer("Tuan", redSide=True)
             self.notRedSide = AIPlayer("AI", redSide=False)
         else:
             self.redSide = AIPlayer("AI", redSide=True)
             self.notRedSide = HumanPlayer("Tuan", redSide=False)
         self.game = Game(self.redSide, self.notRedSide)
         self.game.printBoard()
         print(
             "\nWelcome! To play, enter a command, e.g. '\033[95mh3\033[0m'. 'h' for horizontal and 'v' for vertical."
         )
         while not self.game.isEnd():
             self.redSideMove()
             if not self.game.isEnd():
                 self.notRedSideMove()
                 if self.game.isEnd():
                     self.printResult()
                 continue
             else:
                 self.printResult()
예제 #4
0
    def test_playerMove3(self):
        self.playerAI = AIPlayer("O")
        self.testGame.makeMove((5, 9), "X")
        self.testGame.makeMove((6, 7), "X")
        self.testGame.makeMove((6, 11), "X")
        self.testGame.makeMove((7, 8), "X")
        self.testGame.makeMove((7, 9), "X")
        self.testGame.makeMove((8, 6), "X")
        self.testGame.makeMove((8, 8), "X")
        self.testGame.makeMove((8, 10), "X")
        self.testGame.makeMove((9, 6), "X")
        self.testGame.makeMove((9, 7), "X")
        self.testGame.makeMove((9, 8), "X")
        self.testGame.makeMove((9, 10), "X")
        self.testGame.makeMove((12, 6), "X")

        self.testGame.makeMove((6, 8), "O")
        self.testGame.makeMove((6, 9), "O")
        self.testGame.makeMove((6, 10), "O")
        self.testGame.makeMove((7, 7), "O")
        self.testGame.makeMove((7, 10), "O")
        self.testGame.makeMove((8, 9), "O")
        self.testGame.makeMove((9, 5), "O")
        self.testGame.makeMove((9, 7), "O")
        self.testGame.makeMove((10, 6), "O")
        self.testGame.makeMove((10, 8), "O")
        self.testGame.makeMove((11, 7), "O")
        self.testGame.makeMove((12, 8), "O")
        print(self.testGame.getPlayerScore("X"),
              self.testGame.getPlayerScore("O"))
        coord = self.playerAI.makeMove(self.testGame)
        possiblePlay1 = (8, 4)
        possiblePlay2 = (13, 9)
        print(coord)
        self.assertTrue(coord == possiblePlay1 or coord == possiblePlay2)
예제 #5
0
 def test_move_first(self):
     ''' Make sure the AI cannot lose when it goes first by testing all
         possible game combinations. '''
     board = Board()
     player = AIPlayer(True, board)
     # Let the AI go first
     player.next_move()
     self._test_all_moves(board, player)
예제 #6
0
    def start_selfplay(self,
                       batch_num=10000,
                       c_puct=5,
                       n_playout=400,
                       best_model=None):
        """
        启动持续的selfplay,用于为模型train生成训练数据
        Params:
            batch_num   selfplay对战次数
            c_puct      MCTS child搜索深度
            n_playout   模型训练时每个action的mcts模拟次数
        """
        logging.info("__start_selfplay__")
        # 1.init net & ai player
        model_last_mdy_time = os.stat(best_model).st_mtime if os.path.exists(
            best_model) else time.time()  # 模型最后更新时间
        policy_value_net = self._load_policy_value_net(best_model)
        ai_player = AIPlayer(policy_value_net.policy_value_fn,
                             c_puct=c_puct,
                             n_playout=n_playout,
                             is_selfplay=1)

        # 2.start selfplay
        try:
            for i in range(batch_num):  # 对战盘数
                # 2.1使用MCTS蒙特卡罗树搜索进行自我对抗
                logging.info("selfplay batch start: {}".format(i + 1))
                winner, play_data = self._selfplay(ai_player)
                logging.info(
                    "selfplay batch res. batch:{}, winner:{}, step_num:{}".
                    format(i + 1, winner, len(play_data)))
                # 2.2保存本局数据到databuffer目录文件
                data_file = self._get_databuffer_file(event=n_playout,
                                                      winner=winner,
                                                      step_num=len(play_data))
                utils.pickle_dump(play_data, data_file)
                logging.info("selfplay batch save. batch:{}, file:{}".format(
                    i + 1, data_file))
                # 2.3检查是否有新的模型需要reload
                model_time = os.stat(best_model).st_mtime if os.path.exists(
                    best_model) else time.time()  # 模型最后更新时间
                if model_time > model_last_mdy_time:
                    logging.info(
                        "selfplay reload model! new:{} > old:{}".format(
                            utils.get_date(os.stat(best_model).st_mtime),
                            utils.get_date(model_last_mdy_time)))
                    model_last_mdy_time = os.stat(
                        best_model).st_mtime if os.path.exists(
                            best_model) else time.time()  # 模型最后更新时间
                    policy_value_net = self._load_policy_value_net(best_model)
                    ai_player = AIPlayer(policy_value_net.policy_value_fn,
                                         c_puct=c_puct,
                                         n_playout=n_playout,
                                         is_selfplay=1)

        except KeyboardInterrupt:
            logging.info('\n\rselfplay quit')
예제 #7
0
파일: othello.py 프로젝트: MakubexZ/Othello
 def make_two_players(self):
     while True:
         ps = input(
             "Please select two player`s type:\n\t0.Human\n\t1.AI\nSuch as:0 0\n:"
         )
         pss = ps.split(' ')
         if len(pss) != 2:
             print('\nWrong choice, please enter numbers as example')
             continue
         elif len(pss) == 2:
             p1, p2 = [int(p) for p in ps.split(' ')]
             if p1 > 1 or p2 > 1:
                 print('\nWrong choice, please enter numbers as example')
                 continue
             break
     while True:
         if p1 == 1 and p2 == 1:
             level_ix1 = int(
                 input(
                     "Please select the level of AI player1.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix1 > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             level_ix2 = int(
                 input(
                     "Please select the level of AI player2.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix2 > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             player1 = AIPlayer('X', level_ix1)
             player2 = AIPlayer('O', level_ix2)
             break
         elif p1 == 1 or p2 == 1:
             level_ix = int(
                 input(
                     "Please select the level of AI player.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             else:
                 if p1 == 0:
                     player1 = HumanPlayer('X')
                     player2 = AIPlayer('O', level_ix)
                     break
                 elif p2 == 0:
                     player1 = AIPlayer('X', level_ix)
                     player2 = HumanPlayer('O')
                     break
         else:
             player1, player2 = HumanPlayer('X'), HumanPlayer('O')
             break
     return player1, player2
예제 #8
0
 def _test_all_moves(self, board, player):
     # Try each possible move
     for move in board.open_moves():
         # Try a move, then let the AI go again
         new_board = Board(board.x_first)
         new_board._state = board._state
         new_board.move(move, not player.player)
         if(self._game_over(new_board)):
             continue
         new_player = AIPlayer(player.player, new_board)
         new_player.next_move()
         if(self._game_over(new_board)):
             continue
         self._test_all_moves(new_board, new_player)
예제 #9
0
 def botVsbot(self):
     self.redSide = LimitAIPlayer("BOT limit", redSide=True)
     self.notRedSide = AIPlayer("BOT mini", redSide=False)
     self.game = Game(self.redSide, self.notRedSide)
     self.game.printBoard()
     while not self.game.isEnd():
         self.redSideMove()
         if not self.game.isEnd():
             self.notRedSideMove()
             if self.game.isEnd():
                 self.printResult()
             continue
         else:
             self.printResult()
예제 #10
0
    def eval_fn(self, best_logic, new_logic, game_rounds):
        players = [AIPlayer(0, new_logic, monitor=False)]
        players += [AIPlayer(i, best_logic, monitor=False) for i in range(1, self.player_num)]
        game = self.new_game(players=players)
        # cumulative_result = [0] * len(self.player_num)
        cumulative_result = np.zeros((self.player_num, ), dtype=float)
        for i in range(game_rounds):
            result = game.start()
            cumulative_result += np.array(result)
            # for i, single_result in enumerate(result):
            #     cumulative_result[i] += result

        avg_result = cumulative_result / game_rounds
        # avg_result = [result * 1.0 / game_rounds for result in cumulative_result]
        return avg_result
예제 #11
0
파일: game.py 프로젝트: javedr8/Cassino
    def add_player(self, name, difficulty):
        if difficulty == 5:
            self.players.append(Player(name))
        else:
            self.players.append(AIPlayer(name, difficulty))

        self.one_human = self.is_only_one_human()
예제 #12
0
 def test_playerMove1(self):
     self.playerAI = AIPlayer("X")
     self.testGame.makeMove((6, 6), "X")
     self.testGame.makeMove((7, 6), "X")
     self.testGame.makeMove((7, 7), "X")
     self.testGame.makeMove((8, 6), "X")
     self.testGame.makeMove((6, 8), "O")
     self.testGame.makeMove((7, 8), "O")
     self.testGame.makeMove((8, 7), "O")
     self.testGame.makeMove((9, 6), "O")
     # print(self.testGame.getPlayerScore("X"), self.testGame.getPlayerScore("O"))
     coord = self.playerAI.makeMove(self.testGame)
     possiblePlay1 = (6, 9)
     possiblePlay2 = (10, 5)
     # print(coord)
     self.assertTrue(coord == possiblePlay1 or coord == possiblePlay2)
예제 #13
0
 def create_p_vs_ai_game(cls):
     p_name = cls._prompt_name("Player", [])
     ai_diff = cls._prompt_difficulty("AI")
     print()
     p = HumanPlayer(p_name)
     ai = AIPlayer("Bot", ai_diff)
     return Game(p, ai)
예제 #14
0
 def self_play(self, logic, game_rounds, temperature=None):
     if not callable(temperature):
         t = lambda round: 1.0
     else:
         t = temperature
     players = [AIPlayer(i, logic, monitor=True) for i in range(self.player_num)]
     game = self.new_game(players=players)
     statuses = list()
     actions = list()
     results = list()
     rounds = list()
     for i in range(game_rounds):
         result = game.start()
         history = players[0].get_singleton_history()
         for player_idx, status, action, round in history:
             statuses.append(status)
             actions.append(action) # dict
             results.append(result[player_idx])
             rounds.append(round)
         # print("PLAY | Round %d/%d. %d entries of history." % (i, game_rounds, len(history)))
         players[0].reset_history()
     x = np.array(statuses,)
     y = np.zeros((len(actions), self.policy_width+1,), float)
     for i, action in enumerate(actions):
         for key, value in action.items():
             y[i, key] = value
         y[i] = np.power(y[i], t(rounds[i]))
         squaresum = np.sum(y[i])
         y[i] /= squaresum
         y[i, -1] = results[i]
     return x, y
예제 #15
0
def main():
    script_dir = os.path.dirname(__file__)
    # Set up the player.
    with open(os.path.join(script_dir, 'go-player.config')) as f:
        player_config = json.load(f)
    player = StateProxyPlayer(
        AIPlayer(
            PrioritizeCaptureStrategy(
                max_search_depth=player_config["depth"])))

    # Connect to server.
    with open(os.path.join(script_dir, 'go.config')) as f:
        network_config = json.load(f)
    clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    while True:
        try:
            time.sleep(1)
            clientsocket.connect(
                (network_config["IP"], network_config["port"]))
            break
        except OSError:
            continue

    while True:
        # Get commands from server and relay to player.
        data = clientsocket.recv(8192).decode()
        if not data:
            break
        json_input = json.loads(data)
        result = command_player(player, json_input)
        if result:
            clientsocket.send(utils.jsonify(result).encode())

    clientsocket.close()
예제 #16
0
    def __init__(self, output, num_players=8):

        self.output = output
        self.players = [AIPlayer(x + 1) for x in range(num_players)]
        #self.players = [AIPlayer('Robit'), HumanPlayer("Bob")]
        self.output(self.players)
        self.board = Board(self.players)

        self.start_game()
예제 #17
0
def create_newgame(model=None,
                   player1AI=None,
                   player2AI=None,
                   gui=True,
                   stepmode=False):
    '''Creates a new game. If no_gui, both players must be AI players'''
    if not gui:
        '''No GUI'''
        if player1AI is not None and player2AI is not None:
            player1 = AIPlayer(1, model, player1AI)
            player2 = AIPlayer(2, model, player2AI)
            game = connectk.ConnectK(model, player1, player2)
            p = Thread(target=game.play)
            p.start()
            return
        else:
            raise NoGUIError(
                "If no GUI option is used, both players must be AIs.")
    else:
        '''GUI'''
        root = TK.Tk()
        if model is None:
            model = BoardModel()  #New instance with default settings
        gui = ConnectKGUI(root, model)
        if stepmode:
            gui.stepmode.set(True)

        if player1AI is None:
            player1 = GUIPlayer(1, model)
            gui.add_button_listener(player1.action_listener, 1)
        else:
            player1 = AIPlayer(1, model, player1AI)

        if player2AI is None:
            player2 = GUIPlayer(2, model)
            gui.add_button_listener(player2.action_listener, 2)
        else:
            player2 = AIPlayer(2, model, player2AI)

        game = connectk.ConnectK(model, player1, player2, gui)
        p = Thread(target=game.play)
        gui.update_gui(time=2)
        p.start()
        root.mainloop()
예제 #18
0
파일: game.py 프로젝트: shaohy/Tic-tac-toe
 def _make_controller(colour, controller_type):
     """
     Returns a controller with the specified colour.
     "player" == Player,
     "ai" == AiPlayer.
     """
     if controller_type == "player":
         return Player(colour)
     else:
         return AIPlayer(colour)
예제 #19
0
 def create_players(self):
     print( "X goes first.")
     self.human_player = HumanPlayer(game = self)
     self.ai_player    = AIPlayer(game = self)
     self.human_player.set_playing_letter(self.letter_choice())
     self.ai_player.set_playing_letter({"X":"O","O":"X"}.get(self.human_player.playing_letter))
     print "[DEBUG] ai_player plays as",self.ai_player.playing_letter
     print "[DEBUG] human player plays as",self.human_player.playing_letter
     # We need an ordered list for the mainloop
     return self.human_first() and [self.human_player,self.ai_player] or [self.ai_player,self.human_player]
예제 #20
0
class TestMinimax(unittest.TestCase):
    def setUp(self):
        self.testDonkey = AIPlayer("testDonkey", "x")

    def tearDown(self):
        del self.testDonkey

    def test_move_valid(self):
        """Test if AIPlayer.move() returns valid col No.
        So whatever column ai chooses, in any case it should be valid, ie. not full.
        Requires that board is not full.
        """
        for b in allBoards:
            with self.subTest(b=b):
                self.assertIn(self.testDonkey.move(b), b.nonFullCols())

    def test_move_avert_defeat(self):
        """Test if ai averts defeat if this is necessary and possible.
        """
        #In Board 'bNoWin2' defeat can be averted by moving to 4 (starts at 0)
        self.assertEqual(self.testDonkey.move(bNoWin2), 4)
예제 #21
0
def AIPlayerTests_testInit():
    print("TEST -- AIPlayerTests_testInit :")
    succes = True

    try:
        player = AIPlayer("rat", "AIs/Test_Rat1.py", (0, 0), False, (10, 10),
                          100, 200)
    except ArgsException as e:
        print("-->Test 0 : ArgsException occurred but should not. Value :", e)

    if type(player._q1ToAI) != multiprocessing.queues.Queue:
        print("-->Test 1 : Error with player._q1ToAI. \n Received : " +
              str(player._q1ToAI) + " (" + str(type(player._q1ToAI)) + ")")
        succes = False
    if type(player._q2FromAI) != multiprocessing.queues.Queue:
        print("-->Test 2 : Error with player._q2FromAI. \n Received : " +
              str(player._q2FromAI) + " (" + str(type(player._q2FromAI)) + ")")
        succes = False
    if type(player._process) != multiprocessing.context.Process:
        print("-->Test 3 : Error with player._process. \n Received : " +
              str(player._process) + " (" + str(type(player._process)) + ")")
        succes = False
    if type(player._name) != str or player._name != "Triple-patte":
        print("-->Test 4 : Error with name. \n Received : " +
              str(player._name) + " (" + str(type(player._name)) + ")")
        succes = False

    try:
        player = AIPlayer("rat", "InexistantFile", (0, 0), False, (10, 10),
                          100, 200)
    except ArgsException as e:
        print("-->Test 5 : ArgsException occurred but should not. Value :", e)

    if type(player._name) != str or player._name != "Dummy":
        print("-->Test 6 : Error with name. \n Received : " +
              str(player._name) + " (" + str(type(player._name)) + ")")
        succes = False

    return succes
예제 #22
0
 def __init__(self, num_players=1, difficulty=3, debug=False):
     # Initialize colorama to enable styled terminal output on Windows
     init()
     # 2-person games and 2-AI games are only for testing right now
     self.players = []
     if num_players == 0:
         self.players.append(
             AIPlayer(self.player_victory,
                      0,
                      difficulty=difficulty,
                      verbose=debug))
         self.players.append(
             AIPlayer(self.player_victory,
                      1,
                      difficulty=difficulty,
                      verbose=debug))
     elif num_players == 1:
         self.players.append(HumanPlayer(self.player_victory, 0))
         self.players.append(
             AIPlayer(self.player_victory,
                      1,
                      difficulty=difficulty,
                      verbose=debug))
     elif num_players == 2:
         self.players.append(HumanPlayer(self.player_victory, 0))
         self.players.append(HumanPlayer(self.player_victory, 1))
     self.difficulty = difficulty
     self.messages = [Message()]
     self.debug = debug
     self.deck = Deck()
     self.crib = Hand()
     self.upcard = Card()
     self.pegging_cards = []
     self.pegging_count = -1
     self.dealer = -1
     self.pone = -1
예제 #23
0
    def __init__(self, players, roles, include_ai=0):
        if len(roles) != len(players) + 3 + (include_ai):
            raise Exception('you done fd up. %s != %s' % (players, roles))

        self.roles = [Role(r) for r in roles]
        self.players = [
            Player(p.name, inform=p.inform, ask=p.ask) for p in players
        ] + [Center(i) for i in range(3)]
        for i in range(include_ai):
            self.players.append(
                AIPlayer('AI_' + str(i), self.roles, self.players))
        self.assignment = Assignment({}, roles)
        self.assign()
        self.inform_players()
        print self.assignment
예제 #24
0
    def __init__(self, enableAiPlayer):
        pygame.init()

        self.is_ai_player = enableAiPlayer
        self.wm = None
        if not self.is_ai_player:
            self.player = KeyboardPlayer()

        self.screen = pygame.display.set_mode((config.SCREEN_WIDTH, config.SCREEN_HEIGHT))
        self.asphalt = (pygame.image.load(os.path.join("drawable/asphalt.png"))).convert()
        self.sky = (pygame.image.load(os.path.join("drawable/sky.png"))).convert()

        self.kX = config.SCREEN_WIDTH / config.SPACE_WIDTH
        self.kY = config.SCREEN_HEIGHT / config.SPACE_HEIGHT

        self.init_display()
예제 #25
0
 def policy_evaluate(self,
                     n_playout_ai=400,
                     n_playout_mcts=100,
                     n_games=10):
     """
     策略胜率评估:模型与纯MCTS玩家对战n局看胜率
         n_playout_ai    ai预测每个action的mcts模拟次数
         n_playout_mcts  纯mcts随机走子时每个action的mcts模拟步数
         n_games         策略评估胜率时的模拟对局次数
     """
     logging.info("__policy_evaluate__")
     # ai玩家(使用策略价值网络来指导树搜索和评估叶节点)
     ai_player = AIPlayer(self.policy_value_net.policy_value_fn,
                          n_playout=n_playout_ai)
     # 纯mcts玩家
     mcts_player = MCTSPlayer(n_playout=n_playout_mcts)
     win_cnt = {'ai': 0, 'mcts': 0, 'tie': 0}
     for i in range(n_games):  # 对战
         if i % 2 == 0:  # ai first
             logging.info("policy evaluate start: {}, ai use W".format(i +
                                                                       1))
             winner = self.game.start_play(ai_player, mcts_player)
             if winner == 0:
                 win_cnt['ai'] += 1
             elif winner == 1:
                 win_cnt['mcts'] += 1
             else:
                 win_cnt['tie'] += 1
         else:  # mcts first
             logging.info("policy evaluate start: {}, ai use B".format(i +
                                                                       1))
             winner = self.game.start_play(mcts_player, ai_player)
             if winner == 0:
                 win_cnt['mcts'] += 1
             elif winner == 1:
                 win_cnt['ai'] += 1
             else:
                 win_cnt['tie'] += 1
         # win_cnt[winner] += 1
         logging.info("policy evaluate res: {},{}".format(i + 1, win_cnt))
     # 胜率
     win_ratio = 1.0 * (win_cnt['ai'] + 0.5 * win_cnt['tie']) / n_games
     logging.info(
         "evaluate n_playout_mcts:{}, win: {}, lose: {}, tie:{}".format(
             n_playout_mcts, win_cnt['ai'], win_cnt['mcts'],
             win_cnt['tie']))
     return win_ratio
예제 #26
0
    def __init__(self, enableAiPlayer):
        pygame.init()

        self.is_ai_player = enableAiPlayer
        self.wm = None
        if not self.is_ai_player:
            self.player = KeyboardPlayer()

        self.screen = pygame.display.set_mode(
            (config.SCREEN_WIDTH, config.SCREEN_HEIGHT))
        self.asphalt = (pygame.image.load(
            os.path.join("drawable/asphalt.png"))).convert()
        self.sky = (pygame.image.load(
            os.path.join("drawable/sky.png"))).convert()

        self.kX = config.SCREEN_WIDTH / config.SPACE_WIDTH
        self.kY = config.SCREEN_HEIGHT / config.SPACE_HEIGHT

        self.init_display()
예제 #27
0
 def createPlayer(animal, file, location, randomStart, mazeSize, preparationTime, turnTime):
             
     if animal != "rat" and animal != "python":
         raise ArgsException("PlayerFactory.createPlayer : animal is incorrect") 
     
     if type(file) != str:
         raise ArgsException("PlayerFactory.createPlayer : file is not a string")         
     
     if type(mazeSize) != tuple:
         raise ArgsException("PlayerFactory.createPlayer : mazeSize is not a tuple")
     if type(mazeSize[0]) != int or type(mazeSize[1]) != int:
         raise ArgsException("PlayerFactory.createPlayer : mazeSize is not a tuple of int")  
     if mazeSize[0]<0 or mazeSize[1]<0 :
         raise ArgsException("PlayerFactory.createPlayer : mazeSize should not negative")               
     
     if type(location) != tuple:
         raise ArgsException("PlayerFactory.createPlayer : Location is not a tuple")
     if type(location[0]) != int or type(location[1]) != int:
         raise ArgsException("PlayerFactory.createPlayer : Location is not a tuple of int")
     if location[0]<0 or location[0]>=mazeSize[0] or location[1]<0 or location[1]>=mazeSize[1]:
         raise ArgsException("PlayerFactory.createPlayer : Location is not in the maze")
     
     if type(randomStart) != bool:
         raise ArgsException("PlayerFactory.createPlayer : randomStart is not a boolean")
     
     if type(preparationTime) != int:
         raise ArgsException("PlayerFactory.createPlayer : preparationTime is not a int")  
     if preparationTime < 0:
         raise ArgsException("PlayerFactory.createPlayer : preparationTime is negative") 
     
     if type(turnTime) != int:
         raise ArgsException("PlayerFactory.createPlayer : turnTime is not a int")  
     if turnTime < 0:
         raise ArgsException("PlayerFactory.createPlayer : turnTime is negative")           
         
     if file == "":
         return InactivePlayer(location, randomStart, mazeSize)
     elif file == "human" :
         return HumanPlayer(location, randomStart, mazeSize)
     else :
         return AIPlayer(animal, file, location, randomStart, mazeSize, preparationTime, turnTime)
예제 #28
0
 def setUp(self):
     self.testDonkey = AIPlayer("testDonkey", "x")
예제 #29
0
class Game:
    def __init__(self,board_size=3):
        self.board_size = board_size
        self.reset()

    def reset(self):
        self.board = Board(self,self.board_size)
        
    def intro(self):
        print('Welcome to Jose\'s Unbeatable Tic Tac Toe!')
        print """

        Use your keypad as if it were the board
        
        7 | 8 | 9
        ---------
        4 | 5 | 6
        ---------
        1 | 2 | 3
        
        Have fun, and good luck.
        """

    def letter_choice(self):
        letter = None
        while not (letter == 'X' or letter == 'O'):
            print('Do you want to be X or O?')
            letter = raw_input().upper()

        return letter

    def create_players(self):
        print( "X goes first.")
        self.human_player = HumanPlayer(game = self)
        self.ai_player    = AIPlayer(game = self)
        self.human_player.set_playing_letter(self.letter_choice())
        self.ai_player.set_playing_letter({"X":"O","O":"X"}.get(self.human_player.playing_letter))
        print "[DEBUG] ai_player plays as",self.ai_player.playing_letter
        print "[DEBUG] human player plays as",self.human_player.playing_letter
        # We need an ordered list for the mainloop
        return self.human_first() and [self.human_player,self.ai_player] or [self.ai_player,self.human_player]

    def human_first(self):
        return self.human_player.playing_letter == "X"
        
    def play_again(self):
        print('Do you want to play again? (yes or no)')
        return (raw_input().lower().startswith('y'))

    def mainloop(self):
        players         = self.create_players()
        game_is_playing = True
        while game_is_playing:
            for player in players :
                player.play()
                #self.board.show()
                if player.wins():
                    print "[DEBUG] show board after win"
                    self.board.show()                    
                    player.display_winning_message()
                    # gets out of the while loop
                    game_is_playing = False
                    # gets out of the foor loop
                    break
                elif self.board.is_full():
                    self.board.show()
                    print('The game is a tie.')
                    # gets out of the while loop
                    game_is_playing = False
                    # gets out of the foor loop
                    break

        return self.play_again()
예제 #30
0
# 导入玩家基类
from player import Player, RandomPlayer, HumanPlayer, AIPlayer
from board import Board
from game import Game
import random



if __name__ == "__main__":
    # black_player = RandomPlayer("X")
    # white_player = AIPlayer("O", 1)
    black_player = AIPlayer("X", 0)
    white_player = AIPlayer("O", 1)


    # 游戏初始化,第一个玩家是黑棋,第二个玩家是白棋
    game = Game(black_player, white_player)
    # 开始下棋
    winner_id, result, diff = game.run()
예제 #31
0
 def set_world_model(self, wm):
     self.wm = wm
     if self.is_ai_player:
         self.player = AIPlayer(self.wm)
예제 #32
0
class GUI:
    def __init__(self, enableAiPlayer):
        pygame.init()

        self.is_ai_player = enableAiPlayer
        self.wm = None
        if not self.is_ai_player:
            self.player = KeyboardPlayer()

        self.screen = pygame.display.set_mode((config.SCREEN_WIDTH, config.SCREEN_HEIGHT))
        self.asphalt = (pygame.image.load(os.path.join("drawable/asphalt.png"))).convert()
        self.sky = (pygame.image.load(os.path.join("drawable/sky.png"))).convert()

        self.kX = config.SCREEN_WIDTH / config.SPACE_WIDTH
        self.kY = config.SCREEN_HEIGHT / config.SPACE_HEIGHT

        self.init_display()

    def set_world_model(self, wm):
        self.wm = wm
        if self.is_ai_player:
            self.player = AIPlayer(self.wm)

    def init_display(self):
        pygame.display.set_caption(config.WINDOW_NAME)

        # Calculate drawn area width, height, x and y
        self.daWitdh = self.screen.get_size()[0]
        self.daHeight = self.screen.get_size()[1] - (self.sky.get_size()[1])
        self.daX = 0
        self.daY = self.sky.get_size()[1]
        self.daRect = pygame.Rect(self.daX,
                                  self.daY,
                                  self.daWitdh,
                                  self.daHeight)

        # Create drawn area background
        self.drawnArea = (pygame.Surface((self.daWitdh, self.daHeight))).convert()
        self.drawnArea.fill(config.BACKGROUND_COLOR)

        # Drawing images on the background
        screenY = self.screen.get_size()[1]

        self.screen.blit(self.drawnArea, (self.daX, self.daY))
        self.screen.blit(self.sky, (0, 0))
        self.screen.blit(self.asphalt, (0, screenY - self.asphalt.get_size()[1]))

        pygame.display.flip()

    def draw(self):
        self.clean_background()
        self.draw_cart_and_pendulum()
        pygame.display.update(self.daRect)

    def draw_cart_and_pendulum(self):
        screenY = self.screen.get_size()[1]

        pendulum = self.wm.get_pendulum()
        cart = self.wm.get_cart()

        # calculate cart position
        cartX = cart.pos * self.kX - cart.drawable.get_size()[0] / 2
        cartY = screenY - self.asphalt.get_size()[1] - cart.drawable.get_size()[1]

        # calculate pendulum position
        angle = radians(pendulum.angle); cosp = cos(angle); sinp = sin(angle)

        poviotX=cart.pos*self.kX
        poviotY=cartY
        pendulumX=poviotX-100*sinp
        pendulumY=poviotY-100*cosp

        # draw the on the screen
        self.screen.blit(self.asphalt, (0, screenY - self.asphalt.get_size()[1]))
        self.screen.blit(cart.drawable, (cartX, cartY))
        pygame.draw.line(self.screen, config.ROD_COLOR, [poviotX, poviotY], [pendulumX,pendulumY], 7)
        self.screen.blit(pendulum.main_drawable, (pendulumX - pendulum.main_drawable.get_size()[0]/2, pendulumY -pendulum.main_drawable.get_size()[1]/2))

    def get_action(self):
        for event in pygame.event.get():
            if event.type == pygame.locals.QUIT:
                raise OnExitException()

        return self.player.get_next_move()

    def clean_background(self):
        self.screen.blit(self.drawnArea, (self.daX, self.daY))

    def close(self):
        pygame.quit()
        sys.exit()
예제 #33
0
def AIPlayerTests_argstest():
    print("TEST -- AIPlayerTests_argstest :")
    succes = True

    #Tests for the arguments
    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, 10, 100, 200)
        print(
            "-->Test 1 : ArgsException should occurre, mazeSize is not a tuple"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (True, 10), 100, 200)
        print(
            "-->Test 2 : ArgsException should occurre, mazeSize is not a tuple of int"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, "ok"), 100, 200)
        print(
            "-->Test 3 : ArgsException should occurre, mazeSize is not a tuple of int"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (-10, 10), 100, 200)
        print("-->Test 4 : ArgsException should occurre, mazeSize is negative")
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, -10), 100, 200)
        print("-->Test 5 : ArgsException should occurre, mazeSize is negative")
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", False, False, (10, 10), 100, 200)
        print(
            "-->Test 6 : ArgsException should occurre, location is not a tuple"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, True), False, (10, 10), 100, 200)
        print(
            "-->Test 7 : ArgsException should occurre, location is not a tuple of int"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", ("ok", 0), False, (10, 10), 100, 200)
        print(
            "-->Test 8 : ArgsException should occurre, location is not a tuple of int"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (-10, 0), False, (10, 10), 100, 200)
        print(
            "-->Test 9 : ArgsException should occurre, location is outside the maze"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, -10), False, (10, 10), 100, 200)
        print(
            "-->Test 10 : ArgsException should occurre, location is outside the maze"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (10, 0), False, (10, 10), 100, 200)
        print(
            "-->Test 11 : ArgsException should occurre, location is outside the maze"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 10), False, (10, 10), 100, 200)
        print(
            "-->Test 12 : ArgsException should occurre, location is outside the maze"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), 0, (10, 10), 100, 200)
        print(
            "-->Test 13 : ArgsException should occurre, randomStart is not a boolean"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer(1010, "AIs/RatTest.py", (0, 0), False, (10, 10), 100, 200)
        print(
            "-->Test 14 : ArgsException should occurre, animal is not a string"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", 5658, (0, 0), False, (10, 10), 100, 200)
        print(
            "-->Test 15 : ArgsException should occurre, file is not a string")
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, 10), False, 200)
        print(
            "-->Test 16 : ArgsException should occurre, preparationTime is not a int"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, 10), -100, 200)
        print(
            "-->Test 17 : ArgsException should occurre, preparationTime is not negative"
        )
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, 10), 100,
                 "hello")
        print(
            "-->Test 18 : ArgsException should occurre, turnTime is not a int")
        succes = False
    except ArgsException as e:
        ()

    try:
        AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, 10), 100, -200)
        print(
            "-->Test 19 : ArgsException should occurre, turnTime is not negative"
        )
        succes = False
    except ArgsException as e:
        ()

    return succes
예제 #34
0
def AIPlayerTests_testMoveFunctions():
    print("TEST -- AIPlayerTests_testMoveFunctions :")
    succes = True

    player = AIPlayer("rat", "AIs/Test_Rat1.py", (0, 0), False, (10, 10), 100,
                      200)

    #Test cellOfDecision
    cell = player.cellOfDecision("U")
    if cell != (0, 1):
        print("-->Test 1 : Error with cellOfDecision(U). \n Result : " +
              str(cell) + " instead of (0,1)")
        succes = False
    cell = player.cellOfDecision("D")
    if cell != (0, -1):
        print("-->Test 2 : Error with cellOfDecision(D). \n Result : " +
              str(cell) + " instead of (0,-1)")
        succes = False
    cell = player.cellOfDecision("L")
    if cell != (-1, 0):
        print("-->Test 3 : Error with cellOfDecision(L). \n Result : " +
              str(cell) + " instead of (-1,0)")
        succes = False
    cell = player.cellOfDecision("R")
    if cell != (1, 0):
        print("-->Test 4 : Error with cellOfDecision(R). \n Result : " +
              str(cell) + " instead of (1,0)")
        succes = False
    cell = player.cellOfDecision("None")
    if cell != (0, 0):
        print("-->Test 5 : Error with cellOfDecision(None). \n Result : " +
              str(cell) + " instead of (0,0)")
        succes = False
    cell = player.cellOfDecision("invalid")
    if cell != (0, 0):
        print("-->Test 6 : Error with cellOfDecision(invalid). \n Result : " +
              str(cell) + " instead of (0,0)")
        succes = False
    cell = player.cellOfDecision(300)
    if cell != (0, 0):
        print("-->Test 7 : Error with cellOfDecision(300). \n Result : " +
              str(cell) + " instead of (0,0)")
        succes = False

    player.reduceStuckTurns()
    player.move("L", mazeInfo.getMaze())
    if player.getStuckTurns() != -1:
        print("-->Test 8 : Error with move. : " + "Result : " +
              str(player.getStuckTurns()) + " instead of -1")
        succes = False
    if player.getLocation() != (0, 0):
        print("-->Test 9 : Error with move. : " + "Result : " +
              str(player.getLocation()) + " instead of (0,0)")
        succes = False
    if player.getMoves() != 0:
        print("-->Test 10 : Error with move. : " + "Result : " +
              str(player.getMoves()) + " instead of 0")
        succes = False
    if player.getMissedTurns() != 1:
        print("-->Test 11 : Error with move. : " + "Result : " +
              str(player.getMissedTurns()) + " instead of 1")
        succes = False
    if player.getMudFence() != 0:
        print("-->Test 12 : Error with move. : " + "Result : " +
              str(player.getMudFence()) + " instead of 0")
        succes = False

    player.reduceStuckTurns()
    player.move("R", mazeInfo.getMaze())
    if player.getStuckTurns() != 1:
        print("-->Test 13 : Error with move. : " + "Result : " +
              str(player.getStuckTurns()) + " instead of 1")
        succes = False
    if player.getLocation() != (1, 0):
        print("-->Test 14 : Error with move. : " + "Result : " +
              str(player.getLocation()) + " instead of (1,0)")
        succes = False
    if player.getMoves() != 1:
        print("-->Test 15 : Error with move. : " + "Result : " +
              str(player.getMoves()) + " instead of 1")
        succes = False
    if player.getMissedTurns() != 1:
        print("-->Test 16 : Error with move. : " + "Result : " +
              str(player.getMissedTurns()) + " instead of 1")
        succes = False
    if player.getMudFence() != 0:
        print("-->Test 17 : Error with move. : " + "Result : " +
              str(player.getMudFence()) + " instead of 0")
        succes = False

    player.reduceStuckTurns()
    player.move("L", mazeInfo.getMaze())
    if player.getStuckTurns() != 1:
        print("-->Test 18 : Error with move. : " + "Result : " +
              str(player.getStuckTurns()) + " instead of 1")
        succes = False
    if player.getLocation() != (0, 0):
        print("-->Test 19 : Error with move. : " + "Result : " +
              str(player.getLocation()) + " instead of (0,0)")
        succes = False
    if player.getMoves() != 2:
        print("-->Test 20 : Error with move. : " + "Result : " +
              str(player.getMoves()) + " instead of 2")
        succes = False
    if player.getMissedTurns() != 1:
        print("-->Test 21 : Error with move. : " + "Result : " +
              str(player.getMissedTurns()) + " instead of 1")
        succes = False
    if player.getMudFence() != 0:
        print("-->Test 22 : Error with move. : " + "Result : " +
              str(player.getMudFence()) + " instead of 0")
        succes = False

    player.reduceStuckTurns()
    player.move("U", mazeInfo.getMaze())
    if player.getStuckTurns() != 1:
        print("-->Test 23 : Error with move. : " + "Result : " +
              str(player.getStuckTurns()) + " instead of 1")
        succes = False
    if player.getLocation() != (0, 1):
        print("-->Test 24 : Error with move. : " + "Result : " +
              str(player.getLocation()) + " instead of (0,1)")
        succes = False
    if player.getMoves() != 3:
        print("-->Test 25 : Error with move. : " + "Result : " +
              str(player.getMoves()) + " instead of 3")
        succes = False
    if player.getMissedTurns() != 1:
        print("-->Test 26 : Error with move. : " + "Result : " +
              str(player.getMissedTurns()) + " instead of 1")
        succes = False
    if player.getMudFence() != 0:
        print("-->Test 27 : Error with move. : " + "Result : " +
              str(player.getMudFence()) + " instead of 0")
        succes = False

    player.reduceStuckTurns()
    player.move("U", mazeInfo.getMaze())
    if player.getStuckTurns() != 1:
        print("-->Test 28 : Error with move. : " + "Result : " +
              str(player.getStuckTurns()) + " instead of 1")
        succes = False
    if player.getLocation() != (0, 2):
        print("-->Test 29 : Error with move. : " + "Result : " +
              str(player.getLocation()) + " instead of (0,2)")
        succes = False
    if player.getMoves() != 4:
        print("-->Test 30 : Error with move. : " + "Result : " +
              str(player.getMoves()) + " instead of 4")
        succes = False
    if player.getMissedTurns() != 1:
        print("-->Test 31 : Error with move. : " + "Result : " +
              str(player.getMissedTurns()) + " instead of 1")
        succes = False
    if player.getMudFence() != 0:
        print("-->Test 32 : Error with move. : " + "Result : " +
              str(player.getMudFence()) + " instead of 0")
        succes = False

    player = AIPlayer("rat", "AIs/RatTest.py", (0, 0), False, (10, 10), 100,
                      200)
    test = player.isOnAPieceOfCheese(mazeInfo)
    if test:
        print("-->Test 33 : Error with isOnAPieceOfCheese. : " + "Result : " +
              str(test) + " instead of False")
        succes = False

    player._location = (9, 0)
    player._stuckTurns = 2
    test = player.isOnAPieceOfCheese(mazeInfo)
    if test:
        print("-->Test 34 : Error with isOnAPieceOfCheese. : " + "Result : " +
              str(test) + " instead of False")
        succes = False

    player._stuckTurns = -2
    test = player.isOnAPieceOfCheese(mazeInfo)
    if (test):
        print("-->Test 35 : Error with isOnAPieceOfCheese. : " + "Result : " +
              str(test) + " instead of False")
        succes = False

    return succes
예제 #35
0
    game.printBoard()

    letter = "X"

    # TODO: or no more available coords
    while game.winner == None:
        print("Player " + letter + " move")
        if letter == "X":
            pos = playerX.makeMove(game)
            # game.moves["X"].append(pos)
        else:
            pos = playerO.makeMove(game)
            # game.moves["O"].append(pos)
        print("X score: ", game.getPlayerScore("X"))
        print("O score: ", game.getPlayerScore("O"))

        game.printBoard()
        print(game.moves)

        # swap player
        letter = "X" if letter == "O" else "O"

    return


if __name__ == "__main__":
    g = Game()
    playerX = AIPlayer("X")
    playerO = AIPlayer("O")
    play(g, playerX, playerO)
예제 #36
0
    pygame.display.update()
    pygame.time.wait(1000)
    game_running = False


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if check_clicked(PLAYER1_BUTTON_POS, PLAYER_BUTTON_SIZE,
                             event.pos):
                #  player 1 button pressed
                if type(player1) == Person:
                    player1 = AIPlayer(1)
                else:
                    player1 = Person(1)
            elif check_clicked(PLAYER2_BUTTON_POS, PLAYER_BUTTON_SIZE,
                               event.pos):
                #  player 2 button pressed
                if type(player2) == Person:
                    player2 = AIPlayer(2)
                else:
                    player2 = Person(2)
            elif check_clicked(START_BUTTON_POS, START_BUTTON_SIZE, event.pos):
                #  start button pressed
                run_game()

    refresh_screen()
    clock.tick(30)
예제 #37
0
    def make_two_players(self):
        player1 = AIPlayer('X', 2)
        player2 = AIPlayer('O', 2)

        return player1, player2
예제 #38
0
            elif a == 1:
                pygame.draw.circle(screen, (100, 100, 255), (x, y),
                                   cycleRadius - 10)
            else:
                pygame.draw.circle(screen, (255, 100, 100), (x, y),
                                   cycleRadius - 10)

            x += 2 * cycleRadius
        y += 2 * cycleRadius

    pygame.display.flip()


# -----------
player1 = Person("player 1", 1)
player2 = AIPlayer("AI player", 2)

currentPlayer = player2

refresh_screen()
droppedCount = 0
allSlots = len(gameBoard.game_map) * len(gameBoard.game_map[0])
while droppedCount != allSlots:
    dropped = False
    if type(currentPlayer) == Person:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.MOUSEMOTION:
                posX = event.pos[0]
                if posX < len(gameBoard.game_map[0]) * cycleRadius * 2:
예제 #39
0
# 导入黑白棋文件
from player import Player, RandomPlayer, HumanPlayer, AIPlayer
from game import Game

# AI玩家黑棋初始化
# Alpha-Beta
# black_player = AIPlayer("X", 1)
# MCTS
black_player = AIPlayer("X")

# 人类玩家黑棋初始化
# black_player = HumanPlayer("X")

# AI玩家白棋初始化
# Alpha-Beta
# white_player = AIPlayer("O", 1)
# MCTS
white_player = AIPlayer("O")

# 游戏初始化,第一个玩家是黑棋,第二个玩家是白棋
game = Game(black_player, white_player)

# 开始下棋
game.run()