def handleConnection( self, connection ): # Just keep polling the connection for messages, when we get one we act with it. global _Sound_Playing done = False while not done: message = "" try: message = RAProtocol.receiveMessage(connection) # Try getting a message from them. logger.write_line("Hidden: Got a message! %s" % message) except: pass # When you don't get anything. if message != "": # Non-blank message, we got data. logger.write_line('Hidden: Got the following message from the server: "%s"' % message) if "_play_" in message and not _Sound_Playing: # Format from engine for a play sound message is: "_play_ soundname" where soundname is the name of a file you wish to play from the sounds directory message = message.split() # Split into _play_ and the sound name sound_name = message[1] _Sound_Playing = True ###To block other plays for now. thread.start_new_thread(play_sound, (sound_name,)) logger.write_line("Output: Playing sound file called %s" % sound_name) elif not "_play_" in message: # This isn't a playsound message, we can print it. print >>sys.stdout, "\n" + message.strip() logger.write_line("Output: %s" % message) time.sleep(1.0) return True
def connect_to_server(self, line): # currently used for login purposes only outSocket = self.outSocket() RAProtocol.sendMessage(line, outSocket) self.log.write_line('login message sent to server awaiting response') message = RAProtocol.receiveMessage(outSocket) #return message from server validating login self.log.write_line('response recieved = %s' % str(message)) outSocket.close() self.log.write_line('login socket closed.') ports = message if ports in ['invalid', 'banned_name', "affiliation_get"]: # login fails self.emit(QtCore.SIGNAL("mainDisplay(QString)"), "That login is invalid. Try Again." ) self.name = "" self.password = "" self.log.write_line('login attempt invalid. Reset Name and Password') else: #logIn accepted process self.log.write_line('Login Valid changing login file to %s' % str(self.name)) self.log = Q2logging.out_file_instance('logs/GuiClient/PlayLogs/%s' % str(self.name)) ports = ports.split() self.iPort = int(ports[1]) self.oPort = int(ports[0]) self.log.write_line('in/out ports saved in = %d, out = %d' % (self.iPort, self.oPort)) # set port and host for In thread... Start thread & start ping timer self.iThread.port = self.iPort self.iThread.host = self.localHost self.log.write_line('inThread atributes changed to inPort & localHost') self.iThread.start() self.pingTimer.start(10000) # Login True for proper input box operation from this point forward. Emit to print to display. self.loggedIn = True self.log.write_line('thread started, Ping timer Started') self.emit(QtCore.SIGNAL("mainDisplay(QString)"), "You are now logged in...." )
def run(self): self.log.write_line('inThread started') self.iSocket = self.inSocket() self.iSocket.listen(4) self.log.write_line('InSocket created, bound and listening port = %d, host = %s' % (self.port, str(self.host))) while 1: # Accept Connection from server conn, addr = self.iSocket.accept() message = RAProtocol.receiveMessage(conn) self.log.write_line('message recieved on inThread = %s' % str(message)) self.emit(QtCore.SIGNAL("messageReceived(QString)"), message)
def connect_to_server(line): """ """ global _Server_Host global _Login_Port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket(sock, certfile = 'cert.pem') ssl_sock.connect((_Server_Host, _Login_Port)) RAProtocol.sendMessage(line, ssl_sock) logger.write_line('Hidden: Making connection with remote server') message = RAProtocol.receiveMessage(ssl_sock) ssl_sock.close() return message
def handleInput(self, conn): """ """ global _Sound_Playing message = RAProtocol.receiveMessage(conn) logger.write_line('Hidden: Got the following message from the server: "%s"'%message) conn.close() if '_play_'in message and not _Sound_Playing: #Format from engine for a play sound message is: "_play_ soundname" where soundname is the name of a file you wish to play from the sounds directory message = message.split() #Split into _play_ and the sound name sound_name = message[1] _Sound_Playing = True ###To block other plays for now. thread.start_new_thread(play_sound, (sound_name,)) logger.write_line('Output: Playing sound file called %s' % sound_name) elif not '_play_' in message: #This isn't a playsound message, we can print it. print >>sys.stdout, "\n" + message.strip() logger.write_line('Output: %s' % message) return True
def run(self): global _Shutdown global _Shutdown_Lock logger.write_line("Beginning input thread for %s" % self.name) _Shutdown_Lock.acquire() done = _Shutdown _Shutdown_Lock.release() while not done: try: input_data = RAProtocol.receiveMessage(self.connection) logger.write_line("Got the following from the client %s: %s" % (self.name, input_data)) except: input_data = "" if input_data != "": # We got something, yay self.handle_input(self.name, input_data) _Shutdown_Lock.acquire() done = _Shutdown _Shutdown_Lock.release() time.sleep(0.05)
def main(): global _CMD_Queue global _Server_Host global _Login_Port global _Local_Host logger.write_line("Beginning client operations") it = InThread() # Start listening on port 8888 for connections it.start() logger.write_line("Beginning in port watching thread.") rank_list = {"Obama": 0, "Kanye": 0, "OReilly": 0, "Gottfried": 0, "Burbiglia": 0} used_ranks = [5, 4, 3, 2, 1] # First get whether the user wishes to log in, or register. while 1: # Control loop for initial stages of user interaction prior to the actual connection being made choice = raw_input("Would you like to register, or login, or quit?\r\n") logger.write_line("Output: Would you like to register, or login, or quit?") logger.write_line("Input: %s" % choice) if choice == "register": # Do registration uname = raw_input("Please enter a username you would like to use:\r\n") logger.write_line("Output: Please enter a username you would like to use:") logger.write_line("Input: %s" % uname) password = raw_input("Please enter a password you would like to use:\r\n") logger.write_line("Output: Please enter a password you would like to use:") if password != "": # We got one. logger.write_line("Input: User entered a password.") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ssl_sock = ssl.wrap_socket(sock, certfile = 'cert.pem') sock.connect((_Server_Host, _Login_Port)) logger.write_line("Hidden: Connection to server made successfully") line = uname + " " + password + " " + "_register_" RAProtocol.sendMessage(line, sock) # Send the command to the server. logger.write_line("Hidden: Sending message to the server: %s" % line) response = RAProtocol.receiveMessage(sock) # Get the response logger.write_line("Hidden: Getting response from the server: %s" % response) if response == "_affiliation_get_": # They want our affiliation. print >>sys.stdout, "This is a new player, which requires you to rank your affiliation with people." logger.write_line( "Output: This is a new player, which requires you to rank your affiliation with people." ) print >>sys.stdout, "Please rank the following people 1 through 5 in order of preference:" logger.write_line("Output: Please rank the following people 1 through 5 in order of preference:") for person in rank_list: print >>sys.stdout, "\t" + person logger.write_line(person) line = "" for person in rank_list: while 1: rank = raw_input("On a scale of 1 to 5, where would you rank %s?\r\n" % person) logger.write_line("Output: On a scale of 1 to 5, where would you rank %s?\r\n" % person) logger.write_line("Input: %s" % rank) rank = int(rank) if rank in used_ranks: # This is okay rank_list[person] = rank used_ranks.remove(rank) break else: print >>sys.stdout, "Sorry, you may only give each person a different ranking" logger.write_line("Output: Sorry, you may only give each person a different ranking") for person in rank_list: line = ( line + " " + person + " " + str(rank_list[person]) ) # Add all the people and their ranking to line RAProtocol.sendMessage(line, sock) # Send our response about the affiliation logger.write_line("Hidden: Sending message to server: %s" % line) resp = RAProtocol.receiveMessage(sock) # Receive the response from the server. logger.write_line("Hidden: Response from server: %s" % resp) if resp == "_get_ip_": # They want the IP we are at so they can make a connection to us, yay. RAProtocol.sendMessage(_Local_Host, sock) # Send them our IP logger.write_line("Hidden: Sending our IP to the server: %s" % _Local_Host) resp = RAProtocol.receiveMessage(sock) # Get the last message back logger.write_line("Hidden: Got response from server: %s" % resp) if resp == "_out_conn_made_": # We completed the connection and login process, horray. logger.write_line( "Hidden: Incoming connection from server completed, ending inbound processing on this socket" ) break else: # There was an error! print >>sys.stdout, "Sorry, trouble connecting to the server. Please try again in a moment." else: # They don't want our IP, failed attempt: print >>sys.stdout, "Sorry, trouble connecting to the server. Please try again?" elif ( response != "_affiliation_get_" ): # We picked register and they don't want our affiliation? We were probably rejected then. print >>sys.stdout, "Registration failed: %s" % response elif choice == "login": # Do the login proceedure. uname = raw_input("Please enter a username you would like to use:\r\n") logger.write_line("Input: Attempting to log in with username <%s>" % uname) password = raw_input("Please enter a password you would like to use:\r\n") logger.write_line("Input: Got password to try. Testing.") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ssl_sock = ssl.wrap_socket(sock, certfile = 'cert.pem') sock.connect((_Server_Host, _Login_Port)) logger.write_line("Hidden: Connected to the server.") line = uname + " " + password + " " + "_login_" RAProtocol.sendMessage(line, sock) # Send the command to the server. logger.write_line("Hidden: Sending message with uname/pass to server.") response = RAProtocol.receiveMessage(sock) # Get the response logger.write_line("Hidden: Got the following reponse from the server: %s" % response) if response == "_invalid_": # They provided a wrong username/password combination. print >>sys.stdout, "Log in failed, incorrect username or password" logger.write_line("Output: Log in failed, incorrect username or password") elif response == "_requires_registration_": # They provided a username/password which is not registered print >>sys.stdout, "Log in failed, that is not a registered account" logger.write_line("Output: Log in failed, that is not a registered account") elif response == "_get_ip_": # They want our IP to connect to us, this is good. logger.write_line("Hidden: Server is requesting our IP.") RAProtocol.sendMessage(_Local_Host, sock) # Send them our IP logger.write_line("Hidden: Sending server the following IP: %s" % _Local_Host) response = RAProtocol.receiveMessage(sock) # Get their response logger.write_line("Hidden: Got the following response from the server: %s" % response) if response == "_out_conn_made_": # We completed the connection and login process. logger.write_line( "Hidden: Incoming connection from the server completed, ending inbound processing on this socket" ) kat = KeepAliveThread() logger.write_line("Hidden: Beginning run of KeepAliveThread") kat.start() rlt = ReadLineThread() logger.write_line("Hidden: Beginning ReadLineThread") rlt.start() ot = OutThread(sock) # Give it the connection to keep sending outgoing data on. logger.write_line("Hidden: Beginning run of OutThread.") ot.start() break else: # Anything else print >>sys.stdout, "Sorry, trouble connecting to the server. Please try again in a moment." logger.write_line("Sorry, trouble connecting to the server. Please try again in a moment.") elif choice == "quit": # They are quitting the program. logger.write_line("Input: %s" % choice) logger.write_line("Hidden: User Qutting.") return True quit_game = False while not quit_game: _Quit_Lock.acquire() quit_game = _Quit _Quit_Lock.release() time.sleep(0.05) return True
def register_player(self, name, password, connection): global _Logged_in global _Player_Loc_Lock global _Player_Locations global _Player_Data_Lock global _Player_Data global _User_Pings_Lock global _User_Pings global _Threads_Lock global _Threads global _Players_Lock global _Players path = "login_file/%s.txt" % name location = (0, 0, 1, 0) player_affil = {} # Initially blank affiliation items = [] prev_coords = (0, 0, 1, 0) fih = 30 vote_history = {} print "Creating user: <%s>" % name logger.write_line("Creating user: <%s>" % name) RAProtocol.sendMessage("_affiliation_get_", connection) # Let them know we need their affiliation temp_affil = RAProtocol.receiveMessage(connection) # Get their affiliation a_string = temp_affil.split() if len(a_string) == 10: # Affiliation data logger.write_line("Received a user affiliation, confirmed.") cur_person = "" for i in range(0, len(a_string)): if i % 2 == 1: # This is an odd numbered cell, and as such is an affinity. player_affil[cur_person] = int(a_string[i]) else: # Even numbered, person cur_person = a_string[i] player_affil[cur_person] = 0 fin = open(path, "w") fin.write(password) # Save the player file fin.close() logger.write_line("Player login file created") logged_in = True _Logged_in.append(name) _Player_Loc_Lock.acquire() _Player_Locations[name] = "lobby" # Log in to the lobby initially _Player_Loc_Lock.release() _Player_Data_Lock.acquire() _Player_Data[name] = [] _Player_Data[name].append(location) # Add the location tuple to the list. _Player_Data_Lock.release() person = engine_classes.Player(name, (0, 0, 1, 0), (0, 0, 1, 0), player_affil) # Make this person loader.save_player(person) logger.write_line("Saving newly created player %s" % name) else: RAProtocol.sendMessage("_reject_", connection) logger.write_line("User login attempt rejected") return False if logged_in: _User_Pings_Lock.acquire() _User_Pings[name] = time.time() logger.write_line("Putting user into _User_Pings") _User_Pings_Lock.release() _Player_Data_Lock.acquire() _Player_Data[name].append(player_affil) # This may be {}, but we check for that later. _Player_Data[name].append(prev_coords) # (0,0,1,0) unless loaded as otherwise. _Player_Data[name].append(items) # [] if not loaded. _Player_Data[name].append(fih) # 30 if not loaded as otherwise. _Player_Data[name].append(vote_history) # {} if not loaded as otherwise. _Player_Data_Lock.release() logger.write_line("Finished adding additional data to _Player_Data[%s]" % name) # *create player state and add to _Player_States (to be added) # add new player I/O queues oqueue = Queue.Queue() _Player_OQueues_Lock.acquire() _Player_OQueues[name] = oqueue _Player_OQueues_Lock.release() line = "\r\n" for world in _World_list: line += "\t" + world + "\r\n" oqueue.put( "Welcome to the RenAdventure lobby!\r\nThe following worlds are available (type: join name_of_world):" + line ) ###TEST logger.write_line("Sending welcome message") line = "The following people are in the lobby: \r\n" _Player_Loc_Lock.acquire() for person in _Player_Locations: if ( _Player_Locations[person] == "lobby" and person != name ): # This person is in the lobby, and isn't the person we're listing people to. line += "\t" + person + "\r\n" _Player_Loc_Lock.release() if line != "The following people are in the lobby: \r\n": # We added players to this line oqueue.put(line) else: # There are no people in the lobby but you oqueue.put("There is no one else in the lobby at present.") # oqueue.put(engine_classes.engine_helper.get_room_text(name, location, engine)) #####NEED FILTER RAProtocol.sendMessage("_get_ip_", connection) # Tell them we need their IP for outgoing messages logger.write_line("Getting IP from client...") ip = RAProtocol.receiveMessage( connection ) # Get their IP from the client and make an outgoing connection with it. logger.write_line("Received the following IP: %s" % ip) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((ip, 8888)) # Connect to client on port 8888 for sending messages logger.write_line("Connection to socket on port 8888 made.") RAProtocol.sendMessage("_out_conn_made_", connection) ot = PlayerOutput(name, sock) ot.start() _Threads_Lock.acquire() _Threads.append(ot) _Threads_Lock.release() except: RAProtocol.sendMessage("_conn_failure_", connection) logger.write_line("Failed to connect.") return True else: RAProtocol.sendMessage("_reject_", connection) logger.write_line("User log in rejected") return False
def verify_player(self, name, password, connection): global _Logged_in global _Banned_names global _Logger global _User_Pings global _Player_Loc_Lock global _Player_Locations global _World_list global _Player_Data global _Player_Data_Lock global _Threads_Lock global _Threads path = "login_file/%s.txt" % name logger.write_line("Verifying player credentials") player_affil = {} # Current player's affiliation data. prev_coords = (0, 0, 1, 0) items = [] fih = 30 vote_history = {} if ( name not in _Logged_in and name not in _Banned_names ): # This person is not already logged in to the game, they may proceed to the next step. logger.write_line("This player is not already logged in, or banned. Proceed") if os.path.exists(path): # This file exists logger.write_line("This player's login file does indeed exist.") fin = open(path) pwd = fin.readline() fin.close() if password == pwd: # Login successful print "User <%s> authenticated" % name logger.write_line("User <%s> authenticated." % name) _Logged_in.append(name) _Player_Loc_Lock.acquire() _Player_Locations[name] = "lobby" # Log in to the lobby initially _Player_Loc_Lock.release() _Player_Data_Lock.acquire() _Player_Data[name] = [] # [0]: location tuple, [1]: affiliation dict _Player_Data_Lock.release() player_path = "players/%s.xml" % name try: person = loader.load_player(player_path) logger.write_line("Loading player file %s successful." % player_path) logged_in = True prev_coords = person.prev_coords items = person.items fih = person.fih vote_history = person.vote_history except: logger.write_line("Error loading player file %s, file does not exist" % player_path) print "Error loading player file %s, file does not exist" % player_path return False player_affil = person.affiliation # Load in the players affiliation location = person.coords _Player_Data_Lock.acquire() _Player_Data[name].append(location) # Add the location tuple to the list. _Player_Data_Lock.release() else: print "User <%s> failed to authenticate." % name logger.write_line("User <%s> failed to authenticate." % name) RAProtocol.sendMessage("_invalid_", connection) return False else: # File does not exist, require them to register RAProtocol.sendMessage( "_requires_registration_", connection ) # Tell them they are required to register and drop them? logger.write_line("User is not registered, ending.") return False if logged_in: # They have been logged in and their player data is known. _User_Pings_Lock.acquire() _User_Pings[name] = time.time() _User_Pings_Lock.release() _Player_Data_Lock.acquire() _Player_Data[name].append(player_affil) # This may be {}, but we check for that later. _Player_Data[name].append(prev_coords) # (0,0,1,0) unless loaded as otherwise. _Player_Data[name].append(items) # [] if not loaded. _Player_Data[name].append(fih) # 30 if not loaded as otherwise. _Player_Data[name].append(vote_history) # {} if not loaded as otherwise. _Player_Data_Lock.release() loader.save_player(person) # Save the file logger.write_line("Saving player file for user <%s>" % name) # *create player state and add to _Player_States (to be added) # add new player I/O queues oqueue = Queue.Queue() line = "\r\n" for world in _World_list: line += "\t" + world + "\r\n" oqueue.put( "Welcome to the RenAdventure lobby!\r\nThe following worlds are available (type: join name_of_world):" + line ) ###TEST _Player_OQueues_Lock.acquire() _Player_OQueues[name] = oqueue _Player_OQueues_Lock.release() line = "The following people are in the lobby: \r\n" _Player_Loc_Lock.acquire() for person in _Player_Locations: if ( _Player_Locations[person] == "lobby" and person != name ): # This person is in the lobby, and isn't the person we're listing people to. line += "\t" + person + "\r\n" _Player_Loc_Lock.release() if line != "The following people are in the lobby: \r\n": # We added players to this line oqueue.put(line) else: # There are no people in the lobby but you oqueue.put("There is no one else in the lobby at present.") # oqueue.put(engine_classes.engine_helper.get_room_text(name, location, engine)) #####NEED FILTER RAProtocol.sendMessage("_get_ip_", connection) # Tell them we need their IP for outgoing messages logger.write_line("Getting IP from client..") ip = RAProtocol.receiveMessage( connection ) # Get their IP from the client and make an outgoing connection with it. logger.write_line("Received the following IP from the client: %s" % ip) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((ip, 8888)) # Connect to client on port 8888 for sending messages logger.write_line("Connected to socket.") RAProtocol.sendMessage("_out_conn_made_", connection) ot = PlayerOutput(name, sock) # Output thread for this player ot.start() _Threads_Lock.acquire() _Threads.append(ot) _Threads_Lock.release() except: RAProtocol.sendMessage("_connection_fail_", connection) logger.write_line("Failed to connect") _Players_Lock.acquire() _Players.append(name) _Players_Lock.release() return True # Player has been logged in, et cetera if they made it this far. elif name not in _Banned_names: # Player name is in _Logged_in, and not in _Banned_names print "Error, attempt to log in to an account already signed on" logger.write_line("Error, attempting to log in to an account already signed on: <%s>" % name) RAProtocol.sendMessage("already_logged_in", connection) return False else: # player_name in _Banned_names print "Attempt to log in with a banned name <%s>, account creation rejected" % name logger.write_line("Attempt to log in with a banned name <%s>, account creation rejected" % name) RAProtocol.sendMessage("banned_name", connection) return False
def run(self): """ Creates a socket on the listen_port, waits for new connections, then handles new connections """ global _Logger global _Logged_in global _Banned_names global _User_Pings global _Player_Loc_Lock global _Player_Locations global _World_list global _Player_Data global _Player_Data_Lock global _Player_Connections global _Player_Connections_Lock global _Threads_Lock global _Threads global _Shutdown global _Shutdown_Lock # Create a socket to listen for new connections sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Login Socket created" logger.write_line("Login Socket created") sock.bind((self.host, self.listen_port)) print "Login Socket bound" logger.write_line("Login Socket bound") # Listen for new connections sock.listen(1000) print "Login socket listening" logger.write_line("Login socket listening") # wait to accept a connection _Shutdown_Lock.acquire() done = _Shutdown _Shutdown_Lock.release() while not done: conn, addr = sock.accept() print "Connected with " + addr[0] + ":" + str(addr[1]) logger.write_line("Connected with " + str(addr[0]) + ":" + str(addr[1])) # connstream = ssl.wrap_socket(conn, certfile = 'cert.pem', server_side = True) start_dialogue = RAProtocol.receiveMessage(conn) logger.write_line("Got start_dialogue: %s" % start_dialogue) ###DEBUG a_string = start_dialogue.split() # Split on space player_name = a_string[0] player_pass = a_string[1] flag = a_string[2] # Flag for either "_login_" to attempt to login, or "_register_" to attempt to register? if flag == "_login_": # Try and log them in print "Player wishes to log in as <%s>, verifying.." % player_name logger.write_line("Player wishes to log in as <%s>, verifying..." % player_name) proceed = self.verify_player(player_name, player_pass, conn) if proceed: # Valid player, with registration data it = PlayerInput(player_name, conn) # Input reading thread for player_name using conn. it.start() # Begin execution of in thread. _Threads_Lock.acquire() _Threads.append(it) _Threads_Lock.release() elif flag == "_register_": # Attempt to register them based on the data print "Player wishes to register as <%s>, proceeding.." % player_name logger.write_line("Player wishes to register as <%s>, proceeding..." % player_name) proceed = self.register_player(player_name, player_pass, conn) if proceed: # Valid player, we have their registration now. it = PlayerInput(player_name, conn) # Input reading thread for player_name using conn. it.start() # Begin execution of in thread. _Threads_Lock.acquire() _Threads.append(it) _Threads_Lock.release() _Shutdown_Lock.acquire() done = _Shutdown _Shutdown_Lock.release() time.sleep(0.05)
def handleInput(self, conn): """ Receive input, parse the message*, and place it in the correct queue* * message parsing and separate queuing will be implemented if the chat input and game input share a port """ global _Logged_in global _InThreads global _OutThreads global _Logger global _User_Pings global game_engine global _Player_Loc_Lock global _Player_Locations global _Lobby_Queue message = RAProtocol.receiveMessage(conn) if message != '_ping_': # add it to the queue if message != 'quit': _Player_Loc_Lock.acquire() ###IP location = _Player_Locations.get(self.name, 'lobby') #Get whether player is in "Lobby" or a world? ###IP _Player_Loc_Lock.release() ###IP if location == 'lobby': #Player is in the lobby ###IP try: _Lobby_Queue.put((self.name, message)) logger.write_line("Putting in the lobby message queue: <%s>; '%s'" % (self.name, message)) except: pass elif location == 'sandbox': #Player is in the game instance known as sandbox ###IP try: _CMD_Queue.put((self.name, message)) logger.write_line('Putting in the command queue: <%s>; "%s"'%(self.name, message)) except: pass conn.close() elif message == 'quit':#User is quitting, we can end this thread _InThreads[self.name] = False _OutThreads[self.name] = False _Logged_in.remove(self.name) logger.write_line('Removing <%s> from _Logged_in' % self.name) game_engine._Characters_Lock.acquire() if self.name in game_engine._Characters: #This player has been added to the game game_engine.remove_player(self.name) #Remove player existence from gamestate. game_engine._Characters_Lock.release() _Player_Loc_Lock.acquire() if _Player_Locations[self.name] == 'lobby': #This person is in the lobby, tell everyone they quit. _Player_OQueues_Lock.acquire() for person in _Player_OQueues: if person != self.name: #This is not the person quitting, tell them who quit. _Player_OQueues[person].put("%s quit."%self.name) _Player_OQueues_Lock.release() _Player_Loc_Lock.release() _User_Pings_Lock.acquire() del _User_Pings[self.name] #This player quit, remove them from pings. _User_Pings_Lock.release() elif message == '_ping_': #Keepalive ping _User_Pings_Lock.acquire() _User_Pings[self.name] = time.time() _User_Pings_Lock.release() logger.write_line("Got a ping from <%s>"%self.name)
def addPlayer(self, conn, addr): """ Add a new player to the game """ global _Logged_in global _Banned_names global _Logger global _User_Pings global _Player_Loc_Lock global _Player_Locations global _World_list global _Player_Data global _Player_Data_Lock # receive message logged_in = False input_data = RAProtocol.receiveMessage(conn) if isinstance(input_data, RAProtocol.command): a_string = str(input_data.body) else: a_string = input_data a_string = a_string.split() #Split on space player_name = a_string[0] player_pass = a_string[1] player_affil = {} #Current player's affiliation data. prev_coords = (0,0,1,0) items = [] fih = 30 vote_history = {} path = 'login_file/%s.txt' % player_name if player_name not in _Logged_in and player_name not in _Banned_names: #This person is not already logged in to the game if os.path.exists(path): #This file exists fin = open(path) pwd = fin.readline() fin.close() if player_pass == pwd: #Login successful print 'User <%s> logged in' % player_name logger.write_line('User <%s> logged in.'%player_name) logged_in = True _Logged_in.append(player_name) _Player_Loc_Lock.acquire() _Player_Locations[player_name] = "lobby" #Log in to the lobby initially _Player_Loc_Lock.release() _Player_Data_Lock.acquire() _Player_Data[player_name] = [] #[0]: location tuple, [1]: affiliation dict _Player_Data_Lock.release() player_path = 'players/%s.xml'%player_name try: person = loader.load_player(player_path) prev_coords = person.prev_coords items = person.items fih = person.fih vote_history = person.vote_history except: logger.write_line("Error loading player file %s, file does not exist" % player_path) print "Error loading player file %s, file does not exist" % player_path player_affil = person.affiliation #Load in the players affiliation location = person.coords _Player_Data_Lock.acquire() _Player_Data[player_name].append(location) #Add the location tuple to the list. _Player_Data_Lock.release() else: print 'User <%s> failed to authenticate.' % player_name logger.write_line('User <%s> failed to authenticate.'%player_name) RAProtocol.sendMessage('invalid', conn) else: #File does not exist if len(a_string) == 2: #We just got name and password, not affiliation RAProtocol.sendMessage('affiliation_get', conn) print 'Getting user affiliation' logger.write_line('Required user affiliation from <%s>'%player_name) elif len(a_string) == 12: #We got the affiliation data this time. print 'Creating user: <%s>'% player_name logger.write_line('Creating user: <%s>'%player_name) cur_person = '' for i in range(2, len(a_string)): if i % 2 == 1: #This is an odd numbered cell, and as such is an affinity. player_affil[cur_person] = int(a_string[i]) else: #Even numbered, person cur_person = a_string[i] player_affil[cur_person] = 0 fin = open(path, 'w') fin.write(player_pass) fin.close() location = (0,0,1,0) logged_in = True _Logged_in.append(player_name) _Player_Loc_Lock.acquire() _Player_Locations[player_name] = "lobby" #Log in to the lobby initially _Player_Loc_Lock.release() _Player_Data_Lock.acquire() _Player_Data[player_name] = [] _Player_Data[player_name].append(location) #Add the location tuple to the list. _Player_Data_Lock.release() person = engine_classes.Player(player_name, (0,0,1,0), (0,0,1,0), player_affil) #Make this person if logged_in: _User_Pings_Lock.acquire() _User_Pings[player_name] = time.time() _User_Pings_Lock.release() _Player_Data_Lock.acquire() _Player_Data[player_name].append(player_affil) #This may be {}, but we check for that later. _Player_Data[player_name].append(prev_coords) #(0,0,1,0) unless loaded as otherwise. _Player_Data[player_name].append(items) #[] if not loaded. _Player_Data[player_name].append(fih) #30 if not loaded as otherwise. _Player_Data[player_name].append(vote_history) #{} if not loaded as otherwise. _Player_Data_Lock.release() loader.save_player(person) #Save the file! logger.write_line("Creating player file for user <%s>" % player_name) # *create player state and add to _Player_States (to be added) # add new player I/O queues oqueue = Queue.Queue() line = "\r\n" for world in _World_list: eng = _World_list[world] if eng._IsRunning: line += "\t"+world+"\r\n" oqueue.put("Welcome to the RenAdventure lobby!\r\nThe following worlds are available (type: join name_of_world):"+line) ###TEST line = "The following people are in the lobby: \r\n" _Player_Loc_Lock.acquire() for person in _Player_Locations: if _Player_Locations[person] == 'lobby' and person != player_name: #This person is in the lobby, and isn't the person we're listing people to. line+= "\t"+person+'\r\n' _Player_Loc_Lock.release() if line != "The following people are in the lobby: \r\n": #We added players to this line oqueue.put(line) else: #There are no people in the lobby but you oqueue.put("There is no one else in the lobby at present.") #oqueue.put(engine_classes.engine_helper.get_room_text(player_name, location, engine)) #####NEED FILTER _Player_OQueues_Lock.acquire() _Player_OQueues[player_name] = oqueue _Player_Loc_Lock.acquire() for person in _Player_Locations: if _Player_Locations[person] == 'lobby' and person != player_name: #This person is in the lobby and is not who just joined. Tell everyone else. _Player_OQueues[person].put("%s has joined the lobby" % player_name) _Player_Loc_Lock.release() _Player_OQueues_Lock.release() # Get I/O port self.spawn_port_lock.acquire() iport = self.spawn_port oport = self.spawn_port + 1 self.spawn_port += 2 self.spawn_port_lock.release() # spin off new PlayerI/O threads ithread = PlayerInput(iport, player_name) othread = PlayerOutput(oqueue, addr, oport, player_name) _Threads_Lock.acquire() _Threads.append(ithread) _Threads.append(othread) _Threads_Lock.release() _InThreads[player_name] = True _OutThreads[player_name] = True ithread.start() othread.start() # send new I/O ports to communicate on ports = str(iport) + " " + str(oport) message = str(ports) RAProtocol.sendMessage(message, conn) # add player to _Players _Players_Lock.acquire() _Players.append(player_name) _Players_Lock.release() conn.close() print player_name + " added to the game." logger.write_line('<'+player_name+'>'+" added to the game.") elif player_name not in _Banned_names: #Player name is in _Logged_in, and not in _Banned_names print 'Error, attempt to log in to an account already signed on' logger.write_line('Error, attempting to log in to an account already signed on: <%s>'%player_name) RAProtocol.sendMessage('already_logged_in', conn) else: #player_name in _Banned_names print 'Attempt to log in with a banned name <%s>, account creation rejected' % player_name logger.write_line('Attempt to log in with a banned name <%s>, account creation rejected'%player_name) RAProtocol.sendMessage('banned_name',conn)