教機器學習的內容
衡量機器人的棋力
包括以下內容:
建立目錄 dlgo,其下建 3 個文件:
文件__init__.py內容為空。
在模塊 gotype.py 中 定義棋手和棋盤點位:
import enum
class Player(enum.Enum):
black = 1
white = 2
@property
def other(self):
return Player.black if self == Player.white else Player.white
from collections import namedtuple
class Point(namedtuple('Point', 'row col')):
def neighbors(self):
return [
Point(self.row - 1, self.col),
Point(self.row + 1, self.col),
Point(self.row, self.col - 1),
Point(self.row, self.col + 1),
]
Player 的用法
Player = Player.black
print(Player.value)
print(Player.other.value)
輸出結果是 1 和 2
Point的用法
p = Point(row=3,col=3)
print(p.neighbors())
輸出結果是:
[Point(row=2, col=3),
Point(row=4, col=3),
Point(row=3, col=2),
Point(row=3, col=4)]
在模塊 goboard_slow.py 中 定義落子、放棄一手和認輸:
import copy
from gotypes import Player
class Move():
def __init__(self, point=None, is_pass=False, is_resign=False):
assert (point is not None) ^ is_pass ^ is_resign
self.point = point
self.is_play = (self.point is not None)
self.is_pass = is_pass
self.is_resign = is_resign
@classmethod
def play(cls, point):
return Move(point=point)
@classmethod
def pass_turn(cls):
return Move(is_pass=True)
@classmethod
def resign(cls):
return Move(is_resign=True)
Move 的用法
Move.play(Point(3, 3))
move = Move.play(Point(3, 3))
print(move.is_play)
print(move.point.row)
move = Move.resign()
print(move.is_resign)
輸出結果是:
True
3
True
用 assert 測試 Move 是否合法
下例,落子與pass同時發生,將引發報錯:
move = Move(Point(2,2),is_pass=True,is_resign=False)
定義棋串
class GoString():
def __init__(self, color, stones, liberties):
self.color = color
self.stones = set(stones)
self.liberties = set(liberties)
def remove_liberty(self, point):
self.liberties.remove(point)
def add_liberty(self, point):
self.liberties.add(point)
def merged_with(self, go_string):
assert go_string.color == self.color
combined_stones = self.stones | go_string.stones
return GoString(self.color,combined_stones,
(self.liberties | go_string.liberties) - ombined_stones)
@property
def num_liberties(self):
return len(self.liberties)
def __eq__(self, other):
return isinstance(other, GoString) and \
self.color == other.color and \
self.stones == other.stones and \
self.liberties == other.liberties
注意,__eq__ 用於判別类的實例是否相等
GoString 的用法
a = GoString(Player.black,[Point(3,3),Point(3,4),Point(3,5)],[3,2,2])
b = GoString(Player.black,[Point(3,3),Point(3,4),Point(3,5)],[3,2,2])
print(a==b)
a = GoString(Player.black,[Point(3,3),Point(3,4),Point(3,5)],[3,2,2])
b = GoString(Player.black,[Point(13,3),Point(13,4),Point(13,5)],[3,2,2])
print(a==b)
輸出結果是:
True
False