赞
踩
五子棋是一种两人对弈的纯策略型棋类游戏。五子棋有两种玩法。玩法一:双方分别使用黑白两色的棋子,下在棋盘直线与横线的交叉点上,先形成五子连线者获胜。玩法二:自己形成五子连线就替换对方任意一枚棋子。被替换的棋子可以和对方交换棋子。最后以先出完所有棋子的一方为胜。本代码实现的是第一种玩法。
首先安装Python,再安装pip命令,最后安装pygame模块。
目前如果你在 python.org 下载最新版本的安装包,则是已经自带了该工具。
pip 是 Python 包管理工具,该工具提供了对Python 包的查找、下载、安装、卸载的功能。pip 官网: https://pypi.org/project/pip 注意:Python 2.7.9 + 或 Python 3.4+ 以上版本都自带 pip 工具。
你可以通过以下命令来判断是否已安装:pip --version
3. 安装pygame:pip install pygame
- SIZE = 30 # 棋盘每个点之间的间隔
- Line_Points = 19 # 棋盘每行/每列点数
- Outer_Width = 20 # 棋盘外宽度
- Border_Width = 4 # 边框宽度
- Inside_Width = 4 # 边框跟实际的棋盘之间的间隔
- Border_Length = SIZE * (Line_Points - 1) + Inside_Width * 2 + Border_Width # 边框线的长度
- Start_X = Start_Y = Outer_Width + int(Border_Width / 2) + Inside_Width # 网格线起点(左上角)坐标
- SCREEN_HEIGHT = SIZE * (Line_Points - 1) + Outer_Width * 2 + Border_Width + Inside_Width * 2 # 游戏屏幕的高
- SCREEN_WIDTH = SCREEN_HEIGHT + 200 # 游戏屏幕的宽
-
- Stone_Radius = SIZE // 2 - 3 # 棋子半径
- Stone_Radius2 = SIZE // 2 + 3
- Checkerboard_Color = (0xE3, 0x92, 0x65) # 棋盘颜色
- BLACK_COLOR = (0, 0, 0)
- WHITE_COLOR = (255, 255, 255)
- RED_COLOR = (200, 30, 30)
- BLUE_COLOR = (30, 30, 200)
- # 画棋盘
- def _draw_checkerboard(screen):
- # 填充棋盘背景色
- screen.fill(Checkerboard_Color)
- # 画棋盘网格线外的边框
- pygame.draw.rect(screen, BLACK_COLOR, (Outer_Width, Outer_Width, Border_Length, Border_Length), Border_Width)
- # 画网格线
- for i in range(Line_Points):
- pygame.draw.line(screen, BLACK_COLOR,
- (Start_Y, Start_Y + SIZE * i),
- (Start_Y + SIZE * (Line_Points - 1), Start_Y + SIZE * i),
- 1)
- for j in range(Line_Points):
- pygame.draw.line(screen, BLACK_COLOR,
- (Start_X + SIZE * j, Start_X),
- (Start_X + SIZE * j, Start_X + SIZE * (Line_Points - 1)),
- 1)
- def _get_direction_score(self, point, x_offset, y_offset):
- count = 0 # 落子处我方连续子数
- _count = 0 # 落子处对方连续子数
- space = None # 我方连续子中有无空格
- _space = None # 对方连续子中有无空格
- both = 0 # 我方连续子两端有无阻挡
- _both = 0 # 对方连续子两端有无阻挡
-
- # 如果是 1 表示是边上是我方子,2 表示敌方子
- flag = self._get_stone_color(point, x_offset, y_offset, True)
- if flag != 0:
- for step in range(1, 6):
- x = point.X + step * x_offset
- y = point.Y + step * y_offset
- if 0 <= x < self._line_points and 0 <= y < self._line_points:
- if flag == 1:
- if self._checkerboard[y][x] == self._my.Value:
- count += 1
- if space is False:
- space = True
- elif self._checkerboard[y][x] == self._opponent.Value:
- _both += 1
- break
- else:
- if space is None:
- space = False
- else:
- break # 遇到第二个空格退出
- elif flag == 2:
- if self._checkerboard[y][x] == self._my.Value:
- _both += 1
- break
- elif self._checkerboard[y][x] == self._opponent.Value:
- _count += 1
- if _space is False:
- _space = True
- else:
- if _space is None:
- _space = False
- else:
- break
- else:
- # 遇到边也就是阻挡
- if flag == 1:
- both += 1
- elif flag == 2:
- _both += 1
- if space is False:
- space = None
启动游戏:python aivsman.py
重置游戏: 任一方获胜后,按esc或enter键复原初始状态
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。