python - 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)
解决方案
推荐阅读
- c++ - 我如何在 Visual C++ 的代码中包含 if else 问题
- html - 导航栏透明,直到在 Angular 上滚动
- javascript - js,ecmascript 6 箭头函数的问题不起作用,是的,我确实声明了它
- mysql - 根据条件更新 MySQL 中的字段
- javascript - 我是一个初学者 js 编码器,试图与计算机对手进行乒乓球比赛,但球直接穿过桨
- javascript - 在 useEffect 中设置状态然后访问它的属性
- c++ - 在 Rcpp 中使用 OptimLib 时出错
- scala - Scala 特征和继承
- vb.net - 如何使用 vb.net 删除 INI 文件的一部分中的一行?
- python - Pandas 只保留指定的子序列(groupby order 保留子序列)