注意:本篇文章是基于清华大学出版社,陈强教授编写的《Python项目实战开发》一书来行文的,具体有写的不清楚的地方,建议参考陈强教授写的具体内容,若写的有错误的地方,欢迎大家及时指出,更改。同时,本文适用于有一定Python基础的同学阅读学习,能够理解一定的算法思想。

对于pygame模块不是很清楚的可以参考文章点击这里

目录

1.系统架构分析

1.1五子棋的基本棋型

1.2功能模块

2.具体实现

2.1设置基础参数

2.2绘制棋盘

2.3编写函数intoNextTurn()

2.4编写函数getLocate()

2.5编写函数getIdex()

2.6编写函数isInside()

2.7编写函数isEmpty()

2.8编写函数printChessPiece()

2.9实现AI功能

2.9.1方法分析

2.9.2功能实现

2.10实现按钮功能

2.11实现重写功能(即游戏的调用函数)

3.完整代码及运行结果图

4.软件封装

4.1pyinstaller的简介

4.2pyinstaller的安装

4.3准备

4.4程序打包


1.系统架构分析

1.1五子棋的基本棋型

对五子棋游戏来说,有常见的七种基本棋型:连五,活四,冲四,活三,眠三,活二,眠二。

①连五:顾名思义,五颗同色棋子连在一起。
②活四:有两个连五点(即有两个点可以形成五)。
③冲四:有一个连五点,均为冲四棋型。
④活三:可以形成活四的三,代表两种最基本的活三棋型。活三棋型是进攻中最常见的一种,因为活三之后,如果对方不以理会,将可以下一手将活三变成活四,而活四是已经无法单纯防守住了。所以,当面对活三的时候,需要非常谨慎对待。在自己没有更好的进攻手段的情况下,需要对其进行防守,以防止其形成可怕的活四棋型。
⑤眠三:只能够形成冲四的三。眠三的棋型与活三的棋型相比,危险系数下降不少,因为眠三棋型即使不去防守,下一手它也只能形成冲四,而对于单纯的冲四棋型,是可以防守住的。
⑥活二:能够形成活三的二,是三种基本的活二棋型。活二棋型看起来似乎很无害,因为下一手棋才能形成活三,等形成活三,再防守也不迟。但其实活二棋型是非常重要的,尤其是在开局阶段,形成较多的活二棋型的话,将活二变成活三时,才能够令自己的活三绵绵不绝微风里,让对手防不胜防。
⑦眠二:能够形成眠三的二。

1.2功能模块

根据五子棋的游戏规则和基本棋型分析项目架构,最终得出的功能模块如下图:  

2.具体实现

2.1设置基础参数

在实例文件中,会多次用到这些基础参数,例如:设置棋盘单元格的大小,棋盘的大小,按钮的位置和大小信息等,故将这些基础参数写在代码前面,如下:

# 基础参数设置
square_size = 40  # 单格的宽度(不是格数!是为了方便绘制棋盘用的变量
chess_size = square_size // 2 - 2  # 棋子大小
web_broad = 15  # 棋盘格数+1(nxn)
map_w = web_broad * square_size  # 棋盘长度
map_h = web_broad * square_size  # 棋盘高度
info_w = 60  # 按钮界面宽度
button_w = 120  # 按钮长宽
button_h = 45
screen_w = map_w  # 总窗口长宽
screen_h = map_h + info_w

2.2绘制棋盘

在实例文件中,使用如下MAP_ENUM和Map两个类,来绘制棋盘的界面。

在MAP_ENUM类中使用的数字表示当前格子的使用情况,

class MAP_ENUM(IntEnum):  # 用数字表示当前格的情况be_empty = 0,  # 无人下player1 = 1,  # 玩家一,执白player2 = 2,  # 玩家二,执黑out_of_range = 3,  # 出界

在Map类中,使用self.map初始化二维数组来表示棋盘的大小,该数组中的值与类MAP_ENUM中的值对应,0表示空,该处没人下棋,1表示玩家一下的棋(在实例中为白棋),2表示玩家二下的棋,3表示超出允许下棋的界面,用self.steps来按顺序保存一下的棋子。

class Map:  # 地图类def __init__(self, width, height):  # 构造函数self.width = widthself.height = heightself.map = [[0 for x in range(self.width)] for y in range(self.height)]  # 存储棋盘的二维数组self.steps = []  # 记录步骤先后def get_init(self):  # 重置棋盘for y in range(self.height):for x in range(self.width):self.map[y][x] = 0self.steps = []

2.3编写函数intoNextTurn()

编写intoNextTurn()函数,意思是进入下一回合的比赛,交换下棋人。

    def intoNextTurn(self, turn):  # 进入下一回合,交换下棋人if turn == MAP_ENUM.player1:return MAP_ENUM.player2else:return MAP_ENUM.player1

2.4编写函数getLocate()

编写getLocate()函数,功能是根据出入的下标返回棋子的具体位置。

    def getLocate(self, x, y):  # 输入下标,返回具体位置map_x = x * square_sizemap_y = y * square_sizereturn (map_x, map_y, square_size, square_size)  # 返回位置信息

2.5编写函数getIdex()

编写getIdex()函数,功能是根据输入的具体位置,返回棋子的下标。

    def getIndex(self, map_x, map_y):  # 输入具体位置,返回下标x = map_x // square_sizey = map_y // square_sizereturn (x, y)

2.6编写函数isInside()

编写isInside()函数,功能是判断当前位置是否在棋盘的有效位置,即没有出界。

    def isInside(self, map_x, map_y):  # 是否在有效范围内if (map_x <= 0 or map_x >= map_w ormap_y <= 0 or map_y >= map_h):return Falsereturn True

2.7编写函数isEmpty()

编写isEmpty()函数,功能是判断当前的格子是否已经存在棋子。

    def isEmpty(self, x, y):  # 当前格子是否已经有棋子return (self.map[y][x] == 0)

2.8编写函数printChessPiece()

编写printChessPiece()函数,功能是在棋盘中绘制已经下的棋子,并且会按照下棋的顺序加上序号,在绘制时会区分黑棋和白棋。

    def printChessPiece(self, screen):  # 绘制棋子player_one = (255, 245, 238)  # 象牙白player_two = (41, 36, 33)  # 烟灰player_color = [player_one, player_two]for i in range(len(self.steps)):x, y = self.steps[i]map_x, map_y, width, height = self.getLocate(x, y)pos, radius = (map_x + width // 2, map_y + height // 2), chess_sizeturn = self.map[y][x]pygame.draw.circle(screen, player_color[turn - 1], pos, radius)  # 画棋子def drawBoard(self, screen):  # 画棋盘color = (0, 0, 0)  # 线色for y in range(self.height):# 画横着的棋盘线start_pos, end_pos = (square_size // 2, square_size // 2 + square_size * y), (map_w - square_size // 2, square_size // 2 + square_size * y)pygame.draw.line(screen, color, start_pos, end_pos, 1)for x in range(self.width):# 画竖着的棋盘线start_pos, end_pos = (square_size // 2 + square_size * x, square_size // 2), (square_size // 2 + square_size * x, map_h - square_size // 2)pygame.draw.line(screen, color, start_pos, end_pos, 1)

2.9实现AI功能

2.9.1方法分析

在文章的一开始,已经说明了,五子棋游戏有七种基本棋型,那么究竟如何记录棋盘上个的棋型个数呢?我们可以创建黑棋和白棋两个数组,记录棋盘上的黑棋和白棋分别形成的所有棋型的个数,然后按照一定的评分规则进行评分。本文的记录棋型的方法就是对整个棋盘进行遍历,对于每一个白棋或者黑棋,以它为中心,记录符合棋型的个数。具体诗仙女如下:

1)遍历棋盘上的每个点,对这个点所在的四个方向(水平,竖直,\,/)形成的四条线进行评估。

2)对于一条具体的线,以它为中心,取这条线为方向上的前后各四个点,组成一个长度为9的数组。

3)找出这个长度为9的数组里面和中心点相同颜色的棋子有多少,在进行下一次评估的时候要将在数组内的同色棋子排除,避免重复统计棋型。

4)根据棋盘上的黑棋和白棋的棋型信息,按照一定的评分规则进行评分。值得注意一点的是,在评分的时候要标记最后一步棋是什么颜色的,因为,假设,最后一步是黑棋下的(评分规则是黑棋得分-白棋得分),那么在相同棋型和相同个数的情况下,即评分相同,白棋会占优,因为下一步是白棋下。本实例按照下面的评分规则进行依次匹配:
黑棋连五,评分为10000,
白棋连五,评分为-10000,
黑棋有两个冲四,可以当成一个活四,
白棋有活四,评分为-9050,
白棋有冲四,评分为-9040,
黑棋有活四,评分为9030,
黑棋有冲四和活三,评分为9020,
黑棋没有冲四,且白棋有活三,评分为9010,
黑棋有2个活三,且白棋没有活三或眠三,评分为9000,
最后针对黑棋或者白棋的活三,眠三,活二,眠二的个数进行依次增加分数,具体评分值为(黑棋得分-白棋得分)。

2.9.2功能实现

有了上面的评分标准后,当轮到AI下棋的时候,只要针对当前的棋型,找到一个最有利的位置进行下棋即可。下面进行编写评估函数,来获取最有利的位置:
先遍历整个棋盘的每一个空点,并在这个空点上下棋,获取新的棋局评分,
如果是比之前更高的得分,则保存该位置,
然后将这个位置恢复为空点,
最后获取最高得分的位置。

在实例文件中,通过类MyChessAI实现AI的功能,实现流程如下:
1)使用构造函数试下初始化的功能,在数组record中记录所有位置的4个方向是否被检测过,使用二维数组count记录白棋和黑棋的棋型个数统计。通过position_isgreat方法给棋盘上的每个位置设置一个初始分数,越靠近棋盘中心,分数越高,这样在最初没有任何棋型的时候,AI会优先选择靠近中心的位置。

class MyChessAI():def __init__(self, chess_len):  # 构造函数self.len = chess_len  # 当前棋盘大小# 二维数组,每一格存的是:横评分,纵评分,左斜评分,右斜评分self.record = [[[0, 0, 0, 0] for i in range(chess_len)] for j in range(chess_len)]# 存储当前格具体棋型数量self.count = [[0 for i in range(SITUATION_NUM)] for j in range(2)]# 位置分(同条件下越靠近棋盘中央越高)self.position_isgreat = [[(web_broad - max(abs(i - web_broad / 2 + 1), abs(j - web_broad / 2 + 1))) for i in range(chess_len)]for j in range(chess_len)]def get_init(self):  # 初始化for i in range(self.len):for j in range(self.len):for k in range(4):self.record[i][j][k] = 0for i in range(len(self.count)):for j in range(len(self.count[0])):self.count[i][j] = 0self.save_count = 0def isWin(self, board, turn):  # 当前人胜利return self.evaluate(board, turn, True)

2)编写函数genmove(),功能是返回所有没有下棋的坐标(位置从好到坏)。

    def genmove(self, board, turn):moves = []for y in range(self.len):for x in range(self.len):if board[y][x] == 0:score = self.position_isgreat[y][x]moves.append((score, x, y))moves.sort(reverse=True)return moves

3)编写search()函数,功能是返回当前最优解的下标。先通过函数genmove()获取棋盘上所有的点,然后一次尝试,获得评分最高的位置,并且返回。

    def search(self, board, turn):moves = self.genmove(board, turn)bestmove = Nonemax_score = -99999  # 无穷小for score, x, y in moves:board[y][x] = turn.valuescore = self.evaluate(board, turn)board[y][x] = 0if score > max_score:max_score = scorebestmove = (max_score, x, y)return bestmove

4)编写函数getScore(),功能是对黑棋和白棋进行评分。

    def getScore(self, mychess, yourchess):mscore, oscore = 0, 0if mychess[FIVE] > 0:return (10000, 0)if yourchess[FIVE] > 0:return (0, 10000)if mychess[S4] >= 2:mychess[L4] += 1if yourchess[L4] > 0:return (0, 9050)if yourchess[S4] > 0:return (0, 9040)if mychess[L4] > 0:return (9030, 0)if mychess[S4] > 0 and mychess[L3] > 0:return (9020, 0)if yourchess[L3] > 0 and mychess[S4] == 0:return (0, 9010)if (mychess[L3] > 1 and yourchess[L3] == 0 and yourchess[S3] == 0):return (9000, 0)if mychess[S4] > 0:mscore += 2000if mychess[L3] > 1:mscore += 500elif mychess[L3] > 0:mscore += 100if yourchess[L3] > 1:oscore += 2000elif yourchess[L3] > 0:oscore += 400if mychess[S3] > 0:mscore += mychess[S3] * 10if yourchess[S3] > 0:oscore += yourchess[S3] * 10if mychess[L2] > 0:mscore += mychess[L2] * 4if yourchess[L2] > 0:oscore += yourchess[L2] * 4if mychess[S2] > 0:mscore += mychess[S2] * 4if yourchess[S2] > 0:oscore += yourchess[S2] * 4return (mscore, oscore)  # 自我辅助效果,counter对面效果

5)编写evaluate()函数,功能是对上面的得分进行进一步的处理,参数turn表示最后一步棋是谁下的,根据turn的值决定的me(表示自己棋的值)和you(表示对手棋的值,下一步有对手下),在对棋型评分时会用到。checkWin用来判断是否有一方获胜。

    def evaluate(self, board, turn, checkWin=False):self.get_init()if turn == MAP_ENUM.player1:me = 1you = 2else:me = 2you = 1for y in range(self.len):for x in range(self.len):if board[y][x] == me:self.evaluatePoint(board, x, y, me, you)elif board[y][x] == you:self.evaluatePoint(board, x, y, you, me)mychess = self.count[me - 1]yourchess = self.count[you - 1]if checkWin:return mychess[FIVE] > 0  # 检查是否已经胜利else:mscore, oscore = self.getScore(mychess, yourchess)return (mscore - oscore)  # 自我辅助效果,counter对面效果

6)编写函数evaluatePoint(),功能是对某一个位置的4个方向分别进行检查。

    def evaluatePoint(self, board, x, y, me, you):direction = [(1, 0), (0, 1), (1, 1), (1, -1)]  # 四个方向for i in range(4):if self.record[y][x][i] == 0:# 检查当前方向棋型self.getBasicSituation(board, x, y, i, direction[i], me, you, self.count[me - 1])else:self.save_count += 1

7)编写getLine()函数,功能是把当前方向的棋型存储下来,方便后续的使用。改函数能够根据棋子的位置和方向,获取上面说的长度为9的线。如果线上的位置超出了棋盘的范围,就将这个位置设置为对手的值,因为超出范围和被对手的棋当着,对棋型判断的结果是相同的。

    def getLine(self, board, x, y, direction, me, you):line = [0 for i in range(9)]# “光标”移到最左端tmp_x = x + (-5 * direction[0])tmp_y = y + (-5 * direction[1])for i in range(9):tmp_x += direction[0]tmp_y += direction[1]if (tmp_x < 0 or tmp_x >= self.len or tmp_y < 0 or tmp_y >= self.len):line[i] = you  # 出界else:line[i] = board[tmp_y][tmp_x]return line

8)编写函数getBasicSituation(),功能是把当前方向的棋型识别成具体的情况,例如把MMMMX识别成活四冲四,活三眠三等。

    def getBasicSituation(self, board, x, y, dir_index, dir, me, you, count):# record赋值def setRecord(self, x, y, left, right, dir_index, direction):tmp_x = x + (-5 + left) * direction[0]tmp_y = y + (-5 + left) * direction[1]for i in range(left, right):tmp_x += direction[0]tmp_y += direction[1]self.record[tmp_y][tmp_x][dir_index] = 1empty = MAP_ENUM.be_empty.valueleft_index, right_index = 4, 4line = self.getLine(board, x, y, dir, me, you)while right_index < 8:if line[right_index + 1] != me:breakright_index += 1while left_index > 0:if line[left_index - 1] != me:breakleft_index -= 1left_range, right_range = left_index, right_indexwhile right_range < 8:if line[right_range + 1] == you:breakright_range += 1while left_range > 0:if line[left_range - 1] == you:breakleft_range -= 1chess_range = right_range - left_range + 1if chess_range < 5:setRecord(self, x, y, left_range, right_range, dir_index, dir)return SITUATION.NONEsetRecord(self, x, y, left_index, right_index, dir_index, dir)m_range = right_index - left_index + 1if m_range == 5:count[FIVE] += 1# 活四冲四if m_range == 4:left_empty = right_empty = Falseif line[left_index - 1] == empty:left_empty = Trueif line[right_index + 1] == empty:right_empty = Trueif left_empty and right_empty:count[L4] += 1elif left_empty or right_empty:count[S4] += 1# 活三眠三if m_range == 3:left_empty = right_empty = Falseleft_four = right_four = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:  # MXMMMsetRecord(self, x, y, left_index - 2, left_index - 1, dir_index, dir)count[S4] += 1left_four = Trueleft_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:  # MMMXMsetRecord(self, x, y, right_index + 1, right_index + 2, dir_index, dir)count[S4] += 1right_four = Trueright_empty = Trueif left_four or right_four:passelif left_empty and right_empty:if chess_range > 5:  # XMMMXX, XXMMMXcount[L3] += 1else:  # PXMMMXPcount[S3] += 1elif left_empty or right_empty:  # PMMMX, XMMMPcount[S3] += 1# 活二眠二if m_range == 2:left_empty = right_empty = Falseleft_three = right_three = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:setRecord(self, x, y, left_index - 2, left_index - 1, dir_index, dir)if line[left_index - 3] == empty:if line[right_index + 1] == empty:  # XMXMMXcount[L3] += 1else:  # XMXMMPcount[S3] += 1left_three = Trueelif line[left_index - 3] == you:  # PMXMMXif line[right_index + 1] == empty:count[S3] += 1left_three = Trueleft_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:if line[right_index + 3] == me:  # MMXMMsetRecord(self, x, y, right_index + 1, right_index + 2, dir_index, dir)count[S4] += 1right_three = Trueelif line[right_index + 3] == empty:# setRecord(self, x, y, right_index+1, right_index+2, dir_index, dir)if left_empty:  # XMMXMXcount[L3] += 1else:  # PMMXMXcount[S3] += 1right_three = Trueelif left_empty:  # XMMXMPcount[S3] += 1right_three = Trueright_empty = Trueif left_three or right_three:passelif left_empty and right_empty:  # XMMXcount[L2] += 1elif left_empty or right_empty:  # PMMX, XMMPcount[S2] += 1# 特殊活二眠二(有空格if m_range == 1:left_empty = right_empty = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:if line[left_index - 3] == empty:if line[right_index + 1] == you:  # XMXMPcount[S2] += 1left_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:if line[right_index + 3] == empty:if left_empty:  # XMXMXcount[L2] += 1else:  # PMXMXcount[S2] += 1elif line[right_index + 2] == empty:if line[right_index + 3] == me and line[right_index + 4] == empty:  # XMXXMXcount[L2] += 1# 以上都不是则为none棋型return SITUATION.NONE

2.10实现按钮功能

该游戏的界面上会有四个按钮:
Pick White:选择白棋
Pick Black:选择黑棋
Surrender:投降
Multiple:多人对战

1)编写游戏的按钮类button,这是一个父类,通过函数draw()根据按钮的enablel状态填色。

class Button:def __init__(self, screen, text, x, y, color, enable):  # 构造函数self.screen = screenself.width = button_wself.height = button_hself.button_color = colorself.text_color = (255, 255, 255)  # 纯白self.enable = enableself.font = pygame.font.SysFont(None, button_h * 2 // 3)self.rect = pygame.Rect(0, 0, self.width, self.height)self.rect.topleft = (x, y)self.text = textself.init_msg()# 重写pygame内置函数,初始化我们的按钮def init_msg(self):if self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])else:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.center# 根据按钮enable状态填色,具体颜色在后续子类控制def draw(self):if self.enable:self.screen.fill(self.button_color[0], self.rect)else:self.screen.fill(self.button_color[1], self.rect)self.screen.blit(self.msg_image, self.msg_image_rect)

2)编写类WhiteStartButton,实现选择白棋的功能。

class WhiteStartButton(Button):  # 开始按钮(选白棋)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(26, 173, 25), (158, 217, 157)], True)def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色game.start()game.winner = Nonegame.multiple = Falseself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = True

3)编写类BlackStartButton,实现选择黑棋的功能。

class BlackStartButton(Button):  # 开始按钮(选黑棋)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(26, 173, 25), (158, 217, 157)], True)def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色,安排AI先手game.start()game.winner = Nonegame.multiple = Falsegame.useAI = Trueself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = True

4)编写类GiveupButton,实现投降功能。

class GiveupButton(Button):  # 投降按钮(任何模式都能用def __init__(self, screen, text, x, y):super().__init__(screen, text, x, y, [(230, 67, 64), (236, 139, 137)], False)def click(self, game):  # 结束游戏,判断赢家if self.enable:game.is_play = Falseif game.winner is None:game.winner = game.map.intoNextTurn(game.player)self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 保持不变,填充颜色if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = True

5)编写类MultiStartButton,实现多人对战功能。

class MultiStartButton(Button):  # 开始按钮(多人游戏)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(153, 51, 250), (221, 160, 221)], True)  # 紫色def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色game.start()game.winner = Nonegame.multiple=Trueself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = True

2.11实现重写功能(即游戏的调用函数)

为了更好地在主函数中规划和控住整个游戏的代码,编写Game类,在Game类中调用上面的功能函数,然后分别绘制棋盘、按钮和判断获胜的一方。

1)通过__init__(self, caption)实现初始化处理,设置按钮的内容和可用性。

class Game:  # pygame类,以下所有功能都是根据需要重写def __init__(self, caption):# 使用pygame之前必须初始化pygame.init()self.screen = pygame.display.set_mode([screen_w, screen_h])        # 设置主屏窗口pygame.display.set_caption(caption)       #设置窗口标题,即游戏名称self.clock = pygame.time.Clock()self.buttons = []self.buttons.append(WhiteStartButton(self.screen, 'Pick White', 10, map_h))self.buttons.append(BlackStartButton(self.screen, 'Pick Black', 170, map_h))self.buttons.append(GiveupButton(self.screen, 'Surrender', 330, map_h))self.buttons.append(MultiStartButton(self.screen, 'Multiple', 490, map_h))self.is_play = Falseself.map = Map(web_broad, web_broad)self.player = MAP_ENUM.player1self.action = Noneself.AI = MyChessAI(web_broad)self.useAI = Falseself.winner = Noneself.multiple = False

2)定义函数start(self),功能为开始游戏,默认白棋先下。

    def start(self):self.is_play = Trueself.player = MAP_ENUM.player1  # 白棋先手self.map.get_init()

3)定义函数play(self),绘制出棋盘和按钮。

    def play(self):# 画底板self.clock.tick(60)wood_color = (210, 180, 140)pygame.draw.rect(self.screen, wood_color, pygame.Rect(0, 0, map_w, screen_h))pygame.draw.rect(self.screen, (255, 255, 255), pygame.Rect(map_w, 0, info_w, screen_h))# 画按钮for button in self.buttons:button.draw()if self.is_play and not self.isOver():if self.useAI and not self.multiple:x, y = self.AI.findBestChess(self.map.map, self.player)self.checkClick(x, y, True)self.useAI = Falseif self.action is not None:self.checkClick(self.action[0], self.action[1])self.action = Noneif not self.isOver():self.changeMouseShow()if self.isOver():self.showWinner()# self.buttons[0].enable = True# self.buttons[1].enable = True# self.buttons[2].enable = Falseself.map.drawBoard(self.screen)self.map.printChessPiece(self.screen)

4)定义函数changeMouseShow(self),在开始游戏的时候吧鼠标指针切换成棋子的形态。

    def changeMouseShow(self):  # 开始游戏的时候把鼠标预览切换成预览棋子的样子map_x, map_y = pygame.mouse.get_pos()x, y = self.map.getIndex(map_x, map_y)if self.map.isInside(map_x, map_y) and self.map.isEmpty(x, y):  # 在棋盘内且当前无棋子pygame.mouse.set_visible(False)smoke_blue = (176, 224, 230)pos, radius = (map_x, map_y), chess_sizepygame.draw.circle(self.screen, smoke_blue, pos, radius)else:pygame.mouse.set_visible(True)def checkClick(self, x, y, isAI=False):  # 后续处理self.map.click(x, y, self.player)if self.AI.isWin(self.map.map, self.player):self.winner = self.playerself.click_button(self.buttons[2])else:self.player = self.map.intoNextTurn(self.player)if not isAI:self.useAI = True

5)定义函数mouseClick(self, map_x, map_y),处理下棋动作,将某个棋子放到棋盘中的某个位置。

    def mouseClick(self, map_x, map_y):  # 处理下棋动作if self.is_play and self.map.isInside(map_x, map_y) and not self.isOver():x, y = self.map.getIndex(map_x, map_y)if self.map.isEmpty(x, y):self.action = (x, y)

6)定义函数isOver(self),如果一方获胜则中断游戏。

    def isOver(self):  # 中断条件return self.winner is not None

7)定义函数showWinner(self),功能是打印输出获胜者。

    def showWinner(self):  # 输出胜者def showFont(screen, text, location_x, locaiton_y, height):font = pygame.font.SysFont(None, height)font_image = font.render(text, True, (255, 215, 0), (255, 255, 255))  # 金黄色font_image_rect = font_image.get_rect()font_image_rect.x = location_xfont_image_rect.y = locaiton_yscreen.blit(font_image, font_image_rect)if self.winner == MAP_ENUM.player1:str = 'White Wins!'else:str = 'Black Wins!'showFont(self.screen, str, map_w / 5, screen_h / 8, 100)  # 居上中,字号100pygame.mouse.set_visible(True)

8)游戏开始入口

if __name__ == '__main__':game = Game(version)while True:game.play()# 更新屏幕内容pygame.display.update()# 循环获取事件,监听事件状态for event in pygame.event.get():# 判断用户是否点了"X"关闭按钮,并执行if代码段if event.type == pygame.QUIT:# 卸载所有模块pygame.quit()# 终止程序,确保退出程序sys.exit()elif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()game.mouseClick(mouse_x, mouse_y)game.check_buttons(mouse_x, mouse_y)

3.完整代码及运行结果图

完整代码如下:

import time
from enum import IntEnum
import pygame
import sys
t = time.localtime()
date = str(t.tm_year) + '-' + str(t.tm_mon) + '-' + str(t.tm_mday) + ' ' + str(t.tm_hour) + ':' + str(t.tm_min) + ':' + str(t.tm_sec)
version = 'FiveChessV1.0  作者:栩珩  time:' + date# 基础参数设置
square_size = 40  # 单格的宽度(不是格数!是为了方便绘制棋盘用的变量
chess_size = square_size // 2 - 2  # 棋子大小
web_broad = 15  # 棋盘格数+1(nxn)
map_w = web_broad * square_size  # 棋盘长度
map_h = web_broad * square_size  # 棋盘高度
info_w = 60  # 按钮界面宽度
button_w = 120  # 按钮长宽
button_h = 45
screen_w = map_w  # 总窗口长宽
screen_h = map_h + info_w# 地图绘制模块class MAP_ENUM(IntEnum):  # 用数字表示当前格的情况be_empty = 0,  # 无人下player1 = 1,  # 玩家一,执白player2 = 2,  # 玩家二,执黑out_of_range = 3,  # 出界class Map:  # 地图类def __init__(self, width, height):  # 构造函数self.width = widthself.height = heightself.map = [[0 for x in range(self.width)] for y in range(self.height)]  # 存储棋盘的二维数组self.steps = []  # 记录步骤先后def get_init(self):  # 重置棋盘for y in range(self.height):for x in range(self.width):self.map[y][x] = 0self.steps = []def intoNextTurn(self, turn):  # 进入下一回合,交换下棋人if turn == MAP_ENUM.player1:return MAP_ENUM.player2else:return MAP_ENUM.player1def getLocate(self, x, y):  # 输入下标,返回具体位置map_x = x * square_sizemap_y = y * square_sizereturn (map_x, map_y, square_size, square_size)  # 返回位置信息def getIndex(self, map_x, map_y):  # 输入具体位置,返回下标x = map_x // square_sizey = map_y // square_sizereturn (x, y)def isInside(self, map_x, map_y):  # 是否在有效范围内if (map_x <= 0 or map_x >= map_w ormap_y <= 0 or map_y >= map_h):return Falsereturn Truedef isEmpty(self, x, y):  # 当前格子是否已经有棋子return (self.map[y][x] == 0)def click(self, x, y, type):  # 点击的下棋动作self.map[y][x] = type.value  # 下棋self.steps.append((x, y))  # 记录步骤信息def printChessPiece(self, screen):  # 绘制棋子player_one = (255, 245, 238)  # 象牙白player_two = (41, 36, 33)  # 烟灰player_color = [player_one, player_two]for i in range(len(self.steps)):x, y = self.steps[i]map_x, map_y, width, height = self.getLocate(x, y)pos, radius = (map_x + width // 2, map_y + height // 2), chess_sizeturn = self.map[y][x]pygame.draw.circle(screen, player_color[turn - 1], pos, radius)  # 画棋子def drawBoard(self, screen):  # 画棋盘color = (0, 0, 0)  # 线色for y in range(self.height):# 画横着的棋盘线start_pos, end_pos = (square_size // 2, square_size // 2 + square_size * y), (map_w - square_size // 2, square_size // 2 + square_size * y)pygame.draw.line(screen, color, start_pos, end_pos, 1)for x in range(self.width):# 画竖着的棋盘线start_pos, end_pos = (square_size // 2 + square_size * x, square_size // 2), (square_size // 2 + square_size * x, map_h - square_size // 2)pygame.draw.line(screen, color, start_pos, end_pos, 1)# 高级AI模块class SITUATION(IntEnum):  # 棋型NONE = 0,  # 无SLEEP_TWO = 1,  # 眠二LIVE_TWO = 2,  # 活二SLEEP_THREE = 3,  # 眠三LIVE_THREE = 4,  # 活三CHONG_FOUR = 5,  # 冲四LIVE_FOUR = 6,  # 活四LIVE_FIVE = 7,  # 活五SITUATION_NUM = 8  # 长度# 方便后续调用枚举内容
FIVE = SITUATION.LIVE_FIVE.value
L4, L3, L2 = SITUATION.LIVE_FOUR.value, SITUATION.LIVE_THREE.value, SITUATION.LIVE_TWO.value
S4, S3, S2 = SITUATION.CHONG_FOUR.value, SITUATION.SLEEP_THREE.value, SITUATION.SLEEP_TWO.valueclass MyChessAI():def __init__(self, chess_len):  # 构造函数self.len = chess_len  # 当前棋盘大小# 二维数组,每一格存的是:横评分,纵评分,左斜评分,右斜评分self.record = [[[0, 0, 0, 0] for i in range(chess_len)] for j in range(chess_len)]# 存储当前格具体棋型数量self.count = [[0 for i in range(SITUATION_NUM)] for j in range(2)]# 位置分(同条件下越靠近棋盘中央越高)self.position_isgreat = [[(web_broad - max(abs(i - web_broad / 2 + 1), abs(j - web_broad / 2 + 1))) for i in range(chess_len)]for j in range(chess_len)]def get_init(self):  # 初始化for i in range(self.len):for j in range(self.len):for k in range(4):self.record[i][j][k] = 0for i in range(len(self.count)):for j in range(len(self.count[0])):self.count[i][j] = 0self.save_count = 0def isWin(self, board, turn):  # 当前人胜利return self.evaluate(board, turn, True)# 返回所有未下棋坐标(位置从好到坏)def genmove(self, board, turn):moves = []for y in range(self.len):for x in range(self.len):if board[y][x] == 0:score = self.position_isgreat[y][x]moves.append((score, x, y))moves.sort(reverse=True)return moves# 返回当前最优解下标def search(self, board, turn):moves = self.genmove(board, turn)bestmove = Nonemax_score = -99999  # 无穷小for score, x, y in moves:board[y][x] = turn.valuescore = self.evaluate(board, turn)board[y][x] = 0if score > max_score:max_score = scorebestmove = (max_score, x, y)return bestmove# 主要用于测试的函数,现在已经没什么用def findBestChess(self, board, turn):# time1 = time.time()score, x, y = self.search(board, turn)# time2 = time.time()# print('time:%f  (%d, %d)' % ((time2 - time1), x, y))return (x, y)# 得出一点的评分# 直接列举所有棋型def getScore(self, mychess, yourchess):mscore, oscore = 0, 0if mychess[FIVE] > 0:return (10000, 0)if yourchess[FIVE] > 0:return (0, 10000)if mychess[S4] >= 2:mychess[L4] += 1if yourchess[L4] > 0:return (0, 9050)if yourchess[S4] > 0:return (0, 9040)if mychess[L4] > 0:return (9030, 0)if mychess[S4] > 0 and mychess[L3] > 0:return (9020, 0)if yourchess[L3] > 0 and mychess[S4] == 0:return (0, 9010)if (mychess[L3] > 1 and yourchess[L3] == 0 and yourchess[S3] == 0):return (9000, 0)if mychess[S4] > 0:mscore += 2000if mychess[L3] > 1:mscore += 500elif mychess[L3] > 0:mscore += 100if yourchess[L3] > 1:oscore += 2000elif yourchess[L3] > 0:oscore += 400if mychess[S3] > 0:mscore += mychess[S3] * 10if yourchess[S3] > 0:oscore += yourchess[S3] * 10if mychess[L2] > 0:mscore += mychess[L2] * 4if yourchess[L2] > 0:oscore += yourchess[L2] * 4if mychess[S2] > 0:mscore += mychess[S2] * 4if yourchess[S2] > 0:oscore += yourchess[S2] * 4return (mscore, oscore)  # 自我辅助效果,counter对面效果# 对上述得分进行进一步处理def evaluate(self, board, turn, checkWin=False):self.get_init()if turn == MAP_ENUM.player1:me = 1you = 2else:me = 2you = 1for y in range(self.len):for x in range(self.len):if board[y][x] == me:self.evaluatePoint(board, x, y, me, you)elif board[y][x] == you:self.evaluatePoint(board, x, y, you, me)mychess = self.count[me - 1]yourchess = self.count[you - 1]if checkWin:return mychess[FIVE] > 0  # 检查是否已经胜利else:mscore, oscore = self.getScore(mychess, yourchess)return (mscore - oscore)  # 自我辅助效果,counter对面效果def evaluatePoint(self, board, x, y, me, you):direction = [(1, 0), (0, 1), (1, 1), (1, -1)]  # 四个方向for i in range(4):if self.record[y][x][i] == 0:# 检查当前方向棋型self.getBasicSituation(board, x, y, i, direction[i], me, you, self.count[me - 1])else:self.save_count += 1# 把当前方向棋型存储下来,方便后续使用def getLine(self, board, x, y, direction, me, you):line = [0 for i in range(9)]# “光标”移到最左端tmp_x = x + (-5 * direction[0])tmp_y = y + (-5 * direction[1])for i in range(9):tmp_x += direction[0]tmp_y += direction[1]if (tmp_x < 0 or tmp_x >= self.len or tmp_y < 0 or tmp_y >= self.len):line[i] = you  # 出界else:line[i] = board[tmp_y][tmp_x]return line# 把当前方向的棋型识别成具体情况(如把MMMMX识别成冲四)def getBasicSituation(self, board, x, y, dir_index, dir, me, you, count):# record赋值def setRecord(self, x, y, left, right, dir_index, direction):tmp_x = x + (-5 + left) * direction[0]tmp_y = y + (-5 + left) * direction[1]for i in range(left, right):tmp_x += direction[0]tmp_y += direction[1]self.record[tmp_y][tmp_x][dir_index] = 1empty = MAP_ENUM.be_empty.valueleft_index, right_index = 4, 4line = self.getLine(board, x, y, dir, me, you)while right_index < 8:if line[right_index + 1] != me:breakright_index += 1while left_index > 0:if line[left_index - 1] != me:breakleft_index -= 1left_range, right_range = left_index, right_indexwhile right_range < 8:if line[right_range + 1] == you:breakright_range += 1while left_range > 0:if line[left_range - 1] == you:breakleft_range -= 1chess_range = right_range - left_range + 1if chess_range < 5:setRecord(self, x, y, left_range, right_range, dir_index, dir)return SITUATION.NONEsetRecord(self, x, y, left_index, right_index, dir_index, dir)m_range = right_index - left_index + 1if m_range == 5:count[FIVE] += 1# 活四冲四if m_range == 4:left_empty = right_empty = Falseif line[left_index - 1] == empty:left_empty = Trueif line[right_index + 1] == empty:right_empty = Trueif left_empty and right_empty:count[L4] += 1elif left_empty or right_empty:count[S4] += 1# 活三眠三if m_range == 3:left_empty = right_empty = Falseleft_four = right_four = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:  # MXMMMsetRecord(self, x, y, left_index - 2, left_index - 1, dir_index, dir)count[S4] += 1left_four = Trueleft_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:  # MMMXMsetRecord(self, x, y, right_index + 1, right_index + 2, dir_index, dir)count[S4] += 1right_four = Trueright_empty = Trueif left_four or right_four:passelif left_empty and right_empty:if chess_range > 5:  # XMMMXX, XXMMMXcount[L3] += 1else:  # PXMMMXPcount[S3] += 1elif left_empty or right_empty:  # PMMMX, XMMMPcount[S3] += 1# 活二眠二if m_range == 2:left_empty = right_empty = Falseleft_three = right_three = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:setRecord(self, x, y, left_index - 2, left_index - 1, dir_index, dir)if line[left_index - 3] == empty:if line[right_index + 1] == empty:  # XMXMMXcount[L3] += 1else:  # XMXMMPcount[S3] += 1left_three = Trueelif line[left_index - 3] == you:  # PMXMMXif line[right_index + 1] == empty:count[S3] += 1left_three = Trueleft_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:if line[right_index + 3] == me:  # MMXMMsetRecord(self, x, y, right_index + 1, right_index + 2, dir_index, dir)count[S4] += 1right_three = Trueelif line[right_index + 3] == empty:# setRecord(self, x, y, right_index+1, right_index+2, dir_index, dir)if left_empty:  # XMMXMXcount[L3] += 1else:  # PMMXMXcount[S3] += 1right_three = Trueelif left_empty:  # XMMXMPcount[S3] += 1right_three = Trueright_empty = Trueif left_three or right_three:passelif left_empty and right_empty:  # XMMXcount[L2] += 1elif left_empty or right_empty:  # PMMX, XMMPcount[S2] += 1# 特殊活二眠二(有空格if m_range == 1:left_empty = right_empty = Falseif line[left_index - 1] == empty:if line[left_index - 2] == me:if line[left_index - 3] == empty:if line[right_index + 1] == you:  # XMXMPcount[S2] += 1left_empty = Trueif line[right_index + 1] == empty:if line[right_index + 2] == me:if line[right_index + 3] == empty:if left_empty:  # XMXMXcount[L2] += 1else:  # PMXMXcount[S2] += 1elif line[right_index + 2] == empty:if line[right_index + 3] == me and line[right_index + 4] == empty:  # XMXXMXcount[L2] += 1# 以上都不是则为none棋型return SITUATION.NONE# 主程序实现部分# 控制进程按钮类(父类)
class Button:def __init__(self, screen, text, x, y, color, enable):  # 构造函数self.screen = screenself.width = button_wself.height = button_hself.button_color = colorself.text_color = (255, 255, 255)  # 纯白self.enable = enableself.font = pygame.font.SysFont(None, button_h * 2 // 3)self.rect = pygame.Rect(0, 0, self.width, self.height)self.rect.topleft = (x, y)self.text = textself.init_msg()# 重写pygame内置函数,初始化我们的按钮def init_msg(self):if self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])else:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.msg_image_rect = self.msg_image.get_rect()self.msg_image_rect.center = self.rect.center# 根据按钮enable状态填色,具体颜色在后续子类控制def draw(self):if self.enable:self.screen.fill(self.button_color[0], self.rect)else:self.screen.fill(self.button_color[1], self.rect)self.screen.blit(self.msg_image, self.msg_image_rect)class WhiteStartButton(Button):  # 开始按钮(选白棋)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(26, 173, 25), (158, 217, 157)], True)def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色game.start()game.winner = Nonegame.multiple = Falseself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = Trueclass BlackStartButton(Button):  # 开始按钮(选黑棋)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(26, 173, 25), (158, 217, 157)], True)def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色,安排AI先手game.start()game.winner = Nonegame.multiple = Falsegame.useAI = Trueself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = Trueclass GiveupButton(Button):  # 投降按钮(任何模式都能用def __init__(self, screen, text, x, y):super().__init__(screen, text, x, y, [(230, 67, 64), (236, 139, 137)], False)def click(self, game):  # 结束游戏,判断赢家if self.enable:game.is_play = Falseif game.winner is None:game.winner = game.map.intoNextTurn(game.player)self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 保持不变,填充颜色if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = Trueclass MultiStartButton(Button):  # 开始按钮(多人游戏)def __init__(self, screen, text, x, y):  # 构造函数super().__init__(screen, text, x, y, [(153, 51, 250), (221, 160, 221)], True)  # 紫色def click(self, game):  # 点击,pygame内置方法if self.enable:  # 启动游戏并初始化,变换按钮颜色game.start()game.winner = Nonegame.multiple=Trueself.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[1])self.enable = Falsereturn Truereturn Falsedef unclick(self):  # 取消点击if not self.enable:self.msg_image = self.font.render(self.text, True, self.text_color, self.button_color[0])self.enable = Trueclass Game:  # pygame类,以下所有功能都是根据需要重写def __init__(self, caption):# 使用pygame之前必须初始化pygame.init()self.screen = pygame.display.set_mode([screen_w, screen_h])        # 设置主屏窗口pygame.display.set_caption(caption)       #设置窗口标题,即游戏名称self.clock = pygame.time.Clock()self.buttons = []self.buttons.append(WhiteStartButton(self.screen, 'Pick White', 10, map_h))self.buttons.append(BlackStartButton(self.screen, 'Pick Black', 170, map_h))self.buttons.append(GiveupButton(self.screen, 'Surrender', 330, map_h))self.buttons.append(MultiStartButton(self.screen, 'Multiple', 490, map_h))self.is_play = Falseself.map = Map(web_broad, web_broad)self.player = MAP_ENUM.player1self.action = Noneself.AI = MyChessAI(web_broad)self.useAI = Falseself.winner = Noneself.multiple = Falsedef start(self):self.is_play = Trueself.player = MAP_ENUM.player1  # 白棋先手self.map.get_init()def play(self):# 画底板self.clock.tick(60)wood_color = (210, 180, 140)pygame.draw.rect(self.screen, wood_color, pygame.Rect(0, 0, map_w, screen_h))pygame.draw.rect(self.screen, (255, 255, 255), pygame.Rect(map_w, 0, info_w, screen_h))# 画按钮for button in self.buttons:button.draw()if self.is_play and not self.isOver():if self.useAI and not self.multiple:x, y = self.AI.findBestChess(self.map.map, self.player)self.checkClick(x, y, True)self.useAI = Falseif self.action is not None:self.checkClick(self.action[0], self.action[1])self.action = Noneif not self.isOver():self.changeMouseShow()if self.isOver():self.showWinner()# self.buttons[0].enable = True# self.buttons[1].enable = True# self.buttons[2].enable = Falseself.map.drawBoard(self.screen)self.map.printChessPiece(self.screen)def changeMouseShow(self):  # 开始游戏的时候把鼠标预览切换成预览棋子的样子map_x, map_y = pygame.mouse.get_pos()x, y = self.map.getIndex(map_x, map_y)if self.map.isInside(map_x, map_y) and self.map.isEmpty(x, y):  # 在棋盘内且当前无棋子pygame.mouse.set_visible(False)smoke_blue = (176, 224, 230)pos, radius = (map_x, map_y), chess_sizepygame.draw.circle(self.screen, smoke_blue, pos, radius)else:pygame.mouse.set_visible(True)def checkClick(self, x, y, isAI=False):  # 后续处理self.map.click(x, y, self.player)if self.AI.isWin(self.map.map, self.player):self.winner = self.playerself.click_button(self.buttons[2])else:self.player = self.map.intoNextTurn(self.player)if not isAI:self.useAI = Truedef mouseClick(self, map_x, map_y):  # 处理下棋动作if self.is_play and self.map.isInside(map_x, map_y) and not self.isOver():x, y = self.map.getIndex(map_x, map_y)if self.map.isEmpty(x, y):self.action = (x, y)def isOver(self):  # 中断条件return self.winner is not Nonedef showWinner(self):  # 输出胜者def showFont(screen, text, location_x, locaiton_y, height):font = pygame.font.SysFont(None, height)font_image = font.render(text, True, (255, 215, 0), (255, 255, 255))  # 金黄色font_image_rect = font_image.get_rect()font_image_rect.x = location_xfont_image_rect.y = locaiton_yscreen.blit(font_image, font_image_rect)if self.winner == MAP_ENUM.player1:str = 'White Wins!'else:str = 'Black Wins!'showFont(self.screen, str, map_w / 5, screen_h / 8, 100)  # 居上中,字号100pygame.mouse.set_visible(True)def click_button(self, button):if button.click(self):for tmp in self.buttons:if tmp != button:tmp.unclick()def check_buttons(self, mouse_x, mouse_y):for button in self.buttons:if button.rect.collidepoint(mouse_x, mouse_y):self.click_button(button)break# 以下为pygame1.9帮助文档的示例代码
if __name__ == '__main__':game = Game(version)while True:game.play()# 更新屏幕内容pygame.display.update()# 循环获取事件,监听事件状态for event in pygame.event.get():# 判断用户是否点了"X"关闭按钮,并执行if代码段if event.type == pygame.QUIT:# 卸载所有模块pygame.quit()# 终止程序,确保退出程序sys.exit()elif event.type == pygame.MOUSEBUTTONDOWN:mouse_x, mouse_y = pygame.mouse.get_pos()game.mouseClick(mouse_x, mouse_y)game.check_buttons(mouse_x, mouse_y)

游戏运行结果如图:

4.软件封装

4.1pyinstaller的简介

本实例用pyinstaller来打包py程序,生成可执行程序。pyinstaller是一个跨平台的Python应用打包工具,支持 Windows/Linux/MacOS三大主流平台,能够把 Python 脚本及其所在的 Python 解释器打包成可执行文件,从而允许最终用户在无需安装 Python 的情况下执行应用程序。但是,pyInstaller 制作出来的执行文件并不是跨平台的,如果需要为不同平台打包,就要在相应平台上运行pyInstaller进行打包。

4.2pyinstaller的安装

pip install Pyinstaller

4.3准备

需要准备的内容就是,要打包的py文件,必要时可以加上程序的图像。上面的五子棋.io就是软件的图标,五子棋游戏.py就是要打包的Python文件(建议将程序图标转换成ico格式,因为其他格式如PNG,JPG等可能会报错)。

4.4程序打包

首先打开cmd窗口,
然后把路径切换到当前路径打开命令提示行,(一定要切换到项目目录再执行打包命令),
然后输入打包命令

pyinstaller -F -i 五子棋.ico -w 五子棋游戏.py

输入命令后看见 successfully 那就是成功了.

具体的pyinstaller使用方法和实例可以参考文章点击这里

AI人机对战五子棋游戏【Python(pygame)+AI】并实现软件输出相关推荐

  1. Python编写人机对战小游戏(抓狐狸)(2)

    封面图片:<中学生可以这样学Python>,董付国.应根球著,清华大学出版社 =========== 很久很久以前,在公众号里推送过一个抓狐狸游戏,详见Python编写人机对战小游戏(抓小 ...

  2. python自学 适合新手的 python人机对战小游戏

    目录 前言 一,游戏规则 二,游戏拆解: 版本1.0(自定属性,人工PK) 版本2.0(随机属性,自动PK) 版本3.0(打印结果,三局两胜) 前言 有很多人问,怎样学python可以进步最快,我回顾 ...

  3. 介绍一款Android小游戏--交互式人机对战五子棋

    学习Android系统开发之余,编写了一个小游戏--交互式人机对战五子棋,自娱自乐.之所以称之为交互式人机对战五子棋,一是因为在进入人机对战模式这前,你可以任意设置好开局,同时,在对战过程中,你可以看 ...

  4. python人机对战_【人机对战】用python打造经典井字游戏

    井字游戏是一个经典的棋盘游戏, 在一个3x3的棋盘上面玩, 谁的棋子先连成一条线就赢了, 我直接拿上次在[人机对战]用python打造经典黑白棋游戏写的程式来改很快就改出来了. 我的版本将程式逻辑拆成 ...

  5. 步步为营-墙棋AI人机对战(Android)

    放纵了三天了,之前写了一半懒得去动的墙棋,反而在这几天间隙断断续续完成了,也是挺可笑的. 简介-关于墙棋 路墙棋(Quoridor),或译墙棋.步步为营,是由Mirko Marchesi(米尔科·迈凯 ...

  6. java swing人机对战五子棋(含背景音乐)

    一.项目简介 本项目是一套基于java swing的人机对战五子棋系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者. 包含:项目源码.数据库脚本等,该项目附带全部源码可 ...

  7. iOS简易蓝牙对战五子棋游戏设计思路之二——核心棋盘逻辑与胜负判定算法

    2019独角兽企业重金招聘Python工程师标准>>> iOS简易蓝牙对战五子棋游戏设计思路之二--核心棋盘逻辑与胜负判定算法 一.引言 上一篇博客我们介绍了在开发一款蓝牙对战五子棋 ...

  8. C++毕业设计——基于C+++EasyX+剪枝算法的能人机对弈的五子棋游戏设计与实现(毕业论文+程序源码)——五子棋游戏

    基于C+++EasyX+剪枝算法的能人机对弈的五子棋游戏设计与实现(毕业论文+程序源码) 大家好,今天给大家介绍基于C+++EasyX+剪枝算法的能人机对弈的五子棋游戏设计与实现,文章末尾附有本毕业设 ...

  9. iOS简易蓝牙对战五子棋游戏设计思路之一——核心蓝牙通讯类的设计

    iOS简易蓝牙对战五子棋游戏设计思路之一--核心蓝牙通讯类的设计 一.引言 本系列博客将系统的介绍一款蓝牙对战五子棋的开发思路与过程,其中的核心部分有两个,一部分是蓝牙通讯中对战双方信息交互框架的设计 ...

  10. 【181018】VC++ 网络对战五子棋游戏(服务端+用户端)

    VC++ 网络对战五子棋游戏(服务端+客户端),编译后先开启服务器端,服务端管理着各个用户之间的数据传递,用户端是多个的.就像游戏大厅一样.用户登录了后服务端将向用户端发送当前所有在线玩家列表数据.由 ...

最新文章

  1. 一种集合“相等性”的实现
  2. java:BIO, NIO
  3. Py之logging:logging的简介、安装、使用方法之详细攻略
  4. js三元运算符_这些优化技巧可以避免我们在 JS 中过多的使用 IF 语句
  5. 工作和人工智能的未来
  6. 原创 子网划分的讲解 例题加思路
  7. 让VS2013支持 C# 6.0 语法
  8. mysql常用函数参考
  9. Bootstarp4 列表组
  10. Swift 弱引用与无主引用
  11. directx修复工具 4.0_A12-A13最稳定越狱工具发布,支持iOS13.0—iOS13.3
  12. 中国新能源汽车行业十四五展望规划与投资决策建议报告2022版
  13. 耐得住寂寞方能不寂寞
  14. DNS概述和DNS服务器部署(详细正向解析)
  15. laravel jwt attempt 总是返回false
  16. 静态方法:关于Java8中的日期时间API,你需要掌握这些!!
  17. 【TypeScript 专题】之 Ts 中的类(class)
  18. cmd远程连接上传下载文件
  19. 鸿蒙系统能适配麒麟970处理器么,鸿蒙OS手机版即将适配,麒麟970及以下处理器或无缘更新...
  20. ARP攻击以及伪造ARP响应 实操

热门文章

  1. python写几个好玩的程序_Python写的Msn机器人,几好玩的
  2. Rpg maker mv角色扮演游戏制作大师简介
  3. seo外链工具是什么?外链工具有用吗?
  4. PMP倒计时,整理项目管理中工具和技术
  5. 身份证扫描件用手机怎么弄?手把手教你生成电子身份证
  6. php 检测是否有jmail,asp空间判断jmail组件是否安装或支持的代码
  7. Android 混淆
  8. 软件工程 第五章:交互图
  9. 关于word使用之三线表制作
  10. 数据分析 超市条码_深圳超市通道摆闸常见故障解决|指示灯|摆闸|通道|限位