- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我用 Python 制作了一个 TicTacToe 程序作为我的第一个小项目(使用 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("\n\n %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)
附:你不需要那些反斜杠。在括号内足以让 Python 知道表达式继续。
关于python - 检查 TicTacToe 获胜条件的有效方法//编辑 : How to check for tie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25876814/
我正在开发一个 CMD 批次。我想在里面做一些数学运算。这个公式:(x+1)100:y 所以批量处理,x = %x%, and y = %y% .我知道如何设置变量。现在,如何批量计算这个? (WIN
我正在使用 Electron 制作桌面应用程序,我制作了自己的最小化最大化和关闭按钮,所有这些按钮都工作正常,但是当您单击最大化并且它已经最大化时,它并没有取消最大化。这是我的代码: const $
目前我在这里面临着危机。 问题是,当我尝试使用 Windows 窗体的默认 WebBrowser 控件打开 G-Mail 时,它说浏览器不支持较新版本的 HTML 即 XHTML。 那么,有人能建议我
我遇到了一个让我发疯的问题。我在一个网站上工作,该网站在与主导航相同的 div 中有一个框。它一直显示到右边(栏的宽度为 100%),我需要它显示在带有主导航的 div 中(宽度 1020px) 我正
我是一名优秀的程序员,十分优秀!