2012-08-08 78 views
-1

在紙筆遊戲中,2名玩家輪流在3×3的方格板上標記'X'和'O'。在垂直,水平或對角線條紋中成功標記連續「X」或「O」的玩家贏得比賽。編寫一個函數來確定一個井字遊戲的結果。pyschools-tictactoe

例子

>>> tictactoe([('X', ' ', 'O'), 
       (' ', 'O', 'O'), 
       ('X', 'X', 'X') ]) 
"'X' wins (horizontal)." 
>>> tictactoe([('X', 'O', 'X'), 
...   ('O', 'X', 'O'), 
...   ('O', 'X', 'O') ]) 
'Draw.' 
>>> tictactoe([('X', 'O', 'O'), 
...   ('X', 'O', ' '), 
...   ('O', 'X', ' ') ]) 
"'O' wins (diagonal)." 
>>> tictactoe([('X', 'O', 'X'), 
...   ('O', 'O', 'X'), 
...   ('O', 'X', 'X') ]) 
"'X' wins (vertical)." 




def tictactoe(moves): 
for r in range(len(moves)): 
    for c in range(len(moves[r])):  
     if moves[0][c]==moves[1][c]==moves[2][c]: 
      a="'%s' wins (%s)."%((moves[0][c]),'vertical') 
     elif moves[r][0]==moves[r][1]==moves[r][2]: 
      a="'%s' wins (%s)."%((moves[r][0]),'horizontal') 
     elif moves[0][0]==moves[1][1]==moves[2][2]: 
      a="'%s' wins (%s)."%((moves[0][0]),'diagonal') 
     elif moves[0][2]==moves[1][1]==moves[2][0]: 
      a="'%s' wins (%s)."%((moves[0][2]),'diagonal') 
     else: 
      a='Draw.' 
print(a) 

我寫了這樣的代碼,我的範圍不工作(我認爲)。因爲它將r和c的值設爲3,而不是0,1,2,3。那麼,請任何人都可以幫助我呢? 謝謝

+1

什麼錯誤? 另外,您的縮進是錯誤的。對於需要進一步縮進的文件,請參閱def – I82Much 2012-08-08 02:09:01

+0

ya,我crrctd。謝謝你 – Fasna 2012-08-08 02:52:18

回答

0

當玩家獲勝時,您的循環不會退出。我想嘗試這樣的事:

def tictactoe_state(moves): 
    for r in range(len(moves)): 
    for c in range(len(moves[r])): 
     if moves[0][c] == moves[1][c] == moves[2][c]: 
     return "'%s' wins (%s)." % (moves[0][c], 'vertical') 
     elif moves[r][0] == moves[r][1] == moves[r][2]: 
     return "'%s' wins (%s)." % (moves[r][0], 'horizontal') 
     elif moves[0][0] == moves[1][1] == moves[2][2]: 
     return "'%s' wins (%s)." % (moves[0][0], 'diagonal') 
     elif moves[0][2] == moves[1][1] == moves[2][0]: 
     return "'%s' wins (%s)." % (moves[0][2], 'diagonal') 

    # You still have to make sure the game isn't a draw. 
    # To do that, see if there are any blank squares. 

    return 'Still playing' 

另外,我想移動if語句檢查對角線出循環。它們不取決於rc

+0

謝謝你Blender,:) – Fasna 2012-08-08 02:46:25

0

試試這個..

def tictactoe(moves): 
    for r in range(len(moves)): 
     for c in range(len(moves[r])):  
      if moves[0][c]==moves[1][c]==moves[2][c]: 
       return "\'%s\' wins (%s)." % ((moves[0][c]),'vertical') 
      elif moves[r][0]==moves[r][1]==moves[r][2]: 
       return "\'%s\' wins (%s)."%((moves[r][0]),'horizontal') 
      elif moves[0][0]==moves[1][1]==moves[2][2]: 
       return "\'%s\' wins (%s)."%((moves[0][0]),'diagonal') 
      elif moves[0][2]==moves[1][1]==moves[2][0]: 
       return "\'%s\' wins (%s)."%((moves[0][2]),'diagonal') 
    return 'Draw.' 
+0

請解釋爲什麼這個工程。這可以防止複製和粘貼,而不會完全理解。 – rayryeng 2014-07-14 04:04:37