如何为 nim 游戏 python 编写极小极大算法? [英] How can I programme a minimax algorithm for nim game python?

查看:60
本文介绍了如何为 nim 游戏 python 编写极小极大算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 python 中编写一个极小极大算法.但它是如此令人困惑.我是递归函数的新手.我的思维结构在某处有一些错误,但我无法解决.我的极小极大树返回 '-100' 必须是 100 才能获得正确答案.如果有什么遗漏或不清楚,请告诉我.谢谢

I tried to programme a minimax algorithm in python. But it is so confusing. I am new to recursion functions. My mind structure has some error at somewhere but I could not solve it. My minimax tree returns with '-100' that must be 100 to achieve true answer. If anything is missing or not clear, please just let me know. Thank you

def startposition():
    return 2, 'max'


def terminalstate(state):
    if state == (0, 'min') or state == (0, 'max'):
        return True
    else:
        return False


def minimax(state):
    if terminalstate(state):
        return utilitystatic(state)
    else:
        if state[1] == 'min':
            value = -250
            for x in successorsgenerator(state):
                value = max(value, minimax(x))
        elif state[1] == 'max':
            value = 250
            for x in successorsgenerator(state):
                value = min(value, minimax(x))
    return value
def utilitystatic(state):
    assert terminalstate(state)
    if state[1] == 'max':
        return -100
    elif state[1] == 'min':
        return 100
    assert False


def successorsgenerator(state):
    successors = []
    state = toggle(state)
    newstate = decrease(state)
    i = 0
    while newstate[0] >= 0 and i < 3:
        successors.append(newstate)
        i += 1
        newstate = decrease(newstate)

    print('successors:', successors)
    return successors


def toggle(state):
    state = list(state)
    state[1] = 'min' if state[1] == 'max' else 'max'
    state = tuple(state)
    return state


def decrease(state):
    state = state[:0] + (state[0] - 1,) + state[1:2]
    return state


stick = startposition()
exit = minimax(stick)
print('last result', exit)

推荐答案

我解决了我的问题.我需要将 value = min(value, minimax(x)) 更改为 value = max(value, minimax(x)) 并将 250 更改为 -250.问题解决了.

I solved my problem. I needed to change value = min(value, minimax(x)) to value = max(value, minimax(x)) and 250 to -250. Problem solved.

这篇关于如何为 nim 游戏 python 编写极小极大算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆