I am trying to match diagonal elements of a list called 'grid[]' or elements of tic-tac-toe board input as one dimension. I want to make the board size dynamic and be able to check for 3 by 3, 4 by 4, 5 by 5 and so on.
I have already written code for checking columns and rows:
import math
grid = ['*', '*', '*', '*', '*', '*', '*', '*', '*']
dim = (round(math.sqrt(len(grid))))
count4 = 0
for i in range(dim):
if all(grid[count4 i] == "X" for i in range(dim)):
count3 = 0
print ("Player X win")
print ("-------------")
for i in range(dim):
print(grid[0 count3 : dim count3])
count3 = dim
print ("-------------")
count4 = dim
count4 = 0
for i in range(dim):
if all(grid[count4 i] == "X" for i in range(0, (dim * dim), dim )):
count3 = 0
print ("Player X win")
print ("-------------")
for i in range(dim):
print(grid[0 count3 : dim count3])
count3 = dim
print ("-------------")
count4 = 1
I am not able to figure out how do I check for diagonals (left and right). Can someone help?
Thank you.
CodePudding user response:
I think this works, at least for dim = 3
and dim = 4
:
diagonal1 = [(dim 1) * i for i in range(dim)]
diagonal2 = [(i 1) * (dim - 1) for i in range(dim)]
if all(grid[d] == "X" for d in diagonal1):
print ("Player X win")
count3 = 0
print ("-------------")
for i in range(dim):
print(grid[0 count3 : dim count3])
count3 = dim
print ("-------------")
if all(grid[d] == "X" for d in diagonal2):
count3 = 0
print ("Player X win")
print ("-------------")
for i in range(dim):
print(grid[0 count3 : dim count3])
count3 = dim
print ("-------------")