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

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

Loading…
Cancel
Save