欧美成人午夜免费全部完,亚洲午夜福利精品久久,а√最新版在线天堂,另类亚洲综合区图片小说区,亚洲欧美日韩精品色xxx

千鋒扣丁學(xué)堂Python培訓(xùn)之socket實(shí)現(xiàn)單機(jī)五子棋到雙人對(duì)戰(zhàn)

2019-06-18 13:10:58 3052瀏覽

今天千鋒扣丁學(xué)堂Python培訓(xùn)老師給大家分享一篇關(guān)于基于python的socket實(shí)現(xiàn)單機(jī)五子棋到雙人對(duì)戰(zhàn)的詳細(xì)介紹,首先本次實(shí)驗(yàn)使用python語(yǔ)言。通過(guò)socket進(jìn)行不同機(jī)器見的通信,具體可以分為以下四步:1.創(chuàng)建ServerSocket和Socket;2.打開鏈接到Socket的輸入/輸出流;3.按照協(xié)議對(duì)Socket進(jìn)行讀/寫操作;4.關(guān)閉輸入輸出流、關(guān)閉Socket。



由于是雙人對(duì)戰(zhàn),服務(wù)器必須應(yīng)對(duì)多人及以上的客戶端的連接,因此本實(shí)驗(yàn)還引入了python的threading多線程模塊,通過(guò)監(jiān)聽實(shí)時(shí)監(jiān)控網(wǎng)絡(luò)狀態(tài),同時(shí)利用socket.listen(2)引入排隊(duì)等待機(jī)制。

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
    #添加桌面標(biāo)簽
    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):
        #判斷是否結(jié)束
        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):
        #判斷是否結(jié)束
        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):
        #判斷是否結(jié)束
        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):
        #判斷是否結(jié)束
        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):
        #判斷是否結(jié)束
        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):
        # 判斷是否結(jié)束
        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循環(huán)實(shí)現(xiàn)的單機(jī)版五子棋

# -*- coding: utf-8 -*-
#單機(jī)版五子棋
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函數(shù)
  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)

———————分割線———————

由于要實(shí)現(xiàn)雙人對(duì)戰(zhàn),所以服務(wù)器端必須要用多線程使其服務(wù)多個(gè)客戶端,因此使用threading

服務(wù)器端

# -*- coding: utf-8 -*-
#服務(wù)器
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
# 創(chuàng)建 socket 對(duì)象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 獲取本地主機(jī)名
host = socket.gethostname()
port = 9999
# 綁定端口號(hào)
s.bind((host, port))
address=(host, port)
# 設(shè)置最大連接數(shù),超過(guò)后排隊(duì)
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
 
# 創(chuàng)建 socket 對(duì)象
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 獲取本地主機(jī)名
#host = socket.gethostname()
host='10.41.114.198'
# 設(shè)置端口號(hào)
port = 9999
# 連接服務(wù),指定主機(jī)和端口
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傳輸時(shí)只能傳送bytes,因此list先用json轉(zhuǎn)成str,再encode編碼

使用方法:先更改客戶端host為自己地址,然后先打開服務(wù)端,然后打開多個(gè)客戶端(大于2個(gè)開始排隊(duì)),然后開始輸入X,Y坐標(biāo)開始游戲。



以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,希望大家能靈活掌握本文中提到的方法,想要了解更多關(guān)于Python開發(fā)方面內(nèi)容的小伙伴,請(qǐng)關(guān)注扣丁學(xué)堂Python培訓(xùn)官網(wǎng)、微信等平臺(tái),扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育有專業(yè)的Python講師為您指導(dǎo),此外扣丁學(xué)堂老師精心推出的Python視頻教程定能讓你快速掌握Python從入門到精通開發(fā)實(shí)戰(zhàn)技能。扣丁學(xué)堂Python技術(shù)交流群:279521237。


扣丁學(xué)堂微信公眾號(hào)                          Python全棧開發(fā)爬蟲人工智能機(jī)器學(xué)習(xí)數(shù)據(jù)分析免費(fèi)公開課直播間


      【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】         【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】



查看更多關(guān)于"Python開發(fā)資訊"的相關(guān)文章>

標(biāo)簽: Python培訓(xùn) Python視頻教程 Python在線視頻 Python學(xué)習(xí)視頻 Python培訓(xùn)班

熱門專區(qū)

暫無(wú)熱門資訊

課程推薦

微信
微博
15311698296

全國(guó)免費(fèi)咨詢熱線

郵箱:codingke@1000phone.com

官方群:148715490

北京千鋒互聯(lián)科技有限公司版權(quán)所有   北京市海淀區(qū)寶盛北里西區(qū)28號(hào)中關(guān)村智誠(chéng)科創(chuàng)大廈4層
京ICP備2021002079號(hào)-2   Copyright ? 2017 - 2022
返回頂部 返回頂部