-
Notifications
You must be signed in to change notification settings - Fork 4
/
tic_tac_toe.py
113 lines (90 loc) · 2.64 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import random
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
currentPlayer = "X"
winner = None
gameRunning = True
def printBoard(board):
print(board[0] + " | " + board[1] + " | " + board[2])
print("---------")
print(board[3] + " | " + board[4] + " | " + board[5])
print("---------")
print(board[6] + " | " + board[7] + " | " + board[8])
def playerInput(board):
inp = int(input("Select a spot 1-9: "))
if board[inp-1] == "-":
board[inp-1] = currentPlayer
else:
print("Oops player is already at that spot.")
def checkHorizontal(board):
global winner
if board[0] == board[1] == board[2] and board[0] != "-":
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[3]
return True
def checkDiag(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[4] != "-":
winner = board[2]
return True
def checkIfWin(board):
global gameRunning
if checkHorizontal(board):
printBoard(board)
print(f"The winner is {winner}!")
gameRunning = False
elif checkRow(board):
printBoard(board)
print(f"The winner is {winner}!")
gameRunning = False
elif checkDiag(board):
printBoard(board)
print(f"The winner is {winner}!")
gameRunning = False
def checkIfTie(board):
global gameRunning
if "-" not in board:
printBoard(board)
print("It is a tie!")
gameRunning = False
def switchPlayer():
global currentPlayer
if currentPlayer == "X":
currentPlayer = "O"
else:
currentPlayer = "X"
def computer(board):
while currentPlayer == "O":
position = random.randint(0, 8)
if board[position] == "-":
board[position] = "O"
switchPlayer()
while gameRunning:
printBoard(board)
playerInput(board)
checkIfWin(board)
checkIfTie(board)
switchPlayer()
computer(board)
checkIfWin(board)
checkIfTie(board)