コード例 #1
0
ファイル: client.py プロジェクト: PlumpMath/Centipede3D
    def __init__(self,
                 host,
                 port,
                 timeout=3000,
                 compress=False,
                 connectionStateChangedHandler=None):
        DirectObject.__init__(self)

        self.connectionStateChangedHandler = connectionStateChangedHandler

        self.myConnection = None

        self.host = host
        self.port = port
        self.timeout = timeout
        self.compress = compress

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

        # By default, we are not connected
        self.connected = False

        self.passedData = []

        self.connect(self.host, self.port, self.timeout)
コード例 #2
0
ファイル: client.py プロジェクト: atatsu/panda3d-fun
    def __init__(self, base, host, port):
        self.base = base
        self.host = host
        self.port = port

        self._conn = None

        self._retry_elapsed = 0
        self._retry_next = 0
        self._data_last_received = 0

        self.manager = QueuedConnectionManager()

        self.reader = QueuedConnectionReader(
            self.manager,
            0,  # number of threads
        )

        # we're using our own protocol so we don't want panda reading our headers and getting
        # all foobared by it (not setting raw mode causes `dataAvailable` to block
        # once there is actually data to process)
        self.reader.setRawMode(True)

        self.writer = ConnectionWriter(
            self.manager,
            0,  # number of threads
        )
コード例 #3
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)
コード例 #4
0
ファイル: TestingClient.py プロジェクト: jaimodha/MMOG
    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)
コード例 #5
0
ファイル: client.py プロジェクト: Jerommaas/Thunderstruck
    def __init__(self, host="localhost", port=5001, name="client"):
        self.name = name

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

        self.readerCallbacks = []

        taskMgr = Task.TaskManager()

        # how long until we give up trying to reach the server?
        timeout_in_miliseconds = 3000  # 3 seconds

        self.myConnection = self.cManager.openTCPClientConnection(
            host, port, timeout_in_miliseconds)
        if not self.myConnection:
            print("{}: Failed to connect to server!".format(self.name))
            return

        self.cReader.addConnection(
            self.myConnection)  # receive messages from server
        taskMgr.add(self.tskReaderPolling, "Poll the connection reader", -40)
        print("{}: Successfully connected to server {} at {}!".format(
            self.name, port, host))
コード例 #6
0
ファイル: TCP_Socket.py プロジェクト: grimfang/grim_net
    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)
コード例 #7
0
	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!
コード例 #8
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)
コード例 #9
0
ファイル: ConnectionManager.py プロジェクト: jaimodha/MMOG
    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
コード例 #10
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)
コード例 #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!")
コード例 #12
0
ファイル: Register.py プロジェクト: avenirf/HW2-1
 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')
コード例 #13
0
ファイル: client.py プロジェクト: rkbeatss/mafia
 def connect_to_server(self) -> None:
     self.manager = QueuedConnectionManager()
     self.reader = QueuedConnectionReader(self.manager, 0)
     self.writer = ConnectionWriter(self.manager, 0)
     try:
         self.connection = self.manager.openTCPClientConnection(
             self.addr, self.port, self.timeout)
         # Listen for data sent from server
         taskMgr.add(self.handle_server_connection,
                     "Poll the connection listener", -40)
         print("Connected to server...")
         self.reader.addConnection(self.connection)
         taskMgr.add(self.send_server_message, "Send msg", -41)
     except:
         print("Server not connected...")
コード例 #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)
コード例 #15
0
ファイル: server.py プロジェクト: PlumpMath/Centipede3D
    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()
コード例 #16
0
    def __init__(self, server_address):
        # server information
        self.server_address = server_address
        self.server_port = 15000
        self.timeout = 4000
        self.server_connection = None

        # networking modules from panda3d
        self.manager = QueuedConnectionManager()
        self.reader = QueuedConnectionReader(self.manager, 0)
        self.writer = ConnectionWriter(self.manager, 0)

        # modules that deal with messages
        self.sender_manager = MessageSendersManager(self)
        self.handler = Handler(self)
        self.section_state_fetcher = SectionStateFetcher(self)
コード例 #17
0
 def startClient(self, ipAddress):
     """
         Finishes client init and attempts a connection.
     """
     # Initialize Reader and Writer:
     self._connReader = QueuedConnectionReader(self._connManager, 0)
     self._connWriter = ConnectionWriter(self._connManager, 0)
     # Initialize connection:
     self._connection = self._connManager.openTCPClientConnection(
         ipAddress, self._portAddress, self._timeout)
     if self._connection:
         print("[Client Connected]")
         self._connReader.addConnection(self._connection)
         # Begin handling messages (start listening):
         taskMgr.add(self._onReaderPoll, "Poll the connection reader", -40)
         self._gameManager.onLocalClientJoinedParty(self._connection\
             .this) # GameManager callback
コード例 #18
0
    def __init__(self, dc_loader, address, port, channel, timeout=5000):
        NetworkManager.__init__(self)

        self._dc_loader = dc_loader
        self.__address = address
        self.__port = port
        self._channel = channel
        self.__timeout = timeout

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

        self.__socket = None

        self.__read_task = None
        self.__disconnect_task = None
コード例 #19
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))
コード例 #20
0
    def __init__(self, host="localhost", port=5001, name="client or server"):
        self.name = name
        self.port = port
        self.host = host

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

        self.connections = [
        ]  # list of connections, contains 1 item for client, multiple for server

        self.readerCallback = None  # will be called when a new message arrives
        self.writerCallback = None  # will be called when a message needs to be constructed

        self.taskMgr = Task.TaskManager()
        self.taskMgr.add(self.tskReaderPolling, "Poll the connection reader",
                         -40)
        self.taskMgr.add(self.tskWriterPolling, "Send data package", -39)
コード例 #21
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
コード例 #22
0
    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()
コード例 #23
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
コード例 #24
0
    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)
コード例 #25
0
    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)
コード例 #26
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)
コード例 #27
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')
コード例 #28
0
ファイル: networking.py プロジェクト: loonaticx/ToonTrouble
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()
コード例 #29
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()
コード例 #30
0
ファイル: network.py プロジェクト: PlumpMath/yyagl
 def start(self, reader_cb):
     self.c_mgr = QueuedConnectionManager()
     self.c_reader = QueuedConnectionReader(self.c_mgr, 0)
     self.c_writer = ConnectionWriter(self.c_mgr, 0)
     eng.attach_obs(self.on_frame, 1)
     self.reader_cb = reader_cb