Book Image

Instant Pygame for Python Game Development How-to

By : Ivan Idris
Book Image

Instant Pygame for Python Game Development How-to

By: Ivan Idris

Overview of this book

<p>Pygame is a library created to make multimedia software documenting easy to design. It adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the Python language. Pygame comes with functions and tools that will help you create a great user experience."Instant Pygame for Python Game Development How-to" is written in a concise and result-oriented format. Leading you through practical recipes, you'll find that this essential reference guide helps you to create visually appealing and thrilling games with a few clicks.This book starts with the basic instructions to install Pygame on different servers. It then goes into creating a sample game and explaining the features of drawing, animating, using fonts and Matplotlib with Pygame. The book then takes you through recipes to get access to some great sound and graphic effects. Giving you the steps to allow you to configure these games on Android and other networks, it ends with a walkthrough of the features of Sprites, OpenGL, and Simulation.</p>
Table of Contents (7 chapters)

Adding networking functionality (Advanced)


Games become more engaging when you are able to play against other people. Usually this means playing over the Internet using some sort of client-server architecture. In the Python world, Twisted is commonly used for this kind of architecture.

Getting ready

Twisted can be installed in several ways depending on your operating system. For more information see https://twistedmatrix.com/trac/wiki/Downloads.

How to do it...

Unfortunately, we cannot create a massive multiplayer game in this tutorial, but we can create a simple client-server setup, which will lay the foundations for a puzzle we will create in a later recipe.

  1. The server: First, we will set up the server, which will echo the message from the client and prepend it with a sequence number:

    from twisted.internet import reactor, protocol
    
    class Server(protocol.Protocol):
        def __init__(self):
           self.count = 0
    
        def dataReceived(self, msg):
             self. count += 1
             self.transport.write("%d %s" % (self.count, msg))
    
    
    def main():
        factory = protocol.ServerFactory()
        factory.protocol = Server
        reactor.listenTCP(8888,factory)
        reactor.run()
    
    if __name__ == '__main__':
        main()

    As you can see the server runs on port 8888 over TCP (see http://en.wikipedia.org/wiki/Transmission_Control_Protocol).

  2. Client setup: The client sends messages over the same port as the server and also shows the messages from the server in a Pygame GUI. We will go over the details in the next section. In a later example we will do more interesting things with this code:

    from twisted.internet import reactor, protocol
    from pygame.locals import *
    import pygame
    
    class Client(protocol.Protocol):
        def __init__(self):
           self.msg = 'Hello'
           self.end_msg = False
    
        def sendMessage(self, msg):
            self.transport.write(msg)
            self.update(msg)
    
        def dataReceived(self, msg):
           self.msg = msg
    
           if msg.startswith("19"):
              self.end_msg = True
        
        def update(self, msg):
            screen = pygame.display.get_surface()
    
            screen.fill((255, 255, 255))
            font = pygame.font.Font(None, 36)
            text = font.render(self.msg, 1, (200, 200, 200))
            textpos = text.get_rect(centerx=screen.get_width()/2, centery=screen.get_height()/2)
            screen.blit(text, textpos)
            pygame.display.flip()
    
            if self.end_msg:
               reactor.stop()
        
    def send(p):
        p.sendMessage("Hello!")
    
        for i in xrange(1, 20):
          reactor.callLater(i * .1, p.sendMessage, "IMPORTANT MESSAGE!")
    
    def main():
        pygame.init()
        screen = pygame.display.set_mode((400, 400))
        pygame.display.set_caption('Network Demo')
    
        c = protocol.ClientCreator(reactor, Client)
        c.connectTCP("localhost", 8888).addCallback(send)
        reactor.run()
    
    
        while True:
           for event in pygame.event.get():
             if event.type == QUIT:
                 return
    
    if __name__ == '__main__':
        main()

    We need to start the server, before we can start the client. In the game GUI, you should see Hello being displayed followed by 1 IMPORTANT MESSAGE! to 19 IMPORTANT MESSAGE! as shown in the following screenshot:

How it works...

We saw in this example how to create a simple server and client with a Pygame GUI. In principle, we can now extend this setup to create a multiplayer game. The details of the Twisted client and server setup are given as follows:

Function

Description

self.transport.write("%d %s" % (self.count, msg))

This writes a message. In this case we are prepending a sequence number to the message.

factory = protocol.ServerFactory()

This creates a Twisted server factory, which itself creates Twisted servers.

reactor.listenTCP(8888,factory)

This listens to port 8888 using the given factory.

reactor.run()

This starts the server or client.

reactor.stop()

This stops the client or server.

reactor.callLater(i * .1, p.sendMessage, "IMPORTANT MESSAGE!")

This registers a callback function with a parameter to be executed after a specified time in seconds.

protocol.ClientCreator(reactor, Client)

This creates a Twisted client.

c.connectTCP("localhost", 8888).addCallback(send)

This connects the client via TCP on port 8888 and registers a callback function.