我正在制作Tic Tac Toe游戏,我确实有有效的代码,到目前为止,它可以满足我的要求。我只是想知道是否有一种方法可以缩短此功能。我的代码如下...
def EnterMove(board):
move = input("Enter your move (number between 1 - 9): ")
if move == '1':
board[0][0] = 'O'
elif move == '2':
board[0][1] = 'O'
elif move == '3':
board[0][2] = 'O'
elif move == '4':
board[1][0] = 'O'
elif move == '5':
board[1][1] = 'O'
elif move == '6':
board[1][2] = 'O'
elif move == '7':
board[2][0] = 'O'
elif move == '8':
board[2][1] = 'O'
elif move == '9':
board[2][2] = 'O'
#Making the playing board
board = []
for i in range(3):
row = [Empty for i in range(3)]
board.append(row)
board[0][0] = '1'
board[0][1] = '2'
board[0][2] = '3'
board[1][0] = '4'
board[1][1] = '5'
board[1][2] = '6'
board[2][0] = '7'
board[2][1] = '8'
board[2][2] = '9'
因此,就像我说的那样,到目前为止一切都可以很好地完成,我只是想知道是否有更简单的方法来构建开发板和构建EnterMove函数。非常感谢。
(注意:播放器移动将是“ O”,而计算机的移动将是“ X”,我将为我们提供与播放器移动功能几乎相同的代码,但只需使用{{1} }来决定计算机的移动方向
答案 0 :(得分:1)
您可以使用除法和取模来获取行和列:
def EnterMove(board):
move = int(input("Enter your move (number between 1 - 9): ")) - 1
board[move // 3][move % 3] = 'O'
board = []
for i in range(3):
row = [Empty for i in range(3)]
board.append(row)
for i in range(9):
board[i // 3][i % 3] = str(i + 1)