Skip to content

Commit 3f7b716

Browse files
Merge pull request #2846 from smty2018/ai-tic-tac-toe
Tic Tac Toe(AI) terminal game
2 parents efe3604 + 2fc4407 commit 3f7b716

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

Terminal Tic Tac Toe(AI)/app.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import random
2+
3+
def pb(b):
4+
for r in b:
5+
print('|'.join(r))
6+
print('-'*5)
7+
8+
def iw(b, p):
9+
return any(all(c == p for c in r) for r in b) or any(all(b[i][j] == p for i in range(3)) for j in range(3)) or all(b[i][i] == p for i in range(3)) or all(b[i][2-i] == p for i in range(3))
10+
11+
def id(b):
12+
return all(all(c != '.' for c in r) for r in b)
13+
14+
def gec(b):
15+
return [(i, j) for i in range(3) for j in range(3) if b[i][j] == '.']
16+
17+
def mm(b, d, im):
18+
s = {'X': 1, 'O': -1, 'draw': 0}
19+
if iw(b, 'X'):
20+
return s['X'] - d
21+
elif iw(b, 'O'):
22+
return s['O'] + d
23+
elif id(b):
24+
return s['draw']
25+
if im:
26+
bs = float('-inf')
27+
for i, j in gec(b):
28+
b[i][j] = 'X'
29+
s = mm(b, d + 1, False)
30+
b[i][j] = '.'
31+
bs = max(bs, s)
32+
return bs
33+
else:
34+
bs = float('inf')
35+
for i, j in gec(b):
36+
b[i][j] = 'O'
37+
s = mm(b, d + 1, True)
38+
b[i][j] = '.'
39+
bs = min(bs, s)
40+
return bs
41+
42+
def gbm(b):
43+
bs = float('-inf')
44+
bm = None
45+
for i, j in gec(b):
46+
b[i][j] = 'X'
47+
s = mm(b, 0, False)
48+
b[i][j] = '.'
49+
if s > bs:
50+
bs = s
51+
bm = (i, j)
52+
return bm
53+
54+
def main():
55+
b = [['.' for _ in range(3)] for _ in range(3)]
56+
p = 'X'
57+
while True:
58+
pb(b)
59+
if iw(b, 'X'):
60+
print("You win!")
61+
break
62+
elif iw(b, 'O'):
63+
print("AI wins!")
64+
break
65+
elif id(b):
66+
print("It's a draw!")
67+
break
68+
if p == 'X':
69+
r, c = map(int, input("Enter row and column (0-2) separated by space: ").split())
70+
if b[r][c] != '.':
71+
print("Invalid move. Try again.")
72+
continue
73+
b[r][c] = 'X'
74+
p = 'O'
75+
else:
76+
print("AI is thinking...")
77+
r, c = gbm(b)
78+
b[r][c] = 'O'
79+
p = 'X'
80+
81+
if __name__ == "__main__":
82+
main()

Terminal Tic Tac Toe(AI)/readme.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
A command-line tic-tac-toe game where you can play against an AI opponent that uses the minimax algorithm to make its moves.
2+
3+
To play the game, you'll execute this script in a Python environment that supports command-line input/output. The game board is printed, and you're prompted to enter your move by specifying the row and column (both ranging from 0 to 2). The AI calculates its move and takes its turn automatically.

0 commit comments

Comments
 (0)