When I'm trying to do the move or more specifically change the element in the nested list, depending on what move to do, I'm instead changing the last element in all of the nested lists. I think I've constructed the list with the nested list correctly and that the problem lies in my method show_board. However I can't see what I'm doing wrong.
Here is my code:
class TicTacToe:
def __init__(self, sz):
self.sz = sz
self.board = []
def create_board(self):
"""Creating the game board with the given size."""
self.column = []
for _ in range(self.sz):
self.column.append('-')
self.board.append(self.column)
return self.board
def check_board(self):
"""Checking if the board is full."""
for row in self.board:
for spot in row:
if spot == '-':
return False
return True
def check_win(self, player):
"""Method for checking if a player has won the game. Evaluating rows, columns and
diagonals."""
win = None
#Checking rows for win:
for row in range(len(self.board)):
# win = True
for column in range(len(self.column)):
if self.board[row][column] == player:
continue
else:
win = False
return win
win = True
return win
#Checking columns for win:
for column in range(len(self.column)):
for row in range(len(self.board)):
if self.board[column][row] == player:
continue
else:
win = False
return win
win = True
return win
#Checking first diagonal for win:
for spot in range(len(self.board)):
if self.board[spot][spot] == player:
continue
elif self.board[spot][spot] == '-':
win = False
return win
win = True
return win
#Checking second diagonal for win:
for spot in range(len(self.board)):
if self.board[len(self.board)-spot-1][len(self.board)-spot-1] == player:
continue
elif self.board[len(self.board)-spot-1][len(self.board)-spot-1] == player:
win = False
return win
win = True
return win
def show_board(self):
"""Showing the current board"""
for row in self.board:
for item in row:
print(item, end=" ")
print()
def get_random_first_player(self):
"""Randomizing the first player."""
if random.randint(0,1) == 0:
player = 'X'
else:
player = 'O'
return player
def players_turn(self, player):
"""Changing the players turn."""
return 'X' if player == 'O' else 'O'
def place_move(self, row, column, player):
"""Placing the move, namely putting the players
symbol in the list at the given place."""
self.board[row][column] = player
def start(self):
self.create_board()
player = self.get_random_first_player()
while True:
print(f'It is {player} turn')
self.show_board()
row = int(input('Enter row: '))
column = int(input('Enter column: '))
print()
# row, column = list(
# map(int, input("Enter row and column numbers to fix spot: ").split()))
# print()
self.place_move(row - 1, column - 1, player)
if self.check_win(player):
print(f'{player} wins the game')
break
if self.check_board():
print('We have a draw')
break
player = self.players_turn(player)
print()
self.show_board()
v = TicTacToe(3)
v.start()