Python3利用Qt5实现简易的五子棋游戏
作者:WXjzcccc 发布时间:2022-03-31 20:39:12
要写出一个五子棋游戏,我们最先要解决的,就是如何下子,如何判断已经五子连珠,而不是如何绘制画面,因此我们先确定棋盘
五子棋采用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_())
来源:https://blog.csdn.net/WXjzcccc/article/details/122092875


猜你喜欢
- 前言Pytorch、Tensoflow等许多深度学习框架集成了大量常见的网络层,为我们搭建神经网络提供了诸多便利。但在实际工作中,因为项目要
- JavaScript 代码一般最常见的语法格式就是定义函数 function xxx(){/*code...*/},经常有这样的一大堆函数定
- 本周的PyCoder's Weekly 上分享了一篇小文章,它里面提到的冷知识很有意思,我稍作补充,分享给大家。它提到的部分问题,读
- 使用 Django 或 Flask 这种框架开发 web app 的时候一般都会用内建服务器开发和调试程序,等程序完成后再移交到生产环境部署
- 本机环境: Windows 10服务器环境: Windows Server 2012 R2背景:公司需要我开发一个简单的web应用。开发的时
- 本文实例讲述了django框架中ajax的使用及避开CSRF 验证的方式。分享给大家供大家参考,具体如下:ajax(Asynchronous
- 本文实例讲述了Python基于回溯法子集树模板实现图的遍历功能。分享给大家供大家参考,具体如下:问题一个图:A --> BA --&g
- *在起初pip install matplotlib时,主动安装到当时最新版本(matplotlib==3.3.2),在StackOverf
- 基于 RSA 加密算法的接口鉴权方案假设接口调用者是客户端,接口提供方是服务端,则此方案存在以下规则:客户端需要使用 RSA 算法(1024
- 也许你听说过Hibernate的大名,但可能一直不了解它,也许你一直渴望使用它进行开发,那么本文正是你所需要的!在本文中,我向大家重点介绍H
- 前言对于会PhotoShop的人来说,抠图是非常简单的操作了,有时候几秒钟就能扣好一张图。不过一些比较复杂的图,有时候还是要画点时间的,今天
- 内容摘要:在本人上一篇教程《彻底弄懂CSS盒子模式五(定位强化练习) 》有讲到一个很酷的链接面板提示的实例制作,那时主要是用到di
- MYSQL的profiling功能要在Mysql版本5.0.37以上才能使用。查看profile是否开启mysql> show var
- 这篇文章主要介绍了python enumerate内置函数用法总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价
- PDOStatement::executePDOStatement::execute — 执行一条预处理语句(PHP 5 >= 5.1
- AJAX 客户端页面代码: index.html <html> <body> <h1>Ajax file
- groupby官方解释DataFrame.groupby(by=None, axis=0, level=None, as_index=Tru
- 昨晚在往MySQL数据库中插入一组数据时,出错了!数据库无情了给我报了个错误:ERROR 1365(22012):Division by 0
- 我就废话不多说了,大家还是直接看代码吧!import kerasimport numpy as npfrom keras.applicati
- SqlServer将数据库中的表复制到另一个数据库一、如果两个数据库在同一台服务器上1、复制表结构和数据(A->B):SELECT *