在紙筆遊戲中,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。那麼,請任何人都可以幫助我呢? 謝謝
什麼錯誤? 另外,您的縮進是錯誤的。對於需要進一步縮進的文件,請參閱def – I82Much 2012-08-08 02:09:01
ya,我crrctd。謝謝你 – Fasna 2012-08-08 02:52:18