【发布时间】:2025-12-20 13:40:12
【问题描述】:
我正在为一个学校项目制作一个井字游戏,并制作了一个函数,该函数接受两个参数(row 和col)并从中生成一个Position 对象。 Position 对象有一个属性 index,它使用其 self.row 和 self.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类来处理轮流并在Player和Board之间传递信息。
标签: python matrix indexing tic-tac-toe