Reputation: 39
I'm still new to OOP programming and writing compact code so there probably something I'm overlooking, I'm trying to figure out a way to check for vertical wins and diagonal wins in tic-tac-toe, I have horizontal already.
If possible is there a way to incorporate the other two ways into something like what I already have?
#creates the gameboard that stores if spaces are open or not
game_board = [ [0,0,0], [0, 0, 0], [0, 0, 0,] ]
#0 = open space
#1 = O
#2 = X
#check for winners horizontaly
def find_winner():
# y represents the y axis
for y in range(3):
if game_board[y][0] == game_board[y][1] == game_board[y][2] != 0:
#returns if the X or 0 has won
return game_board[y][0]
#returns 0 if no-one has won
return 0
Upvotes: 1
Views: 687
Reputation: 768
game_board = [ [1, 0, 1],
[0, 1, 0],
[0, 1, 0] ]
# Horizontals
h = [str(i+1) + ' Row' for i, v in enumerate(game_board) if sum(v) == 3]
# Verticals
v = [str(i+1) + ' Col' for i in range(3) if sum([j[i] for j in game_board]) == 3]
# Diagonals
d = [['Left Diag', '','Right Diag'][i+1] for i in [-1, 1] if sum([game_board[0][1+i], game_board[1][1]], game_board[2][1-i]) == 3]
if any([h,v,d]):
print('You won on:', h, v, d)
else:
print('No win yet')
Upvotes: 1
Reputation: 178
Maybe this can help, these are the two functions for vertical and diagonal checking
# Checks for vertical row
def win(game_board, player):
for x in range(len(game_board)):
win = True
for y in range(len(game_board)):
if game_board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
# Checks diagonal win
def diag_win(game_board, player):
win = True
y = 0
for x in range(len(game_board)):
if game_board[x, x] != player:
win = False
win = True
if win:
for x in range(len(game_board)):
y = len(game_board) - 1 - x
if game_board[x, y] != player:
win = False
return win
Feel free to comment if you have some queries or suggestions. For the above function, the players are selected at random. It is a good practice to use functions
Upvotes: 1
Reputation: 27577
You can add more if
statements like this:
game_board = [ [0, 0, 0],
[0, 0, 0],
[0, 0, 0,] ]
def find_winner():
for y in range(3):
if game_board[y][0] == game_board[y][1] == game_board[y][2] != 0: # Check horizontal
return game_board[y][0]
if : # Check vertical
return game_board[0][y]
if game_board[0][0] == game_board[1][1] == game_board[2][2] != 0 or game_board[0][2] == game_board[1][1] == game_board[2][0] != 0: # Check diagonal
return game_board[1][1]
return 0
Upvotes: 5