def start_new(self, option_choice): os.system(['clear', 'cls'][os.name == 'nt']) # reset game status self._round = 1 self._finished = False self._winner = None # the human select if he wants to play first or second if option_choice == 1: self.players[0] = HumanPlayer(self.colors[0]) self.players[1] = AIPlayer(self.colors[1], self) self._current_player = self.players[0] elif option_choice == 2: self.players[0] = AIPlayer(self.colors[0], self) self.players[1] = HumanPlayer(self.colors[1]) self._current_player = self.players[0] # clear grid with white spaces self.matrix = [] for i in xrange(self.board_height): self.matrix.append([]) for j in xrange(self.board_width): self.matrix[i].append(' ') # start a new game self.start()
def start_human_vs_human_game(self): self.clear_buttons() self.team_black = HumanPlayer(self, self.board, Team.Black) self.team_red = HumanPlayer(self, self.board, Team.Red) self.start_game()
def test_reset__not_finished(self): person = HumanPlayer("Sam") person.finished = True person.reset_hand() self.assertFalse(person.finished)
def test_print_results__one_person_high_hand(self, mock_print: MagicMock): person = HumanPlayer("Matthew") person.print_player = MagicMock() person.cards = [Card(10, "Test"), Card(10, "Test"), Card(10, "Test")] print_game_results([person]) person.print_player.assert_called_once()
def main(): """Program entrypoint""" game = Draughts() state = game.new_game([HumanPlayer(), HumanPlayer()]) while game.evaluate(state) == 0: print(game.display(state)) state = game.play_turn(state)
def test_print_results__one_person__is_winner(self, mock_print: MagicMock): person = HumanPlayer("Matthew") person.print_player = MagicMock() person.cards = [] print_game_results([person]) mock_print.assert_called_once_with("Winner: Matthew")
def test_take_card__reduces_deck(self): deck = Deck() deck._cards = [Card(3, "Test"), Card(2, "Test")] person = HumanPlayer("Sam") person.take_card(deck) self.assertEqual(1, len(deck))
def __init__(self): self.round = 1 self.game = 1 self.finished = False self.winner = None self.last_move = None # do cross-platform clear screen # os.system(['clear', 'cls'][os.name == 'nt']) print("Welcome to Conniption Board Game") print("Should Player 1 be a Human/AI/Random?") while self.players[0] == None: choice = str(input("Type 'H'/'A'/'R': ")) if choice.lower() == "human" or choice.lower() == "h": name = str(input("What is Player 1's name? ")) self.players[0] = HumanPlayer(name, self.colors[0], self.MAX_FLIP) elif choice.lower() == "ai" or choice.lower() == "a": name = str(input("What is Player 1's name? ")) diff = int(input("Enter difficulty for this AI (1 - 4) ")) self.players[0] = AIPlayer(name, self.colors[0], self.MAX_FLIP, diff + 1) elif choice.lower() == "random" or choice.lower() == "r": name = str(input("What is Player 1's name? ")) self.players[0] = RandomPlayer(name, self.colors[0], self.MAX_FLIP) else: print("Invalid choice, please try again") print("{0} will be {1}".format(self.players[0].name, self.colors[0])) print("Should Player 2 be a Human/AI/Random?") while self.players[1] == None: choice = str(input("Type 'H'/'A'/'R': ")) if choice.lower() == "human" or choice.lower() == "h": name = str(input("What is Player 2's name? ")) self.players[1] = HumanPlayer(name, self.colors[1], self.MAX_FLIP) elif choice.lower() == "ai" or choice.lower() == "a": name = str(input("What is Player 2's name? ")) diff = int(input("Enter difficulty for this AI (1 - 4) ")) self.players[1] = AIPlayer(name, self.colors[1], self.MAX_FLIP, diff + 1) elif choice.lower() == "random" or choice.lower() == "r": name = str(input("What is Player 2's name? ")) self.players[1] = RandomPlayer(name, self.colors[1], self.MAX_FLIP) else: print("Invalid choice, please try again") print("{0} will be {1}".format(self.players[1].name, self.colors[1])) # x always goes first (arbitrary choice on my part) self.turn = self.players[0] self.board = [] for i in range(6): self.board.append([]) for j in range(7): self.board[i].append(' ')
def test_value__three_aces(self): person = HumanPlayer("Sam") person.cards = [ Card("A", "Test"), Card("A", "Test"), Card("A", "Test") ] self.assertEqual(13, person.value())
def test_value__ace_low_21(self): person = HumanPlayer("Sam") person.cards = [ Card("K", "Test"), Card("Q", "Test"), Card("A", "Test") ] self.assertEqual(21, person.value())
def test_take_card__removes_card(self): deck = Deck() deck._cards = [Card(3, "Test"), Card(2, "Test")] person = HumanPlayer("Sam") person.take_card(deck) card = person.cards[0] self.assertNotIn(card, deck)
def test_take_card__adds_to_hand(self): deck = Deck() deck._cards = [Card(3, "Test"), Card(2, "Test")] person = HumanPlayer("Sam") self.assertEqual(0, len(person.cards)) person.take_card(deck) self.assertEqual(1, len(person.cards))
class Human_PC(IPlayerController): """Human player Controller, that calls to the GUI for resolution of its functions""" def __init__(self, player, args, container): super().__init__(player, args) self.humanPlayerGui = HumanPlayer(self.player.getName(), container) def pollDraft(self, state): """Function that returns the choice of a stack from the draw field""" # Bind in the percieved fields percievedField = state.deck.percieveCardField() selectedStackIndex = self.humanPlayerGui.decisionMaking_Drafting( percievedField) if selectedStackIndex is not None: fieldOfChoice = percievedField[selectedStackIndex] # returns the index of the choosen stack return fieldOfChoice[0] else: # returns None as long as no choice is made return None def pollPlay(self, state): """Function that returns which card the PC want to play""" # chooses a card from the players hand hand = self.player.getHand() cardOfChoice = self.humanPlayerGui.decisionMaking_Playing( hand, self.player.canEmergencyStop()) if cardOfChoice is not None: #return choice return cardOfChoice else: # returns None as long as no choice is made return None def pollEmergencyStop(self, state): """Function that returns the choice of using the emergency stop as a boolean""" doesPlayES = self.humanPlayerGui.decisionMaking_EmergencyStop() if doesPlayES is not None: #return choice return doesPlayES else: # returns None as long as no choice is made return None def announceWinner(self, state): """Function that updates the PC after the last turn""" return None def informReveal(self, cards): """Informs the PlayerController of the cards which have been played""" self.log.info("Human informed about %s" % cards) def isHuman(self): """The board need to be able to find the human player, which this function will help with""" return True
class Human_PC(IPlayerController): """Human player Controller, that calls to the GUI for resolution of its functions""" def __init__(self, player, args,container): super().__init__(player,args) self.humanPlayerGui = HumanPlayer(self.player.getName(),container) def pollDraft(self, state): """Function that returns the choice of a stack from the draw field""" # Bind in the percieved fields percievedField = state.deck.percieveCardField() selectedStackIndex = self.humanPlayerGui.decisionMaking_Drafting(percievedField) if selectedStackIndex is not None: fieldOfChoice = percievedField[selectedStackIndex] # returns the index of the choosen stack return fieldOfChoice[0] else: # returns None as long as no choice is made return None def pollPlay(self, state): """Function that returns which card the PC want to play""" # chooses a card from the players hand hand = self.player.getHand() cardOfChoice = self.humanPlayerGui.decisionMaking_Playing(hand, self.player.canEmergencyStop()) if cardOfChoice is not None: #return choice return cardOfChoice else: # returns None as long as no choice is made return None def pollEmergencyStop(self, state): """Function that returns the choice of using the emergency stop as a boolean""" doesPlayES = self.humanPlayerGui.decisionMaking_EmergencyStop() if doesPlayES is not None: #return choice return doesPlayES else: # returns None as long as no choice is made return None def announceWinner(self, state): """Function that updates the PC after the last turn""" return None def informReveal(self, cards): """Informs the PlayerController of the cards which have been played""" self.log.info("Human informed about %s" % cards) def isHuman(self): """The board need to be able to find the human player, which this function will help with""" return True
def test_reset__empty_hand(self): person = HumanPlayer("Sam") person.cards = [ Card("A", "Test"), Card("A", "Test"), Card("A", "Test"), Card("A", "Test") ] person.reset_hand() self.assertEqual([], person.cards)
def selectMode(self): value = input("Please enter 1 for vs npc, or 2 for player vs player\n") while value != "1" and value != "2": os.system('cls') value = input( "Invalid input. Please enter 1 for vs npc, or 2 for player vs player\n" ) self.vsNPC = value == "1" self.player1 = HumanPlayer(1) if self.vsNPC: self.player2 = NPC(2) else: self.player2 = HumanPlayer(2)
def test_set_piece(self): player1 = HumanPlayer() player1.set_piece(Board.X) self.assertEqual(Board.X, player1.piece) player2 = HumanPlayer() player2.set_piece(Board.O) self.assertEqual(Board.O, player2.piece)
def run(): game = GomokuGame(height=9, width=9, row_in_line=5) player = [] # for player_id in [1, 2]: # player.append(GomokuPlayer(player_id)) player.append(HumanPlayer(1)) player.append(MctsPlayer(2)) for r in range(5): game.reset() for e in range(300): player_id = game.whose_term() if player[0].player_id == player_id: position = player[0].get_action(game) else: position = player[1].get_action(game) h = int(position / game.shape[1]) v = position - h * game.shape[1] ret = game.step(player_id, h, v) if ret: game.gomoku_board.show(show_pic=False) time.sleep(0.1) else: print("Position {},{} is not valid".format(h, v)) break game_end, winner = game.game_end() if game_end: if winner != 0: print("Player {}({}) Win in {}!!!".format( int(winner), player[int(winner) - 1].__str__(), e)) print("h={}, v={}.".format(h + 1, v + 1)) else: print("No winner, board is full!!!") time.sleep(30) break
def test_select_players(self, select_mock): select_mock.side_effect = [RandomPlayer(), HumanPlayer()] player1, player2 = self.console._select_players() self.assertIsInstance(player1, RandomPlayer) self.assertIsInstance(player2, HumanPlayer) self.assertEqual([call(Board.X), call(Board.O)], select_mock.call_args_list)
def createPlayers(self): print("--- Welcome to Espadinha! ---\n") print('Please insert your name: ') p1 = HumanPlayer(input()) p3 = RuleBasedPlayer("Bot 3") p2 = CustomPlayer("Partner") p4 = RuleBasedPlayer("Bot 4") return (p1, p2, p3, p4)
def begin_game(): # Determine opponent type opponent_type = determine_opponent() # Instantiate players player_one = HumanPlayer() if opponent_type == '1': player_two = HumanPlayer('', 2) else: player_two = ComputerPlayer() # Setup Tracking variables counter = 1 # 5 turns winner_exists = False max_counter = 5 # Process game turns while counter <= max_counter and not winner_exists: print(f'===== Turn {counter} =====') player_one_choice = player_one.method_of_play( game_gestures.gesture_name_list) player_two_choice = player_two.method_of_play( game_gestures.gesture_name_list) turn_winner = check_turn_winner(player_one_choice, player_two_choice) if turn_winner == 1: player_one.wins += 1 elif turn_winner == 2: player_two.wins += 1 else: # increment max counter to accommodate for tie rounds max_counter += 1 # Check for end of game if player_one.wins == 3 or player_two.wins == 3: winner_exists = True # increment counter counter += 1 # Declare/show winner declare_winner(player_one, player_two, opponent_type)
def __init__(self): self.deck: List[Card] = [] self.players: List[Player] = [] for player_preset in self.players_presets: if player_preset.is_ai: player = RobotPlayer(name=player_preset.name) else: player = HumanPlayer(name=player_preset.name) self.players.append(player)
def main(): logging.basicConfig(format=_red + "%(levelname)s][%(asctime)s] %(message)s" + _normal, datefmt="%m/%d/%Y %H:%M:%S", level=logging.DEBUG) players = [HumanPlayer() for i in range(3)] # players.append(NetworkPlayer(None, 15, 4, 25)) table = Table(players, 8000, 25) table.play()
def __init__(self): self.numbers = {n for n in range(1, 91)} num_of_players, num_of_cards = self.ask_for_params() self.players = [] self.done_win_conditions = [] for i in range(0, num_of_players): if i == 0: self.players.append(HumanPlayer(num_of_cards)) else: self.players.append(Player(num_of_cards)) input('Press any button to play.') self.play()
def test_reset__zero_value(self): person = HumanPlayer("Sam") person.cards = [Card("K", "Test"), Card("A", "Test")] person.reset_hand() self.assertEqual(0, person.value())
def assign_players(self): players = [] for name in self.players_: if name == 'dfs': players.append(Depth_Limited_Player()) elif name == 'a-star': players.append(A_Star_Player()) elif name == 'aai': players.append(Advanced_AI_Player()) elif name == 'bfs': players.append(Graph_Search_BF()) else: players.append(HumanPlayer(name)) return players
class TestHumanPlayer(unittest.TestCase): def setUp(self) -> None: self.b = Board() self.p = HumanPlayer(self.b, 'test-name') def test_human_player(self): self.assertIsInstance(self.p, HumanPlayer) self.assertEqual(self.p.shape, 'X') # default shape self.assertEqual(self.p.name, 'test-name') def test_next_move(self): cases = {'0,0': (0, 0), '1, 1': (1, 1), ' 2 , 1 ': (2, 1)} for mock_input in cases: with self.subTest(mock_input=mock_input): with patch('builtins.input', lambda *_: mock_input): x, y = self.p.next_move() self.assertEqual((int(x), int(y)), cases[mock_input])
def make_players_and_insert_to_queue(self): """Make human and AI Players; insert them to the global players_queue. Prompt human player for its name and use it in its object creation. :return: None """ while True: num_of_human_players = input('How many human players? ') if '1' == num_of_human_players or '2' == num_of_human_players: break else: print( 'Valid options are: 1 for Player Vs. AI or 2 for player Vs. Player.' ) for n in range(int(num_of_human_players)): player_name = input(f'What is your name player {n+1}? ') self.players_queue.append(HumanPlayer(self.board, player_name)) if len(self.players_queue) == 1: self.players_queue.append(AIPlayer(self.board))
def build(self): rows = 8 columns = 8 self._board = self.setup_board(rows, columns) self._engine = Engine(HumanPlayer(self._board), AiPlayer(AlphaBeta(), Evaluator()), rows, columns) self._engine.set_board_state_change_listener(self.on_state_change) self._root = BoxLayout(orientation='vertical') self._start_button = Button(text="start", size_hint=(0.5, 0.2)) self._start_button.background_color = (0.7, 0.7, 0.7, 1.0) self._start_button.bind(on_press=self.on_start_press_listener) self._stop_button = Button(text="stop", size_hint=(0.5, 0.2)) self._stop_button.background_color = (0.7, 0.7, 0.7, 1.0) self._stop_button.bind(on_press=self.on_stop_press_listener) self._root.add_widget(self._board) self._buttons = BoxLayout(orientation='horizontal') self._buttons.add_widget(self._start_button) self._buttons.add_widget(self._stop_button) self._root.add_widget(self._buttons) return self._root
def main(): human_player_count = 0 if len(sys.argv) > 1: try: human_player_count = int(sys.argv[1]) assert 0 <= human_player_count <= 2 except (IndexError, ValueError, AssertionError): print("Please enter the amount of human players you want to add (0-2) as first parameter") exit() players = [BraindeadPlayer() for i in range(4 - human_player_count)] + [HumanPlayer() for i in range(human_player_count)] manager = GameManager(players) try: game_result = manager.play_game() victory_string = "a tie!" winner = game_result.get_winner() if winner is not None: victory_string = "won by team {0}.".format(winner) print("The game was " + victory_string) print("Final " + str(game_result)) except exceptions.RuleViolationError as e: print("The game was ended due to a rule violation by player {0}:".format(e.player_id)) print("\t", e) print("As a result, team {0} wins the game by forfeiture".format((e.player_id + 1) % 2))
def __init__(self, player, args,container): super().__init__(player,args) self.humanPlayerGui = HumanPlayer(self.player.getName(),container)
def __init__(self): """ Constructor for a new Ludo game using a GUI. """ # Initialize a Ludo game nn = NN(237, '01062016_nn_exp_2_19_23.txt') players = [ QLPlayer(id=0, train=False, nn=nn, epsilon=0), HumanPlayer(id=1, name="Andres"), QLPlayer(id=2, train=False, nn=nn, epsilon=0), HumanPlayer(id=3, name="Sol") ] """players = [QLPlayer(id=0, train=False, nn=nn, epsilon=0), QLPlayer(id=1, train=False, nn=nn, epsilon=0), QLPlayer(id=2, train=False, nn=nn, epsilon=0), QLPlayer(id=3, train=False, nn=nn, epsilon=0)]""" Ludo.__init__(self, players) # For debugging # self.player_turn = 0 # self.players[0].state[0] = 0.75 # self.players[0].state[28] = 0.25 # self.players[1].state[0] = 0.75 # self.players[1].state[12] = 0.25 # self.players[2].state[0] = 0.75 # self.players[2].state[51] = 0.25 # Initialize Tk frame: http://effbot.org/tkinterbook/tkinter-hello-tkinter.htm self.root = Tk.Tk() self.root.title("Ludo") self.root.resizable(0, 0) # Center window: http://stackoverflow.com/questions/14910858/how-to-specify-where-a-tkinter-window-opens ws = self.root.winfo_screenwidth() hs = self.root.winfo_screenheight() - 50 x = (ws / 2) - (TkLudo.board_w / 2) y = (hs / 2) - (TkLudo.board_h / 2) self.root.geometry('%dx%d+%d+%d' % (TkLudo.board_w, TkLudo.board_h, x, y)) # Create canvas: http://stackoverflow.com/questions/15795916/image-behind-buttons-in-tkinter-photoimage self.canvas = Tk.Canvas(self.root, width=TkLudo.board_w - 5, height=TkLudo.board_h - 5) self.canvas.pack() self.board_img = Tk.PhotoImage(file='ludo_board.gif') self.playState = PlayState.paused self.turn = 0 self.play_btn = Tk.Button(self.root, text="Start!", width=10) self.play_btn.bind('<ButtonRelease-1>', self.handle_play_btn) self.onemove_btn = Tk.Button(self.root, text="One Move", width=10) self.onemove_btn.bind('<ButtonRelease-1>', self.handle_onemove_btn) self.dice_lbl = Tk.Label(self.root, text="", width=2, bg="#fff", font="Helvetica 16 bold", relief=Tk.RAISED) self.canvas.create_image(0, 0, image=self.board_img, anchor=Tk.NW) self.canvas.create_window(5, 5, window=self.play_btn, anchor=Tk.NW) self.canvas.create_window(176, 5, window=self.onemove_btn, anchor=Tk.NW) self.canvas.create_window(TkLudo.board_w - 6, 5, window=self.dice_lbl, anchor=Tk.NE) self.canvas_pieces_ids = [] self.draw_current_state() self.root.protocol("WM_DELETE_WINDOW", self.handle_quit) self.root.mainloop()
class CheckersGame(object): def __init__(self, root, board): self.root = root self.board = board self.human_vs_AI = tk.Button(self.root, text="Start 1-player Game", command=self.start_human_vs_ai_game) self.board.create_window(140, 155, anchor=tk.NW, window=self.human_vs_AI) self.human_vs_human = tk.Button(self.root, text="Start 2-player Game", command=self.start_human_vs_human_game) self.board.create_window(140, 190, anchor=tk.NW, window=self.human_vs_human) self.AI_vs_AI = tk.Button(self.root, text="Start AI vs AI Game", command=self.start_ai_vs_ai_game) self.board.create_window(140, 225, anchor=tk.NW, window=self.AI_vs_AI) # self.human_vs_human.invoke() # XXX def clear_buttons(self): if self.human_vs_AI: self.human_vs_AI.destroy() if self.human_vs_human: self.human_vs_human.destroy() if self.AI_vs_AI: self.AI_vs_AI.destroy() def start_human_vs_ai_game(self): self.clear_buttons() self.team_black = HumanPlayer(self, self.board, Team.Black) self.team_red = RandomPlayer(self, self.board, Team.Red) self.start_game() def start_human_vs_human_game(self): self.clear_buttons() self.team_black = HumanPlayer(self, self.board, Team.Black) self.team_red = HumanPlayer(self, self.board, Team.Red) self.start_game() def start_ai_vs_ai_game(self): self.clear_buttons() def start_game(self): self.turn = self.team_black self.team_black.choose_move() def select_move(self, source_row, source_column, dest_row, dest_column): # execute the move. # if the move is a jump, check if that piece can jump again, and if so, # let the player to play again is_jump, _ = self.board.get_possible_moves(source_row, source_column) # assume move is valid self.board.move_piece(source_row, source_column, dest_row, dest_column) if (is_jump): self.board.remove_piece((source_row + dest_row) / 2, (source_column + dest_column) / 2) can_jump, _ = self.board.get_possible_moves(dest_row, dest_column) if (can_jump): self.turn.select_additional_jump(dest_row, dest_column) else: self.next_turn() else: self.next_turn() def next_turn(self): if (self.turn == self.team_black): self.turn = self.team_red self.team_red.choose_move() else: self.turn = self.team_black self.team_black.choose_move() def game_over(self): if (self.turn == self.team_black): print "RED WINS" else: print "BLACK WINS"