def single_game(difficulty_level): shots = 0 human_player = set_up_player() computer_player = ComputerPlayer(difficulty_level) computer_ocean = computer_player.get_ocean() computer_add_ships(computer_player) while True: human_turn(human_player, computer_player) shots = add_shot(shots) if human_player.is_winner(computer_player): score = high_score(difficulty_level, shots) player_data = player_score(score, shots, difficulty_level, human_player.get_name()) high_scores_data = import_hall_of_fame('high_scores.csv', player_data) print( get_highscore_table(high_scores_data, player_data, 'high_scores.csv')) export_hall_of_fame('high_scores.csv', high_scores_data) press_enter_to_continue() print_screen('you_win.txt') break computer_turn(computer_player, human_player) if computer_player.is_winner(human_player): print_screen('you_lose.txt') break
def play_game(user_color=chess.Color) -> None: valuator = PieceSumValuator(is_use_piece_position_values=True, is_use_game_status=True) searcher = AlphaBetaSearcher(max_depth=4) computer_player = ComputerPlayer(searcher, valuator) b = chess.Board() print("Game starts.") print_board(b, user_color) print() while True: if b.turn == user_color: user_move = ask_move(b) print_user_move(user_move) b.push(user_move) print_board(b, user_color) else: _, computer_move = computer_player.get_move(b) print_computer_move(computer_move) b.push(computer_move) print_board(b, user_color) if b.is_game_over(): print(b.result()) break print()
def computer_plays(a, b, verbose=False): """ Runs computer guessers on the words in the range(a,b) in the Gettysburg address dictionary. This dictionary is what is used by default when creating a computer player. Return three dictionaries mapping words to the number of guesses your player took where g0 corresponds to your dictionary for skill level 0, g1 --> skill level 1, g2 --> skill level 2. Start by implementing `play_and_add`. After that the provided code will populate g0 correctly. Using that as an example. fill in g1 and g2 to complete the test. The doctest below compares your g0, g1, g2 to the staffs solution. If you match or beat our guess rate, you will pass the test:) >>> g0, g1, g2 = computer_plays(0, 100) >>> d_contained_in(g0, staff_g0) >>> d_contained_in(g1, staff_g1) >>> d_contained_in(g2, staff_g2) # Should not pass until after q6 """ picker = ComputerPlayer(name="you") g0 = {} g1 = {} g2 = {} for i in range(a, b): # Changes the pick_word method, so we deterministically get the words in (a, b) picker.pick_word = lambda: picker.possible_words.words()[i] # A skill level 0 guesser with the Gettysburg address dictionary guesser0 = ComputerPlayer(name="AI thing") play_and_add(picker, guesser0, g0, verbose) # BEGIN "*** YOUR CODE HERE ***" # END # # Might be useful in debugging # print("Guesser skill level 0: ", g0) # print("Guesser skill level 1: ", g1) # print("Guesser skill level 2: ", g2) return g0, g1, g2
def main(): """Configure the game.""" parser = argparse.ArgumentParser( "Play tic-tac-toe against an AI powered by minimax search") parser.add_argument("--players", "-p", type=int, choices=[0, 1, 2], default=1, dest="players") parser.add_argument("--order", "-o", type=int, choices=[1, 2], default=1, dest="order") args = parser.parse_args() if args.players == 2: p1 = Player(TOKENS.X) p2 = Player(TOKENS.O) elif args.players == 1: if args.order == 1: p1 = Player(TOKENS.X) p2 = ComputerPlayer(TOKENS.O) else: p1 = ComputerPlayer(TOKENS.X) p2 = Player(TOKENS.O) else: p1 = ComputerPlayer(TOKENS.X) p2 = ComputerPlayer(TOKENS.O) board = blank_board() play(board, p1, p2)
def __init__(self, discord_client, names, player_number, dice_number): self.round = 0 self.players = [] self.discord_client = for name in names: self.players.append( HumanPlayer( name=name, dice_number=dice_number, game=self ) ) for i in range(0, player_number): self.players.append( ComputerPlayer( name=self.get_random_name(), dice_number=dice_number, game=self ) ) random.shuffle(self.players) print(welcome_message(self.players)) self.first_player = random.choice(self.players) while len(self.players) > 1: self.run_round() print(winner(self.players[0].name))
def play_game(times): print( "Welcome to Rock, Paper, Scissors! \nType your choice to play with CPU! \nAfter you're done, please type Finish." ) player_lower = '' while player_lower != 'finish': # in range(times): player = str(input("Your choice? ")) player_lower = player.lower() if player_lower not in ["rock", "paper", "scissors", "finish"]: print("Something is wrong, please try again!") player = str(input("Your choice? ")) player_lower = player.lower() cp = ComputerPlayer(player_lower) CPU = cp.cpu_turn() print(cp.compare(CPU)) print("\n------\n")
def __init__(self, human_names, computer_strategies, deck_file=None, total_turns=10): self.view = TerminalView() self.turns_remaining = total_turns self.deck = Deck(deck_file) self.discard = Deck() self.direction = self.CLOCKWISE self.current_player_index = 0 self.top_card = self.deal_one_card() if "wild" in self.top_card.special: self.top_card.color = choice(self.COLORS) self.players = [] for name in human_names: self.players.append(HumanPlayer(name)) for i in range(4 - len(human_names) - len(computer_strategies)): computer_strategies.append("basic") for i, strategy_string in enumerate( computer_strategies[:(4 - len(human_names))]): if strategy_string.lower() == "random": self.players.append( RandomComputerPlayer("Computer {} ({})".format( i, strategy_string))) elif strategy_string.lower() == "student": self.players.append( StudentComputerPlayer("Computer {} ({})".format( i, strategy_string))) else: self.players.append( ComputerPlayer("Computer {} ({})".format( i, strategy_string)))
def human_plays(): dictionary = Dictionary("assets/lincoln.txt") Player(dictionary) picker = ComputerPlayer() guesser = HumanPlayer(name="guesser") game = Game(picker, [guesser]) board = game.play(True) print("Solved ", board.word(), " in ", len(board.guesses()), "guesses")
def __init__(self): self.welcome_text = lmgr.GLOBAL_LANGUAGE.Global.welcome_text self.help_ps = 'help' self.__each_score = 10 self.__referee = Referee() self.__players = [ComputerPlayer(), HumanPlayer()] self.__global_socre = 0 self.__global_save = None
def game(debug): """The main game loop""" print "Welcome to Battleship!\n\n" attacking = HumanPlayer() defending = ComputerPlayer() if debug: print "DEBUG CPU" print str(defending.my_board) while True: print "{}'s turn".format(str(attacking)) attack_pos = attacking.choose_attack() hit = defending.receive_attack(attack_pos) attacking.update_enemy_board(attack_pos[0], attack_pos[1], hit) if defending.has_lost(): print "{} has won!\nCongratulations".format(str(attacking)) break else: attacking, defending = defending, attacking print ""
def __init__(self, board_width, board_height, win_seq_length, p1_is_cpu=False, p2_is_cpu=False): self.board = Board(board_width, board_height, win_seq_length) self.board_width = board_width self.board_height = board_height self.win_seq_length = win_seq_length self.in_progress = True if p1_is_cpu: self.p1 = ComputerPlayer(self.p1_id, "Computer Player 1", self.p1_colour, 1) else: self.p1 = HumanPlayer(self.p1_id, "Player 1", self.p1_colour) if p2_is_cpu: self.p2 = ComputerPlayer(self.p2_id, "Computer Player 2", self.p2_colour, 1) else: self.p2 = HumanPlayer(self.p2_id, "Player 2", self.p2_colour) self.current_player = self.p1
def __init__(self): self.mw = tkinter.Tk() self.size = 3 self.buttons_2d_list = [] for i in range(self.size): self.row = [' '] * self.size self.buttons_2d_list.append(self.row) # place players 1 and 2 in tuple for turn based game. self.gboard = GameBoard(3) p1 = HumanPlayer("X") p2 = ComputerPlayer("O", self.buttons_2d_list) self.players_lst = (p1, p2) self.currnt_player_index = 0 self.winner = False
def __init__(self): ComputerPlayer.__init__(self)
return False return 'Tie' def play_game(self): winner_not_found = True whose_move = self.HumanPlayer while winner_not_found: time.sleep(.5) self.print_board(self.board) move = whose_move.get_move(self.board, self.available_moves) self.make_move(self.board, move, whose_move) if self.check_for_winner(self.board, whose_move) == 'Winner': self.print_board(self.board) print('\n') print(f'Player {whose_move.letter} wins!') winner_not_found = False elif self.check_for_winner(self.board, whose_move) == 'Tie': self.print_board(self.board) print('It\'s a tie!') winner_not_found = False else: if whose_move == self.HumanPlayer: whose_move = self.ComputerPlayer else: whose_move = self.HumanPlayer continue if __name__ == '__main__': t = Tic_Tac_Toe(HumanPlayer('X'), ComputerPlayer('O')) t.play_game()
from game import Tictactoe, play from player import HumanPlayer, ComputerPlayer if __name__ == "__main__": player1 = HumanPlayer('x') player2 = ComputerPlayer('0') game = Tictactoe(player1, player2) play(game) pass
self.player_move = self.process_input(self.current_player.get_move()) if self.player_move.valid: self.update_spot(self.player_move.r_spot, self.player_move.c_spot) else: self.print_board(False) #check to see if the game needs ended if not self.game_is_running: break #go to the opposite player for their turn only if the move was successful if self.move_successful: if self.current_player.letter == 'x': self.current_player = self.o_player else: self.current_player = self.x_player #this processes a players input and calls the correct methods if it can understand the input def process_input(self, p_input): try: return Move(int((p_input.strip().split(','))[0]), int((p_input.strip().split(','))[1]), self.current_player, True, self.board) except: p_move = Move(5, 5, self.current_player, False, self.board) if not p_move.valid: os.system('cls') print("Unknown input! Please try again!\n") return p_move game = TicTacToe(HumanPlayer('x'), ComputerPlayer('o'), 3, 3) game.start()
letter = 'X' while game.empty_squares(): if letter == 'O': square = o_player.get_move(game) else: square = x_player.get_move(game) if game.make_move(square, letter): if print_game: print(letter + ' makes a move to square {}'.format(square)) game.print_board() print('') if game.current_winner: if print_game: print(letter + ' wins!') return letter # ends the loop and exits the game letter = 'O' if letter == 'X' else 'X' # switches player time.sleep(.8) if print_game: print('It\'s a tie!') if __name__ == '__main__': x_player = ComputerPlayer('X') o_player = HumanPlayer('O') t = TicTacToe() play(t, x_player, o_player, print_game=True)
def main(debug=False, warm_start=False, opponent=None, num_games=1000, overwrite=False): # Initialization attack_dict = None if warm_start and os.path.isfile("attack_dict.pickle"): attack_dict = pickle.load(open("attack_dict.pickle", "rb")) redistribution_dict = None if warm_start and os.path.isfile("redistribution_dict.pickle"): redistribution_dict = pickle.load(open("redistribution_dict.pickle", "rb")) model1 = Model( attack_dict=attack_dict, redistribution_dict=redistribution_dict, debug=debug ) if opponent == "self": model2 = model1 elif opponent == "naive": model2 = None elif opponent == "independent": attack_dict2 = None if warm_start and os.path.isfile("attack_dict2.pickle"): attack_dict2 = pickle.load(open("attack_dict2.pickle", "rb")) redistribution_dict2 = None if warm_start and os.path.isfile("redistribution_dict2.pickle"): redistribution_dict2 = pickle.load( open("redistribution_dict2.pickle", "rb") ) model2 = Model( attack_dict=attack_dict2, redistribution_dict=redistribution_dict2, debug=debug, ) else: raise NotImplementedError() # Iterative gameplay num_player1_wins = 0 for i in range(num_games): player1 = ComputerPlayer(model=model1, name="A") player2 = ComputerPlayer(model=model2, name="B") player1_wins = run_game(player1, player2) if player1_wins: if debug: print(f"Player 2 loses game {i}") player1.model.update(player1.attacks, player1.redistributions, True) player2.model.update(player2.attacks, player2.redistributions, False) num_player1_wins += 1 else: if debug: print(f"Player 1 loses game {i}") player1.model.update(player1.attacks, player1.redistributions, False) player2.model.update(player2.attacks, player2.redistributions, True) if debug: print(f"Player 1's attacks: {player1.attacks}") print(f"Player 2's attacks: {player2.attacks}") # Look at model(s) that evolved if debug: print("Attack dictionary") pprint.pprint(player1.model._attack_dict) if opponent == "independent": pprint.pprint(player2.model._attack_dict) print("Redistribution dictionary") pprint.pprint(player1.model._redistribution_dict) if opponent == "independent": pprint.pprint(player2.model._redistribution_dict) if overwrite: pickle.dump(player1.model._attack_dict, open("attack_dict.pickle", "wb")) pickle.dump( player1.model._redistribution_dict, open("redistribution_dict.pickle", "wb") ) if opponent == "independent": pickle.dump(player2.model._attack_dict, open("attack_dict2.pickle", "wb")) pickle.dump( player2.model._redistribution_dict, open("redistribution_dict2.pickle", "wb"), ) print(f"Player 1 wins {num_player1_wins} out of {num_games} games")
# A skill level 0 guesser with the Gettysburg address dictionary guesser0 = ComputerPlayer(name="AI thing") play_and_add(picker, guesser0, g0, verbose) # BEGIN guesser1 = ComputerPlayer(name="Better AI Thing", skill=1) play_and_add(picker, guesser1, g1, verbose) guesser2 = ComputerPlayer(name="Best AI Thing", skill=2) play_and_add(picker, guesser2, g2, verbose) # END # # Might be useful in debugging # print("Guesser skill level 0: ", g0) # print("Guesser skill level 1: ", g1) # print("Guesser skill level 2: ", g2) return g0, g1, g2 if __name__ == "__main__": picker = ComputerPlayer(name="you") computer_plays(0, len(picker.possible_words.words())) """ Dictionary mapping words to number of guesses for the staffs version of each computer player skill_level. g0 corresponds to level 0, g1 to 1, g2 to 2. Use this to test if your guesser matches the staff solution! Try to see if you can automate this testing:) """ staff_g0 = {'a': 5, 'above': 18, 'add': 8, 'advanced': 16, 'ago': 12, 'all': 9, 'altogether': 12, 'and': 8, 'any': 21, 'are': 5, 'as': 11, 'battlefield': 18, 'be': 18, 'before': 18, 'birth': 18, 'brave': 18, 'brought': 18, 'but': 18, 'by': 21, 'can': 13, 'cause': 15, 'civil': 16, 'come': 19, 'conceived': 16, 'consecrate': 13, 'consecrated': 13, 'continent': 13, 'created': 13, 'dead': 8, 'dedicate': 13, 'dedicated': 13, 'detract': 13, 'devotion': 16, 'did': 8, 'died': 8, 'do': 8, 'earth': 10, 'endure': 15, 'engaged': 12, 'equal': 23, 'far': 14, 'fathers': 14, 'field': 14, 'final': 14, 'fitting': 14, 'for': 14, 'forget': 14, 'forth': 14, 'fought': 15, 'four': 15, 'freedom': 19, 'from': 19, 'full': 15, 'gave': 16, 'god': 12, 'government': 19, 'great': 12, 'ground': 15, 'hallow': 17, 'have': 16, 'here': 10, 'highly': 21, 'honored': 10, 'in': 7, 'increased': 13, 'is': 11, 'it': 7, 'larger': 12, 'last': 11, 'liberty': 21, 'little': 9, 'live': 16, 'lives': 16, 'living': 16, 'long': 12, 'measure': 19, 'men': 19, 'met': 19, 'might': 19, 'nation': 7, 'never': 16, 'new': 17, 'nobly': 21, 'nor': 6, 'not': 6, 'note': 6, 'now': 17, 'of': 14, 'on': 6, 'or': 4, 'our': 15, 'people': 20, 'perish': 20, 'place': 20, 'poor': 20, 'portion': 20, 'power': 20, 'proper': 20, 'proposition': 20, 'rather': 10, 'remaining': 19, 'remember': 19, 'resolve': 16, 'resting': 12, 'say': 21, 'score': 13, 'sense': 11, 'seven': 16, 'shall': 11, 'should': 15, 'so': 11, 'struggled': 15, 'take': 22, 'task': 22, 'testing': 12, 'that': 10, 'the': 10, 'their': 10, 'these': 11, 'they': 21, 'this': 11, 'those': 11, 'thus': 15, 'to': 4, 'under': 15, 'unfinished': 15, 'us': 15, 'vain': 16, 'war': 17, 'we': 17, 'what': 17, 'whether': 17, 'which': 17, 'who': 17, 'will': 17, 'work': 22, 'world': 17, 'years': 21} staff_g1 = {'a': 1, 'above': 13, 'add': 4, 'advanced': 11, 'ago': 10, 'all': 12, 'altogether': 14, 'and': 4, 'any': 15, 'are': 6, 'as': 8, 'battlefield': 14, 'be': 5, 'before': 16, 'birth': 13, 'brave': 13, 'brought': 17, 'but': 16, 'by': 14, 'can': 17, 'cause': 16, 'civil': 12, 'come': 19, 'conceived': 15, 'consecrate': 11, 'consecrated': 12, 'continent': 10, 'created': 14, 'dead': 9, 'dedicate': 10, 'dedicated': 7, 'detract': 14, 'devotion': 11, 'did': 18, 'died': 9, 'do': 9, 'earth': 8, 'endure': 13, 'engaged': 9, 'equal': 22, 'far': 9, 'fathers': 12, 'field': 15, 'final': 15, 'fitting': 12, 'for': 9, 'forget': 14, 'forth': 15, 'fought': 14, 'four': 15, 'freedom': 16, 'from': 18, 'full': 15, 'gave': 17, 'god': 10, 'government': 17, 'great': 18, 'ground': 13, 'hallow': 18, 'have': 11, 'here': 8, 'highly': 19, 'honored': 10, 'in': 6, 'increased': 11, 'is': 3, 'it': 7, 'larger': 11, 'last': 10, 'liberty': 21, 'little': 8, 'live': 11, 'lives': 11, 'living': 17, 'long': 17, 'measure': 17, 'men': 13, 'met': 13, 'might': 21, 'nation': 11, 'never': 11, 'new': 8, 'nobly': 20, 'nor': 5, 'not': 7, 'note': 14, 'now': 8, 'of': 10, 'on': 6, 'or': 11, 'our': 14, 'people': 10, 'perish': 15, 'place': 19, 'poor': 20, 'portion': 18, 'power': 19, 'proper': 10, 'proposition': 12, 'rather': 11, 'remaining': 13, 'remember': 12, 'resolve': 19, 'resting': 11, 'say': 19, 'score': 12, 'sense': 10, 'seven': 11, 'shall': 6, 'should': 15, 'so': 2, 'struggled': 14, 'take': 13, 'task': 13, 'testing': 11, 'that': 5, 'the': 11, 'their': 8, 'these': 8, 'they': 21, 'this': 10, 'those': 9, 'thus': 15, 'to': 7, 'under': 16, 'unfinished': 16, 'us': 12, 'vain': 14, 'war': 8, 'we': 13, 'what': 16, 'whether': 20, 'which': 17, 'who': 11, 'will': 16, 'work': 16, 'world': 17, 'years': 20} staff_g2 = {'a': 1, 'above': 6, 'add': 2, 'advanced': 6, 'ago': 7, 'all': 3, 'altogether': 8, 'and': 3, 'any': 5, 'are': 6, 'as': 3, 'battlefield': 8, 'be': 5, 'before': 5, 'birth': 7, 'brave': 6, 'brought': 8, 'but': 9, 'by': 6, 'can': 4, 'cause': 7, 'civil': 8, 'come': 7, 'conceived': 7, 'consecrate': 8, 'consecrated': 9, 'continent': 6, 'created': 7, 'dead': 3, 'dedicate': 6, 'dedicated': 6, 'detract': 6, 'devotion': 7, 'did': 5, 'died': 3, 'do': 2, 'earth': 5, 'endure': 5, 'engaged': 5, 'equal': 5, 'far': 3, 'fathers': 7, 'field': 7, 'final': 7, 'fitting': 6, 'for': 5, 'forget': 7, 'forth': 8, 'fought': 9, 'four': 7, 'freedom': 6, 'from': 7, 'full': 8, 'gave': 4, 'god': 6, 'government': 8, 'great': 5, 'ground': 8, 'hallow': 7, 'have': 5, 'here': 3, 'highly': 7, 'honored': 8, 'in': 4, 'increased': 8, 'is': 4, 'it': 5, 'larger': 5, 'last': 5, 'liberty': 7, 'little': 4, 'live': 7, 'lives': 7, 'living': 7, 'long': 8, 'measure': 6, 'men': 5, 'met': 8, 'might': 8, 'nation': 8, 'never': 4, 'new': 5, 'nobly': 10, 'nor': 4, 'not': 5, 'note': 9, 'now': 6, 'of': 2, 'on': 3, 'or': 4, 'our': 5, 'people': 4, 'perish': 6, 'place': 7, 'poor': 6, 'portion': 7, 'power': 7, 'proper': 4, 'proposition': 8, 'rather': 5, 'remaining': 8, 'remember': 4, 'resolve': 6, 'resting': 7, 'say': 7, 'score': 5, 'sense': 3, 'seven': 4, 'shall': 6, 'should': 8, 'so': 3, 'struggled': 11, 'take': 7, 'task': 6, 'testing': 6, 'that': 4, 'the': 8, 'their': 5, 'these': 4, 'they': 5, 'this': 5, 'those': 5, 'thus': 6, 'to': 4, 'under': 5, 'unfinished': 8, 'us': 5, 'vain': 6, 'war': 4, 'we': 6, 'what': 5, 'whether': 5, 'which': 7, 'who': 6, 'will': 9, 'work': 7, 'world': 8, 'years': 5}
def player(): return ComputerPlayer(Ticket())
while game.empty_squares(): if letter == 'O': square = o_player.get_move(game) else: square = x_player.get_move(game) if game.make_move(square, letter): if print_game: print(letter + f'makes a move to square {square}') game.print_board() print('') if game.current_winner: if print_game: print(letter + 'wins!') return letter #after we made ot move, we need to alternate letters letter = 'O' if letter == 'X' else 'X' if print_game: print('It\'s a tie!') if __name__ == '__main__': x_player = HumanPlayer('X') o_player = ComputerPlayer('O') t = TicTacToe() play(t, x_player, o_player, print_game=True)
def main(): if not os.path.isfile("attack_dict.pickle") or not os.path.isfile( "redistribution_dict.pickle"): print("Create strategy pickles first.") return attack_dict = pickle.load(open("attack_dict.pickle", "rb")) redistribution_dict = pickle.load(open("redistribution_dict.pickle", "rb")) model = Model(attack_dict=attack_dict, redistribution_dict=redistribution_dict) a = ComputerPlayer(model=model, name="Computer") name = input("Enter your name:\n") b = InteractivePlayer(name=name) start_str = input("Should the computer start? (0 for no and 1 for yes)") try: start = int(start_str) if start not in [0, 1]: raise ValueError except ValueError: print( "Didn't get a 0 or 1 as expected for start_str question. Exiting") return while True: if start == 1: a.turn(b) if not b.alive(): print(b.name + " loses") break turn_success = b.turn(a) if not turn_success: return if not a.alive(): print("Computer loses") break elif start == 0: turn_success = b.turn(a) if not turn_success: return if not a.alive(): print("Computer loses") break a.turn(b) if not b.alive(): print(b.name + " loses") break print("Even if you just won, the computer got smarter soo...") pickle.dump(a.model._attack_dict, open("attack_dict.pickle", "wb")) pickle.dump(a.model._redistribution_dict, open("redistribution_dict.pickle", "wb"))
from functools import partial from board import Board from game import Game from player import HumanPlayer, ComputerPlayer from algorithms import sequential, random_search from full_tree_search import full_tree_search # Intialise board board = Board() # Create players - have to use partial application to get a version of tree_search for each token player_set = {'O': 'Alice', 'X': 'Bob'} # , 'Y': 'Charles', 'Z': 'Dennis'} tree_search = full_tree_search(board, list(player_set.keys())) players = [ComputerPlayer(value, key, partial(tree_search, token = key)) for key, value in player_set.items()] # Create and play the game g = Game(board, players) g.play_game()
def computer_plays(): picker = HumanPlayer(name="you") guesser = ComputerPlayer(name="AI thing") game = Game(picker, [guesser]) board = game.play(True) print("Solved ", board.word(), " in ", len(board.guesses()), "guesses")
def play(times): for i in range(times): player_choose = input("1 - Rock \n2 - Paper\n3- Scissors\n") cp = ComputerPlayer() print(cp.play()) print("\n------\n")