在tictactoe中胜出

时间:2013-12-18 07:00:57

标签: python python-2.7

我正在尝试制作这款游戏​​,但我遇到了检查胜利的问题(在我的checkWin()功能中)。现在我使用X作为测试用例,只检查第一列。我的问题甚至是,如果在第一列中没有X,它总会告诉我我赢了。我理解为什么会这样做,但我不知道如何只让win成为True ,如果这些框填充了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() 

2 个答案:

答案 0 :(得分:1)

    for i in range(len(takenSpots)):
        if takenSpots[i % 3 == 0]:
            win = True

这个循环搞砸了。首先,takenSpots是所有点的列表;你永远不会检查玩家是否真的占据了任何位置。其次,您的if检查列表中的任何点是否在左列中,而不是点是否连续形成3。第三,你没有任何迹象表明赢了。您需要检查特定玩家的胜利,或者获得更多信息,以指示哪个玩家获胜。

执行检查的简单方法是为每行,每列和对角线制作一个索引列表,然后迭代这些索引并检查是否有人占用整行:

win_positions = [
    (0, 3, 6),
    (1, 4, 7),
    (2, 5, 8),
    (0, 1, 2),
    (3, 4, 5),
    (6, 7, 8),
    (0, 4, 8),
    (2, 4, 6),
]
for line in win_positions:
    if all(takenSpots[position] == player for position in line):
        return some_sort_of_indicator_that_that_player_won

答案 1 :(得分:0)

我刚才做了一个Tic-Tac-Toe游戏。我使用了两个巨大的If / And语句来检查任一团队的胜利者。这不是最好的方式,但它最终有效。

它是在visual basic中,但看起来有点像这样: if (conerTL & middle & conerBR == "X" or etc...) {}else if (etc.. == "O"){}