所以我制作了一个TicTacToe程序,作为我在Python中的第一个小项目(使用3.4)
到目前为止,它是有效的,但我想知道是否有可能简化获胜条件检查
import os
clear = lambda: os.system('cls')
def playerChange(player): #Function for easily swapping out players
if player == "X":
return "O"
else:
return "X"
player = "X" #Setting initial player
tttfield = ["1","2","3","4","5","6","7","8","9"] #setting up tictactoe field
clear()
while True:
print("", tttfield[0], "|", tttfield[1], "|", tttfield[2], "n",
"---------", "n",
tttfield[3], "|", tttfield[4], "|", tttfield[5], "n",
"---------", "n",
tttfield[6], "|", tttfield[7], "|", tttfield[8], "n")
choice = 0
choice = input("n%s, choose a slot: " % player)
if choice in tttfield:
tttfield[int(choice)-1] = player #marks space
player = playerChange(player) #changes player
else:
input("Not a valid number! Choose again!")
clear()
#check for win condition
if ((tttfield[0]==tttfield[1]==tttfield[2]) or
(tttfield[3]==tttfield[4]==tttfield[5]) or
(tttfield[6]==tttfield[7]==tttfield[8]) or
(tttfield[0]==tttfield[3]==tttfield[6]) or
(tttfield[1]==tttfield[4]==tttfield[7]) or
(tttfield[2]==tttfield[5]==tttfield[8]) or
(tttfield[0]==tttfield[4]==tttfield[8]) or
(tttfield[6]==tttfield[4]==tttfield[2])) :
clear()
input("nn %s wins!" % playerChange(player))
break
由于所有的检查,获胜条件检查看起来相当笨拙。有没有办法压缩它?
编辑:刚刚注意到我的程序中有个错误。我没有任何领带检查,遇到领带的情况会让你陷入困境——我该如何检查领带?我不知道我该怎么做。
一种常见的方法是将获胜状态存储在紧凑的数据结构中,例如
winners = [[0, 1, 2], [3, 4, 5] ...]
然后循环通过它们,例如
for squares in winners:
if all(tttfield[square]=='x' for square in squares):
print "X wins!"
(您希望对X和O都运行此操作,即添加一个外部循环,并在内部使用其变量而不是文字X/O)
p.s.你不需要那些反斜杠。位于圆括号内就足以让Python知道表达式在继续。