DoubleQ 3 years ago
parent 15b3394ae5
commit 17234132a0

@ -43,6 +43,7 @@ port = None
addr = None
connection = None
#网络版更新需要注意多线程的问题?
server_died_message = 'fucking server died and quit'
#尝试写一个函数分配一个新线程供监听
def startNewThread(target):
@ -53,12 +54,16 @@ def listenFromServer():
global networkMsg
try:
while True:
recvMsg = client.recvfrom(1024).decode('utf-8')
recvMsg = client.recv(1024).decode('utf-8')
if len(recvMsg) != 0:
networkMsg = json.loads(recvMsg)
print('receive thread catch: ',networkMsg)
except socket.error as e:
print(e)
return e
except OSError:
networkMsg = server_died_message
return None
def startNetworkServices():
global client,server,port,addr,connection
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']
valid_moves=game_state.getAllMoves()
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
game_over = False
square_selected = () #刚开始没有选择任何一个棋子
click_queue = [] #点击队列,记录第一次点击和第二次点击位置,方便移动棋子
pg.display.update()
startGamePage(mode)
@ -350,32 +359,55 @@ def main(mode):
login_packet = login_packet.encode('utf-8')
lastNetworkMsg = networkMsg
client.send(login_packet)
while networkMsg == None: pass
while running:
#print('current moving color: ',game_state.color())
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中保存当前字典
if 'status' in networkMsg.keys():
if networkMsg['status'] == 1:
print('Waiting for another player to connect')
elif 'src' and 'dst' in networkMsg.keys():
if other_joined == False:
other_joined = True
#Login_handler
if networkMsg['status'] == 1: #Finished Login process
if other_joined == False:
other_joined = True
print('Game start 2 play!')
else:
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()
game_id = networkMsg['game_id']
MySide = networkMsg['side']
other_stage = True if networkMsg['side']==0 else False
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():
#接下来处理游戏中的事件
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()
sys.exit()
elif e.type == pg.MOUSEBUTTONDOWN:
#鼠标点击事件:用于选择棋子,移动棋子
if not game_over:
if not game_over and not other_stage:
mouse_loc = pg.mouse.get_pos()
row = int((mouse_loc[1] - bias_top) / SIZE)
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]
nxt_piece_loc = click_queue[1]
move = backend.Move(cur_piece_loc,nxt_piece_loc,game_state.board)
thisMove = move
if move in valid_moves:
game_state.makeMove(move)
mademove = True
@ -406,14 +439,37 @@ def main(mode):
#? 但是考虑到ui刷新问题故仍尝试在main中写
#ShowGameState(screen,game_state,valid_moves,square_selected)
if mademove:
valid_moves = game_state.getAllMoves()
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)
if game_state.conquer():
showGameOverText(screen,"player "+game_state.win_person+" wins")
game_over = True
clock.tick(10)
clock.tick(5)
pg.display.flip()

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

Loading…
Cancel
Save