def setPlayer(self, playerNumber, playerType): if playerNumber == 1: if playerType == "Human": self.player1 = HumanPlayer() elif playerType == "BotRand": self.player1 = BotPlayer("rand") elif playerType == "BotMaterial": self.player1 = BotPlayer("material") elif playerType == "BotMinimax": self.player1 = BotPlayer("minimax") elif playerType == "BotAlphaBeta": self.player1 = BotPlayer("alphabeta") self.player1.set_color(chess.WHITE) else: if playerType == "Human": self.player2 = HumanPlayer() elif playerType == "BotRand": self.player2 = BotPlayer("rand") elif playerType == "BotMaterial": self.player2 = BotPlayer("material") elif playerType == "BotMinimax": self.player2 = BotPlayer("minimax") elif playerType == "BotAlphaBeta": self.player2 = BotPlayer("alphabeta") self.player2.set_color(chess.BLACK) return True
def select_starter(self): while self.game_status.to_move is None: answer = input("Do you want to start? (Y/N)") if answer == "Y" or answer == "y": self.player1 = HumanPlayer(1) self.player2 = SimpleComputerPlayer(2) self.game_status.to_move = self.player1 self.game_status.other = self.player2 if answer == "N" or answer == "n": self.player1 = HumanPlayer(2) self.player2 = SimpleComputerPlayer(1) self.game_status.to_move = self.player2 self.game_status.other = self.player1
def spawnExtraPlayers(playerType, amount, names=None): # Returns: Array with amount of players specified. Returns object if amount == 1 if isinstance(playerType, Bot): # Spawn bots if amount == 1: return Bot() else: return [Bot() for i in range(amount)] else: # Spawn humans if amount == 1: return HumanPlayer().randomName() else: return [HumanPlayer().randomName() for i in range(amount)]
def __init__(self, algorithm, playerColor, dificulty): self.humanPlayer = HumanPlayer(playerColor) self.aiPlayer = AiPlayer(playerColor) if playerColor == "white": print("You are white") print("Enemy player is black") self.humanPlayer.lastRow = 7 self.aiPlayer.lastRow = 0 elif playerColor == "black": print("You are black") print("Enemy player is white") self.humanPlayer.lastRow = 0 self.aiPlayer.lastRow = 7 if dificulty == "low": self.depth = 2 elif dificulty == "medium": self.depth = 4 elif dificulty == "hard": self.depth = 6 self.board = Board() self.gameWinner = None for counter in self.aiPlayer.currentCounters: self.board.PutCounterOnBoardInPosition(counter.positions[0], counter.positions[1], counter.character) for counter in self.humanPlayer.currentCounters: self.board.PutCounterOnBoardInPosition(counter.positions[0], counter.positions[1], counter.character) self._restart = False
def run_test_1(): print('------- Scenario 1: Equivance of Minimax and AlphaBeta --------') #-- Scenario 1: Test to make sure MiniMaxAI and AlphaBetaAI are giving the same results #-- Here are the various players. player_human = HumanPlayer() player_mini = MinimaxAI(3, color=True) player_alphaBeta = AlphaBetaAI(3, color=True) #-- Set up the board in a the following fashion. Remember our AIs are WHITE in these scenarios. game = ChessGame(player_human, player_mini) game.board.clear_board() game.board.set_piece_at(piece=chess.Piece(4, False), square=16) game.board.set_piece_at(piece=chess.Piece(2, False), square=8) game.board.set_piece_at(piece=chess.Piece(3, False), square=10) game.board.set_piece_at(piece=chess.Piece(3, True), square=1) #-- Display the board and possible moves. print(game) print("Possible Moves:") for move in game.board.pseudo_legal_moves: print(move) print('---------------------------') #-- Look at the choice for MinimaxAI: print('Chosen Move:', player_mini.choose_move(game.board)) print('---------------------------') #-- Look at the choice for AlphaBetaAI: print('Chosen Move:', player_alphaBeta.choose_move(game.board)) print('---------------------------')
def test_type_difference(self): self.player_1 = HumanPlayer() self.player_2 = Bot() self.assertFalse( type(self.player_2) == 'HumanPlayer.HumanPlayer', "Player 1 type %s, Player 2 type %s")
def run_test_2(): print('------- Scenario 2: Take the Win! --------') #-- Scenario 2: Test to make dure MiniMax and AlphaBetaAI take the win for a more complicated scenario (4 more checkmate) in a predefined position. #-- Here are the various players. player_human = HumanPlayer() player_mini = MinimaxAI(3, color=True) player_alphaBeta = AlphaBetaAI(3, color=True) game = ChessGame(player_human, player_mini) game.board.reset() game.board.push(chess.Move(12,28)) game.board.push(chess.Move(52, 36)) game.board.push(chess.Move(5, 26)) game.board.push(chess.Move(57, 42)) game.board.push(chess.Move(3, 39)) game.board.push(chess.Move(62, 45)) #-- Display Board print(game) print('---------------------------') #-- Look at choice for MiniMaxAI print('Chosen Move:', player_mini.choose_move(game.board)) print('---------------------------') #-- Look at choice for AlphaBetaAI print('Chosen Move:', player_alphaBeta.choose_move(game.board)) print('---------------------------')
def run(config=None): if config == None: config = load_config(file_name=root_data_file + 'resnet_6_6_4.model', only_load_param=True) try: board = Board(width=config.board_width, height=config.board_height, n_in_row=config.n_in_row) game = Game(board) # --------------- human VS AI ---------------- best_policy = PolicyValueNet( config.board_width, config.board_height, Network=config.network, net_params=config.policy_param ) # setup which Network to use based on the net_params mcts_player = AlphaZeroPlayer( best_policy.predict, c_puct=config.c_puct, nplays=100, add_noise=True) # set larger nplays for better performance # uncomment the following line to play with pure MCTS # mcts_player2 = RolloutPlayer(nplays=1000, c_puct=config.c_puct) # human player, input your move in the format: 2,3 human = HumanPlayer() # set who_first=0 for human first game.start_game(human, mcts_player, who_first=1, is_shown=1) except KeyboardInterrupt: print('\n\rquit')
def test_bearoff(): board = Board() board.board = [[0, 2, 2, 3, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]] player = HumanPlayer(0) dice = Dice() return RuleBook(board, player, dice)
def test_request_user_colour(test_human_game, monkeypatch): human_player = HumanPlayer(0) computer_player = ComputerPlayer(1) monkeypatch.setattr('builtins.input', lambda x: 'b') test_human_game.request_user_colour() assert test_human_game.player1 == human_player and test_human_game.player2 == computer_player human_player = HumanPlayer(1) computer_player = ComputerPlayer(0) monkeypatch.setattr('builtins.input', lambda x: 'w') test_human_game.request_user_colour() assert test_human_game.player1 == human_player and test_human_game.player2 == computer_player
def main(args): assert args.c <= args.columns and args.c <= args.rows print('----- Parámetros -----') print('columnas: \t', args.columns) print('filas: \t\t', args.rows) print('c: \t\t', args.c) print('p: \t\t', args.p) print('----------------------') if args.blue_player is None: blue_player = HumanPlayer(BLUE) else: executable = args.blue_player.pop(0) blue_player = PlayerCommunicator(executable, args.blue_player, BLUE, RED) if args.red_player is None: red_player = HumanPlayer(RED) else: executable = args.red_player.pop(0) red_player = PlayerCommunicator(executable, args.red_player, RED, BLUE) ref = Referee(args.columns, args.rows, args.c, args.p, blue_player, red_player, show_ui=args.ui) iteration = 0 resultados = {RED: 0, BLUE: 0, TIE: 0} while args.iterations is None or args.iterations > iteration: iteration += 1 if args.first == BLUE: ganador = ref.runPlay(blue_player) elif args.first == RED: ganador = ref.runPlay(red_player) else: ganador = ref.runPlay(choice([blue_player, red_player])) resultados[ganador] += 1 print(resultados) ref.exit()
def addAllPlayers(self, player_n, bot_n): player_bucket = [] player_names = self.askPlayerNames(player_n) for i in range(player_n): if player_names: player_bucket.append(HumanPlayer(player_names[i])) else: player_bucket.append(HumanPlayer()) for i in range(bot_n): player_bucket.append(Bot().randomName()) if not self.test: shuffle(player_bucket) for p in player_bucket: self.addPlayer(p)
def play_random_game(_): players = [ HumanPlayer("Hans"), RandomPlayer("Opponent1"), RandomPlayer("Teammate"), RandomPlayer("Opponent2") ] game = Game(players) return game.play_game(choice(players)).total_points
def __init__(self, playername): # Create a list of players, one human and four computer self._playerList = [HumanPlayer(playername, self)] for i in range(1, 5): self._playerList.append(ComputerPlayer("Computer " + str(i), self)) # Get the first player firstPlayer = self._getFirstPlayer(self._playerList) print(firstPlayer.getName() + " gets to go first!") # Start the game self.newRound(firstPlayer)
def __init__(self): self.boardGui = GameGui() #self.placementGui = BoardGui() #self.placementGui = PlacementGui() self.player2 = ComputerPlayer(2) #self.human = ComputerPlayer("Player 1") self.player1 = HumanPlayer(1, self.boardGui) self.shipLengths = [2, 3, 3, 4, 5] self.numberOfShips = len(self.shipLengths) self.run()
def choose_player(kind, my_mark, their_mark): if kind == "h": return HumanPlayer(my_mark) elif kind == "c": # Currently available difficulties are: diff_low = 1 diff_high = 2 difficulty = read_int( "How clever do you want the computer to be? " "(1 and 2 i.e. stupid & slightly less so are the only current options)" ) while not diff_low <= difficulty <= diff_high: difficulty = read_int( "That is not a valid option. Please enter a number between %d and %d" % (diff_low, diff_high)) return ComputerPlayer(my_mark, their_mark, difficulty) else: print("Error with option, returning human player as default") return HumanPlayer(my_mark)
def __init__(self, player1IsHuman=True, player2IsHuman=True, numRows=6, numCols=7, winLength=4, displayTurns=False): if (player1IsHuman): self.player1 = HumanPlayer() else: self.player1 = MachinePlayer() if (player2IsHuman): self.player2 = HumanPlayer() else: self.player2 = MachinePlayer() if (player1IsHuman or player2IsHuman): self.displayTurns = True else: self.displayTurns = displayTurns self.gameBoard = Board(numRows, numCols, winLength) self.currentTurn = 1
def run_example_game(): """ Runs a complete example game. """ players = [HumanPlayer(hand_size, "Human"), DefensivePlayer(hand_size, "Player")] env = DurakEnv(players, True) done = False state = env.reset() env.render() while not done: act = (env.get_turn_player()).get_action(state, env.to_attack()) state, _, done = env.step(act) env.render() env.end_gui()
def test_decision_phase_human_to_human_pass(self): test_card = Card("2", "Hearts") extraPlayer = spawnExtraPlayers(HumanPlayer(), 1) f1 = sys.stdin f = open('../../test_data/decision_phase/decision_phase_test_#2.txt', 'r') sys.stdin = f self.humanPlayer.hand.append(test_card) self.engine.setPlayers([self.humanPlayer, extraPlayer]) self.engine.initialize() self.assertIs(self.engine.getPlayerAmount(), 2) self.engine.decisionPhase(self.humanPlayer) f.close() sys.stdin = f1 self.assertIs(self.humanPlayer.getChosenPlayer(), extraPlayer) self.assertEqual(self.humanPlayer.getChosenCard(), test_card)
def start_game(self): """We start the game with setup: first the two players place their ships. Then, while there is no winner yet, we get the move from the player and then get the move from the computer, repeatedly. Once there is a winner, the game is over and the winner's name is announced.""" self.player = HumanPlayer(self.user_player_name, controller=self) self.computer = ComputerPlayer(controller=self) self.is_human_turn = True self.winner = None self.submarine_name = None self.orientation = '>' # self.game_state = StringProperty('setup') self.user_submarines_positioned = 0 self.submarine_name = None self.orientation = '>' self.user_submarines_positioned = 0 self.screen_manager.current = 'game' self.game_state = 'setup'
def test_draw_hand(self): self.deck = Deck() self.deck.initialize() self.player_1 = HumanPlayer() # Make sure the deck is 52 cards (one full deck) self.assertIs(self.deck.currentAmount(), 52) # Player draws a full hand from the deck self.player_1.drawHand(self.deck) # Make sure after drawing that the deck takes 7 # cards away from its full total self.assertIs(self.deck.currentAmount(), 45) # Assert that the player actually has a hand self.assertIsNot(self.player_1.getHand(), []) # At least for Go Fish, the hand should be 7 # cards big when the player is starting out self.assertIs(self.player_1.countHand(), 7)
def playGameAgainstHuman(): finalPlayer = FinalPlayer( dominion, featureExtractor.newestFeatureExtractor, explorationProb=0, usingCachedWeights=True, cacheStringKey=defaultCacheStringKey, actionPlayer=ExpectimaxActionPhasePlayer(dominion)) cachedWeights = Counter() cacheWeightsBackpropagate.bpsetWeightsFromCache(dominion.startKingdom, cachedWeights, finalPlayer.cacheStringKey, 1) finalPlayer.weights = cachedWeights if cachedWeights == Counter(): print "####NO WEIGHTS FOUND####" humanPlayer = HumanPlayer(dominion) players = [] players.append(finalPlayer) players.append(humanPlayer) simulateDominion(dominion, players, numGames=1, maxTurns=100, verbose=True)
def run(config=None): if config == None: config = load_config(file_name=root_data_file + 'resnet_6_6_4.model', only_load_param=True) try: board = Board(width=config.board_width, height=config.board_height, n_in_row=config.n_in_row) #--------------------1.set player:alphazero VS human---------------------# best_policy = PolicyValueNet( config.board_width, config.board_height, Network=config.network, net_params=config.policy_param ) # setup which Network to use based on the net_params player1 = AlphaZeroPlayer( best_policy.predict, c_puct=config.c_puct, nplays=1000) #set larger nplays for better performance # uncomment the following line to play with pure MCTS #player2 = RolloutPlayer(nplays=1000, c_puct=config.c_puct) player2 = HumanPlayer() # --------------------2.set order---------------------# who_first = 0 # 0 means player1 first, otherwise player2 first # --------------------3.start game--------------------# game = Game(board, is_visualize=True) t = threading.Thread(target=game.start_game, args=(player1, player2, who_first)) t.start() game.show() except: print('\n\rquit')
def test_can_bear_off(test_bearoff, test_bar, test_rulebook): assert test_bearoff.can_bear_off() # can bear off from points indicated by the dice test_bearoff.board.board = [[0, 2, 2, 3, 2, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0]] assert not test_bearoff.can_bear_off() # one checker is not in home board test_bearoff.dice.set_dice(5, 6) test_bearoff.board.board = [[3, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]] assert test_bearoff.can_bear_off() # no checkers in points 5 and 6 but can still bear off from highest point where there are checkers test_bearoff.dice.set_dice(1, 3) test_bearoff.board.board = [[0, 2, 0, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]] assert not test_bearoff.can_bear_off() # there are checkers in higher numbered points which must be moved before bearing-off test_bearoff.player = HumanPlayer(1) assert not test_bearoff.can_bear_off()
# pip3 install python-chess # Code for testing the algorithm, and playing the AI. # To make a move, type from-square and to-square in console, no space. ex: e2e4 could be an opening move for white. import chess from RandomAI import RandomAI from HumanPlayer import HumanPlayer from MinimaxAI import MinimaxAI from AlphaBetaAI import AlphaBetaAI from ChessGame import ChessGame from IterativeAI import IterativeAI import sys player1 = HumanPlayer() player2 = AlphaBetaAI() # player2 = MinimaxAI() # player2 = IterativeAI(AlphaBetaAI(), 20) # player2 = IterativeAI(MinimaxAI(), 20) game = ChessGame(player1, player2) # function that significantly simplifies the start board def open_board(game): board = game.board board.clear() white_king = chess.Piece(6, True) black_king = chess.Piece(6, False) board.set_piece_at(chess.parse_square("a1"), white_king)
self.turn.change_turn(False) print "{} ne peut pas jouer de position legale.".format( player.name) return False # Game continues def game_loop(self): """Boucle principale de jeu.""" over = False while not over: player = self.turn.get_player() over = self.game(player) return over if __name__ == "__main__": player_X = HumanPlayer("X", "Marshall Bruce Mathers III") player_O = HumanPlayer("O", "Lesane Parish Crooks") Score = Score(player_X, player_O) print "\nTest de Score.update_score() :" # Test en changeant le score de X à 42 et celui de O à 65 Score.update_score(42, 65) if Score.black_score == 42 and Score.white_score == 65: test = "OK" else: test = "NOK" print "\nScore.update_score({},{}) => Score X : {} // Score O : {} \nResultat attendu = Score X : {} // Score O : {}".format( 42, 65, Score.black_score, Score.white_score, 42, 65) print " ---> test {}".format(test)
def getHumanVsHumanOpponents(): return (HumanPlayer(1, gameBoard), HumanPlayer(2, gameBoard))
def getAiVsHumanOpponents(): return (AIPlayer(1, gameBoard), HumanPlayer(2, gameBoard))
def test_rulebook(): board = Board() player = HumanPlayer(0) dice = Dice() return RuleBook(board, player, dice)
import sys sys.path.append('./Controller') from TicTacToe import TicTacToe from RandomBot import RandomBot from HumanPlayer import HumanPlayer if __name__ == '__main__': p1 = HumanPlayer('Human') p2 = RandomBot('Bot') A_TicTacToe = TicTacToe(3, 3, p1, p2) A_TicTacToe.run()