-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tic-Tac-Toe
62 lines (40 loc) · 1.31 KB
/
Tic-Tac-Toe
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
import random
board = [" " for _ in range(9)]
def print_board():
for i in range(0, 9, 3):
print(f"{board[i]} | {board[i+1]} | {board[i+2]}")
if i < 6:
print("-" * 9)
def check_win(board, player):
winning_combinations = [(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 a, b, c in winning_combinations:
if board[a] == board[b] == board[c] == player:
return True
return False
def play_game():
print("Welcome to Tic-Tac-Toe!")
print_board()
while True:
move = int(input("Enter your move (1-9): ")) - 1
if board[move] == " ":
board[move] = "X"
else:
print("Invalid move. Try again.")
continue
print_board()
if check_win(board, "X"):
print("You win!")
break
if " " not in board:
print("It's a tie!")
break
ai_move = random.choice([i for i, spot in enumerate(board) if spot == " "])
board[ai_move] = "O"
print(f"AI plays {ai_move + 1}:")
print_board()
if check_win(board, "O"):
print("AI wins!")
break
play_game()