PencilCoder

Multiplayer!

Goals:

  • Use socket.IO to communicate between two or more computers.

Coding Snippets:

  • coding snippets
  • Invoke io.connect to create a socket object. Sockets instantiated from the same Pencil Code account on different browsers maintain an open connection between those browers.
  • Communicate between browsers using events. Transmit messages using the emit method. The first argument names the socket event. Additional arguments can be used to pass additional info.
  • Set up event listeners using the socket's on method. All but the first argument passed to emit are automatically passed to this callback.

Math and Computer Concepts:

  • socket.IO is a JavaScript library which is automatically imported to Pencil Code programs. It simplifies the tasks required to connect and communicate between computers over the internet.
  • Technically speaking, io.connect creates a socket object that connects your browser to the Pencil Code server. The server facilitates communication between all browsers connected to this socket, passing messages sent from one browser to all connected browsers. In computer-communications lingo, all these browsers that connect to the server are called clients.
  • For separate clients to to share a connection, they must establish a socket from programs under the same Pencil Code account. Clients can connect by running the same program, or they can each run separate programs, so long as they are under the same account.
  • Activities:

    Save each of the following in a folder called Multiplayer.

    • ChatApp: Use sockets to create a multi-user chat. Your script should start by asking the client for their name, which you can then use to track the origin of each message by passing it as an argument to calls to emit.

    • EcholessSnippet: A challenge when working wth socket.IO's emit method is that all connected clients receive all messages—including the sender. Modify the code from the lesson's coding snippet to include a unique ID for each client. Pass this ID as an argument to each call to emit, and code the associated event callback so that when the event fires, the behavior differs according to whether the client was or was not the event source.

    • Polygraphs: write a program that duplicates what each client draws (using mouse events) on his/her own screen on every other connected-client's screen. You will also need to pass some sort of ID with your messages to keep track of which sprite is which.