如何找到领带游戏python

时间:2014-03-01 11:08:08

标签: python

嗨我正在制作这个tic tac toe游戏,我看了一些教程,但是没有任何游戏可以以领带游戏结束我试图制作一个但是当游戏出现时游戏冻结不用担心关于我的芬兰变量和评论

import random

board = [0,1,2,
3,4,5,
6,7,8]

def show():
    print board[0], '|',board[1],'|',board[2]
    print '----------'
    print board[3], '|',board[4],'|',board[5]
    print '----------'
    print board[6], '|',board[7],'|',board[8]

def checkLine(char, spot1, spot2, spot3):
    if (board[spot1] == char) and (board[spot2] == char) and (board [spot3] == char)    :
        return True
    else:
        return False

def checkAll(char):
    ret = False
    if checkLine(char, 0, 1, 2):
        ret = True
    if checkLine(char, 0,3, 6):
        ret = True
    if checkLine(char, 1, 4, 7):
        ret = True
    if checkLine(char, 2, 5, 8):
        ret = True
    if checkLine(char, 6, 7, 8):
        ret = True
    if checkLine(char, 3, 4, 5):
        ret = True
    if checkLine(char, 2, 4, 6):
        ret = True
    if checkLine(char, 0, 4, 8):
        ret = True
    return ret

moves = range(9) 
numindex = 1
ratkennut = False
while moves:
    show()

    input = raw_input("Put x: ")
    try:
        val = int(input)
        input = int(input)
    except ValueError:
        print("Input number!")
        input = raw_input("Put x: ")
        input = int(input)
    if input in moves:
        moves.remove(input)

    if board [input] != 'x' and board[input] != 'o':
        board[input] = 'x'

        if checkAll('x') == True:
            print "~~ X Won ~~"
            ratkennut = True
            break;

        while moves:
            random.seed() #Gives opponents move
            opponent = random.choice(moves)
            moves.remove(opponent)

            if board[opponent] != 'o' and board[opponent] != 'x':
                board[opponent] = 'o'

                if checkAll('o') == True:
                    print "~~ O Won ~~"
                    ratkennut = True
                break;
    else:
        print 'This  spot is taken'
else:
    print "Tie!"

问题:当游戏以领带游戏结束时,这段代码有什么问题它冻结了我需要按ctrl + c如何让它找到领带游戏并打印“领带游戏” 我编辑了它,现在它真的很棒!

2 个答案:

答案 0 :(得分:2)

对手的randint循环中的while移动选择可以无限期地运行,尤其是当剩余的有效移动数量变小时。相反,列出有效的移动,并从中移动list.remove()

moves = range(9) 

这简化了用户的行动:

if input in moves:
    moves.remove(input)

对手的举动:

opponent = random.choice(moves)
moves.remove(opponent)

确定游戏结束:

while moves:
    ...
else:
    print "It's a tie."

答案 1 :(得分:1)

你可以计算你的动作,在一个tic tac toe游戏中只有9个动作。

你想要这样的东西:

if  not checkAll('o') and  not checkAll('x') and moves == 9:
    print "Tie Game"
    break