Example #1
0
def main():
    """ create an instance of TicTacToe class"""
    t = TicTacToe()
        
    #get the value of whose turn it is X or O
    board_state = random.choice([t.STATES.NAUGHT_TURN, t.STATES.CROSS_TURN])

    """ use a while loop to intrectively play TicTacToe and save the board state
        run loop until someone wins or its draw
        get the valid user input for location in form of row,col
        call place_marker funtion on user input and print the updated board state 
    """
    while board_state != t.STATES.NAUGHT_WON and board_state != t.STATES.CROSS_WON and board_state != t.STATES.DRAW:
        print(board_state)
        val = input('Enter location in format row,column:').split(',')
        turn = 'x' if (board_state == t.STATES.CROSS_TURN) else 'o'
        row = int(val[0]) 
        col = int(val[1])

        if row not in range(0,3) or col not in range(0,3) or t.board[row][col] != ' ':
            print('Please enter valid location in format row,column')
            continue
    
        board_state = t.place_marker(turn,row,col) 
        print(t.board[0])
        print(t.board[1])
        print(t.board[2])
    print(board_state)
Example #2
0
    def onObjectTalked(self, obj, phrase):
        "Callback when an object in the room has been kicked"

        used = False

        if obj != None and obj.getName() == "Wizard" and obj.getState(
        ) == AdventureGameObjectWizard.State.readyForGame:
            ttt = TicTacToe()
            winner = ttt.start()

            if winner == 1:
                print("\nCongratulations, you won!")
                print(
                    "Take this magic sword, it will pierce anything, even a troll!"
                )
                print("Good bye now!")
                print("\nThe wizard teleports away.")
                self.gameHandler.inventory.add(AdventureGameObjectMagicSword())
                self.removeObject("Wizard")
            elif winner == 2:
                print("\nThe wizard wins")
                print(
                    "Just talk to me if you want to try again, I got all the time in the world."
                )
            else:
                print("\nIt's a tie!")
                print(
                    "Just talk to me if you want to try again, I got all the time in the world."
                )

            used = True

        return used
Example #3
0
def play_x(board: TicTacToe) -> int:
    """
    Plays the game until a player wins based on the win function
    :return: The player that won
    :rtype: int
    """
    while not board.winner and not board.cats:
        board.make_move(position=get_move(board))
        print(f"Player: {board.get_symbol(board.turn % board.players + 2)}")
        print(board.print_board())
        try:
            move = map(
                lambda x: int(x),
                input(">> ").replace("(", "").replace(")", "").split(","))
        except (TypeError, ValueError):
            print("Please use numbers in the form (x,y)")
        else:
            if len(list(move)) != 2:
                print("Please make a move in the form (x,y)")
            else:
                valid = board.make_move(position=(next(move), next(move)))
                print("")
    print(
        f"Player {board.get_symbol(player=(board.turn - 1) % board.players + 1)} wins!!"
    )
    print(board.print_board())
    return (board.turn - 1) % board.players + 1 if not board.cats else 0
Example #4
0
class GameManager_GUI:
    def __init__(self):
        self.ttt = TicTacToe()
        CANVAS_SIZE = 300
        self.TILE_SIZE = CANVAS_SIZE / 3

        self.root = tkinter.Tk()
        self.root.title("틱택토") # setTitle이 아닌, 그냥 title
        self.root.geometry(str(CANVAS_SIZE) + "x" + str(CANVAS_SIZE)) # "300x300"
        self.root.resizable(width=False, height=False) # 창크기 변경 x
        self.canvas = tkinter.Canvas(self.root, bg="white", width=CANVAS_SIZE, height=CANVAS_SIZE)
        self.canvas.pack()

        self.images = dict()
        self.images["O"] = tkinter.PhotoImage(file="img/O.gif")
        self.images["X"] = tkinter.PhotoImage(file="img/X.gif")

        self.canvas.bind("<Button-1>", self.click_handler)

    def click_handler(self, event):
        row = int(event.y // self.TILE_SIZE) # 교과서 : math.floor(event.y / self.TILE_SIZE)
        col = int(event.x // self.TILE_SIZE)
        self.ttt.set(row, col)
        # print(self.ttt)

        # draw_board()
        self.draw_board()

        #check_winner()
        if self.ttt.check_winner() == "O":
            messagebox.showinfo("게임오버", "O win !")
            self.root.quit()
        elif self.ttt.check_winner() == "X":
            messagebox.showinfo("게임오버", "X win !")
            self.root.quit()
        elif self.ttt.check_winner() == "d":
            messagebox.showinfo("게임오버", "무승부")
            self.root.quit()

    def draw_board(self):
        # clear
        self.canvas.delete("all")

        x = 0
        y = 0

        for i, v in enumerate(self.ttt.board):
            if v == ".":
                pass
            elif v == "O":
                self.canvas.create_image(x, y, anchor="nw", image=self.images["O"])
            elif v == "X":
                self.canvas.create_image(x, y, anchor="nw", image=self.images["X"])
            x += self.TILE_SIZE
            if i % 3 == 2:
                x = 0
                y += self.TILE_SIZE

    def play(self):
        self.root.mainloop()
Example #5
0
 def test_result_should_return_dot_if_no_winner(self):
     game = TicTacToe([
         'XO.',
         '.Ox',
         '.X.',
     ])
     self.assertEqual('.', game.result())
Example #6
0
 def test_result_should_return_winner_if_row_is_complete(self):
     game = TicTacToe([
         'XXX',
         '.Ox',
         '.X.',
     ])
     self.assertEqual('X', game.result())
Example #7
0
def test_1():
    # random vs random

    O_win = 0
    X_win = 0
    draw = 0

    for i in range(100):
        game = TicTacToe()

        p1 = RandomPlayer(game, 'O')
        p2 = RandomPlayer(game, 'X')

        while not game.is_finished():
            p1.make_move()
            p2.make_move()

        if game.result == 'O':
            O_win += 1
        elif game.result == 'X':
            X_win += 1
        else:
            draw += 1

    print('Random vs random:')
    print('O: ', O_win)
    print('X: ', X_win)
    print('draw: ', draw)
Example #8
0
    def make_move(self, ttt: TicTacToe):
        # explore - make a random move
        if np.random.rand() < self.epsilon:
            while True:
                coord = np.random.randint(3, size=2)
                x = coord[0]
                y = coord[1]

                if ttt.make_move(x, y, self.symbol) or ttt.game_over():
                    return

        # let the network predict the next move
        state = ttt.get_state()
        one_hot = self.one_hot_encoded(state, ttt)
        values = self.model.predict(np.asarray([one_hot]))[0]

        high = -1000  # value of field
        field = -1  # index of field

        for i in range(len(state)):  # select best move
            if state[i] == 0:
                if values[i] > high:
                    high = values[i].copy()
                    field = i

        x = field % 3
        y = field // 3
        if ttt.make_move(x, y, self.symbol):
            return
        else:
            raise Exception("dafuq?")
Example #9
0
def test_3():
    # full minimax vs full minimax

    O_win = 0
    X_win = 0
    draw = 0

    states_tree = minimax_full(State())

    for i in range(100):
        game = TicTacToe()

        p1 = FullPlayer(game, 'O', states_tree)
        p2 = FullPlayer(game, 'X', states_tree)

        while not game.is_finished():
            p1.make_move()
            p2.make_move()

        if game.result == 'O':
            O_win += 1
        elif game.result == 'X':
            X_win += 1
        else:
            draw += 1

    print('Full minimax vs Full minimax:')
    print('O: ', O_win)
    print('X: ', X_win)
    print('draw: ', draw)
Example #10
0
class TicTacToeComprehensiveTestCase(TestCase):
    def setUp(self):
        self.game = TicTacToe([
            'XOXOXO',
            'O..O.X',
            '.XXO..',
            'OOXO.O',
            'X.XO.X',
            '..XOX.',
        ])

    def test_board_should_be_correct(self):
        self.assertTrue(self.game.is_correct())

    def test_should_not_detect_complete_row(self):
        self.assertIsNone(self.game.check_rows())

    def test_should_not_detect_complete_diagonal(self):
        self.assertIsNone(self.game.check_diagonals())

    def test_should_detect_complete_column(self):
        self.assertEqual('O', self.game.check_columns())

    def test_should_return_winner_based_on_complete_column(self):
        self.assertEqual('O', self.game.result())
Example #11
0
    def test_start_game(self):
        steps_1 = step_gen(["11", "12", "22", "23", "33"])
        with patch('builtins.input', lambda :next(steps_1)),\
             patch('sys.stdout', StringIO()) as p:
            self.game.start_game()
            self.assertEqual(p.getvalue().strip()[-len("Player X won!"):],
                             "Player X won!")

        self.game = TicTacToe()

        steps_2 = step_gen(["12", "31", "33", "22", "21", "13"])
        with patch('builtins.input', lambda :next(steps_2)),\
             patch('sys.stdout', StringIO()) as p:
            self.game.start_game()
            self.assertEqual(p.getvalue().strip()[-len("Player O won!"):],
                             "Player O won!")

        self.game = TicTacToe()

        steps_3 = step_gen(
            ["11", "21", "31", "22", "12", "13", "32", "33", "23"])
        with patch('builtins.input', lambda :next(steps_3)),\
             patch('sys.stdout', StringIO()) as p:
            self.game.start_game()
            self.assertEqual(p.getvalue().strip()[-len("Draw!"):], "Draw!")
class Gamemanager:
    def __init__(self):
        self.ttt = TicTacToe()

    def play(self):
        #show_bord

        #반복하자
        while True:
            #위치를 입력 받자
            row = int(input("row: "))
            col = int(input("col: "))
            #말을 놓자
            self.ttt.set(row,col)
            print(self.ttt)
            #check_winner()
            if self.ttt.check_winner() == "o":
                print("O 승리,ㅊㅋㅊㅋ")
                break
            elif self.ttt.check_winner() == "x":
                print("x 승리,ㅊㅋㅊㅋ")
                break
            elif self.ttt.check_wiiner() == "d":
                print("무승부")
                break
Example #13
0
    def monte_carlo(self, board, depth=None):
        if depth is None:
            depth = []

        ttt = TicTacToe()
        ttt.copy(board)

        # ランダムに自分の一手を行う
        position = self.pick_one(ttt)
        ttt.set(position, self.t)

        if ttt.eval() == TicTacToe.ON_PROGRESS:
            # 敵の手もランダムに一手を行う
            t_enemy = TicTacToe.O if self.t == TicTacToe.X else TicTacToe.X
            position_enemy = self.pick_one(ttt)
            ttt.set(position_enemy, t_enemy)

        depth = depth + [position]

        # 結果を判定。決着がつかないなら再帰的に繰り返す
        result = ttt.eval()
        if result != TicTacToe.ON_PROGRESS:
            return {
                "position": depth[0],
                "game_result": result,
                "moves": depth
            }

        return self.monte_carlo(ttt.board, depth)
Example #14
0
class GameManager:
    def __init__(self):
        self.ttt = TicTacToe()

    def play(self):
        print(self.ttt)

        while True:

            row = int(input("row : "))
            col = int(input("col : "))
            self.ttt.set(row, col)
            print(self.ttt)

            if self.ttt.check_winner() == "0":
                print(" O win!!!")
                break

            elif self.ttt.chenck_winner() == "X":
                print("X win!!!")
                break

            elif self.ttt.check_winner() == "d":
                print("무승부")
                break
class TicTacToeApp(EasyFrame):
    """Displays a tictactoe board in the window."""
    def __init__(self):
        """Sets up the window and the panels."""
        EasyFrame.__init__(self, title="TicTacToe")
        self.model = TicTacToe()
        self.addButton("New Game",
                       row=3,
                       column=0,
                       columnspan=3,
                       command=self.newGame)
        color = "black"
        number = 0
        self.squares = list()
        for row in range(3):
            for column in range(3):
                square = TTTSquare(parent=self,
                                   width=50,
                                   height=50,
                                   background=color,
                                   number=number,
                                   model=self.model)
                self.addCanvas(square, row=row, column=column)
                number += 1
                if color == "black":
                    color = "white"
                else:
                    color = "black"
                self.squares.append(square)

    def newGame(self):
        """Re-starts a new Tic Tac Toe game."""
        self.model.newGame()
        for square in self.squares:
            square.clear()
 def __init__(self):
     """Sets up the window and the panels."""
     EasyFrame.__init__(self, title="TicTacToe")
     self.model = TicTacToe()
     self.addButton("New Game",
                    row=3,
                    column=0,
                    columnspan=3,
                    command=self.newGame)
     color = "black"
     number = 0
     self.squares = list()
     for row in range(3):
         for column in range(3):
             square = TTTSquare(parent=self,
                                width=50,
                                height=50,
                                background=color,
                                number=number,
                                model=self.model)
             self.addCanvas(square, row=row, column=column)
             number += 1
             if color == "black":
                 color = "white"
             else:
                 color = "black"
             self.squares.append(square)
Example #17
0
class GameManager:
    def __init__(self):
        self.ttt = TicTacToe()

    def play(self):
        #show board
        print(self.ttt)
        #반복하자
        while (True):
            #   위치를 입력받자
            row = int(input("row : "))
            col = int(input("col : "))
            #   말을 놓자
            self.ttt.set(row, col)
            print(self.ttt)
            #   check_winner()
            #결과 출력하자
            if self.ttt.check_winner() == "O":
                print("O 승리, ㅊㅋㅊㅋ")
                break
            elif self.ttt.check_winner() == "X":
                print("X 승리, ㅊㅋㅊㅋ")
                break
            elif self.ttt.check_winner() == "d":
                print("무승부")
                break
Example #18
0
def move():
	# Get the current state of the game
	current_state = store.lrange(session['uuid'], 0, -1)
	current_state.reverse()

	player_board = json.loads(request.args['board'])
	player = request.args['player']

	# find out if there are more than 1 differences in between the last state and this one
	if difference(current_state, player_board) > 1:
		return json.dumps({"status": "NOTVALID"}) # Prevent cheating

	ai = enemy(player)
	ttt = TicTacToe(player_board)

	# Check to see if the game is over after the player made a move
	gameover = is_gameOver(ttt)
	if gameover:
		return json.dumps({"status": "OVER", "winner": gameover})

	move = determine_move(ttt, ai)
	ttt.set_move(move, ai)

	# Set the new state in the store
	store.delete(session["uuid"])
	store.lpush(session['uuid'], *ttt.get_board())

	# check to see if the game is over after the AI made a move
	gameover = is_gameOver(ttt)
	if gameover:
		return json.dumps({"status": "MOVE", "move": str(move), "gameover": True, "winner": gameover})

	# Get the next move
	return json.dumps({"status": "MOVE", "move": str(move), "gameover": False, "winner": None})
Example #19
0
 def test_dgn_rl(self):
     """ test the dgn_rl_checker for winning and loosing conditoin  """
     t = TicTacToe()
     board: List[List[str]] = [['x', 'o', 'x'], ['o', 'x', 'x'],
                               ['o', 'x', 'x']]
     self.assertTrue(t.dgn_rl_checker(board) == (False, ))
     board = [['x', 'o', 'x'], ['o', 'x', 'x'], ['x', ' ', ' ']]
Example #20
0
def main():
    args = get_args()

    if args.mode in ('hh', 'hc') and args.quiet:
        parser.error('--quiet cannot be used with mode set either to hh or hc')

    if not args.quiet:
        print("Enter 'name,char' {0}. "
              "For example, 'John Smith,{1}'".format(CHARS, CHARS[0]))
        name1, char1 = input('Player1: ').split(',')
        name2, char2 = input('Player2: ').split(',')
    else:
        name1, char1 = 'player1', CHARS[0]
        name2, char2 = 'player2', CHARS[1]

    if args.mode == 'hh':
        player1 = HumanPlayer(name1, char1)
        player2 = HumanPlayer(name2, char2)
    elif args.mode == 'hc':
        player1 = HumanPlayer(name1, char1)
        player2 = ComputerPlayer(name2, char2)
    else:
        player1 = ComputerPlayer(name1, char1, verbose=args.verbose)
        player2 = ComputerPlayer(name2, char2, verbose=args.verbose)

    game = TicTacToe(player1, player2, verbose=not args.quiet,
                     record_states=args.record)
    game.play(args.number)
Example #21
0
def test_5():
    # random vs minimax depth = 4

    O_win = 0
    X_win = 0
    draw = 0

    for i in range(100):
        game = TicTacToe()
        p1 = RandomPlayer(game, 'O')
        p2 = MinimaxPlayer(game, 'X', 4)

        while not game.is_finished():
            p1.make_move()
            p2.make_move()

        if game.result == 'O':
            O_win += 1
        elif game.result == 'X':
            X_win += 1
        else:
            draw += 1

    print('Random (O) vs minimax depth = 4 (X):')
    print('O: ', O_win)
    print('X: ', X_win)
    print('draw: ', draw)
Example #22
0
 def test_recieve_input(self):
     player = AIPlayer()
     game = TicTacToe(player, Player())
     options = game.possible_movements()
     action = player.recieve_input(options)
     self.assertGreaterEqual(action, 0)
     self.assertLessEqual(action, len(options))
 def test_winner(self):
     game = TicTacToe()
     assert game.winner() is None
     for i in range(3):
         game.turn((0, i))
         game.turn((1, i))
     assert game.winner() is 1
Example #24
0
 def test_correct_board_should_return_true_if_board_is_square(self):
     game = TicTacToe([
         '...',
         '...',
         '...',
     ])
     self.assertTrue(game.is_correct())
class TestTicTacToe(unittest.TestCase):
    def setUp(self) -> None:
        self.game = TicTacToe()

    def test_set_current_player(self):
        self.assertIs(self.game.set_current_player(), self.game.player1)

    # @unittest.skip("WIP")
    def test_check_draw_condition(self):
        self.game.board.grid[0][0] = 'X'
        self.game.board.grid[0][1] = 'X'
        self.game.board.grid[0][2] = 'X'
        self.game.board.grid[1][0] = 'O'
        self.game.board.grid[1][1] = 'X'
        self.game.board.grid[1][2] = 'O'
        self.game.board.grid[2][0] = 'X'
        self.game.board.grid[2][1] = 'O'
        self.game.board.grid[2][2] = 'X'

        self.assertTrue(True, self.game.check_draw_condition())

    def test_switch_players_turn(self):
        self.game.switch_players_turn()
        self.assertEqual(False, self.game.player1.turn)
        self.assertEqual(True, self.game.player2.turn)
Example #26
0
class GameManager:
    def __init__(self):
        self.ttt = TicTacToe()

    def play(self):
        #게임판 보여주기
        print(self.ttt)

        while True:
            #row, col 입력받기
            row = int(input("row : "))
            col = int(input("col : "))

            self.ttt.set(row, col)
            print(self.ttt)

            #check_winner 면 끝내자
            if self.ttt.check_winner() == "o":
                print("o Win!")
                break
            elif self.ttt.check_winner() == "x":
                print("x Win!")
                break
            elif self.ttt.check_winner() == "d":
                print("무승부")
                break
Example #27
0
 def test_check_columns_should_return_none_if_column_is_incomplete(self):
     game = TicTacToe([
         'X...',
         'X...',
         'X...',
         '....',
     ])
     self.assertIsNone(game.check_columns())
Example #28
0
 def test_naught_won(self):
     """ test the place_marker for naugth_won state by filling in board """
     t = TicTacToe()
     self.assertEqual(t.place_marker('o', 2, 2), t.STATES.CROSS_TURN)
     self.assertEqual(t.place_marker('x', 0, 0), t.STATES.NAUGHT_TURN)
     self.assertEqual(t.place_marker('o', 0, 2), t.STATES.CROSS_TURN)
     self.assertEqual(t.place_marker('x', 1, 1), t.STATES.NAUGHT_TURN)
     self.assertEqual(t.place_marker('o', 1, 2), t.STATES.NAUGHT_WON)
Example #29
0
 def test_policy_to_tensor(self):
     board = TicTacToe()
     policy = [((1, 1), 0.1), ((0, 2), 0.9)]
     expected = np.zeros((3, 3, 1))
     expected[1, 1, 0] = 0.1
     expected[0, 2, 0] = 0.9
     self.assertTrue(
         np.isclose(board.policy_to_tensor(policy), expected).all())
Example #30
0
 def test_evaluate_winner_row(self):
     player1 = Player()
     game = TicTacToe(player1, Player())
     game.player_in_turn = 0
     game.board.set_cell(0, 0, "x")
     game.board.set_cell(0, 1, "x")
     game.board.set_cell(0, 2, "x")
     self.assertEqual(player1, game.evaluate_winner())
Example #31
0
 def test_check_rows_should_return_none_if_row_is_incomplete(self):
     game = TicTacToe([
         'XXX.',
         'X...',
         '.OOO',
         '....',
     ])
     self.assertIsNone(game.check_rows())
Example #32
0
File: ai.py Project: xmye/games
 def test_ai_vs_ai(self):
     o, x = DepthFirstSearchAI('O'), DepthFirstSearchAI('X')
     tictactoe = TicTacToe(o, x)
     while True:
         score = tictactoe.round()
         if score is not None:
             break
     self.assertEqual(score, 0, "AI vs AI game must always end up in a tie:\n" + str(tictactoe))
Example #33
0
 def test_ai_vs_ai(self):
     o, x = DepthFirstSearchAI('O'), DepthFirstSearchAI('X')
     tictactoe = TicTacToe(o, x)
     while True:
         score = tictactoe.round()
         if score is not None:
             break
     self.assertEqual(score, 0, "AI vs AI game must always end up in a tie:\n" + str(tictactoe))
Example #34
0
def payment(state):
    game = TicTacToe(state.grid)
    if game.is_finished():
        if game.result == 'O':
            return 1
        if game.result == 'X':
            return -1
    return 0
Example #35
0
 def simulate(moves, human_first):
     T = TicTacToe()
     for move in moves:
         self.ri.return_value = str(move)
         moves = [T.human_move, T.computer_move]
         for i in range(2):
             moves[(i + human_first) % 2]()
             winner = T.tic_tac_toe(T.board)
             if winner:
                 return winner == T.computer or winner == "cat"
     return True
Example #36
0
    def post(self): # should run at most 1/s
        try:
       	    tie_counter = 0;
       	    Message = "%s%s" % ("Round Start: ", self.request.get('tournament_entries'))
            print >>sys.stderr, Message
            #log = TournamentLog(message = Message)
            #log.put()
            
            round_entries = []
            print >>sys.stderr, "Round Entries Created"
            round_winners = []
            print >>sys.stderr, "Round Winners Created"
            round_entries = json.loads(self.request.get('tournament_entries'))
            print >>sys.stderr, "Round Entries Loaded"
            while len(round_entries) >= 2:
                player1 = round_entries.pop()
                print >>sys.stderr,"Pop"
                player2 = round_entries.pop()
                print >>sys.stderr,"Pop"
                p1_AI = getUserRuleDict(player1, 'tictactoe')
                p2_AI = getUserRuleDict(player2, 'tictactoe')
                print >>sys.stderr,"AIs Loaded"
                result = TicTacToe.runMatch(player1,player2,player1,p1_AI,p2_AI)
                while result["winner"] == "Tie Game" and tie_counter < 20:
                    result = TicTacToe.runMatch(player1,player2,player1,p1_AI,p2_AI)
                    print >>sys.stderr, "Tie"
                    tie_counter = tie_counter + 1
                if result["winner"] == "Tie Game":
                    round_winners.append(player1)
                else:	
                    round_winners.append(str(result["winner"]))
                #Message = "%s%s" % ("Round Winner: ", str(result["winner"]))
                print >>sys.stderr, result["winner"]
                #log = TournamentLog(message = Message)
                #log.put()
            # Need to do something about adding basic scores with person who gets the by
            print >>sys.stderr, "Prepping Exit"
            by = "None"                
            if len(round_entries) == 1:
                by = round_entries.pop()
                Message = "%s%s" % ("Assigning By:", str(by))            
                print >>sys.stderr, Message
                #log = TournamentLog(message = Message)
                #log.put()
            # Determine if another round is necessary or if winner can be declared
            print >>sys.stderr, "Exiting"    
            taskqueue.add(url='/score', params={'tournament_entries': json.dumps(round_winners), 'by': by}, countdown=180)

        except:
            self.response.clear()
            self.response.set_status(500)
            print >>sys.stderr, "Round Interrupted"
Example #37
0
def tictactoe(state):
    len(state) == 9 or abort(404)
    all(s in 'xo-' for s in state) or abort(404)
    if (not state.count('x') == state.count('o') and
            not state.count('x')  == state.count('o') + 1):
        abort(404)

    board = TicTacToe(state)

    move = request.args.get('move', '')
    if move:
        if board.completed():
            abort(422)
        move = 'abc'.index(move[0]), '012'.index(move[1])
        if move not in board.empty():
            abort(422)

        board = board.move(move)

        return redirect(url_for('tictactoe', state=str(board)))

    board_dict = {
        'class': 'tictactoe-board',
        'properties': {
            'repr': str(board),
            'turn': board.turn(),
            'winner': board.winner(),
            'completed': board.completed(),
            'state': board,
        },
        'links': [
            {'rel': ['self'], 'href': url_for('tictactoe', state=str(board))},
            {'rel': ['games'], 'href': url_for('games')}
        ]
    }

    if not board.completed():
        board_dict['actions'] = [
            {
                'name': 'tictactoe-move',
                'title': 'Make your move',
                'method': 'GET',
                'href': url_for('tictactoe', state=str(board)),
                'fields': [
                    {
                        'name': 'move',
                        'type': 'select',
                        'options': [
                            {'value': 'abc'[r] + str(c)} for r,c in board.empty()
                        ]
                    }
                ]
            }
        ]

    return jsonify(board_dict)
 def _test_local_return(self):
     appurl = 'DEFAULT_TICTACTOE'
     function = 'get_new_board'
     result = TicTacToe.local_return(appurl, function, {})
     self.assertEqual(True, 'board' in result)
     
     function = 'is_board_valid'
     next_result = TicTacToe.local_return(appurl, function, result)
     if not next_result:
         self.assertTrue(False)
     
     function=='is_move_valid'
     d = {'board':'***/n***/n***', 'move':'X**/n***/n***'}
     result = TicTacToe.local_return(appurl, function, d)
     self.assertEqual(True, 'valid' in result)
Example #39
0
 def get(self):
     action = self.request.get('action')
     if action== 'getSystemUserList':
         users = db.GqlQuery("SELECT * FROM User WHERE type='system'").fetch(5000)
         result = []
         for user in users:
             result.append([user.id,user.score])
         self.response.out.write('{"data":'+json.dumps(result)+'}')
     if action== 'getHumanUserList':
         users = db.GqlQuery("SELECT * FROM User WHERE type='user'").fetch(5000)
         result = []
         for user in users:
             result.append([user.id,user.score])
         self.response.out.write('{"data":'+json.dumps(result)+'}')
     if action== 'getUserList':
         users = db.GqlQuery("SELECT * FROM User").fetch(5000)
         result = []
         for user in users:
             result.append([user.id,user.score])
         self.response.out.write('{"data":'+json.dumps(result)+'}')
     if action == 'getStrategy':
         self.response.out.write(json.dumps(getUserRuleDict(self.request.get('player'),self.request.get('game'))))
     if action== 'runMatch':
         result = TicTacToe.runMatches(self.request.get('p1'), self.request.get('p2'), 20)
         self.response.out.write('{"result":'+json.dumps(result)+'}')
     if action== 'checkUserName':
         userName = self.request.get('userName').lower()
         existingUser = db.GqlQuery("SELECT * FROM User WHERE id=:1",userName).fetch(500)
         if existingUser:
             self.response.out.write('Already taken')
         else:
             self.response.out.write('Okay')
Example #40
0
 def __init__(self, player1, player2):
     self.create()
     self.layout()
     self.show()
     self.player1 = player1
     self.player2 = player2
     self.tictactoe = TicTacToe()
Example #41
0
    def post(self):
        action  = self.request.get('action')
        if action == 'makeNewStrategy':
            ruleBoardList = eval(self.request.get('ruleBoardList'))
#            addedRule = TicTacToe.addCustomRule(ruleBoard, self.request.get('title'), self.request.get('desc'), self.request.get('user'), self.request.get('translationInvariant'), self.request.get('flipping'), self.request.get('rowPermutation'), self.request.get('columnPermutation'), self.request.get('rotation'))
            addedRule = TicTacToe.addCustomRuleList(ruleBoardList, self.request.get('title'), self.request.get('desc'), self.request.get('user'))
            userAI = getAI(self.request.get('user'),'tictactoe')
            result = userAI.addRule(addedRule)
            print >>sys.stderr, json.dumps(result)
            self.response.out.write(json.dumps(result)) # True or False
Example #42
0
    def get(self):
        action  = self.request.get('action')
        if action == 'getStrategy':
            self.response.out.write(json.dumps(getUserRuleDict(self.request.get('player'),self.request.get('game'))))
        elif action == 'getPublicStrategyDict':
            dict = getBuiltInRuleDict(self.request.get('game'))
            self.response.out.write(json.dumps(dict))
        elif action == 'findBestStrategy':
            result = TicTacToe.findBestStrategy(json.loads(self.request.get('board')),self.request.get('user'),self.request.get('turn'))
            self.response.out.write(json.dumps(result)) 
        elif action == 'findMatchingStrategy':
            result = TicTacToe.findMatchingStrategy(json.loads(self.request.get('board')), self.request.get('turn'), self.request.get('loc'))  
            self.response.out.write(json.dumps(result))
        elif action == 'enableStrategy':
            # append a builtIn strategy to the user's AI data 
            result = TicTacToe.activateBuiltInRule(self.request.get('player'), self.request.get('strategyToEnable'))
            self.response.out.write(json.dumps(result))
        elif action == 'deleteRule':
            # append a builtIn strategy to the user's AI data 
            result = TicTacToe.deleteRule(self.request.get('player'), self.request.get('strategyToDelete'))
            self.response.out.write(json.dumps(result))

        elif action == 'changeOrder':
            user_id = self.request.get('player')
            game_title = self.request.get('game')
            keyStringList = json.loads(self.request.get('newStrategy'))
            userAI = getAI(user_id,game_title)
            self.response.out.write(userAI.updateByKeyStringList(keyStringList))
        elif action == 'a':
            self.response.out.write("hi")
            userAI = AI.get_by_key_name('ingrahaj_tictactoe')
            print userAI
            self.response.out.write(userAI.data)
        elif action == '':
            self.response.out.write("no action")
            pass
        else:
            self.response.out.write("unrecognized action: "+action)
            # ignore this
            pass        
Example #43
0
    def get_message(self, channel, message, user):
        players = self.user_manager.get_users_mentioned(message)
        players.add(user)
        if len(players) > 2:
            self.msg_writer.send_message(
                "You may not have more than two players currently", channel
            )
            return
        tokens = message.split()
        size = 3
        length = 3
        match_type = False
        move = ""
        for token in tokens:
            if TicTacToeManager.size_command in token:
                numbers = re.search(r'\d+', token)
                if numbers:
                    size = int(re.search(r'\d+', token).group())
            elif TicTacToeManager.length_command in token:
                numbers = re.search(r'\d+', token)
                if numbers:
                    length = int(re.search(r'\d+', token).group())
            elif token == TicTacToeManager.bolton_command:
                match_type = TicTacToeManager.bolton_command
            elif token == TicTacToeManager.pvp_command:
                match_type = TicTacToeManager.pvp_command
            else:
                move = token

        if match_type:
            game = TicTacToe(size, length, match_type, players)
            self.game_manager.add_game(
                game, players, channel, TicTacToeManager.name
            )
            self.msg_writer.send_message(game.starting_message(), channel)
        else:
            self.game_manager.process_message(
                players, channel, TicTacToeManager.name, move, user
            )
Example #44
0
 def get(self):
     ''' this signup module will receive ajax call from lobby.html  '''
     # read given user id and password 
     # create User object defined in datastore.py
     # assign usr id and password and save it
     # send back success message
     print >>sys.stderr, "Sign up process start"
     namePattern = re.compile(r"[a-zA-Z][a-zA-Z0-9]{2,16}$")
     id = self.request.get('id')
     if namePattern.match(self.request.get('id'))==None:
         self.response.out.write("User name(3~16 characters) should contain only alphabets and numbers(not for the first character).")
         return
     existingUser = db.GqlQuery("SELECT * FROM User WHERE id=:1",id).get()
     if existingUser:
         self.response.out.write(id+" already exists. Try a different name please.")
         return
     user = User(key_name=id,
                 id = id,
                 email = self.request.get('email'),
                 type = 'user',
                 password = self.request.get('password'),
                 botKind = self.request.get('botKind'),
                 botName = self.request.get('botName'),
                 score = 0)            
     result = user.put()         
     print >>sys.stderr, result       
     if result:
         AI(key_name=id+"_tictactoe",
                     user = id,
                     game = "tictactoe").put()
         TicTacToe.activateBuiltInRuleByTitle(id, 'Take Random')
         self.sess = sessions.Session()
         self.sess['loggedInAs'] = user.id;
         self.response.out.write("yes")  
         return
     else: 
         self.response.out.write("no")  
         return       
Example #45
0
def instance(name, bot, exploratory, rounds):
    print("task: name:", name, "bot:", bot, "exploratory:", exploratory, "rounds:", rounds)
    start_time = time.process_time()
    env = environment.Environment(discount=1.0, q_init=0.5)
    first_player = player.Player(name=1, exploratory=exploratory, environment=env)
    second_player = player.Player(name=2, exploratory=exploratory, environment=env)
    first_bot = bot(environment=env, player=first_player)
    second_bot = bot(environment=env, player=second_player)

    game = TicTacToe()
    # play the first bot against the second bot, self learning !!
    # the game should last .. long
    # report every 1000 rounds
    report = 1000
    # play until ends
    # the first bot makes move, alternate this afterwards
    start_turn = first_bot.player.name
    for round in range(rounds):
        # do the training
        # playing against each other
        # from the start
        # the players will alternatively begin
        game.restart(start=start_turn)
        whose_turn = start_turn
        start_turn = start_turn % 2 + 1
        first_bot.restart()
        second_bot.restart()
        while not game.is_end():
            # keep playing
            # the first bot makes move
            if first_bot.player.name is whose_turn:
                current_bot = first_bot
            else:
                current_bot = second_bot
            current_state = game.table
            action = current_bot.take_turn(current_state)
            # next player comes into play
            whose_turn = whose_turn % 2 + 1
            game.turn(action)

        # make the robot to learn something a bit
        # this will make the bots learn about the result of the game
        current_state = game.table
        first_bot.take_turn(current_state)
        second_bot.take_turn(current_state)

        if round % report is 0:
            # make report
            print("exploratory : ", exploratory, "percent: ", round / rounds * 100)

    # write the q_table into a file
    # only the fist_bot is important
    filename = "results/" + name + "-" + str(exploratory) + "-" + str(rounds) + ".txt"
    print("saving into file:", filename)
    json.dump(first_bot.q_table, open(filename, "w"))
    print("finished exploratory: ", exploratory, " time: ", time.process_time() - start_time)
    return 0
Example #46
0
        def best_move(tictactoe: TicTacToe, recursion_level: int=1) -> Tuple[int, TicTacToe.Tile]:
            best_score, best_tile = -math.inf, None

            for tile in tictactoe.choices():
                tictactoe.set(tile)
                score = tictactoe.score(tile)
                if score is None:
                    opponent_score, opponent_tile = best_move(tictactoe, recursion_level + 1)
                    score = -opponent_score
                else:
                    score /= recursion_level
                if score > best_score:
                    best_score, best_tile = score, tile
                tictactoe.unset(tile)
            return best_score, best_tile
Example #47
0
from tictactoe import TicTacToe

t = TicTacToe()
t.go()
Example #48
0
proj_root = normpath(join(abspath(sys.path[0]), "../../../.."))
sys.path.append(join(proj_root, "clients/Python"))
sys.path.append(join(proj_root, "samples/tictactoe/clients/Python"))

import grebe
from tictactoe import TicTacToe

if not (3 <= len(sys.argv) <= 4):
    print("Invalid number of args", file=sys.stderr)
    sys.exit(1)

username = sys.argv[1]
server = sys.argv[2]
port = int(sys.argv[3]) if len(sys.argv) == 4 else 13579

client = TicTacToe(server, port)

open_cells = [(r, c) for r in (1, 2, 3) for c in (1, 2, 3)]

try:
    role, _, _ = client.login(username, "")

    if role == "P1":
        move = random.choice(open_cells)
        open_cells.remove(move)
        client.move(*move)

    while True:
        p1move, p2move = client.waitForNextTurn()
        opmove = p2move if role == "P1" else p1move
        open_cells.remove(opmove)
Example #49
0
sys.path.append(os.path.abspath('../tic-tac-toe-thegame'))
from tictactoe import TicTacToe

__author__ = 'phizaz'

bot_desc = {
    'name': 'BotRLBetterDiscovery',
    'exploratory': 1,
    'rounds': 100000,
}

bot = Bot(name=1, q_table=Tools.load_source(bot_desc))
# bot starts first, but alternatively afterwards
start_turn = bot.name
while True:
    game = TicTacToe()
    game.restart(start=start_turn)
    whose_turn = start_turn
    start_turn = start_turn % 2 + 1
    print('game start : ')
    while True:
        if whose_turn is bot.name:
            # bot action
            action = bot.take_turn(game.table)
        else:
            # user action
            action = (int(input('row:')),
                      int(input('col:')))
        game.turn(action)
        game.display()
        whose_turn = whose_turn % 2 + 1
Example #50
0
class TestTicTacToe(unittest.TestCase):
    def setUp(self):
        self.T = TicTacToe()
        __builtins__.raw_input = Mock()
        self.ri = __builtins__.raw_input

    def tearDown(self):
        self.T = None

    def test_human_move_char(self):
        """Test that the human_move does not accept input outside of range"""
        self.ri.return_value = "c"
        assert False == self.T.human_move()

    def test_human_move_taken(self):
        self.T.board[0][0] = "x"
        self.ri.return_value = "0"
        assert False == self.T.human_move()

    def test_human_move_acceptable(self):
        """Test that the human_move accepts all possible input"""
        for i in range(9):
            self.ri.return_value = str(i)
            T = TicTacToe()
            assert self.T.human_move() == True
            T = None

    def test_win(self):
        """Test that a winner is detected"""
        self.T.board[0] = ["x"] * 3
        assert self.T.tic_tac_toe(self.T.board)

    def test_winner_1(self):
        """Horizontal winner found"""
        self.T.board[0] = ["x"] * 3
        assert self.T.tic_tac_toe(self.T.board)[0][0] == "x"

    def test_winner_2(self):
        """Vertical winner found"""
        self.T.board[0][0] = self.T.board[1][0] = self.T.board[2][0] = "x"
        assert self.T.tic_tac_toe(self.T.board) == "x"

    def test_winner_3(self):
        """Diagonal winner found"""
        self.T.board[0][2] = "o"
        self.T.board[1][1] = "o"
        self.T.board[2][0] = "o"
        assert self.T.tic_tac_toe(self.T.board) == "o"

    def sim(self, prep, win):
        for move in prep:
            self.T.board[move[0]][move[1]] = "x"
        assert win == self.T.win(self.T.board, "x")

    # test win possibilities
    def test_win_top_row(self):
        self.sim(((0, 1), (0, 2)), (0, 0))

    def test_win_mid_row(self):
        self.sim(((1, 0), (1, 2)), (1, 1))

    def test_win_bottom_row(self):
        self.sim(((2, 0), (2, 1)), (2, 2))

    def test_win_left_col(self):
        self.sim(((0, 1), (0, 2)), (0, 0))

    def test_win_mid_col(self):
        self.sim(((1, 0), (1, 2)), (1, 1))

    def test_win_right_col(self):
        self.sim(((2, 0), (2, 1)), (2, 2))

    def test_win_first_diag(self):
        self.sim(((0, 0), (1, 1)), (2, 2))

    def test_win_second_diag(self):
        self.sim(((0, 2), (2, 0)), (1, 1))

    # Test fork
    def test_fork_1(self):
        self.T.board[0][1] = "x"
        self.T.board[1][0] = "x"
        self.T.board[0][0] = "o"
        assert self.T.fork(self.T.board, "x") == (1, 1)

    def test_fork_2(self):
        self.T.board[0][0] = "x"
        self.T.board[2][2] = "x"
        self.T.board[1][1] = "o"
        self.T.board[0][2] = "o"
        assert self.T.fork(self.T.board, "x") == (2, 0)

    def test_block_fork_1(self):
        self.T.board[0][0] = "x"
        self.T.board[2][2] = "x"
        self.T.board[1][1] = "o"
        assert self.T.bock_fork() == (0, 1)

    def test_block_fork_1(self):
        self.T.board[0][1] = "x"
        self.T.board[1][0] = "x"
        self.T.board[1][1] = "o"
        assert self.T.block_fork() == (0, 0)

    def test_center(self):
        assert self.T.center() == (1, 1)

    def test_opposite_corner_1(self):
        self.T.board[0][0] = "x"
        assert self.T.opposite_corner() == (2, 2)

    def test_opposite_corner_2(self):
        self.T.board[2][0] = "x"
        assert self.T.opposite_corner() == (0, 2)

    def test_empty_corner_1(self):
        assert self.T.empty_corner() == (0, 0)

    def test_empty_corner_2(self):
        self.T.board[0][0] = "x"
        self.T.board[0][2] = "x"
        assert self.T.empty_corner() == (2, 0)

    def test_empty_side_1(self):
        self.T.board[0][1] = "x"
        assert self.T.empty_side() == (1, 0)
Example #51
0
 def initGame(self):
     self.player = QTicTacToe.QPlayer('O')
     ArtificialIntelligence = QTicTacToe.AIs["Depth First Search AI"]
     self.ai = ArtificialIntelligence('X')
     self.ticTacToe = TicTacToe(o=self.player, x=self.ai)
Example #52
0
 def play(self, scenario: List[str], o: TicTacToe.Player, x: TicTacToe.Player):
     tictactoe = TicTacToe.build(scenario, o=o, x=x)
     tile = x.play()
     correct = self.find(scenario, '#')
     self.assertEqual((tile.row, tile.column), correct)
Example #53
0
class TicTacToeBoard(object):

    def __init__(self, player1, player2):
        self.create()
        self.layout()
        self.show()
        self.player1 = player1
        self.player2 = player2
        self.tictactoe = TicTacToe()

    def create(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_default_size(400, 400)
        self.window.connect("destroy", self.destroy)
        self.window.connect("delete_event", self.delete_event)
        self.table = gtk.Table(rows=3, columns=3, homogeneous=True)
        self.buttons = [gtk.Button(label=" - ") for i in xrange(9)]
        for index, button in enumerate(self.buttons):
            button.position = index
            button.connect('clicked', self.button_clicked)

    def layout(self):
        for i in xrange(3):
            for j in xrange(3):
                self.table.attach(self.buttons[i * 3 + j], j, j + 1, i, i + 1)
        self.window.add(self.table)

    def show(self):
        for button in self.buttons:
            button.show()
        self.table.show()
        self.window.show()

    def is_gameover(self):
        if self.tictactoe.is_gameover():
            if self.tictactoe.winner == self.player1.marker:
                msg = 'You wins!'
            elif self.tictactoe.winner == self.player2.marker:
                msg = 'Computer wins!'
            else:
                msg = 'Game over with Draw'
            md = gtk.MessageDialog(self.window,
                                   0,
                                   gtk.MESSAGE_INFO,
                                   gtk.BUTTONS_OK,
                                   msg)
            md.run()
            md.destroy()
            return True
        return False

    def button_clicked(self, widget):
        if not self.is_gameover():
            if widget.position not in self.tictactoe:
                md = gtk.MessageDialog(self.window,
                                       0,
                                       gtk.MESSAGE_ERROR,
                                       gtk.BUTTONS_OK,
                                       "Invalid move. Retry")
                md.run()
                md.destroy()
            else:
                widget.set_label(self.player1.marker)
                self.tictactoe.mark(self.player1.marker, widget.position)
                if not self.is_gameover():
                    move_position, _ = self.player2.maximized_move(
                        self.tictactoe)
                    self.tictactoe.mark(self.player2.marker, move_position)
                    self.buttons[move_position].set_label(self.player2.marker)
                    self.is_gameover()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def delete_event(self, widget, event, data=None):
        return False

    def play(self):
        gtk.main()
Example #54
0
 def setUp(self):
     self.T = TicTacToe()
     __builtins__.raw_input = Mock()
     self.ri = __builtins__.raw_input
Example #55
0
import random
from board import Board
from randomai import RandomAI
from pseudorandomai import PseudoRandomAI
from humanai import HumanAI
from tictactoe import TicTacToe

if __name__ == "__main__":
  while True:
    board = Board()
    ttt = TicTacToe()
    print "Choose the match-up:"
    print "Type 1 for Random AI v/s Pseudo Random AI"
    print "Type 2 for Pseudo Random AI v/s Pseudo Random AI"
    print "Type 3 for Random AI v/s You"
    print "Type 4 for Pseudo Random AI v/s You"
    print "Type 5 for a 2 player game"
    choice = int( raw_input( "Type in your choice: "))
    if choice == 1:
      ttt.start(board, RandomAI(), PseudoRandomAI())
    elif choice == 2:
      ttt.start(board, PseudoRandomAI(), PseudoRandomAI())
    elif choice == 3:
      humanPlayer = HumanAI()
      ttt.start(board, RandomAI(), humanPlayer)
    elif choice == 4:
      humanPlayer = HumanAI()
      ttt.start(board, humanPlayer, PseudoRandomAI())
    elif choice == 5:
      humanPlayer1 = HumanAI()
      humanPlayer2 = HumanAI()
 def __init__(self, h=7, v=6, k=4):
     TicTacToe.__init__(self, h, v, k)
Example #57
0
class QTicTacToe(QWidget):

    class QTileButton(QPushButton):
        SymbolMap = {'-': " ", 'O': "◯", 'X': "☓"}

        def __init__(self, parent, tile):
            super(QTicTacToe.QTileButton, self).__init__(parent)
            self.tile = tile
            self.setFocusPolicy(Qt.NoFocus)
            self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
            self.setContextMenuPolicy(Qt.CustomContextMenu)

        def clickEvent(self):
            self.parent().round(self.tile)
            self.repaint()

        def marked(self):
            self.setEnabled(self.tile.player is None)
            self.setText(self.SymbolMap[str(self.tile)])
            self.update()

        def resizeEvent(self, resizeEvent: QResizeEvent):
            font = self.font()
            font.setBold(True)
            font.setPixelSize(round(0.50 * min(self.width(), self.height())))
            self.setFont(font)

        def sizeHint(self) -> QSize:
            return QSize(40, 40)

    class QPlayer(TicTacToe.Player):
        tile = None

        def play(self):
            return self.tile

    AIs = {"Depth First Search AI": DepthFirstSearchAI}

    def __init__(self):
        super(QTicTacToe, self).__init__()
        self.ticTacToe = None
        self.player, self.ai = None, None
        self.initGame()
        self.initUI()
        self.show()

    def initGame(self):
        self.player = QTicTacToe.QPlayer('O')
        ArtificialIntelligence = QTicTacToe.AIs["Depth First Search AI"]
        self.ai = ArtificialIntelligence('X')
        self.ticTacToe = TicTacToe(o=self.player, x=self.ai)

    def initUI(self):
        self.setWindowTitle(self.tr("Tic-Tac-Toe"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        gridLayout = QGridLayout()
        gridLayout.setSpacing(3)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(self.selectAI)
        layout.addWidget(aiComboBox)
        layout.addLayout(gridLayout)

        for tile in self.ticTacToe:
            button = QTicTacToe.QTileButton(self, tile)
            gridLayout.addWidget(button, tile.row, tile.column)
            button.clicked.connect(button.clickEvent)
            tile.delegate = button

    def round(self, tile: TicTacToe.Tile):
        QApplication.setOverrideCursor(Qt.WaitCursor)
        self.player.tile = tile
        score = self.ticTacToe.round(True)
        QApplication.restoreOverrideCursor()
        if score is not None:
            if score == +1:
                QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
            if score == 0:
                QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
            if score == -1:
                QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
            self.ticTacToe.reset(True)

    def selectAI(self, name: str):
        ArtificialIntelligence = QTicTacToe.AIs[name]
        self.ai = ArtificialIntelligence(self.ticTacToe, self.ai.symbol)
        self.ticTacToe.x = self.ai

    def sizeHint(self) -> QSize:
        return QSize(180, 220)
 def _test_get_players(self):
     result = TicTacToe.get_players()
     self.assertEqual(True, len(result)>0)
Example #59
0
from tictactoe import TicTacToe

game = TicTacToe()
game.run()

 def test_display(self):
     game = TicTacToe()
     for i in range(3):
         game.turn((0, i))
         game.turn((1, i))
     game.display()