• python实现五子棋-人机对战/人人对战(动图演示+源码分享)


    大家好,我是梦执,对梦执着。希望能和大家共同进步!

     

     

    前言

    快520了,咱们来玩玩五子棋陶冶情操。快拿这个和你女朋友去对线。(分了别来找我哇)。多的不说直接进入正题

    人人对战

    游戏规则:p1为黑子,p2为白子,黑子先手,一方达到五子相连即为获胜。

    动态演示

    6a3ac41810024212b967d1539366a8c8.gif#pic_center

    源码分享

    cheackboard.py

    定义黑白子,落子位置以及获胜规则。

    1. from collections import namedtuple
    2. Chessman = namedtuple('Chessman', 'Name Value Color')
    3. Point = namedtuple('Point', 'X Y')
    4. BLACK_CHESSMAN = Chessman('黑子', 1, (45, 45, 45))
    5. WHITE_CHESSMAN = Chessman('白子', 2, (219, 219, 219))
    6. offset = [(1, 0), (0, 1), (1, 1), (1, -1)]
    7. class Checkerboard:
    8. def __init__(self, line_points):
    9. self._line_points = line_points
    10. self._checkerboard = [[0] * line_points for _ in range(line_points)]
    11. def _get_checkerboard(self):
    12. return self._checkerboard
    13. checkerboard = property(_get_checkerboard)
    14. # 判断是否可落子
    15. def can_drop(self, point):
    16. return self._checkerboard[point.Y][point.X] == 0
    17. def drop(self, chessman, point):
    18. """
    19. 落子
    20. :param chessman:
    21. :param point:落子位置
    22. :return:若该子落下之后即可获胜,则返回获胜方,否则返回 None
    23. """
    24. print(f'{chessman.Name} ({point.X}, {point.Y})')
    25. self._checkerboard[point.Y][point.X] = chessman.Value
    26. if self._win(point):
    27. print(f'{chessman.Name}获胜')
    28. return chessman
    29. # 判断是否赢了
    30. def _win(self, point):
    31. cur_value = self._checkerboard[point.Y][point.X]
    32. for os in offset:
    33. if self._get_count_on_direction(point, cur_value, os[0], os[1]):
    34. return True
    35. def _get_count_on_direction(self, point, value, x_offset, y_offset):
    36. count = 1
    37. for step in range(1, 5):
    38. x = point.X + step * x_offset
    39. y = point.Y + step * y_offset
    40. if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
    41. count += 1
    42. else:
    43. break
    44. for step in range(1, 5):
    45. x = point.X - step * x_offset
    46. y = point.Y - step * y_offset
    47. if 0 <= x < self._line_points and 0 <= y < self._line_points and self._checkerboard[y][x] == value:
    48. count += 1
    49. else:
    50. break
    51. return count >= 5

    人人对战.py

    导入模块

    如出现模块的错误,在pycharm终端输入如下指令。

    pip install 相应模块 -i https://pypi.douban.com/simple

    1. import sys
    2. import pygame
    3. from pygame.locals import *
    4. import pygame.gfxdraw
    5. from 小游戏.五子棋.checkerboard import Checkerboard, BLACK_CHESSMAN, WHITE_CHESSMAN, Point

    设置棋盘和棋子参数

    1. SIZE = 30 # 棋盘每个点时间的间隔
    2. Line_Points = 19 # 棋盘每行/每列点数
    3. Outer_Width = 20 # 棋盘外宽度
    4. Border_Width = 4 # 边框宽度
    5. Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
    6. Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度
    7. Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标
    8. SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高
    9. SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽
    10. Stone_Radius = SIZE // 2 - 3 # 棋子半径
    11. Stone_Radius2 = SIZE // 2 + 3
    12. Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色
    13. BLACK_COLOR = (0, 0, 0)
    14. WHITE_COLOR = (255, 255, 255)
    15. RED_COLOR = (200, 30, 30)
    16. BLUE_COLOR = (30, 30, 200)
    17. RIGHT_INFO_POS_X = SCREEN_HEIGHT + Stone_Radius2 * 2 + 10

    局内字体设置

    1. def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    2. imgText = font.render(text, True, fcolor)
    3. screen.blit(imgText, (x, y))
    4. def main():
    5. pygame.init()
    6. screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    7. pygame.display.set_caption('五子棋')
    8. font1 = pygame.font.SysFont('SimHei', 32)
    9. font2 = pygame.font.SysFont('SimHei', 72)
    10. fwidth, fheight = font2.size('黑方获胜')
    11. checkerboard = Checkerboard(Line_Points)
    12. cur_runner = BLACK_CHESSMAN
    13. winner = None
    14. computer = AI(Line_Points, WHITE_CHESSMAN)
    15. black_win_count = 0
    16. white_win_count = 0

    落子循坏体

    1. while True:
    2. for event in pygame.event.get():
    3. if event.type == QUIT:
    4. sys.exit()
    5. elif event.type == KEYDOWN:
    6. if event.key == K_RETURN:
    7. if winner is not None:
    8. winner = None
    9. cur_runner = BLACK_CHESSMAN
    10. checkerboard = Checkerboard(Line_Points)
    11. computer = AI(Line_Points, WHITE_CHESSMAN)
    12. elif event.type == MOUSEBUTTONDOWN:
    13. if winner is None:
    14. pressed_array = pygame.mouse.get_pressed()
    15. if pressed_array[0]:
    16. mouse_pos = pygame.mouse.get_pos()
    17. click_point = _get_clickpoint(mouse_pos)
    18. if click_point is not None:
    19. if checkerboard.can_drop(click_point):
    20. winner = checkerboard.drop(cur_runner, click_point)
    21. if winner is None:
    22. cur_runner = _get_next(cur_runner)
    23. computer.get_opponent_drop(click_point)
    24. AI_point = computer.AI_drop()
    25. winner = checkerboard.drop(cur_runner, AI_point)
    26. if winner is not None:
    27. white_win_count += 1
    28. cur_runner = _get_next(cur_runner)
    29. else:
    30. black_win_count += 1
    31. else:
    32. print('超出棋盘区域')

    画棋盘

    1. def _draw_checkerboard(screen):
    2. # 填充棋盘背景色
    3. screen.fill(Checkerboard_Color)
    4. # 画棋盘网格线外的边框
    5. pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
    6. # 画网格线
    7. for i in range(Line_Points):
    8. pygame.draw.line(screen, BLACK_COLOR,
    9. (Start_Y, Start_Y + SIZE * i),
    10. (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
    11. 1)
    12. for j in range(Line_Points):
    13. pygame.draw.line(screen, BLACK_COLOR,
    14. (Start_X + SIZE * j, Start_X),
    15. (Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
    16. 1)
    17. # 画星位和天元
    18. for i in (3, 9, 15):
    19. for j in (3, 9, 15):
    20. if i == j == 9:
    21. radius = 5
    22. else:
    23. radius = 3
    24. # pygame.draw.circle(screen, BLACK, (Start_X + SIZE * i, Start_Y + SIZE * j), radius)
    25. pygame.gfxdraw.aacircle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)
    26. pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * i, Start_Y + SIZE * j, radius, BLACK_COLOR)

    画棋子

    1. def _draw_chessman(screen, point, stone_color):
    2. # pygame.draw.circle(screen, stone_color, (Start_X + SIZE * point.X, Start_Y + SIZE * point.Y), Stone_Radius)
    3. pygame.gfxdraw.aacircle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
    4. pygame.gfxdraw.filled_circle(screen, Start_X + SIZE * point.X, Start_Y + SIZE * point.Y, Stone_Radius, stone_color)
    5. def _draw_chessman_pos(screen, pos, stone_color):
    6. pygame.gfxdraw.aacircle(screen, pos[0], pos[1], Stone_Radius2, stone_color)
    7. pygame.gfxdraw.filled_circle(screen, pos[0], pos[1], Stone_Radius2, stone_color)

    运行框返回落子坐标

    1. def _get_clickpoint(click_pos):
    2. pos_x = click_pos[0] - Start_X
    3. pos_y = click_pos[1] - Start_Y
    4. if pos_x < -Inside_Width or pos_y < -Inside_Width:
    5. return None
    6. x = pos_x // SIZE
    7. y = pos_y // SIZE
    8. if pos_x % SIZE > Stone_Radius:
    9. x += 1
    10. if pos_y % SIZE > Stone_Radius:
    11. y += 1
    12. if x >= Line_Points or y >= Line_Points:
    13. return None
    14. return Point(x, y)

    执行文件

    1. if __name__ == '__main__':
    2. main()

    人机对战

    动态演示

    8f6c6f8ebd794eea95f252b419444352.gif#pic_center

    all源码自取

    五子棋人机对战和人人对战的源码网盘自取:点击提取,提取码5201

     

  • 相关阅读:
    善用浏览器的一些调试技巧
    电脑系统重装后如何开启Win11实时辅助字幕
    [附源码]Python计算机毕业设计出版社样书申请管理系统
    C#界面里Control.Enabled 属性的使用
    2023秋招大疆C++开发笔试
    最远点采样 — D-FPS与F-FPS
    软件设计模式白话文系列(八)桥接模式
    Linux中的/proc文件系统详解(C/C++代码实现)
    计算机网络的性能指标
    【C++】C++基础知识(五)---数组
  • 原文地址:https://blog.csdn.net/m0_70127749/article/details/124838861