我正在处理一个实践问题,在这个问题中,我们将把一个列表输入到一个函数参数中,它将表示一个tic-tac-toe板,并返回该板的结果。也就是说,X胜、O胜、平局或无(空字符串)。你知道吗
我已经解决了这个问题,但是我想知道是否有一种方法可以将我的算法操作成一个循环,因为有人建议使用一个循环来比较主对角线的每个元素和所有元素 元素,然后检查两条对角线。我是python新手,所以我的解决方案可能会比它需要的时间长一些。如何实现一个循环来检查tic-tac趾板的结果?你知道吗
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 ''
首先,在蒂克塔乔只有八种获胜的方法。你有九个比较和返回语句,所以一个是多余的。事实上,在进一步的检查中,你检查了
00, 11, 22
三次(病例3、6和9),并且完全错过了02, 11, 20
病例。你知道吗在使用循环进行检查时,可以从对角线中拆分行/列检查,如下所示:
请注意,这确保了一行空单元格不会立即被任何人视为赢家。你只需要检查一个“真正的”玩家的胜利。我的意思是,如果第二行有一个实际的赢家,您不希望在第一行检测到三个空单元格并基于此返回指示。你知道吗
当然,有很多方法可以重构这样的代码,使其更易于阅读和理解。一种方法是分离出检查单个行的逻辑,然后为每一行调用该逻辑:
然后你可以使用:
在你的代码中,你要么得到赢家,要么得到一个空的指示,如果没有一个。你知道吗
相关问题 更多 >
编程相关推荐