Basic networking with Pygame

This was asked recently on Reddit, so I’ll more or less just copy my answer over from there. I apologize for not being able to provide more links, I have <10 rep so I can only post two at a time.

Twisted might work, but I don’t have a whole lot of experience with it. I’d recommend going with sockets, as that’s what Twisted uses in the background anyway. Beej’s guide (google it) is pretty much the Holy Bible of sockets if you want to learn how they work (in C++, but the concepts extend everywhere). Python does abstract some of the complexity away, but it’s still a good idea to know what’s going on in the background.

For Python specific sockets, you can go ahead and just use the howto (user745294 posted a link above). Here‘s a nice article titled “What every programmer needs to know about Game Networking”. It goes into the different types of major networking styles (client-server, p2p, udp v. tcp, etc.) and the history behind what some major games used for their networking.

Below is a link to a demo I did on making a networked “game” in Python 2.6/Pygame. It’s not actually a game, but each client you create connects to the server and controls a character. You can move your character with the arrow keys and the character will move on all connected clients. I tried commenting the source code with some indication of what I’m sending back and forth, but you may need a little knowledge about sockets to understand it.

The source code is provided in the codepad links in the comment below this post. You will need to provide two images in the same directory as the scripts:

  1. bg.png is the background sprite. It should be an image 400px wide and 300px tall (this can be changed in the GameClient class if needed)
  2. sprite.png is the player character. It should be smaller than the background so that you can see it moving around.

Leave a Comment