您好,登錄后才能下訂單哦!
基于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+j<self.size: chess=self.__board[i+j][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) 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 i+j<self.size: chess=self.__board[j][j+i] 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) 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+1>0: 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
然后是用while循環實現的單機版五子棋
# -*- coding: utf-8 -*- #單機版五子棋 from chess import chessboard def changeid(id): if id==1: return 2 elif id==2: return 1 else: return 0 t=chessboard() id=1#初始化id t.draw() while (not t.is_end()):#end函數 print('your id is %d,input your next drop(x,y)'% id) x=input() y=input() x=int(x) y=int(y) if t.drop_chess(x,y,id): t.draw() else: print('_________Illegal Input,Please Check Again_________') continue id=changeid(id)
———————分割線———————
由于要實現雙人對戰,所以服務器端必須要用多線程使其服務多個客戶端,因此使用threading
服務器端
# -*- coding: utf-8 -*- #服務器 import os import socket import json import threading import time import sys from chess import chessboard t=chessboard() id=1#初始化id def handle(): while (not t.is_end()): for c in socks: global id json_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\n" c.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')) continue id = changeid(id) def clear(): os.system('cls') def changeid(id): if id==1: return 2 elif id==2: return 1 else: return 0 # 創建 socket 對象 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 獲取本地主機名 host = socket.gethostname() port = 9999 # 綁定端口號 s.bind((host, port)) address=(host, port) # 設置最大連接數,超過后排隊 s.listen(2) socks=[] th = threading.Thread(target=handle) th.start() while 1: c, addr = s.accept() print 'connected from:', addr socks.append(c) s.close()
然后是客戶端
# -*- coding: utf-8 -*- #客戶端 import socket import time # 創建 socket 對象 c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 獲取本地主機名 #host = socket.gethostname() host='10.41.114.198' # 設置端口號 port = 9999 # 連接服務,指定主機和端口 c.connect((host, port)) address=(host, port) while 1: #s=c.accept() print('') print('__________________wait__________________') msg0 = c.recv(2048).decode('utf-8') # 棋盤大于1024 for 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')#棋盤大于1024 if msg3=='_________Illegal Input,Please Check Again_________': print(msg3) continue else: #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坐標開始游戲。
由于時間緊急,暫時未處理單個客戶端退出后的程序初始化問題,可能過幾日會補上。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。