Python实现双人五子棋对局

2022-07-15,,

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

效果:

自己需要两个棋子:

服务器玩家全部代码:

# 案列使用tcp连接
# 这是服务器端

import socket
import wx
import threading
import time
from pil import image

#  定义套接字 s
s=socket.socket(socket.af_inet,socket.sock_stream)
cell=40

# 定义窗口类
class myframe(wx.frame):
    # 初始化这里就是生成界面,然后绑定了按钮事件,其他没了
    def __init__(self):
        super().__init__(parent=none,size=(600,600),title="五子棋:服务器")
        self.center()
        self.panel=wx.panel(parent=self)
        #openbutton = wx.button(parent=map, id=1, label="开房间")
        #self.bind(wx.evt_button, self.startgame)
        self.panel.bind(wx.evt_paint, self.paintbackground) # 绘图
        self.panel.bind(wx.evt_left_down,self.gochess) # 绑定鼠标左键消息
        self.picture = [wx.bitmap("黑.png"), wx.bitmap("白.png")]
        # 创造二维数组用来判断自己是否获胜
        self.map = [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "] for y in range(15)]
        # 定义一个变量来标志自己是否可以走棋
        self.isgogame = true

        self.startgame()


    # 画背景函数
    def paintbackground(self,event):
        self.dc = wx.paintdc(self.panel)
        # 创造背景
        brush = wx.brush("white")
        self.dc.setbackground(brush)
        self.dc.clear()
        # 画方格线
        pen = wx.pen(wx.colour(0, 0, 0), 1, wx.solid)
        self.dc.setpen(pen)
        for i in range(15):
            self.dc.drawline(0, cell*i, 600, cell*i)
            self.dc.drawline(cell * i, 0, cell * i, 600)


    # 在x,y坐标绘制棋子
    def paintpiece(self,x,y):
        image = wx.staticbitmap(self.panel, -1, self.picture[0],size=(40,40),pos=(x*cell+cell/2,y*cell+cell/2))
        #image.setposition((x*cell+cell/2,y*cell+cell/2))

    # 玩家自己走棋
    def gochess(self,event):
        #setposition(event.getposition())
        if self.isgogame:
            pos = event.getposition()  # 在x,y坐标绘制棋子
            x = int((pos.x - cell / 2) // cell)
            y = int((pos.y - cell / 2) // cell)
            self.paintpiece(x, y)

            # 下子后,向客户端发送位置
            msg = str(x) + "," + str(y)
            self.conn.send(msg.encode())  # 给客户端发送信息
            print("服务器发送:", msg)
            self.map[x][y]="a"
            # 判断是否胜利
            if self.win_lose("a"):
                self.one_dialog("win")
            self.isgogame=false
        else:
            self.one_dialog("notgo")

    # 开启服务器端函数
    def startgame(self):
        self.othernum=0
        self.image=[]
        for item in range(50):
            self.image.append(wx.staticbitmap(self.panel, -1, self.picture[1], size=(40, 40),pos=(-100,-100)))
        threadgame=threading.thread(target=self.thread_body,name="srever")
        threadgame.start()

    def thread_body(self):
        s.bind(("127.0.0.1", 8888))  # 绑定ip和端口(参数为二元组),就是寻址
        s.listen(5)  # 因为是tcp,所有要监听端口
        print("服务器启动·····")
        self.conn, self.addess = s.accept()  # 等待客户端连接(参数为最大连接数),返回一个二元组(新的socket对象+客户端地址)
        while true:
            data = self.conn.recv(1024)  # 接受1024字节序列数据(这个函数阻塞,直到接受到数据)
            if len(data) != 0:
                msg = data.decode()
                print("服务器接收:",msg)
                msg = msg.split(",")
                #self.paintpiece(int(msg[0]), int(msg[1]))
                #image = wx.staticbitmap(self.panel, -1, self.picture[0], size=(40, 40))

                # 设置原来实例化好的棋子的位置
                self.image[self.othernum].setposition((int(msg[0]) * cell + cell / 2, int(msg[1])* cell + cell / 2))
                self.othernum+=1
                self.map[int(msg[0])][int(msg[1])] = "b"
                if self.win_lose("b"): # 判断对方玩家是否胜利
                    self.one_dialog("lose")
                self.isgogame = true # 接收消息后 玩家能够走棋

            #time.sleep(2)

    def one_dialog(self,msg):
        if msg=="win":
            dlg = wx.messagedialog(none, u"你胜利了!", u"恭喜", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                self.close(true)
            dlg.destroy()
        elif msg=="lose":
            dlg = wx.messagedialog(none, u"你输了!", u"很遗憾", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                self.close(true)
            dlg.destroy()
        elif msg == "notgo":
            dlg = wx.messagedialog(none, u"等待对方下棋!", u"提示", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                #self.close(true)
                dlg.destroy()

    def win_lose(self,msg):
        a = str(msg)
        print("a=", a)
        for i in range(0, 11):
            for j in range(0, 11):
                if self.map[i][j] == a and self.map[i + 1][j + 1] == a and self.map[i + 2][j + 2] == a and \
                                self.map[i + 3][
                                            j + 3] == a and self.map[i + 4][j + 4] == a:
                    print("x=y轴上形成五子连珠")
                    return true
        for i in range(4, 15):
            for j in range(0, 11):
                if self.map[i][j] == a and self.map[i - 1][j + 1] == a and self.map[i - 2][j + 2] == a and \
                                self.map[i - 3][
                                            j + 3] == a and self.map[i - 4][j + 4] == a:
                    print("x=-y轴上形成五子连珠")
                    return true
        for i in range(0, 15):
            for j in range(4, 15):
                if self.map[i][j] == a and self.map[i][j - 1] == a and self.map[i][j - 2] == a and self.map[i][
                            j - 2] == a and self.map[i][
                            j - 4] == a:
                    print("y轴上形成了五子连珠")
                    return true
        for i in range(0, 11):
            for j in range(0, 15):
                if self.map[i][j] == a and self.map[i + 1][j] == a and self.map[i + 2][j] == a and \
                                self.map[i + 3][j] == a and \
                                self.map[i + 4][j] == a:
                    print("x轴形成五子连珠")
                    return true
        return false


# 应用程序
class app(wx.app):
    def oninit(self):
        frame=myframe()
        frame.show()
        return true
    def onexit(self):
        s.close() # 关闭socket对象
        return 0

# 进入main函数运行:循环
if __name__=="__main__":
    app=app()
    app.mainloop()

客户端玩家全部代码:

# 案列使用tcp连接
# 这是服务器端

import socket
import wx
import threading
import time
from pil import image


#  定义套接字 s
s=socket.socket(socket.af_inet,socket.sock_stream)
cell=40

# 定义窗口类
class myframe(wx.frame):
    # 初始化这里就是生成界面,然后绑定了按钮事件,其他没了
    def __init__(self):
        super().__init__(parent=none,size=(600,600),title="五子棋:客户端")
        self.center()
        self.panel=wx.panel(parent=self)
        #openbutton = wx.button(parent=map, id=1, label="开房间")
        #self.bind(wx.evt_button, self.startgame)
        self.panel.bind(wx.evt_paint, self.paintbackground) # 绘图
        self.panel.bind(wx.evt_left_down,self.gochess) # 绑定鼠标左键消息
        self.picture=[wx.bitmap("白.png"),wx.bitmap("黑.png")]

        # 创造二维数组用来判断自己是否获胜
        self.map = [[" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "] for y in range(15)]
        # 定义一个变量来标志自己是否可以走棋
        self.isgogame=false

        self.startgame()

    # 画背景函数
    def paintbackground(self,event):
        self.dc = wx.paintdc(self.panel)
        # 创造背景
        brush = wx.brush("white")
        self.dc.setbackground(brush)
        self.dc.clear()
        # 画方格线
        pen = wx.pen(wx.colour(0, 0, 0), 1, wx.solid)
        self.dc.setpen(pen)
        for i in range(15):
            self.dc.drawline(0, cell*i, 600, cell*i)
            self.dc.drawline(cell * i, 0, cell * i, 600)

    # 在x,y坐标绘制棋子
    def paintpiece(self,x,y):
        image = wx.staticbitmap(self.panel, -1,self.picture[0] ,size=(40,40),pos=(x*cell+cell/2,y*cell+cell/2))
        #image.setposition()

    def gochess(self,event):
        #setposition(event.getposition())
        if self.isgogame: # 轮到自己下棋
            pos = event.getposition()  # 在x,y坐标绘制棋子
            x=int((pos.x-cell/2)//cell)
            y=int((pos.y-cell/2)//cell)
            self.paintpiece(x, y)

            # 下子后,向客户端发送位置
            msg=str(x)+","+str(y)
            s.send(msg.encode())  # 给客户端发送信息
            print("客户端发送:", msg)
            self.map[x][y] = "a"
            # 判断是否胜利
            if self.win_lose("a"):
                self.one_dialog("win")
            self.isgogame=false
        else:
            self.one_dialog("notgo")


    # 开启服务器端函数
    def startgame(self):
        self.image=[]
        self.othernum = 0
        for item in range(50):
            self.image.append(wx.staticbitmap(self.panel, -1, self.picture[1], size=(40, 40), pos=(-100, -100)))
        while true:
            try:
                s.connect(("127.0.0.1", 8888))
                break
            except:
                print("等待服务器启动~")
        threadgame = threading.thread(target=self.thread_body, name="client")
        threadgame.start()
        return

    def thread_body(self):
        while true:
            data = s.recv(1024)  # 等待接收服务器端信息
            if len(data) != 0:
                msg=data.decode()
                print("客户端接收:", msg)
                msg = msg.split(",")
                #self.paintpiece(int(msg[0]), int(msg[1]))
                #image = wx.staticbitmap(self.panel, -1, self.picture[0], size=(40, 40))
                self.image[self.othernum].setposition((int(msg[0]) * cell + cell / 2, int(msg[1]) * cell + cell / 2))
                self.othernum += 1
                self.map[int(msg[0])][int(msg[1])] = "b"
                if self.win_lose("b"):
                    self.one_dialog("lose")
                self.isgogame=true
            #time.sleep(2)

    def one_dialog(self, msg):
        if msg == "win":
            dlg = wx.messagedialog(none, u"你胜利了!", u"恭喜", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                self.close(true)
            dlg.destroy()
        if msg == "lose":
            dlg = wx.messagedialog(none, u"你输了!", u"很遗憾", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                self.close(true)
            dlg.destroy()
        if msg == "notgo":
            dlg = wx.messagedialog(none, u"等待对方下棋!", u"提示", wx.yes_no | wx.icon_question)
            if dlg.showmodal() == wx.id_yes:
                #self.close(true)
                dlg.destroy()

    # 判断整个棋盘的输赢
    def win_lose(self,msg):
        a = str(msg)
        print("a=", a)
        for i in range(0, 11):
            for j in range(0, 11):
                if self.map[i][j] == a and self.map[i + 1][j + 1] == a and self.map[i + 2][j + 2] == a and self.map[i + 3][
                            j + 3] == a and self.map[i + 4][j + 4] == a:
                    print("x=y轴上形成五子连珠")
                    return true
        for i in range(4, 15):
            for j in range(0, 11):
                if self.map[i][j] == a and self.map[i - 1][j + 1] == a and self.map[i - 2][j + 2] == a and self.map[i - 3][
                            j + 3] == a and self.map[i - 4][j + 4] == a:
                    print("x=-y轴上形成五子连珠")
                    return true
        for i in range(0, 15):
            for j in range(4, 15):
                if self.map[i][j] == a and self.map[i][j - 1] == a and self.map[i][j - 2] == a and self.map[i][j - 2] == a and self.map[i][
                            j - 4] == a:
                    print("y轴上形成了五子连珠")
                    return true
        for i in range(0, 11):
            for j in range(0, 15):
                if self.map[i][j] == a and self.map[i + 1][j] == a and self.map[i + 2][j] == a and self.map[i + 3][j] == a and \
                                self.map[i + 4][j] == a:
                    print("x轴形成五子连珠")
                    return true
        return false

# 应用程序
class app(wx.app):
    def oninit(self):
        frame=myframe()
        frame.show()
        return true
    def onexit(self):
        s.close() # 关闭socket对象
        return 0

# 进入main函数运行:循环
if __name__=="__main__":
    app=app()
    app.mainloop()

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

《Python实现双人五子棋对局.doc》

下载本文的Word格式文档,以方便收藏与打印。