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)

Artificial intelligence (Intermediate)


Often we need to mimic intelligent behavior within a game. The scikits-learn project aims to provide an API for Machine Learning. What I like most about it is the amazing documentation.

Getting ready

We can install scikit-learn by typing the following command at the command line:

pip install -U scikit-learn

Or:

easy_install -U scikit-learn

This might not work because of permissions, so you might need to put sudo in front of the commands or log in as admin.

How to do it...

We will generate some random points and cluster them, which means that points that are close to each other are put in the same cluster. This is only one of the many techniques that you can apply with scikits-learn. Clustering is a type of machine learning algorithm that aims to group items based on similarities.

  1. Generating random points: We will generate 30 random point positions within a square of 400 by 400 pixels:

    positions = numpy.random.randint(0, 400, size=(30, 2))
    
  2. Calculating the affinity matrix: We will use the Euclidean distance to the origin as the affinity metric. The affinity matrix is a matrix holding affinity scores, in this case distances:

    positions_norms = numpy.sum(positions ** 2, axis=1)
    S = - positions_norms[:, numpy.newaxis] - positions_norms[numpy.newaxis, :] + 2 * numpy.dot(positions, positions.T)
    
  3. Clustering the points: Give the AffinityPropagation class the result from the previous step. This class labels the points with the appropriate cluster number:

    aff_pro = sklearn.cluster.AffinityPropagation().fit(S)
    labels = aff_pro.labels_
    
  4. Drawing polygons: We will draw polygons for each cluster. The function involved requires a list of points, a color (let's paint it red), and a surface:

    pygame.draw.polygon(screen, (255, 0, 0), polygon_points[i])
    

    The result is a bunch of polygons for each cluster as shown in the following screenshot:

    The clustering example code is shown as follows:

    import numpy
    import sklearn.cluster
    import pygame, sys
    from pygame.locals import *
    
    
    positions = numpy.random.randint(0, 400, size=(30, 2))
    
    positions_norms = numpy.sum(positions ** 2, axis=1)
    S = - positions_norms[:, numpy.newaxis] - positions_norms[numpy.newaxis, :] + 2 * numpy.dot(positions, positions.T)
    
    aff_pro = sklearn.cluster.AffinityPropagation().fit(S)
    labels = aff_pro.labels_
    
    polygon_points = []
    
    for i in xrange(max(labels) + 1):
       polygon_points.append([])
    
    
    # Sorting points by cluster
    for i, l in enumerate(labels):
       polygon_points[l].append(positions[i])
    
    pygame.init()
    screen = pygame.display.set_mode((400, 400))
    
    
    while True: 
       for point in polygon_points:
          pygame.draw.polygon(screen, (255, 0, 0), point)
    
       for event in pygame.event.get():
          if event.type == QUIT:
             pygame.quit()
             sys.exit()
    
       pygame.display.update()

How it works...

The most important lines in the artificial intelligence recipe are described in more detail in the following table:

Function

Description

numpy.random.randint(0, 400, size=(30, 2))

This creates an array of 30 by 2 random integers. This corresponds to 30 points in two-dimensional space. The values are between 0 and 400.

numpy.sum(positions ** 2, axis=1)

This sums an array of the square of the positions array.

numpy.dot(positions, positions.T)

This computes the dot product of the positions array and its transpose.

sklearn.cluster.AffinityPropagation().fit(S)

This creates an AffinityPropagation object and performs a fit using an affinity matrix.

pygame.draw.polygon(screen, (255, 0, 0), polygon_points[i])

This draws a polygon given a surface, a color (red in this case), and a list of points.