-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTicTacToeVSComp.py
93 lines (77 loc) · 2.38 KB
/
TicTacToeVSComp.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
import random
board = ["-","-","-",
"-","-","-",
"-","-","-"]
currentPlayer = "T"
winner = None
gameRunning = 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 playerInput(board):
inp = int(input ("Enter a Number from 1-9: "))
if inp >= 1 and inp <= 9 and board[inp-1] == "-":
board[inp-1] = currentPlayer
else:
print("OOPS! player is already there")
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[3]
return True
def checkRows(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[1]
return True
def checkTie(board):
if "-" not in board:
printBoard(board)
print("It's a Tie")
gameRunning = False
def checkWin():
if checkDiagonal(board) or checkHorizontal(board) or checkRows(board):
print(f"The winner is {winner} ")
gameRunning = False
def switchPlayer():
global currentPlayer
if currentPlayer == "T":
currentPlayer = "O"
else:
currentPlayer = "T"
def computer(board):
while currentPlayer == "O":
position = random.randint(0,8)
if board[position] == "-":
board[position] = "O"
switchPlayer()
while gameRunning:
printBoard(board)
playerInput(board)
checkWin()
checkTie(board)
switchPlayer()
computer(board)
checkWin()
checkTie(board)