def test_accuse_bad_guess_of_cards(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '1L', '2L') # opponent id, first card, second card joe = HumanPlayer('joe') joe._hand = [(4, 'L'), (8, 'L'), (5, 'H'), (8, 'H')] ai = AIPlayer('ai') ai._hand = [(1, 'L'), (3, 'L'), (1, 'H'), (9, '$')] state = GameState() state.turn = 23 state.current_player = joe state.players = [joe, ai] state.evidence_cards = [(5, '$'), (5, 'L')] with captured_output() as (out, err): self.assertTrue(accuse_command(state)) self.assertEqual('Accuse\n\n' 'Your guess is: Incorrect', output(out)) accusation = state.accusations.pop() self.assertEqual('joe', accusation['player'].name) self.assertEqual('ai', accusation['accused'].name) self.assertEqual([(1, 'L'), (2, 'L')], accusation['cards']) self.assertEqual('incorrect', accusation['outcome']) self.assertEqual('ended', state.status) finally: Interactive.raw_input = old_raw_input
def test_accuse_bad_guess_of_murderer(self): try: old_raw_input = raw_input Interactive.raw_input = mock_raw_input('1', '3L', '5L') # opponent id, first card, second card joe = HumanPlayer('joe') joe._hand = [(4, 'L'), (7, 'L'), (5, 'H'), (8, 'H')] ai1 = AIPlayer('ai1') ai1._hand = [(1, 'L'), (3, 'L'), (1, 'H'), (9, '$')] ai2 = AIPlayer('ai2') ai2._hand = [(8, 'L'), (3, 'H'), (2, '$'), (3, '$')] state = GameState() state.turn = 23 state.current_player = joe state.players = [joe, ai1, ai2] state.evidence_cards = [(3, 'L'), (5, 'L')] with captured_output() as (out, err): self.assertTrue(accuse_command(state)) self.assertEqual('Accuse\n\n' 'Your guess is: Incorrect', output(out)) self.assertEqual('ended', state.status) finally: Interactive.raw_input = old_raw_input
def human_game(): white = HumanPlayer("Biały", True, 6, 3) black = HumanPlayer("Czarny", False, 0, 3) board = Board(white, black) clear() new_game(board) key_input = input("Nacisnij dowolny klawisz, aby wrocic do menu glownego") menu()
def init_game(self): print("Please choose X or O:", end = " ") self.h_letter = input() if self.h_letter == "x" or self.h_letter == "X": self.c_letter = "O" else: self.c_letter = "X" self.draw_board() self.rcp = RandomComputerPlayer(self) self.hp = HumanPlayer(self)
def test_secret_is_refused_if_no_secrets_left(self): player = HumanPlayer('joe') player._secret = 0 state = GameState() state.turn = 1 state.current_player = player with captured_output() as (out, err): turn_ended = secret_command(state) self.assertEqual('Secret already used!', output(out)) self.assertFalse(turn_ended)
def test_print_summary_at_start(self): human = HumanPlayer('john') human._hand = [(3, 'L'), (5, 'H'), (9, '$')] state = GameState() state.human_player = human state.players = [human] with captured_output() as (out, err): print_summary(state) self.assertEqual('Game Summary\n' 'Your hand: 3L 5H 9$\n' 'Secret to play: [john: 1]', output(out))
def test_determine_murderer_when_its_another_player(self): state = GameState() john = HumanPlayer('john') jim = AIPlayer('jim') jack = AIPlayer('jack') state.current_player = john state.players = [john, jim, jack] state.extra_card = (8, 'L') john._hand = [(5, 'L'), (9, 'H'), (6, '$')] jim._hand = [(4, 'L'), (7, 'L'), (3, '$')] jack._hand = [(1, 'L'), (3, 'H'), (5, '$')] accusation_cards = [(5, 'L'), (7, '$')] # => murder card = 3H self.assertEqual(jack, determine_murderer(state, accusation_cards))
def make_player(name, num): if name=='ai': return AIPlayer(num) elif name=='random': return RandomPlayer(num) elif name=='human': return HumanPlayer(num)
def make_player(name, num): if name == 'ai': return AIPlayer(num) # TODO Change this back to hand in just board elif name == 'random': return RandomPlayer(num) elif name == 'human': return HumanPlayer(num)
def test_print_summary_with_extra_card_and_low_suit(self): human = HumanPlayer('john') human._hand = [(3, 'L'), (5, 'H'), (9, '$')] human.set_low_suit('H') state = GameState() state.human_player = human state.players = [human] state.extra_card = (5, 'L') with captured_output() as (out, err): self.assertFalse(print_summary(state)) self.assertEqual( 'Game Summary\n' 'Your hand: 3L 5H 9$\n' 'Extra card: 5L\n' 'Low Suits: [john: H]\n' 'Secret to play: [john: 1]', output(out))
def min_max_game(): clear() print("Czy chcesz grac (B)ialym czy (C)zarnym?") white_black = input(">") while white_black != "B" and white_black != 'C': white_black = input("Bledna opcja! Sproboj ponownie: ") print("Podaj glebokosc przeszukiwania algorytmi min-max. Zalecena: 3") while True: try: key_input = input(">") depth = int(key_input) if (depth > 4): print( "Uwaga: Wybrano glebokosc wieksza niz 4. Algorytm moze dzialac powoli" ) break except ValueError: print('Niepoprawne znaki! Sprobuj ponownie') continue if white_black == "B": white = HumanPlayer("Biały", True, 6, 3) black = MinMaxPlayer("Czarny", False, 0, 3, depth) board = Board(white, black) clear() print("Grasz jako bialy. Powodzenia!") new_game(board) key_input = input( "Nacisnij dowolny klawisz, aby wrocic do menu glownego") menu() if white_black == "C": white = MinMaxPlayer("Biały", True, 6, 3, depth) black = HumanPlayer("Czarny", False, 0, 3) board = Board(white, black) clear() print("Grasz jako czarny. Powodzenia!") new_game(board) key_input = input( "Nacisnij dowolny klawisz, aby wrocic do menu glownego") menu()
class TestValidation(TestCase): black = HumanPlayer(Checker.BLACK) white = HumanPlayer(Checker.WHITE) logging.basicConfig(level=logging.DEBUG) def setUp(self) -> None: self.game = Game(self.black, self.white) def test_move_checkers_from_valid_to_valid_with_no_items_out_and_not_in_home_success(self): self.game.current_dice = Die(3, 4) print(self.game.board) self.assertIsNone(game_moves_are_valid(self.black, [(13, 9), (13, 10)], self.game)) def test_move_checkers_from_valid_to_invalid_target_location_with_no_items_out_and_not_in_home_fail(self): self.game.current_dice = Die(1, 4) self.assertRaises(ValueError, lambda: game_moves_are_valid(self.black, [(13, 12), (13, 9)], self.game)) def test_move_checkers_invalid_checker_fail(self): self.game.current_dice = Die(1, 4) pprint(self.game.board.board) self.assertRaises(ValueError, lambda: game_moves_are_valid(self.white, [(13, 14), (12, 8)], self.game)) def test_checker_number_all(self): loser_pos = self.game.board.get_checkers_position_of(self.white) self.assertEqual(sum(map(lambda p: len(self.game.board[p]), loser_pos)), 15) def test_checker_number_with_two_removed(self): self.game.board.remove_from(1) self.game.board.remove_from(12) loser_pos = self.game.board.get_checkers_position_of(self.white) self.assertEqual(sum(map(lambda p: len(self.game.board[p]), loser_pos)), 13) def test_two_in_out_move_black(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(0, self.black.color) self.game.board.place_at(0, self.white.color) print(self.game.board[0]) self.game.board.move(self.black.color, 0, 4) print(self.game.board[0])
def __init__(self, numHumanPlayers, numAIPlayers=0, deck=[]): #initialize and shuffle deck if deck == []: self.deck = ['6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣', 'A♣',\ '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♦',\ '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♥',\ '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', 'A♠'] random.shuffle(self.deck) else: self.deck = deck self.trump = self.deck[0] #initialize players self.players = [] for i in range(numHumanPlayers): self.players.append(HumanPlayer("Player " + str(i + 1))) #deal hands for _ in range(6): self.players[i].addCard(self.drawCard()) for i in range(numAIPlayers): self.players.append( AIPlayer("Player " + str(i + numHumanPlayers + 1))) #deal hands for _ in range(6): self.players[i + numHumanPlayers].addCard(self.drawCard())
def game_flow(): board = Board() player1 = AIPlayer('X', (255, 255, 0)) player2 = HumanPlayer('O', (0, 0, 255)) current_player = player1 while True: # Animation loop (game flow loop) row, column = current_player.play_turn( board) # Get selected cell's row and col, for current player if row is None: # No move was selected continue board.update_board(row, column, current_player) # Update board with selected cell if has_won(board.board, 3 * row + column): # Check if last move was a wining move print("{} has won!".format(current_player.shape)) break if not board.empty_cells(): # Check for a tie print("TIE") break current_player = player2 if current_player is player1 else player1 # Update current player
class Test(TestCase): black = HumanPlayer(Checker.BLACK) white = HumanPlayer(Checker.WHITE) logging.basicConfig(level=logging.DEBUG) def setUp(self) -> None: self.game = Game(self.black, self.white, create_protocol=False) def test_move_generator_double_six(self): pprint.pprint(generate_moves(self.white, Die(6, 6), self.game.board)) def test_move_generator_double_two(self): pprint.pprint(generate_moves(self.white, Die(2, 2), self.game.board)) def test_move_generator_double_three(self): pprint.pprint(generate_moves(self.white, Die(3, 3), self.game.board)) def test_move_generator_one_and_two(self): pprint.pprint(generate_moves(self.white, Die(2, 3), self.game.board)) def test_move_generator_one_and_two_and_one_out(self): self.game.board.remove_from(19) self.game.board.place_at(0, self.white.color) pprint.pprint(generate_moves(self.white, Die(1, 2), self.game.board)) def test_move_generator_one_and_two_one_not_in_home(self): self.fill_home() self.game.board.place_at(7, self.white.color) pprint.pprint(self.game.board) pprint.pprint(generate_moves(self.white, Die(5, 6), self.game.board)) def test_move_generator_five_six_in_home_one_out(self): self.fill_home() self.game.board.place_at(0, self.white.color) moves = generate_moves(self.white, Die(5, 6), self.game.board) pprint.pprint(moves) self.assertEqual(len(moves), 3) def test_move_generator_double_six_black(self): pprint.pprint(generate_moves(self.black, Die(6, 6), self.game.board)) def test_move_generator_one_and_two_and_one_out_black(self): self.game.board.remove_from(19) self.game.board.place_at(0, self.black.color) pprint.pprint(generate_moves(self.black, Die(1, 2), self.game.board)) def test_move_generator(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(23, self.white.color, 2) pprint.pprint(generate_moves(self.white, Die(4, 6), self.game.board)) def fill_home(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(1, self.white.color, 2) self.game.board.place_at(2, self.white.color, 2) self.game.board.place_at(3, self.white.color, 2) self.game.board.place_at(4, self.white.color, 2) self.game.board.place_at(5, self.white.color, 2) self.game.board.place_at(6, self.white.color, 2) def test_move_white_checker_from_bar_in(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(0, self.white.color, 1) moves = generate_moves(self.white, Die(2, 3), self.game.board) expected_moves = [[(0, 22), (22, 20)], [(0, 23), (23, 20)]] self.assertEqual(moves, expected_moves) def test_move_dark_checker_from_bar_in(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(0, self.black.color, 1) print(self.game.board) moves = generate_moves_serial(self.black, Die(2, 3), self.game.board) expected_moves = [[(0, 22), (22, 20)], [(0, 23), (23, 20)]] pprint.pprint(moves) self.assertEqual(moves, expected_moves) def test_parallel_move_dark_checker_from_bar_in(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(0, self.black.color, 1) print(self.game.board) moves = generate_moves(self.black, Die(2, 3), self.game.board) expected_moves = [[(0, 22), (22, 20)], [(0, 23), (23, 20)]] pprint.pprint(moves) self.assertEqual(moves, expected_moves) def test_two_out_can_move_only_one(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(0, self.black.color, 1) self.game.board.place_at(0, self.black.color, 1) self.game.board.place_at(19, self.white.color, 1) self.game.board.place_at(19, self.white.color, 1) moves = generate_moves_serial(self.black, Die(2, 6), self.game.board) expected_moves = [[(0, 23)]] self.assertEqual(moves, expected_moves) def test_black_move_out(self): rand_black = RandomPlayer(Checker.BLACK) human_white = RandomPlayer(Checker.WHITE) game = Game(player_1=human_white, player_2=rand_black, create_protocol=False) game.board.board = game.board.clear_board() game.current_player = rand_black game.current_dice = Die(4, 6) game.board.place_at(19, Checker.BLACK, 1) game.board.place_at(22, Checker.BLACK, 1) game.board.place_at(18, Checker.WHITE, 4) game.run() moves = generate_moves_serial(self.black, Die(4, 6), game.board.get_view(True)) print(moves) def test_black_move_out_4(self): self.game.board.board = self.game.board.clear_board() self.game.board.place_at(22, self.black.color, 4) self.game.board.place_at(21, self.black.color, 2) self.game.current_player = self.black self.game.board.place_at(23, self.white.color, 6) moves = generate_moves_serial(self.black, Die(4, 4), self.game.board.get_view(True)) moves = gui.HumanPlayer.map_out_moves([(3, 0), (4, 0), (3, 0), (4, 0)], moves) expected_moves = [(3, -1), (3, -1), (4, 0), (4, 0)] self.assertEqual(sorted(moves), expected_moves)
from IterativeDeepeningPlayer import IterativeDeepeningPlayer from Board import Board from FancyDisplay import FancyDisplay from Move import Move import sys import argparse parser = argparse.ArgumentParser(description='Play a game of chess!') parser.add_argument('playertypes', nargs=2, choices=['h', 'r', 'g', 'n', 'np', 'id', 'skirmish'], help='playertype of white and black') args = parser.parse_args() # create players players = {} for i, color in enumerate(('white', 'black')): if args.playertypes[i] == 'h': players[color] = HumanPlayer() elif args.playertypes[i] == 'r': players[color] = RandomPlayer() elif args.playertypes[i] == 'g': players[color] = GreedyPlayer() elif args.playertypes[i] == 'n': players[color] = NegamaxPlayer() elif args.playertypes[i] == 'skirmish': players[color] = SkirmishPlayer() elif args.playertypes[i] == 'np': players[color] = NegamaxPruningPlayer() elif args.playertypes[i] == 'id': players[color] = IterativeDeepeningPlayer()
from Player import HumanPlayer, CPUPlayer from Board import Board def play(board, players): current_player = players[0] while not board.is_full(): print() for row in board.get_board(): print(row) row, col = current_player.move(board, players) while not board.put(current_player.get_id(), row, col): print("Spróbuj jeszcze raz") row, col = current_player.move(board, players) current_player.add_points(board.sum_points(row, col)) current_player = players[0] if current_player == players[ 1] else players[1] size = 4 board = Board(size) players = (HumanPlayer(1, "RED", "Konrad"), CPUPlayer(2, "BLUE")) play(board, players)
from Game import Game from Player import MCTSPlayer, HumanPlayer from policy_value_net import PolicyValueNet from utils import symmetry_board_moves game = Game() goat = HumanPlayer() pvnet = PolicyValueNet("models/model.h5") pvnet_fn = pvnet.policy_value_fn bagh = MCTSPlayer(pvnet_fn, n_playout=500) data = game.start_play(bagh, goat) data = [x for x in data] data = symmetry_board_moves(data) state_batch = [x[0] for x in data] mcts_probs_batch = [x[1] for x in data] winner_batch = [x[2] for x in data] pvnet.train(state_batch, mcts_probs_batch, winner_batch, 5) pvnet.save_model("model.h5")
def load_latest_game_state() -> GameStateLog: path = os.path.abspath("log/board_state.log") with open(path, "r") as f: last_line = f.readlines()[-1] obj = jsonpickle.decode(last_line) return obj class DebugPlayer(Player): def __init__(self, color: Checker, move): super().__init__(color) self.move = move def calculate_moves(self, dices: Die, board) -> [(int, int)]: return self.move if __name__ == "__main__": game_state = load_latest_game_state() game_state player2_color = Checker.WHITE if game_state.player.color == Checker.BLACK else Checker.BLACK debug_player: DebugPlayer = DebugPlayer(game_state.player.color, game_state.moves) player2: HumanPlayer = HumanPlayer(player2_color) game: Game = Game(debug_player, player2) game.current_player = debug_player game.board.board = game_state.board game.current_dice = game_state.die game.play()
def test_hand_with_three_lowest_suit(self): player = HumanPlayer('test') for card in [(2, '$'), (9, 'H'), (8, '$'), (2, 'H'), (4, 'L'), (5, 'L')]: player.deal_card(card) self.assertItemsEqual(['L', '$', 'H'], player.lowest_suits())
def test_hand_is_sorted(self): player = HumanPlayer('test') for card in [(2, '$'), (9, 'L'), (8, 'H'), (2, 'H'), (4, 'L')]: player.deal_card(card) self.assertEqual([(4, 'L'), (9, 'L'), (2, 'H'), (8, 'H'), (2, '$')], player.hand)
class TerminalBoard(Board): def __init__(self, board_data): super().__init__(board_data) self.init_game() def init_game(self): print("Please choose X or O:", end = " ") self.h_letter = input() if self.h_letter == "x" or self.h_letter == "X": self.c_letter = "O" else: self.c_letter = "X" self.draw_board() self.rcp = RandomComputerPlayer(self) self.hp = HumanPlayer(self) def draw_board(self): print("\n\n") index = 0 for i in range(3): print("\t\t\t %s | %s | %s \n" %(self.board_data[index], self.board_data[index + 1], self.board_data[index + 2])) index += 3 def available_space(self): return [i for i, x in enumerate(self.board_data) if x == 0] def make_move(self, position): # makes the move and redraw the board on the screen self.available_space() def is_winner(self, letter): index = 0 # checking for the row similarity for i in range(3): row_set = set(self.board_data[index: index+3]) if len(row_set) == 1 and (letter in row_set): return True index +=3 # checking for the column similarity for i in range(3): if (self.board_data[i] == letter and self.board_data[i+3] == letter and self.board_data[i+6] == letter): return True if (self.board_data[0] == letter and self.board_data[4] == letter and self.board_data[8] == letter): return True if (self.board_data[2] == letter and self.board_data[4] == letter and self.board_data[6] == letter): return True return False def play(self): while (len(self.available_space()) > 0): print(self.next_turn) if self.next_turn == "X": if self.h_letter == "X": self.hp.next_move() self.draw_board() if self.is_winner("X"): print("X is the winner!") exit() self.next_turn = "O" else: self.hp.next_move() self.draw_board() if self.is_winner("X"): print("X is the winner!") exit() self.next_turn = "O" else: if self.h_letter == "O": self.rcp.next_move() self.draw_board() if self.is_winner("O"): print("O is the winner!") exit() self.next_turn = "X" else: self.rcp.next_move() self.draw_board() if self.is_winner("O"): print("O is the winner!") exit() self.next_turn = "X"
def test_lowest_suits_when_a_suit_has_no_cards(self): player = HumanPlayer('test') for card in [(2, '$'), (8, '$'), (2, 'H')]: player.deal_card(card) self.assertItemsEqual(['L'], player.lowest_suits())
mainDbName = database_name + ".csv" mirrorDbName = database_name + "-mirror.csv" #Copy the main database, dbMirror = copyfile(mainDbName, mirrorDbName) mirrorDouble(mirrorDbName) # then mirror it train_data = pd.read_csv('./' + mirrorDbName, sep=';') #Use the mirrored data train_data.drop_duplicates() # ------ Initialize a game ----- match = Connect4(register=True, drawBoard=True) player1 = HumanPlayer(match) player2 = MLPCPlayer(match, train_data) players = [player1, player2] gamesLeft = 20 while gamesLeft > 0: print("Starting a new game! #", gamesLeft) tour = random.choice([0,1]) while (not match.gameHasEnded): #If it's the player's turn, register the move. match.register = (tour == 0)
square = o_player.get_move(game) else: square = x_player.get_move(game) if game.make_move(square, letter): if print_game: print(f"{letter} makes a move to {square}") game.print_board() print('') if game.current_winner: if print_game: print(letter + ' wins') return letter #alternate between players letter = 'O' if letter == 'X' else 'X' #check if we won after each move.... #tiny break after each iteration time.sleep(.75) if print_game: print('Its a tie!') if __name__ == "__main__": x_player = HumanPlayer('X') o_player = AIComputerPlayer('O') t = TicTacToe() play(t, x_player, o_player, True)
if letter == 'O': square = o_player.get_move(game) else: square = x_player.get_move(game) if game.make_move(square, letter): # make_move returns a valid move or not # show players move in board if print_game: print(letter + " has moved to square {}\n".format(square)) game.print_board() print() game.print_board_numbers() # check for winner if game.current_winner: if print_game: print("\n", letter + " WINS !!") return letter letter = 'O' if letter == 'X' else 'X' # switch letter time.sleep(0.6) if print_game: print("\nDRAW!! There is no winner.") if __name__ == '__main__': x_player = AIPlayer('X') o_player = HumanPlayer('O') t = TicTacToe() play(t, x_player, o_player, print_game=True)
from Game import Game from Player import MCTSPlayer, HumanPlayer from policy_value_net import PolicyValueNet game = Game() bagh = HumanPlayer() pvnet = PolicyValueNet("models/model.h5") pvnet_fn = pvnet.policy_value_fn goat = MCTSPlayer(pvnet_fn, n_playout=800) game.start_play(goat, bagh)
game.print_board_nums() letter = 'X' while game.empty(): if letter == 'O': square = o.get_move(game) else: square = x.get_move(game) if game.make_move(square, letter): if print_game: game.print_board() print('') if game.current_winner: print(letter + ' wins!') return letter letter = 'O' if letter == 'X' else 'X' time.sleep(.8) print('Its a tie') x = HumanPlayer('X') #o = RandomComputerPlayer('O') Play agaisnt AI or change to randomCompPlayer o = AIPlayer('O') t = TicTacToe() play(t, x, o, print_game=True)