基于python的socket实现单机五子棋到双人对战,供大家参考,具体内容如下

本次实验使用python语言。通过socket进行不同机器见的通信,具体可以分为以下四步:1.创建ServerSocket和Socket;2.打开链接到Socket的输入/输出流;3.按照协议对Socket进行读/写操作;4.关闭输入输出流、关闭Socket。
由于是双人对战,服务器必须应对多人及以上的客户端的连接,因此本实验还引入了python的threading多线程模块,通过监听实时监控网络状态,同时利用socket.listen(2)引入排队等待机制。
chess类
#五子棋类
import os
class 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 < self.size:
ntr=str(n)
self.__board[0][n] = ntr.zfill(2)
self.__board[n][0] = ntr.zfill(2)
n=n+1
self.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 1
elif len(ch_stack) == 5 and ch_stack[-1] == '@ ':
print('winner=id 2')
return 2
if chess==' ':
ch_stack.clear()
else:
if (not ch_stack) or ch_stack[-1] == chess:
ch_stack.append(chess)
else:
ch_stack.clear()
ch_stack.append(chess)
ch_stack.clear()
ch_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 1
elif len(ch_stack) == 5 and ch_stack[-1] == '@ ':
print('winner=id 2')
return 2
chess=self.__board[i][j]
if chess==' ':
ch_stack.clear()
else:
if (not ch_stack) or ch_stack[-1] == chess:
ch_stack.append(chess)
else:
ch_stack.clear()
ch_stack.append(chess)
ch_stack.clear()
ch_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 1
elif len(ch_stack) == 5 and ch_stack[-1] == '@ ':
print('winner=id 2')
return 2
if i+j0:
chess=self.__board[self.size-i-j][j]
if chess==' ':
ch_stack.clear()
elif not chess:
break
else:
if (not ch_stack) or ch_stack[-1] == chess:
ch_stack.append(chess)
else:
ch_stack.clear()
ch_stack.append(chess)
else:
break
ch_stack.clear()
ch_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 1
elif len(ch_stack) == 5 and ch_stack[-1] == '@ ':
print('winner=id 2')
return 2
if self.size-i-j> 0:
chess = self.__board[j][self.size-i-j]
if chess == ' ':
ch_stack.clear()
elif not chess:
break
else:
if (not ch_stack) or ch_stack[-1] == chess:
ch_stack.append(chess)
else:
ch_stack.clear()
ch_stack.append(chess)
else:
break
ch_stack.clear()
ch_stack.clear()
return 0
def draw(self):
#clear()
for x in self.__board:
print(x)
return 0
def drop_chess(self,x,y,id):
if id==1 and self.__board[x][y]==' ':
self.__board[x][y]='* '
return 1
elif id==2 and self.__board[x][y]==' ':
self.__board[x][y]='@ '
return 1
else:
return 0 另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。