引用来自ShangtongZhang的代码chapter01/tic_tac_toe.py
Tic-Tac-Toe的python代码实现
1、引入模块并定义井字棋的常量
1 | import numpy as np |
2、创建环境,State类,表征棋盘上的X和O子的情况。
1 | class State: |
关于这里的hash函数,是为了得到不重复的所有棋盘情况。但是为什么可以通过这种算法那?
假设两个不同的棋盘情况A和B,他们的hash值是一致的,我们不妨设他们的最高位不相同,那么我们看到,该位最少相差1,通过等比数列求和可以得到,3^(n+1)>2*(1+3^1+3^2+…+3^n),即最高位不同是无法通过其余位来弥补的,那么可见他们的最高位不同是不可能hash值相同的,以此递推,则可得A和B值是一样,即一样的棋盘,假设不成立。
3、公共函数,用来获取当前state。
1 | def get_all_states_impl(current_state, current_symbol, all_states): |
4、Player类,用来模拟AI选手下棋的行为,得到value function
1 | # AI player |
这里需要注意一点就是,在backup方法里,只有greedy-action才会更新value,exploring虽然不会更新value,但是其随后的greedy-action会进行更新,个人的理解是:exploring并不能保证最优,它只是提供一种“探索”行为,帮助Learning method更好的学习value,所以只对greedy-action进行update。这地方原文有解释:
Exploratory moves do not result in any learning, but each of our other moves does, causing updates as suggested by the curved arrow in which estimated values are moved up the tree from later nodes to earlier as detailed in the text.
5、创建对决类Judger,通过一次对局完成一次value table的update
1 | class Judger: |
6、训练并让两名AI Player进行对局
1 | def train(epochs): |