So i made a tic-tac-toe game in python and the main game board is basically a list of lists as follows:
board = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "],
]
Making a move in the game would modify this board
variable. Now I have to check after each move whether a player has won or the game has tied. Basically have to check every configuration in board
which would in an actual game be a win.
For which I have the following function, defining win_lines
as a list which contains all the possible winning lines.
def check_has_won(board: list, player):
win_lines = [
board[0], # top row
board[1], # mid row
board[2], # bottom row
[row[0] for row in board], # first col
[row[1] for row in board], # sec col
[row[2] for row in board], # third col
[board[0][0], board[1][1], board[2][2]], # diag 1
[board[0][2], board[1][1], board[2][0]], # diag 2
]
for line in win_lines:
if " " not in line:
if foe[player] not in line: #foe = {"X":"O", "O":"X"}
return True # player has won
else:
for row in board:
if " " in row: # implies theres still empty positions to play
return False
else: # Game has tied
return None
The problem I have doing it this way is:
I find it inefficient to keep defining the win_lines
variable after every move, it would be nice if it would modify itself whenever board
is modified in a move. So in a way linking the correct elements of board
with elements of win_lines
. Is this possible? If so, how could I do it?
Possibly helpful code: (If there's more required code I'm missing, let me know.)
def make_move(board, player, position):
"""
checks 'board' to see if 'position' is playable. if so plays there, else prompts again\n
"""
board_indices = [
None, # so that `position` matches the index of this list.
# make first element of `board_indices` (index 0) = None
[0, 0], #e.g `position = 1` corresponds with index [0][0] in `board`
[0, 1],
[0, 2],
[1, 0],
[1, 1], # another e.g. `position = 5` corresponds with index [1][1] in `board`
[1, 2],
[2, 0],
[2, 1],
[2, 2],
]
f_index, s_index = board_indices[position]
if board[f_index][s_index] == " ":
board[f_index][s_index] = player
return None
else:
position = input("Choose a new position: ")
return make_move(board, player, position)