python实现人机五子棋_python

来源:脚本之家  责任编辑:小易  

五子棋、贪吃蛇、扫雷、俄罗斯方块、坦克大战、FlappyBird,源码地址github

本文实例为大家分享了python实现人机五子棋的具体代码,供大家参考,具体内容如下

复古风格发挥好

图形界面引用PyQt5,还有socket通信。可以局域网对战,可以人机对战,应该存在一些小的bug,但是还没有找出来。希望读者可以找到

你都做到这个程度了,当然就是高手了。 把棋子位置放在一个数据里。然后做一个路径搜索算法。只搜索8个方

下面附几张运行的截图:

搜这本书: PC 游戏编程(人机博弈)有五子棋的算法的详细说明,有代码。 极大极小算不了几层

五子棋.py代码:

#五子棋import appuifw,e32,key_codesfrom graphics impo

from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sys import MyButton import DoublePlayerGame import SinglePlayerGame from NetConfig import * import NetPlayerGame class Mainwindow(QWidget): def __init__(self,parent = None): super().__init__(parent) self.resize(760,650) self.setWindowTitle("我的五子棋") #设置窗口图标 self.setWindowIcon(QIcon("source/icon.ico")) #设置背景图片 p = QPalette(self.palette())#获得当前的调色板 brush = QBrush(QImage("source/五子棋界面.png")) p.setBrush(QPalette.Background,brush)#设置调色版 self.setPalette(p)#给窗口设置调色板 self.singlePlayerBtn = MyButton.MyButton('source/人机对战_hover.png', 'source/人机对战_normal.png', 'source/人机对战_press.png', parent=self) self.singlePlayerBtn.move(300,300) self.dancelePlayerBtn = MyButton.MyButton('source/双人对战_hover.png', 'source/双人对战_normal.png', 'source/双人对战_press.png', parent=self) self.dancelePlayerBtn.move(300,400) #self.dancelePlayerBtn.clicked.connect(DoublePlayerGame) self.drawlePlayerBtn = MyButton.MyButton('source/联机对战_hover.png', 'source/联机对战_normal.png', 'source/联机对战_press.png', parent=self) self.drawlePlayerBtn.move(300,500) #绑定开始双人游戏信号和槽函数 self.dancelePlayerBtn.clicked.connect(self.startDoubliGame) self.singlePlayerBtn.clicked.connect(self.startSingleGame) self.drawlePlayerBtn.clicked.connect(self.startNetGame) def startDoubliGame(self): print("in") #构建双人对战界面 self.doublePlayerGame = DoublePlayerGame.DoublePlayGame() #绑定返回界面 self.doublePlayerGame.backSignal.connect(self.showStartGame) self.doublePlayerGame.show()#显示游戏界面 self.close() def startSingleGame(self): self.SingleGame = SinglePlayerGame.SinglePlayerGame() self.SingleGame.backSignal.connect(self.showStartGame2) self.SingleGame.show() self.close() def startNetGame(self): self.netConfig = NetConfigWidget() self.netConfig.exit_signal.connect(self.show) self.netConfig.show() self.netConfig.config_signal.connect(self.receiveNetConfig) self.close() def receiveNetConfig(self,nettype,name,ip,port): ''' 接收网络配置信息 ''' print("net config:",nettype,name,ip,port) if nettype == "client": net_object = NetClient(name,ip,port) elif nettype == "server": net_object = NetServer(name,ip,port) else: return self.netPlayerGame = NetPlayerGame.NetPlayerGame(net_object=net_object) self.netPlayerGame.backSignal.connect(self.show) self.close() self.netPlayerGame.show() self.netConfig.hide() '''lbl = QLabel(self) pix = QPixmap("source/人机大战_norma.")''' #显示开始界面 def showStartGame(self): self.show() self.doublePlayerGame.close() def showStartGame2(self): self.show() self.SingleGame.close() if __name__ == "__main__": import cgitb cgitb.enable("text") a = QApplication(sys.argv) m = Mainwindow() m.show() sys.exit(a.exec_())

  给家里添置大家电不是小事,尤其是冰箱这种一用10年往上的电器,您在选购的时候还是不要任性,一定要慎重!!  通常来说,选购冰箱的尺寸大小和容量大小是成正比的,容量越大尺寸也就越大,反之亦然。一定不要以为容量越大用的越爽哦!大容量冰箱不仅体积大、占空间,耗电量也大,而且还容易让食物堆积,引发冰箱类疾病。因此,建议家用冰箱人均容量在80-100升左右是比较合适的。  ※单门冰箱:  冷藏室和冷冻室都合在只有一扇门的箱体内,是最传统且古老的冰箱品类,以冷藏和保鲜为主。  优点:结构简单,方便使用,耗电较少,价格较低。  缺点:容积小,且只是在冷藏室内另做一个小的冷冻室,只能装少量的食材。大部分空

doubleplayergame.py代码:

你如何拍车轨?是不是等很多车开过来的时候,你在按动快门。然后希望曝光的时候过来很多车,周尾灯行程的车轨会漂亮。其实,这样的方法太OUT了。我来告诉你,一分钟搞定。首先看看这五张图片吧,拍摄于上海外白渡桥。由于当时车不多,除了第四张的效果还不错外,其它几张图片中都没有留下理想的车流尾灯效果。既然前期拍摄的不是很理想,那我们就用后期来弥吧,马上搞定!打开photshop,文件-脚本-将文件载入堆栈。载入这几张图片。如果担心拍摄的时候,相机和三脚架会有震动,可以选择上“对齐源图像”。然后点击确定,这样photoshop就以图层的形式载入了这几张图片。点击图层中的第一张图像,按住shift键,再按最后

from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5 import * import sys class Chessman(QLabel): def __init__(self, color = "black",parent = None): super().__init__(parent) self.color = color self.pic = None if self.color == "black": self.pic = QPixmap("source/黑子.png") else: self.pic = QPixmap("source/白子.png") self.setPixmap(self.pic) self.setFixedSize(self.pic.size())#设置棋子大小 self.show() self.x = 0 self.y = 0 def move(self,a0:QtCore.QPoint): super().move(a0.x()-15,a0.y()-15) def setIndex(self,x,y): self.x = x self.y = y import MyButton class DoublePlayGame(QWidget): backSignal = pyqtSignal()#返回信号 def __init__(self,parent = None): super().__init__(parent=parent) #左上角chessboard[0][0] #右上角chessboard[0][18] #左下角chessboard[18][0] #右下角chessboard[18][18] #chessboard[行下标][列下标] self.chessboard = [[None for i in range(19)] for i in range(19)] #落子棋子颜色 self.turnChessColor = "black" self.history = [] self.history2 = [] self.is_over = False #配置背景图 p = QPalette(self.palette())#获得当前的调色板 brush = QBrush(QImage("source/游戏界面.png")) p.setBrush(QPalette.Background,brush)#设置调色版 self.setPalette(p)#给窗口设置调色板 #设置标题 #self.resize(760,650) self.setWindowTitle("双人联机") #设置窗口图标 self.setWindowIcon(QIcon("source/icon.ico")) #设置窗口大小 self.setFixedSize(QImage("source/游戏界面.png").size()) self.backBtn = MyButton.MyButton('source/返回按钮_hover.png', 'source/返回按钮_normal.png', 'source/返回按钮_press.png', parent=self) self.backBtn.move(650,50) self.startBtn = MyButton.MyButton('source/开始按钮_hover.png', 'source/开始按钮_normal.png', 'source/开始按钮_press.png', parent=self) self.startBtn.move(650,300) self.returnBtn = MyButton.MyButton('source/悔棋按钮_hover.png', 'source/悔棋按钮_normal.png', 'source/悔棋按钮_press.png', parent=self) self.returnBtn.move(650,400) self.loseBtn = MyButton.MyButton('source/认输按钮_hover.png', 'source/认输按钮_normal.png', 'source/认输按钮_press.png', parent=self) self.loseBtn.move(650,500) #绑定返回按钮 self.backBtn.clicked.connect(self.goBack) self.startBtn.clicked.connect(self.restar) self.loseBtn.clicked.connect(self.lose) self.returnBtn.clicked.connect(self.huiback) self.gameStatu = [] self.focusPoint = QLabel(self) self.focusPoint.setPixmap(QPixmap("source/标识.png")) def goBack(self): self.backSignal.emit() self.close() def closeEvent(self, a0: QtGui.QCloseEvent): self.backSignal.emit() def mouseReleaseEvent(self, a0: QtGui.QMouseEvent): if self.gameStatu == False: return None print(a0.pos()) print("x:",a0.x()) print("y:",a0.y()) pos,chess_index = self.reversePos(a0) if pos is None: return if self.chessboard[chess_index[1]][chess_index[0]] != None: return self.chess = Chessman(color=self.turnChessColor,parent=self) self.chess.setIndex(chess_index[0], chess_index[1]) self.chess.move(pos) self.chess.show()#显示棋子 self.history.append(self.chess) self.history2.append(self.focusPoint) self.focusPoint.move(QPoint(pos.x()-15,pos.y()-15)) self.focusPoint.show() self.focusPoint.raise_() print("棋盘交点位置:",chess_index) #放入棋盘 self.chessboard[chess_index[1]][chess_index[0]] = self.chess if self.turnChessColor=="black": self.turnChessColor="white" else: self.turnChessColor="black" self.lbl = None result = self.isWin(self.chess) if result != None: print(result + '赢了') self.showResult(result) #自动落子 #self.autoDown() #坐标转换 def reversePos(self, a0: QtCore.QPoint): if a0.x() <= 50 - 15 or a0.x() >= 590 +15 or a0.y() <= 50 - 15 or a0.y() >= 590+15 : return None, None self.x = (a0.x()-35)//30 self.y = (a0.y()-35)//30 x = 50+30*self.x y = 50+30*self.y return QPoint(x, y),(self.x, self.y) def isWin(self,chessman): print("in iswin,lastChessman:",chessman.color,chessman.x,chessman.y) #水平方向y相同,chessboard[chessman.y][i] count = 1 #左边 i = chessman.x - 1 while i>=0: if self.chessboard[chessman.y][i] == None or self.chessboard[chessman.y][i].color != chessman.color: break count += 1 i -= 1 #右边 i = chessman.x + 1 while i<=18: if self.chessboard[chessman.y][i] == None or self.chessboard[chessman.y][i].color != chessman.color: break count += 1 i += 1 if count >=5: return chessman.color count = 1 j = chessman.y - 1 while j >= 0: if self.chessboard[j][chessman.x] == None or self.chessboard[j][chessman.x].color != chessman.color: break count += 1 j -= 1 j = chessman.y + 1 while j <= 18: if self.chessboard[j][chessman.x] == None or self.chessboard[j][chessman.x].color != chessman.color: break count += 1 j += 1 if count >=5: return chessman.color count = 1 j,i = chessman.y - 1,chessman.x + 1 while j >= 0 and i <= 18: if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color: break count += 1 j -= 1 i += 1 j,i = chessman.y + 1,chessman.x - 1 while i >= 0 and j <= 18: if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color: break count += 1 i -= 1 j += 1 if count >=5: return chessman.color count = 1 j,i = chessman.y-1,chessman.x-1 while j>=0 and i>=0: if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color: break count += 1 j -= 1 i -= 1 j,i = chessman.y+1,chessman.x+1 while j<=18 and i<=18: if self.chessboard[j][i] == None or self.chessboard[j][i].color != chessman.color: break count += 1 j += 1 i += 1 if count >=5: return chessman.color return None def showResult(self,isWin = None): self.gameStatu = False if isWin == "white": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/白棋胜利.png")) self.lbl.move(150,150) self.lbl.show() elif isWin == "black": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/黑棋胜利.png")) self.lbl.move(150,150) self.lbl.show() else: return def restar(self): for i in range(19): for j in range(19): if self.chessboard[i][j] != None: self.chessboard[i][j].close() self.chessboard[i][j] = None self.focusPoint.close() else: pass if self.lbl != None: self.lbl.close() self.gameStatu = True def lose(self): if self.gameStatu == False: return if self.turnChessColor == "black": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/白棋胜利.png")) self.lbl.move(150,150) self.lbl.show() elif self.turnChessColor == "white": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/黑棋胜利.png")) self.lbl.move(150,150) self.lbl.show() else: return def huiback(self): if self.gameStatu == False: return m = self.history.pop() a = self.history2.pop() self.chessboard[m.y][m.x] = None m.close() a.close() if self.turnChessColor=="black": self.turnChessColor="white" else: self.turnChessColor="black" if __name__ == "__main__": import cgitb cgitb.enable("text") a = QApplication(sys.argv) m = DoublePlayGame() m.show() sys.exit(a.exec_()) pass

腕表就是拥有一定的阅历一定的经济所必要的一个物件,今天为大家推荐的这几款腕表,价格都在万元以内,作为人生的第一款入手腕表绝对是不错的选择。这一款腕表是艾米龙近几年最受关注的表款之一,精钢表壳打造,镶嵌蓝色陶瓷的可旋转精钢表圈,腕表采用的为深蓝色盘面,深邃神秘,诱惑力十足,这款腕表还拥有300米的防水效果,不管是生活防水还是游泳都无惧。浪琴的这款腕表采用34毫米直径设计,可以说是非常的小巧,且腕表的厚度仅有7毫米,非常的贴合手腕。精钢表壳搭配黑色皮质表带,经典而时尚,腕表同样的采用全黑色设计,金色指针和金色时标在表盘上格外显眼,读时清晰方便。复古的外观又很有浪琴的内涵,作为正装或者日常佩戴腕表再

NetConfig.py代码:

粮票是困难时期的有价证券,在当时,人们每月必须拿着粮票到粮食公司去,购买大米或面粉,当然,出差在外,系带粮票更加方便,也就是说,凡是粮食制品,都要粮票。粮票距今虽然几十年了,而在我们当地,崭新的全国粮票或地方粮票,都不值价,也不值得收藏,

from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5 import * import socket import threading class NetConfigWidget(QWidget): config_signal = pyqtSignal([str,str,str,str]) exit_signal = pyqtSignal() def __init__(self,parent = None): super().__init__(parent = parent) self.initUI() def initUI(self): self.setWindowTitle("网络配置") self.name_label = QLabel("姓名:",self) self.name_input = QLineEdit("玩家1",self) self.ip_label = QLabel("IP:",self) self.ip_input = QLineEdit("127.0.0.1",self) self.port_label = QLabel("Prot:",self) self.port_input = QLineEdit("10086",self) self.client_button = QPushButton("链接主机",self) self.server_button = QPushButton("我是主机",self) gridLayout = QGridLayout() gridLayout.addWidget(self.name_label,0,0) gridLayout.addWidget(self.name_input,0,1) gridLayout.addWidget(self.ip_label,1,0) gridLayout.addWidget(self.ip_input,1,1) gridLayout.addWidget(self.port_label,2,0) gridLayout.addWidget(self.port_input,2,1) gridLayout.addWidget(self.client_button,3,0) gridLayout.addWidget(self.server_button,3,1) self.setLayout(gridLayout) self.client_button.clicked.connect(self.client_btn_signal) self.server_button.clicked.connect(self.server_btn_signal) def server_btn_signal(self): self.config_signal.emit("server",self.name_input.text(),self.ip_input.text(),self.port_input.text()) def client_btn_signal(self): self.config_signal.emit("client",self.name_input.text(),self.ip_input.text(),self.port_input.text()) def closeEvent(self,a0:QtGui.QCloseEvent): self.close() self.exit_signal.emit() class NetClient(QObject): msg_signal = pyqtSignal([str]) def __init__(self,name,ip,port): super().__init__() self.name = name self.ip = ip self.port = port self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) def buildConnect(self): '''建立链接''' self.socket.connect((self.ip,int(self.port))) threading.Thread(target=self.recv).start() pass def send(self,data): '''发送数据 data(发送的数据)字符串类型''' self.socket.send(data.encode()) pass def recv(self): '''接收数据''' while True: try: data = self.socket.recv(4096).decode() self.msg_signal.emit(data) except: pass class NetServer(QObject): msg_signal = pyqtSignal([str]) def __init__(self,name,ip,port): super().__init__() self.name = name self.ip = ip self.port = port self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.cli_socket = None def buildConnect(self): self.socket.bind(("",int(self.port))) self.socket.listen(1) threading.Thread(target=self.__acceptConnect).start() def __acceptConnect(self): try: self.cli_socket,cli_addr = self.socket.accept() except: pass while True: try: data = self.cli_socket.recv(4096).decode() self.msg_signal.emit(data) except Exception as e: print(e) def send(self,data): if self.cli_socket == None: return self.cli_socket.send(data.encode()) if __name__ == "__main__": import sys import cgitb cgitb.enable("text") a = QApplication(sys.argv) m = NetConfigWidget() m.show() sys.exit(a.exec_()) pass

NetplayerGame.py代码:

from DoublePlayerGame import * import json from NetConfig import * from PyQt5.QtMultimedia import QSound class NetPlayerGame(DoublePlayGame): def __init__(self,net_object, parent = None): super().__init__(parent = parent) self.net_object = net_object self.net_object.buildConnect()#建立网络链接 self.net_object.msg_signal.connect(self.parseData) self.m_color = None#玩家棋子颜色 self.cuicuBtn = MyButton.MyButton('source/催促按钮_hover.png', 'source/催促按钮_normal.png', 'source/催促按钮_press.png', parent=self) self.cuicuBtn.move(650,600) self.cuicuBtn.clicked.connect(self.cuicu) def cuicu(self): QSound.play('source/cuicu.wav') msg = {} msg['msg_type'] = 'cuicu' self.net_object.send(json.dumps(msg)) pass def goBack(self): self.backSignal.emit() self.close() self.net_object.socket.close() def downChessman(self,point,color): ''' 自动落子 :return: ''' #point = self.getPoint() # 注意:x,y坐标对应 chess_index = (point.y(), point.x()) # 棋子在棋盘中的下标 pos = QPoint(50+point.x()*30, 50+point.y()*30) # 棋子在棋盘中的坐标 self.chessman = Chessman(color=color, parent=self) self.chessman.setIndex(chess_index[0], chess_index[1]) self.chessman.move(pos) self.chessman.show() # 显示棋子 # 显示标识 self.focusPoint.move(QPoint(pos.x() - 15, pos.y() - 15)) self.focusPoint.show() self.focusPoint.raise_() self.chessboard[chess_index[0]][chess_index[1]] = self.chessman # 历史记录 self.history.append((chess_index[0], chess_index[1], self.chessman.color)) # 改变落子颜色 if self.turnChessColor == 'black': self.turnChessColor = 'white' else: self.turnChessColor = 'black' # 判断输赢 result = self.isWin(self.chessman) if result != None: print(result + '赢了') self.showResult(result) pass ''' { "msg_type":"positon", "x":"10", "y":"15", "color":"black" } ''' #解析网路数据 def parseData(self,data): print("pardata:",data) try: msg = json.loads(data) except Exception as e: print(e) #msg = json.loads(data) print("msg:",msg) if msg["msg_type"] == "position": self.downChessman(QPoint(int(msg["x"]),int(msg["y"])),msg["color"]) pass elif msg["msg_type"] == "restart": result = QMessageBox.information(None,'五子棋_提示消息','请求开始游戏',QMessageBox.Yes |QMessageBox.No) if result == QMessageBox.Yes: self.restartGame()#白子 self.m_color = 'white' msg = {} msg['msg_type'] = "response" msg['action_type'] = 'restart' msg['action_result'] = 'yes' self.net_object.send(json.dumps(msg)) else: msg = {} msg['msg_type'] = "response" msg['action_type'] = 'restart' msg['action_result'] = 'no' self.net_object.send(json.dumps(msg)) elif msg['msg_type'] == 'response': if msg['action_type'] == 'restart': if msg['action_result'] == 'yes': self.restartGame() self.m_color = 'balck' else: QMessageBox.information(self,'五子棋_提示消息','对方拒绝游戏') elif msg['action_type'] == 'huiqi': if msg['action_result'] == 'Yes': self.huiqigame() else: QMessageBox.information(self,'五子棋_提示消息','对方拒绝悔棋',QMessageBox.Yes |QMessageBox.No) elif msg['msg_type'] == 'huiqi': result = QMessageBox.information(self,'五子棋_提示消息','对方请求悔棋',QMessageBox.Yes |QMessageBox.No) if result == QMessageBox.Yes: msg = {} msg['msg_type'] = "response" msg['action_type'] = 'huiqi' msg['action_result'] = 'Yes' self.net_object.send(json.dumps(msg)) self.huiqigame() else: msg = {} msg['msg_type'] = "response" msg['action_type'] = 'huiqi' msg['action_result'] = 'No' self.net_object.send(json.dumps(msg)) elif msg['msg_type'] == 'lose': show.showResult(self.m_color) elif msg['msg_type'] == 'cuicu': QSound.play('source/cuicu.wav') QMessageBox.window(self,'0') def restartGame(self): for i in range(19): for j in range(19): if self.chessboard[i][j] != None: self.chessboard[i][j].close() self.chessboard[i][j] = None self.focusPoint.close() else: pass self.lbl = None if self.lbl != None: self.lbl.close() self.gameStatu = True self.focusPoint.hide() self.turnChessColor="black" def mouseReleaseEvent(self, a0: QtGui.QMouseEvent): if self.m_color != self.turnChessColor: return if self.gameStatu == False: return None pos,chess_index = self.reversePos(a0) if pos is None: return if self.chessboard[chess_index[1]][chess_index[0]] != None: return self.chess = Chessman(color=self.turnChessColor,parent=self) self.chess.setIndex(chess_index[1], chess_index[0]) self.chess.move(pos) self.chess.show()#显示棋子 self.history.append(self.chess) self.history2.append(self.focusPoint) self.focusPoint.move(QPoint(pos.x()-15,pos.y()-15)) self.focusPoint.show() self.focusPoint.raise_() print("棋盘交点位置:",chess_index) #放入棋盘 self.chessboard[chess_index[1]][chess_index[0]] = self.chess #发送落子信息 msg = {} msg["msg_type"] = "position" msg["x"] = chess_index[1] msg["y"] = chess_index[0] msg["color"] = self.turnChessColor self.net_object.send(json.dumps(msg)) if self.turnChessColor=="black": self.turnChessColor="white" else: self.turnChessColor="black" self.lbl = None result = self.isWin(self.chess) if result != None: print(result + '赢了') self.showResult(result) def huiqi(self): if self.gameStatu == None: QMessageBox.warning(self,'五子棋提示','游戏没有开始,不能悔棋') if self.m_color != self.turnChessColor: QMessageBox.warning(self,'五子棋提示','不是你的回合') msg = {} msg['msg_type'] = 'huiqi' self.net_object.send(json.dumps(msg)) def huiqigame(self): if self.gameStatu == False: return m = self.history.pop() a = self.history2.pop() self.chessboard[m.y][m.x] = None m.close() a.close() if self.turnChessColor=="black": self.turnChessColor="white" else: self.turnChessColor="black" def restar(self): msg = {} msg["msg_type"] = "restart" self.net_object.send(json.dumps(msg)) def lose(self): if self.gameStatu == False: QMessageBox.warning(None,'五子棋','游戏没有开始') if self.m_color == "black": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/白棋胜利.png")) self.lbl.move(150,150) self.lbl.show() elif self.m_color == "white": self.lbl = QLabel(self) self.lbl.setPixmap(QPixmap("source/黑棋胜利.png")) self.lbl.move(150,150) self.lbl.show() else: return msg = {} msg['msg_type'] = "lose" #msg['action_type'] = 'restart' #msg['action_result'] = 'no' self.net_object.send(json.dumps(msg)) if __name__ == '__main__': import cgitb cgitb.enable("text") a = QApplication(sys.argv) m = NetPlayerGame() m.show() sys.exit(a.exec_()) pass

MyButton.py代码:

# -*- coding:utf-8 -*- # @author: alex # @time: 2018/12/27 16:29 from PyQt5 import QtGui, QtCore from PyQt5.QtWidgets import * from PyQt5 import * from PyQt5.QtGui import * import sys from PyQt5.QtCore import * class MyButton(QLabel): clicked = pyqtSignal()#自定义一个信号 def __init__(self, *args, parent=None): super().__init__(parent) self.hoverPixmap = QPixmap(args[0]) self.normalPixmap = QPixmap(args[1]) self.pressPixmap = QPixmap(args[2]) self.enterState = False self.setPixmap(self.normalPixmap) self.setFixedSize(self.normalPixmap.size()) def mouseReleaseEvent(self, ev: QtGui.QMouseEvent): if self.enterState == False: self.setPixmap(self.normalPixmap) else: self.setPixmap(self.hoverPixmap) self.clicked.emit()#发射信号 print("鼠标释放") pass def mousePressEvent(self, ev: QtGui.QMouseEvent): self.setPixmap(self.pressPixmap) print("鼠标按下") pass def enterEvent(self, a0: QtCore.QEvent): self.setPixmap(self.hoverPixmap) self.enterState = True print("鼠标进入") pass def leaveEvent(self, a0: QtCore.QEvent): self.setPixmap(self.normalPixmap) self.enterState = False print("鼠标离开") pass if __name__ == '__main__': a = QApplication(sys.argv) mybtn = MyButton('source/人机对战_hover.png', 'source/人机对战_normal.png', 'source/人机对战_press.png') mybtn.show() sys.exit(a.exec_())

SingerPlayerGame.py代码:

from DoublePlayerGame import * class SinglePlayerGame(DoublePlayGame): def __init__(self, parent=None): super().__init__(parent=parent) self.setWindowTitle('五子棋-单机模式') def mouseReleaseEvent(self, a0: QtGui.QMouseEvent): if self.gameStatu == False: return None print(a0.pos()) print("x:",a0.x()) print("y:",a0.y()) pos,chess_index = self.reversePos(a0) if pos is None: return if self.chessboard[chess_index[1]][chess_index[0]] != None: return # 玩家落子 super().mouseReleaseEvent(a0) # 电脑落子 self.autoDown() def getPointScore(self, x, y, color): ''' 返回每个点的得分 y:行坐标 x:列坐标 color:棋子颜色 :return: ''' # 分别计算点周围5子以内,空白、和同色的分数 blank_score = 0 color_score = 0 # 记录每个方向的棋子分数 blank_score_plus = [0, 0, 0, 0] # 横向 纵向 正斜线 反斜线 color_score_plus = [0, 0, 0, 0] # 横线 # 右侧 i = x # 横坐标 j = y # 纵坐标 while i < 19: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[0] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[0] += 1 else: break if i >= x + 4: break i += 1 # print('123123') # 左侧 i = x # 横坐标 j = y # 纵坐标 while i >= 0: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[0] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[0] += 1 else: break if i <= x - 4: break i -= 1 # 竖线 # 上方 i = x # 横坐标 j = y # 纵坐标 while j >= 0: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[1] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[1] += 1 else: break if j <= y - 4: break j -= 1 # 竖线 # 下方 i = x # 横坐标 j = y # 纵坐标 while j < 19: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[1] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[1] += 1 else: break if j >= y + 4: # 最近五个点 break j += 1 # 正斜线 # 右上 i = x j = y while i < 19 and j >= 0: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[2] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[2] += 1 else: break if i >= x + 4: # 最近五个点 break i += 1 j -= 1 # 左下 i = x j = y while j < 19 and i >= 0: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[2] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[2] += 1 else: break if j >= y + 4: # 最近五个点 break i -= 1 j += 1 # 反斜线 # 左上 i = x j = y while i >= 0 and j >= 0: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[3] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[3] += 1 else: break if i <= x - 4: break i -= 1 j -= 1 # 右上 i = x j = y while i < 19 and j < 19: if self.chessboard[j][i] is None: blank_score += 1 blank_score_plus[3] += 1 break elif self.chessboard[j][i].color == color: color_score += 1 color_score_plus[3] += 1 else: break if i >= x + 4: break i += 1 j += 1 for k in range(4): if color_score_plus[k] >= 5: return 100 # color_score *= 5 return max([x + y for x, y in zip(color_score_plus, blank_score_plus)]) def getPoint(self): ''' 返回落子位置 :return: ''' # 简单实现:返回一个空白交点 # for i in range(19): # for j in range(19): # if self.chessboard[i][j] == None: # return QPoint(j, i) # # 没有找到合适的点 white_score = [ [ 0 for i in range(19) ] for j in range(19)] black_score = [ [ 0 for i in range(19) ] for j in range(19)] for i in range(19): for j in range(19): if self.chessboard[i][j] != None: continue # 模拟落子 self.chessboard[i][j] = Chessman(color='white',parent=self) white_score[i][j] = self.getPointScore(j, i, 'white') self.chessboard[i][j].close() self.chessboard[i][j] = None self.chessboard[i][j] = Chessman(color='black',parent=self) black_score[i][j] = self.getPointScore(j, i, 'black') self.chessboard[i][j].close() self.chessboard[i][j] = None print('----------------') # 将二维坐标转换成以为进行计算 r_white_score = [] r_black_score = [] for i in white_score: r_white_score.extend(i) for i in black_score: r_black_score.extend(i) # 找到分数最大值 score = [ max(x,y) for x,y in zip(r_white_score,r_black_score) ] # 找到分数做大的下标 chess_index = score.index(max(score)) print(score,'\n',max(score)) y = chess_index //19 x = chess_index % 19 return QPoint(x,y) def autoDown(self): ''' 自动落子 :return: ''' point = self.getPoint() # 注意:x,y坐标对应 chess_index = (point.y(), point.x()) # 棋子在棋盘中的下标 pos = QPoint(50+point.x()*30, 50+point.y()*30) # 棋子在棋盘中的坐标 self.chessman = Chessman(color=self.turnChessColor, parent=self) self.chessman.setIndex(chess_index[1], chess_index[0]) self.chessman.move(pos) self.chessman.show() # 显示棋子 # 显示标识 self.focusPoint.move(QPoint(pos.x() - 15, pos.y() - 15)) self.focusPoint.show() self.focusPoint.raise_() self.chessboard[chess_index[0]][chess_index[1]] = self.chessman # 历史记录 self.history.append((chess_index[0], chess_index[1], self.chessman.color)) # 改变落子颜色 if self.turnChessColor == 'black': self.turnChessColor = 'white' else: self.turnChessColor = 'black' # 判断输赢 result = self.isWin(self.chessman) if result != None: print(result + '赢了') self.showResult(result) pass if __name__ == '__main__': import cgitb cgitb.enable('text') a = QApplication(sys.argv) m = SinglePlayerGame() m.show() sys.exit(a.exec_())

更多关于python游戏的精彩文章请点击查看以下专题:

python俄罗斯方块游戏集合

python经典小游戏汇总

python微信跳一跳游戏集合

源码下载:五子棋游戏人机版

扩展阅读,根据您访问的内容系统为您准备了以下内容,希望对您有帮助。

在线等!求一个简单的python 五子棋源代码,最好是有人人跟一个简单AI的人机的,不胜感谢!

我有一次想做,发现有些复杂。不过最近我在做机器学习。这个五子棋是个好东西。我可以做出来给我家孩子玩。 做成多人游戏更好玩。

暂时没有办法告诉你了。不过如果不用机器学习也可以通过三到五步的计算深度,试着算出一个方案来。

怎么用PYTHON编写五子棋啊

其实用类应该可以。。。我也有疑问,你是打算人机交战吗?这得有多麻烦的算法

求解用python 编写五子棋怎样编写判断输赢的函数,应该从哪方面考虑呢?最好有代码,,,,谢谢

你都做到这个程度了,当然就是高手了。 把棋子位置放在一个数据里。然后做一个路径搜索算法。只搜索8个方向,如果某个方向有5个子连在一起就赢了。

这是个笨方法,还有很多优化的地方,比如上一次搜索后,建立一个路径数组。下一次,只需要检验上一次结果,并将新的棋子放进路径里就可以了。 这样就效率很高了。

具体的你自己研究。这个对你来说应该轻松啦。追问非常感谢你的回答,只是我真的才学习python不到一周。你所说的路径搜索我估计明白一点,但我真的不知道怎么做,能不能给一个路径搜索的例子,我参考参考估计才能正在明白,麻烦你了,,,追答比如设置一个数组,它是包括2个棋子连成的一条线,它的类型就是连线方向。新棋子落下后,找附近8个方面的棋子,如果它们在数组里,就检查是否与数组构成同一个方向的延伸,如果构成就合并进去。当一个数组长度超过5个就是赢了。

如何用python制作五子棋游戏

这个问题有点泛,你要先弄懂五子棋的游戏规则,和程序实现的算法,然后再做图形用户界面,如果要进行人机对战,还要写一个智能算法,当然,简单的就不用了···

  • 本文相关:
  • python版本五子棋的实现代码
  • python实现五子棋小游戏
  • python pygame实现五子棋小游戏
  • python实现五子棋小程序
  • python实现简单五子棋游戏
  • python实现五子棋游戏
  • 使用python实现简单五子棋游戏
  • python制作简单五子棋游戏
  • python使用minimax算法实现五子棋
  • python五子棋游戏的设计与实现
  • python从excel中读取日期一列的方法
  • python字符串、列表、元组、字典、集合的补充实例详解
  • pycharm 解除默认unittest模式的方法
  • 使用mixin设计模式进行python编程的方法讲解
  • python创建一个元素都为0的列表实例
  • selenium webdriverwait类等待机制的实现
  • 用python做一个搜索引擎(pylucene)的实例代码
  • python将主机名转换为ip地址的方法
  • python中扩展包的安装方法详解
  • python序列化基础知识(json/pickle)
  • 在线等!求一个简单的python 五子棋源代码,最好是有人人跟一个简单AI的人机的,不胜感谢!
  • 怎么用PYTHON编写五子棋啊
  • 求解用python 编写五子棋怎样编写判断输赢的函数,应该从哪方面考虑呢?最好有代码,,,,谢谢
  • 如何用python制作五子棋游戏
  • python 五子棋 大作业
  • 请用PYTHON编一个小游戏,如五子棋,连连看,贪吃蛇,扫雷,计算器等等
  • 求python 编写的五子棋游戏
  • 求解用python 编写五子棋怎样编写判断输赢的函数,
  • 求助python五子棋估价算法,并在最先走的人的角度确定当前最佳走步 要求如上,希望帮我写出具体py...
  • 求一个编写的五子棋小游戏python的代码,求借鉴啊!!急急急。。。
  • 网站首页网页制作脚本下载服务器操作系统网站运营平面设计媒体动画电脑基础硬件教程网络安全vbsdos/bathtahtcpythonperl游戏相关vba远程脚本coldfusionruby专题autoitseraphzonepowershelllinux shellluagolangerlang其它首页pythonpython俄罗斯方块游戏集合python经典小游戏汇总python微信跳一跳游戏集合python版本五子棋的实现代码python实现五子棋小游戏python pygame实现五子棋小游戏python实现五子棋小程序python实现简单五子棋游戏python实现五子棋游戏使用python实现简单五子棋游戏python制作简单五子棋游戏python使用minimax算法实现五子棋python五子棋游戏的设计与实现python从excel中读取日期一列的方法python字符串、列表、元组、字典、集合的补充实例详解pycharm 解除默认unittest模式的方法使用mixin设计模式进行python编程的方法讲解python创建一个元素都为0的列表实例selenium webdriverwait类等待机制的实现用python做一个搜索引擎(pylucene)的实例代码python将主机名转换为ip地址的方法python中扩展包的安装方法详解python序列化基础知识(json/pickle)python入门教程 超详细1小时学会python 列表(list)操作方法详解python 元组(tuple)操作详解python 字典(dictionary)操作详解pycharm 使用心得(一)安装和首python strip()函数 介绍python 中文乱码问题深入分析python科学计算环境推荐——anacpython逐行读取文件内容的三种方python中使用xlrd、xlwt操作excepython 垃圾收集机制的实例详解详解django配置优化方法python的pytest框架之命令行参数详解(下python实现梯度下降和逻辑回归使用django的模版来配合字符串翻译工作对pandas进行数据预处理的实例讲解window10+python3.5安装opencv的教程推荐python 判断是否为正小数和正整数的实例浅析python中的多条件排序实现python中函数eval和ast.literal_eval的区
    免责声明 - 关于我们 - 联系我们 - 广告联系 - 友情链接 - 帮助中心 - 频道导航
    Copyright © 2017 www.zgxue.com All Rights Reserved