def send_network(self, cmd): self.cmds = ['up', 'down', 'left', 'right'] poll() if cmd in self.cmds: msg = cmd self.do_send({'input' : msg})
def fetch_game_state(self): args = {'name': game.myname} # TODO: bad: out-of-band info # need a hypermedia form instead self.enqueue_request('GET', '/game/1', args, self._callback_game) while len( self._request_queue) > 0 or self._pending_rsrc_req is not None: poll(timeout=0.1)
def poll(self): poll() p = self.m.pellets[0] # always target the first pellet b = self.m.mybox if p[0] > b[0]: cmd = 'right' elif p[0] < b[0]: # p[2] to avoid stuttering left-right movement cmd = 'left' elif p[1] > b[1]: cmd = 'down' else: cmd = 'up' self.m.do_cmd(cmd)
def poll(self): poll() if len(self.m.players) > 0: p = self.m.pellets[0] # always target the first pellet b = self.m.mybox if p[0] > b[0]: cmd = 'right' elif p[0] + p[2] < b[0]: # p[2] to avoid stuttering left-right movement cmd = 'left' elif p[1] > b[1]: cmd = 'down' else: cmd = 'up' msg = {'input': cmd} self.m.do_send(msg)
def run(): #while 1: # enqueue the player events received by the client handlers poll() '''checks what kind of event happened, then filters it so that it can send the correct event out to the clients. within the messages, the first part is the type of message(player joined, player quit player pushed a key, etc) the second part is the name of the player that did that event ''' ''' for event, handler in event_queue: if event == 'quit': msg = {'msg_type':'quit', 'their_name': players[handler].name(), } del players[handler] broadcast(msg) elif event == 'join': player_name = generate_name() players[handler] = Player(player_name) msg = {'msg_type': 'join', 'their_name': players[handler].name(), 'players_list': players } broadcast(msg) elif event == 'input': msg = {'msg_type': 'player_movement', 'their_name': players[handler].name(), 'input': event } broadcast(msg) elif event == 'shot': msg = {'msg_type': 'player_shot', 'their_name': players[handler].name() } broadcast(msg) ''' event_queue = [] sleep(1. / 20) # seconds
def run(): #while 1: #msg = "" #message #if msg == 'quit' or msg == 'exit': # client.do_close() #elif msg: # ignore empty strings #client.do_send({'myname': myname, 'input': msg}) poll() # push and pull network messages #for m in event_queue: #process_input("")#m) event_queue = [] sleep(1. / 20) # seconds
def poll(self): clock = Clock() poll() p = self.m.pellets[0] # always target the first pellet b = self.m.mybox if p[0] > b[0]: cmd = 'right' elif p[0] + p[2] - 1< b[0]: # p[2] to avoid stuttering left-right movement cmd = 'left' elif p[1] > b[1]: cmd = 'down' else: cmd = 'up' msg = {'input': cmd} self.client.do_send(msg) # removes jittery movement clock.tick(30)
def poll(self): poll() if len(self.m.players) != 0: p = self.m.pellets[0] # always target the first pellet b = self.m.players[self.m.players.keys()[0]] if p[0] > b[0]: cmd = 'right' # print p elif p[0] + p[2] < b[0]: cmd = 'left' elif p[1] > b[1]: cmd = 'down' # print p elif p[1] == b[1]: cmd = 'left' elif p[0] == b[0]: cmd = 'right' else: cmd = 'up' msg = {'input': cmd} self.m.do_send(msg)
def periodic_poll(): while 1: if not len(chatting) and len(connected_users): next_user = connected_users.values()[0] chatting[next_user.handler] = next_user print "user in room" elif len(chatting) == 1 and chatting.keys()[0] in connected_users and len(connected_agents): next_agent = connected_agents.values()[0] for person in chatting: person.do_send({'join': next_agent.name}) next_agent.handler.do_send({'speak': chatting.values()[0].name.upper(), 'txt': chatting.values()[0].topic.upper()}) chatting[next_agent.handler] = next_agent print "agent joins user" elif len(chatting) == 1 and chatting.keys()[0] in connected_agents and len(connected_users): next_user = connected_users.values()[0] for person in chatting: person.do_send({'join': next_user.name}) chatting.keys()[0].do_send({'speak': next_user.name.upper(), 'txt': next_user.topic.upper()}) chatting[next_user.handler] = next_user print "user joins agent" poll(timeout=0.05) # in seconds
def periodic_poll(): while 1: poll(timeout=0.05) # seconds
handlers[self] = msg['join'] userName = username + " Joined" for h in handlers: h.do_send(userName) for h in handlers: h.do_send('Users: ' + handlers[self]) elif 'speak' in msg: for h in handlers : print h if h != msg['speak']: h.do_send(msg['speak'] + ': ' + msg['txt']) elif 'close' in msg: self.on_close(self) print msg class Serv(Listener): handlerClass = MyHandler port = 8888 server = Serv(port) while 1: poll() sleep(0.05) # seconds
def update(self): poll(0.01)
def sendGameStateToClients(gameState): for x in handlerList: handlerList[x].do_send(gameState) port = 8888 server = Listener(port, MyHandler) while True: windowSurfaceObj.fill(blackColor) pygame.draw.lines(windowSurfaceObj, greyColor, False, groundPoints) poll(timeout=0.05) for x in particleList: pygame.draw.rect(windowSurfaceObj, greyColor, pygame.Rect(x.getPosX(), x.getPosY(), 2, 2)) for x in landerList: landerList[x].update() for x in particleList: x.update() if x.queuedForRemoval(): particleList.remove(x) landersToBeDestroyed = set() for x in landerList: for y in landerList: if landerList[x] != landerList[y]:
from network import Listener, Handler, poll done = False class MyHandler(Handler): def on_open(self): print 'srv on open' def on_close(self): print 'srv on close' def on_msg(self, data): print 'srv received %s' % str(data) msg = {12: 3, 'hello': (1, 2)} self.do_send(msg) print 'srv sent %s' % str(msg) self.close_when_done() global done done = True port = 8888 server = Listener(port, MyHandler) while not done: poll(timeout=.1) server.stop() # cleanup
def poll(self): poll(0.05) self.do_send({'input':self.move()})
client = Client('localhost', 8888) pygame_init() screen = set_mode((400, 300)) clock = Clock() font = Font(None, 15) # default pygame Font, height in pixels borders = [Rect(0, 0, 2, 300), Rect(0, 0, 400, 2), Rect(398, 0, 2, 300), Rect(0, 298, 400, 2)] dx, dy = 0, 1 # start direction: down delay = 0 # start moving right away while True: clock.tick(50) # frames per second poll() # push and pull network messages for event in pygame_event.get(): # inputs if event.type == QUIT: exit() if event.type == KEYDOWN: key = event.key if key == K_ESCAPE: exit() elif key == K_UP: dx, dy = 0, -1 elif key == K_DOWN: dx, dy = 0, 1 elif key == K_LEFT: dx, dy = -1, 0 elif key == K_RIGHT:
def serverLoop(self): while 1: poll(timeout=0.05) # in seconds
""" Directory: Give the list of connected peers when asked for it. Keep an up-to-date directory by receiving periodic heartbeats from the peers. """ from network import Listener, Handler, poll peers = set() class MyHandler(Handler): def on_close(self): peers.remove(self) def on_msg(self, data): mtype = data['mtype'] if mtype == 'join_dir': self.ip_port = data['ip_port'] self.do_send({'mtype': 'welcome', 'others_ip_port': [p.ip_port for p in peers]}) peers.add(self) Listener(8888, MyHandler) while 1: poll(timeout=.1) # seconds
def beginGame(): host, port = '192.168.0.3', 8888 client = Client(host, port) has_lander = False game_over = False game_over_tick = 0 while game_over_tick < 120: if game_over == True: game_over_tick += 1 if should_exit == True: ##print('**** Disconnected from server ****') ##sys.exit() pass poll() windowSurfaceObj.fill(blackColor) pygame.draw.lines(windowSurfaceObj, greyColor, False, groundPoints) for x in particleList: pygame.draw.rect(windowSurfaceObj, greyColor, pygame.Rect(x[0], x[1], 2, 2)) for x in landerList: if x[7] != 'DESTROYED': windowSurfaceObj.blit( pygame.transform.rotate(landerSurfaceObj, x[0]), (x[1], x[2])) for x in landerList: try: if x[4] == client.getPlayerID(): has_lander = True myLander = x except: pass if has_lander: if myLander[5] != '': game_over = True gameWinLoseText = gameFont.render(myLander[5], True, greyColor) if has_lander: landerPlayerIdentifierText = gameFont.render( 'You', True, greyColor) windowSurfaceObj.blit(landerPlayerIdentifierText, (myLander[1], myLander[2] - 20)) landerFuelText = gameFont.render( 'Lander Y Velocity: ' + str(myLander[6]), True, greyColor) windowSurfaceObj.blit(landerFuelText, (400, 30)) if game_over: windowSurfaceObj.blit(gameWinLoseText, (30, 30)) if has_lander: landerFuelText = gameFont.render( 'Lander Fuel: ' + str(myLander[3]), True, greyColor) windowSurfaceObj.blit(landerFuelText, (400, 50)) userCommand = checkForKeyPress() sendCommandToServer(client, userCommand) pygame.display.update() fpsClock.tick(30) client.do_close()
# connect to the peers others_ip_port = data['others_ip_port'] connect_to_peers(others_ip_port) # create pellets if I'm the only peer, fetch them otherwise if others_ip_port: # other peers have pellets data fetch_pellets() else: create_pellets() ##################################################################### # Establish connection with the directory server. dir_client = DirectoryClient(DIRECTORY_HOST, 8888) # async connect while not dir_client.connected: poll(timeout=.1) # seconds print 'Connected to the directory server.' # Send the IP and port I will be listening to. # Receive in response the list of (IP, port) of peers in the network. dir_client.do_send({'mtype': 'join_dir', 'ip_port': my_ip_port}) while not dir_client.directory_received: poll(timeout=.1) # seconds print 'Retrieved a directory of %d peers.' % len(peers) # Listen to incoming P2P connections from future peers. p2p_listener = Listener(my_port, Peer) pygame.init()
def poll_messages(self): poll() sleep(.02)
def poll_messages(self): poll() sleep(.01)
def periodic_poll(): while 1: poll() sleep(0.05) # seconds
from network import Handler, poll done = False class Conn(Handler): def on_open(self): print 'cli on open' msg = [1, 2, 3] self.do_send(msg) print 'cli sent %s' % str(msg) def on_close(self): print 'cli on close' def on_msg(self, data): print 'cli received %s' % str(data) self.close_when_done() global done done = True host, port = 'localhost', 8888 client = Conn(host, port) while not done: poll(timeout=.1) client.do_close() # cleanup
def render(handler): # render game state into a surface. This rendering varies for each player. screen = pygame.Surface((WIDTH, HEIGHT)) screen.fill((0, 0, 64)) # dark blue [pygame.draw.rect(screen, (0, 191, 255), b) for b in borders] # deep sky blue [pygame.draw.rect(screen, (255, 192, 203), p) for p in pellets] # shrimp [pygame.draw.rect(screen, (255, 0, 0), p.box) for h, p in players.items() if h != handler] pygame.draw.rect(screen, (0, 191, 255), players[handler].box) return screen while 1: loop_start = time.time() # enqueue the player events received by the client handlers apply_client_events() update_avatars() # render and send screenshot for h in players.keys(): surface = render(h) msg = pygame.image.tostring(surface, 'RGB') h.do_send(msg) # poll until the tick is over while time.time() - loop_start < TICK_DURATION: poll(TICK_DURATION - (time.time() - loop_start))
create_pellets() def connect_to_peers(self, ip_ports): for ip_port in ip_ports: ip, port = str(ip_port).split(':') peer = Peer(ip, int(port)) peer.ip_port = ip_port peer.do_send({'mtype': 'join', 'ip_port': MY_IP_PORT}) # Send the IP and port I will be listening to. # Receive in response the list of (IP, port) of peers in the network. dir_client = DirectoryClient(DIRECTORY_HOST, 8888) # async connect dir_client.do_send({'mtype': 'join_dir', 'ip_port': MY_IP_PORT}) while not dir_client.directory_received: poll(timeout=.1) # seconds print 'Retrieved a directory of %d peers.' % len(peers) # Listen to incoming P2P connections from future peers. p2p_listener = Listener(MY_PORT, Peer) ################### loop ################ TICK_DURATION = 0.02 # seconds while 1: loop_start = time.time() process_inputs() update_me() broadcast({'mtype': 'position', 'box': mybox}) draw_everything()
self.do_send({'news': 'connected'}) def on_close(self): del handlers[self] plyrs['n'] -= 1 print("a client has disconnected") def on_msg(self, msg): if 'txt' in msg: if msg['txt'] == 'rdy': self.do_send({'num_rdy': plyrs['n']}) elif msg['txt'] == 'lesgo': if self not in lesgo: lesgo[self] = None if self in lesgo: pass if len(lesgo) == 2: broadcast({'news': 'START'}) elif 'crt' in msg: all_scores[self] = msg['crt'] evryscr = [] broadcast({'top_score': str(find_top_score())}) for player in all_scores: evryscr.append(all_scores[player]) broadcast({'evryscr': evryscr}) Listener(8888, MyHandler) while 1: poll(0.05)
def loop(self): port = 8888 s = Listener(port, MyHandler) while 1: poll(timeout=0.05) # in seconds
if '#' in txt or '@' in txt: word_list = txt.split(" ") send_list = [] for word in word_list: if '#' in word: pub = word.replace("#", "") temp = subs.get(pub) if temp != None: for h in temp: if h not in send_list: send_list.append(h) #Private Publish if '@' in word: privpub = word.replace("@", "") if names.has_key(privpub): privhandler = names[privpub] if privhandler not in send_list: send_list.append(privhandler) if send_list != None: for h in send_list: h.do_send({'speak': name, 'txt' : txt}) #No topic in msg if "#" not in txt and "+" not in txt and "-" not in txt and "@" not in txt and txt != "": broadcast({'speak': name, 'txt': txt}) Listener(8888, MyHandler) while 1: poll(0.05)
def beginGame(): host, port = '169.234.87.121', 8888 client = Client(host, port) has_lander = False game_over = False game_over_tick = 0 while game_over_tick < 120: if game_over == True: game_over_tick += 1 if should_exit == True: ##print('**** Disconnected from server ****') ##sys.exit() pass poll() windowSurfaceObj.fill(blackColor) pygame.draw.lines(windowSurfaceObj, greyColor, False, groundPoints) for x in particleList: pygame.draw.rect(windowSurfaceObj, greyColor, pygame.Rect(x[0], x[1], 2, 2)) for x in landerList: if x[7] != 'DESTROYED': windowSurfaceObj.blit(pygame.transform.rotate(landerSurfaceObj, x[0]), (x[1], x[2])) for x in landerList: try: if x[4] == client.getPlayerID(): has_lander = True myLander = x except: pass if has_lander: if myLander[5] != '': game_over = True gameWinLoseText = gameFont.render(myLander[5], True, greyColor) if has_lander: landerPlayerIdentifierText = gameFont.render('You', True, greyColor) windowSurfaceObj.blit(landerPlayerIdentifierText, (myLander[1], myLander[2] - 20)) landerFuelText = gameFont.render('Lander Y Velocity: ' + str(myLander[6]), True, greyColor) windowSurfaceObj.blit(landerFuelText, (400, 30)) if game_over: windowSurfaceObj.blit(gameWinLoseText, (30, 30)) if has_lander: landerFuelText = gameFont.render('Lander Fuel: ' + str(myLander[3]), True, greyColor) windowSurfaceObj.blit(landerFuelText, (400, 50)) userCommand = checkForKeyPress() sendCommandToServer(client, userCommand) pygame.display.update() fpsClock.tick(30) client.do_close()
# Leaving the room if msg['txt'] == "quit": self.do_close() # tell the others he left message = {'left':msg['speak'], 'users' : self._get_all_users()} else: message = msg # send it back if message != "": self._send_to_all_users(message) #print msg def _send_to_all_users(self,msg): for h in handlers: h.do_send(msg) def _get_all_users(self): users = "" for h in handlers: users = handlers[h] if users == "" else users +","+handlers[h] return users port = 8888 server = Listener(port, MyHandler) while 1: poll(timeout=0.05) # in seconds
'size': [w, h] }) elif msgtype == 'eat_player': # grow the big by the size of the small small = players[data['target']] players[self.myname][2] += small[2] players[self.myname][3] += small[3] broadcast({ 'msg_type': 'grow', 'name': self.myname, 'size': [players[self.myname][2], players[self.myname][3]] }) elif msgtype == 'die': # back to normal size and place me randomly players[self.myname] = [randint(0, 280), randint(0, 280), 10, 10] broadcast({ 'msg_type': 'die', 'name': self.myname, 'state': players[self.myname] }) server = Listener(8888, MyHandler) # loop while 1: poll() sleep(.05) # seconds
def sendGameStateToClients(gameState): for x in handlerList: handlerList[x].do_send(gameState) port = 8888 server = Listener(port, MyHandler) while True: windowSurfaceObj.fill(blackColor) pygame.draw.lines(windowSurfaceObj, greyColor, False, groundPoints) poll(timeout=0.05) for x in particleList: pygame.draw.rect(windowSurfaceObj, greyColor, pygame.Rect(x.getPosX(), x.getPosY(), 2, 2)) for x in landerList: landerList[x].update() for x in particleList: x.update()
def periodic_poll(self): while 1: poll() sleep(0.05) # seconds
def on_close(self): for name, h in handlers.items(): if h == self: del handlers[name] user = waiting.popleft() handlers[user[0]] = user[1] user[1].do_send(prompt) def on_msg(self, msg): if 'join' in msg: if len(handlers) >= 2: waiting.append((msg['join'], self)) self.do_send("Please wait for next available agent") else: handlers[msg['join']] = self self.do_send(prompt) else: if (msg['speak'], self) in waiting: self.do_send("Please wait for next available agent") else: for name in handlers.keys(): if name != msg['speak']: handlers[name].do_send(msg['speak'] + ": " + msg['txt']) port = 8888 server = Listener(port, MyHandler) while 1: poll(timeout=0.05) # in seconds
def periodic_poll(): while 1: poll() sleep(0.05)
print "SERVER ON_ACCEPT" print msg print self class MyListener(Listener): def on_accept(self, h): print "MYLISTENER CLASS ON_ACCEPT" print h print self def parseUser(msg): #print "MSG: " + msg if msg.find('join') != -1: strArr = msg.split("'") return strArr[3] else: return "%$$--#" #------MODEL------ handlers = {} # map client handler to user name port = 7577 server = MyListener(port, MyHandler) #------CONTROLLER------ try: while 1: poll(timeout=0.1) except KeyboardInterrupt: print "CLOSING" handlers["Admin"].do_send("ADMIN IS CLOSING") currentCustomer.do_send("ADMIN IS CLOSING")
def on_msg(self, msg): surface = pygame.image.fromstring(msg, (WIDTH, HEIGHT), 'RGB') screen.blit(surface, (0, 0, WIDTH, HEIGHT)) client = Client('localhost', 8888) # connect asynchronously valid_inputs = {K_UP: 'up', K_DOWN: 'down', K_LEFT: 'left', K_RIGHT: 'right'} while 1: loop_start = time.time() # send valid inputs to the server for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: key = event.key if key == K_ESCAPE: exit() elif key in valid_inputs: msg = {'input': valid_inputs[key]} client.do_send(msg) # poll until tick is over while time.time() - loop_start < TICK_DURATION: poll(TICK_DURATION - (time.time() - loop_start)) pygame.display.update()
request = (method, resource, req_args, callback) self._request_queue.append(request) self._send_next_request() def fetch_game_state(self): args = {'name': game.myname} # TODO: bad: out-of-band info # need a hypermedia form instead self.enqueue_request('GET', '/game/1', args, self._callback_game) while len( self._request_queue) > 0 or self._pending_rsrc_req is not None: poll(timeout=0.1) client = Client('localhost', 8888) # connect asynchronously while not client.connected: # poll until connected poll(timeout=0.1) ############## inputs ############ # TODO: this mapping was obtained out of band valid_inputs = {K_UP: 'up', K_DOWN: 'down', K_LEFT: 'left', K_RIGHT: 'right'} def process_inputs(): # send valid inputs to the server for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: key = event.key if key == K_ESCAPE: exit()