I have made the following tic tac toe game which reads the current state of the board, stores it in entries, then I read a text file which has data in the format XOXXXO
O:6
where the part after :
is the number of box the AI should choose on the basis of the part before the :
so that the AI never loses. For some reason, it kinda stops working after my 3rd input.
main function
global win
global boxsize
entries = [[None] * 3, [None] * 3, [None] * 3]
windowsize = 300
boxsize = 100
win = GraphWin("Tic Tac Toe", windowsize, windowsize, autoflush=False)
for i in range(2):
hline = Line(Point(0, (windowsize / 3) * (i + 1)), Point(windowsize, (windowsize / 3) * (i + 1)))
hline.draw(win)
vline = Line(Point((windowsize / 3) * (i + 1), 0), Point((windowsize / 3) * (i + 1), windowsize))
vline.draw(win)
for i in range(1, 10):
print("Player 1: click a square.")
p1mouse = win.getMouse()
p1x = p1mouse.getX()
p1y = p1mouse.getY()
tic_tac_toe_X(entries, win, p1x, p1y)
if (check(entries) == True):
print("Player 1 is the winner.")
break
tic_tac_toe_O_ai(entries, win)
if (check(entries) == True):
print("Player 2 is the winner.")
break
print("Enter 1 to play again, 0 to Exit : ")
x = int(input())
if (x == 1):
win.close()
main()
else:
sys.exit()
Function that reads the text file and returns the box number move for the AI
Reads the .txt file to get the box number to move to
def ai_move(entries):
df = pd.read_csv("Dataset.txt", sep=":", names=['strings', 'moves'])
a = df[['strings']]
b = df[['moves']]
status = a.to_numpy()
next_move = b.to_numpy()
status = status.flatten()
next_move = next_move.flatten()
str = ""
for i in range(3):
for j in range(3):
if entries[i][j] == 'x':
str += "X"
elif entries[i][j] == 'o':
str += "O"
else:
str += " "
for i in range(2112):
if str == status[i]:
next = int(next_move[i])
return next
function that prints the 'O' for the AI
# Draws the 'O' for the AI
def tic_tac_toe_O_ai(entries, win):
box = ai_move(entries)
if (box == 0):
center = Point(50, 50)
entries[0][0] = 'o'
elif (box == 1):
center = Point(150, 50)
entries[1][0] = 'o'
elif (box == 2):
center = Point(250, 50)
entries[2][0] = 'o'
elif (box == 3):
center = Point(50, 150)
entries[0][1] = 'o'
elif (box == 4):
center = Point(150, 150)
entries[1][1] = 'o'
elif (box == 5):
center = Point(250, 150)
entries[2][1] = 'o'
elif (box == 6):
center = Point(50, 250)
entries[0][2] = 'o'
elif (box == 7):
center = Point(150, 250)
entries[1][2] = 'o'
elif (box == 8):
center = Point(250, 250)
entries[2][2] = 'o'
circle = Circle(center, 50)
circle.setOutline('green')
circle.setWidth(5)
circle.draw(win)