首页 > 解决方案 > for循环中的递归python函数

问题描述

想深入挖掘递归作为学校 tictactoe 项目实施 minimax 的前奏

第一次发帖。一直在尝试在 tictactoe 上实现 minimax。看到一堆代码,但我的项目需要单独查看终端状态的路径以简化空间复杂度。我想了解更多关于递归的知识,所以我创建了一个小代码来证明概念。如果矩阵完整但如果矩阵有 3 个缺失点,我能够获得赢/输/平局 (1, -1, 0) 的效用函数,我的理解是 AI 代理必须玩各种游戏在场景中,填补缺失的点并进行人类/人工智能交替移动的迭代,并在达到最终状态时停止。我下面的代码继续运行而不是停止。当记录胜利时,理想的进展应该停止,这是 XXX 的第 3 个矩阵。但它一直在试图填补最后一个空白。

import numpy as np

filename="xFlux.txt"
m=np.loadtxt(filename,delimiter=" ",dtype=str)



def checkWin(m, mark):
    won = False # Variable holding the return value

    # Check wins by examining each combination of positions
    # Check each row
    for i in range(3):
        won = True
        for j in range(3):

            if m[i][j]!=mark:
                won=False
                break        

        if won:
            break

    # Check each column
    if not won:
        for i in range(3):
            won = True
            for j in range(3):
                if m[j][i]!=mark:
                    won=False
                    break
            if won:
                break

    # Check first diagonal
    if not won:
        for i in range(3):
            won = True
            if m[i][i]!=mark:
                won=False
                break

    # Check second diagonal
    if not won:
        for i in range(3):
            won = True
            if m[2-i][i]!=mark:
                won=False
                break

    return won

# Determines whether the board is full
# If full, returns True, and False otherwise
def noMoreMoves(m):
   return (m !=' ').all()

def minimax(m):
  print('entering Minimax')
  print (m)
  print('-----')

  if checkWin(m,'O'):
        # Computer won
        return 1


  elif checkWin(m,'X'):
        print('entering win X',m)
        return -1


  elif  noMoreMoves(m):
        # No moves left -> draw
        return 0 

#find empty cells
print('entering nexted for')
for i in range(3):
    for j in range(3):
         if m[i][j] ==' ':
              print('$$$',i,j)
              m[i][j]='X'
              poke.append((i,j))
              print(m)
              print( poke)
              minimax(m)

#poke is set that will storing the (x,y) tuple
#for the simulated marks which need to be erased later


poke=[]                        
#print (m)
evalX = minimax(m)
print ('eval returns ' , evalX)

标签: python

解决方案


推荐阅读