fixed some bugs... on network functions

master
tzzzzzzzx 3 years ago
parent cb713a61df
commit 5118bd9cbe

@ -18,6 +18,7 @@ import socket
import SafariChess_backend as backend import SafariChess_backend as backend
from SafariChess_Classes import Button, DropDown from SafariChess_Classes import Button, DropDown
from threading import Thread, Lock from threading import Thread, Lock
from itertools import cycle
import time import time
#设置棋盘的参数 #设置棋盘的参数
@ -46,7 +47,6 @@ connection = None
#网络版更新需要注意多线程的问题? #网络版更新需要注意多线程的问题?
server_died_message = 'fucking server died and quit' server_died_message = 'fucking server died and quit'
#尝试写一个函数分配一个新线程供监听 #尝试写一个函数分配一个新线程供监听
def startNewThread(target): def startNewThread(target):
thread = Thread(target=target) thread = Thread(target=target)
thread.daemon =True thread.daemon =True
@ -60,11 +60,9 @@ def listenFromServer():
networkMsg = json.loads(recvMsg) networkMsg = json.loads(recvMsg)
print('receive thread catch: ',networkMsg) print('receive thread catch: ',networkMsg)
except socket.error as e: except socket.error as e:
#print('Error encountered in connection. Quit.')
print(e) print(e)
return e return False
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)
@ -213,7 +211,7 @@ def showGameOverText(screen, text):
screen.blit(text_object, text_location) screen.blit(text_object, text_location)
text_object = font.render(text, False, pg.Color('red')) text_object = font.render(text, False, pg.Color('red'))
screen.blit(text_object, text_location.move(-2 , -2)) screen.blit(text_object, text_location.move(-2 , -2))
pg.display.flip()
def MainMenu(): def MainMenu():
#显示主菜单 #显示主菜单
@ -418,7 +416,7 @@ def main(mode):
# 每隔1秒发送一次自定义事件 # 每隔1秒发送一次自定义事件
pg.time.set_timer(COUNT,1000) pg.time.set_timer(COUNT,1000)
now = time.ctime()# 获得系统当前时间 now = time.ctime()# 获得系统当前时间
countdown_clock = now[11:19]# 格式化形式为时分秒 countdown_clock = now[11:19] # 格式化形式为时分秒
bigfont = pg.font.SysFont("Courier", 32) bigfont = pg.font.SysFont("Courier", 32)
minfont = pg.font.SysFont("Courier", 24) minfont = pg.font.SysFont("Courier", 24)
showText(screen,bigfont,"Time:",600,600) showText(screen,bigfont,"Time:",600,600)
@ -426,6 +424,8 @@ def main(mode):
showText(screen,bigfont,countdown_clock,600,650) showText(screen,bigfont,countdown_clock,600,650)
pg.display.update() pg.display.update()
startNetworkServices() startNetworkServices()
#! start login
myPlayerData = { myPlayerData = {
'type': 0, # game state type ? 'type': 0, # game state type ?
'msg': { 'msg': {
@ -437,14 +437,26 @@ 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 login_font = pg.font.SysFont("comicsansms", 32)
text_object = login_font.render('waiting 4 connection...', True, pg.Color("grey"))
login_text_location = pg.Rect(0, 0, BOARD_WIDTH, BOARD_HEIGHT).move(BOARD_WIDTH / 2 - text_object.get_width() / 2,BOARD_HEIGHT / 2 - text_object.get_height() / 2)
while networkMsg == None:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
screen.blit(text_object,login_text_location)
clock.tick(20)
pg.display.update()
pg.display.flip()
#! end login
while running: while running:
#! 特别注意红方是0蓝方是1
#print('current moving color: ',game_state.color()) #print('current moving color: ',game_state.color())
if lastNetworkMsg != networkMsg:#handle if lastNetworkMsg != networkMsg:#handle
if(networkMsg == server_died_message): #! 无法解决的问题:判断延迟导致无法同时接收来自服务器的两条转发消息。
print("server died")
return None
print('catch new msg: ',networkMsg) print('catch new msg: ',networkMsg)
lastNetworkMsg = networkMsg #networkMsg中保存当前字典 lastNetworkMsg = networkMsg #networkMsg中保存当前字典
if 'status' in networkMsg.keys(): if 'status' in networkMsg.keys():
@ -455,24 +467,25 @@ def main(mode):
print('Game start 2 play!') print('Game start 2 play!')
game_id = networkMsg['game_id'] game_id = networkMsg['game_id']
MySide = networkMsg['side'] MySide = networkMsg['side']
other_stage = True if networkMsg['side']==0 else False other_stage = True if networkMsg['side']==1 else False #一开始如果我是蓝方则other_stage为真
if(other_stage == True): if(other_stage == True):
print('waiting for other player to move...') print('waiting for other player to move...')
#quick_game_handler #state_game_handler
elif networkMsg['status'] == 2 : # Stopping request elif networkMsg['status'] == 2 : # Stopping request
print('other player returned special message: ',networkMsg['request']) print('other player returned special message: ',networkMsg['request'])
if networkMsg['request']=='quit': if networkMsg['request']=='quit':
other_joined = False other_joined = False
elif networkMsg['request'] == 'stop': elif networkMsg['request'] == 'stop':
game_state.win_person = 'b' if networkMsg['side'] == 1 else 'r'
pass pass
elif networkMsg['request'] == 'report': elif networkMsg['request'] == 'report':
foul = networkMsg['side'] foul = networkMsg['side']
otherQuitJson = { otherQuitJson = {
'type': 3, 'type': 3,
'side': 0 'side': MySide
} }
client.send(json.dumps(otherQuitJson).encode('utf-8')) client.send(json.dumps(otherQuitJson).encode('utf-8'))
game_over = True game_over = True
@ -482,17 +495,19 @@ def main(mode):
time_out_side = networkMsg['side'] time_out_side = networkMsg['side']
otherQuitJson = { otherQuitJson = {
'type': 3, 'type': 3,
'side': 0 'side': MySide
} }
client.send(json.dumps(otherQuitJson).encode('utf-8')) client.send(json.dumps(otherQuitJson).encode('utf-8'))
game_over = True game_over = True
#Move handler
elif 'src' and 'dst' in networkMsg.keys(): 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) theMove = backend.Move([networkMsg['src']['y'],networkMsg['src']['x']],[networkMsg['dst']['y'],networkMsg['dst']['x']],game_state.board)
game_state.makeMove(theMove) game_state.makeMove(theMove)
valid_moves = game_state.getAllMoves() valid_moves = game_state.getAllMoves()
other_stage = not other_stage other_stage = not other_stage
game_state.conquer()#update conquer stage
thisMove = None thisMove = None
for e in pg.event.get(): for e in pg.event.get():
#接下来处理游戏中的事件 #接下来处理游戏中的事件
@ -544,14 +559,14 @@ def main(mode):
'msg': { 'msg': {
"game_id": game_id, "game_id": game_id,
"side": MySide, "side": MySide,
"chessman": thisMove.cur_piece, "chessman": int(thisMove.cur_piece[1:]),
"src": { "src": {
"x": thisMove.start_row, "y": thisMove.start_row,
"y": thisMove.start_col "x": thisMove.start_col
}, },
"dst": { "dst": {
"x": thisMove.end_row, "y": thisMove.end_row,
"y": thisMove.end_col "x": thisMove.end_col
} }
} }
} }
@ -561,10 +576,10 @@ def main(mode):
#思路变成:定时对敌方进行扫描,若收到更新相关包则进行局面更新。 #思路变成:定时对敌方进行扫描,若收到更新相关包则进行局面更新。
ShowGameState(screen,game_state,valid_moves,square_selected) ShowGameState(screen,game_state,valid_moves,square_selected)
if game_state.conquer(): if game_state.conquer() and not game_over:
print("GAME OVER!") print("GAME OVER!")
showGameOverText(screen,"player "+game_state.win_person+" wins") #
if not game_over and game_state.win_person == ('b' if MySide == 0 else 'r' ): if game_state.win_person == ('b' if MySide == 1 else 'r'):
winJson = { winJson = {
'type': 2, 'type': 2,
'msg': { 'msg': {
@ -574,12 +589,17 @@ def main(mode):
} }
} }
client.send(json.dumps(winJson).encode("utf-8")) client.send(json.dumps(winJson).encode("utf-8"))
print('i won, and game over message sent.')
game_over = True game_over = True
#print('game over label confirmed.')
if game_over and other_joined:
if (game_state.win_person == ''): game_state.conquer()
showGameOverText(screen,"player "+game_state.win_person+" wins")
if game_over and not other_joined: if game_over and not other_joined:
showGameOverText(screen,"player "+ ("b" if MySide==1 else "r") + " quitted the game") showGameOverText(screen,"player "+ ("b" if MySide==0 else "r") + " quitted the game") #对手退出了
if time_out_side != None: if time_out_side != None:
showGameOverText(screen,"player "+ ("b" if time_out_side==0 else "r")+" timed out") showGameOverText(screen,"player "+ ("b" if time_out_side==1 else "r")+" timed out") #超时了
clock.tick(50) clock.tick(50)
@ -588,8 +608,8 @@ def main(mode):
pg.display.flip() pg.display.flip()
if __name__ == '__main__': if __name__ == '__main__':
print("Loading...") #print("Loading...")
print("Initialing game...") #print("Initialing game...")
mode = MainMenu() mode = MainMenu()
#mode = 2 #mode = 2
main(mode) main(mode)

@ -1,5 +1,5 @@
SOCKET_HOST=127.0.0.1 SOCKET_HOST=127.0.0.1
SOCKET_PORT=50005 SOCKET_PORT=50005
MAX_WAITING_TIME=600 MAX_WAITING_TIME=600
MAX_THNIKING_TIME=15 MAX_THNIKING_TIME=200
MAX_TOTAL_TIME=1000 MAX_TOTAL_TIME=1000

Loading…
Cancel
Save