Pyt*_*oob 0 python loops for-loop while-loop
我正在研究一个实践问题,我们要在一个函数参数中输入一个列表,它将代表一个tic tac toe board,并返回董事会的结果.也就是说,X获胜,O获胜,平局或无(空字符串).
我已经解决了,但我想知道是否有一种方法可以将我的算法操作成循环,因为建议使用循环来比较主对角线的每个元素与其相交的行和列的所有元素,然后检查两个对角线.我是python的新手,所以我的解决方案可能需要更长的时间.如何实施一个循环来检查tic tac toe board的结果?
def gameState (List):
xcounter=0
ocounter=0
if List[0][0]==List[0][1] and List[0][0]==List[0][2]:
return List[0][0]
elif List[0][0]==List[1][0] and List[0][0]==List[2][0]:
return List[0][0]
elif List[0][0]==List[1][1] and List[0][0]==List[2][2]:
return List[0][0]
elif List[1][1]==List[1][2] and List[1][1]==List[1][0] :
return List[1][1]
elif List[1][1]==List[0][1] and List[1][1]==List[2][1]:
return List[1][1]
elif List[1][1]==List[0][0] and List[1][1]==List[2][2]:
return List[1][1]
elif List[2][2]==List[2][0] and List[2][2]==List[2][1]:
return List[2][2]
elif List[2][2]==List[1][2] and List[2][2]==List[0][2]:
return List[2][2]
elif List[2][2]==List[1][1] and List[2][2]==List[0][0]:
return List[2][2]
for listt in List:
for elm in listt:
if elm=="X" or elm=="x":
xcounter+=1
elif elm=="O" or elm=="o":
ocounter+=1
if xcounter==5 or ocounter==5:
return "D"
else:
return ''
Run Code Online (Sandbox Code Playgroud)
首先,只有八种方式可以赢得TicTacToe.你有九个比较和返回语句,所以一个是多余的.事实上,在进一步的检查中,检查00, 11, 22 3次(例3,6和9),完全错过了02, 11, 20情况.
在使用循环检查方面,您可以从对角线中拆分行/列检查,如下所示:
# Check all three rows and columns.
for idx in range(3):
if List[0][idx] != ' ':
if List[0][idx] == List[1][idx] and List[0][idx] == List[2][idx]:
return List[0][idx]
if List[idx][0] != ' ':
if List[idx][0] == List[idx][1] and List[idx][0] == List[idx][2]:
return List[idx][0]
# Check two diagonals.
if List[1][1] != ' ':
if List[1][1] == List[0][0] and List[1][1] == List[2][2]:
return List[1][1]
if List[1][1] == List[0][2] and List[1][1] == List[2][0]:
return List[1][1]
# No winner yet.
return ' '
Run Code Online (Sandbox Code Playgroud)
请注意,这样可以确保一排空单元格不被任何人立即选为胜利.你需要只检查"真正的"玩家的胜利.这样,我的意思是你不想在第一行中检测到三个空单元格,如果第二行有实际的赢家,则返回基于该单元格的指示.
当然,有许多方法可以重构这些代码,使其更容易阅读和理解.一种方法是分离出检查单行的逻辑,然后为每行调用它:
# Detect a winning line. First cell must be filled in
# and other cells must be equal to first.
def isWinLine(brd, x1, y1, x2, y2, x3, y3):
if brd[x1][y1] == ' ': return False
return brd[x1][y1] == brd[x2][y2] and brd[x1][y1] == brd[x3][y3]
# Get winner of game by checking each possible line for a winner,
# return contents of one of the cells if so. Otherwise return
# empty value.
def getWinner(brd):
# Rows and columns first.
for idx in range(3):
if isWinLine(brd, idx, 0, idx, 1, idx, 2): return brd[idx][0]
if isWinLine(brd, 0, idx, 1, idx, 2, idx): return brd[0][idx]
# Then diagonals.
if isWinLine(brd, 0, 0, 1, 1, 2, 2): return brd[1][1]
if isWinLine(brd, 2, 0, 1, 1, 0, 2): return brd[1][1]
# No winner yet.
return ' '
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:
winner = getWinner(List)
Run Code Online (Sandbox Code Playgroud)
在您的代码中,如果没有,您将获得胜利者或空的指示.
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |