Esempio n. 1
0
def main():
    playerName = input("Give your name: ")

    #Luodaan pelaajaoliot
    human = HumanPlayer(playerName)
    cpu = CPUPlayer("CPU")

    isQuitting = False
    while not isQuitting:
        humanResult = human.play()
        cpuResult = cpu.play()

        result = resolve(humanResult, cpuResult)

        print(human.name, humanResult)
        print(cpu.name, cpuResult)

        if result == 0:
            print("It's a tie!")
        elif result == 1:
            print(human.name, "wins!!")
        else:
            print(cpu.name, "wins!!")

        playAgain = input("Play again (y/n").lower().strip()
        isQuitting = playAgain == "n"
Esempio n. 2
0
 def create_p_vs_p_game(cls):
     p1_name = cls._prompt_name("Player 1", [])
     p2_name = cls._prompt_name("Player 2", [p1_name])
     print()
     p1 = HumanPlayer(p1_name)
     p2 = HumanPlayer(p2_name)
     return Game(p1, p2)
Esempio n. 3
0
 def humanVsBot(self):
     while True:
         print(
             "\033[94m===================================================================\033[0m\033[22m"
         )
         control = input("Do you want to play first: (y/n)? ")
         if control == "y":
             self.redSide = HumanPlayer("Tuan", redSide=True)
             self.notRedSide = AIPlayer("AI", redSide=False)
         else:
             self.redSide = AIPlayer("AI", redSide=True)
             self.notRedSide = HumanPlayer("Tuan", redSide=False)
         self.game = Game(self.redSide, self.notRedSide)
         self.game.printBoard()
         print(
             "\nWelcome! To play, enter a command, e.g. '\033[95mh3\033[0m'. 'h' for horizontal and 'v' for vertical."
         )
         while not self.game.isEnd():
             self.redSideMove()
             if not self.game.isEnd():
                 self.notRedSideMove()
                 if self.game.isEnd():
                     self.printResult()
                 continue
             else:
                 self.printResult()
Esempio n. 4
0
 def make_two_players(self):
     while True:
         ps = input(
             "Please select two player`s type:\n\t0.Human\n\t1.AI\nSuch as:0 0\n:"
         )
         pss = ps.split(' ')
         if len(pss) != 2:
             print('\nWrong choice, please enter numbers as example')
             continue
         elif len(pss) == 2:
             p1, p2 = [int(p) for p in ps.split(' ')]
             if p1 > 1 or p2 > 1:
                 print('\nWrong choice, please enter numbers as example')
                 continue
             break
     while True:
         if p1 == 1 and p2 == 1:
             level_ix1 = int(
                 input(
                     "Please select the level of AI player1.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix1 > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             level_ix2 = int(
                 input(
                     "Please select the level of AI player2.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix2 > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             player1 = AIPlayer('X', level_ix1)
             player2 = AIPlayer('O', level_ix2)
             break
         elif p1 == 1 or p2 == 1:
             level_ix = int(
                 input(
                     "Please select the level of AI player.\n\t0: random\n\t1: minmax\n\t2: minimax_alphabeta\n\t3: MCTS3s\n\t4: MCTS?s\n:"
                 ))
             if level_ix > 4:
                 print('\nWrong choice, please enter numbers as behind')
                 continue
             else:
                 if p1 == 0:
                     player1 = HumanPlayer('X')
                     player2 = AIPlayer('O', level_ix)
                     break
                 elif p2 == 0:
                     player1 = AIPlayer('X', level_ix)
                     player2 = HumanPlayer('O')
                     break
         else:
             player1, player2 = HumanPlayer('X'), HumanPlayer('O')
             break
     return player1, player2
Esempio n. 5
0
    def __init__(self, max_depth: int, num_human: int, random_players: int,
                 smart_players: List[int]) -> None:
        """Initialize this game, as described in the Assignment 2 handout.

        Precondition:
            2 <= max_depth <= 5
        """
        self.board = random_init(0, max_depth)
        self.board.update_block_locations((0, 0), BOARD_WIDTH)
        num_players = num_human + random_players + len(smart_players)
        self.renderer = Renderer(num_players)
        self.players = []
        if random.random() < 0.5:
            for i in range(num_human):
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(HumanPlayer(self.renderer, \
                                                len(self.players), \
                                                BlobGoal(target)))
            for i in range(random_players):
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(RandomPlayer(self.renderer, \
                                                 len(self.players), \
                                                 BlobGoal(target)))
            for i in smart_players:
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(SmartPlayer(self.renderer, \
                                                len(self.players), \
                                                BlobGoal(target), \
                                                i))
        else:
            for i in range(num_human):
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(HumanPlayer(self.renderer, \
                                                len(self.players), \
                                                PerimeterGoal(target)))
            for i in range(random_players):
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(RandomPlayer(self.renderer, \
                                                 len(self.players), \
                                                 PerimeterGoal(target)))
            for i in smart_players:
                target = \
                    COLOUR_LIST[int(random.random() * len(COLOUR_LIST))]
                self.players.append(SmartPlayer(self.renderer, \
                                                len(self.players), \
                                                PerimeterGoal(target), \
                                                i))
        self.renderer.draw(self.board, 0)
Esempio n. 6
0
class TestPlayer(unittest.TestCase):
    def setUp(self):
        self.game = TicTacToe()
        self.human_player = HumanPlayer("X")
        self.computer_player = GeniusComputerPlayer("O")

    @patch('player.input')
    @patch('game.TicTacToe.available_moves')
    def test_human_get_move(self, availableMovesMock, inputMock):
        inputMock.return_value = 4
        availableMovesMock.return_value = [0, 1, 3, 4, 5, 6, 7, 8]
        self.assertEqual(4, self.human_player.get_move(self.game))
        inputMock.return_value = 2
        self.assertIsNone(self.human_player.get_move(self.game))
Esempio n. 7
0
	def initPlayers(self):
		self.width = 9
		self.height = 9
		self.board = Board(width=self.width, height=self.height, n_in_row=5)
		self.mcts_player = MCTSPlayer(c_puct=5, n_playout=1000)
		self.human_player = HumanPlayer()

		self.start_player = 0	# 0 - human, 1 - mcts_player

		self.board.init_board(self.start_player)
		p1, p2 = self.board.players
		self.human_player.set_player_id(p1)
		self.mcts_player.set_player_id(p2)
		self.players = {p2: self.mcts_player, p1: self.human_player}
		self.board.show(self.human_player.playerId, self.mcts_player.playerId)
Esempio n. 8
0
 def create_p_vs_ai_game(cls):
     p_name = cls._prompt_name("Player", [])
     ai_diff = cls._prompt_difficulty("AI")
     print()
     p = HumanPlayer(p_name)
     ai = AIPlayer("Bot", ai_diff)
     return Game(p, ai)
Esempio n. 9
0
	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))
Esempio n. 10
0
 def player(player_type,token,display_object=None):
     if display_object is None:  display_object=Prompter()
     players = {"Human":HumanPlayer(token,display_object),
                "Humanoid":Humanoid(token,display_object),
                "ImpossibleAI":ImpossibleAI(token,display_object),
                "EasyAI":ImpossibleAI(token,display_object,Minimax(token,1))}
     return players.get(player_type)
Esempio n. 11
0
 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)))
Esempio n. 12
0
 def run_game(self, num_h, num_r, num_s):
     t = 0
     l = []
     for i in range(num_h):
         l.append(HumanPlayer(self.b))
         t += 2
     for i in range(num_r):
         l.append(RandomPlayer(self.b))
         t += 2
     for i in range(num_s):
         l.append(SmartPlayer(self.b, -1 + t))
         t += 2
     while not self.game_over():
         for playr in l:
             self.draw_board()
             plm = playr.move()
             self.make_move(plm[0], plm[1])
             print(
                 '\n' + str(playr) + ' ' + str(l.index(playr)) +
                 ' made move (' + str(plm[0]) + ', ' + str(plm[1]) +
                 ')\n\n---------------------------------------------------\n'
             )
             if self.game_over():
                 print('\n\n' + str(playr) + ' ' + str(l.index(playr)) +
                       ' Lost')
                 return l.index(playr)
Esempio n. 13
0
	async def perudo(self):

		self.round = 0
		self.players = []


		for joueur in self.liste_joueurs:
			self.players.append(
				HumanPlayer(
					joueur = joueur,
					dice_number = self.dice_number,
					client = self
				)
			)

		random.shuffle(self.players)

		print(welcome_message(self.players))
		await self.perudo_chanel.send(welcome_message(self.players))

		self.first_player = random.choice(self.players)

		while len(self.players) > 1:
			await self.run_round()

		print(winner(self.players[0].name))

		await self.perudo_chanel.send(winner(self.players[0].name))
Esempio n. 14
0
    def __init__(self, max_depth: int, num_human: int, random_players: int,
                 smart_players: List[int]) -> None:
        """Initialize this game, as described in the Assignment 2 handout.

        Each player has a random target colour, and all players share the
        same goal(Players might have same target colour.)

        Precondition:
            2 <= max_depth <= 5
        """
        self.board = random_init(0, max_depth)
        self.board.update_block_locations((0, 0), BOARD_WIDTH)
        num_player = num_human + random_players + len(smart_players)
        self.renderer = Renderer(num_player)
        self.players = []

        random_num = random.randint(0, 1)
        for i in range(num_player):
            if random_num == 0:
                goal = BlobGoal(COLOUR_LIST[random.randint(0, 3)])
            else:
                goal = PerimeterGoal(COLOUR_LIST[random.randint(0, 3)])
            if i < num_human:
                self.players.append(HumanPlayer(self.renderer, i, goal))
            elif num_human <= i < num_human + random_players:
                self.players.append(RandomPlayer(self.renderer, i, goal))
            else:
                self.players.append(
                    SmartPlayer(
                        self.renderer, i, goal,
                        smart_players[i - (num_human + random_players)]))
        # Display each player's goal before starting game.
        for i in range(num_player):
            self.renderer.display_goal(self.players[i])
Esempio n. 15
0
    def set_players(self, num_human, random_players, smart_players):
        """Generate a common goal with different target colours for each players

        Each player gets player_id from 0 to total number of players.
        Add all of players to self.players
        """
        rand_goal, num = random.randint(0, 1), 0
        for _ in range(num_human):
            if rand_goal == 1:
                goal = BlobGoal(COLOUR_LIST[random.randint(0, 3)])
            else:
                goal = PerimeterGoal(COLOUR_LIST[random.randint(0, 3)])
            new_player = HumanPlayer(self.renderer, num, goal)
            self.renderer.display_goal(new_player)
            self.players.append(new_player)
            num += 1
        for _ in range(random_players):
            if rand_goal == 1:
                goal = BlobGoal(COLOUR_LIST[random.randint(0, 3)])
            else:
                goal = PerimeterGoal(COLOUR_LIST[random.randint(0, 3)])
            self.players.append(RandomPlayer(self.renderer, num, goal))
            num += 1
        for i in range(len(smart_players)):
            if rand_goal == 1:
                goal = BlobGoal(COLOUR_LIST[random.randint(0, 3)])
            else:
                goal = PerimeterGoal(COLOUR_LIST[random.randint(0, 3)])
            self.players.append(
                SmartPlayer(self.renderer, num, goal, smart_players[i]))
            num += 1
Esempio n. 16
0
    def _generate_players(self, num_players: int, player_type: str,
                          goal_type: str, start_id: int) -> List[Player]:
        """Generate a list of players with the given number of players,
        of the given type, with the given <goal_type>, with ids incrementing
        from <start_id>.

        Preconditions:
            player_type == 'human', 'random', or 'smart'
            goal_type == 'blob', or 'perimeter'
        """
        player_list = []
        player_count = 0
        id_count = start_id

        while player_count < num_players:
            # Generate a blob goal or a perimeter goal with a random colour
            if goal_type == 'blob':
                goal = BlobGoal(COLOUR_LIST[random.randint(0, 3)])
            else:
                goal = PerimeterGoal(COLOUR_LIST[random.randint(0, 3)])

            # Generate a player of the given type, using goal
            if player_type == 'human':
                player = HumanPlayer(self.renderer, id_count, goal)
            elif player_type == 'random':
                player = RandomPlayer(self.renderer, id_count, goal)
            else:
                player = SmartPlayer(self.renderer, id_count, goal)

            # Add player to the player list, iterate counts by one
            player_list.append(player)
            player_count += 1
            id_count += 1

        return player_list
Esempio n. 17
0
def test_human_player():

    nodes = [
        GameNode(0, [], [1, 2]),
        GameNode(1, [], [0, 2]),
        GameNode(2, [], [0, 1, 3]),
        GameNode(3, [], [2, 4, 5]),
        GameNode(4, [], [3, 5]),
        GameNode(5, [], [3, 4])
    ]

    players = [
        HumanPlayer(0, [HumanInteractionUnit(0, nodes[0])], [nodes[0]],
                    nodes[0]),
        HumanPlayer(1, [HumanInteractionUnit(1, nodes[1])], [nodes[1]],
                    nodes[1]),
        HumanPlayer(2, [HumanInteractionUnit(2, nodes[4])], [nodes[4]],
                    nodes[4]),
        HumanPlayer(3, [HumanInteractionUnit(3, nodes[5])], [nodes[5]],
                    nodes[5])
    ]

    nodes[0].add_unit(players[0].units[0])
    nodes[1].add_unit(players[1].units[0])
    nodes[4].add_unit(players[2].units[0])
    nodes[5].add_unit(players[3].units[0])

    graph = GameGraph(nodes)

    game = Game(players, graph)

    game.update_state([], False)

    def next_round(event):
        win = game.play_round()
        if win is None:
            graphics.draw(f, w, l, game.state)
        else:
            graphics.draw_winner(w, win)

    f, w, l = graphics.setup(game.state, next_round)

    for p in players:
        p.canvas = w

    graphics.draw(f, w, l, game.state)
    graphics.show()
Esempio n. 18
0
 def createPlayers(playerName="John Doe",
                   team1Name="Team Suriname",
                   team2Name="Team Nederland"):
     p1 = HumanPlayer(1, playerName, team1Name)
     p2 = Player(2, "Bob Marley", team1Name)
     p3 = Player(3, "Tupac Shakur", team2Name)
     p4 = Player(4, "Jimi Hendrix", team2Name)
     return [p1, p3, p2, p4]
Esempio n. 19
0
    def get_player(self):
        'Get new player or vacant player if any'
        player = self.get_left_player()
        if player is None:
            return HumanPlayer()

        player.rejoin()
        return player
Esempio n. 20
0
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")
Esempio n. 21
0
 def __init__(self,
              players={
                  'mikko': HumanPlayer(),
                  'beta-ai': RandomPlayer()
              }):
     self.players = players
     player_names = list(players.keys())
     shuffle(player_names)
     self.game_state = dominion.GameState(player_names)
Esempio n. 22
0
def main():
    game = Game()
    render = Render(game)
    timer = pygame.time.Clock()
    players = []

    # add player
    tank = Tank()
    tank.pos = Vec2d(200, 200)
    p1 = HumanPlayer('Ray', tank)
    p1.Mapping = HumanPlayer.MappingSet1

    tank2 = Tank()
    tank2.pos = Vec2d(400, 200)
    p2 = HumanPlayer('Pest', tank2)
    p2.Mapping = HumanPlayer.MappingSet2

    players += [p1, p2]
    for p in players:
        game.add_player(p)

    # add obstacle
    for pos, col in zip([(100, 400), (500, 400)], ['blue', 'red']):
        obs = ObstacleBlock((100, 100), pos,  Color(col))
        game.obstacles.append(obs)

    timer.tick()
    FPS = config.FPS
    dt = 1.0/FPS
    while 1:
        for e in pygame.event.get():
            if e.type == QUIT:
                return
            elif e.type == KEYDOWN:
                for p in players:
                    p.on_keydown(e.key)
                if e.key == K_b or (e.mod & KMOD_LCTRL) and e.key == K_q:
                    return
            elif e.type == KEYUP:
                for p in players:
                    p.on_keyup(e.key)
        game.loop(dt)
        render.draw()
        game.fps = timer.tick(FPS)
Esempio n. 23
0
 def create_players(self):
     print( "X goes first.")
     self.human_player = HumanPlayer(game = self)
     self.ai_player    = AIPlayer(game = self)
     self.human_player.set_playing_letter(self.letter_choice())
     self.ai_player.set_playing_letter({"X":"O","O":"X"}.get(self.human_player.playing_letter))
     print "[DEBUG] ai_player plays as",self.ai_player.playing_letter
     print "[DEBUG] human player plays as",self.human_player.playing_letter
     # We need an ordered list for the mainloop
     return self.human_first() and [self.human_player,self.ai_player] or [self.ai_player,self.human_player]
Esempio n. 24
0
    def __init__(self, *args):
        self.players = []
        for count, arg in enumerate(*args, start=1):
            if not arg:
                self.players.append(HumanPlayer(f'Player {count}'))
            else:
                self.players.append(Player(f'Computer {count}'))

        self.game_bag = Bag()
        self.round = 1
Esempio n. 25
0
    def __init__(self, max_depth: int, num_human: int, random_players: int,
                 smart_players: List[int]) -> None:
        """Initialize this game, as described in the Assignment 2 handout.

        Precondition:
            2 <= max_depth <= 5
        """
        self.max_depth = max_depth
        self.num_human = num_human
        self.random_players = random_players
        self.smart_players = smart_players
        self.num_players = num_human + random_players + len(smart_players)

        # 1 create a Renderer for this game
        self.renderer = Renderer(self.num_players)

        # 2 Generate a random goal typr, for all players to share
        potential_goal = [
            BlobGoal(COLOUR_LIST[0]),
            PerimeterGoal(COLOUR_LIST[0])
        ]
        self.goal = potential_goal[random.randint(0, 1)]

        # 3 Generate a random board, with the given maximum depth
        self.board = random_init(0, max_depth)
        self.board.update_block_locations((0, 0), 750)

        # 4 Generate the right number of human players, random players,
        # and smart players
        self.players = []
        for human_id in range(num_human):
            self.players.append(HumanPlayer(self.renderer, human_id,
                                            self.goal))
        for ran_id in range(num_human, num_human + random_players):
            self.players.append(RandomPlayer(self.renderer, ran_id, self.goal))
        for smart_id in range(num_human + random_players, self.num_players):
            difficulty_level = smart_players[smart_id - num_human -
                                             random_players]
            self.players.append(
                SmartPlayer(self.renderer, smart_id, self.goal,
                            difficulty_level))

        for player in self.players:
            player.goal.colour = COLOUR_LIST[random.randint(0, 3)]
            if isinstance(self.goal, BlobGoal):
                player.goal = BlobGoal(player.goal.colour)
            else:
                player.goal = PerimeterGoal(player.goal.colour)
            if isinstance(player, HumanPlayer):
                self.renderer.display_goal(player)

        # 5 before returning, draw the board
        for player_id in range(len(self.players)):
            self.renderer.draw(self.board, player_id)
Esempio n. 26
0
def test_mcplayer_vs_humanplayer(N):
    """
    test against human player
    :return:
    """
    board = Board(N)
    p1 = MCPlayerQ(N, epsilon=0)
    p1.load_Q(player_file[N])
    p2 = HumanPlayer(N)
    match = Match(N, p1, p2, verbose=True)
    match.play_match()
Esempio n. 27
0
def test_mcplayer_vs_humanplayer_3x3():
    """
    test against human player
    :return:
    """
    board = Board(3)
    p1 = HumanPlayer(3)
    p2 = MCPlayerQ(3)
    p2.load_Q(player_file[3])
    match = Match(3, p1, p2, verbose=True)
    match.play_match()
Esempio n. 28
0
    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
Esempio n. 29
0
 def __init__(self, _view: view.View):
     self.view = _view
     self.games = 0
     self.isTraining = False
     self.player2 = HumanPlayer("p2", -1)
     self.player1 = Player("pl", 1)
     self.player1.load_policy(const.POLICY1)
     self.machine = None
     self.game_type = ""
     self.disabled_action = True  # disable ability to click on board
     self.t = None  # thread
     self.mode = -1
Esempio n. 30
0
    def __init__(self, max_depth: int,
                 num_human: int,
                 random_players: int,
                 smart_players: List[int]) -> None:
        """Initialize this game, as described in the Assignment 2 handout.

        Precondition:
            2 <= max_depth <= 5
        """
        # Create the board
        self.board = random_init(0, max_depth)
        self.board.update_block_locations((0, 0), BOARD_WIDTH)
        # Generate a goal
        goals = [BlobGoal, PerimeterGoal]
        index = random.randrange(0, 2)
        goal = goals[index]

        # Create render
        num_players = num_human + random_players + len(smart_players)
        self.renderer = Renderer(num_players)

        # Create players
        self.players = []
        val = 0
        for id_ in range(num_human):
            # Create a colour for this player
            index = random.randrange(0, 4)
            colour = COLOUR_LIST[index]
            self.players.append(HumanPlayer(self.renderer, id_, goal(colour)))
            val += 1

        for id_ in range(random_players):
            # Create a colour for this player
            index = random.randrange(0, 4)
            colour = COLOUR_LIST[index]
            self.players.append(RandomPlayer(self.renderer, val, goal(colour)))
            val += 1

        # A SmartPlayer has a difficulty level
        if len(smart_players) > 0:
            for id_ in range(len(smart_players)):
                # Create a colour for this player
                index = random.randrange(0, 4)
                colour = COLOUR_LIST[index]
                self.players.append(SmartPlayer(self.renderer, val,
                                                goal(colour),
                                                smart_players[id_]))
                val += 1
        # Display the goal and draw the board
        for i in self.players:
            self.renderer.display_goal(i)
            self.renderer.draw(self.board, i.id)
Esempio n. 31
0
def run():
    parse = argparse.ArgumentParser(description="gomoku program")
    parse.add_argument("player1",
                       type=int,
                       choices=[1, 2, 3, 4],
                       help="1.Human; 2.MCTS; 3.Random; 4.Expert")

    parse.add_argument("player2",
                       type=int,
                       choices=[1, 2, 3, 4],
                       help="1.Human; 2.MCTS; 3.Random; 4.Expert")

    parse.add_argument("--size",
                       type=int,
                       default=8,
                       help="The Board size,default is 8*8 ")

    parse.add_argument("--simulate_time",
                       type=int,
                       default=2,
                       help="The MCTS playout simulation time,default is 2s ")

    args = parse.parse_args()
    chess = Gomoku(board_size=args.size)
    p1 = {
        1: HumanPlayer(chess),
        2: MCTSPlayer(chess, simulate_time=args.simulate_time),
        3: RandomPlayer(chess),
        4: ExpertPlayer(chess)
    }

    p2 = {
        1: HumanPlayer(chess),
        2: MCTSPlayer(chess, simulate_time=args.simulate_time),
        3: RandomPlayer(chess),
        4: ExpertPlayer(chess)
    }

    chess.play(p1[args.player1], p2[args.player2], isShow=True)
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 ""
Esempio n. 33
0
def play(policy_number):
    player1 = HumanPlayer()
    player2 = Player(epsilon=0, symbol=-1)
    player2.load_policy(policy_number)
    while True:
        judger = Judger(player1, player2)
        winner = judger.play()
        if winner == player2.symbol:
            print("You lose!")
        elif winner == player1.symbol:
            print("You win!")
        else:
            print("It is a tie!")
Esempio n. 34
0
class Game:
    def __init__(self,board_size=3):
        self.board_size = board_size
        self.reset()

    def reset(self):
        self.board = Board(self,self.board_size)
        
    def intro(self):
        print('Welcome to Jose\'s Unbeatable Tic Tac Toe!')
        print """

        Use your keypad as if it were the board
        
        7 | 8 | 9
        ---------
        4 | 5 | 6
        ---------
        1 | 2 | 3
        
        Have fun, and good luck.
        """

    def letter_choice(self):
        letter = None
        while not (letter == 'X' or letter == 'O'):
            print('Do you want to be X or O?')
            letter = raw_input().upper()

        return letter

    def create_players(self):
        print( "X goes first.")
        self.human_player = HumanPlayer(game = self)
        self.ai_player    = AIPlayer(game = self)
        self.human_player.set_playing_letter(self.letter_choice())
        self.ai_player.set_playing_letter({"X":"O","O":"X"}.get(self.human_player.playing_letter))
        print "[DEBUG] ai_player plays as",self.ai_player.playing_letter
        print "[DEBUG] human player plays as",self.human_player.playing_letter
        # We need an ordered list for the mainloop
        return self.human_first() and [self.human_player,self.ai_player] or [self.ai_player,self.human_player]

    def human_first(self):
        return self.human_player.playing_letter == "X"
        
    def play_again(self):
        print('Do you want to play again? (yes or no)')
        return (raw_input().lower().startswith('y'))

    def mainloop(self):
        players         = self.create_players()
        game_is_playing = True
        while game_is_playing:
            for player in players :
                player.play()
                #self.board.show()
                if player.wins():
                    print "[DEBUG] show board after win"
                    self.board.show()                    
                    player.display_winning_message()
                    # gets out of the while loop
                    game_is_playing = False
                    # gets out of the foor loop
                    break
                elif self.board.is_full():
                    self.board.show()
                    print('The game is a tie.')
                    # gets out of the while loop
                    game_is_playing = False
                    # gets out of the foor loop
                    break

        return self.play_again()