函数应返回True或False时返回None

2024-06-16 16:14:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为Connect 4游戏制作一个win checking功能。网格是7x6,一行有4个平铺应该会导致函数返回True,否则返回False。有关守则如下:

grid=[[" O ","   ","   ","   ","   ","   "],["   "," O ","   ","   ","   ","   "],["   ","   "," O ","   ","   ","   "],["   ","   ","   "," O ","   ","   "],["   ","   ","   ","   "," O ","   "],["   ","   ","   ","   ","   "," O "],["   ","   ","   ","   ","   ","   "]]
#2D array for grid

typetofunct={"left":"x-1,y,'left'","right":"x+1,y,'right'","up":"x,y+1,'up'","down":"x,y-1,'down'","topleft":"x-1,y+1,'topleft'","topright":"x+1,y+1,'topright'","downleft":"x-1,y-1,'downleft'","downright":"x+1,y-1,'downright'"}
def check(x,y,checktype,count):
    if not ((x==0 and (checktype=="left" or checktype=="topleft" or checktype=="bottomleft")) or (x==6 and (checktype=="right" or checktype=="bottomright" or checktype=="topright")) or (y==0 and (checktype=="down" or checktype=="downleft" or checktype=="downright")) or (y==5 and (checktype=="up" or checktype=="topleft" or checktype=="topright"))): #doesn't check if it's on a boundary
        print("Checked {0}".format(checktype))
        if grid[x][y]!="   ":
            print(count)
            count+=1
            if count>=4:
                print("True reached")
                return True
            else:
                print("Looping")
                return exec("check({0},count)".format(typetofunct.get(checktype)))
                #recurs the function, has to get it from a dictionary according to string
        else:
            print("Grid was empty")
            return count>=4
    else:
        print("Out of bounds")
        return False
print(check(0,0,"topright",0))

这应该是打印:

Checked topright
0
Looping
Checked topright
1
Looping
Checked topright
2
Looping
Checked topright
3
True reached
True

但我得到的是:

Checked topright
0
Looping
Checked topright
1
Looping
Checked topright
2
Looping
Checked topright
3
True reached
None

据我所知,这个函数应该只返回True或False。请帮忙


Tags: orandfalsetruereturnifcheckcount
2条回答

问题是函数exec不返回任何内容,即使它内部的函数返回。所以这句话:

return exec("check({0},count)".format(typetofunct.get(checktype)))

将始终返回None

为什么不直接调用函数本身,而不使用exec

return check(typetofunct.get(checktype),count)

return exec("check({0},count)".format(typetofunct.get(checktype)))是返回的None

>>> a = exec("print('ciao')")
ciao
>>> a is None
True
>>>

相关问题 更多 >