0

我正在编写一个用于制作井字游戏的 python 代码。我需要编写一个函数,它接受三个输入,板、x 和 y。棋盘是棋盘的当前显示,然后 x 和 y 的值是 0、1 或 2。游戏设置为向用户询问坐标。

def CheckVictory(board, x, y):

    #check if previous move was on vertical line and caused a win
    if board[0][y] == ('X') and board[1][y] == ('X') and board [2][y] == ('X'):
        return True
    if board[0][y] == ('O') and board[1][y] == ('O') and board [2][y] == ('O'):
        return True

    #check if previous move was on horizontal line and caused a win
    if board[x][0] == ('X') and board[x][1] == ('X') and board [x][2] == ('X'):
        return True
    if board[x][0] == ('O') and board[x][1] == ('O') and board [x][2] == ('O'):
        return True

    #check if previous move was on the main diagonal and caused a win
    if board[0][0] == ('X') and board[1][1] == ('X') and board [2][2] == ('X'):
        return True
    if board[0][0] == ('O') and board[1][1] == ('O') and board [2][2] == ('O'):
        return True
    #check if previous move was on the secondary diagonal and caused a win
    if board[0][2] == ('X') and board[1][1] == ('X') and board [2][0] == ('X'):
        return True
    if board[0][2] == ('O') and board[1][1] == ('O') and board [2][0] == ('O'):
        return True

    return False 
#end of CheckVictory function

该函数在游戏循环中被调用,如下所示

p_x, p_y = playerTurn(board)    #let player take turn
displayBoard(board)             #show board after move has been made
if CheckVictory(board, p_x, p_y):   #see if user has won
    print("CONGRATULATIONS, you win!")
    newGame(board)  #game over start new one
    continue

电脑转也是类似的

我觉得有更好的方法来编写这个函数。我觉得我应该更多地使用 x 和 y 或者有更好的方法来检查而不是写下所有的可能性。那么有什么更好的方法来写这个呢?使其简短明了。

4

1 回答 1

3

我看不出你为什么需要xy参数,你应该检查是否连续有三个 X 字母或三个 O 字母,你不需要坐标。而是先编辑棋盘,更新玩家输入的坐标,然后检查胜利是否发生。

这是我的做法,但如果你想使用你的方法 - 随意。你仍然可以从我的版本中学到一些东西。

def check_victory(board):
    combinations = [
        # horizontal
        ((0,0), (1,0), (2,0)),
        ((0,1), (1,1), (2,1)),
        ((0,2), (1,2), (2,2)),
        # vertical
        ((0,0), (0,1), (0,2)),
        ((1,0), (1,1), (1,2)),
        ((2,0), (2,1), (2,2)),
        # crossed
        ((0,0), (1,1), (2,2)),
        ((2,0), (1,1), (0,2))
    ]

    for coordinates in combinations:
        letters = [board[y][x] for x,y in coordinates]
        if len(set(letters)) == 1:
            return letters[0] # returns corresponding letter for winner (X/O)

    return False

请注意,它使用列表推导和集合。如果您不熟悉这些,我建议您在使用此解决方案之前学习它们。

于 2013-04-05T17:10:45.490 回答