Ошибка типа: не может распаковать неповторяемый объект NoneType python функция - PullRequest
0 голосов
/ 04 апреля 2020

Я кодирую лучшую тиктактую игру вместе с ИИ, чтобы играть против пользователя. Чтобы определить, где AI будет размещать свои O, я кодировал следующее:

def AIsemidecentboy(allowed, grid):
print("hi")
x = allowed[0] # x = the location from where man is allowed to be
y = allowed[1] #variable y =the location from where man is allowed to be on the y plane
if allowed[0] == -1 and allowed[1] == -1:
    for x in range(allowed[0]+1, (allowed[0] + 10)): # when x is in the range of the x plane allowed positions
        for y in range(allowed[1]+1, (allowed[1] + 10)): # when y is in the range of the y plane allowed positions
            if grid[x][y] == 0: # if the position in the grid is not filled
                print(x,y)
                return(x, y) #return the first possible filling positions
else: # if the location where man is allowed to be isnt simply the whole thing and therefore is one of the minicubes
    for x in range(allowed[0], (allowed[0] + 3)): #when x is in the range of the 3 different x positions it can be in
        for y in range(allowed[1], (allowed[1] + 3)):# when y is in the range of the 3 different y positions it can be in
            if grid[x][y] == 0:
                print("MANLIKE")
                print(x,y)# if the position on the grid is available
                if grid[x][y+1] == 1:
                    print("hellman")
                    print(x,y)
                    return(x, y)
                elif grid[x][y-1] == 1:  
                    print(x,y)
                    print("hellman")                       # For all of these simply observe the notebook
                    return(x, y)
                elif grid[x+1][y] == 1:
                    print(x,y)
                    print("hellman")
                    return(x,y)
                elif grid[x+1][y+1] == 1:
                    print(x,y)
                    print("hellman")
                    return(x,y)
                elif grid[x-1][y+1] == 1:
                    print(x,y)
                    print("hellman")
                    return(x,y)
                elif grid[x+1][y-1] == 1:
                    print(x,y)
                    print("hellman")
                    return(x,y)
                elif grid[x-1][y-1] == 1:
                    print(x,y)
                    print("hellman")
                    return(x,y) 
            else: 
                print("filip")
                for x in range(allowed[0], (allowed[0] + 3)): #when x is in the range of the 3 different x positions it can be in
                    for y in range(allowed[1], (allowed[1] + 3)):# when y is in the range of the 3 different y positions it can be in
                        if grid[x][y] == 0:
                            print(x,y)
                            return(x,y)

эта функция предназначена для возврата значений для x и y, которые затем могут быть введены в качестве решения, принятого алгоритм. Диапазоны существуют, потому что можно либо поместить их х / о в поле 9 на 9, либо в поля c 3 на 3 в зависимости от функции рандомизации, выполняемой игрой.

Функция работает в первый раз, когда ее вызывают, и переходит к последнему, где печатается «filip», однако после этого возвращается следующая ошибка:

Traceback (most recent call last):
File "/Users/skanderlejmi/Desktop/ask.py", line 398, in <module>
xcord, ycord = AIsemidecentboy([allowedx, allowedy], grid)
TypeError: cannot unpack non-iterable NoneType object

Я предполагаю, что по какой-то причине код, инициировавший функцию, извлекает значения x и y до того, как они были определены, или что функция возвращает обнуленные значения x и y. В любом случае, меня особенно смущает вопрос, почему в одном случае функция переходит к другому в конце, а в другом - нет.

Я был бы очень признателен всем, кто помог бы мне в этом вопросе, поскольку я все еще начинающий с этим.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...