You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在2048游戏实现Mini-Max算法时遇类型错误求助

解决Mini-Max算法在2048游戏中的TypeError问题

这个错误的根源很明确:你在Mini-Max算法的递归逻辑里,直接比较了Tree类的实例对象,而Python并没有为自定义的Tree类定义>这类比较运算符,所以才会抛出TypeError: '>' not supported between instances。

下面给你两种具体的修复方案,你可以根据自己的代码逻辑选择:

方案1:在Mini-Max中直接比较节点的得分值

你的Tree类里self.data = [None, data],看起来第二个元素是节点的评估得分(比如2048游戏的盘面得分)。那你只需要在Mini-Max的递归过程中,提取这个得分值来比较,而不是比较Tree实例本身。

举个例子,假设你原来的Mini-Max代码是这样的(错误版):

def minimax(node, depth, is_maximizing):
    if depth == 0 or node.is_terminal():
        return node  # 返回了Tree实例
    if is_maximizing:
        best_val = float('-inf')
        for son in node.sons:
            current_val = minimax(son, depth-1, False)
            if current_val > best_val:  # 这里在比较Tree实例和数值,报错
                best_val = current_val
        return best_val
    # 最小化玩家逻辑类似...

改成这样(正确版):

def minimax(node, depth, is_maximizing):
    if depth == 0 or node.is_terminal():
        return node.data[1]  # 返回得分数值,而非Tree实例
    if is_maximizing:
        best_val = float('-inf')
        for son in node.sons:
            current_val = minimax(son, depth-1, False)
            if current_val > best_val:  # 现在都是数值,可以正常比较
                best_val = current_val
        return best_val
    else:
        best_val = float('inf')
        for son in node.sons:
            current_val = minimax(son, depth-1, True)
            if current_val < best_val:
                best_val = current_val
        return best_val

方案2:给Tree类添加比较运算符

如果你希望保持Mini-Max逻辑里直接比较Tree实例的写法,可以给Tree类添加__gt__(大于)和__lt__(小于)方法,让Python知道怎么比较两个Tree节点:

class Tree(object):
    def __init__(self, num_sons, data, parent=None):
        self.data = [None, data]
        self.sons = []
        self.index_son = 0
        self.parent = parent
        for i in range(num_sons):
            self.sons.append(None)
    def add_son(self, son):
        self.sons[self.index_son] = son
        self.index_son += 1
    def get_son(self, index):
        return self.sons[index]
    def is_terminal(self):
        return self.index_son == 0
    
    # 添加大于比较方法
    def __gt__(self, other):
        if isinstance(other, Tree):
            return self.data[1] > other.data[1]
        return NotImplemented
    
    # 添加小于比较方法
    def __lt__(self, other):
        if isinstance(other, Tree):
            return self.data[1] < other.data[1]
        return NotImplemented

这样之后,你在Mini-Max里直接写if son_eval > best_val(当best_val也是Tree实例时)就不会报错了。

额外小建议

你的self.data = [None, data]这个结构有点奇怪,如果None没有特殊用途,直接用self.data = data存储得分会更简洁,也能减少后续代码里索引错误的概率。

内容的提问来源于stack exchange,提问作者Bar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:09:08