def double_player_game(): board = GameBoard() print("Player 1: Please type in your name: ") player_name_1 = input() print("Player 2: Please type in your name: ") player_name_2 = input() player1 = Human('X', player_name_1) player2 = Human('O', player_name_2) current_player = player1 other_player = player2 winner = None game_over = False while not game_over: print(current_player.name, "Please select the column: [1-7]") print(board) move_allowed = False while not move_allowed: move = current_player.get_move(board, other_player) move_allowed = board.try_place_piece(move, current_player.sign) game_over, winner = board.is_game_over(board.board, current_player.sign, other_player.sign) current_player, other_player = other_player, current_player print(board) if winner: print("Player", other_player.name, "just won! Game over") else: print("Tie!")
def create_players(self, player_type1: str, player_type2: str): """ Instantiates the player objects and assigns them to the appropriate instance attributes. :param player_type1: Type of player1 - user, easy, medium :param player_type2: Type of player2 """ difficulties = ['easy', 'medium', 'hard'] if player_type1 == 'user': self.player1 = Human('X') elif player_type1 in difficulties: self.player1 = AI('X', player_type1) else: raise InvalidPlayerTypeError(player_type1) if player_type2 == 'user': self.player2 = Human('O') elif player_type2 in difficulties: self.player2 = AI('O', player_type2) else: raise InvalidPlayerTypeError(player_type2) self.players = (self.player1, self.player2)
class PvP(GUI): def __init__(self, size, window_width, window_height): GUI.__init__(self, size, window_width, window_height) self.player1 = Human(1) self.player2 = Human(2) def run(self): while not self.done: for event in pygame.event.get(): # User did something move = [0, 0] if self.TOURN == 1: if event.type == pygame.MOUSEBUTTONDOWN: move, warunek = self.player1.run( self.map_x, self.map_y, self.board) if warunek: print(self.board.getState()) self.done = self.board.isEnd() self.TOURN = 2 else: if event.type == pygame.MOUSEBUTTONDOWN: move, warunek = self.player2.run( self.map_x, self.map_y, self.board) if warunek: print(self.board.getState()) self.done = self.board.isEnd() self.TOURN = 1 key_pressed = pygame.key.get_pressed() if key_pressed[pygame.K_LEFT]: # and map_x != 0: self.map_x -= self.map_x_c elif key_pressed[pygame.K_RIGHT]: self.map_x += self.map_x_c elif key_pressed[pygame.K_UP]: self.map_y -= self.map_x_c elif key_pressed[pygame.K_DOWN]: self.map_y += self.map_x_c elif key_pressed[pygame.K_ESCAPE]: quit() # Set the screen background self.main_map.fill(self.BLACK) # Draw the grid self.draw() self.screen.blit(self.main_map, (self.map_x, self.map_y, self.window_width, self.window_height)) # Limit to 60 frames per second self.clock.tick(80) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
def do_user_move(self, player: Human): """ Takes the user's move from the standard input and updates the board. Checks to be sure that the move is valid and requests input until a valid move is given. :param player: (Human) The human user object making the move. """ while True: move = player.get_move() try: move = [int(s) for s in move] except ValueError: print('You should enter numbers!') else: move = tuple(move) if len(move) != 2: print('You should enter 2 coordinates!') elif not self.move_is_on_board(move): print('Coordinates should be from 1 to 3!') elif not self.is_open_cell(move): print('This cell is occupied! Choose another one!') else: self.board.update_cell(move, player.token) break
def single_player_game(): board = GameBoard() print("Player 1: Please type in your name: ") player_name = input() player1 = Human('X', player_name) player2 = Computer('O', 6) print("Please select the column: [1-7]") current_player = player1 other_player = player2 winner = None game_over = False while not game_over: print(board) move_allowed = False while not move_allowed: start = time.time() # Get the start time move = current_player.get_move(board, other_player) move_allowed = board.try_place_piece(move, current_player.sign) game_over, winner = board.is_game_over(board.board, current_player.sign, other_player.sign) end = time.time() # Testing end time difference = end - start # Get the time from start to end current_player, other_player = other_player, current_player print("Computing Time: ", difference) print(board) if winner: print("Computer Won! Game over") else: print("Tie!")
def showcase(self, qtable): self.players = [None, None] self.players[0] = Agent("Agent 1", 1, qtable) self.players[1] = Human("GG", -1) again = 'y' while again == 'y': self.reset() while True: # display qtable value and get/execute action for active player state = boardToState(self.board) if np.sum(self.board) == 1: state = boardToState(invertBoard(self.board)) print(qtable[state][:]) action = self.getNextAction() self.execAction(action) # check for end of game winner = self.checkWin() if winner != 0: print("%i wins!" % winner) break # check for draw if len(self.fields) == 0: print("Draw!") break again = input("Play again? (y/n)")
def prepare_game(self, ai_player_count): self.presentation.Hide() try: if ai_player_count == 0: p1 = Human(self.presentation.get_player_name("Player #1")) p2 = Human(self.presentation.get_player_name("Player #2")) hotseat = True elif ai_player_count == 1: p1 = Human(self.presentation.get_player_name("Player #1")) p2 = AI(self.presentation.get_ai_file("Player #2")) hotseat = False else: # ai_player_count == 2: p1 = AI(self.presentation.get_ai_file("Player #1")) p2 = AI(self.presentation.get_ai_file("Player #2")) hotseat = False except UserCancelError: return self.presentation.stop_sonar() return_msg = self.run_game([p1, p2], hotseat) self.presentation.play_game_over_sound() self.presentation.give_message("Game Over", return_msg['msg']) self.presentation.Show() self.presentation.start_sonar()
def initPlayers(self, player_types): chars = [1, -1] if not(0 <= np.sum(player_types) <= 2): raise ValueError("Can't have %i players" % np.sum(player_types)) # init human players for i in range(player_types[0]): self.players.append(Human(input("Name of Player %i: " % (i+1)), chars[i])) # init random choice bots for i in range(player_types[1]): self.players.append(Bot("Bot %i" % (i+1), chars[player_types[0]+i])) # init qrl agents for i in range(player_types[2]): self.players.append(Agent("Agent %i" % (i+1), chars[player_types[0]+player_types[1]+i]))
def test_valid_input_failed_predictor_num_not_in_range( ): # last letter is not in range 0-4 human = Human("You") human.is_predictor = True assert human.validate_input("CC9") == False
def test_valid_input_failed_predictor_nums(): # last letter is not a number human = Human("You") human.is_predictor = True assert human.validate_input("CCC") == False
def test_valid_input(): human = Human("You") human.is_predictor = False assert human.validate_input("OO") == True
def test_valid_input_failed_predictor_chars( ): # first two letters are not in the form human = Human("You") human.is_predictor = True assert human.validate_input("123") == False
def test_valid_input_failed_arbitrary_input(): # arbitrary input human = Human("You") human.is_predictor = True assert human.validate_input("chicken") == False
def test_valid_input_failed_chars(): # letters are not in the form human = Human("You") human.is_predictor = False assert human.validate_input("CT") == False
def test_valid_input_failed_letter_exceed(): # letters exceed human = Human("You") human.is_predictor = False assert human.validate_input("OO2") == False
import pickle import Environment from Player import Player from Player import Human import State from Model import Model env = Environment.Environment(3, 3) prefix = input("Input the prefix for the model to be loaded: ") model_name = input("Input the name of the model you want: ") if len( sys.argv) != 2 else sys.argv[1] print("Loading model with filename {}{} . . .".format(prefix, model_name)) agent = Player(model_name, env, 1, 0) agent.load_policy(model_name, prefix) human = Human('human', env, -1) players = [human, agent] while True: while True: for player in players: if env.turn != player.symbol: env.turn *= -1 game_over = False # choose action action = player.choose_action(env.state) # take action next_state, result = env.update(action, must_be_legal=True) env.display()
""" ####### Init Game, Players and Board instances ####### #init boardgame board_size = sys.argv[3] board = Board(board_size) #init players RED, BLUE = 1, 2 player1_type = sys.argv[1] player2_type = sys.argv[2] ai_algorithms = ['random', 'mc', 'mc_ucb1', 'uct', 'uct_wm'] if player1_type == 'h': # h for human player1 = Human(RED) elif player1_type in ai_algorithms: player1 = AI(RED, player1_type) else: print('Wrong player type.') print(f'Available options: {["h"] + ai_algorithms}.') exit() if player2_type == 'h': player2 = Human(BLUE) elif player2_type in ai_algorithms: player2 = AI(BLUE, player2_type) else: print(f'Wrong player type.') print(f'Available options: {["h"] + ai_algorithms}.') exit()
from Game import Game from Player import Human, Bot print("Welcome to The Open-Closed Game") while (True): human = Human("You") bot = Bot("Bot") game = Game(human, bot) game.play() if (not game.check_play_again()): break
def __init__(self, size, window_width, window_height): GUI.__init__(self, size, window_width, window_height) self.player1 = Human(1) self.player2 = AlfaBetaOdd(2, size=self.size)
def __init__(self, size, window_width, window_height): GUI.__init__(self, size, window_width, window_height) self.player1 = Human(1) self.player2 = Human(2)