+ 4

# [Challenging question] checking 2d array[tic tac toe]

I already did my Tic Tac Toe game in python using Minimax algorithm( only 3x3 board) . So I decided i will try to make tic tac toe AI for bigger boards. Problem I had was my checkWin function. It is not that easy to check if anybody win,if player can choose size of the board(for example 5x10, 7x2). Today finally i completed this checkWin function. I did not use any library like numpy(if i did it would be much, much easier). So i am asking: How would you make this checkWin function. I am still learning python and i am interested how other programmers would do it. (It has to check board vertically, horizontally and all diagonals). More information about my solution in my code. https://code.sololearn.com/c785sAlA6AUS/?ref=app

5 Answers

+ 7

A Tic Tac Toe board could be a square if m==n or a rectangle if m < n.
One lazy approach I would use is to test each index of a player set vertically, horizontally and diagonally.
vertical, and horizontal check are quite simple, if the board size is 5*5 and I've got a selected tile at these indexes
1. [0, 0]
2. [3, 2]
3. [8, 7]
You just have to loop through this indexes and check if
1. All the tiles are filled up
2. All the tiles are instance of the selected tiles.
Diagonal check need some calculations, if the selected tiles is located at index [0, 5], it's clear you only need to check left-diagonal because the current position would be
Where tS = tileSize
diffX = x2(5)*tS - x1(0)*tS;
diffY = x2(0) * tS - x1(0) * tS.
abs(diffY) > abs(diffX);
Get the bottom-left tile at [5, 0];
No_move = dist_bottom_left / tS;
Loop to the maximum of No_move, and for each tile
x = floor(current / ts)
y = floor(current / tS)
Return Win If all instance array index for [y * tileSize + x] == selected

+ 6

It's also advice to normalise each tiles so you won't be confused, and also you need to add an untidy values when checking diagonally, for example if you check this index diagonally [3.5, 5]
And you floor the result, you'll likely be checking a different tile of [3, 5+1] instead you should add 0.9 to each value of y, so floor [3.5, 5+1-0.9] = [3, 5]

+ 1

I dont understand, I just tested it horizontally, vertically and diagonally, everything seemed to pass. What issues are you experiencing?

+ 1

Mirielle I am sorry, but I don't understand you. Could you please illustrate this in Sololearn playgroud, like I did with my solution(it should have 2d array, which represents playing board and checkWin function, which returns True if player won, False if player did NOT win) Thanks.
https://code.sololearn.com/c785sAlA6AUS/?ref=app