def main(self): """ do main processing of the server """ try: while True: lst = [self.server] + User.get_sockets_from_users_list( self.users) rlist, _, xlist = select(lst, lst, lst) for sock in rlist + xlist: if sock is self.server: self.add_user(*sock.accept()) else: user = User.get_by_socket(sock, self.users) if sock in xlist: data = '' else: try: data = sock.recv(1024) except socket.error: data = '' if data == '': self.remove_user(sock) else: self.read(user, utils.parse_msg(data)) except (KeyboardInterrupt, SystemExit): pass except Exception: traceback.print_exc() finally: print "Server shutdown..." for user in self.users: # type: User self.remove_user(user, reason='shutdown', by='SYSTEM') self.server.close() sys_exit(0)
def main(self): """ main program loop """ term.colorama.init() term.clear() for thread in self.connections: # type: Connection thread.start() try: lst = (self.socket_, ) while True: if self.exit: raise KeyboardInterrupt with self.lock: rlist, _, _ = select(lst, [], [], 0) rlist = [(sock, sock.recv(1024)) for sock in rlist] for _, data in rlist: # type: _socket.socket, basestring if data == '': raise KeyboardInterrupt self.on_data(utils.parse_msg(data)) except (KeyboardInterrupt, SystemExit): for thread in self.connections: # type: Connection thread.kill() term.clear() term.position() self.socket_.close() sys.exit(1)
def process_msg(self, msg, client_address): conn = self.socket exprs = utils.parse_msg(msg) msg_type = exprs[0] game_id = exprs[1] nick_name = exprs[2] # handle write to client if msg_type == 1: # create new game self.game_id = game_id self.user1 = nick_name self.address1 = client_address # wait for opponent wait_opponent_msg = struct.pack('!B', 4) conn.sendto(wait_opponent_msg, self.address1) elif msg_type == 2: # join existing game if game_id == self.game_id: self.user2 = nick_name self.address2 = client_address # wait for game start wait_start_msg = struct.pack('!B', 5) conn.sendto(wait_start_msg, self.address1) conn.sendto(wait_start_msg, self.address2) # after 1 second, game start time.sleep(1) self.game_start = True elif msg_type == 3: dire = exprs[3] # move if nick_name == self.user1: self.snake1_to = dire move_status = self.snake1.move(dire, self.apple, self.snake2) if move_status == -1: self.result = 1 self.winner_nick_name = self.user2 if self.snake1.head() == self.apple: while self.apple in self.snake1.body or self.apple in self.snake2.body: self.apple = self.choose_random_pos() else: move_status = self.snake2.move(dire, self.apple, self.snake1) self.snake2_to = dire if move_status == -1: self.result = 1 self.winner_nick_name = self.user1 if self.snake2.head() == self.apple: while self.apple in self.snake1.body or self.apple in self.snake2.body: self.apple = self.choose_random_pos() print('move_status: ', move_status) self.process_game_status(move_status)
def take_move(self, dire): move_msg = struct.pack('!B', 3) # 1 byte for type move_msg += struct.pack('!B', len(self.game_id)) # 1 byte for game_id length move_msg += struct.pack('!B', len( self.nick_name)) # 1 byte for player nick_name length move_msg += self.game_id.encode( 'utf-8') # many bytes for player game_id move_msg += self.nick_name.encode( 'utf-8') # many bytes for player nick_name if dire == 'UP': direction = 0 elif dire == 'RIGHT': direction = 1 elif dire == 'DOWN': direction = 2 else: direction = 3 move_msg += struct.pack('!B', direction) # 1 byte for direction print('move msg to server: ', move_msg) self.socket.sendto(move_msg, self.server_address) print('read back game status...') game_status_msg, addr = self.socket.recvfrom(1024) print('client receive game_status_msg: ', game_status_msg) exprs = utils.parse_msg(game_status_msg) print('client receive exprs: ', exprs) game_status_msg_type = exprs[0] if game_status_msg_type == 6: # game over print('game over') result = exprs[1] if result == 0: winner = '' else: winner = exprs[2] self.draw_game_over(winner) elif game_status_msg_type == 7: # draw board self.draw_board(exprs)
def ask(self, question, rule=lambda x: True, users=None): """ :type question: str :type users: list[User] """ if users is None: users = [self] users.remove(self) res = '' while res is not None: new_question = question if res.strip(): new_question = '%s (%s)' % (question, res) self.send('ask', question=new_question) data = utils.parse_msg(self.client.recv(1024))['answer'] res = rule(data) users.append(self) return data
def on_data(self, _data): """ process data sent by the server .. to be overridden :type _data: str :rtype: bool :return: to rewrite input or not :raise: Exception to signal EXIT """ # split to messages _data = (utils.parse_msg(d) for d in _data.split('\n') if d) # separate control messages from data messages msgs = (d for d in _data if d['type'] == 'msg') # overwrite line stdout.write('\r') stdout.flush() # print messages for msg in msgs: print '{}: {}'.format(msg['user'], msg['msg']) return bool(_data)
def listen_server(self): while True: print('client is listening server..., game start: ', self.game_start) game_status_msg, addr = self.socket.recvfrom(1024) print('client receive game_status_msg: ', game_status_msg) exprs = utils.parse_msg(game_status_msg) game_status_msg_type = exprs[0] action_res_msg_type = exprs[0] if action_res_msg_type == 4: # wait for opponent, draw waiting print('wait for opponent') self.draw_waiting() elif action_res_msg_type == 5: # wait for start, draw starting and set start true print('wait for start') self.game_start = True self.draw_starting() elif game_status_msg_type == 6: # game over print('game over') result = exprs[1] if result == 0: winner = '' else: winner = exprs[2] self.draw_game_over(winner) self.socket.close() break elif game_status_msg_type == 7: self.draw_board(exprs)
async def on_message(message): if message.author == client.user: return if message.content.startswith("/r") or message.content.startswith("/roll"): check_err = utils.parse_msg(message.content) if check_err == -1: await message.channel.send("Ooops...Wrong arguments!") else: vicious, destructive, attr_score, adv, repeat_factor = utils.parse_msg( message.content) results, info = utils.calculate_result(vicious, destructive, attr_score, adv, repeat_factor) msg = "{} rolled: ".format(message.author.display_name) for result in results: msg += "\n\n**Roll {}**".format(results.index(result) + 1) total_base = sum(sum(result[0][0], [])) total_attr = sum(sum(result[1][0], [])) separator = " " table = str.maketrans('[]', '()') base_kept = separator.join(map(str, result[0][0])).translate(table) base_dropped = separator.join(map( str, result[0][1])).translate(table) if base_dropped == "": base_dropped = "-" base_dropped_vs = separator.join(map( str, result[0][2])).translate(table) if base_dropped_vs == "": base_dropped_vs = "-" attr_kept = separator.join(map(str, result[1][0])).translate(table) if attr_kept == "": attr_kept = "-" attr_dropped = separator.join(map( str, result[1][1])).translate(table) if attr_dropped == "": attr_dropped = "-" msg += "\n----------\nTotal: {} \nBase (1d20 -> {}): \t {} \n> \t *Dropped: {}*".format( (total_base + total_attr), total_base, base_kept, base_dropped) if vicious == True: # Only appends Vicious Strike info if the flag returns True msg += "\n> \t _Dropped **(Vicious Strike)**: {}_".format( base_dropped_vs) msg += "\nAttribute ({} -> {}): \t {} \n> \t *Dropped: {}*".format( info, total_attr, attr_kept, attr_dropped) await message.channel.send(msg) elif message.content.startswith("/!r") or message.content.startswith( "/!roll"): args = message.content.split(" ")[1:] result = utils.roll_raw(args[0]) if result != -1: await message.channel.send("{} rolled: {} -> {}".format( message.author.display_name, args[0], result)) elif message.content.startswith("/help") or message.content.startswith( "/h"): file = open("./usage_help_msg", "r") msg = file.read() file.close() await message.channel.send(msg)