更改列表值并再次 运行 函数后,该值将重置为原来的值

After changing a list value and running the function again, the value resets to what it originally was

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

的方法

代码片段 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.

代码片段 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]]

第二个代码片段是前一个函数中使用的所有 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 对象都会将其所有索引重置为 ' '。我怎样才能防止这种情况发生?

你似乎从来没有把棋盘传给 main.py 中的实际玩家。 getTurnCoordinates()中的self.board指的是什么?

每个 Player 对象都有一个单独的 self.board。该代码没有用以前的值替换板;它显示的是另一块仍处于初始配置的板。

您需要重新考虑您的 class 和他们之间的关系。我会将其设计为一个 Board class 和两个 Player 实例,但您当然也可以使每个 Player 独立并使其 __init__ 方法接收引用共享 Board.