我是 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
uj5u.com熱心網友回復:
代碼非常復雜,但從我所見:
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].
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/382207.html
下一篇:將串列的索引連接到字串變數中
