The examples in this article share the specific code of python to achieve human-machine gobang for your reference. The specific content is as follows
The graphical interface references PyQt5, as well as socket communication. You can play against the LAN, you can play against the machine, there should be some small bugs, but I haven't found out yet. Hope readers can find
Here are some screenshots of running:
Gobang.py code:
from PyQt5.QtWidgets import*from PyQt5.QtGui import*import sys
import MyButton
import DoublePlayerGame
import SinglePlayerGame
from NetConfig import*import NetPlayerGame
classMainwindow(QWidget):
def __init__(self,parent = None):super().__init__(parent)
self.resize(760,650)
self.setWindowTitle("My gomoku")
# Set window icon
self.setWindowIcon(QIcon("source/icon.ico"))
# Set background image
p =QPalette(self.palette())#Get the current palette
brush =QBrush(QImage("source/Gobang interface.png"))
p.setBrush(QPalette.Background,brush)#Set the palette
self.setPalette(p)#Set the palette for the window
self.singlePlayerBtn = MyButton.MyButton('source/Man-machine battle_hover.png','source/Man-machine battle_normal.png','source/Man-machine battle_press.png',
parent=self)
self.singlePlayerBtn.move(300,300)
self.dancelePlayerBtn = MyButton.MyButton('source/Two players_hover.png','source/Two players_normal.png','source/Two players_press.png',
parent=self)
self.dancelePlayerBtn.move(300,400)
# self.dancelePlayerBtn.clicked.connect(DoublePlayerGame)
self.drawlePlayerBtn = MyButton.MyButton('source/Online battle_hover.png','source/Online battle_normal.png','source/Online battle_press.png',
parent=self)
self.drawlePlayerBtn.move(300,500)
# Bind the start two-player game signal and slot function
self.dancelePlayerBtn.clicked.connect(self.startDoubliGame)
self.singlePlayerBtn.clicked.connect(self.startSingleGame)
self.drawlePlayerBtn.clicked.connect(self.startNetGame)
def startDoubliGame(self):print("in")
# Build a two-player battle interface
self.doublePlayerGame = DoublePlayerGame.DoublePlayGame()
# Binding return interface
self.doublePlayerGame.backSignal.connect(self.showStartGame)
self.doublePlayerGame.show()#Show game interface
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):'''
Receive network configuration information
'''
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/Man-machine war_norma.")'''
# Show start screen
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_())
doubleplayergame.py code:
from PyQt5.QtWidgets import*from PyQt5.QtGui import*from PyQt5.QtCore import*from PyQt5 import*import sys
classChessman(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/Kuroko.png")else:
self.pic =QPixmap("source/Baizi.png")
self.setPixmap(self.pic)
self.setFixedSize(self.pic.size())#Set chess 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
classDoublePlayGame(QWidget):
backSignal =pyqtSignal()#Return signal
def __init__(self,parent = None):super().__init__(parent=parent)
# Chessboard in the upper left corner[0][0]
# Chessboard in the upper right corner[0][18]
# Chessboard in the lower left corner[18][0]
# Chessboard in the lower right corner[18][18]
# chessboard[Row subscript][Column subscript]
self.chessboard =[[None for i inrange(19)]for i inrange(19)]
# The color of the pawn
self.turnChessColor ="black"
self.history =[]
self.history2 =[]
self.is_over = False
# Configure background image
p =QPalette(self.palette())#Get the current palette
brush =QBrush(QImage("source/game interface.png"))
p.setBrush(QPalette.Background,brush)#Set the palette
self.setPalette(p)#Set the palette for the window
# Set title
# self.resize(760,650)
self.setWindowTitle("Double online")
# Set window icon
self.setWindowIcon(QIcon("source/icon.ico"))
# Set window size
self.setFixedSize(QImage("source/game interface.png").size())
self.backBtn = MyButton.MyButton('source/Back button_hover.png','source/Back button_normal.png','source/Back button_press.png',
parent=self)
self.backBtn.move(650,50)
self.startBtn = MyButton.MyButton('source/Start button_hover.png','source/Start button_normal.png','source/Start button_press.png',
parent=self)
self.startBtn.move(650,300)
self.returnBtn = MyButton.MyButton('source/Regret button_hover.png','source/Regret button_normal.png','source/Regret button_press.png',
parent=self)
self.returnBtn.move(650,400)
self.loseBtn = MyButton.MyButton('source/Admit button_hover.png','source/Admit button_normal.png','source/Admit button_press.png',
parent=self)
self.loseBtn.move(650,500)
# Bind the back button
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/Logo.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:returnif 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()#Show pieces
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("Board intersection position:",chess_index)
# Put on the board
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 +'Won')
self.showResult(result)
# Automatic drop
# self.autoDown()
# Coordinate conversion
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
returnQPoint(x, y),(self.x, self.y)
def isWin(self,chessman):print("in iswin,lastChessman:",chessman.color,chessman.x,chessman.y)
# The horizontal direction y is the same, chessboard[chessman.y][i]
count =1
# left
i = chessman.x -1while i =0:if self.chessboard[chessman.y][i]== None or self.chessboard[chessman.y][i].color != chessman.color:break
count +=1
i -=1
# right
i = chessman.x +1while i<=18:if self.chessboard[chessman.y][i]== None or self.chessboard[chessman.y][i].color != chessman.color:break
count +=1
i +=1if count =5:return chessman.color
count =1
j = chessman.y -1while 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 +1while j <=18:if self.chessboard[j][chessman.x]== None or self.chessboard[j][chessman.x].color != chessman.color:break
count +=1
j +=1if count =5:return chessman.color
count =1
j,i = chessman.y -1,chessman.x +1while 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 -1while 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 +=1if count =5:return chessman.color
count =1
j,i = chessman.y-1,chessman.x-1while 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+1while 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 +=1if 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/White victory.png"))
self.lbl.move(150,150)
self.lbl.show()
elif isWin =="black":
self.lbl =QLabel(self)
self.lbl.setPixmap(QPixmap("source/Black victory.png"))
self.lbl.move(150,150)
self.lbl.show()else:return
def restar(self):for i inrange(19):for j inrange(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:returnif self.turnChessColor =="black":
self.lbl =QLabel(self)
self.lbl.setPixmap(QPixmap("source/White victory.png"))
self.lbl.move(150,150)
self.lbl.show()
elif self.turnChessColor =="white":
self.lbl =QLabel(self)
self.lbl.setPixmap(QPixmap("source/Black victory.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
NetConfig.py code:
from PyQt5.QtWidgets import*from PyQt5.QtCore import*from PyQt5 import*import socket
import threading
classNetConfigWidget(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("Network Configuration")
self.name_label =QLabel("Name:",self)
self.name_input =QLineEdit("Player 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("Link host",self)
self.server_button =QPushButton("I am the host",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()classNetClient(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):'''Build link'''
self.socket.connect((self.ip,int(self.port)))
threading.Thread(target=self.recv).start()
pass
def send(self,data):'''send data
data(Data sent)String type'''
self.socket.send(data.encode())
pass
def recv(self):'''Receive data'''while True:try:
data = self.socket.recv(4096).decode()
self.msg_signal.emit(data)
except:
pass
classNetServer(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 code:
from DoublePlayerGame import*import json
from NetConfig import*from PyQt5.QtMultimedia import QSound
classNetPlayerGame(DoublePlayGame):
def __init__(self,net_object, parent = None):super().__init__(parent = parent)
self.net_object = net_object
self.net_object.buildConnect()#Establish network link
self.net_object.msg_signal.connect(self.parseData)
self.m_color = None#Player color
self.cuicuBtn = MyButton.MyButton('source/Urge button_hover.png','source/Urge button_normal.png','source/Urge button_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):'''
Automatic drop
: return:'''
# point = self.getPoint()
# Note: x,y coordinate
chess_index =(point.y(), point.x()) #Subscript of chess pieces on the board
pos =QPoint(50+point.x()*30,50+point.y()*30) #The coordinates of the pieces on the board
self.chessman =Chessman(color=color, parent=self)
self.chessman.setIndex(chess_index[0], chess_index[1])
self.chessman.move(pos)
self.chessman.show() #Show pieces
# Display logo
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
# history record
self.history.append((chess_index[0], chess_index[1], self.chessman.color))
# Change the drop color
if self.turnChessColor =='black':
self.turnChessColor ='white'else:
self.turnChessColor ='black'
# Win or lose
result = self.isWin(self.chessman)if result != None:print(result +'Won')
self.showResult(result)
pass
'''
{" msg_type":"positon","x":"10","y":"15","color":"black"}'''
# Parse network data
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,'Gobang_Prompt message','Request to start the game',QMessageBox.Yes |QMessageBox.No)if result == QMessageBox.Yes:
self.restartGame()#Baizi
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,'Gobang_Prompt message','The opponent refuses to play')
elif msg['action_type']=='huiqi':if msg['action_result']=='Yes':
self.huiqigame()else:
QMessageBox.information(self,'Gobang_Prompt message','The opponent refused to regret the game',QMessageBox.Yes |QMessageBox.No)
elif msg['msg_type']=='huiqi':
result = QMessageBox.information(self,'Gobang_Prompt message','The opponent asks for regret',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 inrange(19):for j inrange(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:returnif self.gameStatu == False:return None
pos,chess_index = self.reversePos(a0)if pos is None:returnif 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()#Show pieces
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("Board intersection position:",chess_index)
# Put on the board
self.chessboard[chess_index[1]][chess_index[0]]= self.chess
# Send placement information
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 +'Won')
self.showResult(result)
def huiqi(self):if self.gameStatu == None:
QMessageBox.warning(self,'Gobang Tips','The game has not started, can not regret chess')if self.m_color != self.turnChessColor:
QMessageBox.warning(self,'Gobang Tips','Not your turn')
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,'Gobang','The game did not start')if self.m_color =="black":
self.lbl =QLabel(self)
self.lbl.setPixmap(QPixmap("source/White victory.png"))
self.lbl.move(150,150)
self.lbl.show()
elif self.m_color =="white":
self.lbl =QLabel(self)
self.lbl.setPixmap(QPixmap("source/Black victory.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 code:
# - *- coding:utf-8-*-
# @ author: alex
# @ time:2018/12/2716:29from PyQt5 import QtGui, QtCore
from PyQt5.QtWidgets import*from PyQt5 import*from PyQt5.QtGui import*import sys
from PyQt5.QtCore import*classMyButton(QLabel):
clicked =pyqtSignal()#Customize a signal
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()#transmit a signal
print("Mouse release")
pass
def mousePressEvent(self, ev: QtGui.QMouseEvent):
self.setPixmap(self.pressPixmap)print("Mouse down")
pass
def enterEvent(self, a0: QtCore.QEvent):
self.setPixmap(self.hoverPixmap)
self.enterState = True
print("Mouse enter")
pass
def leaveEvent(self, a0: QtCore.QEvent):
self.setPixmap(self.normalPixmap)
self.enterState = False
print("Mouse away")
pass
if __name__ =='__main__':
a =QApplication(sys.argv)
mybtn =MyButton('source/Man-machine battle_hover.png','source/Man-machine battle_normal.png','source/Man-machine battle_press.png')
mybtn.show()
sys.exit(a.exec_())
SingerPlayerGame.py code:
from DoublePlayerGame import*classSinglePlayerGame(DoublePlayGame):
def __init__(self, parent=None):super().__init__(parent=parent)
self.setWindowTitle('Gobang-Stand-alone mode')
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:returnif self.chessboard[chess_index[1]][chess_index[0]]!= None:return
# Player placement
super().mouseReleaseEvent(a0)
# Computer placement
self.autoDown()
def getPointScore(self, x, y, color):'''
Return the score for each point
y:Row coordinates
x:Column coordinates
color: chess piece color
: return:'''
# Calculate the scores of the blank, and the same color within 5 points around the point
blank_score =0
color_score =0
# Record the scores of the pieces in each direction
blank_score_plus =[0,0,0,0] #Horizontal and vertical forward slash and back slash
color_score_plus =[0,0,0,0]
# Horizontal line
# Right
i = x #Abscissa
j = y #Y-axis
while i <19:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[0]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[0]+=1else:breakif i = x +4:break
i +=1
# print('123123')
# Left
i = x #Abscissa
j = y #Y-axis
while i =0:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[0]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[0]+=1else:breakif i <= x -4:break
i -=1
# Vertical line
# Above
i = x #Abscissa
j = y #Y-axis
while j =0:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[1]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[1]+=1else:breakif j <= y -4:break
j -=1
# Vertical line
# Below
i = x #Abscissa
j = y #Y-axis
while j <19:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[1]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[1]+=1else:breakif j = y +4: #The last five points
break
j +=1
# Forward slash
# Upper right
i = x
j = y
while i <19 and j =0:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[2]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[2]+=1else:breakif i = x +4: #The last five points
break
i +=1
j -=1
# Lower left
i = x
j = y
while j <19 and i =0:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[2]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[2]+=1else:breakif j = y +4: #The last five points
break
i -=1
j +=1
# Backslash
# Upper left
i = x
j = y
while i =0 and j =0:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[3]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[3]+=1else:breakif i <= x -4:break
i -=1
j -=1
# Upper right
i = x
j = y
while i <19 and j <19:if self.chessboard[j][i] is None:
blank_score +=1
blank_score_plus[3]+=1break
elif self.chessboard[j][i].color == color:
color_score +=1
color_score_plus[3]+=1else:breakif i = x +4:break
i +=1
j +=1for k inrange(4):if color_score_plus[k]=5:return100
# color_score *=5returnmax([x + y for x, y inzip(color_score_plus, blank_score_plus)])
def getPoint(self):'''
Return to the position
: return:'''
# Simple implementation: return a blank intersection
# for i inrange(19):
# for j inrange(19):
# if self.chessboard[i][j]== None:
# returnQPoint(j, i)
#
# Did not find a suitable point
white_score =[[0for i inrange(19)]for j inrange(19)]
black_score =[[0for i inrange(19)]for j inrange(19)]for i inrange(19):for j inrange(19):if self.chessboard[i][j]!= None:continue
# Simulated move
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('----------------')
# Convert two-dimensional coordinates into for calculation
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)
# Find the maximum score
score =[max(x,y)for x,y inzip(r_white_score,r_black_score)]
# Find the subscript that makes the score bigger
chess_index = score.index(max(score))print(score,'\n',max(score))
y = chess_index //19
x = chess_index %19returnQPoint(x,y)
def autoDown(self):'''
Automatic drop
: return:'''
point = self.getPoint()
# Note: x,y coordinate
chess_index =(point.y(), point.x()) #Subscript of chess pieces on the board
pos =QPoint(50+point.x()*30,50+point.y()*30) #The coordinates of the pieces on the board
self.chessman =Chessman(color=self.turnChessColor, parent=self)
self.chessman.setIndex(chess_index[1], chess_index[0])
self.chessman.move(pos)
self.chessman.show() #Show pieces
# Display logo
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
# history record
self.history.append((chess_index[0], chess_index[1], self.chessman.color))
# Change the drop color
if self.turnChessColor =='black':
self.turnChessColor ='white'else:
self.turnChessColor ='black'
# Win or lose
result = self.isWin(self.chessman)if result != None:print(result +'Won')
self.showResult(result)
pass
if __name__ =='__main__':import cgitb
cgitb.enable('text')
a =QApplication(sys.argv)
m =SinglePlayerGame()
m.show()
sys.exit(a.exec_())
For more wonderful articles about python games, please click to view the following topics:
python tetris game collection
Python classic games summary
Python WeChat Jump Jump Game Collection
Source download: Gomoku game man-machine version
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts