2013-04-05 18 views
0

我正在编写一个用于制作井字游戏的python代码。我需要编写一个函数,它需要三个输入,board,x和y。棋盘是棋盘的当前显示,然后x和y的值为0,1或2.游戏设置为询问用户的坐标。如何在Python中改进井字检查代码

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,或者有更好的方法来检查而不是写所有的可能性。那么写这个更好的方法是什么?简洁明了。

+1

如果你的代码有效,codereview.stackexchange.com可能是一个更好的地方问。 (虽然我会先检查是否存在有关Python井字游戏实现的问题) – geoffspear 2013-04-05 16:49:28

+0

它可以正常工作,但随后我的这个函数的后续函数将无法正常工作,因为我认为我写这个函数的效果很差。 – chh 2013-04-05 16:51:29

+1

1.函数不应该知道最后一步。由于您有权访问“board”,因此您可以评估当前状态以确定派对是否赢了。 2.你可以使用for-loops来检查水平或垂直方向是否有3行。现在只需添加检查对角线。 3.将要检查的参与方作为参数(X或O) – Paranaix 2013-04-05 16:51:31

回答

2

我看不出为什么你需要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 

请注意,它使用列表理解和设置。如果你不熟悉这些,我建议在使用这个解决方案之前先学习它们。