Exemplo n.º 1
0
def main():
    x = 0
    game = Tictactoe()
    while True:
        for i in [1, 4, 7]:
            print(game.myfunc(i))
        while True:
            choice = input(
                "Player {} Enter your move(1-9):".format(x + 1)).strip()
            try:
                choice = int(choice)
            except:
                print("Invalid Number!")
                choice = -1
            if 1 <= choice <= 9:
                break
            else:
                print('Please enter valid input between 1 - 9')
        if game.board[choice - 1] == ' ':
            if x == 0:
                game.board[choice - 1] = 'X'
                if game.isVictory('X'):
                    print('\n Player {} is the winner!'.format(x + 1))
                    break
                x = 1
            else:
                game.board[choice - 1] = 'Y'
                if game.isVictory('Y'):
                    print('\n Player {} is the winner!'.format(x + 1))
                    break
                x = 0
        else:
            print("\n Space is taken!")
Exemplo n.º 2
0
def generate_data():

    possibilities = get_possibilities()
    train = open("NeuralNetwork/train.data", "w")
    test = open("NeuralNetwork/test.data", "w")

    train.write(str(len(possibilities) / 2) + " 9 1\n")

    def nnWrite(file, board, sol):
        file.write(board + "\n" + str(sol) + "\n")

    def getBoardAsString(possibilitie):
        res = ""
        for tab in possibilitie[0]:
            for i in tab:
                res = res + str(i) + " "
        return res

    for i in range(len(possibilities)):
        possibilitie = possibilities[i]
        t = Tictactoe(data=possibilitie)
        ia = IA(t, (t.turn % 2) + 1)
        ia.minimax(ia.game, 0)
        res = ia.choice

        if i < len(possibilities) / 2:
            nnWrite(train, getBoardAsString(possibilitie), res)
        else:
            nnWrite(test, getBoardAsString(possibilitie), res)
Exemplo n.º 3
0
def get_possibilities():

    t = Tictactoe()
    res = []

    def convertPos(x):
        if x < 3:
            return [0, x]
        else:
            return [(x // 3), (x % 3)]

    def possibilities(game):
        if game.testWin() == 0:
            for move in game.getMoves():
                possibilities(game.getNewState(convertPos(move)))
            res.append(game.export())
        return

    possibilities(t)
    return res
Exemplo n.º 4
0
 def test_stopped(self):
     o = 1
     x = 2
     grid = [[x, o, o], [o, x, x], [x, x, o]]
     self.assertEqual("Always", Tictactoe().getStatus(grid))
Exemplo n.º 5
0
 def test_win_colum3(self):
     o = 1
     x = 2
     grid = [[x, 0, o], [o, x, o], [x, o, o]]
     self.assertEqual("O is Winner!", Tictactoe().getStatus(grid))
Exemplo n.º 6
0
 def test_playing(self):
     o = 1
     x = 2
     grid = [[0, 0, 0], [0, 0, 0], [x, 0, 0]]
     self.assertEqual("Runing", Tictactoe().getStatus(grid))
Exemplo n.º 7
0
 def test_win_colum2(self):
     o = 1
     x = 2
     grid = [[o, x, o], [0, x, 0], [o, x, o]]
     self.assertEqual("X is Winner!", Tictactoe().getStatus(grid))
Exemplo n.º 8
0
 def test_win_slash(self):
     o = 1
     x = 2
     grid = [[o, 0, x], [o, x, 0], [x, o, o]]
     self.assertEqual("X is Winner!", Tictactoe().getStatus(grid))
Exemplo n.º 9
0
 def test_win_row3(self):
     o = 1
     x = 2
     grid = [[o, 0, o], [o, 0, 0], [x, x, x]]
     self.assertEqual("X is Winner!", Tictactoe().getStatus(grid))
Exemplo n.º 10
0
 def test_win_row1(self):
     o = 1
     x = 2
     grid = [[o, o, o], [x, 0, x], [x, 0, 0]]
     self.assertEqual("O is Winner!", Tictactoe().getStatus(grid))
Exemplo n.º 11
0
 def __init__(self):
     self.client = socket(AF_INET, SOCK_STREAM)
     self.host = gethostname()
     self.port = 5000
     self.tic = Tictactoe()
     self.player = None
Exemplo n.º 12
0
from tictactoe import Tictactoe
board = Tictactoe()
print("\t\tGIVE THE FOLLOWING DETAILS\n")
count = 0
player1 = (raw_input("\t\tFIRST PLAYER   :  "))
player2 = (raw_input("\t\tSECOND PLAYER  :  "))
while (1):
    if (board.isfull()):
        print "\t\tNO MORE MOVE ALLOWED SPACE IS FULL"
        print "\n\t\t\t\tMATCH DRAWN !!!!!"
        break
    count = count % 2
    print "\n\n"
    if (count == 0):
        print("\t\t %s YOUR TURN") % player1
    if (count == 1):
        print("\t\t %s YOUR TURN") % player2
    row = int(raw_input("\t\t ROW     :  "))
    column = int(raw_input("\t\t COLUMN  :  "))
    board.move(row, column, count)
    board.display()
    a = board.result()
    if (a == 1):
        print("\t\t\t\tWINNER   %s  !!!!!!!!!") % player1
        break
    if (a == 2):
        print("\t\t\t\tWINNER   %s  !!!!!!!!!") % player2
        break
    if (a == 0):
        count += 1
        continue
Exemplo n.º 13
0
 def __init__(self, n_rom):
     self.tic = Tictactoe()
     self.nrom = n_rom
     self.player_1 = None
     self.player_2 = None
     self.turn = 'X'
Exemplo n.º 14
0
def play(args):
    """
    Arguments:
    ----------
    - `args' : List of arguments

    Returns, from a new game parametrized with `args` :
        - Number of moves for each player
        - Total execution time for each player
        - The final state of the game
    """
    if len(args) < 6:
        help()
        return -1

    try:
        n = int(args[1])
    except BaseException:
        help()
        return -1
    try:
        m = int(args[2])
    except BaseException:
        help()
        return -1

    try:
        k = int(args[3])
    except BaseException:
        help()
        return -1

    try:
        p1 = args[4]
        if p1[0] != "h":
            name = p1.split("_")[1]
            p1 = extractAgent(name, 1, k, TIMEOUT)
        else:
            p1 = Human(1, k)
    except BaseException:
        help()
        return -1

    try:
        p2 = args[5]
        if p2[0] != "h":
            name = p2.split("_")[1]
            p2 = extractAgent(name, 2, k, TIMEOUT)
        else:
            p2 = Human(2, k)
    except BaseException:
        help()
        return -1
    env = Tictactoe(n, m, k)
    p = [p1, p2]
    t = [0, 0]
    nact = [0, 0]
    while not env.terminalState():
        _, currentPlayer, _, _ = env.currentState()
        tX, act = f_with_timeout(p[currentPlayer - 1].move, deepcopy(env))
        if act is not None:
            i, j = act
            env.step((currentPlayer, i, j))
        else:
            lst = np.argwhere(env.M == 0)
            move = tuple(lst[np.random.randint(lst.shape[0])])
            env.step((currentPlayer, move[0], move[1]))
        t[currentPlayer - 1] += tX
        nact[currentPlayer - 1] += 1
    return (nact, t, env)
Exemplo n.º 15
0
            if event.type == pygame.MOUSEBUTTONDOWN:
                point = event.pos
                b_ = False

                # Play as X or O
                if playXButton.collidepoint(point):
                    ai_turn = False
                    b_ = True
                elif playOButton.collidepoint(point):
                    ai_turn = True
                    b_ = True

                # Start Play state
                if b_:
                    gamestate = PLAY_STATE
                    ttt = Tictactoe()
                    time.sleep(0.1)
        # Play state
        elif gamestate == PLAY_STATE:

            # Mouse click
            if event.type == pygame.MOUSEBUTTONDOWN:
                point = event.pos

                # If user's trun
                if not ai_turn:

                    # If game is not over
                    if not ttt.gameover():
                        # Cells
                        b_ = True
Exemplo n.º 16
0
    def train(self, num_games):
        """
        Trains the agent by playing games against itself

        Args:
            num_games (int): number of games to train
        """

        # Play num_games games
        for n in range(num_games):

            # Print game number
            if n % 1000 == 0:
                print(f'Game #{n + 1}')

            # Initialize the game
            ttt = Tictactoe()

            # Keep track of last state and actions
            last = {
                'X': {
                    'state': None,
                    'action': None
                },
                'O': {
                    'state': None,
                    'action': None
                }
            }

            # Play the game
            while True:

                # Get the state and action
                state = ttt.get_board()
                action = self.best_action(state, epsilon_true=True)

                # Save as lasts
                last[ttt.get_player()]['state'] = state
                last[ttt.get_player()]['action'] = action

                # Apply action and get the new state
                ttt.action(action)
                new_state = ttt.get_board()

                # Game over
                if ttt.gameover():

                    # Won the game
                    if ttt.get_winner() is not None:

                        # Update q value for winner
                        self.update_q_value(state, action, new_state, 1)

                        # Update q value for loser
                        self.update_q_value(last[ttt.get_player()]['state'],
                                            last[ttt.get_player()]['action'],
                                            new_state, -1)

                    # Draw
                    else:
                        # Update q value
                        self.update_q_value(state, action, new_state, 0)

                    break

                # Game continues
                elif last[ttt.get_player()]['state'] is not None:

                    # Update last action
                    self.update_q_value(last[ttt.get_player()]['state'],
                                        last[ttt.get_player()]['action'],
                                        new_state, 0)

        print('Training done')