-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtic_tac_toe.py
69 lines (59 loc) · 1.68 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
import numpy
board=numpy.array([['-','-','-'],['-','-','-'],['-','-','-']])
p1s='X'
p2s='O'
def checkrows(symbol):
for r in range(3):
count=0
for c in range(3):
if board[r][c]==symbol:
count+=1
if count==3:
print(symbol,'won')
return True
return False
def checkcols(symbol):
for c in range(3):
count=0
for r in range(3):
if board[r][c]==symbol:
count+=1
if count==3:
print(symbol,'won')
return True
return False
def check_diagonal(symbol):
if board[0][2]==board[1][1] and board[1][1]==board[2][0] and board[1][1]==symbol:
print(symbol,'won')
return True
elif board[0][0]==board[1][1] and board[1][1]==board[2][2] and board[1][1]==symbol:
print(symbol,'won')
return True
return False
def won(symbol):
return checkrows(symbol) or checkcols(symbol) or check_diagonal(symbol)
def place(symbol):
print(numpy.matrix(board))
while(1):
row=int(input('Enter row - 1 or 2 or 3:'))
col=int(input('Enter column - 1 or 2 or 3:'))
if row>0 and row<4 and col>0 and col<4 and board[row-1][col-1]=='-':
break
else:
print('Invalid input. Please enter again')
board[row-1][col-1]=symbol
def play():
for turn in range(9):
if turn%2==0:
print('X turn')
place(p1s)
if won(p1s):
break
else:
print('O turn')
place(p2s)
if won(p2s):
break
if not(won(p1s)) and not(won(p2s)):
print('Draw')
play()