【问题标题】:After changing a list value and running the function again, the value resets to what it originally was更改列表值并再次运行该函数后,该值将重置为原来的值
【发布时间】:2025-12-20 13:40:12
【问题描述】:

我正在为一个学校项目制作一个井字游戏,并制作了一个函数,该函数接受两个参数(rowcol)并从中生成一个Position 对象。 Position 对象有一个属性 index,它使用其 self.rowself.col 值生成 list。该函数是一个class Player 的方法。

代码 sn-p 1:

def getTurnCoordinates(self):
        row = int(input('In which row would you like to place the symbol ' + self.symbol + '?: '))
        col = int(input('In which column would you like to place the symbol ' + self.symbol + '?: '))
        pos = Position(row, col, self.symbol)
        if pos.isTaken():
            print("Position taken. Please choose another.")
            self.getTurnCoordinates()
        else:
            self.board.setPosition(pos.index, self.symbol)
            return self.board.getBoard()

这是获取参数的方法。其目的是获取int 值,这些值稍后将用于更改矩阵Board 中特定索引的值。

代码 sn-p 2:

class Board(object):
    def __init__(self):
        ROWS = COLS = 3
        self.board = [[Position(i%ROWS, i%COLS, ' ').symbol for i in range(COLS)] for i in range(ROWS)]
        self.display = f"""
 Tic  Tac  Toe
{self.getBoard()}
  0    1    2"""

    def getBoard(self):
        return '\n'.join(map(str, self.board))
        
    def setPosition(self, position, sym):
        self.board[position[0]][position[1]] = sym

    def getPosition(self, position: list):
        return self.board[position[0]][position[1]]

第二个代码 sn-p 是前一个函数中使用的所有 Board class 方法。 当我运行我的 main.py 文件时,我得到了这个输出。

main.py:

from classes.board import Board
from classes.player import Player

b = Board()

print(b.display)

p1 = Player('X')
p2 = Player('O')
players = Player.playerList

for ply in players:
    print(ply.getTurnCoordinates())

输出:

Tic  Tac  Toe
[' ', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
  0    1    2
In which row would you like to place the symbol X?: 0
In which column would you like to place the symbol X?: 0
['X', ' ', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
In which row would you like to place the symbol O?: 0
In which column would you like to place the symbol O?: 1
[' ', 'O', ' ']
[' ', ' ', ' ']
[' ', ' ', ' ']
>>>

每次运行该函数时,原始Board 对象将其所有索引重置为' '。我怎样才能防止这种情况发生?

【问题讨论】:

  • 请提供minimal, reproducible example。似乎Player 类将board 作为一个属性。难道每个实例都有不同的板子吗? Player 没有理由与董事会互动。它应该只包含有关玩家的功能,即请求坐标和符号。你应该有一个 Game 类来处理轮流并在 PlayerBoard 之间传递信息。

标签: python matrix indexing tic-tac-toe


【解决方案1】:

每个Player 对象都有一个单独的self.board。该代码不会用以前的值替换板;它正在显示一个仍在其初始配置中的不同板。

您需要重新考虑您的班级及其关系。我会将其设计为一个带有两个Player 实例的Board 类,但您当然也可以使每个Player 独立,并使其__init__ 方法接收对共享Board 的引用。

【讨论】:

    【解决方案2】:

    main.py 中,您似乎从未将棋盘传递给实际玩家。 self.boardin getTurnCoordinates() 指的是什么?

    【讨论】:

    • 虽然您很可能是对的,但您的答案与其说是答案不如说是评论。如果您觉得自己的答案在黑暗中被刺穿,请使用这些来要求澄清。
    • 我真的很想发表评论,但我不能。我还没有达到 50 声望限制,这真的很令人沮丧。
    • Answers shouldn't be used to bypass the reputation threshold for comments。即便如此,您确实尝试回答了这个问题,所以没关系。