In Python (V2.7), I'm trying to make a ConnectFour game against a computer player. I've worked out a simple function to find 4 in a row (to determine the end of the game) and return TRUE if so, and now I'm trying use the same function to locate any 3 in a rows and return the location.
def finder(matrix, player,number):
for row in matrix:
count = 0
for item in row:
if item == player:
count +=1
if count == number:
return True
else:
count = 0
Where I can enter: finder(board, "X", 4) to know if four in a row is TRUE or still at default FALSE (and this DOES work). Now I want to try something like this:
def finder(matrix, player,number):
for row in matrix:
count = 0
for item in row:
if item == player:
count +=1
if count == number:
return True
location = row, item
return location
else:
count = 0
However this calls an error that I haven't initialized location, so I then set location = 0, 0. Now it just returns TRUE and the tuple (0,0). How can I get it to give the location of the last element of the 3 in a row?
Edit: I've tried returning the three-tuple: TRUE, row, item. However, the second part in the problem is how do I get the row and col numbers when the function is TRUE? The following code works to realize that there is a threat, but I can't get find a way to obtain the location of a threat given there exists a threat.
if finder(board, "X", 3) is True:
horizontal_threat = True
print row, item
You could do it by
for (i, row) in enumerate(matrix):
...
for (j, item) in row:
...
if (count==number):
return (i, j)
However, there are a few things wrong in the current code.