井字棋AI_强化

完善了井字棋AI—NanaGo的内部函数,使他更加智能。

AI内核函数

使用了简单的穷举遍历计算。

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
def __computer_chess(self):
"""
电脑下棋NanaGo
"""
if self.__game_status != GameStatus.PLAYING:
return

###########################################################
# 下一子后, 判断自己是否直接获胜
###########################################################
# 横向判断
for row in range(3):
fork_count = 0
empty_col = -1
for col in range(3):
if self.__chess_map[row][col] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_col = col
# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_col >= 0:
self.__chess_map[row][empty_col] = ChessType.FORK
print(f"电脑(横向进攻): ({row}, {empty_col}) <- 叉")
return

# 纵向判断
for col in range(3):
fork_count = 0
empty_row = -1
for row in range(3):
if self.__chess_map[row][col] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_row = row
# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][col] = ChessType.FORK
print(f"电脑(纵向进攻): ({empty_row}, {col}) <- 叉")
return

# 对角线判断(左上-右下)
fork_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[0][0] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[0][0] == ChessType.EMPTY:
empty_row, empty_col = 0, 0

if self.__chess_map[1][1] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[2][2] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[2][2] == ChessType.EMPTY:
empty_row, empty_col = 2, 2

# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线\\进攻): ({empty_row}, {empty_col}) <- 叉")
return

# 对角线判断(左下 - 右上)
fork_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[2][0] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[2][0] == ChessType.EMPTY:
empty_row, empty_col = 2, 0

if self.__chess_map[1][1] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[0][2] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[0][2] == ChessType.EMPTY:
empty_row, empty_col = 0, 2

# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线/进攻): ({empty_row}, {empty_col}) <- 叉")
return

###########################################################
# 如果对方下一子后, 能直接获胜, 则需要在对应位置堵住对方
###########################################################
# 横向判断
for row in range(3):
circle_count = 0
empty_col = -1
for col in range(3):
if self.__chess_map[row][col] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_col = col
# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_col >= 0:
self.__chess_map[row][empty_col] = ChessType.FORK
print(f"电脑(横向防守): ({row}, {empty_col}) <- 叉")
return

# 纵向判断
for col in range(3):
circle_count = 0
empty_row = -1
for row in range(3):
if self.__chess_map[row][col] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_row = row
# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][col] = ChessType.FORK
print(f"电脑(纵向防守): ({empty_row}, {col}) <- 叉")
return

# 对角线判断(左上-右下)
circle_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[0][0] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[0][0] == ChessType.EMPTY:
empty_row, empty_col = 0, 0

if self.__chess_map[1][1] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[2][2] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[2][2] == ChessType.EMPTY:
empty_row, empty_col = 2, 2

# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0 and empty_col >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线\\防守): ({empty_row}, {empty_col}) <- 叉")
return

# 对角线判断(左下 - 右上)
circle_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[2][0] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[2][0] == ChessType.EMPTY:
empty_row, empty_col = 2, 0

if self.__chess_map[1][1] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[0][2] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[0][2] == ChessType.EMPTY:
empty_row, empty_col = 0, 2

# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0 and empty_col >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线/防守): ({empty_row}, {empty_col}) <- 叉")
return

###########################################################
# 优先占角
###########################################################
angles = [(0, 0), (0, 2), (2, 0), (2, 2)]
random.shuffle(angles)
for angle in angles:
row, col = angle[0], angle[1]
if self.__chess_map[row][col] == ChessType.EMPTY:
self.__chess_map[row][col] = ChessType.FORK
print(f"电脑(优先占角): ({row}, {col}) <- 叉")
return

###########################################################
# 次要占中心
###########################################################
if self.__chess_map[1][1] == ChessType.EMPTY:
self.__chess_map[1][1] = ChessType.FORK
print(f"电脑(占中心): (1, 1) <- 叉")
return

###########################################################
# 其他情况, 在剩余空白处随机下一个叉
###########################################################
empty_count = 0
for row in range(3):
for col in range(3):
if self.__chess_map[row][col] == ChessType.EMPTY:
empty_count += 1
if empty_count <= 0:
return
new_fork_chess_pos = random.randrange(empty_count)
empty_pos = 0
print("new_fork_chess_pos", new_fork_chess_pos)
print("empty_count", empty_count)
for row in range(3):
is_pass = False
for col in range(3):
if self.__chess_map[row][col] == ChessType.EMPTY:
if empty_pos != new_fork_chess_pos:
empty_pos += 1
continue
self.__chess_map[row][col] = ChessType.FORK
print(f"电脑(随机落子): ({row}, {col}) <- 叉")
is_pass = True
break
if is_pass:
break

完整代码

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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
import enum
import random
from typing import List, Tuple, Optional

import pygame

BG_COLOR = pygame.Color("#EEEEEE") #背景
BOARD_COLAR = pygame.Color("#E96666") # 边框
CIRCLE_CHESS_COLOR = pygame.Color("#3CA273") # 画圈圈的棋子的颜色
FORK_CHESS_COLOR = pygame.Color("#5570C2") # 画叉的棋子的颜色
WIN_LINE_COLOR = pygame.Color("#FFA801") # 获胜划线
CIRCLE_WIN_HINT_TEXT_COLOR = pygame.Color("#029999") # 画圈获胜文本
FORK_WIN_HINT_TEXT_COLOR = pygame.Color("#E94466") # 画叉获胜文本
TIE_HINT_TEXT_COLOR = pygame.Color("#FAC888") # 平局文本
RESTART_HINT_TEXT_COLOR = pygame.Color("#91CBBB") #重新开始


def main():
# 初试化
pygame.init()
pygame.display.set_caption("井字棋AI_NanaGo")
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

scene = GameScene()

while True:
for event in pygame.event.get():
# 退出判断
if event.type == pygame.QUIT:
pygame.quit()
return

# 处理鼠标的输入,传递到我的场景中进行处理
if event.type == pygame.MOUSEBUTTONDOWN:
if event.dict["button"] == pygame.BUTTON_LEFT:
pos = event.dict["pos"] #pos is a tuple
scene.on_mouse_left_button_down(pos[0], pos[1])

elif event.type == pygame.MOUSEMOTION:
#鼠标移动
pos = event.dict["pos"] #pos is a tuple
scene.on_mouse_motion(pos[0], pos[1])


#绘制场景
scene.draw(screen)

#更新屏幕
pygame.display.flip()

#限制帧率
clock.tick(30)



class ChessType(enum.Enum):
"""
棋子类型,画圈圈的是人类,画叉的是电脑AI
"""
EMPTY = 0
"""空位,没有被下子"""

CIRCLE = 1
FORK = 2


class GameStatus(enum.Enum):
"""
游戏状态
"""
PLAYING = 0
CIRCLE_WIN = 1
FORK_WIN = 2

TIE = 3
"""平局"""



class GameScene:
"""
游戏场景
"""
__game_status: GameStatus = None
__chess_map: List[List[ChessType]] = None
__curr_mouse_down_pos: Optional[Tuple[int, int]] = None
__curr_mouse_motion_pos: Optional[Tuple[int, int]] = None
__win_pos_start: Optional[Tuple[int, int]] = None
__win_pos_end: Optional[Tuple[int, int]] = None
__circle_win_hint_text: pygame.Surface = None
__fork_win_hint_text: pygame.Surface = None
__tie_hint_text: pygame.Surface = None
__restart_text: pygame.Surface = None


def __init__(self):
font = pygame.font.Font(pygame.font.get_default_font(), 25)
self.__circle_win_hint_text = font.render("You Win", True, CIRCLE_WIN_HINT_TEXT_COLOR)
self.__fork_win_hint_text = font.render("NanaGo Win", True, FORK_WIN_HINT_TEXT_COLOR)
self.__tie_hint_text = font.render("Tie", True, TIE_HINT_TEXT_COLOR)
self.__restart_text = font.render("Click for a new game", True, RESTART_HINT_TEXT_COLOR)
self.__init()


def __init(self):
print("初始化ing")
self.__game_status = GameStatus.PLAYING

self.__chess_map = [
[ChessType.EMPTY,ChessType.EMPTY,ChessType.EMPTY],
[ChessType.EMPTY,ChessType.EMPTY,ChessType.EMPTY],
[ChessType.EMPTY,ChessType.EMPTY,ChessType.EMPTY]
]

self.__curr_mouse_down_pos = None
self.__win_pos_start = None
self.__win_pos_end = None


if random.random() > 0.5:
print("电脑先手")
self.__computer_chess()
self.__check_game_over()
else:
print("人类先手")



def __computer_chess(self):
"""
电脑下棋
"""


"""
v1, 从左上角开始依次遍历,然后下到第一个empty的地方

"""
# for c in range(3):
# for r in range(3):
# if self.__chess_map[r][c] == ChessType.EMPTY:
# self.__chess_map[r][c] = ChessType.FORK
# return


"""
v2, 穷举法遍历

"""
if self.__game_status != GameStatus.PLAYING:
return

###########################################################
# 下一子后, 判断自己是否直接获胜
###########################################################
# 横向判断
for row in range(3):
fork_count = 0
empty_col = -1
for col in range(3):
if self.__chess_map[row][col] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_col = col
# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_col >= 0:
self.__chess_map[row][empty_col] = ChessType.FORK
print(f"电脑(横向进攻): ({row}, {empty_col}) <- 叉")
return

# 纵向判断
for col in range(3):
fork_count = 0
empty_row = -1
for row in range(3):
if self.__chess_map[row][col] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_row = row
# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][col] = ChessType.FORK
print(f"电脑(纵向进攻): ({empty_row}, {col}) <- 叉")
return

# 对角线判断(左上-右下)
fork_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[0][0] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[0][0] == ChessType.EMPTY:
empty_row, empty_col = 0, 0

if self.__chess_map[1][1] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[2][2] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[2][2] == ChessType.EMPTY:
empty_row, empty_col = 2, 2

# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线\\进攻): ({empty_row}, {empty_col}) <- 叉")
return

# 对角线判断(左下 - 右上)
fork_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[2][0] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[2][0] == ChessType.EMPTY:
empty_row, empty_col = 2, 0

if self.__chess_map[1][1] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[0][2] == ChessType.FORK:
fork_count += 1
elif self.__chess_map[0][2] == ChessType.EMPTY:
empty_row, empty_col = 0, 2

# 2个叉, 并且有一个空白, 则直接下到空白处
if fork_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线/进攻): ({empty_row}, {empty_col}) <- 叉")
return

###########################################################
# 如果对方下一子后, 能直接获胜, 则需要在对应位置堵住对方
###########################################################
# 横向判断
for row in range(3):
circle_count = 0
empty_col = -1
for col in range(3):
if self.__chess_map[row][col] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_col = col
# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_col >= 0:
self.__chess_map[row][empty_col] = ChessType.FORK
print(f"电脑(横向防守): ({row}, {empty_col}) <- 叉")
return

# 纵向判断
for col in range(3):
circle_count = 0
empty_row = -1
for row in range(3):
if self.__chess_map[row][col] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[row][col] == ChessType.EMPTY:
empty_row = row
# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0:
self.__chess_map[empty_row][col] = ChessType.FORK
print(f"电脑(纵向防守): ({empty_row}, {col}) <- 叉")
return

# 对角线判断(左上-右下)
circle_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[0][0] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[0][0] == ChessType.EMPTY:
empty_row, empty_col = 0, 0

if self.__chess_map[1][1] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[2][2] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[2][2] == ChessType.EMPTY:
empty_row, empty_col = 2, 2

# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0 and empty_col >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线\\防守): ({empty_row}, {empty_col}) <- 叉")
return

# 对角线判断(左下 - 右上)
circle_count = 0
empty_row, empty_col = -1, -1

if self.__chess_map[2][0] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[2][0] == ChessType.EMPTY:
empty_row, empty_col = 2, 0

if self.__chess_map[1][1] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[1][1] == ChessType.EMPTY:
empty_row, empty_col = 1, 1

if self.__chess_map[0][2] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[0][2] == ChessType.EMPTY:
empty_row, empty_col = 0, 2

# 2个圈, 并且有一个空白, 则直接下到空白处
if circle_count == 2 and empty_row >= 0 and empty_col >= 0:
self.__chess_map[empty_row][empty_col] = ChessType.FORK
print(f"电脑(对角线/防守): ({empty_row}, {empty_col}) <- 叉")
return

###########################################################
# 优先占角
###########################################################
angles = [(0, 0), (0, 2), (2, 0), (2, 2)]
random.shuffle(angles)
for angle in angles:
row, col = angle[0], angle[1]
if self.__chess_map[row][col] == ChessType.EMPTY:
self.__chess_map[row][col] = ChessType.FORK
print(f"电脑(优先占角): ({row}, {col}) <- 叉")
return

###########################################################
# 次要占中心
###########################################################
if self.__chess_map[1][1] == ChessType.EMPTY:
self.__chess_map[1][1] = ChessType.FORK
print(f"电脑(占中心): (1, 1) <- 叉")
return

###########################################################
# 其他情况, 在剩余空白处随机下一个叉
###########################################################
empty_count = 0
for row in range(3):
for col in range(3):
if self.__chess_map[row][col] == ChessType.EMPTY:
empty_count += 1
if empty_count <= 0:
return
new_fork_chess_pos = random.randrange(empty_count)
empty_pos = 0
print("new_fork_chess_pos", new_fork_chess_pos)
print("empty_count", empty_count)
for row in range(3):
is_pass = False
for col in range(3):
if self.__chess_map[row][col] == ChessType.EMPTY:
if empty_pos != new_fork_chess_pos:
empty_pos += 1
continue
self.__chess_map[row][col] = ChessType.FORK
print(f"电脑(随机落子): ({row}, {col}) <- 叉")
is_pass = True
break
if is_pass:
break




def __check_game_over(self):
for c in range(3):
circle_count = 0
fork_count = 0
for r in range(3):
if self.__chess_map[r][c] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[r][c] == ChessType.FORK:
fork_count += 1

if circle_count == 3:
self.__game_status = GameStatus.CIRCLE_WIN
self.__win_pos_start = (0, c)
self.__win_pos_end = (2, c)
print("人类获胜")
break

if fork_count == 3:
self.__game_status = GameStatus.FORK_WIN
self.__win_pos_start = (0, c)
self.__win_pos_end = (2, c)
print("电脑获胜")
break

if self.__game_status != GameStatus.PLAYING:
return

for r in range(3):
circle_count = 0
fork_count = 0
for c in range(3):
if self.__chess_map[r][c] == ChessType.CIRCLE:
circle_count += 1
elif self.__chess_map[r][c] == ChessType.FORK:
fork_count += 1

if circle_count == 3:
self.__game_status = GameStatus.CIRCLE_WIN
self.__win_pos_start = (r, 0)
self.__win_pos_end = (r, 2)
print("人类获胜")
break

if fork_count == 3:
self.__game_status = GameStatus.FORK_WIN
self.__win_pos_start = (r, 0)
self.__win_pos_end = (r, 2)
print("电脑获胜")
break

if self.__game_status != GameStatus.PLAYING:
return

if self.__chess_map[0][0] == ChessType.CIRCLE and self.__chess_map[1][1] == ChessType.CIRCLE and self.__chess_map[2][2] == ChessType.CIRCLE:
self.__game_status = GameStatus.CIRCLE_WIN
self.__win_pos_start = (0,0)
self.__win_pos_end = (2,2)
elif self.__chess_map[0][0] == ChessType.FORK and self.__chess_map[1][1] == ChessType.FORK and self.__chess_map[2][2] == ChessType.FORK:
self.__game_status = GameStatus.FORK_WIN
self.__win_pos_start = (0,0)
self.__win_pos_end = (2,2)
elif self.__chess_map[2][0] == ChessType.CIRCLE and self.__chess_map[1][1] == ChessType.CIRCLE and self.__chess_map[0][2] == ChessType.CIRCLE:
self.__game_status = GameStatus.CIRCLE_WIN
self.__win_pos_start = (2,0)
self.__win_pos_end = (0, 2)
elif self.__chess_map[2][0] == ChessType.FORK and self.__chess_map[1][1] == ChessType.FORK and self.__chess_map[0][2] == ChessType.FORK:
self.__game_status = GameStatus.FORK_WIN
self.__win_pos_start = (2,0)
self.__win_pos_end = (0,2)

if self.__game_status != GameStatus.PLAYING:
return

has_empty = False
for r in range(3):
for c in range(3):
if self.__chess_map[r][c] == ChessType.EMPTY:
has_empty = True
break
if has_empty == True:
break
if not has_empty:
self.__game_status == GameStatus.TIE

def __get_mouse_on_board_pos(self,
board_pos: Tuple[int, int],
cell_size: int,
mouse_pos:Tuple[int, int]) ->Tuple[int, int]:
"""
获取当前鼠标位置在棋盘中的行列位置(index)(eg(0,0)(0,1)(0,2),...(2,0)(2,1)(2,2)),鼠标没有在棋盘中返回(-1,-1)
"""

assert self #为了防止报错或者warning
board_x, board_y = board_pos[0], board_pos[1]
mouse_x, mouse_y = mouse_pos[0], mouse_pos[1]

x, y = mouse_x - board_x, mouse_y - board_y #用相对距离

if x < 0 or y < 0 or x >= cell_size * 3 or y >= cell_size * 3:
return -1, -1
# 竖直方向表示行,水平方向表示列
return y // cell_size, x // cell_size

def on_mouse_left_button_down(self, pos_x: int, pos_y: int):
"""
鼠标左键按下
"""
self.__curr_mouse_down_pos = (pos_x, pos_y)

def on_mouse_motion(self, pos_x:int, pos_y:int):
self.__curr_mouse_motion_pos = (pos_x, pos_y)


def draw(self, screen: pygame.Surface):
#填充背景
screen.fill(BG_COLOR)

#绘制棋盘
board_cell_size = 100
board_x = round(screen.get_width() / 2 - (3 * board_cell_size) / 2)
board_y = round(screen.get_height() / 2 - (3 * board_cell_size) / 2)
self.__draw_board(screen, (board_x,board_y),board_cell_size,3)

# 如果处于游戏中,判断鼠标(人类)是否有落子
if self.__game_status == GameStatus.PLAYING and self.__curr_mouse_down_pos:
row, col = self.__get_mouse_on_board_pos((board_x, board_y), board_cell_size, self.__curr_mouse_down_pos)
# 人类落子
self.__chess_map[row][col] = ChessType.CIRCLE
print(f"人类(点击落子):({row}, {col}) <- 圈")
self.__check_game_over()
if self.__game_status == GameStatus.PLAYING:
self.__computer_chess()
self.__check_game_over()
self.__curr_mouse_down_pos = None

if self.__game_status != GameStatus.PLAYING and self.__curr_mouse_down_pos:
self.__init()

self.__draw_chess(screen, (board_x,board_y),board_cell_size,20,5)
self.__draw_win_line(screen, (board_x,board_y),board_cell_size,3)
self.__draw_hint_text(screen, (board_x,board_y),board_cell_size)

def __draw_board(self, screen:pygame.Surface, board_pos:Tuple[int, int], cell_size:int, line_width:int):
"""
绘制棋盘
"""
assert self
x, y = board_pos[0], board_pos[1]
#横线
x1 = x
x2 = x + 3 * cell_size
y1 = y + cell_size
y2 = y + 2 * cell_size
pygame.draw.line(screen,BOARD_COLAR,(x1,y1),(x2, y1),line_width)
pygame.draw.line(screen,BOARD_COLAR,(x1,y2),(x2, y2),line_width)


y1 = y
y2 = y + 3 * cell_size
x1 = x + cell_size
x2 = x + 2 * cell_size
pygame.draw.line(screen,BOARD_COLAR,(x1,y1),(x1, y2),line_width)
pygame.draw.line(screen,BOARD_COLAR,(x2,y1),(x2, y2),line_width)


def __draw_chess(self,
screen:pygame.Surface,
board_pos:Tuple[int,int],
board_cell_size:int,
padding:int,
border_width:int):
"""
绘制棋子
"""

board_x, board_y = board_pos[0], board_pos[1]
for r in range(len(self.__chess_map)):
row = self.__chess_map[r]
for c in range(len(row)):
chess = row[c]
if chess == ChessType.CIRCLE:
self.__draw_circle_chess(screen,
(board_x + c * board_cell_size, board_y + r * board_cell_size),
board_cell_size,
padding,
border_width)
elif chess == ChessType.FORK:
self.__draw_fork_chess(screen,
(board_x + c * board_cell_size, board_y + r * board_cell_size),
board_cell_size,
padding,
border_width)

def __draw_circle_chess(self,
screen:pygame.Surface,
chess_pos:Tuple[int,int],
board_cell_size:int,
padding:int,
border_width:int):
"""
绘制圆棋子
"""
assert self
chess_x, chess_y = chess_pos[0], chess_pos[1]
center = round(chess_x + board_cell_size / 2), round(chess_y + board_cell_size / 2)
radius = round(board_cell_size / 2 - padding)
pygame.draw.circle(screen, CIRCLE_CHESS_COLOR, center, radius, border_width)

def __draw_fork_chess(self,
screen:pygame.Surface,
chess_pos:Tuple[int,int],
board_cell_size:int,
padding:int,
border_width:int):
"""
绘制叉棋子
"""
assert self
chess_x, chess_y = chess_pos[0], chess_pos[1]
pygame.draw.line(screen, FORK_CHESS_COLOR, (chess_x + padding, chess_y + padding), (chess_x + board_cell_size - padding, chess_y + board_cell_size - padding ), border_width)
pygame.draw.line(screen, FORK_CHESS_COLOR, (chess_x + board_cell_size - padding, chess_y + padding), (chess_x + padding, chess_y + board_cell_size - padding ), border_width)


def __draw_win_line(self,
screen:pygame.Surface,
board_pos:Tuple[int,int],
cell_size:int,
line_width:int):
"""
绘制获胜曲线
"""
if (not self.__win_pos_start) or (not self.__win_pos_end):
return

board_x, board_y = board_pos[0], board_pos[1]
pos_start_row, pos_start_col = self.__win_pos_start[0], self.__win_pos_start[1]
pos_end_row, pos_end_col = self.__win_pos_end[0], self.__win_pos_end[1]

half_cell_size = round(cell_size / 2)

start = (board_x + pos_start_col * cell_size + half_cell_size, board_y + pos_start_row * cell_size + half_cell_size)
end = (board_x + pos_end_col * cell_size + half_cell_size, board_y + pos_end_row * cell_size + half_cell_size)

pygame.draw.line(screen, WIN_LINE_COLOR, start, end, line_width)




def __draw_hint_text(self,
screen:pygame.Surface,
board_pos:Tuple[int,int],
cell_size:int,
):
board_y = board_pos[1]

if self.__game_status == GameStatus.CIRCLE_WIN:
screen.blit(self.__circle_win_hint_text, (screen.get_width() / 2 - self.__circle_win_hint_text.get_width() / 2, board_y / 2 - self.__circle_win_hint_text.get_height() / 2))
elif self.__game_status == GameStatus.FORK_WIN:
screen.blit(self.__fork_win_hint_text, (screen.get_width() / 2 - self.__fork_win_hint_text.get_width() / 2, board_y / 2 - self.__fork_win_hint_text.get_height() / 2))
elif self.__game_status == GameStatus.TIE:
screen.blit(self.__tie_hint_text, (screen.get_width() / 2 - self.__tie_hint_text.get_width() / 2, board_y / 2 - self.__tie_hint_text.get_height() / 2))


if self.__game_status != GameStatus.PLAYING:
#重新开始的提示
screen.blit(self.__restart_text, (screen.get_width() / 2 - self.__restart_text.get_width() / 2, (screen.get_height() + (board_y + cell_size * 3)) / 2 - self.__restart_text.get_height() / 2))






if __name__ == "__main__":
print("pygame is called")
main()

效果图

总体上来讲,NanaGo还是很强大的。

image-20240226093234898

image-20240226093418689


评论