Home > OS >  List value being overwritten even though I am checking for it
List value being overwritten even though I am checking for it

Time:12-16

I'm new to python and writing my first project. I'm trying to implement a check that if a space is already occupied, not to move there. I can't seem to figure out why my move_player method overwrites the index value of the board even though I am explicitly checking it (If it is O's turn and X has already been placed in the index O is trying to move to, it just overwrites it). I have tried hard coding the check for 'X' and 'O' instead of player.player as well but can't seem to figure it out. Does it have to do something with how Python works or am I implementing it wrong?

class Player:
    def __init__(self, player):
        self.player = player


class Board:
    def __init__(self):
        self.board = [[' ' for i in range(3)] for j in range(3)]


    def display_board(self):
        print('---------')
        for row in self.board:
            print('| ', end='')
            for col in row:
                print(f'{col} ', end='')
            print('|')
        print('---------')


    def move_player(self, player):
        try:
            p1 = Player('X')
            p2 = Player('O')
            coordinates = [int(i) for i in input("Enter coordinates for move: ").split()]
            xCoordinate = coordinates[0]
            yCoordinate = coordinates[1]
            if ((self.board[xCoordinate][yCoordinate] == p1.player) or 
                (self.board[xCoordinate][yCoordinate] == p2.player)):
                print("That space is occupied, please choose another one.")
                self.move_player(player)
            else:
                self.board[xCoordinate - 1][yCoordinate - 1] = player.player
        except (ValueError, IndexError):
            print("Please only enter numbers between 1 and 3.")
            self.move_player(player)


    def has_won(self, player):
        if self.check_diagonal(player):
            return True
        elif self.check_across(player):
            return True
        elif self.check_down(player):
            return True
        return False


if __name__ == '__main__':
    board = Board()
    player1 = Player('X')
    player2 = Player('O')
    player = player1

    while True:
        board.display_board()
        board.move_player(player)

        if board.has_won(player):
            board.display_board()
            print(f'{player.player} wins!!!')
            break

        if player == player1:
            player = player2
        else:
            player = player1

CodePudding user response:

The code is very convoluted but from what I can see:

        if ((self.board[xCoordinate][yCoordinate] == p1.player) or 
            (self.board[xCoordinate][yCoordinate] == p2.player)):

...

            self.board[xCoordinate - 1][yCoordinate - 1] = player.player

You are checking [x,y] but assigning to [x-1,y-1].

  • Related