Beispiel #1
0
    def __init__(self):
        ShowBase.__init__(self)

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.player = Player()
        self.opponents = dict()
        self.logStat = -1

        host = "localhost"
        port = 9252
        self.connection = self.cManager.openTCPClientConnection(
            host, port, 10000)

        self.received = 1

        self.playersText = []

        if self.connection:
            self.cReader.addConnection(self.connection)
            taskMgr.add(self.updateRoutine, 'updateRoutine')
            taskMgr.add(self.login, 'login')
            #taskMgr.doMethodLater(3, self.updateRoutine, 'updateRoutine')
            taskMgr.doMethodLater(.1, self.heartbeat, 'heartbeat')

        self.accept("q", self.listPlayers)
        self.accept("q-up", self.delistPlayers)
        self.accept("escape", self.disconnect)
        self.accept("arrow_up", self.move)
Beispiel #2
0
 def connect(self) -> None:
     # Handle connections and terminations
     self.manager = QueuedConnectionManager()
     # Wait for clients connection requests
     self.listener = QueuedConnectionListener(self.manager, 0)
     # Buffers incoming data from active connection
     self.reader = QueuedConnectionReader(self.manager, 0)
     # Transmit PyDatagrams to active connection
     self.writer = ConnectionWriter(self.manager, 0)
     # Open TCP Rendezvous to accept client connections with a limit
     self.socket = self.manager.openTCPServerRendezvous(
         self.port, self.backlog)
     self.listener.addConnection(self.socket)
     print("Server listening on port %s...." % str(self.port))
     # Listen for mew incoming connections
     taskMgr.add(self.handle_incoming_connections,
                 "Poll the connection listener", -39)
     # Listen for new datagrams
     taskMgr.add(self.handle_connection_data,
                 "Poll the connection reader", -40)
     # Listen for dropped connections
     taskMgr.add(self.handle_dropped_connections,
                 "Poll the dropped connection listener", -41)
     # See if game can be started
     taskMgr.add(self.start_game, "Start Game", -42)
 def _initListener (self):
     """
         Initializes this NetworkHost's connection listener.
     """
     self._connListener = QueuedConnectionListener(self._connManager, 0)
     self._tcpSocket = connManager.openTCPServerRendezvous(self._portAddress,
                                                           self._backlog)
     self._connListener.addConnection(self._tcpSocket)
Beispiel #4
0
    def setupTCP(self):
        self.tcpManager = QueuedConnectionManager()
        self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
        self.tcpWriter = ConnectionWriter(self.tcpManager, 0)
        self.tcpListener = QueuedConnectionListener(self.tcpManager, 0)

        self.tcpSocket = self.tcpManager.openTCPServerRendezvous(self.tcpport, self.backlog)
        self.tcpListener.addConnection(self.tcpSocket)
        print ("Started Server on: ", self.hostname, self.tcpport)
Beispiel #5
0
 def start(self, reader_cb, connection_cb):
     AbsNetwork.start(self, reader_cb)
     self.connection_cb = connection_cb
     self.c_listener = QueuedConnectionListener(self.c_mgr, 0)
     self.connections = []
     self.tcp_socket = self.c_mgr.open_TCP_server_rendezvous(9099, 1000)
     self.c_listener.add_connection(self.tcp_socket)
     self.listener_tsk = eng.add_tsk(self.tsk_listener, -39)
     eng.log_mgr.log('the server is up')
	def __init__(self):
		self.c_manager = QueuedConnectionManager()
		self.c_listener = QueuedConnectionListener(self.c_manager, 0)
		self.c_reader = QueuedConnectionReader(self.c_manager, 0)
		self.c_writer = ConnectionWriter(self.c_manager,0)

		self.active_conns=[]

		self.port_address=9099 #No-other TCP/IP services are using this port
		self.backlog=1000 #If we ignore 1,000 connection attempts, something is wrong!
Beispiel #7
0
    def setupTCP(self):
        self.tcpManager = QueuedConnectionManager()
        self.tcpReader = QueuedConnectionReader(self.tcpManager, 0)
        self.tcpWriter = ConnectionWriter(self.tcpManager, 0)
        self.tcpListener = QueuedConnectionListener(self.tcpManager, 0)

        self.tcpSocket = self.tcpManager.openTCPServerRendezvous(
            self.config.TCPPORT, self.config.BACKLOG)
        self.tcpListener.addConnection(self.tcpSocket)
        print("Started Server on: ", self.config.HOSTNAME, self.config.TCPPORT)
    def __init__(self, host="localhost", port=5001, name="server"):
        super().__init__(host=host, port=port, name=name)
        # self.setReaderCallback( sel.ProcessReaderData )

        backlog = 1000
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cListener.addConnection(self.tcpSocket)

        self.taskMgr.add(self.tskListenerPolling,
                         "Poll the connection listener", -39)
Beispiel #9
0
    def __init__(self):
        self.socket = None
        self.hostName = None
        self.port = None

        self.ourChannel = 100001

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
Beispiel #10
0
    def __init__(self):

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.rqTable = ServerRequestTable()
        self.rsTable = ServerResponseTable()

        self.connection = None
Beispiel #11
0
class Client(ShowBase):
    # notify
    notify = directNotify.newCategory("lp")

    # network
    cManager = QueuedConnectionManager()
    cListener = QueuedConnectionListener(cManager, 0)
    cReader = QueuedConnectionReader(cManager, 0)
    cWriter = ConnectionWriter(cManager, 0)

    def __init__(self):
        ShowBase.__init__(self)
        ShowBase.set_background_color(self, 0.08, 0.08, 0.08, 1)
        render.setAntialias(AntialiasAttrib.MAuto)
        self.disableMouse()

        # create father
        self.father = Father(self.cWriter, self.cManager, self.cReader)

        # create messager
        self.messager = Messager(self.father)

        # inputs
        self.accept('escape', self.debug)

        # try to connect
        self.connect()

    def debug(self):
        # testing_alert = Alert(-1)
        self.father.set_active_level(NIGHT)

    def connect(self):
        port_address = SERVER_PORT
        ip_address = SERVER_IP
        timeout = 3000

        my_connection = self.cManager.openTCPClientConnection(
            ip_address, port_address, timeout)
        if my_connection:
            self.notify.info("Connected")
            self.father.set_connection(my_connection)
            self.cReader.addConnection(my_connection)

            # tasks
            taskMgr.add(self.messager.check_for_message,
                        "Poll the connection reader", -39)
            taskMgr.doMethodLater(HEARTBEAT_PLAYER, self.messager.heartbeat,
                                  "Send heartbeat")
        else:
            Alert(-2)
            self.father.failed_to_connect()
            self.notify.warning("Could not connect!")
Beispiel #12
0
 def attemptLogin(self):
     # checks to make sure the user inputed a username and password:
     #       if they didn't it will spit out an error message
     #       if they did, it will try to connect to the login server 
     #               (under construction)
     
     if(self.usernameBox.get() == ""):
         if(self.passwordBox.get() == ""):
             self.updateStatus("ERROR: You must enter a username and password before logging in.")
         else:
             self.updateStatus("ERROR: You must specify a username")
         self.passwordBox['focus'] = 0
         self.usernameBox['focus'] = 1
             
     elif(self.passwordBox.get() == ""):
         self.updateStatus("ERROR: You must enter a password")
         self.usernameBox['focus'] = 0
         self.passwordBox['focus'] = 1
         
     elif(self.password2Box.get() == ""):
         self.updateStatus("ERROR: You must confirm the password")
         self.passwordBox['focus'] = 0
         self.password2Box['focus'] = 1
         
     elif(self.passwordBox.get() != self.password2Box.get()):
         self.updateStatus("ERROR: Wrong confirmed password, please enter password again")
         self.passwordBox.set("")
         self.password2Box.set("")
         self.passwordBox['focus'] = 1
         self.password2Box['focus'] = 0
         self.usernameBox['focus'] = 0
         
     else:
         self.updateStatus("Attempting to login...")
         print "Attempting to connect to Server with credentials: (" + self.usernameBox.get() + ", " + self.passwordBox.get() + ")"
         # this is where the networking code will get put in
         self.cManager = QueuedConnectionManager()
         self.cListener = QueuedConnectionListener(self.cManager, 0)
         self.cReader = QueuedConnectionReader(self.cManager, 0)
         self.cWriter = ConnectionWriter(self.cManager, 0)
     
         HOST = "localhost";
         PORT = 1234;
         self.connection = self.cManager.openTCPClientConnection(HOST, PORT, 10000)    
         self.received = 1
         
         if self.connection:
                 self.cReader.addConnection(self.connection)                    
         #taskMgr.add(self.updateRoutine, 'updateRoutine')
         taskMgr.doMethodLater(3, self.updateRoutine, 'updateRoutine')
Beispiel #13
0
    def __init__(self, port, backlog=1000, compress=False):
        DirectObject.__init__(self)

        self.port = port
        self.compress = compress

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        self.passedData = []

        self.connect(port, backlog)
        self.startPolling()
Beispiel #14
0
    def connection_open(self):
        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager,0)

        self.activeConnections=[] # We'll want to keep track of these later

        self.cListener = QueuedConnectionListener(self.cManager, 0)
        port_address=9099 #No-other TCP/IP services are using this port
        backlog=1000 #If we ignore 1,000 connection attempts, something is wrong!
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port_address,backlog)
        self.cListener.addConnection(self.tcpSocket)
        print "Network Connection Opened"
        taskMgr.add(self.tskListenerPolling,"Poll the connection listener",-39)
        taskMgr.add(self.tskReaderPolling,"Poll the connection reader",-40)
Beispiel #15
0
    def __init__(self, host="localhost", port=5001):
        taskMgr = Task.TaskManager()

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
        self.activeConnections = []  # We'll want to keep track of these later
        self.readerCallbacks = []

        backlog = 1000  #If we ignore 1,000 connection attempts, something is wrong!
        self.tcpSocket = self.cManager.openTCPServerRendezvous(port, backlog)
        self.cListener.addConnection(self.tcpSocket)

        taskMgr.add(self.tskListenerPolling, "Poll the connection listener",
                    -39)
        taskMgr.add(self.tskReaderPolling, "Poll the connection reader", -40)
        print("started server! ({} at {})".format(port, host))
Beispiel #16
0
    def __init__(self, address, port, handler, backlog=10000):
        NetworkManager.__init__(self)

        self.__address = address
        self.__port = port
        self.__handler = handler
        self.__backlog = backlog

        self.__manager = QueuedConnectionManager()
        self.__listener = QueuedConnectionListener(self.__manager, 0)
        self.__reader = QueuedConnectionReader(self.__manager, 0)
        self.__writer = ConnectionWriter(self.__manager, 0)

        self.__socket = None
        self.__handlers = {}

        self.__listen_task = None
        self.__read_task = None
        self.__disconnect_task = None
    def startHost (self):
        """
            Finishes initialization and begins listening.
        """
        # Initialize Reader and Writer:
        self._connReader = QueuedConnectionReader(self._connManager, 0)
        self._connWriter = ConnectionWriter(self._connManager, 0)
        # Initialize Listener:
        self._connListener = QueuedConnectionListener(self._connManager, 0)
        self._tcpSocket = self._connManager.openTCPServerRendezvous(
                                            self._portAddress, self._backlog)
        self._connListener.addConnection(self._tcpSocket)
        # Begin handling messages (start listening):
        taskMgr.add(self._onListenerPoll,"Poll the connection listener",-39)
        taskMgr.add(self._onReaderPoll,"Poll the connection reader",-40)
        self._isActive = True
        print ("[Host Started at %s]" % socket.gethostbyname(
                                            socket.gethostname()))

        self._gameManager.onHostInitialized()
Beispiel #18
0
    def __init__(self):

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        try:
            host = "localhost"
            port = 9252
            self.connection = self.cManager.openTCPClientConnection(
                host, port, 10000)

            self.received = 1

            if self.connection:
                self.cReader.addConnection(self.connection)
                taskMgr.add(self.updateRoutine, 'updateRoutine')
                # taskMgr.add(self.message, 'message')
        except:
            pass
    def __init__(self):
        super().__init__()

        # Support objects
        self.manager = QueuedConnectionManager()
        self.listener = QueuedConnectionListener(self.manager, 0)
        self.reader = QueuedConnectionReader(self.manager, 0)
        self.writer = ConnectionWriter(self.manager, 0)
        self.handler = Handler(self)

        # Server model
        self.session_manager = SessionManager()
        self.notifier_manager = NotifierManager(self)
        self.task_manager = TaskManager(self)
        self.connections = []

        # Socket
        self.tcp_socket = self.manager.open_TCP_server_rendezvous(15000, 1000)
        self.listener.add_connection(self.tcp_socket)

        self.accept_event(Event.CLIENT_DISCONNECTION_PUBLISHED, self.close_connection)
    def __init__(self,
                 port=None,
                 host=None,
                 ip_addr="127.0.0.1",
                 backlog=10000,
                 timeout=5000):
        self.port = port  # our port
        self.host = host  # host port
        self.ip_addr = ip_addr
        self.backlog = backlog
        self.timeout = timeout

        self.socket = None
        self.connection = None
        self.active_connections = []

        self.handler = None

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
Beispiel #21
0
    def SetupCommunication(self):
        cManager = QueuedConnectionManager()
        cListener = QueuedConnectionListener(cManager, 0)
        cReader = QueuedConnectionReader(cManager, 0)
        self.activeConnections = []  # We'll want to keep track of these later
        port_address = 9098  # No-other TCP/IP services are using this port
        backlog = 1000  # If we ignore 1,000 connection attempts, something is wrong!
        tcpSocket = cManager.openTCPServerRendezvous(port_address, backlog)
        cListener.addConnection(tcpSocket)

        def tskListenerPolling(taskdata):
            if cListener.newConnectionAvailable():

                rendezvous = PointerToConnection()
                netAddress = NetAddress()
                newConnection = PointerToConnection()

                if cListener.getNewConnection(rendezvous, netAddress,
                                              newConnection):
                    newConnection = newConnection.p()
                    self.activeConnections.append(
                        newConnection)  # Remember connection
                    cReader.addConnection(
                        newConnection)  # Begin reading connection
            return Task.cont

        def tskReaderPolling(taskdata):
            if cReader.dataAvailable():
                datagram = NetDatagram(
                )  # catch the incoming data in this instance
                # Check the return value; if we were threaded, someone else could have
                # snagged this data before we did
                if cReader.getData(datagram):
                    self.myProcessDataFunction(datagram)
            return Task.cont

        self.taskMgr.add(tskReaderPolling, "Poll the connection reader", -40)
        self.taskMgr.add(tskListenerPolling, "Poll the connection listener",
                         -39)
Beispiel #22
0
    def __init__(self):
        ShowBase.__init__(self)

        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)

        host = "localhost"
        port = 6002
        self.connection = self.cManager.openTCPClientConnection(
            host, port, 10000)

        self.received = 1

        if self.connection:
            self.cReader.addConnection(self.connection)
            #taskMgr.add(self.updateRoutine, 'updateRoutine')

            # LOGIN Request Starts
            self.uname = raw_input('Enter username :'******'Enter password :'******'Login')
            if (self.received):
                print "->Client request:"
        # Send a request to the server

            myPyDatagram101 = PyDatagram()
            prot = 101
            myPyDatagram101.addUint16(prot)
            myPyDatagram101.addString(self.uname)
            myPyDatagram101.addString(self.password)
            self.cWriter.send(myPyDatagram101, self.connection)
            self.received = 0
            taskMgr.add(self.receiveResponse101, 'Login')
Beispiel #23
0
from panda3d.core import QueuedConnectionManager
from panda3d.core import QueuedConnectionListener
from panda3d.core import QueuedConnectionReader
from panda3d.core import ConnectionWriter
from panda3d.core import NetDatagram
from panda3d.core import PointerToConnection
from panda3d.core import NetAddress

from direct.task.TaskManagerGlobal import taskMgr

cManager = QueuedConnectionManager()
cListener = QueuedConnectionListener(cManager, 0)
cReader = QueuedConnectionReader(cManager, 0)
cWriter = ConnectionWriter(cManager, 0)

activeConnections = []  # We'll want to keep track of these later

port_address = 9099  # No-other TCP/IP services are using this port
backlog = 1000  # If we ignore 1,000 connection attempts, something is wrong!
tcpSocket = cManager.openTCPServerRendezvous(port_address, backlog)

cListener.addConnection(tcpSocket)


def tskListenerPolling(taskdata):
    if cListener.newConnectionAvailable():

        rendezvous = PointerToConnection()
        netAddress = NetAddress()
        newConnection = PointerToConnection()
Beispiel #24
0
class Messager(Notifier):

    # network
    cManager = QueuedConnectionManager()
    cListener = QueuedConnectionListener(cManager, 0)
    cReader = QueuedConnectionReader(cManager, 0)
    cWriter = ConnectionWriter(cManager, 0)

    def __init__(self):
        Notifier.__init__(self, "msgr")

        # dicts
        self.active_connections = {}
        self.games = {}

        port_address = SERVER_PORT
        backlog = 1000
        tcp_socket = self.cManager.openTCPServerRendezvous(
            port_address, backlog)
        self.cListener.addConnection(tcp_socket)

        self.debug_ui = DebugUI(self)

        self.notify.info("[__init__] Created Messager")

    def check_for_new_players(self, taskdata):
        """
        Called repeatedly to check if there's any new connections
        If there are, add them to self.active_connections
        """
        if self.cListener.newConnectionAvailable():
            rendezvous = PointerToConnection()
            net_address = NetAddress()
            new_connection = PointerToConnection()

            if self.cListener.getNewConnection(rendezvous, net_address,
                                               new_connection):
                self.notify.debug("[check_for_new_players] New connection")
                new_connection = new_connection.p()

                pid = self.create_pid()

                new_connection_holder = ConnectionHolder(new_connection, pid)
                self.active_connections[pid] = new_connection_holder

                self.cReader.add_connection(new_connection)

                self.cWriter.send(dg_deliver_pid(pid), new_connection)
        return Task.cont

    def check_for_message(self, taskdata):
        """
        Called repeatedly to check if there's any new messages
        """
        if self.cReader.dataAvailable():
            dg = NetDatagram()
            if self.cReader.getData(dg):
                iterator = PyDatagramIterator(dg)
                connection = dg.getConnection()

                try:
                    msg_id = iterator.getUint8()
                except AssertionError:
                    self.notify.warning("[check_for_message] No message ID")
                    return Task.cont

                # check if real msg_id
                if msg_id in self.mapping:
                    self.mapping[msg_id](self, iterator)
                else:
                    self.notify.warning(
                        "[check_for_message] Invalid msg_id: {}".format(
                            msg_id))
        return Task.cont

    def check_heartbeats(self, task):
        for pid in self.active_connections:
            connection_holder = self.active_connections[pid]
            if connection_holder.heartbeat:
                connection_holder.heartbeat = False
            else:
                self.notify.debug(
                    f"[check_heartbeats] Player {connection_holder.pid} has no heartbeat!"
                )
                self.remove_player(connection_holder.pid, NO_HEART)
        return task.again

    """
    # Utility
    """

    def create_game(self, pid):
        """
        Creates a game for the PID given
        @param pid: PID of player wanting to join a game
        @type pid: int
        @return: if successful
        @rtype: bool
        """
        gid = RandomNumGen(int(round(time.time() * 1000))).randint(0, 65535)

        self.notify.debug(f"[create_game] Create game {gid} for player {pid}")

        # create game
        game = Game(gid, self)
        self.games[gid] = game

        self.add_player_to_game(pid, game.gid)

        return True

    def delete_game(self, gid):
        """
        Deletes the game of the GID given
        @param gid: the game ID
        @type gid: int
        @return: if successful
        @rtype: bool
        """
        self.notify.debug(f"[delete_game] Deleting game {gid}")

        # remove gid from players
        for p in self.games[gid].players:
            if not p.ai:
                self.active_connections[p.pid].gid = None

        del self.games[gid]

        return True

    def add_player_to_game(self, pid, gid):
        """
        Adds a player to a game
        @param pid: the player ID of the player joining the game
        @type pid: int
        @param gid: the game ID of the game the player wants to join
        @type gid: int
        @return: if successful
        @rtype: bool
        """
        self.notify.debug(
            f"[add_player_to_game] Adding player {pid} to game {gid}")

        if self.player_exists(pid):
            if gid in self.games.keys():
                self.active_connections[pid].gid = gid
                self.send_message(pid, dg_deliver_game(self.games[gid]))
                self.games[gid].add_player(pid)
                return True
            else:
                self.notify.warning(
                    f"[add_player_to_game] Attempted to add player {pid} to "
                    f"non-existent game {gid}")
        else:
            self.notify.warning(
                f"[add_player_to_game] Attempted to add non-existent player {pid} to "
                f"game {gid}")
        return False

    def remove_player_from_game(self, pid, reason):
        """
        Removes a player from a game
        @param pid: the player ID of the player leaving the game
        @type pid: int
        @param reason: the reason they're being removed from the game (see 3- codes)
        @type reason: int
        """
        self.notify.debug(f"[remove_player_from_game] Removing player {pid}")

        game = self.game_from_player(pid)
        if game:
            game.remove_player(pid=pid)
            self.active_connections[pid].gid = None
            self.cWriter.send(dg_kick_from_game(reason),
                              self.active_connections[pid].connection)
            return True
        else:
            self.notify.warning(
                f"[remove_player_from_game] Player {pid} not in game! ({game})"
            )
        return False

    def player_exists(self, pid):
        """
        Check if Player with PID exists
        @param pid: Player ID
        @type pid: int
        @return: If PID exists
        @rtype: bool
        """
        if pid in self.active_connections.keys():
            return True
        return False

    def gid_from_player(self, pid):
        """
        Get a GID from a PID
        @param pid: The Player ID
        @type pid: int
        @return: GID, or None if failed
        @rtype: int
        """
        if self.player_exists(pid):
            if self.active_connections[pid].gid:
                return self.active_connections[pid].gid
            else:
                self.notify.warning(
                    f"[gid_from_player] Attempted to find a GID for player {pid}, who isn't"
                    f" in a game!")
        else:
            self.notify.warning(
                f"[gid_from_player] Attempted to get GID from non-existent player {pid}!"
            )
        return None

    def game_from_player(self, pid):
        """
        Get a Game Object from a PID
        @param pid: Player ID
        @type pid: int
        @return: The Game Object, or None if non-existent
        @rtype: Game
        """
        gid = self.gid_from_player(pid)
        if gid:
            if gid in self.games.keys():
                return self.games[gid]
            else:
                self.notify.warning(
                    f"[game_from_player] Player {pid} is in non-existent game {gid}"
                )
        else:
            self.notify.warning(
                f"[game_from_player] Requested game from player {pid}, who isn't in a game"
            )
        return None

    def remove_player(self, pid, reason):
        """
        remove a player from The System
        @param reason: the reason they're being removed from the game (see 3- codes)
        @type reason: int
        @param pid: the player ID
        @type pid: int
        @return: if successful
        @rtype: bool
        """
        self.notify.debug(
            f"[remove_player] Removing player {pid} from The System")

        if self.player_exists(pid):
            # remove them from a game if they're in one
            if self.gid_from_player(pid):
                self.remove_player_from_game(pid, reason)

            # tell them in case they don't know
            self.cWriter.send(dg_kill_connection(),
                              self.active_connections[pid].connection)

            # delete
            del self.active_connections[pid]
            return True
        else:
            self.notify.warning(
                f"[remove_player] Requested to remove non-existent player {pid}"
            )
        return False

    def send_message(self, pid, dg):
        """
        Sends a message to a client
        @param pid: the PID of the player you want to message
        @type pid: int
        @param dg: the datagram you want to send
        @type dg: PyDatagram
        @return: if successful
        @rtype: bool
        """
        if self.player_exists(pid):
            self.cWriter.send(dg, self.active_connections[pid].connection)
            return True
        else:
            self.notify.warning(
                f"[send_message] Attempted to send message to non-existent player {pid}"
            )
        return False

    def create_pid(self):
        """
        Create a new PID
        @return: a new, unique PID
        @rtype: int
        """
        pid = None
        while not pid:
            temp_pid = RandomNumGen(int(round(time.time() * 1000))).randint(
                0, 65535)
            if temp_pid not in self.active_connections:
                pid = temp_pid
        return pid

    """
    # Message Codes
    """

    def request_game(self, iterator):
        """
        Called when someone requests a game
            uint16 - pid: the client's player ID
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
        except AssertionError:
            self.notify.warning("[request_game] Received invalid REQUEST_GAME")
            return False

        self.notify.debug(f"[request_game] Player {pid} has requested a game!")

        if self.player_exists(pid):
            if not self.gid_from_player(pid):
                game = None

                for g in self.games:
                    # make sure game meets our qualifications
                    if self.games[g].open and not self.games[g].started:
                        game = self.games[g]
                        break

                if game:
                    self.add_player_to_game(pid, game.gid)
                else:
                    self.notify.debug(
                        "[request_game] No available games, make one")
                    self.create_game(pid)
                return True
            else:
                self.notify.warning(
                    f"[request_game] {pid} requested game while already in a game"
                )
        else:
            self.notify.warning(
                f"[request_game] Non-existent player {pid} requested a game!")
        return False

    #TODO add bool
    def vote_to_start(self, iterator):
        """
        Called when a player votes to start the game
            uint16 - pid: the client's player ID
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
        except AssertionError:
            self.notify.warning(
                "[vote_to_start] Received invalid VOTE_TO_START")
            return False

        self.notify.debug(f"[vote_to_start] Player {pid} has voted to start!")

        game = self.gid_from_player(pid)

        if game:
            self.games[game].vote_to_start(pid)
            return True
        else:
            self.notify.warning(
                f"[vote_to_start] {pid} voted to start without being in a game!"
            )
        return False

    def leave_lobby(self, iterator):
        """
        Called when people tell the server they're leaving the lobby
            uint16 - pid: the player ID
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
        except AssertionError:
            self.notify.warning("[leave_lobby] Received invalid LEAVE_LOBBY")
            return False

        self.notify.debug(f"[leave_lobby] Player {pid} has left their lobby!")

        return self.remove_player_from_game(pid, LEFT_GAME)

    def set_room(self, iterator):
        """
        Called when a player tells the server what room they want to be in
            uint16 - pid: the player ID
            uint8 - room: the room the player wants to be in
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
            room = iterator.getUint8()
        except AssertionError:
            self.notify.warning("[set_room] Received invalid SET_ROOM")
            return False

        self.notify.debug(
            f"[set_room] Player {pid} is setting their room to {room}")

        game = self.game_from_player(pid)
        if game:
            return game.set_player_room(pid, room)
        return False

    def set_kill(self, iterator):
        """
        Called when a player (who is a killer) tells the server if they want to kill
            uint16 - pid: the player ID
            bool - choice: the player's choice of killing
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
            choice = iterator.getBool()
        except AssertionError:
            self.notify.warning("[set_kill] Received invalid SET_KILL")
            return False

        self.notify.debug(
            f"[set_kill] Player {pid} is setting their kill choice to {choice}"
        )

        game = self.game_from_player(pid)

        if game:
            return game.set_kill_choice(pid, choice)
        return False

    def heartbeat(self, iterator):
        """
        Heartbeat to keep client connected
            uint16 - pid: the player ID
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
        except AssertionError:
            self.notify.warning("Received invalid HEARTBEAT")
            return False

        self.active_connections[pid].heartbeat = True
        return True

    def goodbye(self, iterator):
        """
        Called when the client closes the connection
            uint16 - pid: the player ID
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
        except AssertionError:
            self.notify.warning("Received invalid GOODBYE")
            return False
        self.notify.debug(f"[goodbye] Received goodbye from {pid}")

        return self.remove_player(pid, CLIENT_LOG_OFF)

    def update_name(self, iterator):
        """
        Called when a player says they want to change their name
        @return: if successful
        @rtype: bool
        """
        try:
            pid = iterator.getUint16()
            new_name = iterator.getString()
        except AssertionError:
            self.notify.warning("Received invalid UPDATE_NAME")
            return False
        self.notify.debug(
            f"[update_name] Player {pid} is updating their name to {new_name}")

        game = self.game_from_player(pid)
        if game:
            return game.set_name(pid=pid, name=new_name)
        return False

    # Mapping
    mapping = {
        REQUEST_GAME: request_game,
        VOTE_TO_START: vote_to_start,
        LEAVE_LOBBY: leave_lobby,
        SET_ROOM: set_room,
        SET_KILL: set_kill,
        HEARTBEAT: heartbeat,
        GOODBYE: goodbye,
        UPDATE_NAME: update_name
    }
Beispiel #25
0
    def __init__(self):
         
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        
        self.cManager = QueuedConnectionManager()
        self.cListener = QueuedConnectionListener(self.cManager, 0)
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager, 0)
        
        self.opponents = dict()
        self.logStat = -1
        self.id = 0
        self.username = ""
        
        host = "localhost"
        port = 9252
        self.connection = self.cManager.openTCPClientConnection(host, port, 10000)
        
        self.received = 1
        
        self.playersText = []
        
        if self.connection:
         self.cReader.addConnection(self.connection)
         taskMgr.add(self.updateRoutine, 'updateRoutine')
         taskMgr.add(self.login, 'login')
         taskMgr.doMethodLater(.1, self.heartbeat, 'heartbeat')
         
        # Replace with actual, dynamic list of players from the server
        self.players = dict()
         
        # Placeholder, replace with actual # of players later
        self.numberOfPlayers = 2
         
        # Stores the OnScreenText for each player in the players list
        # Populated and depopulated using listPlayers and delistPlayers
        self.playersText = []
         
        # Stores all the player objects currently logged in
        self.playerObjects = []
         
        base.win.setClearColor(Vec4(0,0,0,1))
 
        # Post the instructions
 
        #self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)")
        #self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        #self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        #self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        #self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        #self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        #self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        #self.inst8 = addInstructions(0.60, "[Q]: Display List Of Connected Players")
         
        # Set up the environment
        #
        # This environment model contains collision meshes.  If you look
        # in the egg file, you will see the following:
        #
        #    <Collide> { Polyset keep descend }
        #
        # This tag causes the following mesh to be converted to a collision
        # mesh -- a mesh which is optimized for collision, not rendering.
        # It also keeps the original mesh, so there are now two copies ---
        # one optimized for rendering, one for collisions.  
 
        self.environ = loader.loadModel("models/world")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
         
         
         
         
         
        # Create the main character, Ralph
 
        ralphStartPos = self.environ.find("**/start_point").getPos()
        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(ralphStartPos)
        ralphStartPos.setY(ralphStartPos.getY()-10)
        self.ralph.setPos(ralphStartPos.getX(),ralphStartPos.getY(),ralphStartPos.getZ())
        self.initx = ralphStartPos.getX()
         
        # Add our Ralph to list to Ralphs
        self.playerObjects.append(self.ralph)
         
        # Load and transform the panda actor.
        self.pandaActor = Actor("models/panda-model",
                                {"walk": "models/panda-walk4"})
        self.pandaActor.setScale(0.003, 0.003, 0.003)
        self.pandaActor.reparentTo(render)
        # Loop its animation.
        #self.pandaActor.loop("walk")
        self.pandaActor.setPos(ralphStartPos.getX(),ralphStartPos.getY()-20,ralphStartPos.getZ())
         
        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
         
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)
 
        # Accept the control keys for movement and rotation
 
        self.accept("escape", self.disconnect)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("q", self.listPlayers)
        self.accept("q-up", self.delistPlayers)
 
        taskMgr.add(self.move,"moveTask")
         
        # Call whenever a ralph has logged in, use arg "out" for logouts
        self.displayLoginText()
 
        # Game state variables
        self.isMoving = False
 
        # Set up the camera
         
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
         
        # We will detect the height of the terrain by creating a collision
        # ray and casting it downward toward the terrain.  One ray will
        # start above ralph's head, and the other will start above the camera.
        # A ray may hit the terrain, or it may hit a rock or a tree.  If it
        # hits the terrain, we can detect the height.  If it hits anything
        # else, we rule that the move is illegal.
 
        self.cTrav = CollisionTraverser()
 
        self.ralphGroundRay = CollisionRay()
        self.ralphGroundRay.setOrigin(0,0,1000)
        self.ralphGroundRay.setDirection(0,0,-1)
        self.ralphGroundCol = CollisionNode('ralphRay')
        self.ralphGroundCol.addSolid(self.ralphGroundRay)
        self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.ralphGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol)
        self.ralphGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler)
         
        self.pandaActorGroundRay = CollisionRay()
        self.pandaActorGroundRay.setOrigin(0,0,1000)
        self.pandaActorGroundRay.setDirection(0,0,-1)
        self.pandaActorGroundCol = CollisionNode('pandaActorRay')
        self.pandaActorGroundCol.addSolid(self.pandaActorGroundRay)
        self.pandaActorGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.pandaActorGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.pandaActorGroundColNp = self.pandaActor.attachNewNode(self.pandaActorGroundCol)
        self.pandaActorGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.pandaActorGroundColNp, self.pandaActorGroundHandler)
         
 
        self.camGroundRay = CollisionRay()
        self.camGroundRay.setOrigin(0,0,1000)
        self.camGroundRay.setDirection(0,0,-1)
        self.camGroundCol = CollisionNode('camRay')
        self.camGroundCol.addSolid(self.camGroundRay)
        self.camGroundCol.setFromCollideMask(BitMask32.bit(0))
        self.camGroundCol.setIntoCollideMask(BitMask32.allOff())
        self.camGroundColNp = base.camera.attachNewNode(self.camGroundCol)
        self.camGroundHandler = CollisionHandlerQueue()
        self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler)
 
        # Uncomment this line to see the collision rays
        #self.ralphGroundColNp.show()
        #self.camGroundColNp.show()
        
        self.miniMap = miniMap(self.ralph)
        self.miniMap.setNpc('tower_1', 'models/hexahedron.png', 0.05, 0.2, 0.3)
        self.miniMap.setNpc('tower_2', 'models/hexahedron.png', 0.05, -0.4, -0.5)
        
        # Uncomment this line to show a visual representation of the 
        # collisions occuring
        #self.cTrav.showCollisions(render)
         
        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))
 
        self.setAI()