-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tic_Tac_Toe
104 lines (96 loc) · 2.39 KB
/
Tic_Tac_Toe
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
# Tic-Tac-Toe-Game
#This is the game of Tic Tac Toe against AI made in Python.
def ConstBoard(board):
print("Current State of the Board: \n"); #-1=x, 1=O, blanks=0
for i in range(0,9):
if((i>0) and (i%3)==0):
print('\n');
if(board[i]==0):
print("_", end=" ");
if(board[i]==-1):
print("X", end=" ");
if(board[i]==1):
print("O", end=" ");
print("\n");
def user1turn(board):
pos= int(input("Enter X's position from [1,2,...9]: "));
if (board[pos-1]!=0):
print("||WRONG MOVE||");
return False;
board[pos-1]=-1;
def user2turn(board):
pos= int(input("Enter O's position from [1,2,...9]: "));
if (board[pos-1]!=0):
print("||WRONG MOVE||");
return False;
board[pos-1]=1;
def minmax(board, player):
x=analyzeboard(board);
if(x!=0):
return (x*player);
pos=-1;
value=-2;
for i in range(0,9):
if board[i]==0:
board[i]=player;
score=-minmax(board, player*-1);
board[i]=0;
if score>value:
value=score;
pos=i;
if(pos==-1):
return 0;
return value;
def CompTurn(board):
pos=-1;
value=-2;
for i in range(0,9):
if board[i]==0:
board[i]=1;
score=-minmax(board, -1);
board[i]=0;
if score>value:
value=score;
pos=i;
board[pos]=1;
def analyzeboard(board):
cb=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
for i in range(0,8):
if (board[cb[i][0]]!=0 and board[cb[i][0]]==board[cb[i][1]] and board[cb[i][0]]==board[cb[i][2]]):
return board[cb[i][0]];
return 0;
def main():
choice= int(input('''Enter 1 for single player
2 for multiplayer: '''))
board= [0,0,0,0,0,0,0,0,0]
if choice==1:
print("Computer: O vs You: X");
player= int(input("Enter to play 1st or 2nd: "));
for i in range(0,9):
if(analyzeboard(board)!=0):
break;
if((i+player)%2==0):
CompTurn(board);
else:
ConstBoard(board);
user1turn(board);
else:
for i in range(0,9):
if(analyzeboard(board)!=0):
break;
if(i%2==0):
ConstBoard(board);
user1turn(board);
else:
ConstBoard(board);
user2turn(board);
x= analyzeboard(board);
if(x==0):
ConstBoard(board);
print("DRAW!!");
if(x==-1):
ConstBoard(board);
print("Player X Wins!!| O Looses!!");
if(x==1):
ConstBoard(board);
print("Player O Wins!!| X Looses!!");