Python实现双人五子棋对局

 更新时间:2022年5月2日 21:35  点击:259 作者:战 胜

本文实例为大家分享了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()

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

原文出处:https://blog.csdn.net/qq_45021180/article/details/113991825

[!--infotagslink--]

相关文章

  • python opencv 画外接矩形框的完整代码

    这篇文章主要介绍了python-opencv-画外接矩形框的实例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • 最炫Python烟花代码全解析

    2022虎年新年即将来临,小编为大家带来了一个利用Python编写的虎年烟花特效,堪称全网最绚烂,文中的示例代码简洁易懂,感兴趣的同学可以动手试一试...2022-02-14
  • python中numpy.empty()函数实例讲解

    在本篇文章里小编给大家分享的是一篇关于python中numpy.empty()函数实例讲解内容,对此有兴趣的朋友们可以学习下。...2021-02-06
  • python-for x in range的用法(注意要点、细节)

    这篇文章主要介绍了python-for x in range的用法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-05-10
  • Python 图片转数组,二进制互转操作

    这篇文章主要介绍了Python 图片转数组,二进制互转操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-09
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • python实现b站直播自动发送弹幕功能

    这篇文章主要介绍了python如何实现b站直播自动发送弹幕,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下...2021-02-20
  • python Matplotlib基础--如何添加文本和标注

    这篇文章主要介绍了python Matplotlib基础--如何添加文本和标注,帮助大家更好的利用Matplotlib绘制图表,感兴趣的朋友可以了解下...2021-01-26
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • python 计算方位角实例(根据两点的坐标计算)

    今天小编就为大家分享一篇python 计算方位角实例(根据两点的坐标计算),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-04-27
  • python实现双色球随机选号

    这篇文章主要为大家详细介绍了python实现双色球随机选号,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-05-02
  • python中使用np.delete()的实例方法

    在本篇文章里小编给大家整理的是一篇关于python中使用np.delete()的实例方法,对此有兴趣的朋友们可以学习参考下。...2021-02-01
  • 使用Python的pencolor函数实现渐变色功能

    这篇文章主要介绍了使用Python的pencolor函数实现渐变色功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-09
  • python自动化办公操作PPT的实现

    这篇文章主要介绍了python自动化办公操作PPT的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-05
  • Python getsizeof()和getsize()区分详解

    这篇文章主要介绍了Python getsizeof()和getsize()区分详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-20
  • python实现学生通讯录管理系统

    这篇文章主要为大家详细介绍了python实现学生通讯录管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-25
  • PyTorch一小时掌握之迁移学习篇

    这篇文章主要介绍了PyTorch一小时掌握之迁移学习篇,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-08
  • 解决python 两个时间戳相减出现结果错误的问题

    这篇文章主要介绍了解决python 两个时间戳相减出现结果错误的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-12
  • Python绘制的爱心树与表白代码(完整代码)

    这篇文章主要介绍了Python绘制的爱心树与表白代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-04-06