Download Python Playground PDF

TitlePython Playground
CategoryComputer Science
Author
TagsPython Programming
LanguageEnglish
File Size11.1 MB
Total Pages353
Table of Contents
                            Brief Contents
Contents in Detail
Acknowledgments
Introduction
	Who Is This Book For?
	What’s in This Book?
		Part I: Warming Up
		Part II: Simulating Life
		Part III: Fun with Images
		Part IV: Enter the 3D
		Part V: Hardware Hacking
	Why Python?
		Python Versions
		The Code in This Book
Part I: Warming Up
	Chapter 1: Parsing iTunes Playlists
		Anatomy of the iTunes Playlist File
		Requirements
		The Code
			Finding Duplicates
			Extracting Duplicates
			Finding Tracks Common Across Multiple Playlists
			Collecting Statistics
			Plotting Your Data
			Command Line Options
		The Complete Code
		Running the Program
		Summary
		Experiments!
	Chapter 2: Spirographs
		Parametric Equations
			Spirograph Equations
			Turtle Graphics
		Requirements
		The Code
			The Spiro Constructor
			The Setup Functions
			The restart() Method
			The draw() Method
			Creating the Animation
			The SpiroAnimator Class
			The genRandomParams() Method
			Restarting the Program
			The update() Method
			Showing or Hiding the Cursor
			Saving the Curves
			Parsing Command Line Arguments and Initialization
		The Complete Code
		Running the Spirograph Animation
		Summary
		Experiments!
Part II: Simulating Life
	Chapter 3: Conway’s Game of Life
		How It Works
		Requirements
		The Code
			Representing the Grid
			Initial Conditions
			Boundary Conditions
			Implementing the Rules
			Sending Command Line Arguments to the Program
			Initializing the Simulation
		The Complete Code
		Running the Game of Life Simulation
		Summary
		Experiments!
	Chapter 4: Generating Musical Overtones with the Karplus-Strong Algorithm
		How It Works
			The Simulation
			Creating WAV Files
			The Minor Pentatonic Scale
		Requirements
		The Code
			Implementing the Ring Buffer with deque
			Implementing the Karplus-Strong Algorithm
			Writing a WAV File
			Playing WAV Files with pygame
			The main() Method
		The Complete Code
		Running the Plucked String Simulation
		Summary
		Experiments!
	Chapter 5: Boids: Simulating a Flock
		How It Works
		Requirements
		The Code
			Computing the Position and Velocities of the Boids
			Setting Boundary Conditions
			Drawing a Boid
			Applying the Rules of the Boids
			Adding a Boid
			Scattering the Boids
			Command Line Arguments
			The Boids Class
		The Complete Code
		Running the Boids Simulation
		Summary
		Experiments!
Part III: Fun with Images
	Chapter 6: ASCII Art
		How It Works
		Requirements
		The Code
			Defining the Grayscale Levels and Grid
			Computing the Average Brightness
			Generating the ASCII Content from the Image
			Command Line Options
			Writing the ASCII Art Strings to a Text File
		The Complete Code
		Running the ASCII Art Generator
		Summary
		Experiments!
	Chapter 7: Photomosaics
		How It Works
			Splitting the Target Image
			Averaging Color Values
			Matching Images
		Requirements
		The Code
			Reading in the Tile Images
			Calculating the Average Color Value of the Input Images
			Splitting the Target Image into a Grid
			Finding the Best Match for a Tile
			Creating an Image Grid
			Creating the Photomosaic
			Adding the Command Line Options
			Controlling the Size of the Photomosaic
		The Complete Code
		Running the Photomosaic Generator
		Summary
		Experiments!
	Chapter 8: Autostereograms
		How It Works
			Perceiving Depth in an Autostereogram
			Depth Maps
		Requirements
		The Code
			Repeating a Given Tile
			Creating a Tile from Random Circles
			Creating Autostereograms
			Command Line Options
		The Complete Code
		Running the Autostereogram Generator
		Summary
		Experiments!
Part IV: Enter 3D
	Chapter 9: Understanding OpenGL
		Old-School OpenGL
		Modern OpenGL: The 3D Graphics Pipeline
			Geometric Primitives
			3D Transformations
			Shaders
			Vertex Buffers
			Texture Mapping
			Displaying OpenGL
		Requirements
		The Code
			Creating an OpenGL Window
			Setting Callbacks
			The Scene Class
		The Complete Code
		Running the OpenGL Application
		Summary
		Experiments!
	Chapter 10: Particle Systems
		How It Works
			Modeling the Motion of a Particle
			Setting a Maximum Spread
			Rendering the Particles
			Using OpenGL Blending to Create More Realistic Sparks
			Using Billboarding
			Animating the Sparks
		Requirements
		The Code for the Particle System
			Defining the Particle Geometry
			Defining the Time-Lag Array for the Particles
			Setting the Initial Particle Velocities
			Creating the Vertex Shader
			Creating the Fragment Shader
			Rendering
			The Camera Class
		The Complete Particle System Code
		The Box Code
		The Code for the Main Program
			Updating the Particles at Each Step
			The Keyboard Handler
			Managing the Main Program Loop
		The Complete Main Program Code
		Running the Program
		Summary
		Experiments!
	Chapter 11: Volume Rendering
		How It Works
			Data Format
			Generating Rays
			Displaying the OpenGL Window
		Requirements
		An Overview of the Project Code
		Generating a 3D Texture
		The Complete 3D Texture Code
		Generating Rays
			Defining the Color Cube Geometry
			Creating the Frame Buffer Object
			Rendering the Back-Faces of the Cube
			Rendering the Front-Faces of the Cube
			Rendering the Whole Cube
			The Resize Handler
		The Complete Ray Generation Code
		Volume Ray Casting
			The Vertex Shader
			The Fragment Shader
		The Complete Volume Ray Casting Code
		2D Slicing
			The Vertex Shader
			The Fragment Shader
			A User Interface for 2D Slicing
		The Complete 2D Slicing Code
		Putting the Code Together
		The Complete Main File Code
		Running the Program
		Summary
		Experiments!
Part V: Hardware Hacking
	Chapter 12: Introduction to the Arduino
		The Arduino
		The Arduino Ecosystem
			Language
			IDE
			Community
			Peripherals
		Requirements
		Building the Light-Sensing Circuit
			How the Circuit Works
			The Arduino Sketch
			Creating the Real-Time Graph
		The Python Code
		The Complete Python Code
		Running the Program
		Summary
		Experiments!
	Chapter 13: Laser Audio Display
		Generating Patterns with a Laser
			Motor Control
			The Fast Fourier Transform
		Requirements
			Constructing the Laser Display
			Wiring the Motor Driver
		The Arduino Sketch
			Configuring the Arduino’s Digital Output Pins
			The Main Loop
			Stopping the Motors
		The Python Code
			Selecting the Audio Device
			Reading Data from the Input Device
			Computing the FFT of the Data Stream
			Extracting Frequency Information from the FFT Values
			Converting Frequency to Motor Speed and Direction
			Testing the Motor Setup
			Command Line Options
			Manual Testing
		The Complete Python Code
		Running the Program
		Summary
		Experiments!
	Chapter 14: A Raspberry Pi–Based Weather Monitor
		The Hardware
			The DHT11 Temperature and Humidity Sensor
			The Raspberry Pi
			Setting Up Your Pi
		Installing and Configuring Software
			The Operating System
			Initial Configuration
			Wi-Fi Setup
			Setting Up the Programming Environment
			Connecting via SSH
			The Bottle Web Framework
			Plotting with flot
			Shutting Down the Pi
		Building the Hardware
		The Code
			Handling Sensor Data Requests
			Plotting the Data
			The update() Method
			The JavaScript Handler for the LED
			Adding Interactivity
		The Complete Code
		Running the Program
		Summary
		Experiments!
Appendix A: Software Installation
	Installing Source Code for the Book’s Projects
	Installing on Windows
		Installing GLFW
		Installing Prebuilt Binaries for Each Module
		Other Options
	Installing on OS X
		Installing Xcode and MacPorts
		Installing Modules
	Installing on Linux
Appendix B: Basic Practical Electronics
	Common Components
	Essential Tools
	Building Circuits
	Going Further
Appendix C: Raspberry Pi Tips & Tricks
	Setting Up Wi-Fi
	Checking Whether Your Pi Is Connected
	Preventing the Wi-Fi Adapter from Going to Sleep
	Backing Up Your Code and Data from the Pi
	Backing Up Your Entire Pi OS
	Logging In to Your Pi with SSH
	Using the Raspberry Pi Camera
	Enabling Sound on Your Pi
	Making Your Pi Talk
	Making HDMI Work
	Making Your Pi Mobile
	Checking Your Raspberry Pi Hardware Version
Index
Resources
More No-nonsense Books from No Starch Press
About the Author
                        
Document Text Contents
Page 1




GEEKY PROJECTS FOR THE CURIOUS PROGRAMMERMAHESH
VENKITACHALAM
PYTHON
PLAYGR
OUNDPYTHON
PLAYGR
OUNDSHELVE IN:
PROGRAMMING LANGUAGES/

PYTHON
$29
.95 ($34.95 CDN)Python is a powerful programming language that™s easy to learn and fun to play with. But once you™ve gotten a handle on the basics, what do you do next?Python Playground is a collection of imaginative programming projects that will inspire you to use
Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. You™ll learn to use common Python tools and libraries like numpy, matplotlib, and pygame to do things like:Generate Spirograph-like patterns using parametric
equations and the turtle module
Create music on your computer by simulating

frequency overtones
Translate graphical images into ASCII artWrite an autostereogram program that produces
3D images hidden beneath random patternsMake realistic animations with OpenGL shaders
by exploring particle systems, transparency, and
billboarding techniques
Construct 3D visualizations using data from CT and
MRI scans

hooking
up your computer to an Arduino
Programming shouldn™t be a chore. Have some solid,
geeky fun with Python Playground.ABOUT THE AUTHOR
Mahesh Venkitachalam is a software engineer with

two decades of programming experience. He has
nurtured a passion for technology since the eighth
grade, which he channels into his popular electronics
and programming blog, electronut.in.
PROGRAMMINGBACK INPUT THE FUNPROGRAMMINGBACK INPUT THE FUNThe projects in this book are
compatible with Python 2 and 3.
PYTHON PLAYGROUND
PYTHON PLAYGROUND
VENKITACHALAMwww.nostarch.comTHE FINEST IN GEEK ENTERTAINMENTŽfiI LIE FLAT.flThis book uses a durable binding that won™t snap shut.



Page 2




PYTHON PLAYGROUND




Page 176




Understanding OpenGL
153
# texture self.texId = glutils.loadTexture('star.png') # show circle? self.showCircle = False
# step def step(self): # increment angle self.t = (self.t + 1) % 360 # set shader angle in radians glUniform1f(glGetUniformLocation(self.program, 'uTheta'), math.radians(self.t)) # render def render(self, pMatrix, mvMatrix): # use shader glUseProgram(self.program)
# set projection matrix glUniformMatrix4fv(self.pMatrixUniform, 1, GL_FALSE, pMatrix) # set modelview matrix glUniformMatrix4fv(self.mvMatrixUniform, 1, GL_FALSE, mvMatrix) # show circle? glUniform1i(glGetUniformLocation(self.program, b'showCircle'), self.showCircle) # enable texture glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.texId) glUniform1i(self.tex2D, 0) # bind VAO glBindVertexArray(self.vao) # draw glDrawArrays(GL_TRIANGLE_STRIP, 0, 4) # unbind VAO glBindVertexArray(0)class RenderWindow: """GLFW Rendering window class""" def __init__(self): # save current working directory cwd = os.getcwd() # initialize glfw - this changes cwd glfw.glfwInit()
# restore cwd os.chdir(cwd)


Page 177




154
Chapter 9
# version hints glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3) glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3) glfw.glfwWindowHint(glfw.GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, glfw.GLFW_OPENGL_CORE_PROFILE)
# make a window self.width, self.height = 640, 480 self.aspect = self.width/float(self.height) self.win = glfw.glfwCreateWindow(self.width, self.height,
b'simpleglfw') # make context current glfw.glfwMakeContextCurrent(self.win)
# initialize GL glViewport(0, 0, self.width, self.height) glEnable(GL_DEPTH_TEST) glClearColor(0.5, 0.5, 0.5, 1.0) # set window callbacks glfw.glfwSetMouseButtonCallback(self.win, self.onMouseButton) glfw.glfwSetKeyCallback(self.win, self.onKeyboard) glfw.glfwSetWindowSizeCallback(self.win, self.onSize) # create 3D self.scene = Scene() # exit flag self.exitNow = False def onMouseButton(self, win, button, action, mods): #print 'mouse button: ', win, button, action, mods pass def onKeyboard(self, win, key, scancode, action, mods): #print 'keyboard: ', win, key, scancode, action, mods if action == glfw.GLFW_PRESS: # ESC to quit if key == glfw.GLFW_KEY_ESCAPE: self.exitNow = True else:
# toggle cut self.scene.showCircle = not self.scene.showCircle def onSize(self, win, width, height): #print 'onsize: ', win, width, height
self.width = width self.height = height
self.aspect = width/float(height) glViewport(0, 0, self.width, self.height)


Page 352




RESOURCESVisit http://nostarch.com/pythonplayground/
for resources, errata, and more.PHONE
:800.420.7240
OR
415.863.9900
EMAIL
:SALES
@NOSTARCH
.COM
WEB
:WWW
.NOSTARCH
.COM
AUTOMATE THE BOR
ING
ST
UFF WITH PYTH
ONPractical Programming for
Total Beginners
by AL
SWEIGART
APRIL
2015, 504
PP
., $29.95
ISBN
978-1-59327-599-0
BL
AC
K HA
T PYTH
ONPython Programming for
Hackers and Pentesters
by JUSTIN
SEITZ
DECEMBER
2014, 192
PP
., $34.95
ISBN
978-1-59327-590-7
THE SPAR
KFUN GU
ID
E TO PROCESS
ING
Create Interactive Art with Code
by DEREK
RUNBERG
AUGUST
2015, 312
PP
., $29.95
ISBN
978-1-59327-612-6
full color
ARDUIN
O WOR
KSHOPA Hands-On Introduction
with 65 Projects
by JOHN
BO
XALL
MAY
2013, 392
PP
., $29.95
ISBN
978-1-59327-448-1
DOING
MA
TH WITH PYTH
ONUse Programming to Explore Algebra,
Statistics, Calculus, and More!
by AMIT
SAHA
AUGUST
2015, 264
PP
., $29.95
ISBN
978-1-59327-640-9
PYTH
ON CRAS
H COURSE
A Hands-On, Project-Based

Introduction to Programming
by ERIC
MATTHES
FALL
2015, 624
PP
., $39.95
ISBN
978-1-59327-603-4
More no-nonsense books from
NO
ST
ARC
H PRESS



Page 353




GEEKY PROJECTS FOR THE CURIOUS PROGRAMMERMAHESH
VENKITACHALAM
PYTHON
PLAYGR
OUNDPYTHON
PLAYGR
OUNDSHELVE IN:
PROGRAMMING LANGUAGES/

PYTHON
$29
.95 ($34.95 CDN)Python is a powerful programming language that™s easy to learn and fun to play with. But once you™ve gotten a handle on the basics, what do you do next?Python Playground is a collection of imaginative programming projects that will inspire you to use
Python to make art and music, build simulations of real-world phenomena, and interact with hardware like the Arduino and Raspberry Pi. You™ll learn to use common Python tools and libraries like numpy, matplotlib, and pygame to do things like:Generate Spirograph-like patterns using parametric
equations and the turtle module
Create music on your computer by simulating

frequency overtones
Translate graphical images into ASCII artWrite an autostereogram program that produces
3D images hidden beneath random patternsMake realistic animations with OpenGL shaders
by exploring particle systems, transparency, and
billboarding techniques
Construct 3D visualizations using data from CT and
MRI scans

hooking
up your computer to an Arduino
Programming shouldn™t be a chore. Have some solid,
geeky fun with Python Playground.ABOUT THE AUTHOR
Mahesh Venkitachalam is a software engineer with

two decades of programming experience. He has
nurtured a passion for technology since the eighth
grade, which he channels into his popular electronics
and programming blog, electronut.in.
PROGRAMMINGBACK INPUT THE FUNPROGRAMMINGBACK INPUT THE FUNThe projects in this book are
compatible with Python 2 and 3.
PYTHON PLAYGROUND
PYTHON PLAYGROUND
VENKITACHALAMwww.nostarch.comTHE FINEST IN GEEK ENTERTAINMENTŽfiI LIE FLAT.flThis book uses a durable binding that won™t snap shut.

Similer Documents