python版本五子棋的实现代码

时间:2022-10-01 13:04:32

正文之前

前阵子做了个《人工智能》 的课程作业,然后写了个人工智障。。。大概就是个可以跟你下五子棋的傻儿子。。。下面是代码和效果

正文

1、 摘要

机器博弈是人工智能领域的重要分支,它的研究对象多以复杂的棋牌类智力游戏为主,已经得到解决的棋类游戏,几乎全部都应归功于机器博弈近半个世纪的发展。计算机解决问题的优势在于能把不易解析的问题,借助于现代计算机的运算速度优势枚举出所有的合理情形而得解;然而,博弈问题的复杂程度决定了它不能过度依赖机器的计算能力。许多待解决的或已经解决的棋类,其状态空间复杂度或博弈树复杂度量级都太过庞大,所以我们需要添加约束,并且采用合理的算法进行优化。

五子棋问题是人工智能中的一个经典问题。当今世界,alphago已经执围棋之牛耳,五子棋领域却鲜少有人问津。本文根据课堂所学知识结合文献、博客,基于两种开发语言实现了一个智能对战的ai五子棋游戏平台。

本文所做工作如下:

(1) 五子棋界面实现;

(2) 智能判定棋盘走势;

(3) 改进了棋盘扫描方式;

(4) 改良了系统评分表评估方式;

(5) 实现了基于点评分表估值找出最佳落子方式。

2、 问题描述、知识表达

2.1 问题描述

五子棋ai问题的最大问题是如何实现智能对弈,即当人落子之后,算法如何解读当前的棋盘并且对其进行分析解读,得到电脑方的最佳落子点。其次还有一个问题是如何判断胜利,这可以作为前面棋盘局势判定的一个子问题,也可以看做是一个单独的问题,不过这个问题总体来说较为简单,所以不做详细说明。

2.2 知识表达

五子棋的整体知识构建包含以下部分:

(1) 棋盘局面表示法

(2) 棋局胜利判定

(3) 棋型知识库

(4) 智能博弈流程

对于问题(1),采用数组表示法。棋盘中的各交叉点有三种状态,不妨令 0表示空(未放置棋子) ,-1 表示有黑子 ,1 表示有白子,数组表示法的基本思想是:以交叉点对应的数组索引值来表达物理位置 ,以交叉点对应的元素值表达状态(空、 黑子、 白子)。令 v = {0 ,1 ,-1} ,棋盘 的第 i 个交叉点的状态 si ∈v ,任何棋局都可以表示成一个 n ×n 的二元组。

对于问题(2), 采用数组表示法时,想知道任意两个元素 si 和sj 是否共线,要通过 i 和 j 之间的数值规律来判断。从这方面看,数组表示法是一种原始、低效的表示方法,但是对于评分表算法来说其性能损失是可以接受的。要判断是否有一方已经胜利,只需要对整个棋盘判定当前落子点的纵、横、正斜、反斜四个方向的最长延伸出四个位置看是否能连成一条同色直线即可。具体的操作可以视为:从落子点出发,向两个方向延伸,如果遇到同色,那么计数器加一,遇到非同色(空白或者异色)则停止在该方向的延伸,一个计数器记下该方向上的两头的连续同色棋子数。等到四个方向都探索完毕,如果四个计数器中有一个计数器达到了5,那么即可判断出已经有五子连珠了,此局结束。

问题(3)棋型知识库主要包括各种既定的棋盘形式,有如下几种:

² 活四 :有两个连五点(即有两个点可以形成五),图中白点即为连五点。当活四出现的时候,整个局势已经无法阻止连五了,活四的归属方一定能取得胜利;

python版本五子棋的实现代码

² 冲四 :有一个连五点,如下面三图,均为冲四棋型。图中白点为连五点。 相对比活四来说,冲四的威胁性就小了很多,因为这个时候,只要跟着防守在那个唯一的连五点上,冲四就没法形成连五。

python版本五子棋的实现代码

² 活三 :可以形成活四的三,如下图,代表两种最基本的活三棋型。图中白点为活四点。活三棋型是进攻中最常见的一种,因为活三之后,如果对方不以理会,将可以下一手将活三变成活四,而活四是无法防守的。所以,面对活三的时候,需要非常谨慎对待。在没有更好的进攻手段的情况下,必须对其进行防守,以防止其形成可怕的活四棋型。

python版本五子棋的实现代码

² 眠三: 只能够形成冲四的三,如下各图,分别代表最基础的六种眠三形状。图中白点代表冲四点。眠三的棋型与活三的棋型相比,危险系数下降不少,因为眠三棋型即使不去防守,下一手它也只能形成冲四,而对于单纯的冲四棋型,是可以很简单的防守住的。

python版本五子棋的实现代码

² 活二 :能够形成活三的二,如下图,是三种基本的活二棋型。图中白点为活三点。

python版本五子棋的实现代码

² 眠二 :能够形成眠三的二。图中四个为最基本的眠二棋型,细心且喜欢思考的同学会根据眠三介绍中的图2-13找到与下列四个基本眠二棋型都不一样的眠二。图中白点为眠三点。

python版本五子棋的实现代码

对于上述的棋型,我们主要考虑的是活四、冲四、活三、眠三这几种主要的进攻棋型的防守与构成,整体棋型遵从以下原则:优先考虑数目,同等数目的情况下考虑是活是眠。评分表算法的设计整体偏向于防守。

对于问题(4),当下棋型的评估分析,算法严格遵从以下流程:

当人类方落下一子,算法启动,扫描全局,得到人类棋子的集合和电脑棋子的集合。全局扫描之后,对当前局势进行排序、计算。对每个集合的每个空白点位置打分,打分依据是根据这个点周围四个方向上的同色连续棋子的数量。按照这些最后得到的评分,得出最大值。得到人类方和电脑方的两个最大值之后,进行比较,如果人类方局势较好(分数较高),则算法将下一次落子位置设置为人类方得分最高的点,尽力降低人类方的下一步得分;如果电脑方的分数较高,那么则直接在使得分数最高的点落子即可。

3、 开发工具

本次课程设计,一共设计了两个版本,一个java版本,为19x19的棋盘,配备简单的消息提示,基于awt实现gui,开发工具intellij idea 2018.1

python版本五子棋的实现代码

另一个版本是使用python设计,核心算法相同,但是受限于图片源文件,为15x15棋盘,基于pygame实现gui,开发工具是:jetbrains pycharm 2018.2.4 x64

python版本五子棋的实现代码

4、 代码实现

?
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
from time import sleep
import pygame
from pygame.locals import *
from random import randint
 
level = 15
grade = 10
max = 1008611
def scan(chesspad, color):
 shape = [[[0 for high in range(5)] for col in range(15)] for row in range(15)]
 # 扫描每一个点,然后在空白的点每一个方向上做出价值评估!!
 for i in range(15):
 for j in range(15):
 
  # 如果此处为空 那么就可以开始扫描周边
  if chesspad[i][j] == 0:
  m = i
  n = j
  # 如果上方跟当前传入的颜色参数一致,那么加分到0位!
  while n - 1 >= 0 and chesspad[m][n - 1] == color:
   n -= 1
   shape[i][j][0] += grade
  if n-1>=0 and chesspad[m][n - 1] == 0:
   shape[i][j][0] += 1
  if n-1 >= 0 and chesspad[m][n - 1] == -color:
   shape[i][j][0] -= 2
  m = i
  n = j
  # 如果下方跟当前传入的颜色参数一致,那么加分到0位!
  while (n + 1 < level and chesspad[m][n + 1] == color):
   n += 1
   shape[i][j][0] += grade
  if n + 1 < level and chesspad[m][n + 1] == 0:
   shape[i][j][0] += 1
  if n + 1 < level and chesspad[m][n + 1] == -color:
   shape[i][j][0] -= 2
  m = i
  n = j
  # 如果左边跟当前传入的颜色参数一致,那么加分到1位!
  while (m - 1 >= 0 and chesspad[m - 1][n] == color):
   m -= 1
   shape[i][j][1] += grade
  if m - 1 >= 0 and chesspad[m - 1][n] == 0:
   shape[i][j][1] += 1
  if m - 1 >= 0 and chesspad[m - 1][n] == -color:
   shape[i][j][1] -= 2
  m = i
  n = j
  # 如果右边跟当前传入的颜色参数一致,那么加分到1位!
  while (m + 1 < level and chesspad[m + 1][n] == color):
   m += 1
   shape[i][j][1] += grade
  if m + 1 < level and chesspad[m + 1][n] == 0:
   shape[i][j][1] += 1
  if m + 1 < level and chesspad[m + 1][n] == -color:
   shape[i][j][1] -= 2
  m = i
  n = j
  # 如果左下方跟当前传入的颜色参数一致,那么加分到2位!
  while (m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == color):
   m -= 1
   n += 1
   shape[i][j][2] += grade
  if m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == 0:
   shape[i][j][2] += 1
  if m - 1 >= 0 and n + 1 < level and chesspad[m - 1][n + 1] == -color:
   shape[i][j][2] -= 2
  m = i
  n = j
  # 如果右上方跟当前传入的颜色参数一致,那么加分到2位!
  while (m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == color):
   m += 1
   n -= 1
   shape[i][j][2] += grade
  if m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == 0:
   shape[i][j][2] += 1
  if m + 1 < level and n - 1 >= 0 and chesspad[m + 1][n - 1] == -color:
   shape[i][j][2] -= 2
  m = i
  n = j
  # 如果左上方跟当前传入的颜色参数一致,那么加分到3位!
  while (m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][n - 1] == color):
   m -= 1
   n -= 1
   shape[i][j][3] += grade
  if m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][n - 1] == 0:
   shape[i][j][3] += 1
  if m - 1 >= 0 and n - 1 >= 0 and chesspad[m - 1][n - 1] == -color:
   shape[i][j][3] -= 2
  m = i
  n = j
  # 如果右下方跟当前传入的颜色参数一致,那么加分到3位!
  while m + 1 < level and n + 1 < level and chesspad[m + 1][n + 1] == color:
   m += 1
   n += 1
   shape[i][j][3] += grade
  if m + 1 < level and n + 1 < level and chesspad[m + 1][n + 1] == 0:
   shape[i][j][3] += 1
  if m + 1 < level and n + 1 < level and chesspad[m + 1][n + 1] == -color:
   shape[i][j][3] -= 2
 return shape
 
 
def sort(shape):
 for i in shape:
 for j in i:
  for x in range(5):
  for w in range(3, x - 1, -1):
   if j[w - 1] < j[w]:
   temp = j[w]
   j[w - 1] = j[w]
   j[w] = temp
 print("this time sort done !")
 return shape
 
 
def evaluate(shape):
 for i in range(level):
 for j in range(level):
 
  if shape[i][j][0] == 4:
  return i, j, max
  shape[i][j][4] = shape[i][j][0]*1000 + shape[i][j][1]*100 + shape[i][j][2]*10 + shape[i][j][3]
 max_x = 0
 max_y = 0
 max = 0
 for i in range(15):
 for j in range(15):
  if max < shape[i][j][4]:
  max = shape[i][j][4]
  max_x = i
  max_y = j
 print("the max is "+ str(max) + " at ( "+ str(max_x)+" , "+str(max_y)+" )")
 return max_x, max_y, max
 
 
class chess(object):
 def __init__(self):
 self.a = [[0 for high in range(15)] for col in range(15)]
 
 def fall(self, x, y, color):
 if (x < 0 or x > level - 1 or y < 0 or y > level - 1):
  return
 self.a[x][y] = color
 if judge(x, y, color, self.a, 4):
  if color < 0:
  print("the winner is white!!")
  else:
  print("the winner is black!!")
 
 def isempty(self, m, n):
 if self.a[m][n] != 0:
  return false
 else:
  return true
 
 
def judge(x, y, color, chesslocation, length):
 count1, count2, count3, count4 = 0, 0, 0, 0
 # 横向判断
 i = x - 1
 while (i >= 0):
 if color == chesslocation[i][y]:
  count1 += 1
  i -= 1
 else:
  break
 i = x + 1
 while i < level:
 if chesslocation[i][y] == color:
  count1 += 1
  i += 1
 else:
  break
 
 # 纵向判断
 j = y - 1
 while (j >= 0):
 if chesslocation[x][j] == color:
  count2 += 1
  j -= 1
 else:
  break
 j = y + 1
 while j < level:
 if chesslocation[x][j] == color:
  count2 += 1
  j += 1
 else:
  break
 
 # 正对角线判断
 i, j = x - 1, y - 1
 while (i >= 0 and j >= 0):
 if chesslocation[i][j] == color:
  count3 += 1
  i -= 1
  j -= 1
 else:
  break
 i, j = x + 1, y + 1
 while (i < level and j < level):
 if chesslocation[i][j] == color:
  count3 += 1
  i += 1
  j += 1
 else:
  break
 # 反对角线判断
 i, j = x + 1, y - 1
 while (i < level and j >= 0):
 if chesslocation[i][j] == color:
  count4 += 1
  i += 1
  j -= 1
 else:
  break
 i, j = x - 1, y + 1
 while (i > 0 and j < level):
 if chesslocation[i][j] == color:
  count4 += 1
  i -= 1
  j += 1
 else:
  break
 
 if count1 >= length or count2 >= length or count3 >= length or count4 >= length:
 return true
 else:
 return false
 
 
def autoplay(ch, m, n):
 a1 = [1,-1,1,-1,1,-1,0,0]
 b1 = [1,-1,-1,1,0,0,1,-1]
 rand = randint(0,7)
 while m+a1[rand]>=0 and m+a1[rand]<level and n+b1[rand]>=0 and n+b1[rand]<level and ch[m+a1[rand]][n+b1[rand]]!=0 :
 rand = randint(0,7)
 return m + a1[rand], n+b1[rand]
 
def betago(ch, m, n, color, times):
 if times < 2:
 return autoplay(ch, m, n)
 else:
 shape_p = scan(ch, -color)
 shape_c = scan(ch,color)
 shape_p = sort(shape_p)
 shape_c = sort(shape_c)
 max_x_p, max_y_p, max_p = evaluate(shape_p)
 max_x_c, max_y_c, max_c = evaluate(shape_c)
 if max_p>max_c and max_c<max:
  return max_x_p,max_y_p
 else:
  return max_x_c,max_y_c
 
 
def satrtgui(ch):
 pygame.init()
 bg = 'bg.png'
 white_image = 'white.png'
 black_image = 'black.png'
 
 screen = pygame.display.set_mode((750, 750), 0, 32)
 background = pygame.image.load(bg).convert()
 white = pygame.image.load(white_image).convert_alpha()
 black = pygame.image.load(black_image).convert_alpha()
 white = pygame.transform.smoothscale(white, (int(white.get_width() * 1.5), int(white.get_height() * 1.5)))
 black = pygame.transform.smoothscale(black, (int(black.get_width() * 1.5), int(black.get_height() * 1.5)))
 
 screen.blit(background, (0, 0))
 font = pygame.font.sysfont("黑体", 40)
 
 pygame.event.set_blocked([1, 4, keyup, joyaxismotion, joyballmotion, joybuttondown, joybuttonup, joyhatmotion])
 pygame.event.set_allowed([mousebuttondown, mousebuttonup, 12, keydown])
 
 dot_list = [(25 + i * 50 - white.get_width() / 2, 25 + j * 50 - white.get_height() / 2) for i in range(level) for
  j in range(level)]
 color = -1
 times = 0
 flag = false
 while not flag:
 for event in pygame.event.get():
  if event.type == quit:
  exit()
  elif event.type == mousebuttondown:
  x, y = pygame.mouse.get_pos()
  if 25 <= x <= 725 and 25 <= y <= 725 and ((x - 25) % 50 <= level or (x - 25) % 50 >= 0) and (
   (y - 25) % 50 <= level or (y - 25) % 50 >= 0):
   color = -1 * color
   m = int(round((x - 25) / 50))
   n = int(round((y - 25) / 50))
   if not ch.isempty(m, n):
   print("black overwrite~~")
   continue
   ch.fall(m, n, color)
   screen.blit(black, dot_list[level * m + n])
   if judge(m, n, color, ch.a, 4):
   screen.blit(font.render('game over,black is win!', true, (110, 210, 30)), (80, 650))
   break
 
   color = -1 * color
   sleep(0.1)
   x, y = betago(ch.a, m, n, color, times)
   times += 1
   print("predict:" + str(x) + " and " + str(y))
   ch.fall(x, y, color)
   screen.blit(white, dot_list[level * x + y])
   if judge(x, y, color, ch.a, 4):
   screen.blit(font.render('game over,white is win!', true, (217, 20, 30)), (80, 650))
   break
 pygame.display.update()
 if flag:
  sleep(5)
 
now = chess()
satrtgui(now)

python版本五子棋的实现代码

bg.png

python版本五子棋的实现代码

black.png

python版本五子棋的实现代码

white.png

5、 小结及展望

5.1 小结

因为近期时间较为紧迫,所以《人工智能》这门课我选择了较为简单的五子棋问题进行课程设计。在本次课程设计中,我的编码能力、调试能力、算法解读实现能力、函数优化能力等各方面有了长足的进步。在本次的设计过程中也出现了几个问题,下面对这些问题进行一个简单的描述:

(1) 对棋盘局势的判断力不够,因为只是简单的对当前的棋盘局势进行判断,基本等同于一个粗通规则而且天赋不高的五子棋选手。如果对手很细心,而且熟练经营各种布局策略,那么基本这个算法就会被钻研出习惯,从而被轻易针对,而且针对方案百试不爽;

(2) 判断棋局形式的时候对边界的评分算法跟中心区域的评分算法一致,无法有效提前识别边界,降低边界空白点的权重;

(3) 用户图形界面需要改进,另外可以增设pk模式以及选色、选择棋盘大小功能等;

5.2 展望

后续可以尝试用博弈树算法尝试与当前算法进行比较。评分表算法牺牲了更高的精度,以求迅速的得出最佳落子点;而博弈树可以通过提前落子进行全局预判进行更全方位的对人类方的围追堵截。

另外,可以通过在课堂上学到的知识,比如bfs、dfs、a*算法、决策树算法 等应用于五子棋的智能决策中。

《人工智能》这门课让我对于图、知识表示、智能决策等各个方面有了更好地认识与体验,课堂设计内容充实有趣,让我受益匪浅,希望今后可以更加深入这个方面,并且将课堂上学到的知识应用于实践之中。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/8e6a245199e0