def _init_players(self, ai_plays: bool) -> Tuple[Player, Player]: choice = input("Do you want to start? Y/n [any key]. ") self.player1 = Human() if choice.lower() == 'y' \ or not ai_plays else AI() self.player2 = Human() if choice.lower() != 'y' \ or not ai_plays else AI() return (self.player1, self.player2) if choice.lower() == 'y' \ else (self.player2, self.player1)
def init_humans() -> tuple: """ Initializes two Human-players (fixed sides X-first) :return: tuple """ player_name1 = input('Enter name for the first player: ') player1 = Human(player_name1, TicTacToe.X) player_name2 = input('Enter name for the second player: ') player2 = Human(player_name2, TicTacToe.O) return player1, player2
def main(argv): game = Game(Board(argv[0])) if (len(argv) == 1): player = Human(game) else: # try: # player = AI(game, argv[1:]) # except: # print("Invalid search parameters, please try again") # exit() player = AI(game, argv[1:]) player.play()
def setup(game, pim, pits, stones, config=None): """Entry Point""" pbar = tqdm(range(10000)) for char in pbar: pbar.set_description("INITIALIZING GAME %s" % char) print() if config: pbar = tqdm(range(10000)) for _ in pbar: pbar.set_description("GETTING CONFIGURATION FROM {0}".format(config)) print() import yaml with open(config, 'r') as stream: try: config_dict = yaml.load(stream)['config'] pim, pits, stones = config_dict.get('pim', pim), config_dict.get('pits', pits), config_dict.get('stones', stones) game = config_dict.get('game', game) except yaml.YAMLError as exc: print("Something went wrong with reading your config file. \n {}".format(exc)) print(colored("Setting up game with the following config: \n Game Type: {0} " "\n Board Pits: {1} \n Board Stones: {2} \n Penalize Invalid Moves: {3}" .format(BoardConfig.GAME_TYPE_MAP.get(game), pits, stones, pim), "yellow")) print() if click.confirm('Do you want to continue with this configuration?', abort=True): print(text2art("AYO \t \t \t \t OLOPON")) board = Board(pim=pim, pits=pits, stones=stones) if game == "hvh": player_one_name, player_two_name = click.prompt("Enter a name for Player 1 "), click.prompt("Enter a name for Player 2 ") player_one = Human(name=player_one_name, pits=BoardConfig.PLAYER_ONE_PITS, store=BoardConfig.PLAYER_ONE_STORE) player_two = Human(name=player_two_name, pits=BoardConfig.PLAYER_TWO_PITS, store=BoardConfig.PLAYER_TWO_STORE) game = Game(players=[player_one, player_two], board=board) elif game == "hvc": player_one_name = click.prompt("Enter a name for the human player") player_one = Human(name=player_one_name, pits=BoardConfig.PLAYER_ONE_PITS, store=BoardConfig.PLAYER_ONE_STORE) player_two = VectorPlayer(name=generate_name(), pits=BoardConfig.PLAYER_TWO_PITS, store=BoardConfig.PLAYER_TWO_STORE) game = Game(players=[player_one, player_two], board=board) else: player_one = VectorPlayer(name=generate_name(), pits=BoardConfig.PLAYER_ONE_PITS, store=BoardConfig.PLAYER_ONE_STORE) player_two = VectorPlayer(name=generate_name(), pits=BoardConfig.PLAYER_TWO_PITS, store=BoardConfig.PLAYER_TWO_STORE) game = Game(players=[player_one, player_two], board=board) if click.confirm('\n\n{} vs {}. \n Start Game'.format(player_one.name.upper(), player_two.name.upper()), abort=True): game.move(player_one)
def main(): computer1 = Computer(Piece.X.name) human = Human(Piece.O.name) state = Game() while (not state.game_over()): print(state.board) if (state.whose_turn == human.piece): state = human.take_turn(state) else: print("Computer is thinking...") state = computer1.take_turn(state) print(state.board) if (state.winner == computer1.piece): print "Computer Wins\n" elif (state.winner == human.piece): print("You Win\n") else: print("Tie\n")
def __init__(self, running_players=QUANTITY_PLAYERS): self.bag = Bag() self.is_running = True self.players = [] self.running_players = running_players self.lap = 1 # набираем игроков for i in range(1, self.running_players + 1): # присваиваем тип игрока self.players.append(Human(i) if choose_who() else Computer(i))
def init_human_bot(side1: str, side2: str) -> tuple: """ Initializes Human and Bot with given sides :param side1: str :param side2: str :return: tuple """ player_name = input('Enter name for the player: ') player = Human(player_name, side1) bot = Bot(side2) return player, bot
def load_players(self, player_count): """load player information from external file Args: player_count (int): number of players """ player_setup = self.setup["setup"]["tokens"].copy() random.shuffle(player_setup) for i in range(player_count): self.players.append( Human(player_setup[i]["name"], player_setup[i]["start"]))
def _config_game(self, ai_plays: bool) -> Tuple[Player, Player, int, int]: player, other = self._init_players(ai_plays) self._choose_sides(player, other) while True: height, width = Human().get_correct_players_input( "Choose size of playground [height]{whitespace}[width] ") if height > 4 and width > 4: break print("Height and width must be at least 5.") return player, other, height, width
def main(): # Initialize Player. player = Human(200, 420, 64, 64) goblin = Goblin(player) win = Game_Window((500, 480), "First Game") objects = {"Player": player, "Goblins": [goblin], "Bullets": []} pg.time.set_timer(NEW_GOBLIN, 8000) # Execute the mainloop. while True: objects = gameplay(win, objects) if objects == -1: break pg.quit()
def main(): players = [ # AllOrNothingBot(maxDepth=4), CenteringBot(maxDepth=4), # InARowBot(maxDepth=4), # InARowAllowBlanksBot(maxDepth=4), # Human(), # AllOrNothingBot(maxDepth=4), # CenteringBot(maxDepth=4), # InARowBot(maxDepth=4), # InARowAllowBlanksBot(maxDepth=4), Human(), ] game = Game(players=players) while not game.isEnded(): game.takeTurn(verbose=True, pause=True) print(game) game.showWhoWon()
from game import Game from player import Human, Computer game = Game() ''' AI against AI game.accept_player(Computer()) game.accept_player(Computer()) ''' ''' Human against AI ''' game.accept_player(Human()) game.accept_player(Computer()) game.start()
import pygame from player import Human from screen import Screen from game import HardGame from main import play_game if __name__ == "__main__": pygame.init() screen = Screen() player = Human(screen.width/2, screen.height-100) game = HardGame() play_game(screen, player, game)
global info info = None global isPlaying isPlaying = True count = 0 def cli(player): global info global isPlaying cmd = input("\n> ").lower() info = player.action(cmd, player, rooms, things) player = Human("The Player", rooms["outside"], "player") while isPlaying: os.system("cls") player.where(rooms, things) if info != None: print(info) info = None cli(player) count += 1 if count > 14: break
def __init__(self): first = 'first' second = 'second' self.players = {first: Human(first), second: AI(second)} GameState.initPlayers(self.players)
class Game: def __init__(self, player, opponent): self.player = player self.opponent = opponent self.state = State() self.turn = 0 def play(self): while not self.state.gameOver(): if not self.turn & 1: move = (self.player.move(copy(self.state), 1), 1) #print "VALID" if self.state.validMove(*move) else "INVALID" while not self.state.validMove(*move): move = (random.randint(0, 6), 1) self.state.makeMove(*move) else: move = (self.opponent.move(copy(self.state), 2), 2) while not self.state.validMove(*move): move = (random.randint(0, 6), 2) self.state.makeMove(*move) self.turn += 1 print self.state return self.state.winState() if __name__ == "__main__": p = Player() q = Human() game = Game(q, p) game.play() print game.state, game.state.winState()
""" """""" """""" """""" """""" """""" """""" """""" from piece import Checker, King from player import Human # , IA from utils import * from gameboard import * if __name__ == "__main__": display_beginning() display_message("Bienvenue sur le meilleur jeu qui existe.") choice = input("Voulez-vous jouer contre un 'joueur' ou un 'ordi' ? ") #Selection de l'adversaire if choice == "joueur": j1 = Human(1, 0) else: display_message("Les autres modes ne sont pas encore disponibles...") j1 = Human(1.0, 0) j2 = Human(2.0, 0) display_message("Let's the game begin !") #Création du plateau gameboard = create_gameboard() view(gameboard) #Définition du tour du joueur player_turn = {"player_number": 1.0, "status": "still playing"} #Début du jeu
class Config: def __init__(self) -> None: self.player1: Player = Human() self.player2: Player = Human() def _init_players(self, ai_plays: bool) -> Tuple[Player, Player]: choice = input("Do you want to start? Y/n [any key]. ") self.player1 = Human() if choice.lower() == 'y' \ or not ai_plays else AI() self.player2 = Human() if choice.lower() != 'y' \ or not ai_plays else AI() return (self.player1, self.player2) if choice.lower() == 'y' \ else (self.player2, self.player1) @staticmethod def _choose_sides(player: Player, other: Player) -> None: while True: choice = input("Do you want to be X or O. ").upper() if choice in ['X', 'O']: player.symbol = choice other.symbol = 'O' if choice == 'X' else 'X' break print("Invalid operation. Choose X or O. ") def _config_game(self, ai_plays: bool) -> Tuple[Player, Player, int, int]: player, other = self._init_players(ai_plays) self._choose_sides(player, other) while True: height, width = Human().get_correct_players_input( "Choose size of playground [height]{whitespace}[width] ") if height > 4 and width > 4: break print("Height and width must be at least 5.") return player, other, height, width @staticmethod def _echo_client(ip: IPv4Address, port: int) -> None: client = Client(ip, port) client.connect_to_server() while True: # separate messages by 'null byte' for text in client.receive_from_server().split('\0'): if text == SERVER_REQUIRES_INPUT: client.send_to_server(input()) elif text != '': print(text) def _echo_server(self, server_player: Player, client_player: Player, port: int) -> None: server = Server(port) # don't know how to tell mypy that players are subclasses of # class 'Player' self.player1.set_server_and_client( # type: ignore server, self.player1 is not server_player) self.player2.set_server_and_client( # type: ignore server, self.player2 is not server_player) print(f"Share this with your friend: ip '{server.host}' " f"port: {port}") server.start_server() server.send_to_client(f"You are player {client_player.symbol}") def init_game(self, create: bool, ip: Optional[List[IPv4Address]], port: Optional[List[int]]) -> None: ai_plays = not create and ip is None if create or ai_plays: server_player, client_player, height, width = \ self._config_game(ai_plays) if not ai_plays: assert port is not None self._echo_server(server_player, client_player, port[0]) game(height, width, self.player1, self.player2) else: assert ip is not None and port is not None self._echo_client(ip[0], port[0])
def __init__(self) -> None: self.player1: Player = Human() self.player2: Player = Human()
self.apples.append(self.map[rand_loc_apple[1]][rand_loc_apple[0]]) self.calculate_fitness() return # Empty next_loc_cell = Snake_Body(loc=next_loc, game=self) self.snake.append(next_loc_cell) self.map[next_loc[1]][next_loc[0]] = next_loc_cell tail = self.snake.pop(0) self.map[tail.loc[1]][tail.loc[0]] = Empty_Cell(loc=tail.loc, game=self) self.calculate_fitness() if self.starving_turn >= self.turn_limit: self.is_game_end = True return if __name__ == "__main__": from player import Human, Machine human = Human() game = Game(player=human, turn_limit=100) while not game.is_game_end: print("-------\nEaten apples:%d, Snake len:%d, Iter:%d, S_turn:%d\n" % (game.eaten_apples, len( game.snake), game.iteration_number, game.starving_turn)) for y in game.map: for x in y: print(x, end=" ") print() game.iterate()
def play(play_with=0): random.seed(0) p1 = RLAgent("RLAgent2", gamma, learning_rate, batch_size, copy_weights_switch, 16, [100, 180, 100], 12, replay_memory_size) p1.load_models() p2 = None if (play_with == 1): p2 = RLAgent("RLAgent2", gamma, learning_rate, batch_size, copy_weights_switch, 16, [100, 180, 100], 12, replay_memory_size) p2.load_models() else: name = input("\nPlease enter your name: ") p2 = Human(name) num_of_games = 5 print("Your player ID: ", p2.id) win_count = {p1.name: 0, p2.name: 0} total_rewards = {p1.name: [], p2.name: []} move_count = {} for i in range(1, num_of_games + 1): number_of_moves = 0 game = Game(game_board_height, game_board_width, p1, p2) episode_rewards = {p1.name: 0, p2.name: 0} print("New Game!") while not game.get_status()["game_over"]: number_of_moves += 1 state = game.get_state() game.draw_game() print("\nActive Player: ", game.active_player.name) selected_edge = int(game.active_player.get_edge(state, 0)) print( "Seleted Edge: ", selected_edge, ) status = game.play(selected_edge) print(status) game_over = status['game_over'] if (status['invalid_move']): r = game.invalid_move_reward elif game_over: if status['winner'] == 0: r = game.tie_reward elif status['winner'] == game.active_player.id: r = game.winning_reward win_count[game.active_player.name] += 1 else: if status['double_closed']: r = game.double_closed_reward print("Bingo! Double closed!") elif status['box_closed']: r = game.box_closed_reward print("Box closed!") else: r = 0 episode_rewards[game.active_player.name] += r if not game_over: game.switch_player() total_rewards[p1.name].append(episode_rewards[p1.name]) total_rewards[p2.name].append(episode_rewards[p2.name]) move_count[i] = number_of_moves print("Game Over!! Winner: ", game.get_player_with_id(game.winner_id).name) print("Game board: ", game.get_state()) print("Total games: ", num_of_games) print("Win_status: ", win_count) print("Move count: ", move_count)