脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python实现双人五子棋对局

Python实现双人五子棋对局

2022-12-13 11:57战 胜 Python

这篇文章主要为大家详细介绍了Python实现双人五子棋对局,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

效果:

Python实现双人五子棋对局

自己需要两个棋子:

Python实现双人五子棋对局

服务器玩家全部代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# 案列使用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()

客户端玩家全部代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# 案列使用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

延伸 · 阅读

精彩推荐
  • PythonDjango跨域请求CSRF的方法示例

    Django跨域请求CSRF的方法示例

    这篇文章主要介绍了Django跨域请求CSRF的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    森林屿麓9942021-04-18
  • Pythonpytorch使用nn.Moudle实现逻辑回归

    pytorch使用nn.Moudle实现逻辑回归

    这篇文章主要为大家详细介绍了pytorch使用nn.Moudle实现逻辑回归,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    zeroooo000oo11172022-07-30
  • PythonPython3+SQLAlchemy+Sqlite3实现ORM教程

    Python3+SQLAlchemy+Sqlite3实现ORM教程

    这篇文章主要介绍了Python3+SQLAlchemy+Sqlite3实现ORM教程,需要的朋友可以参考下...

    诸子流10932021-09-05
  • Pythonpython实现微信每日一句自动发送给喜欢的人

    python实现微信每日一句自动发送给喜欢的人

    这篇文章主要为大家详细介绍了python实现微信每日一句自动发送给喜欢的人,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    正经男大学生BRLF3622021-06-22
  • Pythonpython3中dict(字典)的使用方法示例

    python3中dict(字典)的使用方法示例

    这篇文章主要介绍了python3中dict(字典)的使用方法,文中给出了详细的功能列举,对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。...

    渐晨6572020-09-25
  • Python深入浅析Python中的yield关键字

    深入浅析Python中的yield关键字

    python中有一个非常有用的语法叫做生成器,所利用到的关键字就是yield。接下来脚本之家小编给大家带来了Python中的yield关键字详细解析,感兴趣的朋友参考...

    震灵10072021-01-08
  • Pythonpython负载均衡的简单实现方法

    python负载均衡的简单实现方法

    这篇文章给大家介绍用python实现最简单的负载均衡方法,即将请求发送到未宕机的服务器上,感兴趣的朋友一起看看吧...

    熔遁丶螺旋手里剑5032021-01-12
  • PythonPython+PIL实现支付宝AR红包

    Python+PIL实现支付宝AR红包

    这篇文章主要为大家详细介绍了Python+PIL实现支付宝AR红包,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    christ012712202021-01-14