From 5118bd9cbe8479bb36e5c14cbc7e34911019fc07 Mon Sep 17 00:00:00 2001 From: tzzzzzzzx <414850847@qq.com> Date: Thu, 22 Sep 2022 23:54:54 +0800 Subject: [PATCH] fixed some bugs... on network functions --- SafariChess_Gamev1.0.py | 82 +++++++++++------- .../SafariChess_Classes.cpython-39.pyc | Bin 795 -> 2310 bytes network/config.txt | 2 +- 3 files changed, 52 insertions(+), 32 deletions(-) diff --git a/SafariChess_Gamev1.0.py b/SafariChess_Gamev1.0.py index b0a49b8..0e20afd 100644 --- a/SafariChess_Gamev1.0.py +++ b/SafariChess_Gamev1.0.py @@ -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) diff --git a/__pycache__/SafariChess_Classes.cpython-39.pyc b/__pycache__/SafariChess_Classes.cpython-39.pyc index f522a807260310069fa23f0638fe01ff411ead1a..a59e4456eb90d82fbf6e8728685f2d557be23162 100644 GIT binary patch literal 2310 zcmZuyO^+Kz5bf^i8P9sx`;mlvKmaR(NQRI@4n#r`3dxdOz(H&R$XYa-ou2j1tUcrH z87JA*tQ0Bcn18^*J|Zss6b^_(UpeJ3aDi7n&c+LA$}A$>*ZyKy#G`&4VVD*kYZ=(fwu{V=LSZ zb#iwvE{fppAS{ZwxIQ|xQ**Vwo9p(@xGeLm9cHS%A0O`Ip;qnqah#P!^CgaE-H32; zoVfNLzQ(M_;hs>Q63UtI9-LF|guxk3&KU2GJ)j%O1sf!jnY;KEWTxU33xFxFgyJtq z6O{vW6oVPj?Qqj5^U)yQEj!Y<$uR84#_z{vpyQ}C(xM-QgTYQ1?PG~7;=!(_gL?ib zFOo9JGu?pt3)2WV`}^kRXWQTCJjM1Owr||{VqA`g+4e%z7UhKq8b1hj>@Bv}-A}7p;M^&G>m1M1v&SUx7CFyt(N4tN9M^ z;y_$93x{zKm}U?Rb2T22yb=Tl<8V;V=w(>a8w3>81)u{pU7Fl2hzFlHUHc`1a%#}B z+xQh908TOr36DH->U2jw*+lQTs)4BZ#^2QWXfuD3MYfQzkp{_hpiQiM5ax*`kV?E1 zQwK>UE4T7yh;bmR2GFg1pjRyc8;VlTx45KeSJSfKbnm_V2cxrWnuvU^gJGPFEenwI z5oMPVqrQ>fBA;rCG3lbN%Hv7#;d@+IZr8il-M?c ze?Tbb*@-MgL8kH&1ENT0l9S|4Jz#^Xf94z`i>H1iDv=_ZsYshjzTh)qS1#+{%N2ZW zJ?ES3$EVxk*f|CZshFu%3L}X%%W6%@`?Qy6 zFrJPx6>Cd}kvoH=)GkeaNI;#@=tV5V1x{QqS(V@OVqPG_({k_sMtlRj~@#^xG z#aQneXIS(NPmC<%r*%&Km+Pz8L;H$z0LCwa>5GE+Zt}PJRld%TS|@DN6;5>|Vw!xl zO#ca?jx)GG-lq<_keE?5AihAaY?P>zbm=*_{M|YxCY)&#>t!Xu-SP={PP#JZZn=`R z9evHVbC0uw^xztHy2Ue~XFK3CMXkP7QC@sSnUJo+mo>0FfxNDSm9R(uhCQtn;62`s^F zNXFG+hNs3E#93W#AJII~r#~jJ9Lw@>6q~iLA3WOn^3J1&46j}&s|6HFCEGXtlqC)_rvmc=@LK0gn61zZyzt)1{) z@9*M#Y6SW$0i{XZvdN_Wl;HKbRW`Uh>WZ-g)WWxu8A8y58B!Qim|7T8n3|cQ7*m*o88lfY z#&|L&PZX4#cyzHiGf-U=M?rpZW=Up#UJ)CRyON=ZV{$#?UPji*woKx3AR$erB6c8k zi#4?@HLs+I1IUIDoRf=~!t+3O7YV=xk)%Olj6ecpNHGhL;9%rp1&jD;GTma2k59=@ ij*kZmAejm_fD@?t7Kcr4eoARhsvXFXVkRKL!U_QA_$(Cw diff --git a/network/config.txt b/network/config.txt index 1ead9da..fb5ccb4 100644 --- a/network/config.txt +++ b/network/config.txt @@ -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