在python中从函数返回值时,返回值为空

2024-06-26 03:43:28 发布

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

我正在为一个简单的棋盘游戏制作一个最小-最大算法。当findparent函数返回数据时,有时工作正常,有时由于某种原因返回空。请帮忙。 下面是代码的故障部分

from sys import maxsize
class Node(object):
    def __init__(self,idepth,iplayernum,iboard):
        self.idepth=idepth
        self.iplayernum=iplayernum
        self.iboard=iboard
        self.children=[]
        self.createchildren()
    def createchildren(self):
        if self.idepth>=0:
            for x in range(0,4):
                if self.iboard[x]>0:
                    for y in range(1,self.iboard[x]+1):
                        xiboard=self.iboard.copy()
                        xiboard[x]-=y
                        self.children.append(Node(self.idepth-1,-self.iplayernum,xiboard))
def checknodes(node,turn,ibestvalue,bestchoice):
    for n in range(len(node.children)):
        nchild=node.children[n]
        childarr=[nchild,nchild.iboard]
        for z in range(0,(idepth-nchild.idepth)):
            childarr=findparent(childarr[0],inode)
            print(childarr,'after return')
        bestchoice=childarr[1]
        if nchild.idepth>0:
            checknodes(nchild,turn*-1,ibestvalue,bestchoice)
    return(bestchoice)
def findparent(fnode,node):
    for n in range(len(node.children)):
        nhild=node.children[n]
        if nhild==fnode and nhild.iboard==fnode.iboard:
            print([node,node.iboard],'before return')
            return [node,node.iboard]
        elif nhild.idepth>0:
            findparent(fnode,nhild)
iboardstart=[7,5,3,1]
idepth=3
icurplayer=1
row=int(input('The board is\n{}\n{}\n{}\n{}\nWhat row would you like to take from?'.format(iboardstart[0],iboardstart[1],iboardstart[2],iboardstart[3])))-1
amount=int(input('\nHow many would you like to take?'))
iboardstart[row]-=amount
icurplayer*=-1
inode=Node(idepth,icurplayer,iboardstart)
bestchoice=-100
ibestvalue=-icurplayer*maxsize
bestchoice=checknodes(inode,-1,ibestvalue,bestchoice)
iboardstart=bestchoice
print('Computer plays\n{}\n{}\n{}\n{}'.format(iboardstart[0],iboardstart[1],iboardstart[2],iboardstart[3]))
icurplayer*=-1

如果您运行它,只需输入1作为行,输入1作为量,然后查看它打印出的内容。 希望你们能帮我,伙计们,我会非常感激的


Tags: inselfnodeforrangechildrenidepthiboard
2条回答

您的问题是findparent实际上不会从其递归调用返回任何内容。 然而,它并不像return findparent(fnode,nhild)那么简单,因为如果它在错误的分支中搜索,它有可能返回None。因此,您需要从递归调用中获取值,检查该值是否存在,如果存在,则返回该值

您可以尝试以下方法:

def findparent(fnode, node):
    value = None
    for nchild in node.children:
        if nchild is fnode and nchild.iboard == fnode.iboard:
            print([node, node.iboard], 'before return')
            value = [node, node.iboard]
        elif nchild.idepth > 0:
            value = findparent(fnode, nchild)
        if value:
            return value

作为旁注,当循环遍历列表的元素时,最好使用

for nchild in node.children:

而不是

for n in range(len(node.children)):
        nchild=node.children[n]

似乎checknodes方法中有一个输入错误:

试着改变

childarr=findparent(childarr[0],inode)

进入

childarr=findparent(childarr[0],node)

相关问题 更多 >