Python3使用Qt5来实现简易的五子棋小游戏


Posted in Python onMay 02, 2022

要写出一个五子棋游戏,我们最先要解决的,就是如何下子,如何判断已经五子连珠,而不是如何绘制画面,因此我们先确定棋盘

五子棋采用15*15的棋盘,因此,我们可以使用二维列表来创建一个棋盘,不妨认为0表示未放置棋子,1表示放置白子,2表示放置黑子。

显而易见可以创建列表,注意不能使用*来复制列表

self.chess_board = [[0 for i in range(15)] for i in range(15)]

下棋的步骤十分好做,只需要找到对应的索引进行赋值即可,下一步应该解决如何判断五子连珠的问题。

每当我们落子结束后,应该判断是否已经完成五子连珠。对于刚放置的一颗棋子而言,可能的情况大致分为四种:

1.水平
2.斜向右下
3.竖直
4.斜向右上

要判断是否已经连珠成功,我们以刚放置的棋子为起点,先向前遍历4个棋子,并计算相同棋子的个数,一旦遇到不同的棋子,就停止,然后从起点向后遍历4个棋子,直到全部遍历完成或者棋子总数已经达到5个,就可以返回。我们只需要注意如何获得棋子的前后棋子以及棋盘的边界问题,棋子不可能超出棋盘,因此被遍历的棋子也不能超出棋盘。

以水平为例,可以得到代码

def judge_1(self,x:int,y:int) -> bool:
        count = 1
        if self.chess_board[x][y] != 0:
            for i in range(1,5):
                if y - i >= 0:
                    if self.chess_board[x][y] == self.chess_board[x][y-i]:
                        print(x,y-i)
                        count += 1
                    else:
                        break
                else:
                    break
            for i in range(1,5):
                if y + i <=14:
                    if self.chess_board[x][y] == self.chess_board[x][y+i]:
                        print(x,y+i)
                        count += 1
                    else:
                        break
                else:
                    break
        if count == 5:
            return True
        return False

以相似的步骤完成其余三种判断,就已经完成了五子棋游戏的核心要素了,剩下的就需要交给PyQt5来完成游戏的绘制来完善游戏了。

我们创建一个类来继承QWidget类,创建一个窗口,之后我们需要创建几个属性来完成储存我们的数据信息

#棋子的坐标
self.x = -1
self.y = -1
#区分玩家
#开始标签
self.flag = False
#储存已经下好的白子
self.white_chess = []
#储存已经下好的黑子
self.black_chess = []

我们已经可以开始绘制棋盘,在Qt5中,如果我们需要进行绘制,我们应该重写paintEvent方法,这个方法会由程序自动调用执行。创建一个QPainter对象,将需要绘制的内容用begin与end方法包裹起来,就可以完成绘制。

我们用drawLine方法来绘制线条,用drawEllipse方法来绘制棋子,使用setPen来更改线条样式,setBrush来更改棋子样式。

得到代码(本段代码有参考他人代码,这是我第一次接触Qt的绘制)

--------------------GUI中的x轴竖直向下,y轴水平向右,因此绘制棋子时的x与y需要颠倒---------------

#绘制棋盘与棋子
    def paintEvent(self, e) -> None:
        qp = QPainter()
        qp.begin(self)
        qp.fillRect(self.rect(), QColor("light blue"))
        qp.drawRect(self.rect())
        qp.setBackground(QColor("yellow"))
        qp.setPen(QPen(QColor(0, 0, 0), 2, Qt.SolidLine))
        for i in range(15):
            qp.drawLine(QPoint(30, 30 + 30 * i), QPoint(450, 30 + 30 * i))
        for i in range(15):
            qp.drawLine(QPoint(30 + 30 * i, 30), QPoint(30 + 30 * i, 450))
        qp.setBrush(QColor(0, 0, 0))
        key_points = [(3, 3), (11, 3), (3, 11), (11, 11), (7, 7)]
        if len(self.black_chess) != 0:
            for t in self.black_chess:
                #画黑子
                qp.drawEllipse(QPoint(30 + 30 * t[1], 30 + 30 * t[0]), 6, 6)
        for t in key_points:
            #棋盘的5个定点
            qp.drawEllipse(QPoint(30 + 30 * t[0], 30 + 30 * t[1]), 3, 3)
        qp.setBrush(QColor(255,255,255))
        if len(self.white_chess) != 0:
            for t in self.white_chess:
                #画白子
                qp.drawEllipse(QPoint(30 + 30 * t[1], 30 + 30 * t[0]), 6, 6)
        qp.end()

另一个需要在GUI中解决的问题就是,如何获取要下的棋子的坐标?我们可以通过重写鼠标事件来解决,重写单机事件mousePressEvent,并修改棋子的x坐标与y坐标即可,另外,用户不可能每次都恰巧点到我们规定的坐标点上,因此需要给出一个大致范围判断,这里我的方式是先获取坐标,然后根据坐标找到距离最近的点

def mousePressEvent(self, e) -> None:
        if e.buttons() == QtCore.Qt.LeftButton:
            if e.x() > 15 and e.x() < 465 and e.y() > 15 and e.y() < 465:
                x = e.x()/30 - e.x()//30
                y = e.y()/30 - e.y()//30
                self.y = (e.x()-30)//30 if x < 0.5 else (e.x()-30)//30 + 1
                self.x = (e.y()-30)//30 if y < 0.5 else (e.y()-30)//30 + 1
                if self.flag:
                    print(self.x,self.y)
                    if self.player % 2 == 1:
                        if goBang.put_white_chess(self.x,self.y):
                            self.player += 1 
                            print('黑子行动')
                        else:
                            print('白子行动')
                        if goBang.judge(self.x,self.y):
                            msg_box = QMessageBox(QMessageBox.Information, '提示', '白子获胜!')
                            msg_box.exec_()
                    else:
                        if goBang.put_black_chess(self.x,self.y):
                            self.player += 1
                            print('白子行动')
                        else:
                            print('黑子行动')
                        if goBang.judge(self.x,self.y):
                            msg_box = QMessageBox(QMessageBox.Information, '提示', '黑子获胜!')
                            msg_box.exec_()

每当游戏完成,我们应该可以清空棋盘,也就是将所有储存数据的变量都重新初始化再重绘棋盘

#清除棋盘,重开游戏
    def clear(self) -> None:
        self.x = -1
        self.y = -1
        self.player = 0
        self.flag = False
        self.white_chess = []
        self.black_chess = []
        self.chess_board = [[0 for i in range(15)] for i in range(15)]
        self.update()

这样就大致结束了!!

下面是全部代码:

from PyQt5 import *
from PyQt5 import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
 
class GoBang(QWidget):
    #初始化棋盘
    def __init__(self):
        super().__init__()
        self.setWindowTitle('五子棋Hi~ o(* ̄▽ ̄*)ブ')
        self.x = -1
        self.y = -1
        #区分玩家
        self.player = 0
        #开始标签
        self.flag = False
        #储存已经下好的白子
        self.white_chess = []
        #储存已经下好的黑子
        self.black_chess = []
        self.setFixedSize(800,600)
        self.chess_board = [[0 for i in range(15)] for i in range(15)]
        btn1 = QPushButton('开始',self)
        btn1.setGeometry(500,100,50,30)
        btn1.clicked.connect(self.setFlag)
        btn2 = QPushButton('重开',self)
        btn2.setGeometry(550,100,50,30)
        btn2.clicked.connect(self.clear)
        self.show()
    
    #绘制棋盘与棋子
    def paintEvent(self, e) -> None:
        qp = QPainter()
        qp.begin(self)
        qp.fillRect(self.rect(), QColor("light blue"))
        qp.drawRect(self.rect())
        qp.setBackground(QColor("yellow"))
        qp.setPen(QPen(QColor(0, 0, 0), 2, Qt.SolidLine))
        for i in range(15):
            qp.drawLine(QPoint(30, 30 + 30 * i), QPoint(450, 30 + 30 * i))
        for i in range(15):
            qp.drawLine(QPoint(30 + 30 * i, 30), QPoint(30 + 30 * i, 450))
        qp.setBrush(QColor(0, 0, 0))
        key_points = [(3, 3), (11, 3), (3, 11), (11, 11), (7, 7)]
        if len(self.black_chess) != 0:
            for t in self.black_chess:
                #画黑子
                qp.drawEllipse(QPoint(30 + 30 * t[1], 30 + 30 * t[0]), 6, 6)
        for t in key_points:
            #棋盘的5个定点
            qp.drawEllipse(QPoint(30 + 30 * t[0], 30 + 30 * t[1]), 3, 3)
        qp.setBrush(QColor(255,255,255))
        if len(self.white_chess) != 0:
            for t in self.white_chess:
                #画白子
                qp.drawEllipse(QPoint(30 + 30 * t[1], 30 + 30 * t[0]), 6, 6)
        qp.end()
 
    #更改标签,开始游戏
    def setFlag(self) -> None:
        self.flag = True
 
    def mousePressEvent(self, e) -> None:
        if e.buttons() == QtCore.Qt.LeftButton:
            if e.x() > 15 and e.x() < 465 and e.y() > 15 and e.y() < 465:
                x = e.x()/30 - e.x()//30
                y = e.y()/30 - e.y()//30
                self.y = (e.x()-30)//30 if x < 0.5 else (e.x()-30)//30 + 1
                self.x = (e.y()-30)//30 if y < 0.5 else (e.y()-30)//30 + 1
                if self.flag:
                    print(self.x,self.y)
                    if self.player % 2 == 1:
                        if goBang.put_white_chess(self.x,self.y):
                            self.player += 1 
                            print('黑子行动')
                        else:
                            print('白子行动')
                        if goBang.judge(self.x,self.y):
                            msg_box = QMessageBox(QMessageBox.Information, '提示', '白子获胜!')
                            msg_box.exec_()
                    else:
                        if goBang.put_black_chess(self.x,self.y):
                            self.player += 1
                            print('白子行动')
                        else:
                            print('黑子行动')
                        if goBang.judge(self.x,self.y):
                            msg_box = QMessageBox(QMessageBox.Information, '提示', '黑子获胜!')
                            msg_box.exec_()
 
            
    #下白子
    def put_white_chess(self,x:int,y:int) -> bool:
        if self.chess_board[x][y] != 0:
            msg_box = QMessageBox(QMessageBox.Information, '提示', '这个位置已经有棋子了!')
            msg_box.exec_()
            return False
        else:
            self.chess_board[x][y] = 1
            self.white_chess.append((x,y))
            self.update()
            return True
 
    #下黑子
    def put_black_chess(self,x:int,y:int) -> bool:
        if self.chess_board[x][y] != 0:
            msg_box = QMessageBox(QMessageBox.Information, '提示', '这个位置已经有棋子了!')
            msg_box.exec_()
            return False
        else:
            self.chess_board[x][y] = 2
            self.black_chess.append((x,y))
            self.update()
            return True
 
    #清除棋盘,重开游戏
    def clear(self) -> None:
        self.x = -1
        self.y = -1
        self.player = 0
        self.flag = False
        self.white_chess = []
        self.black_chess = []
        self.chess_board = [[0 for i in range(15)] for i in range(15)]
        self.update()
 
    #判断是否已经五子连珠
    def judge(self,x:int,y:int) -> bool:
        if self.judge_1(x,y) or self.judge_2(x,y) or self.judge_3(x,y) or self.judge_4(x,y):
            return True
        return False
 
    #判断横线
    def judge_1(self,x:int,y:int) -> bool:
        count = 1
        if self.chess_board[x][y] != 0:
            for i in range(1,5):
                if y - i >= 0:
                    if self.chess_board[x][y] == self.chess_board[x][y-i]:
                        print(x,y-i)
                        count += 1
                    else:
                        break
                else:
                    break
            for i in range(1,5):
                if y + i <=14:
                    if self.chess_board[x][y] == self.chess_board[x][y+i]:
                        print(x,y+i)
                        count += 1
                    else:
                        break
                else:
                    break
        if count == 5:
            return True
        return False
 
    #判断右下线
    def judge_2(self,x:int,y:int) -> bool:
        count = 1
        if self.chess_board[x][y] != 0:
            for i in range(1,5):
                if x-i >= 0 and y - i >= 0:
                    if self.chess_board[x][y] == self.chess_board[x-i][y-i]:
                        print(x-i,y-i)
                        count += 1
                    else:
                        break
                else:
                    break
            for i in range(1,5):
                if x + i <= 14 and y + i <= 14:
                    if self.chess_board[x][y] == self.chess_board[x+i][y+i]:
                        print(x+i,y+i)
                        count += 1
                    else:
                        break
                else:
                    break
        if count == 5:
            return True
        return False
 
    #判断竖线
    def judge_3(self,x:int,y:int) -> bool:
        count = 1
        if self.chess_board[x][y] != 0:
            for i in range(1,5):
                if x - i >= 0:
                    if self.chess_board[x][y] == self.chess_board[x-i][y]:
                        print(x-i,y)
                        count += 1
                    else:
                        break
                else:
                    break
            for i in range(1,5):
                if x + i <= 14:
                    if self.chess_board[x][y] == self.chess_board[x+i][y]:
                        print(x+i,y)
                        count += 1
                    else:
                        break
                else:
                    break
        if count == 5:
            return True
        return False
 
    #判断右上线
    def judge_4(self,x:int,y:int) -> bool:
        count = 1
        if self.chess_board[x][y] != 0:
            for i in range(1,5):
                if x - i >= 0 and y + i <= 14:
                    if self.chess_board[x][y] == self.chess_board[x-i][y+i]:
                        print(x-i,y+i)
                        count += 1
                    else:
                        break
                else:
                    break
            for i in range(1,5):
                if x + i <= 14 and y - i >= 0:
                    if self.chess_board[x][y] == self.chess_board[x+i][y-i]:
                        print(x+i,y-i)
                        count += 1
                    else:
                        break
                else:
                    break
        if count == 5:
            return True
        return False
 
#程序入口
if __name__ == '__main__':  
    app = QApplication(sys.argv)  
    goBang = GoBang()
    sys.exit(app.exec_())

以上就是本文的全部内容,希望对大家的学习有所帮助。


Tags in this post...

Python 相关文章推荐
python实现哈希表
Feb 07 Python
Python Web服务器Tornado使用小结
May 06 Python
python中实现php的var_dump函数功能
Jan 21 Python
win10系统中安装scrapy-1.1
Jul 03 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
Mar 12 Python
用python脚本24小时刷浏览器的访问量方法
Dec 07 Python
Python完成哈夫曼树编码过程及原理详解
Jul 29 Python
python 并发编程 非阻塞IO模型原理解析
Aug 20 Python
python 利用toapi库自动生成api
Oct 19 Python
PyTorch梯度裁剪避免训练loss nan的操作
May 24 Python
解决pycharm安装scrapy DLL load failed:找不到指定的程序的问题
Jun 08 Python
Python采集壁纸并实现炫轮播
Apr 30 Python
python开发制作好看的时钟效果
关于的python五子棋的算法
python开发人人对战的五子棋小游戏
python pygame 开发五子棋双人对弈
May 02 #Python
Python开发简易五子棋小游戏
May 02 #Python
Python开发五子棋小游戏
python获取带有返回值的多线程
May 02 #Python
You might like
How do I change MySQL timezone?
2008/03/26 PHP
基于preg_match_all采集后数据处理的一点心得笔记(编码转换和正则匹配)
2014/01/31 PHP
PHP的引用详解
2015/02/22 PHP
如何解决PHP无法实现多线程的问题
2015/09/25 PHP
PHP中字符串长度的截取用法示例
2017/01/12 PHP
PHP面向对象五大原则之接口隔离原则(ISP)详解
2018/04/04 PHP
精心挑选的15个jQuery下拉菜单制作教程
2012/06/15 Javascript
jquery获取div距离窗口和父级dv的距离示例
2013/10/10 Javascript
jQuery选择器全面总结
2014/01/06 Javascript
js实现俄罗斯方块小游戏分享
2014/01/31 Javascript
如何防止回车(enter)键提交表单
2014/05/11 Javascript
jQuery获取页面及个元素高度、宽度的总结——超实用
2015/07/28 Javascript
认识Knockout及如何使用Knockout绑定上下文
2015/12/25 Javascript
用Nodejs搭建服务器访问html、css、JS等静态资源文件
2017/04/28 NodeJs
React Js 微信禁止复制链接分享禁止隐藏右上角菜单功能
2017/05/26 Javascript
layui2.0使用table+laypage实现真分页
2019/07/27 Javascript
python实现的阳历转阴历(农历)算法
2014/04/25 Python
python数据结构之二叉树的统计与转换实例
2014/04/29 Python
Python学习之asyncore模块用法实例教程
2014/09/29 Python
利用信号如何监控Django模型对象字段值的变化详解
2017/11/27 Python
如何利用Python分析出微信朋友男女统计图
2019/01/25 Python
python监控nginx端口和进程状态
2019/09/06 Python
python如何编写win程序
2020/06/08 Python
python3.6中anaconda安装sklearn踩坑实录
2020/07/28 Python
Pycharm操作Git及GitHub的步骤详解
2020/10/27 Python
HTML5中的postMessage API基本使用教程
2016/05/20 HTML / CSS
2014年教师党员自我评价范文
2014/09/22 职场文书
计算机实训报告范文
2014/11/05 职场文书
2015年元宵节活动总结
2015/02/06 职场文书
2016年会开场白台词
2015/06/01 职场文书
外出学习心得体会范文
2016/01/18 职场文书
公务员爱岗敬业心得体会
2016/01/25 职场文书
高质量“欢迎词”
2019/04/03 职场文书
MySQL中order by的使用详情
2021/11/17 MySQL
一文了解JavaScript用Element Traversal新属性遍历子元素
2021/11/27 Javascript
Python实现归一化算法详情
2022/03/18 Python