循环更改井字游戏矩阵中的值?

我正在制作一个井字游戏,并且我确实有工作代码,并且到目前为止它可以完成我想要它做的事情。我只是想知道是否有办法缩短这个功能。我的代码如下...


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”,我将向我们提供与玩家移动功能几乎相同的代码,但只是使用str(random.randint(1,9))它来决定计算机的移动)


侃侃无极
浏览 83回答 1
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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python