for循环中的递归python函数

时间:2019-02-02 06:04:46

标签: python

想通过递归更深入地研究,以为学校的单身动植物项目实施minimax

第一次张贴。尝试在tictactoe上实现minimax。看到了很多代码,但是我的项目需要单独查看终端状态的路径,以简化空间复杂度。我希望了解有关递归的更多信息,所以我创建了一个小的代码来证明概念。我能够获得WIN /损失的效用函数/画(1,-1,0),如果基质是完整的,但如果基体具有比方说,3个人失踪点,我的理解是,AI代理有游戏玩出各种场景中,填充缺失的点并进行交替的人/ AI移动迭代,并在达到最终状态时停止。我下面的代码保存去,而不是停止。记录为XXX的第三个矩阵的获胜时,理想的进程应停止。但它一直试图去填补最后一个空白空间。

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)

0 个答案:

没有答案