-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicTacToe.py
More file actions
83 lines (72 loc) · 2.52 KB
/
TicTacToe.py
File metadata and controls
83 lines (72 loc) · 2.52 KB
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
board = ['-', '-', '-',
'-', '-', '-',
'-', '-', '-']
currentPlayer = "X"
winner = None
gameRunning = True
#printing board
def printBoard(board):
print(board[0] + " | " + board[1] + " | " + board[2])
print("-" * 9)
print(board[3] + " | " + board[4] + " | " + board[5])
print("-" * 9)
print(board[6] + " | " + board[7] + " | " + board[8])
#take player input
def playerInput(board):
while True:
if currentPlayer == "X":
inp = int(input(f"Enter a number 1-9 \033[1;34m Player (X) \033[0;0m : "))
else:
inp = int(input(f"Enter a number 1-9 \033[1;31m Player (0) \033[0;0m : "))
if inp >= 1 and inp <= 9 and board[inp-1] == "-":
board[inp-1] = currentPlayer
break
else:
if currentPlayer == "X":
print(f"Oops! Try again! Player - \033[1;34m Player (X) \033[0;0m ! ")
else:
print(f"Oops! Try again! Player - \033[1;31m Player (0) \033[0;0m ! ")
printBoard(board)
#check for win or tie
def checkHorizontal(board):
global winner
if (board[0] == board[1] == board[2] and board[0] != "-") or (board[3] == board[4] == board[5] and board[3] != "-") or (board[6] == board[7] == board[8] and board[6] != "-"):
winner = currentPlayer
return True
def checkRow(board):
global winner
if (board[0] == board[3] == board[6] and board[0] != "-") or (board[1] == board[4] == board[7] and board[1] != "-") or (board[2] == board[5] == board[8] and board[2] != "-"):
winner = currentPlayer
return True
def checkDiagonal(board):
global winner
if (board[0] == board[4] == board[5] and board[0] != "-") or (board[2] == board[4] == board[6] and board[2] != "-"):
winner = currentPlayer
return True
def checkTie(board):
global gameRunning
if "-" not in board:
printBoard(board)
print("Its a tie")
gameRunning = False
def checkWin():
if checkDiagonal(board) or checkHorizontal(board) or checkRow(board):
print(f"The winner is {winner}")
gameRunning = False
exit()
#switch the player
def switchPlayer():
global currentPlayer
if currentPlayer == "X":
currentPlayer = "O"
else:
currentPlayer = "X"
#check for win or tie again
while gameRunning:
printBoard(board)
if winner != None:
break
playerInput(board)
checkWin()
checkTie(board)
switchPlayer()