我正在尝试制作这个游戏,但是我在检查赢的情况时遇到了一个问题(在我的checkWin()
函数中)。现在我使用X
作为测试用例,只检查第一列。我的问题是,如果第一栏没有X
,它总是告诉我我赢了。我很理解它为什么这么做,但是我不知道如何只让win
成为True
如果X
填充了X
的话。我仍然在研究这个程序的一些问题,但我想把它弄清楚。你知道吗
'''Tic-tac-toe game'''
import time
import random
def printBoard():
print "\n"
print " 1 | 2 | 3 "
print "____|____|____"
print " 4 | 5 | 6 "
print "____|____|____"
print " 7 | 8 | 9 "
print " | | "
print "\n"
def makeMove():
move = raw_input("\nOf the boxes numbered above, choose a move: ")
move = int(move)
return move
def boardCurrent(takenSpots):
print "",takenSpots[0]," |",takenSpots[1]," |",takenSpots[2]," "
print "____|____|____"
print "",takenSpots[3]," |",takenSpots[4]," |",takenSpots[5]," "
print "____|____|____"
print "",takenSpots[6]," |",takenSpots[7]," |",takenSpots[8]," "
print " | | "
print "\n"
def compMove(takenSpots):
move = random.randint(0,8)
if takenSpots[move] == " ":
takenSpots[move] = "O"
else:
compMove(takenSpots)
return takenSpots
def takeSpot(move):
takenSpots[move - 1] = "X"
return takenSpots
def checkWin(takenSpots):
win = False
for i in range(len(takenSpots)):
if takenSpots[i % 3 == 0]:
win = True
if win == True:
print "You win!"
else:
pass
def main():
print "\nWelcome to tic-tac-toe.\n"
printBoard()
person = makeMove()
boardCurrent(takeSpot(person))
print "Now the computer will go...\n"
time.sleep(1)
compMove(takenSpots)
boardCurrent(takenSpots)
boardCurrent(takeSpot(makeMove()))
print "Now the computer will go...\n"
time.sleep(1)
compMove(takenSpots)
boardCurrent(takenSpots)
boardCurrent(takeSpot(makeMove()))
checkWin(takenSpots)
boardCurrent(takeSpot(makeMove()))
boardCurrent(takeSpot(makeMove()))
takenSpots = [" "," "," "," "," "," "," "," "," "]
main()
这个循环搞砸了。首先,
takenSpots
是一个所有点的列表;您从不检查玩家是否真的获得了任何点。第二,您的if
检查列表中是否有任何点位于左列,而不是这些点是否形成一行中的3。第三,你没有任何迹象表明谁赢了。您需要检查特定玩家的胜利,或者有一个更详细的返回值来指示哪个玩家赢了。你知道吗执行检查的简单方法是列出每行、每列和每对角线的索引,然后迭代这些索引,并检查是否有人占用整行:
我刚才做了一个井字游戏。我用了两个巨大的If/And语句来检查两个团队中是否有赢家。虽然不是最好的方法,但最终还是奏效了。你知道吗
它是用visual basic编写的,但看起来有点像这样:
if (conerTL & middle & conerBR == "X" or etc...) {}else if (etc.. == "O"){}
相关问题 更多 >
编程相关推荐