Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for Action – simulating life


The following code is an implementation of the Game of Life, with some modifications:

  • Clicking once with the mouse draws a cross until we click again

  • The r key resets the grid to a random state

  • Pressing b creates blocks based on the mouse position

  • g creates gliders

The most important data structure in the code is a two-dimensional array, holding the color values of the pixels on the game screen. This array is initialized with random values and then recalculated for each iteration of the game loop. Find more information about the involved functions in the next section.

  1. To evaluate the rules, use the convolution as follows:

    def get_pixar(arr, weights):
      states = ndimage.convolve(arr, weights, mode='wrap')
    
      bools = (states == 13) | (states == 12 ) | (states == 3)
    
      return bools.astype(int)
  2. Draw a cross using the basic indexing tricks that we learned in Chapter 2, Beginning with NumPy Fundamentals:

    def draw_cross(pixar):
       (posx, posy) = pygame.mouse.get_pos()...