Say I have a list like so:
board =
[[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0,]
that represents spaces on a 2D board.
If player one goes, it will change to 1.
If player two goes, it will change to 2.
Win conditions are: if a row or column is completely filled, or diagonally.
Here are my functions for horizontal or vertical winners:
def horizontal_winner(board, boxes):
'''
function will find if the horizontal win conditions apply
given 2 inputs. the board, a list and the number of boxes
- board - the 2D board of the game
- boxes - number of boxes per side
'''
for i in range(boxes):
player_1 = 0
player_2 = 0
for j in range(boxes):
if board[i][j] == 1:# first iteration - [1, 0, 0, 0, 0]
player_1 += 1
print("p1: " + str(player_1))
elif board[i][j] == 2:# first iteration - [2, 0, 0, 0, 0]
player_2 += 1
print("p2: " + str(player_2))
if player_1 == boxes:
return True
elif player_2 == boxes:
return False
def vertical_winner(board, boxes):
'''
function will find if the vertical win conditions apply
given 2 inputs. the board, a list and the number of boxes per side
- board - the 2D board of the game
- boxes - number of boxes per side
'''
for i in range(boxes):
player_1 = 0
player_2 = 0
for j in range(boxes):
if board[j][i] == 1:# first iteration - [1, 0, 0, 0, 0]
player_1 += 1
elif board[j][i] == 2:# first iteration - [2, 0, 0, 0, 0]
player_2 += 1
if player_1 == boxes:
return True
elif player_2 == boxes:
return False
How would I check diagonally?
First of all, recognize that there are only 2 diagonals. And the coordinates of each box on them is either (i, i) or (boxes-i-1, i) for some i in range(boxes). That should help you figure it out.