-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTic_tac_toe.py
97 lines (84 loc) · 2.4 KB
/
Tic_tac_toe.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
91
92
93
94
95
96
97
# Tic toe game
# It is played between two players
# either two humans or human and computer
import random
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
player = "x"
winner = None
gamerun = True
def printboard(board):
print(board[0] + "|" + board[1] + "|" + board[2])
print(board[3] + "|" + board[4] + "|" + board[5])
print(board[6] + "|" + board[7] + "|" + board[8])
def playerin(board):
p = int(input("Enter a number 1 - 9: "))
if 1 <= p <= 9 and board[p - 1] == "_":
board[p - 1] = player
else:
print("Invalid input or position already taken. Try again.")
def checkhorizontal(board):
global winner
if board[0] == board[1] == board[2] and board[1] != "_":
winner = board[0]
return True
elif board[3] == board[4] == board[5] and board[3] != "_":
winner = board[3]
return True
elif board[6] == board[7] == board[8] and board[6] != "_":
winner = board[6]
return True
def checkrow(board):
global winner
if board[0] == board[3] == board[6] and board[0] != "_":
winner = board[0]
return True
elif board[1] == board[4] == board[7] and board[1] != "_":
winner = board[1]
return True
elif board[2] == board[5] == board[8] and board[2] != "_":
winner = board[2]
return True
def checkdiagonal(board):
global winner
if board[0] == board[4] == board[8] and board[0] != "_":
winner = board[0]
return True
elif board[2] == board[4] == board[6] and board[2] != "_":
winner = board[2]
return True
return False
def checktie(board):
global gamerun
if "_" not in board:
printboard(board)
print("It's a tie!")
gamerun = False
def switchplayer():
global player
if player == "x":
player = "o"
else:
player = "x"
def checkwin():
if checkdiagonal(board) or checkhori(board) or checkrow(board):
printboard(board)
print(f"The winner is {winner}!")
global gamerun
gamerun = False
def computer(board):
while player == "o":
position = random.randint(0, 8)
if board[position] == "_":
board[position] = "o"
switchplayer()
while gamerun:
printboard(board)
playerin(board)
checkwin()
checktie(board)
switchplayer()
computer(board)
checkwin()
checktie(board)