Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import random

def has_won(board, chess):
    winnings = [
        [0,1,2],[3,4,5],[6,7,8],
        [0,3,6],[1,4,7],[2,5,8],
        [0,4,8],[2,4,6],
    ]
    for winning in winnings:
        if board[winning[0]] == chess and board[winning[1]] == chess and board[winning[2]] == chess:
            return True
    return False

def is_computer_won(board):
	return has_won(board, 'O')
	
def is_player_won(board):
	return has_won(board, 'X')

def initial_board():
    return ['.'] * 9

def get_my_step(board):
    availables = []
    for i in range(9):
        if board[i] == '.':
            availables.append(i)
    return random.choice(availables)

def get_user_step():
    return int(input()) - 1

def is_valid_move(board, k):
    if k < 0 or k >= 9:
        return False
    if board[k] == '.':
        return True
    return False

def is_game_finished(board):
    for i in range(9):
        if board[i] == '.':
            return False
    return True

def display_board(board):
    print(board[:3])
    print(board[3:6])
    print(board[6:])

def display_greeting():
    print("TIC-TAC-TOE Play[X] Me[O]")
    print("type 1..9 to place your next move")

def display_result():
    print("Everyone wins !")

#main

display_greeting()
board = initial_board()
display_board(board)
is_my_turn = random.choice([True, False])
while True:
    if is_my_turn:
        print('My turn ...')
        k = get_my_step(board)
        board[k] = 'O'
        is_my_turn = False
    else:
        print('Your turn:')
        k = get_user_step()
        if is_valid_move(board, k):
            board[k] = 'X'
            is_my_turn = True
        else:
            print("Invalid move!!!")

    display_board(board)

    if is_computer_won(board):
        print("I WON!!")
        break
    if is_player_won(board):
        print("YOU WON!!!")
        break
    if is_game_finished(board):
        print("TIETIETIE")
        break
Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux