-
Notifications
You must be signed in to change notification settings - Fork 0
/
chessboard.py
98 lines (88 loc) · 3.14 KB
/
chessboard.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import numpy as np
# 棋谱
class ChessBoard:
def __init__(self, width=15, height=15, n_in_row=5, state=None):
self.width = width
self.height = height
self.n_in_row = n_in_row
self.state = state
if state is None:
self.state = np.zeros([width, height], dtype=np.byte)
self.available_location = [(x, y) for x in range(width) for y in range(height) if self.state[x, y] == 0]
# 落子,返回 是否结束
def put_piece(self, player, location):
if not self.validate(location):
raise Exception("location error" + str(location))
x, y = location
self.state[x, y] = player.index
self.available_location.remove(location)
return self._is_done(player, x, y)
# 是否可以落子
def validate(self, location):
try:
x, y = location
except Exception as e:
raise e
return 0 <= x < self.width and 0 <= y < self.height and self.state[x, y] == 0
# 棋盘已满
def is_full(self):
return self.state.all()
# 是否结束
def _is_done(self, player, x, y):
return self._x_is_done(player, x, y) or self._y_is_done(player, x, y) or self._xy_is_done(player, x, y) or self._yx_is_done(player, x, y)
# 横向是否结束
def _x_is_done(self, player, x, y):
count = 1
move_x = x - 1
while move_x >= 0 and self.state[move_x, y] == player.index:
count += 1
move_x -= 1
move_x = x + 1
while move_x < self.width and self.state[move_x, y] == player.index:
count += 1
move_x += 1
return count >= self.n_in_row
# 竖向是否结束
def _y_is_done(self, player, x, y):
count = 1
move_y = y - 1
while move_y >= 0 and self.state[x, move_y] == player.index:
count += 1
move_y -= 1
move_y = y + 1
while move_y < self.height and self.state[x, move_y] == player.index:
count += 1
move_y += 1
return count >= self.n_in_row
# 斜向是否结束
def _xy_is_done(self, player, x, y):
count = 1
move_x = x - 1
move_y = y - 1
while move_x >= 0 and move_y >= 0 and self.state[move_x, move_y] == player.index:
count += 1
move_x -= 1
move_y -= 1
move_x = x + 1
move_y = y + 1
while move_x < self.width and move_y < self.height and self.state[move_x, move_y] == player.index:
count += 1
move_x += 1
move_y += 1
return count >= self.n_in_row
# 反斜向是否结束
def _yx_is_done(self, player, x, y):
count = 1
move_x = x - 1
move_y = y + 1
while move_x >= 0 and move_y < self.height and self.state[move_x, move_y] == player.index:
count += 1
move_x -= 1
move_y += 1
move_x = x + 1
move_y = y - 1
while move_x < self.width and move_y >= 0 and self.state[move_x, move_y] == player.index:
count += 1
move_x += 1
move_y -= 1
return count >= self.n_in_row