所以我用Python编写了一个TicTacToe程序作为我的第一个小项目(使用3.4)。在
到目前为止,它是有效的,但是我想知道是否可以简化win条件检查
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("\n\n %s wins!" % playerChange(player))
break
由于所有的检查,win条件检查看起来相当笨拙。有没有办法压缩它?在
编辑:刚刚注意到我的程序有个错误。我没有任何平局检查,进入一个平局将导致你卡住-我如何检查平局?我不知道我怎么能做到。在
一种常见的方法是将获胜状态存储在一个紧凑的数据结构中,例如
然后在它们之间循环,例如
^{pr2}$(您需要同时对X和O运行这个,即添加一个外部循环并使用其变量而不是内部的文本X/O)
另外,你不需要那些反斜杠。在圆括号内就足以让Python知道表达式继续。在
相关问题 更多 >
编程相关推荐