Python 3 NoneType是不可订阅的错误

时间:2013-11-01 04:19:35

标签: python

我遇到了这个错误的严重问题。这是家庭作业,所以我只是在寻找一些关于这个的提示...我已经看了其他问题,但他们没有帮助,所以希望这没关系。我是Python的新手。 :)我正在做一个Tic Tac Toe游戏。我确信它还有其他一些问题,但我现在主要担心的是这个错误。这是我的代码:::

    scoreList = []
"""keeps track of all of the scores, moves, and indexes as tuples for each
        winning board"""

def getEmptySpaces(gameBoard):
    return gameBoard.count('-')

def winner(gameBoard):
    case1 = gameBoard[0]+gameBoard[1]+gameBoard[2]
    case2 = gameBoard[0]+gameBoard[3]+gameBoard[6]
    case3 = gameBoard[0]+gameBoard[4]+gameBoard[8]
    case4 = gameBoard[1]+gameBoard[4]+gameBoard[7]
    case5 = gameBoard[2]+gameBoard[5]+gameBoard[8]
    case6 = gameBoard[2]+gameBoard[4]+gameBoard[6]
    case7 = gameBoard[3]+gameBoard[4]+gameBoard[5]
    case8 = gameBoard[6]+gameBoard[7]+gameBoard[8]

    if case1 == 'xxx' or case1 == 'ooo':
        return True
    elif case2 == 'xxx' or case2 == 'ooo':
        return True
    elif case3 == 'xxx' or case3 == 'ooo':
        return True
    elif case4 == 'xxx' or case4 == 'ooo':
        return True
    elif case5 == 'xxx' or case5 == 'ooo':
        return True
    elif case6 == 'xxx' or case6 == 'ooo':
        return True
    elif case7 == 'xxx' or case7 =='ooo':
        return True
    elif case8 == 'xxx' or case8 == 'ooo':
        return True
    else:
        return False

def draw(gameBoard):
    if getEmptySpaces(gameBoard) ==0:
        if not winner(gameBoard):
            return True
        return False
    return False

def markX(gameBoard,index):
    gameBoard = gameBoard[:index] + 'x' + gameBoard[index+1:]

def markO(gameBoard,index):
    gameBoard = gameBoard[:index] + 'o' + gameBoard[index+1:]

def fitnessFunction(gameBoard):
    #only runs if end game or if all full
    if draw(gameBoard):
        return 0
    else:
        emptySpaces = getEmptySpaces(gameBoard)
        if emptySpaces %2 == 0:
            #max won
            return (emptySpaces + 1) *1
        else:
            #max lost
            return (emptySpaces + 1) *-1

def maxTurn(gameBoard):
    if getEmptySpaces(gameBoard) %2 == 0:
        return True
    return False

def minTurn(gameBoard):
    if getEmptySpaces(gameBoard) %2 != 0:
        return True
    return False

def miniMax(gameBoard):
    if winner(gameBoard) or getEmptySpaces(gameBoard) ==0:
        return fitnessFunction(gameBoard)
    else:
        emptyIndexes = [] 
        count = 0
        for char in str(gameBoard):
            if char == "-":
                emptyIndexes.append(count)
            count +=1             
        for index in emptyIndexes:
            xChild = markX(gameBoard,index)
            output = miniMax(xChild) #returns score
            scoreList.append((output,'x',index))

            oChild = markO(gameBoard,index)
            output = miniMax(oChild) #returns score
            scoreList.append((output,'o',index))
    return scoreList

def main():
    validChars = ['x','o','-']
    valid = True
    gameBoard = input("Please enter your current board configuration: ")

    for char in gameBoard:
        if char not in validChars:
            valid = False
    while not valid or len(gameBoard) !=9:
        print("Boards is not valid.")
        gameBoard = input("Please enter your current board configuarion: ")
        for char in gameBoard:
            valid = True
            if char not in validChars:
                valid = False

    else:
        listOfScores = miniMax(gameBoard)

        if maxTurn(gameBoard):
            best = max(listOfScores, key=lambda x: x[0])
        else:
            best = min(listOfScores, key=lambda x: x[0])

        if best[0] == 0:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a tie.")
        elif best[0] > 0:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a win.")
        else:
            print("You should mark " + best[1] + " in cell " + best[2] + ".")
            print("This will lead to a loss.")

main()        

以下是traceback :::

的错误
Traceback (most recent call last):
  File "C:/Users/Abby/Desktop/CS 3610/hw2/hw2Copy.py", line 134, in <module>
    main()
  File "C:/Users/Abby/Desktop/CS 3610/hw2/hw2Copy.py", line 117, in main
    listOfScores = miniMax(gameBoard)
  File "C:/Users/Abby/Desktop/CS 3610/hw2/hw2Copy.py", line 92, in miniMax
    output = miniMax(xChild) #returns score
  File "C:/Users/Abby/Desktop/CS 3610/hw2/hw2Copy.py", line 81, in miniMax
    if winner(gameBoard) or getEmptySpaces(gameBoard) ==0:
  File "C:/Users/Abby/Desktop/CS 3610/hw2/hw2Copy.py", line 16, in winner
    case1 = gameBoard[0]+gameBoard[1]+gameBoard[2]
TypeError: 'NoneType' object is not subscriptable

我输入“---- x ----”作为我的输入。请给我一些如何摆脱这个错误的指导!我知道这段代码很乱,但此刻我还好。谢谢!

编辑:::我开始工作,但现在当我试图找到我的最高分时,我收到了这个错误:

Traceback (most recent call last):
  File "C:\Users\Abby\Desktop\CS 3610\hw2\hw2Copy.py", line 134, in <module>
    main()
  File "C:\Users\Abby\Desktop\CS 3610\hw2\hw2Copy.py", line 120, in main
    best = max(listOfScores, key=lambda x: x[0])
TypeError: unorderable types: list() > int()

我之前用自己的元组测试了这个并且它工作了,返回一个元组,所以我不确定这里出了什么问题。请帮忙吗?

1 个答案:

答案 0 :(得分:6)

markX函数中,您应该return gameBoard[:index] + 'x' + gameBoard[index+1:]而不是gameBoard = ...。这将覆盖变量,正如您认为的那样。这是因为在python中,函数中定义的变量仅限于该范围。

正在发生的事情是函数返回None,因为您从未将函数设置为返回任何内容。然后,您尝试将None索引为'NoneType' object is not subscriptable

,这是不可能的

markO()功能也是如此。


对于这样的东西,在我看来,最好使用一个类。这样你就可以处理一个变量,比如self.gameBoard,而不必一直在函数中覆盖它。