一 Pyhton实践项目之五子棋人机对战

【一 Pyhton实践项目之五子棋人机对战】1 """五子棋之人机对战"""23 import random4 import sys56 import pygame7 import pygame.gfxdraw8 from pygame.locals import *9 10 from checkerboard import Checkerboard, BLACK_CHESSMAN, WHITE_CHESSMAN, offset, Point 11 12 SIZE = 30# 棋盘每个点时间的间隔 13 Line_Points = 19# 棋盘每行/每列点数 14 Outer_Width = 20# 棋盘外宽度 15 Border_Width = 4# 边框宽度 16 Inside_Width = 4# 边框跟实际的棋盘之间的间隔 17 Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width# 边框线的长度 18 Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width# 网格线起点(左上角)坐标 19 SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2# 游戏屏幕的高 20 SCREEN_WIDTH = SCREEN_HEIGHT + 200# 游戏屏幕的宽 21 22 Stone_Radius = SIZE // 2 - 3# 棋子半径 23 Stone_Radius2 = SIZE // 2 + 3 24 Checkerboard_Color = (0xE3, 0x92, 0x65)# 棋盘颜色 25 BLACK_COLOR = (0, 0, 0) 26 WHITE_COLOR = (255, 255, 255) 27 RED_COLOR = (200, 30, 30) 28 BLUE_COLOR = (30, 30, 200) 29 30 RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10 31 32 33 def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)): 34imgText = font.render(text, True, fcolor) 35screen.blit(imgText, (x, y)) 36 37 38 def main(): 39pygame.init() 40screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) 41pygame.display.set_caption('五子棋') 42 43font1 = pygame.font.SysFont('SimHei', 32) 44font2 = pygame.font.SysFont('SimHei', 72) 45fwidth, fheight = font2.size('黑方获胜') 46 47checkerboard = Checkerboard(Line_Points) 48cur_runner = BLACK_CHESSMAN 49winner = None 50computer = AI(Line_Points, WHITE_CHESSMAN) 51 52black_win_count = 0 53white_win_count = 0 54 55while True: 56for event in pygame.event.get(): 57if event.type == QUIT: 58sys.exit() 59elif event.type == KEYDOWN: 60if event.key == K_RETURN: 61if winner is not None: 62winner = None 63cur_runner = BLACK_CHESSMAN 64checkerboard = Checkerboard(Line_Points) 65computer = AI(Line_Points, WHITE_CHESSMAN) 66elif event.type == MOUSEBUTTONDOWN: 67if winner is None: 68pressed_array = pygame.mouse.get_pressed() 69if pressed_array[0]: 70mouse_pos = pygame.mouse.get_pos() 71click_point = _get_clickpoint(mouse_pos) 72if click_point is not None: 73if checkerboard.can_drop(click_point): 74winner = checkerboard.drop(cur_runner, click_point) 75if winner is None: 76cur_runner = _get_next(cur_runner) 77computer.get_opponent_drop(click_point) 78AI_point = computer.AI_drop() 79winner = checkerboard.drop(cur_runner, AI_point) 80if winner is not None: 81white_win_count += 1 82cur_runner = _get_next(cur_runner) 83else: 84black_win_count += 1 85else: 86print('超出棋盘区域') 87 88# 画棋盘 89_draw_checkerboard(screen) 90 91# 画棋盘上已有的棋子 92for i, row in enumerate(checkerboard.checkerboard): 93for j, cell in enumerate(row): 94if cell == BLACK_CHESSMAN.Value: 95_draw_chessman(screen, Point(j, i), BLACK_CHESSMAN.Color) 96elif cell == WHITE_CHESSMAN.Value: 97_draw_chessman(screen, Point(j, i), WHITE_CHESSMAN.Color) 98 99_draw_left_info(screen, font1, cur_runner, black_win_count, white_win_count)100101if winner:102print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, winner.Name + '获胜',103RED_COLOR)104105pygame.display.flip()106107108 def _get_next(cur_runner):109if cur_runner == BLACK_CHESSMAN:110return WHITE_CHESSMAN111else:112return BLACK_CHESSMAN113114115 # 画棋盘116 def _draw_checkerboard(screen):117# 填充棋盘背景色118screen.fill(Checkerboard_Color)119# 画棋盘网格线外的边框120pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)121# 画网格线122for i in range(Line_Points):123pygame.draw.line(screen, BLACK_COLOR,124(Start_Y, Start_Y + SIZE * i),125(Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),1261)127for j in range(Line_Points):128pygame.draw.line(screen, BLACK_COLOR,129(Start_X + SIZE * j, Start_X),130(Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),1311)132# 画星位和天元133for i in (3, 9, 15):134for j in (3, 9, 15):135if i == j == 9:136radius = 5137else:138radius = 3139# pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)140pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)141pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)142143144 # 画棋子145 def _draw_chessman(screen, point, stone_color):146# pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)147pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)148pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)149150151 # 画左侧信息显示152 def _draw_left_info(screen, font, cur_runner, black_win_count, white_win_count):153_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2), BLACK_CHESSMAN.Color)154_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, Start_X + Stone_Radius2 * 4), WHITE_CHESSMAN.Color)155156print_text(screen, font, RIGHT_INFO_POS_X, Start_X + 3, '玩家', BLUE_COLOR)157print_text(screen, font, RIGHT_INFO_POS_X, Start_X + Stone_Radius2 * 3 + 3, '电脑', BLUE_COLOR)158159print_text(screen, font, SCREEN_HEIGHT, SCREEN_HEIGHT - Stone_Radius2 * 8, '战况:', BLUE_COLOR)160_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - int(Stone_Radius2 * 4.5)),161BLACK_CHESSMAN.Color)162_draw_chessman_pos(screen, (SCREEN_HEIGHT + Stone_Radius2, SCREEN_HEIGHT - Stone_Radius2 * 2), WHITE_CHESSMAN.Color)163print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - int(Stone_Radius2 * 5.5) + 3, f'{black_win_count} 胜',164BLUE_COLOR)165print_text(screen, font, RIGHT_INFO_POS_X, SCREEN_HEIGHT - Stone_Radius2 * 3 + 3, f'{white_win_count} 胜',166BLUE_COLOR)167168169 def _draw_chessman_pos(screen, pos, stone_color):170pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)171pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)172173174 # 根据鼠标点击位置,返回游戏区坐标175 def _get_clickpoint(click_pos):176pos_x = click_pos[0] - Start_X177pos_y = click_pos[1] - Start_Y178if pos_x < -Inside_Width or pos_y < -Inside_Width:179return None180x = pos_x // SIZE181y = pos_y // SIZE182if pos_x % SIZE > Stone_Radius:183x += 1184if pos_y % SIZE > Stone_Radius:185y += 1186if x >= Line_Points or y >= Line_Points:187return None188189return Point(x, y)190191192 class AI:193def __init__(self, line_points, chessman):194self._line_points = line_points195self._my = chessman196self._opponent = BLACK_CHESSMAN if chessman == WHITE_CHESSMAN else WHITE_CHESSMAN197self._checkerboard = [[0] * line_points for _ in range(line_points)]198199def get_opponent_drop(self, point):200self._checkerboard[point.Y][point.X] = self._opponent.Value201202def AI_drop(self):203point = None204score = 0205for i in range(self._line_points):206for j in range(self._line_points):207if self._checkerboard[j][i] == 0:208_score = self._get_point_score(Point(i, j))209if _score > score:210score = _score211point = Point(i, j)212elif _score == score and _score > 0:213r = random.randint(0, 100)214if r % 2 == 0:215point = Point(i, j)216self._checkerboard[point.Y][point.X] = self._my.Value217return point218219def _get_point_score(self, point):220score = 0221for os in offset:222score += self._get_direction_score(point, os[0], os[1])223return score224225def _get_direction_score(self, point, x_offset, y_offset):226count = 0# 落子处我方连续子数227_count = 0# 落子处对方连续子数228space = None# 我方连续子中有无空格229_space = None# 对方连续子中有无空格230both = 0# 我方连续子两端有无阻挡231_both = 0# 对方连续子两端有无阻挡232233# 如果是 1 表示是边上是我方子,2 表示敌方子234flag = self._get_stone_color(point, x_offset, y_offset, True)235if flag != 0:236for step in range(1, 6):237x = point.X + step * x_offset238y = point.Y + step * y_offset239if 0 <= x < self._line_points and 0 <= y < self._line_points:240if flag == 1:241if self._checkerboard[y][x] == self._my.Value:242count += 1243if space is False:244space = True245elif self._checkerboard[y][x] == self._opponent.Value:246_both += 1247break248else:249if space is None:250space = False251else:252break# 遇到第二个空格退出253elif flag == 2:254if self._checkerboard[y][x] == self._my.Value:255_both += 1256break257elif self._checkerboard[y][x] == self._opponent.Value:258_count += 1259if _space is False:260_space = True261else:262if _space is None:263_space = False264else:265break266else:267# 遇到边也就是阻挡268if flag == 1:269both += 1270elif flag == 2:271_both += 1272273if space is False:274space = None275if _space is False:276_space = None277278_flag = self._get_stone_color(point, -x_offset, -y_offset, True)279if _flag != 0:280for step in range(1, 6):281x = point.X - step * x_offset282y = point.Y - step * y_offset283if 0 <= x < self._line_points and 0 <= y < self._line_points:284if _flag == 1:285if self._checkerboard[y][x] == self._my.Value:286count += 1287if space is False:288space = True289elif self._checkerboard[y][x] == self._opponent.Value:290_both += 1291break292else:293if space is None:294space = False295else:296break# 遇到第二个空格退出297elif _flag == 2:298if self._checkerboard[y][x] == self._my.Value:299_both += 1300break301elif self._checkerboard[y][x] == self._opponent.Value:302_count += 1303if _space is False:304_space = True305else:306if _space is None:307_space = False308else:309break310else:311# 遇到边也就是阻挡312if _flag == 1:313both += 1314elif _flag == 2:315_both += 1316317score = 0318if count == 4:319score = 10000320elif _count == 4:321score = 9000322elif count == 3:323if both == 0:324score = 1000325elif both == 1:326score = 100327else:328score = 0329elif _count == 3:330if _both == 0:331score = 900332elif _both == 1:333score = 90334else:335score = 0336elif count == 2:337if both == 0:338score = 100339elif both == 1:340score = 10341else:342score = 0343elif _count == 2:344if _both == 0:345score = 90346elif _both == 1:347score = 9348else:349score = 0350elif count == 1:351score = 10352elif _count == 1:353score = 9354else:355score = 0356357if space or _space:358score /= 2359360return score361362# 判断指定位置处在指定方向上是我方子、对方子、空363def _get_stone_color(self, point, x_offset, y_offset, next):364x = point.X + x_offset365y = point.Y + y_offset366if 0 <= x < self._line_points and 0 <= y < self._line_points:367if self._checkerboard[y][x] == self._my.Value:368return 1369elif self._checkerboard[y][x] == self._opponent.Value:370return 2371else:372if next:373return self._get_stone_color(Point(x, y), x_offset, y_offset, False)374else:375return 0376else:377return 0378379380 if __name__ == '__main__':381main()

经验总结扩展阅读