0

I am writing a tic tac toe game and I am stuck at the step where code is supposed to check if a player has won VERTICALLY, my friend who knows c++ told me to first iterate thru COLUMNS and then ROWS to make the process easier. Not sure how it works in python.

So for example player enters 4x4 table and after a while this is his result.

[0,1,0,0]
[0,1,0,0]
[0,1,0,0]
[0,1,0,0]

He said that if I iterate thru columns first and then rows then it would be like:

CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0

and then column index changes to 1

0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0

sorry for bad explanation...

2 Answers2

0

something like this?

In [22]: import numpy as np

In [23]: a=np.array(range(15)).reshape(3,5)

In [24]: a
Out[24]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [25]: [ [x[i] for x in a] for i in range(a.shape[1])]
Out[25]: [[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14]]
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • if i have `for row in table:` and inside of it `for column in row` -- How do I change the order? –  Nov 05 '16 at 00:45
  • my `x in a` corresponds to your `row in table`. Column will be accessed by index at each row, so you need the number of columns (`shape[1]`) and iterate over them. – karakfa Nov 05 '16 at 01:14
0

You can use the built-in all() function to check if all elements are True,
and zip(*table) notation for Row-to-Column Transposition

mytable1 = [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
mytable2 = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
mytable3 = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
mytable4 = [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable5 = [[0,1,0,0],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable6 = [[2,1,0,0],[2,0,1,0],[2,1,0,0],[2,0,1,0]]
mytable7 = [[2,1,0,0],[0,2,1,0],[0,1,2,0],[0,0,1,2]]

def hasWon(table,player_no):
    #check rows
    for row in table: 
        if all([e==player_no for e in row]):
            return True
    #check columns
    for column in zip(*table): 
        if all([e==player_no for e in column]):
            return True
    #check diagonals
    if all([table[i][i]==player_no for i in range(len(table)) ]): 
        return True
    if all([table[-i-1][i]==player_no for i in range(len(table))]):
        return True
    return False



print(hasWon(mytable1,1))
print(hasWon(mytable2,1))
print(hasWon(mytable3,1))
print(hasWon(mytable4,1))
print(hasWon(mytable5,1))
print(hasWon(mytable6,2))
print(hasWon(mytable7,2))

Outputs:

True
True
True
True
False
True
True
Community
  • 1
  • 1
Sweeney Todd
  • 880
  • 1
  • 11
  • 25