DoubleQ 3 years ago
parent 15b3394ae5
commit 17234132a0

@ -43,6 +43,7 @@ port = None
addr = None addr = None
connection = None connection = None
#网络版更新需要注意多线程的问题? #网络版更新需要注意多线程的问题?
server_died_message = 'fucking server died and quit'
#尝试写一个函数分配一个新线程供监听 #尝试写一个函数分配一个新线程供监听
def startNewThread(target): def startNewThread(target):
@ -53,12 +54,16 @@ def listenFromServer():
global networkMsg global networkMsg
try: try:
while True: while True:
recvMsg = client.recvfrom(1024).decode('utf-8') recvMsg = client.recv(1024).decode('utf-8')
if len(recvMsg) != 0: if len(recvMsg) != 0:
networkMsg = json.loads(recvMsg) networkMsg = json.loads(recvMsg)
print('receive thread catch: ',networkMsg)
except socket.error as e: except socket.error as e:
print(e) print(e)
return e return e
except OSError:
networkMsg = server_died_message
return None
def startNetworkServices(): def startNetworkServices():
global client,server,port,addr,connection global client,server,port,addr,connection
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@ -284,11 +289,15 @@ def main(mode):
#* cancelled args: MySide=True if not isOnline else bool(NewPlayerMessage['side']),game_id=NewPlayerMessage['game_id'] #* cancelled args: MySide=True if not isOnline else bool(NewPlayerMessage['side']),game_id=NewPlayerMessage['game_id']
valid_moves=game_state.getAllMoves() valid_moves=game_state.getAllMoves()
running = True running = True
other_joined = False other_joined = False #network element
other_stage = False #network element
game_id = None #network element
MySide = None #network element
mademove = False mademove = False
game_over = False game_over = False
square_selected = () #刚开始没有选择任何一个棋子 square_selected = () #刚开始没有选择任何一个棋子
click_queue = [] #点击队列,记录第一次点击和第二次点击位置,方便移动棋子 click_queue = [] #点击队列,记录第一次点击和第二次点击位置,方便移动棋子
pg.display.update() pg.display.update()
startGamePage(mode) startGamePage(mode)
@ -350,32 +359,55 @@ def main(mode):
login_packet = login_packet.encode('utf-8') login_packet = login_packet.encode('utf-8')
lastNetworkMsg = networkMsg lastNetworkMsg = networkMsg
client.send(login_packet) client.send(login_packet)
while networkMsg == None: pass
while running: while running:
#print('current moving color: ',game_state.color())
if lastNetworkMsg != networkMsg:#handle if lastNetworkMsg != networkMsg:#handle
print('get new msg: ',networkMsg) if(networkMsg == server_died_message):
print("server died")
return None
print('catch new msg: ',networkMsg)
lastNetworkMsg = networkMsg #networkMsg中保存当前字典 lastNetworkMsg = networkMsg #networkMsg中保存当前字典
if 'status' in networkMsg.keys(): if 'status' in networkMsg.keys():
if networkMsg['status'] == 1: #Login_handler
print('Waiting for another player to connect') if networkMsg['status'] == 1: #Finished Login process
if other_joined == False:
other_joined = True
elif 'src' and 'dst' in networkMsg.keys():
if other_joined == False:
other_joined = True
print('Game start 2 play!') print('Game start 2 play!')
else: game_id = networkMsg['game_id']
theMove = backend.Move([networkMsg['src']['x'],networkMsg['src']['y']],[networkMsg['dst']['x'],networkMsg['dst']['y']],game_state.board) MySide = networkMsg['side']
game_state.makeMove(theMove) other_stage = True if networkMsg['side']==0 else False
game_state.exchange() if(other_stage == True):
print('waiting for other player to move...')
#quick_game_handler
elif networkMsg['status'] == 2 : # other player quit the game
print('other player quitted with message: ',networkMsg['request'])
running = False
elif 'src' and 'dst' in networkMsg.keys():
theMove = backend.Move([networkMsg['src']['x'],networkMsg['src']['y']],[networkMsg['dst']['x'],networkMsg['dst']['y']],game_state.board)
game_state.makeMove(theMove)
#game_state.exchange()
valid_moves = game_state.getAllMoves()
other_stage = not other_stage
thisMove = None
for e in pg.event.get(): for e in pg.event.get():
#接下来处理游戏中的事件 #接下来处理游戏中的事件
if e.type == pg.QUIT: if e.type == pg.QUIT:
quitJson = {
"type": 2,
"msg": {
"request": "quit",
"game_id": game_id,
"side": MySide
}
}
client.send(json.dumps(quitJson).encode('utf-8'))
pg.quit() pg.quit()
sys.exit() sys.exit()
elif e.type == pg.MOUSEBUTTONDOWN: elif e.type == pg.MOUSEBUTTONDOWN:
#鼠标点击事件:用于选择棋子,移动棋子 #鼠标点击事件:用于选择棋子,移动棋子
if not game_over: if not game_over and not other_stage:
mouse_loc = pg.mouse.get_pos() mouse_loc = pg.mouse.get_pos()
row = int((mouse_loc[1] - bias_top) / SIZE) row = int((mouse_loc[1] - bias_top) / SIZE)
col = int((mouse_loc[0] - bias_left) / SIZE) #* get position of mouse click col = int((mouse_loc[0] - bias_left) / SIZE) #* get position of mouse click
@ -389,6 +421,7 @@ def main(mode):
cur_piece_loc = click_queue[0] cur_piece_loc = click_queue[0]
nxt_piece_loc = click_queue[1] nxt_piece_loc = click_queue[1]
move = backend.Move(cur_piece_loc,nxt_piece_loc,game_state.board) move = backend.Move(cur_piece_loc,nxt_piece_loc,game_state.board)
thisMove = move
if move in valid_moves: if move in valid_moves:
game_state.makeMove(move) game_state.makeMove(move)
mademove = True mademove = True
@ -406,14 +439,37 @@ def main(mode):
#? 但是考虑到ui刷新问题故仍尝试在main中写 #? 但是考虑到ui刷新问题故仍尝试在main中写
#ShowGameState(screen,game_state,valid_moves,square_selected) #ShowGameState(screen,game_state,valid_moves,square_selected)
if mademove: if mademove:
valid_moves = game_state.getAllMoves()
mademove = False mademove = False
if isOnline:
print('waiting for the other player to move...')
other_stage = not other_stage
thisMoveJson = {
'type': 1,
'msg': {
"game_id": game_id,
"side": MySide,
"chessman": thisMove.cur_piece,
"src": {
"x": thisMove.start_row,
"y": thisMove.start_col
},
"dst": {
"x": thisMove.end_row,
"y": thisMove.end_col
}
}
}
client.send(json.dumps(thisMoveJson).encode('utf-8'))
#思路变成:定时对敌方进行扫描,若收到更新相关包则进行局面更新。 #思路变成:定时对敌方进行扫描,若收到更新相关包则进行局面更新。
ShowGameState(screen,game_state,valid_moves,square_selected) ShowGameState(screen,game_state,valid_moves,square_selected)
if game_state.conquer(): if game_state.conquer():
showGameOverText(screen,"player "+game_state.win_person+" wins") showGameOverText(screen,"player "+game_state.win_person+" wins")
game_over = True game_over = True
clock.tick(10) clock.tick(5)
pg.display.flip() pg.display.flip()

@ -27,108 +27,108 @@ def startNewThread(target):
thread.daemon = True thread.daemon = True
thread.start() thread.start()
class Network: # class Network:
def __init__(self,isNet=False): #注意:这里是否在传引用? # def __init__(self,isNet=False): #注意:这里是否在传引用?
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "127.0.0.1" # self.server = "127.0.0.1"
self.port = 50005 # self.port = 50005
self.addr = (self.server, self.port) # self.addr = (self.server, self.port)
self.msg = self.connect() # self.msg = self.connect()
#self.game_state = game_state #考虑将game_state接入Network以方便修改 # #self.game_state = game_state #考虑将game_state接入Network以方便修改
global msg_from_serv # global msg_from_serv
thread = Thread(target = self.receive())#开线程始终监听 # thread = Thread(target = self.receive())#开线程始终监听
thread.setDaemon(True) # thread.setDaemon(True)
thread.start() #专用数据接收线程 # thread.start() #专用数据接收线程
def getPos(self): # def getPos(self):
return self.pos # return self.pos
def connect(self): # def connect(self):
try: # try:
self.client.connect(self.addr) # self.client.connect(self.addr)
#return self.client.recv(2048).decode() # #return self.client.recv(2048).decode()
except: # except:
pass # pass
def send(self, msg): # def send(self, msg):
try: # try:
packet = json.dumps(msg) # packet = json.dumps(msg)
if (sys.version[:1] == '3'): # if (sys.version[:1] == '3'):
packet = packet.encode('utf-8') # packet = packet.encode('utf-8')
self.client.send(packet) # self.client.send(packet)
print("send complete") # print("send complete")
return self.client.recv(2048).encode() # return self.client.recv(2048).encode()
except socket.error as e: # except socket.error as e:
print(e) # print(e)
return e # return e
def post(self, data): #using requests lib, data is json # def post(self, data): #using requests lib, data is json
headers = {'Content-Type': 'application/json'} # headers = {'Content-Type': 'application/json'}
response = requests.post(url='http://localhost',data=data) # response = requests.post(url='http://localhost',data=data)
return response # return response
def receive(self): #写成持续监听模式 # def receive(self): #写成持续监听模式
try: # try:
while True: # while True:
recvMsg = self.client.recv(2048).decode('utf-8') # recvMsg = self.client.recv(2048).decode('utf-8')
if len(recvMsg) != 0: # if len(recvMsg) != 0:
msg_from_serv = json.loads(recvMsg) # msg_from_serv = json.loads(recvMsg)
self.dataDealer(msg_from_serv) # self.dataDealer(msg_from_serv)
except socket.error as e: # except socket.error as e:
print(e) # print(e)
return e # return e
def dataDealer(self, msg_json): #根据相关数据对棋盘状态进行更新 # def dataDealer(self, msg_json): #根据相关数据对棋盘状态进行更新
if 'status' in msg_json.keys(): # if 'status' in msg_json.keys():
#处理相关特殊情况 # #处理相关特殊情况
if msg_json['status'] == '1': # if msg_json['status'] == '1':
print('Waiting 4 the other player...') # print('Waiting 4 the other player...')
elif 'src' and 'dst' in msg_json.keys(): #侦测到移动 # elif 'src' and 'dst' in msg_json.keys(): #侦测到移动
theMove = Move([msg_json['src']['x'],msg_json['src']['y']],[msg_json['dst']['x'],msg_json['dst']['y']],self.game_state.board) # theMove = Move([msg_json['src']['x'],msg_json['src']['y']],[msg_json['dst']['x'],msg_json['dst']['y']],self.game_state.board)
self.game_state.makeMove(theMove,toUpload = False) # self.game_state.makeMove(theMove,toUpload = False)
self.game_state.exchange() # self.game_state.exchange()
def dataReceiver(self): # def dataReceiver(self):
try: # try:
while True: # while True:
msg = self.client.recv(2048).decode('utf-8') # msg = self.client.recv(2048).decode('utf-8')
if len(msg) != 0: self.dataDealer(json.loads(msg)) # if len(msg) != 0: self.dataDealer(json.loads(msg))
except socket.error as e: # except socket.error as e:
print(e) # print(e)
return e # return e
def tell_move(self, move: Move): # def tell_move(self, move: Move):
thisMove = { # thisMove = {
'type': 1, # 'type': 1,
'msg':{ # 'msg':{
"game_id": self.game_id, # "game_id": self.game_id,
"side": int(self.red_to_move), # "side": int(self.red_to_move),
"chessman": move.cur_piece, # "chessman": move.cur_piece,
"src": { # "src": {
"x": move.start_row, # "x": move.start_row,
"y": move.start_col # "y": move.start_col
}, # },
"dst": { # "dst": {
"x": move.end_row, # "x": move.end_row,
"y": move.end_col # "y": move.end_col
} # }
} # }
} # }
self.client.send(thisMove) # self.client.send(thisMove)
def login(self,myName): # def login(self,myName):
myPlayerData = { # myPlayerData = {
'type': 0, # game state type ? # 'type': 0, # game state type ?
'msg': { # 'msg': {
'name': myName # 'name': myName
} # }
} # }
self.client.send(myPlayerData) # self.client.send(myPlayerData)
class GameState: class GameState:
def __init__(self): def __init__(self):
@ -221,6 +221,7 @@ class GameState:
for col in range(len(self.board[row])): for col in range(len(self.board[row])):
player = self.board[row][col][0] player = self.board[row][col][0]
if (player == 'r' and self.red_to_move or player == 'b' and not self.red_to_move): if (player == 'r' and self.red_to_move or player == 'b' and not self.red_to_move):
#print('what color is the valid move? ',player)
self.moveFunctions[self.board[row][col][1]](row,col,moves) self.moveFunctions[self.board[row][col][1]](row,col,moves)
return moves return moves

Loading…
Cancel
Save