tic tac toe python easy

Solutions on MaxInterview for tic tac toe python easy by the best coders in the world

showing results for - "tic tac toe python easy"
Giuseppe
22 Apr 2018
1def tic_tac_toe():
2    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
3    end = False
4    win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
5
6    def draw():
7        print(board[0], board[1], board[2])
8        print(board[3], board[4], board[5])
9        print(board[6], board[7], board[8])
10        print()
11
12    def p1():
13        n = choose_number()
14        if board[n] == "X" or board[n] == "O":
15            print("\nYou can't go there. Try again")
16            p1()
17        else:
18
19             board[n] = "X"
20           
21    def p2():
22        n = choose_number()
23        if board[n] == "X" or board[n] == "O":
24            print("\nYou can't go there. Try again")
25            p2()
26        else:
27            board[n] = "O"
28
29    def choose_number():
30        while True:
31            while True:
32                a = input()
33                try:
34                    a  = int(a)
35                    a -= 1
36                    if a in range(0, 9):
37                        return a
38                    else:
39                        print("\nThat's not on the board. Try again")
40                        continue
41                except ValueError:
42                   print("\nThat's not a number. Try again")
43                   continue
44
45    def check_board():
46        count = 0
47        for a in win_commbinations:
48            if board[a[0]] == board[a[1]] == board[a[2]] == "X":
49                print("Player 1 Wins!\n")
50                print("Congratulations!\n")
51                return True
52
53            if board[a[0]] == board[a[1]] == board[a[2]] == "O":
54                print("Player 2 Wins!\n")
55                print("Congratulations!\n")
56                return True
57        for a in range(9):
58            if board[a] == "X" or board[a] == "O":
59                count += 1
60            if count == 9:
61                print("The game ends in a Tie\n")
62                return True
63
64    while not end:
65        draw()
66        end = check_board()
67        if end == True:
68            break
69        print("Player 1 choose where to place a cross")
70        p1()
71        print()
72        draw()
73        end = check_board()
74        if end == True:
75            break
76        print("Player 2 choose where to place a nought")
77        p2()
78        print()
79
80    if input("Play again (y/n)\n") == "y":
81        print()
82        tic_tac_toe()
83
84tic_tac_toe()
85