Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a010f9

Browse files
Merge pull request avinashkranjan#261 from hritik5102/Hritik5102-SWOC-PR2
Tic Tac Toe using MinMax algo
2 parents ec8c1ba + 9c99bad commit 8a010f9

File tree

4 files changed

+256
-0
lines changed

4 files changed

+256
-0
lines changed

‎SCRIPTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,4 @@
6060
| 56\. | Video_Watermark | Add watermark to a video with the given font | [Take Me](https://github.com/avinashkranjan/Amazing-Python-Scripts/tree/master/Video_Watermark) | [Biswajeet Sahoo](https://github.com/bislara) |
6161
| 57\. | Zoom-Auto-Attend | A zoom bot that automatically joins zoom calls for you and saves the meeting id and password | [Take Me](https://github.com/avinashkranjan/Amazing-Python-Scripts/tree/master/Zoom-Auto-Attend) | [Seth Walker](https://github.com/SethWalkeroo) |
6262
| 58\. | Document-Word-Detection | Detect a word present in the document (pages) using OpenCV | [Take Me](https://github.com/avinashkranjan/Amazing-Python-Scripts/tree/master/Document-Word-Detection) | [Hritik Jaiswal](https://github.com/hritik5102) |
63+
| 59\. | TicTacToe-Using-MinMax | An agent (Robot) will play Tic Tac Toe Game with Human. | [Take Me](https://github.com/avinashkranjan/Amazing-Python-Scripts/tree/master/TicTacToe-Using-MinMax) | [Hritik Jaiswal](https://github.com/hritik5102) |

‎TicTacToe-Using-MinMax/Output.gif‎

1.57 MB
Loading[フレーム]

‎TicTacToe-Using-MinMax/README.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# TicTacToe-Using-MinMax
2+
3+
## Description
4+
5+
Adversarial algorithm-Min-Max for Tic-Tac-Toe Game.
6+
An agent (Robot) will play Tic Tac Toe Game with Human.
7+
8+
Min-Max Algorithm: this algorithm also uses the game tree where each level has the additional information as:
9+
10+
Max if player wants to maximize utility(Agent)
11+
12+
Min if player wants to minimize utility(opponent)
13+
14+
Game require two players, 1. Ai Player and 2. Human Player [AI and Human player] for tic-tac-toe game.
15+
16+
## Setup instructions
17+
18+
No package needs to install
19+
20+
## Output
21+
22+
<p align="center"><img src="Output.gif"></p>
23+
24+
## Author(s)
25+
26+
[Hritik Jaiswal](https://github.com/hritik5102)
27+

‎TicTacToe-Using-MinMax/main.py‎

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
# TIC TAC TOE Minmax algorithm
2+
3+
'''
4+
1. Backtracking algorithm
5+
2. Max wiil try to maximize it utility
6+
3. Min will try to minimize user or human utility to win
7+
4. Time complexity : O(b^d)
8+
9+
b : branching factor (choices, number of possible move)
10+
d : depth
11+
'''
12+
13+
# Format colour
14+
bright_cyan = "033円[0;96m"
15+
16+
# import package
17+
import random
18+
19+
20+
board = [' ' for i in range(10)]
21+
def insertLetter(letter,pos):
22+
'''
23+
insert either 'O' or 'X' at perticular position
24+
'''
25+
board[pos] = letter
26+
27+
def spaceIsFree(pos):
28+
'''
29+
Boolean : Check whether their is any empty position is present or not in the board
30+
'''
31+
return board[pos]==' '
32+
33+
def printBoard(board):
34+
'''
35+
Display the board
36+
'''
37+
# "board" is a list of 10 strings representing the board (ignore index 0)
38+
print(' | |')
39+
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
40+
print(' | |')
41+
print('-----------')
42+
print(' | |')
43+
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
44+
print(' | |')
45+
print('-----------')
46+
print(' | |')
47+
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
48+
print(' | |')
49+
50+
def isWinner(board,letter):
51+
'''
52+
Boolean : check whether winning criteria met or not
53+
'''
54+
# condition of horizontal, vertical, diagonal
55+
return (board[1]==letter and board[2]==letter and board[3]==letter) or \
56+
(board[4]==letter and board[5]==letter and board[6]==letter) or \
57+
(board[7]==letter and board[8]==letter and board[9]==letter) or \
58+
(board[1]==letter and board[4]==letter and board[7]==letter) or \
59+
(board[2]==letter and board[5]==letter and board[8]==letter) or \
60+
(board[3]==letter and board[6]==letter and board[9]==letter) or \
61+
(board[1]==letter and board[5]==letter and board[9]==letter) or \
62+
(board[3]==letter and board[5]==letter and board[7]==letter)
63+
64+
def playerMove():
65+
'''
66+
Take the input from user and validate user's input
67+
'''
68+
69+
run = True
70+
while run:
71+
try:
72+
73+
move = int(input("Select a position to place \'X\' (1-9) : "))
74+
if isinstance(move,str):
75+
print("Please enter the valid number 😏")
76+
if move>0 and move<10:
77+
if spaceIsFree(move):
78+
run = False
79+
insertLetter('X',move)
80+
else:
81+
print("Position is already occupied 😳")
82+
else:
83+
print("Please enter valid position within the valid range 😏")
84+
except:
85+
print("Please enter the valid number 😏")
86+
87+
88+
def compMove():
89+
'''
90+
Function decide computer's moves i.e where to place 'O' , so that it win
91+
'''
92+
# 1. winning move
93+
# 2. Block move ,if human gets benefited
94+
# 3. move at corner
95+
# 4. move at center
96+
# 5. move at any edge
97+
possibleMove = [x for x,letter in enumerate(board) if letter==' ' and x!=0]
98+
move = 0
99+
100+
# 1st way -> To check whether computer can win or not , if not then
101+
# computer now tries to block opponent move, so that he could not win
102+
for let in ['O','X']:
103+
for i in possibleMove:
104+
# replica of board
105+
boardCopy = board[:]
106+
boardCopy[i] = let
107+
if isWinner(boardCopy,let):
108+
move = i
109+
return move
110+
111+
112+
if board[1] == 'X' or board[3]=='X' or board[7]=='X' or board[9]=='X':
113+
if 5 in possibleMove:
114+
move=5
115+
return move
116+
117+
edgesOpen = []
118+
119+
if (board[1] == 'X' and board[9]=='X') or (board[3]=='X' and board[7]=='X'):
120+
for i in possibleMove:
121+
if i in [2,4,6,8]:
122+
edgesOpen.append(i)
123+
124+
# randomly select a corner to move Into
125+
if len(edgesOpen)>0:
126+
move = selectRandom(edgesOpen)
127+
return move
128+
129+
# Same code repeat for edges also
130+
cornersOpen = []
131+
132+
# Check whether there is any corner is empty if find empty then we place
133+
# letter in that corner position
134+
135+
for i in possibleMove:
136+
if i in [1,3,7,9]:
137+
cornersOpen.append(i)
138+
139+
# randomly select a corner to move Into
140+
if len(cornersOpen)>0:
141+
move = selectRandom(cornersOpen)
142+
return move
143+
144+
145+
146+
147+
# Place letter at center pow
148+
if 5 in possibleMove:
149+
move = 5
150+
return move
151+
152+
# Check whether there is any edge is empty if find empty then we place
153+
# letter in that edge position
154+
155+
for i in possibleMove:
156+
if i in [2,4,6,8]:
157+
edgesOpen.append(i)
158+
159+
# randomly select a corner to move Into
160+
if len(edgesOpen)>0:
161+
move = selectRandom(edgesOpen)
162+
163+
return move
164+
165+
def selectRandom(li):
166+
return random.choice(li)
167+
168+
def isBoardFull(board):
169+
if board.count(' ') >1:
170+
return False
171+
else:
172+
return True
173+
174+
# Human = 'X'
175+
# Bot = 'O'
176+
177+
def main():
178+
'''
179+
Main function
180+
'''
181+
print(bright_cyan+"# ----------- Welcome to TIC TAC TOE ------------- #")
182+
name = input("Enter your name : ")
183+
print("👲 {} : \'X\' and 🤖 Computer : \'O\' ".format(name.capitalize()))
184+
print()
185+
186+
187+
printBoard(board)
188+
189+
while not (isBoardFull(board)):
190+
if not isWinner(board, 'O'):
191+
playerMove() # Ask player for next move
192+
printBoard(board) # print board
193+
else:
194+
print("\nOOPS O\'s won the game 😞 !!")
195+
break
196+
197+
if not isWinner(board, 'X'):
198+
move = compMove() # Ask computer for next move
199+
if move==0:
200+
print('Tie game !!')
201+
else:
202+
insertLetter('O',move)
203+
print("Computer enter \'O\' at Position : {}".format(move))
204+
printBoard(board) # print board
205+
else:
206+
print("\nYeah X\'s won the game 😎 !!")
207+
break
208+
209+
210+
if isBoardFull(board):
211+
print("Game over !!")
212+
213+
214+
main()
215+
216+
while True:
217+
print()
218+
ans = input("Do want to play again 😀 ... ? (Y|N) : ")
219+
print() # next line
220+
if ans.lower() == 'y' and ans.upper()=='Y':
221+
board = [' ' for i in range(10)]
222+
main()
223+
else:
224+
break
225+
226+
227+
228+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /