【问题标题】:List value being overwritten even though I am checking for it列表值被覆盖,即使我正在检查它
【发布时间】:2022-01-18 12:47:52
【问题描述】:

我是 python 新手,正在编写我的第一个项目。我正在尝试检查一个空间是否已被占用,而不是移动到那里。我似乎无法弄清楚为什么我的 move_player 方法会覆盖棋盘的索引值,即使我正在明确检查它(如果轮到 O 并且 X 已经被放置在 O 试图移动到的索引中,它只是覆盖它)。我也尝试过硬编码检查“X”和“O”而不是 player.player,但似乎无法弄清楚。它是否与 Python 的工作方式有关,还是我执行错了?

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

【问题讨论】:

  • 你的代码太多,也不完整。请添加一些遗漏的方法或将您的代码总结为简单的代码行以提高可读性。

标签: python list multidimensional-array


【解决方案1】:

代码非常复杂,但据我所知:

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

...

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

您正在检查[x,y],但分配给[x-1,y-1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2019-03-14
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多