今天千锋扣丁学堂Python培训老师给大家分享一篇关于基于python的socket实现单机五子棋到双人对战的详细介绍,首先本次实验使用python语言。通过socket进行不同机器见的通讯,具体可以分为以下四步:1.建立ServerSocket和Socket;2.开启连结到Socket的输入/输出流;3.按照协议对Socket进行读/写操作;4.关闭输入输出流、关闭Socket。
由于是双人对战,服务器必须应对多人及以上的客户端的连线,因此本实验还引入了python的threading多执行绪模组,通过实时监控网络状态,同时利用socket.listen(2)引入排队等待机制。chess类#五子棋类import osclass chessboard(object):def __init__(self):self.size = 16#初始化棋盘self.__board=[[\ \ for n in range(self.size)] for m in range(self.size)]n = 0#新增桌面标签while n ntr=str(n)self.__board[0][n] = ntr.zfill(2)self.__board[n][0] = ntr.zfill(2)n=n+1self.id=0#胜利条件def is_end(self):ch_stack=#行检查for i in range(self.size):for j in range(self.size):#判断是否结束chess=self.__board[i][j]if len(ch_stack)==5 and ch_stack[-1]==\* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2if chess==\ \:ch_stack.clearelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)ch_stack.clearch_stack.clear#列检查for j in range(self.size):for i in range(self.size):#判断是否结束if len(ch_stack)==5 and ch_stack[-1]==\* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2chess=self.__board[i][j]if chess==\ \:ch_stack.clearelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)ch_stack.clearch_stack.clear#左斜检查#下三角for i in range(self.size):for j in range(1,self.size):#判断是否结束if len(ch_stack)==5 and ch_stack[-1]==\* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2if i+jchess=self.__board[i+j][j]if chess==\ \:ch_stack.clearelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)else:breakch_stack.clearch_stack.clear#上三角for i in range(self.size):for j in range(1,self.size):#判断是否结束if len(ch_stack)==5 and ch_stack[-1]==\* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2if i+jchess=self.__board[j][j+i]if chess==\ \:ch_stack.clearelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)else:breakch_stack.clearch_stack.clear#右斜检查#上三角for i in range(self.size):for j in range(1,self.size):#判断是否结束if len(ch_stack)==5 and ch_stack[-1]==\* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2if self.size-i-j+1>0:chess=self.__board[self.size-i-j][j]if chess==\ \:ch_stack.clearelif not chess:breakelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)else:breakch_stack.clearch_stack.clear#下三角for i in range(self.size):for j in range(1,self.size):# 判断是否结束if len(ch_stack) == 5 and ch_stack[-1] == \* \:print(\winner=id 1\)return 1elif len(ch_stack) == 5 and ch_stack[-1] == \@ \:print(\winner=id 2\)return 2if self.size-i-j> 0:chess = self.__board[j][self.size-i-j]if chess == \ \:ch_stack.clearelif not chess:breakelse:if (not ch_stack) or ch_stack[-1] == chess:ch_stack.append(chess)else:ch_stack.clearch_stack.append(chess)else:breakch_stack.clearch_stack.clearreturn 0def draw(self):#clearfor x in self.__board:print(x)return 0def drop_chess(self,x,y,id):if id==1 and self.__board[x][y]==\ \:self.__board[x][y]=\* \return 1elif id==2 and self.__board[x][y]==\ \:self.__board[x][y]=\@ \return 1else:return 0然后是用while循环实现的单机版五子棋# -*- coding: utf-8 -*-#单机版五子棋from chess import chessboarddef changeid(id):if id==1:return 2elif id==2:return 1else:return 0t=chessboardid=1#初始化idt.drawwhile (not t.is_end):#end函式print(\your id is %d,input your next drop(x,y)\% id)x=inputy=inputx=int(x)y=int(y)if t.drop_chess(x,y,id):t.drawelse:print(\_________Illegal Input,Please Check Again_________\)continueid=changeid(id)———————分割线———————由于要实现双人对战,所以服务器端必须要用多执行绪使其服务多个客户端,因此使用threading服务器端# -*- coding: utf-8 -*-#服务器import osimport socketimport jsonimport threadingimport timeimport sysfrom chess import chessboardt=chessboardid=1#初始化iddef handle:while (not t.is_end):for c in socks:global idjson_string0 = json.dumps(t._chessboard__board)c.sendto(json_string0.encode(\utf-8\), address)msg1 = \Your id is %d,input your next drop\ % id + \\r\\nc.send(msg1.encode(\utf-8\))msg2x = c.recv(1024)msg2y = c.recv(1024)x = int(msg2x.decode(\utf-8\))y = int(msg2y.decode(\utf-8\))print(\processing......\\n\)if t.drop_chess(x, y, id):json_string = json.dumps(t._chessboard__board)c.sendto(json_string.encode(\utf-8\), address)else:msg3 = \_________Illegal Input,Please Check Again_________\c.send(msg3.encode(\utf-8\))continueid = changeid(id)def clear:os.system(\cls\)def changeid(id):if id==1:return 2elif id==2:return 1else:return 0# 建立 socket 物件s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 获取本地主机名host = socket.gethostnameport = 9999# 系结埠号s.bind((host, port))address=(host, port)# 设定最大连线数,超过后排队s.listen(2)socks=th = threading.Thread(target=handle)th.startwhile 1:c, addr = s.acceptprint\connected from:\, addrsocks.append(c)s.close然后是客户端# -*- coding: utf-8 -*-#客户端import socketimport time# 建立 socket 物件c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 获取本地主机名#host = socket.gethostnamehost=\10.41.114.198\# 设定埠号port = 9999# 连线服务,指定主机和埠c.connect((host, port))address=(host, port)while 1:#s=c.acceptprint(\\)print(\wait\)msg0 = c.recv(2048).decode(\utf-8\) # 棋盘大于1024for x in msg0:if x == \[\:print(\\)else:print(x, end=\\)print(\\)msg1 = c.recv(1024)#接收输入提示print (msg1.decode(\utf-8\))time.sleep(1)x = input(\x=\)y = input(\y=\)c.send(x.encode(\utf-8\))c.send(y.encode(\utf-8\))msg3 = c.recv(2048).decode(\utf-8\)#棋盘大于1024if msg3==\_________Illegal Input,Please Check Again_________\:print(msg3)continueelse:#print(msg3)for x in msg3:if x==\[\:print(\\)else:print(x, end=\\)print(\\)print(\wait\)print(\\)c.close注意socket传输时只能传送bytes,因此list先用json转成str,再encode编码使用方法:先更改客户端host为自己地址,然后先开启服务端,然后开启多个客户端(大于2个开始排队),然后开始输入X,Y座标开始游戏。以上就是本文的全部内容,希望对大家的学习有所帮助,希望大家能灵活掌握本文中提到的方法,想要了解更多关于Python开发方面内容的小伙伴,请关注扣丁学堂Python培训官网、微信等平台,扣丁学堂IT职业线上学习教育有专业的Python讲师为您指导,此外扣丁学堂老师精心推出的Python视讯教程定能让你快速掌握Python从入门到精通开发实战技能。扣丁学堂Python技术交流群:279521237。本文为一点号作者原创,未经授权不得转载