Exemplo n.º 1
0
 def setUp(self):
     self.player1 = AIPlayer('Player1')
     self.player2 = AIPlayer('Player2')
     self.player3 = AIPlayer('Player3')
     self.player4 = AIPlayer('Player4')
     self.game = Game(
         [self.player1, self.player2, self.player3, self.player4])
Exemplo n.º 2
0
    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()
Exemplo n.º 3
0
class TestAIPlayer(unittest.TestCase):
    def setUp(self) -> None:
        self.b = Board()
        self.p = AIPlayer(self.b)

    def test_ai_player(self):
        self.assertIsInstance(self.p, AIPlayer)
        self.assertEqual(self.p.shape, 'O')  # default shape
        self.assertEqual(self.p.name, 'Bot')  # fixed name

    def test_minmax(self):
        shapes_map = {'AI': 'O', 'HUM': 'X'}
        cases = (
            (['X', 'O', 'X', 'O', 'X', 'X', 'O', 'X', 'O'], 'AI', 0),
            (['X', 'X', 'X', 'O', 'O', 5, 6, 7, 8], 'AI', -10),
            (['O', 1, 'X', 'X', 'O', 'O', 'X', 'X', 'O'], 'HUM', 10),
            (['O', 'X', 'O', 'X', 'X', 5, 6, 'O', 'X'], 'AI', 0),
        )
        for c in cases:
            with self.subTest(board=c[0], player=c[1]):
                res = self.p.minmax(c[0], c[1], shapes_map)
                self.assertEqual(res['score'], c[2])

    def test_next_move(self):
        cases = (
            ([[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']], (0, 0)),
            ([['X', 'X', ' '], [' ', 'O', ' '], [' ', ' ', ' ']], (2, 0)),
            ([['X', 'X', 'O'], ['X', 'O', ' '], [' ', ' ', 'X']], (0, 2)),
        )
        for c in cases:
            with self.subTest(board=c[0]):
                self.b.board = c[0]
                x, y = self.p.next_move()
                self.assertEqual((int(x), int(y)), c[1])
Exemplo n.º 4
0
def main():
    ai_player1 = TestPlayer()
    ai_player2 = AIPlayer(15, 15)
    while True:
        game = play_episode(ai_player1, ai_player2)
        if game != None:
            ai_player1.train_game(game)
            ai_player2.model = ai_player1.model
Exemplo n.º 5
0
    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(' ')
Exemplo n.º 6
0
 def from_seed(cls, hex_seed):
     seed = bytes.fromhex(hex_seed).decode()
     values = seed.split('.')
     board = Board(int(values[0]), int(values[1]))
     if values[2] == 'm':
         player_1 = ManualPlayer(values[3], int(values[4]), int(values[5]))
     else:
         player_1 = AIPlayer(values[3], int(values[4]), int(values[5]))
     end = 7 + int(values[6])
     for i in range(7, end):
         coordinates = values[i].split('-')
         x, y = int(coordinates[1]), int(coordinates[0])
         board.fill_tile(x, y, player_1.id)
         Player.p1_add_coordinate(x, y)
     i = end
     if values[i] == 'm':
         player_2 = ManualPlayer(values[i + 1], int(values[i + 2]),
                                 int(values[i + 3]))
     else:
         player_2 = AIPlayer(name=values[i + 1],
                             tokens=int(values[i + 2]),
                             moves=int(values[i + 3]))
         Player.set_state(p2_tokens=int(values[i + 2]),
                          p2_moves=int(values[i + 3]))
     end = i + 5 + int(values[i + 4])
     for j in range(i + 5, end):
         coordinates = values[j].split('-')
         x, y = int(coordinates[1]), int(coordinates[0])
         board.fill_tile(x, y, player_2.id)
         Player.p2_add_coordinate(x, y)
     j = end
     if values[j] == "1":
         current_player = player_1
         Player.set_state(width=int(values[0]),
                          height=int(values[1]),
                          turn=1,
                          p1_tokens=int(values[4]),
                          p1_moves=int(values[5]))
     else:
         current_player = player_2
         Player.set_state(width=int(values[0]),
                          height=int(values[1]),
                          turn=2)
     return cls(player_1=player_1,
                player_2=player_2,
                board=board,
                current_player=current_player,
                moves=30)
Exemplo n.º 7
0
def main():

    width = 15
    height = 15

    player1 = AIPlayer(width, height, True)
    player2 = CommandPlayer()

    for i in range(50000):
        board = Board(width, height)
        referee = Referee()
        result = referee.start_game(board, player1, player1)
        print(board)
        print("win : " + str(result) + "\n")
        print("episode" + str(i) + "\n")

    player1.save()
Exemplo n.º 8
0
 def setUp(self):
     self.player = AIPlayer('Player1')
     self.player2 = AIPlayer('Player2')
     self.player3 = AIPlayer('Player3')
     self.player4 = AIPlayer('Player4')
     self.jack_spades = Card('Spades', 'J', 12)
     self.five_spades = Card('Spades', '5', 5)
     self.ten_clubs = Card('Clubs', '10', 10)
     self.ace_spades = Card('Spades', 'A', 15)
     self.ace_diamonds = Card('Diamonds', 'A', 15)
     self.ace_clubs = Card('Clubs', 'A', 15)
     self.queen_hearts = Card('Hearts', 'Q', 13)
     self.five_hearts = Card('Hearts', '5', 5)
     self.six_hearts = Card('Hearts', '6', 6)
     self.player._cards.extend([
         self.jack_spades, self.five_spades, self.ten_clubs, self.ace_spades
     ])
Exemplo n.º 9
0
class Game:

    PF1 = PlayingField()
    Player1 = Player()
    AIPlayer1 = AIPlayer()

    def __init__(self):
        pass

    def start(self):
        pass

    def end(self):
        pass

    pass
Exemplo n.º 10
0
 def setUp(self):
     self.player = AIPlayer('Player1')
     self.player2 = AIPlayer('Player2')
     self.player3 = AIPlayer('Player3')
     self.player4 = AIPlayer('Player4')
     self.jack_spades = Card('Spades', 'J', 12)
     self.five_spades = Card('Spades', '5', 5)
     self.ten_clubs = Card('Clubs', '10', 10)
     self.ace_spades = Card('Spades', 'A', 15)
     self.ace_diamonds = Card('Diamonds', 'A', 15)
     self.ace_clubs = Card('Clubs', 'A', 15)
     self.queen_hearts = Card('Hearts', 'Q', 13)
     self.five_hearts = Card('Hearts', '5', 5)
     self.six_hearts = Card('Hearts', '6', 6)
     self.player._cards.extend([self.jack_spades, self.five_spades,
                                self.ten_clubs, self.ace_spades])
Exemplo n.º 11
0
    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))
Exemplo n.º 12
0
    def start():
        CLI.clear_window()

        print()
        print('Hi, you might want to play Ohio?!')
        print()
        print('OK, how many people will play? (from 1 to 4)')
        number = input('==> ')
        while not CLI.is_number(number) or int(number) not in range(0, 5):
            CLI.clear_window()
            print()
            print('Hi, you might want to play Ohio?!')
            print()
            print('Please, enter a number from 1 to 4!')
            number = input('==> ')

        players = []
        number = int(number)
        for n in range(1, number + 1):
            CLI.clear_window()
            print()
            print('Please, enter a name for the ' + str(n) + ' player: ')
            name = input('==> ')
            players.append(RealPlayer(name))

        for n in range(1, 5 - number):
            players.append(AIPlayer('AIRobot' + str(n)))

        CLI.clear_window()
        print()
        print('Players are ready to play!')
        print()
        for player in players:
            print(player._name)

        game = Game(players)

        print()
        ok = input('Press any key to start the game...')

        game.start()
Exemplo n.º 13
0
import argparse

from player import HumanPlayer, RandomPlayer
from ai_player import AIPlayer
from ui_game import UIGame
from table_generator import gaussian_table

from ai_player import AIPlayer

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--p1', default='player 1')
    parser.add_argument('--p2', default='player 2')
    args = parser.parse_args()

    player1 = AIPlayer()
    player1.name = args.p1
    player2 = HumanPlayer()
    player2.name = args.p2

    game = UIGame(player1, player2)
Exemplo n.º 14
0
class TestAIPlayer(unittest.TestCase):
    def setUp(self):
        self.player = AIPlayer('Player1')
        self.player2 = AIPlayer('Player2')
        self.player3 = AIPlayer('Player3')
        self.player4 = AIPlayer('Player4')
        self.jack_spades = Card('Spades', 'J', 12)
        self.five_spades = Card('Spades', '5', 5)
        self.ten_clubs = Card('Clubs', '10', 10)
        self.ace_spades = Card('Spades', 'A', 15)
        self.ace_diamonds = Card('Diamonds', 'A', 15)
        self.ace_clubs = Card('Clubs', 'A', 15)
        self.queen_hearts = Card('Hearts', 'Q', 13)
        self.five_hearts = Card('Hearts', '5', 5)
        self.six_hearts = Card('Hearts', '6', 6)
        self.player._cards.extend([
            self.jack_spades, self.five_spades, self.ten_clubs, self.ace_spades
        ])

    def test_card_by_suite(self):
        by_suite = self.player.cards_by_suite('Spades')
        self.assertEqual(by_suite,
                         [self.ace_spades, self.jack_spades, self.five_spades])

    def test_higher_cards_than(self):
        suite = 'Spades'
        value = 7
        higher_cards = self.player.higher_cards_than(suite, value)
        self.assertEqual(higher_cards, [self.ace_spades, self.jack_spades])

    def test_lower_cards_than(self):
        suite = 'Spades'
        value = 13
        lower_cards = self.player.lower_cards_than(suite, value)
        self.assertEqual(lower_cards, [self.jack_spades, self.five_spades])

    def test_points_from_aces(self):
        self.player._cards.extend([self.ace_clubs, self.ace_diamonds])
        points = self.player.points_from_aces()
        self.assertEqual(points, 3)

    def test_is_covered(self):
        self.player._cards.extend(
            [self.queen_hearts, self.five_hearts, self.six_hearts])
        self.assertTrue(self.player.is_covered(self.queen_hearts))

    def test_is_covered_negative(self):
        self.assertFalse(self.player.is_covered(self.jack_spades))

    def test_points_from_covered_cards(self):
        self.player._cards.extend([
            self.ace_diamonds, self.ace_clubs, self.queen_hearts,
            self.five_hearts, self.six_hearts
        ])
        self.assertEqual(self.player.points_from_covered_cards(), 1)

    def test_points_from_low_trumps(self):
        turn = 4
        trump = 'Spades'
        self.assertIn(self.player.points_from_low_trumps(turn, trump), [0, 1])

    def test_has_conflict(self):
        turn = 5
        predictions = {}
        predictions[self.player2] = 2
        predictions[self.player3] = 0
        predictions[self.player4] = 3
        self.assertTrue(self.player.has_conflict(turn, predictions))

    def test_resolved_conflict(self):
        hands = 1
        self.assertIn(self.player.resolved_conflict(hands), [0, 2])

    def test_choose_the_best_high(self):
        self.assertEqual(self.player.choose_the_best(True), self.ace_spades)

    def test_choose_the_best_low(self):
        self.assertEqual(self.player.choose_the_best(False), self.five_spades)

    def test_choose_from_others(self):
        self.assertEqual(
            self.player.choose_from_others(self.ace_diamonds, 'Spades'),
            self.ten_clubs)

    def test_choose_highest_under(self):
        queen_spades = Card('Spades', 'Q', 13)
        self.assertEqual(
            self.player.choose_highest_under(queen_spades, 'Spades'),
            self.jack_spades)

    def test_no_more_hands(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.assertEqual(self.player.no_more_hands(cards_on_table, trump),
                         self.jack_spades)

    def test_try_to_get_with_others(self):
        self.assertEqual(
            self.player.try_to_get_with_others(self.ace_diamonds, 'Hearts'),
            self.five_spades)

    def test_try_to_get(self):
        queen_spades = Card('Spades', 'Q', 13)
        self.assertEqual(self.player.try_to_get(queen_spades, 'Spades'),
                         self.ace_spades)

    def test_need_more_hands_first(self):
        cards_on_table = OrderedDict({})
        trump = 'Clubs'
        self.assertEqual(self.player.need_more_hands(cards_on_table, trump),
                         self.ace_spades)

    def test_need_more_hands_not_first(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.assertEqual(self.player.need_more_hands(cards_on_table, trump),
                         self.ace_spades)

    def test_give_card(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.player._prediction = 4
        self.player._hands = 3
        self.assertEqual(
            self.player.give_card(cards_on_table, trump, 4, None, None),
            self.ace_spades)
Exemplo n.º 15
0
def main():
    selected_game_mode = -1
    while (selected_game_mode < 0 or selected_game_mode > 3):
        print('Select game mode:')
        print('1. Normal chess')
        print('2. Reverse chess (suicide mode)')
        selected_game_mode = int(input('Selection: '))
        print('')

    selected_scenario = -1
    while (selected_scenario < 0 or selected_scenario > 7):
        print('Select game scenario:')
        print('1. Train AI')
        print('2. Watch trained AI vs trained AI')
        print('3. Watch trained AI vs normal AI')
        print('4. Watch normal AI vs normal AI')
        print('5. Play against trained AI')
        print('6. Play against normal AI')
        selected_scenario = int(input('Selection: '))

    # Select playing color if human vs ai
    selected_color = -1
    if (selected_scenario > 4 and selected_scenario <= 6):
        while (selected_color < 0 or selected_color > 3):
            print('Select Color:')
            print('1. White')
            print('2. Black')
            selected_color = int(input('Selection: '))

    game_variant = None
    if (selected_game_mode == 1):
        game_variant = 'chess'
    elif (selected_game_mode == 2):
        game_variant = 'suicide'
    else:
        raise Exception('Invalid game mode!')

    # Load train data if a scenario including 'trained AI' is selected
    # train_data = np.load('train_file.npy')

    # [1. Train AI]
    if (selected_scenario == 1):
        # todoooooooooooooooooooooooooo------------------------------------------
        pass
    else:
        white_player = None
        black_player = None
        # [2. Watch trained AI vs trained AI]
        if (selected_scenario == 2):
            white_player = AIPlayer(is_white=True,
                                    depth=3,
                                    piece_square_table=None)
            black_player = AIPlayer(is_white=False,
                                    depth=3,
                                    piece_square_table=None)
        # [3. Watch trained AI vs normal AI]
        elif (selected_scenario == 3):
            white_player = AIPlayer(is_white=True,
                                    depth=3,
                                    piece_square_table=None)
            black_player = AIPlayer(is_white=False,
                                    depth=3,
                                    piece_square_table=None)
        # [4. Watch normal AI vs normal AI]
        elif (selected_scenario == 4):
            white_player = AIPlayer(is_white=True,
                                    depth=3,
                                    piece_square_table=None)
            black_player = AIPlayer(is_white=False,
                                    depth=3,
                                    piece_square_table=None)
        # [5. Play against trained AI]
        elif (selected_scenario == 5):
            # [1. White]
            if (selected_color == 1):
                white_player = HumanPlayer(is_white=True)
                black_player = AIPlayer(is_white=False,
                                        depth=3,
                                        piece_square_table=None)
            # [2. Black]
            elif (selected_color == 2):
                white_player = AIPlayer(is_white=True,
                                        depth=3,
                                        piece_square_table=None)
                black_player = HumanPlayer(is_white=False)
            else:
                raise Exception('Invalid color!')
        # [6. Play against normal AI]
        elif (selected_scenario == 6):
            # [1. White]
            if (selected_color == 1):
                white_player = HumanPlayer(is_white=True)
                black_player = AIPlayer(is_white=False,
                                        depth=3,
                                        piece_square_table=None)
            # [2. Black]
            elif (selected_color == 2):
                white_player = AIPlayer(is_white=True,
                                        depth=3,
                                        piece_square_table=None)
                black_player = HumanPlayer(is_white=False)
            else:
                raise Exception('Invalid color!')
        else:
            raise Exception('Invalid scenario!')

        chess_game = ChessGame(white_player=white_player,
                               black_player=black_player,
                               variant=game_variant,
                               max_turn=None)

        gameover = False
        result = None
        while (not gameover):
            gameover, result = chess_game.play_half_turn()
        print(gameover)
        print(result)
from __future__ import print_function
from human_player import HumanPlayer
from ai_player import AIPlayer
from game import Game


board = [
    ['.', '.', '.'],
    ['.', '.', '.'],
    ['.', '.', '.']
]

game = Game(HumanPlayer('X'), AIPlayer('O'))


def _is_all_the_same(board, i1, i2, i3, val):
    if (board[i1[0]][i1[1]] == board[i2[0]][i2[1]] and
            board[i1[0]][i1[1]] == board[i3[0]][i3[1]] and
            board[i1[0]][i1[1]] == val
            ):
        return True
    else:
        return False


def get_winner(board):
    for player in ['X', 'O']:
        # rows
        if _is_all_the_same(board, (0, 0), (0, 1), (0, 2), player):
            return player
        if _is_all_the_same(board, (1, 0), (1, 1), (1, 2), player):
Exemplo n.º 17
0
 def __init__(self):
     AIPlayer.__init__(self, 'A-Star', 0)
Exemplo n.º 18
0
 def __init__(self):
     AIPlayer.__init__(self, 'Breadth First Search', 0)
     self.nodes_expanded_ = 0
Exemplo n.º 19
0
import time
from tictactoe import TicTacToe
from player import Player
from ai_player import AIPlayer

p1 = Player()
p2 = AIPlayer()

# Train with 10000 games against itself.
print('Learning...')
t = time.time()
for _ in range(10000):
    game = TicTacToe(p2, p2)
    game.start()
print('Learned {} unique states from {:.0f} games in {:.2f} seconds'.format(
    len(p2.states['x']) + len(p2.states['o']),
    p2.games_played() / 2,
    time.time() - t))

# Only perform best moves.
p2.epsilon = 0

# Play against human player.
while True:
    game = TicTacToe(p1, p2)
    game.start()
Exemplo n.º 20
0
import argparse

from game import Game
from player import HumanPlayer, RandomPlayer
from ai_player import AIPlayer


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--p1', default='player 1')
    parser.add_argument('--p2', default='player 2')
    parser.add_argument('--rows', default='6', type=int)
    parser.add_argument('--cols', default='7', type=int)
    parser.add_argument('--num', default='4', type=int)
    args = parser.parse_args()

    player1 = HumanPlayer(args.p1)
    player2 = AIPlayer(args.p2)
    game = Game(player1, player2, args.cols, args.rows, args.num, verbose=True)
    game.run()
 def __init__(self):
     AIPlayer.__init__(self, 'Depth First Search', 0)
Exemplo n.º 22
0
 def setUp(self) -> None:
     self.b = Board()
     self.p = AIPlayer(self.b)
Exemplo n.º 23
0
        if winner is not None and diff > -1:
            result = {0: 'black_win', 1: 'white_win', 2: 'draw'}[winner]

            # return result,diff
        return winner

    def game_over(self):
        """
        判断游戏是否结束
        :return: True/False 游戏结束/游戏没有结束
        """

        # 根据当前棋盘,判断棋局是否终止
        # 如果当前选手没有合法下棋的位子,则切换选手;如果另外一个选手也没有合法的下棋位置,则比赛停止。
        b_list = list(self.board.get_legal_actions('X'))
        w_list = list(self.board.get_legal_actions('O'))

        is_over = len(b_list) == 0 and len(w_list) == 0  # 返回值 True/False

        return is_over


#
#
if __name__ == '__main__':
    from ai_player import AIPlayer
    x = AIPlayer("X")
    o = AIPlayer("O")
    game = Game(x, o)
    game.run()
Exemplo n.º 24
0
    parser.add_argument('--p1', default='player 1')
    parser.add_argument('--p2', default='player 2')
    parser.add_argument('--rows', default='6', type=int)
    parser.add_argument('--cols', default='7', type=int)
    parser.add_argument('--num', default='4', type=int)
    args = parser.parse_args()

    dicc = {}
    best_tab = [[1, 2, 3, 3, 2, 1], [3, 4, 5, 5, 4, 3], [7, 9, 11, 11, 9, 7],
                [9, 10, 13, 13, 10, 9], [7, 9, 11, 11, 9, 7],
                [3, 4, 5, 5, 4, 3], [1, 2, 3, 3, 2, 1]]
    nb_players = 5

    with open("fights.txt", "a") as log:

        player = AIPlayer(best_tab)
        player.name = "champion"
        dicc[player.name] = {"victoires": 0, "player": player}

        log.write("\nPlayer : " + player.name)
        log.write("\n" + str(best_tab))

        for players in range(nb_players):
            tab = generate_table()

            player = AIPlayer(tab)
            player.name = "player" + str(players)
            dicc[player.name] = {"victoires": 0, "player": player}

            log.write("\n\nPlayer : " + player.name)
            log.write("\n" + str(tab))
Exemplo n.º 25
0
class TestAIPlayer(unittest.TestCase):
    def setUp(self):
        self.player = AIPlayer('Player1')
        self.player2 = AIPlayer('Player2')
        self.player3 = AIPlayer('Player3')
        self.player4 = AIPlayer('Player4')
        self.jack_spades = Card('Spades', 'J', 12)
        self.five_spades = Card('Spades', '5', 5)
        self.ten_clubs = Card('Clubs', '10', 10)
        self.ace_spades = Card('Spades', 'A', 15)
        self.ace_diamonds = Card('Diamonds', 'A', 15)
        self.ace_clubs = Card('Clubs', 'A', 15)
        self.queen_hearts = Card('Hearts', 'Q', 13)
        self.five_hearts = Card('Hearts', '5', 5)
        self.six_hearts = Card('Hearts', '6', 6)
        self.player._cards.extend([self.jack_spades, self.five_spades,
                                   self.ten_clubs, self.ace_spades])

    def test_card_by_suite(self):
        by_suite = self.player.cards_by_suite('Spades')
        self.assertEqual(by_suite, [self.ace_spades, self.jack_spades,
                                    self.five_spades])

    def test_higher_cards_than(self):
        suite = 'Spades'
        value = 7
        higher_cards = self.player.higher_cards_than(suite, value)
        self.assertEqual(higher_cards, [self.ace_spades, self.jack_spades])

    def test_lower_cards_than(self):
        suite = 'Spades'
        value = 13
        lower_cards = self.player.lower_cards_than(suite, value)
        self.assertEqual(lower_cards, [self.jack_spades, self.five_spades])

    def test_points_from_aces(self):
        self.player._cards.extend([self.ace_clubs, self.ace_diamonds])
        points = self.player.points_from_aces()
        self.assertEqual(points, 3)

    def test_is_covered(self):
        self.player._cards.extend([self.queen_hearts, self.five_hearts,
                                   self.six_hearts])
        self.assertTrue(self.player.is_covered(self.queen_hearts))

    def test_is_covered_negative(self):
        self.assertFalse(self.player.is_covered(self.jack_spades))

    def test_points_from_covered_cards(self):
        self.player._cards.extend([self.ace_diamonds, self.ace_clubs,
                                   self.queen_hearts, self.five_hearts,
                                   self.six_hearts])
        self.assertEqual(self.player.points_from_covered_cards(), 1)

    def test_points_from_low_trumps(self):
        turn = 4
        trump = 'Spades'
        self.assertIn(self.player.points_from_low_trumps(turn, trump), [0, 1])

    def test_has_conflict(self):
        turn = 5
        predictions = {}
        predictions[self.player2] = 2
        predictions[self.player3] = 0
        predictions[self.player4] = 3
        self.assertTrue(self.player.has_conflict(turn, predictions))

    def test_resolved_conflict(self):
        hands = 1
        self.assertIn(self.player.resolved_conflict(hands), [0, 2])

    def test_choose_the_best_high(self):
        self.assertEqual(self.player.choose_the_best(True), self.ace_spades)

    def test_choose_the_best_low(self):
        self.assertEqual(self.player.choose_the_best(False), self.five_spades)

    def test_choose_from_others(self):
        self.assertEqual(self.player.choose_from_others(self.ace_diamonds,
                                                        'Spades'),
                         self.ten_clubs)

    def test_choose_highest_under(self):
        queen_spades = Card('Spades', 'Q', 13)
        self.assertEqual(self.player.choose_highest_under(queen_spades,
                                                          'Spades'),
                         self.jack_spades)

    def test_no_more_hands(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.assertEqual(self.player.no_more_hands(cards_on_table, trump),
                         self.jack_spades)

    def test_try_to_get_with_others(self):
        self.assertEqual(self.player.try_to_get_with_others(self.ace_diamonds,
                                                            'Hearts'),
                         self.five_spades)

    def test_try_to_get(self):
        queen_spades = Card('Spades', 'Q', 13)
        self.assertEqual(self.player.try_to_get(queen_spades,
                                                'Spades'),
                         self.ace_spades)

    def test_need_more_hands_first(self):
        cards_on_table = OrderedDict({})
        trump = 'Clubs'
        self.assertEqual(self.player.need_more_hands(cards_on_table, trump),
                         self.ace_spades)

    def test_need_more_hands_not_first(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.assertEqual(self.player.need_more_hands(cards_on_table, trump),
                         self.ace_spades)

    def test_give_card(self):
        cards_on_table = OrderedDict({})
        queen_spades = Card('Spades', 'Q', 13)
        trump = 'Clubs'
        cards_on_table[queen_spades] = self.player2
        cards_on_table[self.ace_diamonds] = self.player3
        cards_on_table[self.six_hearts] = self.player4
        self.player._prediction = 4
        self.player._hands = 3
        self.assertEqual(self.player.give_card(cards_on_table, trump, 4, None,
                                               None),
                         self.ace_spades)
Exemplo n.º 26
0
 def __init__(self):
     self.board = Board()
     self.players = [RandomPlayer(BLACK_PLAYER), AIPlayer(WHITE_PLAYER)]
     self.current_player = 0
Exemplo n.º 27
0
import argparse

from game import Game
from player import HumanPlayer, RandomPlayer
from ai_player import AIPlayer
from venus import AIPlayer as VenusAI

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--p1", default="player 1")
    parser.add_argument("--p2", default="player 2")
    parser.add_argument("--rows", default="6", type=int)
    parser.add_argument("--cols", default="7", type=int)
    parser.add_argument("--num", default="4", type=int)
    args = parser.parse_args()

    player1 = RandomPlayer()
    player1.name = args.p1
    player2 = AIPlayer()
    player2.name = args.p2
    game = Game(player1, player2, args.cols, args.rows, args.num, verbose=True)
    game.run()
Exemplo n.º 28
0
# Local imports
from ai_player import AIPlayer
from beck.beck_display import BeckDisplay
from beck.beck_game import BeckGame
from beck.beck_model import RandomBeckModel, NnetBeckModel
from beck.config import MCTS_ARGS, NNET_ARGS
from mcts import MCTS
from stage import Stage

import time

game = BeckGame(m=4, n=9, k=4)

start_time = time.time()
model1, model2 = NnetBeckModel(game, NNET_ARGS), NnetBeckModel(game, NNET_ARGS)
# model1, model2 = RandomBeckModel(game), RandomBeckModel(game)
trials = 100
for _ in range(trials):
    mcts1, mcts2 = MCTS(game, model1, MCTS_ARGS), MCTS(game, model1, MCTS_ARGS)
    players = [AIPlayer(mcts1, True), AIPlayer(mcts2, True)]

    #display = BeckDisplay(game, ['Rebecca', 'Rebecca'])
    stage = Stage(players, game, None)

    stage.execute()

print('Time: ', (time.time() - start_time) / trials)

import time
time.sleep(5)
Exemplo n.º 29
0
import numpy as np
from tictactoe import TicTacToe
from ai_player import AIPlayer
from softmax_player import SoftmaxPlayer

p1 = AIPlayer()
p2 = SoftmaxPlayer()

# Train e-greedy player against itself.
for _ in range(2000):
    game = TicTacToe(p1, p1)
    game.start()

# Train softmax player against itself.
for _ in range(2000):
    game = TicTacToe(p2, p2)
    game.start()

# Set parameters so that optimal moves are preferred.
p1.epsilon = 0
p2.theta = 1

# Remove stats from training matches.
p1.draws = 0
p1.wins = 0
p1.losses = 0
p2.draws = 0
p2.wins = 0
p2.losses = 0

# E-greedy vs softmax.
Exemplo n.º 30
0
def GPlayer(sigma, mu):
  return AIPlayer(gaussian_table(sigma, mu))